oficina / equipo Public

Merge remote-tracking branch 'origin/main' into native/push

Paul Campbell pushed by claude agent, operated by paul@keymail.dev 0a7440d1d27647f14d73e33637922c597a1f1b16 parent c2acaecparent b6c76de
37 files changed, +1,624 −82
  • .rastrillo/budgets.txt +6 −6
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +1 −0
  • internal/equipo/chat/handoff.go +9 −3
  • internal/equipo/chat/models.go +11 −1
  • internal/equipo/chat/store.go +115 −4
  • internal/equipo/chat/tools.go +7 −0
  • internal/equipo/chat_roster.go +1 −1
  • internal/equipo/copy.go +1 −0
  • internal/equipo/migrations/0095_turn_carried.sql +4 −0
  • internal/equipo/migrations/schema.sql +2 −0
  • internal/equipo/static/chat-stream.js +56 −9
  • internal/equipo/static/equipo.css +22 −1
  • internal/equipo/static/work-stream.js +12 −0
  • internal/equipo/templates/work_parts.html +1 −1
  • internal/equipo/track_working_test.go +84 −0
  • internal/equipo/work_views.go +15 −3
  • internal/fakeclaude/fake.go +4 −0
  • internal/fakecodex/fake.go +4 −0
  • internal/headless/ask_test.go +27 −3
  • internal/headless/engineering_test.go +32 −5
  • internal/headless/env_test.go +5 −2
  • internal/headless/review_test.go +21 −5
  • internal/plan3test/plan3_release_test.go +1 −1
  • internal/runner/provider/accounts.go +9 −4
  • internal/runner/provider/token_test.go +18 −0
  • internal/runner/thin/bridge.go +20 −5
  • internal/runner/thin/claude.go +3 −0
  • internal/runner/thin/copy_reason_test.go +39 −0
  • internal/runner/thin/forge.go +164 −17
  • internal/runner/thin/start_default_test.go +384 −0
  • internal/runner/thin/state.go +3 −1
  • internal/thintest/batching_contract_test.go +27 −6
  • internal/thintest/carried_contract_test.go +138 −0
  • internal/thintest/instance_contract_test.go +123 −0
  • internal/thintest/thinking_browser_test.go +107 −3
  • internal/thintest/track_pulse_browser_test.go +143 −0
  • scripts/staging-thin.py +5 −1
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index ed35e14e..b5b0f186 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,7 +14,7 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 21394 - Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; empty conversation starters (copy and the scriptless draft); measured 21394/3196 source/test lines.
+size internal/equipo 21407 - Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; empty conversation starters (copy and the scriptless draft); measured 21394/3196 source/test lines.
size internal/wire 6637 - Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; measured 6637/2972 source/test lines.
size internal/equipotest - 12013 Task 21 repairs historical migration and conversation fixtures after Plan 3; measured 0/12013 source/test lines.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
@@ -26,7 +26,7 @@ time internal/runner/provider/claude 45s Task 5 measured 32.430s for fake CLI se
time internal/runner/provider/codex 35s Plan 3 CI repair measured 24.464s for the full package (controller CI 27.908s).
time internal/runner/provider/pi 60s The real pinned Pi in bubblewrap against a fake TensorX: probes P1 to P5 (a hundred RPC turns), the hostile repository, and the pinned tree checked whole (about 160 MB); measured 22s locally.
time internal/runner/provider/opencode 90s The real pinned OpenCode in bubblewrap against a fake Go: probes, the hostile repository per source, termination, resume; the 260 MB binary hashed per launch. Measured 40s.
-size internal/runner/provider 5598 - Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; measured 5598/4345 source/test lines.
+size internal/runner/provider 5603 - Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; measured 5603/4363 source/test lines (containment reasons logged).
time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops.
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 27849 21023 Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; measured 27849/21023 source/test lines.
+size internal/runner/thin 28016 21446 Fable follow-up gates and guards, then main started at repo creation; measured 28016/21446 source/test lines (containment reasons logged).
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
@@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device
perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen.
-size internal/equipo/chat 31167 - Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; measured 31167/6180 source/test lines.
+size internal/equipo/chat 31301 - Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; measured 31167/6180 source/test lines.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
@@ -70,8 +70,8 @@ perf GET /api/v1/tasks/{id}/files/{file} skip Research kept images: bearer-only
perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one image, shown on the task page; a file, not a screen.
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
-size internal/headless - 11249 Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; measured 0/11249 source/test lines (live first-stage check).
-size internal/thintest - 32091 Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; empty conversation page and browser checks; measured 1515/32091 source/test lines.
+size internal/headless - 11319 Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; live staging witnesses; measured 0/11319 source/test lines (live first-stage check).
+size internal/thintest - 32620 Fable follow-up: base and diagnostic gates, preview isolation and provenance guards; empty conversation page and browser checks; measured 1515/32338 source/test lines.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage.
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index cbcdb24f..69dfa1d8 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -6757,6 +6757,7 @@ records remain unchanged.
| `conversation.start.feature_draft` | Plan a feature that | Copy specialist | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-20) |
| `conversation.start.project` | Ask about a project | Copy specialist | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-20) |
| `conversation.start.project_draft` | What’s the latest on | Copy specialist | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-20) |
+| `work.track.working` | (work underway) | Copy specialist | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-20) |
## Task 21
diff --git a/internal/equipo/chat/handoff.go b/internal/equipo/chat/handoff.go
index f5b4799c..92b147c2 100644
--- a/internal/equipo/chat/handoff.go
+++ b/internal/equipo/chat/handoff.go
@@ -328,8 +328,9 @@ func (t *txn) liveCall(call toolCallRecord) (turnRecord, error) {
}
// quote is words as the person wrote them in one of the turn's
-// messages: found there compared lower-cased with each run of
-// whitespace as one space, at least minQuote characters. Only a turn
+// messages, or one it carried from a turn that failed before the model
+// saw it (carriedRecord): found there compared lower-cased with each run
+// of whitespace as one space, at least minQuote characters. Only a turn
// the person started has their words (a team_update turn has none).
func (t *txn) quote(r turnRecord, words string) (string, error) {
refuse := assist.Failure{Code: "not_their_words"}
@@ -342,7 +343,12 @@ func (t *txn) quote(r turnRecord, words string) (string, error) {
if err := t.db.Model(&messageRecord{}).Where("turn_id = ? AND person = ? AND role = ?", r.ID, r.Person, wire.RolePerson).Order("seq").Pluck("text", &texts).Error; err != nil {
return "", err
}
- for _, text := range texts {
+ // Exactly the messages dispatch carried: the person's own, in the lane.
+ var carried []string
+ if err := t.db.Model(&messageRecord{}).Where("person = ? AND role = ? AND origin = ? AND coalesce(lane, '') = ? AND id IN (SELECT message_id FROM chat_turn_carried WHERE turn_id = ? AND person = ?)", r.Person, wire.RolePerson, originComposer, r.Lane, r.ID, r.Person).Order("seq").Pluck("text", &carried).Error; err != nil {
+ return "", err
+ }
+ for _, text := range append(texts, carried...) {
if found, ok := quoteIn(text, w); ok {
return found, nil
}
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go
index b042c325..0107066e 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{&cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &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{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}}
+var Models = []any{&cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &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{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}}
type turnRecord struct {
CreateRepo string
@@ -40,6 +40,16 @@ type turnRecord struct {
func (turnRecord) TableName() string { return "chat_turns" }
+// carriedRecord is one person's message a turn carried, unanswered, from
+// a turn that failed before it (dispatch, unanswered).
+type carriedRecord struct {
+ TurnID string `gorm:"primaryKey"`
+ MessageID string `gorm:"primaryKey"`
+ Person string
+}
+
+func (carriedRecord) TableName() string { return "chat_turn_carried" }
+
// messageRecord's integer key is the SQLite rowid, so the person index
// orders by it. Coordinator replies use the key "reply:<turn>". A key is
// unique per person and lane.
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index f81fe642..069283fd 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -7,7 +7,9 @@ import (
"encoding/hex"
"encoding/json"
"errors"
+ "fmt"
"log/slog"
+ "slices"
"strconv"
"strings"
"sync"
@@ -322,9 +324,25 @@ func (t *txn) dispatch(r *turnRecord) error {
if err := t.db.Where("person = ? AND coalesce(lane, '') = ? AND turn_id <> ? AND turn_id NOT IN (SELECT id FROM chat_turns WHERE person = ? AND dispatched = ? AND state = ?)", r.Person, r.Lane, r.ID, r.Person, false, wire.TurnQueued).Order("seq DESC").Limit(wire.MaxTailMessages).Find(&prior).Error; err != nil {
return err
}
+ // The person's words in turns that failed before the model ran never
+ // reached the coordinator: they ride in this turn's frame, marked
+ // unanswered, and not in the tail as if answered.
+ var carried []messageRecord
+ if r.Kind == wire.TurnPerson {
+ var err error
+ if carried, err = t.unanswered(r); err != nil {
+ return err
+ }
+ }
+ inFrame := map[string]bool{}
+ for _, m := range carried {
+ inFrame[m.ID] = true
+ }
tail := make([]wire.TailMessage, 0, len(prior))
for i := len(prior) - 1; i >= 0; i-- {
- tail = append(tail, wire.TailMessage{Role: prior[i].Role, Text: prior[i].Text})
+ if !inFrame[prior[i].ID] {
+ tail = append(tail, wire.TailMessage{Role: prior[i].Role, Text: prior[i].Text})
+ }
}
texts := make([]string, 0, len(mine))
own := make([]string, 0, len(mine))
@@ -370,18 +388,111 @@ func (t *txn) dispatch(r *turnRecord) error {
text += "\n\n" + block
}
}
- cmd := wire.MessageCommand{Person: r.Person, TurnID: r.ID, Attempt: r.Attempt, Kind: r.Kind, Text: text, PersonText: own, Tail: tail, Attachments: files, Lane: r.Lane}
+ cmd := wire.MessageCommand{Person: r.Person, TurnID: r.ID, Attempt: r.Attempt, Kind: r.Kind, Attachments: files, Lane: r.Lane}
if wire.CoordinatorRole(r.Lane) {
if cmd.PlacementNotes, err = t.placementNotes(r.Person); err != nil {
return err
}
}
- if cmd.Tail, err = fitTail(cmd); err != nil {
- return err
+ // The tail gives way first, then the oldest unanswered message: a
+ // runner refuses a frame too big, every time it is resent.
+ for {
+ words := make([]string, 0, len(carried)+len(own))
+ for _, m := range carried {
+ words = append(words, m.Text)
+ }
+ cmd.Text, cmd.PersonText, cmd.Tail = withUnanswered(carried, text), append(words, own...), tail
+ if cmd.Tail, err = fitTail(cmd); err != nil {
+ return err
+ }
+ raw, err := json.Marshal(cmd)
+ if err != nil {
+ return err
+ }
+ if len(raw) <= frameRoom || len(carried) == 0 {
+ break
+ }
+ carried = carried[1:]
+ }
+ // In this turn the carried words are the person's too (quote).
+ for _, m := range carried {
+ if err := t.db.Create(&carriedRecord{TurnID: r.ID, MessageID: m.ID, Person: r.Person}).Error; err != nil {
+ return err
+ }
}
return t.command(r.Person, wire.FrameMessage, cmd)
}
+// A turn carries the person's words from at most maxCarriedTurns failed
+// turns, and at most maxUnanswered messages: words that rode in two turns
+// that failed too may be what makes them fail, so they stop riding.
+const (
+ maxCarriedTurns = 2
+ maxUnanswered = 10
+)
+
+// reachedModel is SQL true when the chat_turns row reached the model: a
+// delta or an activity was recorded for it, or a tool call, or usage.
+// Events are kept a day (wire.EventRetention), longer than a session
+// resumes (the same UTC day); tool calls and usage are kept.
+const reachedModel = "(EXISTS (SELECT 1 FROM chat_tool_calls c WHERE c.turn_id = chat_turns.id) OR EXISTS (SELECT 1 FROM chat_usage u WHERE u.turn_id = chat_turns.id) OR EXISTS (SELECT 1 FROM chat_events e WHERE e.person = chat_turns.person AND e.type IN ('" + wire.EventDelta + "', '" + wire.EventActivity + "') AND e.body LIKE '%\"turn_id\":\"' || chat_turns.id || '\"%'))"
+
+// unanswered is the person's plain messages (composer words, not a card's
+// answer or reply, which reach the model with their card) in the lane's
+// failed person turns since the last that reached the model (answered,
+// or ended after it began), the newest maxCarriedTurns of them, oldest
+// first. So each failed before the model ran: its words are in no
+// transcript, and the tail showed them as if answered. A turn that
+// reached the model bounds them, its own words and those it carried: a
+// resumed session's transcript may hold them. A cancelled turn's are not
+// carried: the person stopped it.
+func (t *txn) unanswered(r *turnRecord) ([]messageRecord, error) {
+ turns := "SELECT id FROM chat_turns WHERE person = ? AND coalesce(lane, '') = ? AND coalesce(kind, '') = '' AND "
+ var last int64
+ if err := t.db.Model(&messageRecord{}).Select("coalesce(max(seq), 0)").Where("person = ? AND coalesce(lane, '') = ? AND role = ? AND turn_id IN ("+turns+"(state = ? OR state IN ? AND "+reachedModel+"))", r.Person, r.Lane, wire.RolePerson, r.Person, r.Lane, wire.TurnReplied, []string{wire.TurnFailed, wire.TurnCancelled}).Scan(&last).Error; err != nil {
+ return nil, err
+ }
+ var rows []messageRecord
+ if err := t.db.Where("person = ? AND coalesce(lane, '') = ? AND role = ? AND seq > ? AND turn_id <> ? AND turn_id IN ("+turns+"state = ?)", r.Person, r.Lane, wire.RolePerson, last, r.ID, r.Person, r.Lane, wire.TurnFailed).Order("seq DESC").Limit(wire.MaxTailMessages).Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ var out []messageRecord
+ seen := map[string]bool{}
+ for _, m := range rows {
+ if !seen[m.TurnID] && len(seen) == maxCarriedTurns {
+ break
+ }
+ seen[m.TurnID] = true
+ if m.Origin != originComposer || len(out) == maxUnanswered {
+ continue
+ }
+ var cards int64
+ if err := t.db.Model(&cardRecord{}).Where("person = ? AND (answer_message = ? OR id IN (SELECT card_id FROM chat_card_threads WHERE message_id = ? AND person = ?))", m.Person, m.ID, m.ID, m.Person).Count(&cards).Error; err != nil {
+ return nil, err
+ }
+ if cards == 0 {
+ out = append(out, m)
+ }
+ }
+ slices.Reverse(out)
+ return out, nil
+}
+
+// withUnanswered is a turn's text with the unanswered messages before
+// it, each quoted under its label; text alone with none.
+func withUnanswered(carried []messageRecord, text string) string {
+ if len(carried) == 0 {
+ return text
+ }
+ var b strings.Builder
+ b.WriteString(noteUnanswered + "\n")
+ for _, m := range carried {
+ b.WriteString(fmt.Sprintf(noteUnansweredMessage, m.Text) + "\n")
+ }
+ b.WriteString("\n" + noteNewest + text)
+ return b.String()
+}
+
// frameRoom is what a message command's body may take: the frame limit
// less its envelope (id and type).
const frameRoom = wire.MaxFrameBytes - 1<<10
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go
index b9aff70d..c73a3393 100644
--- a/internal/equipo/chat/tools.go
+++ b/internal/equipo/chat/tools.go
@@ -97,6 +97,13 @@ const (
noteOpenQuestion = "- Job %q (request %s): %q"
noteMoreQuestion = "1 more job has an open question not listed here: team_status lists every open request with its question, ten at a time (pass its next as after to read on)."
noteMoreQuestions = "%d more jobs have open questions not listed here: team_status lists every open request with its question, ten at a time (pass its next as after to read on)."
+ // noteUnanswered heads the person's messages whose turns failed before
+ // the model ran, since the lane's last turn that reached it
+ // (unanswered). Each follows quoted (noteUnansweredMessage), then the
+ // turn's own text (noteNewest).
+ noteUnanswered = "[Equipo: these earlier messages from the person got no answer: their turns failed before you saw them. They are the person's own words, oldest first, still waiting. Answer them together with the newest message.]"
+ noteUnansweredMessage = "Not yet answered, the person's words: %q"
+ noteNewest = "The person's newest message:\n"
// noteConnected is the note of the turn queued once the person
// connected the apps a connect card asked for (carryOn).
noteConnected = "The person has just connected their Oficina apps. Now complete their most recent request that needed them, as they asked it in the conversation. If that request is already done or no longer applies, end your turn without writing anything, or reply in one short line."
diff --git a/internal/equipo/chat_roster.go b/internal/equipo/chat_roster.go
index cdcede6a..ad4ba4f6 100644
--- a/internal/equipo/chat_roster.go
+++ b/internal/equipo/chat_roster.go
@@ -196,7 +196,7 @@ func rosterTrack(t wire.Task) []trackStop {
out[i].State = "done"
}
if i == current {
- out[i].State, out[i].Tone = "current", rosterTone(t)
+ out[i].State, out[i].Tone, out[i].Working = "current", rosterTone(t), workingNow(t)
}
}
return out
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 13ce010a..cebf6c70 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -850,6 +850,7 @@ var pageCopy = map[string]string{
"work.track.reviewed": "Review", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)
"work.track.preview": "Preview", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)
"work.track.decided": "Decided", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)
+ "work.track.working": "(work underway)", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-20)
"work.tl.merge_dropped": "An earlier attempt to add this change was dropped when the task became an exploration.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)
"work.stopped": "Stopped: %s", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"work.reason.runner_restarted": "the runner restarted", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
diff --git a/internal/equipo/migrations/0095_turn_carried.sql b/internal/equipo/migrations/0095_turn_carried.sql
new file mode 100644
index 00000000..334accda
--- /dev/null
+++ b/internal/equipo/migrations/0095_turn_carried.sql
@@ -0,0 +1,4 @@
+-- The person's messages a turn carried, unanswered, from turns that
+-- failed before it (dispatch): in that turn they are the person's words
+-- too (quote). A message rides in at most two turns.
+CREATE TABLE chat_turn_carried (turn_id text, message_id text, person text, PRIMARY KEY (turn_id, message_id));
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index dd304e75..638fb713 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -734,3 +734,5 @@ WHERE CASE WHEN json_valid(entries) THEN json_type(entries) = 'array' ELSE 0 END
AND EXISTS (SELECT 1 FROM json_each(chat_notebooks.entries) WHERE json_extract(value, '$.source') = 'person');
ALTER TABLE chat_steps ADD COLUMN base_checks text;
+
+CREATE TABLE chat_turn_carried (turn_id text, message_id text, person text, PRIMARY KEY (turn_id, message_id));
diff --git a/internal/equipo/static/chat-stream.js b/internal/equipo/static/chat-stream.js
index fc6ab1f4..a7e9f0df 100644
--- a/internal/equipo/static/chat-stream.js
+++ b/internal/equipo/static/chat-stream.js
@@ -167,10 +167,29 @@
}
return list[deal(key, list.length) % list.length];
}
+ // Each phrase stays at least DWELL ms (Paul, 2026-11-20: "the
+ // thinking kept flashing quite quickly"): a turn's first moments bring
+ // thinking, a tool's label and then its named one, all within a second.
+ // An activity that comes sooner waits, and only the latest waiting one
+ // is drawn; the accessible label and tooltip follow it at once.
+ var DWELL = 1500;
+ function want(li, label) {
+ li.wanted = label;
+ if (li.waiting) return;
+ var wait = DWELL - (Date.now() - (li.shownAt || 0));
+ if (wait <= 0) return flush(li);
+ li.waiting = setTimeout(function () { flush(li); }, wait);
+ }
+ function flush(li) {
+ var label = li.wanted;
+ li.waiting = 0;
+ li.wanted = null;
+ if (label !== null && label !== undefined) draw(li, themed(li, label), false);
+ }
// The next phrase of the situation, when its time has come.
function cycle(li) {
var list = phrases(li);
- if (list.length < 2 || !li.wordKey || Date.now() - (li.wordAt || 0) < li.wordDelay) return;
+ if (li.waiting || list.length < 2 || !li.wordKey || Date.now() - (li.wordAt || 0) < li.wordDelay) return;
li.wordDelay = nextDelay();
li.wordAt = Date.now();
draw(li, list[deal(li.wordKey, list.length) % list.length], false);
@@ -222,6 +241,7 @@
if (keep < b.length) while (keep > 0 && !/[\s…]/.test(b[keep - 1])) keep--;
}
li.phrase = text;
+ li.shownAt = Date.now();
var measure = phrase.querySelector("[data-measure]");
measure.textContent = text;
var natural = measure.offsetWidth + 1;
@@ -233,6 +253,9 @@
var gap=parseFloat(getComputedStyle(line).columnGap)||0;
room=Math.floor(line.clientWidth-(elapsed?elapsed.offsetWidth:0)-(sep?sep.offsetWidth:0)-gap*3-8);
}
+ // One phrase at a time: the old one fades in .2 s, before the new
+ // one's letters start (equipo.css), and one still fading goes now.
+ phrase.querySelectorAll("[data-out]").forEach(function (old) { old.remove(); });
phrase.querySelectorAll("[data-in]").forEach(function (old) {
old.removeAttribute("data-in");
old.setAttribute("data-out", "");
@@ -240,7 +263,7 @@
if (i < keep) c.style.visibility = "hidden";
else c.style.setProperty("--n", 0);
});
- setTimeout(function () { old.remove(); }, 600);
+ setTimeout(function () { old.remove(); }, 250);
});
var next = letters(text, keep);
next.setAttribute("data-in", "");
@@ -267,7 +290,7 @@
span.textContent = label;
var line = li.querySelector("[equipo-activity-line]");
if (line) line.title = label;
- draw(li, themed(li, label), false);
+ want(li, label);
}
// The line gives way (the first words arrived) or comes back (a tool
// after text).
@@ -842,7 +865,7 @@
card.querySelectorAll("textarea, input:not([type=hidden])").forEach(function (el) { if (values[el.name]) { el.value = values[el.name]; el.closest("form").setAttribute("data-has-content", ""); } });
});
feed.querySelectorAll("[data-message]").forEach(function (el) { shown[el.dataset.message] = true; });
- feed.replaceChildren.apply(feed, Array.from(next.children).map(function (el) {
+ var items = Array.from(next.children).map(function (el) {
var fresh = el.matches('[equipo-message="incoming"][data-turn-id]') && !shown[el.dataset.message];
var turn = el.hasAttribute("equipo-thinking") ? el.dataset.turn : fresh ? el.dataset.turnId : "";
var old = turn && keep[turn];
@@ -875,15 +898,17 @@
return old;
}
return settle(old, el);
- }).filter(Boolean));
+ }).filter(Boolean);
+ // A stale page lacks lines for turns that started since: they stay.
+ if (stale) Object.keys(keep).forEach(function (turn) { if (!ended[turn] && !queued[turn]) items.push(keep[turn]); });
+ // Lines shown since a send that no turn has adopted yet come last.
+ arrange(items.concat(pending));
+ if (window.equipoPulse) window.equipoPulse(feed);
if(cardFocus) {
var target=feed.querySelector('[data-card="'+CSS.escape(cardFocus.id)+'"] [name="'+CSS.escape(cardFocus.name)+'"]');
if(target) {target.focus({preventScroll:true});if(target.setSelectionRange)target.setSelectionRange(cardFocus.start,cardFocus.end);}
}
- // A stale page lacks lines for turns that started since: they stay.
- if (stale) Object.keys(keep).forEach(function (turn) { if (!ended[turn] && !queued[turn]) feed.append(keep[turn]); });
local.forEach(function (el) { place(el); });
- pending.forEach(function (el) { feed.append(el); });
Object.keys(drafts).forEach(function (turn) {
if (feed.querySelector('[equipo-thinking][data-turn="' + CSS.escape(turn) + '"], [data-roster-turn="' + CSS.escape(turn) + '"] [equipo-thread-draft]')) showDraft(turn);
});
@@ -892,6 +917,19 @@
scroll();
});
}
+ // arrange makes the feed the items, in order, moving only what must
+ // move: an element taken out and put back starts its animations again,
+ // so a thinking line kept across a refresh drew every fading phrase
+ // over the new one (Paul, 2026-11-20).
+ function arrange(items) {
+ var keep = new Set(items);
+ Array.from(feed.children).forEach(function (el) { if (!keep.has(el)) el.remove(); });
+ var at = feed.firstElementChild;
+ items.forEach(function (el) {
+ if (el === at) at = at.nextElementSibling;
+ else feed.insertBefore(el, at);
+ });
+ }
function apply(type, data) {
var e = JSON.parse(data);
if (e.cursor <= cursor) return;
@@ -1041,7 +1079,16 @@
showActivity(v);
} else if (type === "card" || type === "task" || type === "step") {
// Cards (and the tasks on them) are rendered by the server, like
- // committed replies.
+ // committed replies. A step that starts or stops starts or stops
+ // its track's pulse at once; the refresh then has the last word
+ // (a finished step may hand straight on to the next).
+ if (type === "step" && v && v.task_id) {
+ var on = v.state === "running";
+ if (on || v.state === "failed" || v.state === "cancelled") {
+ document.querySelectorAll('[data-track-task="' + CSS.escape(v.task_id) + '"] > [aria-current="step"]').forEach(function (li) { li.toggleAttribute("data-working", on); });
+ if (window.equipoPulse) window.equipoPulse(document.body);
+ }
+ }
refreshSoon();
} else if (type === "runner" && offline && v.role !== "worker") {
// The offline line is the primary's: a worker going offline is not
diff --git a/internal/equipo/static/equipo.css b/internal/equipo/static/equipo.css
index 161001e1..3a897049 100644
--- a/internal/equipo/static/equipo.css
+++ b/internal/equipo/static/equipo.css
@@ -232,7 +232,9 @@ html:has([equipo-conversation]) { overflow: hidden; scrollbar-gutter: auto; }
[equipo-phrase] > span > span { display: inline-block; white-space: pre; }
[equipo-phrase] > [data-in] > span { animation: equipo-letter-in .32s ease-out calc(.2s + var(--n) * var(--stagger, 14ms)) both, equipo-wave 3.2s ease-in-out calc(.7s + var(--j) * 45ms) infinite; }
[equipo-phrase] > [data-in] > [data-keep] { animation: equipo-wave 3.2s ease-in-out calc(.7s + var(--j) * 45ms) infinite; }
-[equipo-phrase] > [data-out] > span, [equipo-activity-line][data-leaving] [equipo-phrase] > span > span { animation: equipo-letter-out .6s ease both; }
+/* The old phrase is gone in .2 s, as the new one's letters start. */
+[equipo-phrase] > [data-out] > span { animation: equipo-letter-out .2s ease-in both; }
+[equipo-activity-line][data-leaving] [equipo-phrase] > span > span { animation: equipo-letter-out .6s ease both; }
@keyframes equipo-letter-in { from { opacity: 0; transform: translateY(.18em); } }
@keyframes equipo-letter-out { to { opacity: 0; transform: translateY(-.15em); } }
@keyframes equipo-wave { 0%, 22%, 100% { color: var(--rst-text); } 8% { color: var(--rst-accent); } }
@@ -477,6 +479,25 @@ a[equipo-source]:hover { color: var(--rst-text); text-decoration: underline; tex
[equipo-track-full] li[data-s="current"] > span:not([equipo-dot]) { color: var(--rst-text); font-weight: 600; }
[equipo-track-full] li > span { text-align: center; white-space: nowrap; }
[equipo-track-full] li > small { color: var(--rst-text-faint); margin-block-start: -.3rem; }
+/* While a specialist works on the current stop (data-working), the track
+ shows it: every 2.4s a light runs along the line into the stop and its
+ marker sends out one soft ring in the stop's own tone. Nothing moves
+ while the task waits on the person or nothing runs. Reduced motion
+ keeps a still ring. equipoPulse (work-stream.js) holds one phase
+ across live swaps. */
+[equipo-track-full] li[data-s="current"] { --equipo-pulse: var(--rst-accent); }
+[equipo-track-full] li[data-s="current"][data-tone="positive"] { --equipo-pulse: var(--rst-tone-positive-fg); }
+[equipo-track-full] li[data-s="current"][data-tone="negative"] { --equipo-pulse: var(--rst-tone-negative-fg); }
+[equipo-track-full] li[data-s="current"]:is([data-tone="attention"], [data-tone="warning"]) { --equipo-pulse: var(--rst-tone-warning-fg); }
+[equipo-track-full] li[data-working] [equipo-dot]::before { content: ""; position: absolute; inset: 0; border: 1px solid var(--equipo-pulse); border-radius: 50%; box-sizing: border-box; opacity: 0; pointer-events: none; animation: equipo-tl-ring 2.4s cubic-bezier(.16, 1, .3, 1) infinite; }
+[equipo-track-full] li:has(+ li[data-working])::before { mask-image: linear-gradient(90deg, rgb(0 0 0 / .72) 0 43%, #000 50%, rgb(0 0 0 / .72) 57% 100%); mask-size: 300% 100%; mask-repeat: no-repeat; animation: equipo-tl-flow 2.4s cubic-bezier(.45, 0, .55, 1) infinite; }
+[equipo-track-full] li:not([data-working]) > [data-working-cue] { display: none; }
+@keyframes equipo-tl-ring { 0%, 34% { opacity: 0; transform: scale(1.2); } 40% { opacity: .5; } 100% { opacity: 0; transform: scale(2.8); } }
+@keyframes equipo-tl-flow { 0% { mask-position: 100% 0; } 45%, 100% { mask-position: 0 0; } }
+@media (prefers-reduced-motion: reduce) {
+ [equipo-track-full] li[data-working] [equipo-dot]::before { animation: none; opacity: .6; transform: scale(1.9); }
+ [equipo-track-full] li:has(+ li[data-working])::before { animation: none; mask-image: none; }
+}
/* Badges for checks and review. */
[equipo-badge2] { display: inline-flex; align-items: center; gap: .35em; padding: .1rem .5rem .1rem .4rem; border-radius: var(--rst-radius-pill); font-size: var(--rst-fs-xs); white-space: nowrap; border: 1px solid transparent; color: var(--rst-tone-neutral-fg); background: var(--rst-tone-neutral-bg); cursor: default; }
[equipo-badge2] .icon { inline-size: .95em; block-size: .95em; margin: 0; }
diff --git a/internal/equipo/static/work-stream.js b/internal/equipo/static/work-stream.js
index 2b32690f..222baca1 100644
--- a/internal/equipo/static/work-stream.js
+++ b/internal/equipo/static/work-stream.js
@@ -6,6 +6,17 @@
// thread is not a region: chat-stream.js follows it.
(function () {
"use strict";
+ // equipoPulse(root): a stage track's working pulse (equipo.css) keeps
+ // one phase on every page and across swaps. Each ring and light under
+ // root is timed from the document's start, so a track swapped in or
+ // marked working carries on in step, never from the top.
+ window.equipoPulse = function (root) {
+ if (!root || !root.getAnimations) return;
+ root.getAnimations({ subtree: true }).forEach(function (a) {
+ if (a.animationName === "equipo-tl-ring" || a.animationName === "equipo-tl-flow") a.startTime = 0;
+ });
+ };
+ window.equipoPulse(document.body);
if (!document.querySelector("[data-work-live]") || !window.fetch) return;
var inflight = null, again = false, timer = 0;
function busy() {
@@ -26,6 +37,7 @@
var had = old.querySelectorAll("[equipo-tl] > li").length;
var focus = document.activeElement && old.contains(document.activeElement) ? document.activeElement.getAttribute("href") : null;
old.replaceWith(next);
+ window.equipoPulse(next);
Object.keys(open).forEach(function (id) { var d = document.getElementById(id); if (d) d.open = open[id]; });
var items = next.querySelectorAll("[equipo-tl] > li");
for (var i = had; had > 0 && i < items.length; i++) items[i].setAttribute("data-new", "");
diff --git a/internal/equipo/templates/work_parts.html b/internal/equipo/templates/work_parts.html
index ced6c824..2391a944 100644
--- a/internal/equipo/templates/work_parts.html
+++ b/internal/equipo/templates/work_parts.html
@@ -11,7 +11,7 @@
{{define "mono-l"}}<span equipo-mono data-size="l" data-h="{{.Hue}}" title="{{.Title}}" aria-hidden="true">{{.Letter}}</span>{{end}}
{{define "mono-s"}}<span equipo-mono data-size="s" data-h="{{.Hue}}" aria-hidden="true">{{.Letter}}</span>{{end}}
{{define "track"}}<ol equipo-track role="img" aria-label="{{.StepLabel}}">{{range .Track}}<li data-s="{{.State}}"{{if .Tone}} data-tone="{{.Tone}}"{{end}}{{if .Live}} data-live{{end}} title="{{.Label}}">{{if .Live}}{{template "mark" "s"}}{{end}}</li>{{end}}</ol>{{end}}
-{{define "track-full"}}<ol equipo-track-full data-track aria-label="{{.StageLine}}">{{range .Track}}<li data-s="{{.State}}"{{if .Tone}} data-tone="{{.Tone}}"{{end}}{{if .Live}} data-live{{end}}{{if eq .State "current"}} aria-current="step"{{end}}><span equipo-dot>{{if .Live}}{{template "mark" "s"}}{{end}}</span><span>{{.Label}}</span>{{with .At}}<small><time datetime="{{.Format "2006-01-02T15:04:05Z07:00"}}">{{.Format "15:04"}}</time></small>{{end}}</li>{{end}}</ol>{{end}}
+{{define "track-full"}}<ol equipo-track-full data-track data-track-task="{{.ID}}" aria-label="{{.StageLine}}">{{range .Track}}<li data-s="{{.State}}"{{if .Tone}} data-tone="{{.Tone}}"{{end}}{{if .Live}} data-live{{end}}{{if .Working}} data-working{{end}}{{if eq .State "current"}} aria-current="step"{{end}}><span equipo-dot>{{if .Live}}{{template "mark" "s"}}{{end}}</span><span>{{.Label}}</span>{{if eq .State "current"}}<i equipo-visually-hidden data-working-cue> {{copy "work.track.working"}}</i>{{end}}{{with .At}}<small><time datetime="{{.Format "2006-01-02T15:04:05Z07:00"}}">{{.Format "15:04"}}</time></small>{{end}}</li>{{end}}</ol>{{end}}
{{define "badge"}}<span equipo-badge2 data-kind="{{.Kind}}" data-tone="{{.Tone}}" title="{{.Title}}">{{if .Live}}{{template "mark" "s"}}{{else if .Icon}}{{icon .Icon}}{{end}}<span>{{.Text}}</span></span>{{end}}
{{define "chip"}}{{with .Chip}}<span equipo-chip{{if .Live}} data-live{{end}}>{{if .Live}}{{template "mark" "s"}}{{else if .Icon}}{{icon .Icon}}{{end}}<span>{{.Text}}</span>{{with .Since}}{{template "elapsed" .}}{{end}}</span>{{end}}{{end}}
{{define "source"}}{{if .SourceHref}}<a href="{{.SourceHref}}" equipo-source>{{.Source}}</a>{{else}}<span equipo-source>{{.Source}}</span>{{end}}{{end}}
diff --git a/internal/equipo/track_working_test.go b/internal/equipo/track_working_test.go
new file mode 100644
index 00000000..39d15148
--- /dev/null
+++ b/internal/equipo/track_working_test.go
@@ -0,0 +1,84 @@
+package equipo
+
+import (
+ "bytes"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// working is the data-working attribute itself, not data-working-cue.
+var working = regexp.MustCompile(`\sdata-working[\s>]`)
+
+// TestTrackWorkingPulse: the full stage track marks its current stop
+// as working while a specialist's step is queued or running, on the task
+// page and on the conversation's report card, and never while the task
+// waits on the person or nothing runs.
+func TestTrackWorkingPulse(t *testing.T) {
+ step := func(specialist, state string) wire.Step {
+ return wire.Step{ID: "s-" + state, TaskID: "tk", Specialist: specialist, State: state}
+ }
+ for _, tc := range []struct {
+ name string
+ task wire.Task
+ want bool
+ }{
+ {"running", wire.Task{Stage: wire.StageInProgress, Steps: []wire.Step{step(wire.SpecialistEngineering, wire.StepRunning)}}, true},
+ {"queued", wire.Task{Stage: wire.StageInReview, Steps: []wire.Step{step(wire.SpecialistEngineering, wire.StepDone), step(wire.SpecialistChecks, wire.StepQueued)}}, true},
+ {"exploration in review", wire.Task{Kind: wire.KindExplore, Stage: wire.StageInReview, Steps: []wire.Step{step(wire.SpecialistEngineering, wire.StepDone), step(wire.SpecialistReview, wire.StepRunning)}}, true},
+ {"merging", wire.Task{Stage: wire.StageMerging, Steps: []wire.Step{step(wire.SpecialistMerge, wire.StepRunning)}}, true},
+ {"noted", wire.Task{Stage: wire.StageNoted}, false},
+ {"step done", wire.Task{Stage: wire.StageInReview, Steps: []wire.Step{step(wire.SpecialistEngineering, wire.StepDone)}}, false},
+ {"stopped", wire.Task{Stage: wire.StageInProgress, Steps: []wire.Step{step(wire.SpecialistEngineering, wire.StepFailed)}}, false},
+ {"waits on the person", wire.Task{Stage: wire.StageInProgress, NeedsYou: wire.NeedsRunnerOffline, Steps: []wire.Step{step(wire.SpecialistEngineering, wire.StepQueued)}}, false},
+ {"copy held", wire.Task{Stage: wire.StageInReview, CopyHold: true, Steps: []wire.Step{step(wire.SpecialistCopy, wire.StepQueued)}}, false},
+ {"done", wire.Task{Stage: wire.StageDone, Steps: []wire.Step{step(wire.SpecialistMerge, wire.StepRunning)}}, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tc.task.ID, tc.task.Creator, tc.task.Title = "tk", "owner@example.com", "Fix it"
+ now := time.Now()
+ // The task page's track.
+ page := taskLineOf(tc.task, tc.task.Creator)
+ page.richOf(tc.task, tc.task.Creator, nil, now)
+ // The conversation card's track.
+ card := taskLineOf(tc.task, tc.task.Creator)
+ card.richOf(tc.task, tc.task.Creator, nil, now)
+ card.Track = rosterTrack(tc.task)
+ for where, v := range map[string]taskLine{"task page": page, "card": card} {
+ var b bytes.Buffer
+ if err := pages["work_task"].ExecuteTemplate(&b, "track-full", v); err != nil {
+ t.Fatal(err)
+ }
+ html := b.String()
+ if !strings.Contains(html, `data-track-task="tk"`) {
+ t.Fatalf("%s: the track does not name its task: %s", where, html)
+ }
+ items := strings.Split(html, "<li")[1:]
+ n := 0
+ for _, li := range items {
+ if !working.MatchString("<li" + li) {
+ continue
+ }
+ n++
+ if !strings.Contains(li, `aria-current="step"`) {
+ t.Errorf("%s: a stop other than the current one is working: %s", where, li)
+ }
+ }
+ if tc.want && n != 1 || !tc.want && n != 0 {
+ t.Errorf("%s: %d working stops, want working=%v: %s", where, n, tc.want, html)
+ }
+ // The current stop carries the hidden cue; CSS shows it to
+ // assistive technology only while the stop is working.
+ for _, li := range items {
+ cue := strings.Contains(li, `<i equipo-visually-hidden data-working-cue> (work underway)</i>`)
+ if cue != strings.Contains(li, `aria-current="step"`) {
+ t.Errorf("%s: working cue on the wrong stop: %s", where, li)
+ }
+ }
+ }
+ })
+ }
+}
diff --git a/internal/equipo/work_views.go b/internal/equipo/work_views.go
index e83917b0..fad87e35 100644
--- a/internal/equipo/work_views.go
+++ b/internal/equipo/work_views.go
@@ -101,10 +101,12 @@ func exploreIndex(t wire.Task) int {
}
// trackStop is one stop: done, current or todo, the current one with a
-// tone and, while someone is at work, the living mark.
+// tone and, while someone is at work, the living mark. Working is the
+// current stop while a specialist's step is queued or running: its
+// marker pulses.
type trackStop struct {
Stage, Label, State, Tone string
- Live bool
+ Live, Working bool
At *time.Time
}
@@ -201,6 +203,16 @@ func liveStep(t wire.Task) *wire.Step {
return nil
}
+// workingNow reports whether a specialist is at work on t: its newest
+// step queued or running, the task open and not waiting on the person.
+func workingNow(t wire.Task) bool {
+ if len(t.Steps) == 0 || wire.FinalStage(t.Stage) || t.NeedsYou != "" || t.CopyHold || t.CopyCanSkip {
+ return false
+ }
+ s := t.Steps[len(t.Steps)-1].State
+ return s == wire.StepQueued || s == wire.StepRunning
+}
+
// stoppedStep is the newest step when it failed on a task still open.
func stoppedStep(t wire.Task) *wire.Step {
if s := lastStep(t); s != nil && s.State == wire.StepFailed && !wire.FinalStage(t.Stage) {
@@ -295,7 +307,7 @@ func (v *taskLine) trackOf(t wire.Task) {
case i < cur:
n.State = "done"
case i == cur:
- n.State, n.Tone, n.Live = "current", v.Tone, v.Live
+ n.State, n.Tone, n.Live, n.Working = "current", v.Tone, v.Live, workingNow(t)
switch {
case t.Stage == wire.StageMerging:
n.Label = copyText("work.stage.merging")
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go
index b3bc7958..231be71e 100644
--- a/internal/fakeclaude/fake.go
+++ b/internal/fakeclaude/fake.go
@@ -1006,6 +1006,10 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int {
if _, after, ok := strings.Cut(prompt, "Newest message:\n"); ok {
newest = after
}
+ // Words a failed turn left unanswered ride before it, as context.
+ if _, after, ok := strings.Cut(newest, "The person's newest message:\n"); ok {
+ newest = after
+ }
// A move-in or explore turn has no person message to steer by.
steps, intro, settle := settling(prompt)
if settle {
diff --git a/internal/fakecodex/fake.go b/internal/fakecodex/fake.go
index 7ffa2749..5c56412c 100644
--- a/internal/fakecodex/fake.go
+++ b/internal/fakecodex/fake.go
@@ -411,6 +411,10 @@ func (s *server) runTurn(thread, turn, prompt string, stop chan struct{}) {
if _, after, ok := strings.Cut(prompt, "Newest message:\n"); ok {
newest = after
}
+ // Words a failed turn left unanswered ride before it, as context.
+ if _, after, ok := strings.Cut(newest, "The person's newest message:\n"); ok {
+ newest = after
+ }
done := func(status string, turnErr any) {
s.notify("turn/completed", map[string]any{"threadId": thread, "turn": map[string]any{"id": turn, "status": status, "items": []any{}, "error": turnErr}})
}
diff --git a/internal/headless/ask_test.go b/internal/headless/ask_test.go
index 373d2cf0..4829c8a0 100644
--- a/internal/headless/ask_test.go
+++ b/internal/headless/ask_test.go
@@ -171,14 +171,18 @@ func scenarioAsk(t *testing.T, env *Env) {
}
}
-// The staging witness (EQUIPO_STAGING_ASK_TASK): on a task whose steps
-// ran with their sessions kept, ask Engineering what it changed and
+// The staging witness (EQUIPO_STAGING_ASK_TASK, else the task this run's
+// 3_engineering pushed, which 4_review has seen judged): on a task whose
+// steps ran with their sessions kept, ask Engineering what it changed and
// Review what it was unsure about, then ask Engineering to fix a typo,
// which it must decline from here. Answers and timings go to the report.
func scenarioAskWitness(t *testing.T, env *Env) {
id := os.Getenv("EQUIPO_STAGING_ASK_TASK")
+ if id == "" {
+ id = pushedTask
+ }
if !env.Live || id == "" {
- t.Skip("staging only, with EQUIPO_STAGING_ASK_TASK")
+ t.Skip("staging only, with EQUIPO_STAGING_ASK_TASK or this run's 3_engineering task")
}
s := open(t, env)
s.keep()
@@ -186,6 +190,26 @@ func scenarioAskWitness(t *testing.T, env *Env) {
if err != nil {
t.Fatal(err)
}
+ if os.Getenv("EQUIPO_STAGING_ASK_TASK") == "" {
+ // Only a Claude step keeps its session (a Codex step keeps none,
+ // by design), and where this run's steps ran is the runner's call.
+ // The newest finished step of each is the one a question goes to.
+ newest := map[string]wire.Step{}
+ for _, st := range k.Steps {
+ if st.State == wire.StepDone && (st.Specialist == wire.SpecialistEngineering || st.Specialist == wire.SpecialistReview) {
+ newest[st.Specialist] = st
+ }
+ }
+ for _, name := range []string{wire.SpecialistEngineering, wire.SpecialistReview} {
+ st := newest[name]
+ if st.Family != "claude" {
+ t.Skipf("live: this run's %s ran on %s (%s), which keeps no session to ask", st.Specialist, st.Account, st.Family)
+ }
+ if !st.Askable {
+ t.Fatalf("a finished Claude step kept no session: %+v", st)
+ }
+ }
+ }
before := k.CandidateSHA
out := map[string]any{"task": id}
for _, q := range []struct{ name, text, specialist string }{
diff --git a/internal/headless/engineering_test.go b/internal/headless/engineering_test.go
index 27e4f217..59d3d9d0 100644
--- a/internal/headless/engineering_test.go
+++ b/internal/headless/engineering_test.go
@@ -74,6 +74,10 @@ func forgeShow(t *testing.T, bare string, args ...string) string {
return string(out)
}
+// pushedTask is the task a live 3_engineering pushed in this run, for the
+// scenarios that judge and ask about it without a new message.
+var pushedTask string
+
// Scenario 2, to the branch: the person reports a bug; the task is noted
// at once, investigated with a finding, and Engineering's step commits in
// a task tree, records the candidate SHA and pushes the task's own branch
@@ -120,6 +124,7 @@ func scenarioEngineering(t *testing.T, env *Env) {
}
noRepoQuestion(t, s, sent.Turn.ID)
if env.Live {
+ pushedTask = id
return
}
if !slices.Contains(stages, wire.StageInvestigated) || task.Findings[0].Path != "README.md" || task.Findings[0].Line != 5 {
@@ -163,11 +168,15 @@ func scenarioStepCrash(t *testing.T, env *Env) {
s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online })
text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Slowly. stepsleep:4000 edit:README.md|teh panes|the panes"
if env.Live {
+ if env.CrashWitness == "" {
+ t.Fatal("EQUIPO_STAGING_CRASH_WITNESS is not set")
+ }
text = env.CrashWitness
}
sent := s.send(t, text)
id := s.taskOf(t, sent.Turn.ID)
- running := s.step(t, id, 5*time.Minute, wire.StepRunning)
+ // Live, the step may queue behind the earlier tasks' checks and review.
+ running := s.step(t, id, 10*time.Minute, wire.StepRunning)
if !env.Live {
// What Engineering started shows while it runs: the fake reads the
// file it will edit before it sleeps.
@@ -225,23 +234,38 @@ func scenarioStepCrash(t *testing.T, env *Env) {
}
// Cancel during a step: the task ends only when the runner reports the
-// attempt's termination; nothing is pushed.
+// attempt's termination; nothing is pushed. Live, the person asks for a
+// real change (EQUIPO_STAGING_CANCEL_WITNESS) and cancels it a second
+// after the real Engineering step starts, long before it could push.
func scenarioStepCancel(t *testing.T, env *Env) {
s := open(t, env)
s.keep()
- sent := s.send(t, "tool:record_task:oficina/sample|Slow change|x\ntool:start_task:$task|stepsleep:20000 edit:README.md|teh|the")
+ text, running, ended := "tool:record_task:oficina/sample|Slow change|x\ntool:start_task:$task|stepsleep:20000 edit:README.md|teh|the", time.Minute, time.Minute
+ if env.Live {
+ if env.CancelWitness == "" {
+ t.Fatal("EQUIPO_STAGING_CANCEL_WITNESS is not set")
+ }
+ // The live step may queue behind the earlier task's checks and
+ // review, and ends only when the runner has stopped a real
+ // process tree.
+ text, running, ended = env.CancelWitness, 10*time.Minute, 3*time.Minute
+ }
+ sent := s.send(t, text)
id := s.taskOf(t, sent.Turn.ID)
- s.step(t, id, time.Minute, wire.StepRunning)
+ s.step(t, id, running, wire.StepRunning)
time.Sleep(time.Second)
acc, err := env.Client.CancelTask(s.ctx, id)
if err != nil || acc.Attempt != 1 {
t.Fatalf("cancel: %+v %v", acc, err)
}
- st := s.step(t, id, time.Minute, wire.StepCancelled, wire.StepFailed, wire.StepDone)
+ st := s.step(t, id, ended, wire.StepCancelled, wire.StepFailed, wire.StepDone)
if st.State != wire.StepCancelled || !st.Terminated || st.Pushed {
t.Fatalf("cancelled step %+v", st)
}
s.wait(t, "task cancelled", 30*time.Second, func(c *thintest.Conversation) bool { return c.Tasks[id].Stage == wire.StageCancelled })
+ if env.Live {
+ return
+ }
if forgeHead(t, env.ForgePath("amadan.net/oficina/sample"), wire.TaskBranch(id, "Slow change")) != "" {
t.Fatal("a cancelled step pushed")
}
@@ -250,6 +274,9 @@ func scenarioStepCancel(t *testing.T, env *Env) {
// A step that asks to write outside /workspace is denied by the
// permission callback, and the tree commits only what it changed inside.
func scenarioStepContained(t *testing.T, env *Env) {
+ if env.Live {
+ t.Skip("local only: the fake CLI asks to write outside /workspace; a live model is never steered to")
+ }
s := open(t, env)
s.keep()
sent := s.send(t, "tool:record_task:oficina/sample|Contained|x\ntool:start_task:$task|escape:/etc/hostname escape:/home/runner/.claude/x edit:README.md|teh|the")
diff --git a/internal/headless/env_test.go b/internal/headless/env_test.go
index e906a10a..17b0a351 100644
--- a/internal/headless/env_test.go
+++ b/internal/headless/env_test.go
@@ -94,8 +94,10 @@ type Env struct {
// BreakDesk makes the desk record unwritable, then starts the runner.
BreakDesk func(t *testing.T)
// Witness is what the person says in the live Engineering scenario
- // (EQUIPO_STAGING_WITNESS); CrashWitness the same for scenario 4.
- Witness, CrashWitness string
+ // (EQUIPO_STAGING_WITNESS); CrashWitness the same for scenario 4 and
+ // CancelWitness for the step cancel. Each asks for a different change,
+ // so no two of a run's tasks read alike.
+ Witness, CrashWitness, CancelWitness string
// ForgePath is a local forge repository's bare path (local only).
ForgePath func(repo string) string
// GrantNow makes a repository reachable without restarting the
@@ -447,6 +449,7 @@ func stagingEnv(t *testing.T) *Env {
Project: os.Getenv("EQUIPO_STAGING_PROJECT"),
Witness: os.Getenv("EQUIPO_STAGING_WITNESS"),
CrashWitness: os.Getenv("EQUIPO_STAGING_CRASH_WITNESS"),
+ CancelWitness: os.Getenv("EQUIPO_STAGING_CANCEL_WITNESS"),
turns: &turns,
}
}
diff --git a/internal/headless/review_test.go b/internal/headless/review_test.go
index f78f3daa..8844f871 100644
--- a/internal/headless/review_test.go
+++ b/internal/headless/review_test.go
@@ -69,20 +69,32 @@ func witnessTask(t *testing.T, k wire.Task, checks, review wire.Step, since time
// and verdict agree, so the task is ready to merge, and Equipo merges that
// SHA into main through the forge (a merge commit, the branch deleted) and
// says so in one line.
+//
+// Live, the task is the one 3_engineering pushed in this run, judged with
+// no new message (or a new one from EQUIPO_STAGING_REVIEW_WITNESS): it
+// ends ready to merge or needing its person, on one SHA, and checks that
+// could not run say why.
func scenarioReview(t *testing.T, env *Env) {
- if env.Live && os.Getenv("EQUIPO_STAGING_REVIEW_WITNESS") == "" {
- t.Skip("EQUIPO_STAGING_REVIEW_WITNESS is not set")
+ witness := os.Getenv("EQUIPO_STAGING_REVIEW_WITNESS")
+ if env.Live && witness == "" && pushedTask == "" {
+ t.Skip("live: needs this run's 3_engineering task or EQUIPO_STAGING_REVIEW_WITNESS")
}
s := open(t, env)
s.keep()
s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online })
text := "tool:record_task:oficina/sample|Make edge swipe go back|Swiping from the edge does nothing.\ntool:start_task:$task|review:need:README.md|keeps your place, always|edit=README.md~keeps your place~keeps your place, always; edit:panes/swipe.go|return false|return true"
if env.Live {
- text = os.Getenv("EQUIPO_STAGING_REVIEW_WITNESS")
+ text = witness
}
start := time.Now()
- sent := s.send(t, text)
- id := s.taskOf(t, sent.Turn.ID)
+ var sent wire.Sent
+ var id string
+ if env.Live && witness == "" {
+ id = pushedTask
+ } else {
+ sent = s.send(t, text)
+ id = s.taskOf(t, sent.Turn.ID)
+ }
k := s.settled(t, id, 40*time.Minute)
checks, review := oneSHA(t, k)
witnessTask(t, k, checks, review, start)
@@ -91,6 +103,10 @@ func scenarioReview(t *testing.T, env *Env) {
if k.Stage != wire.StageReadyToMerge && k.NeedsYou == "" {
t.Fatalf("task ended %s", k.Stage)
}
+ // Honest checks: what could not run says why, and is never a pass.
+ if k.Checks == wire.ChecksCannotRun && (k.ChecksReason == "" || checks.Checks != wire.ChecksCannotRun) {
+ t.Fatalf("checks that could not run: task %s (%q), step %+v", k.Checks, k.ChecksReason, checks)
+ }
return
}
// Approved with checks passed on the branch's head: Equipo merges it.
diff --git a/internal/plan3test/plan3_release_test.go b/internal/plan3test/plan3_release_test.go
index 3f15d17e..e67e4abb 100644
--- a/internal/plan3test/plan3_release_test.go
+++ b/internal/plan3test/plan3_release_test.go
@@ -170,7 +170,7 @@ func plan3CopyInventory(t *testing.T) {
acceptedRound2 := slices.Contains([]string{"CopyCalibrationFunding"}, key) && strings.TrimSuffix(cells[3], " |") == "COPY ACCEPTED FOR NOW (Paul, 2026-11-05; iterate in context)"
// Paul delegated copy review on 2026-10-25; a row Astra's
// delegated pass accepted carries that marker.
- acceptedDelegation := strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)") || strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)") || strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)") || slices.Contains([]string{"docs/api/equipo-v1.md / COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)", "docs/api/equipo-v1.md / Retry writes and handle revisions", "docs/api/equipo-v1.md / Reconnect and answer questions", "docs/api/equipo-v1.md / Talk to your Coordinator from a device"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-19)") || slices.Contains([]string{"conversation.empty", "conversation.start.label", "conversation.start.bug", "conversation.start.bug_draft", "conversation.start.feature", "conversation.start.feature_draft", "conversation.start.project", "conversation.start.project_draft"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-20)")
+ acceptedDelegation := strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)") || strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12)") || strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)") || slices.Contains([]string{"docs/api/equipo-v1.md / COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)", "docs/api/equipo-v1.md / Retry writes and handle revisions", "docs/api/equipo-v1.md / Reconnect and answer questions", "docs/api/equipo-v1.md / Talk to your Coordinator from a device"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-19)") || slices.Contains([]string{"conversation.empty", "conversation.start.label", "conversation.start.bug", "conversation.start.bug_draft", "conversation.start.feature", "conversation.start.feature_draft", "conversation.start.project", "conversation.start.project_draft", "work.track.working"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-20)")
// Paul's own review of the publish strings (base-publish).
approvedPublish := strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-12, copy-review jadya3tfrmkf7t3ym2nqhpgira, unchanged)")
// Paul's own review of the Assistant lane's strings and API section.
diff --git a/internal/runner/provider/accounts.go b/internal/runner/provider/accounts.go
index edd6a829..5ce82146 100644
--- a/internal/runner/provider/accounts.go
+++ b/internal/runner/provider/accounts.go
@@ -8,7 +8,6 @@ import (
"encoding/hex"
"encoding/json"
"errors"
- "fmt"
"io"
"os"
"os/user"
@@ -900,6 +899,12 @@ func (l *AccountLease) PreflightFingerprint(ctx context.Context) (string, error)
return hex.EncodeToString(sum[:]), nil
}
-func accountContainment(reason string) error {
- return fmt.Errorf("%w: %s", ErrContainment, reason)
-}
+// containmentError is ErrContainment with its category, always a literal.
+type containmentError struct{ reason string }
+
+func (e containmentError) Error() string { return string(ErrContainment) + ": " + e.reason }
+func (e containmentError) Unwrap() error { return ErrContainment }
+func accountContainment(reason string) error { return containmentError{reason} }
+
+// ContainmentReason is a containment refusal's category, safe to log; "" otherwise.
+func ContainmentReason(err error) string { var c containmentError; errors.As(err, &c); return c.reason }
diff --git a/internal/runner/provider/token_test.go b/internal/runner/provider/token_test.go
index 8a9a129d..47798190 100644
--- a/internal/runner/provider/token_test.go
+++ b/internal/runner/provider/token_test.go
@@ -118,3 +118,21 @@ func TestClaudeTokenIdentity(t *testing.T) {
t.Fatal(err)
}
}
+
+// A containment refusal keeps its fixed category: the runner's log needs
+// it to say what changed in a copy, and it is never a path.
+func TestContainmentKeepsItsReason(t *testing.T) {
+ l := openTokenCopy(t, tokenFixture(t))
+ // A signed-in CLI records the account in its native config.
+ writeFake(t, filepath.Join(l.Binding().Home, ".claude.json"), `{"oauthAccount":{"emailAddress":"a@example.com","accountUuid":"u1"}}`)
+ err := l.CheckCopy(context.Background())
+ if !errors.Is(err, ErrContainment) {
+ t.Fatalf("changed account metadata accepted: %v", err)
+ }
+ if got := ContainmentReason(err); got != "runtime_claude_identity" {
+ t.Fatalf("reason %q", got)
+ }
+ if got := ContainmentReason(ErrPolicy); got != "" {
+ t.Fatalf("a policy refusal has containment reason %q", got)
+ }
+}
diff --git a/internal/runner/thin/bridge.go b/internal/runner/thin/bridge.go
index a0e93615..8ca8919e 100644
--- a/internal/runner/thin/bridge.go
+++ b/internal/runner/thin/bridge.go
@@ -100,15 +100,30 @@ func (b *bridge) call(ctx context.Context, person, turn string, attempt int64, n
}
// Creation progress is kept with the call: a resent call never
// creates twice, and a repository that already exists (an earlier
- // answer was lost) is adopted.
+ // answer was lost, or another writer made it) is adopted as it is.
+ // "made" is recorded only once the hub answered that this call
+ // created it, so only such a repository gets main started, also
+ // when a resent call finishes a start that failed.
state, err := b.State.creation(ctx, base, repo)
if err != nil {
return toolCreateError, true
}
- if state == "" {
- exists, err := b.Forge.Exists(ctx, repo)
- if err == nil && !exists {
- err = b.Forge.Create(ctx, repo)
+ if state == "" || state == "made" {
+ ours := state == "made"
+ if !ours {
+ var exists bool
+ if exists, err = b.Forge.Exists(ctx, repo); err == nil && !exists {
+ switch err = b.Forge.Create(ctx, repo); {
+ case err == nil:
+ ours, err = true, b.State.setCreation(ctx, base, repo, "made")
+ case errors.Is(err, ErrAdopted):
+ err = nil
+ }
+ }
+ }
+ if err == nil && ours && b.Clones != nil {
+ // main first, so task branches start from it and merge into it.
+ err = b.Clones.StartDefault(ctx, repo)
}
if err == nil {
err = b.State.setCreation(ctx, base, repo, "created")
diff --git a/internal/runner/thin/claude.go b/internal/runner/thin/claude.go
index cb80a226..402d40c0 100644
--- a/internal/runner/thin/claude.go
+++ b/internal/runner/thin/claude.go
@@ -277,6 +277,9 @@ func (c *coordBase) log(msg string, err error) {
// sanitize keeps only provider error codes: no paths or provider output.
func sanitize(err error) string {
+ if reason := provider.ContainmentReason(err); reason != "" {
+ return string(provider.ErrContainment) + ": " + reason
+ }
var p provider.Error
if errors.As(err, &p) {
return string(p)
diff --git a/internal/runner/thin/copy_reason_test.go b/internal/runner/thin/copy_reason_test.go
new file mode 100644
index 00000000..5a78e489
--- /dev/null
+++ b/internal/runner/thin/copy_reason_test.go
@@ -0,0 +1,39 @@
+package thin
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+// The log keeps a containment refusal's fixed category (2026-11-20:
+// production logged only provider_account_containment).
+func TestSanitizeKeepsContainmentReason(t *testing.T) {
+ root := t.TempDir()
+ home := filepath.Join(root, "claude-1")
+ id := provider.Identity{AccountID: "token:claude-1", HomeID: "h", ProviderVersion: provider.ClaudeVersion}
+ raw, _ := json.Marshal(id)
+ if os.Mkdir(home, 0700) != nil || os.WriteFile(filepath.Join(home, provider.IdentityFile), raw, 0600) != nil || os.WriteFile(filepath.Join(home, provider.TokenFile), []byte("sk-ant-oat01-canary"), 0600) != nil {
+ t.Fatal("home")
+ }
+ b := provider.Binding{ID: "claude-1", Home: home, AccountID: id.AccountID, Provider: "claude", Token: true, Expected: id, RuntimeRoot: filepath.Join(root, "homes")}
+ l, err := provider.OpenRuntimeCopy(context.Background(), b, func(context.Context, provider.Binding) (provider.Identity, error) { return id, nil }, time.Second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l.Close()
+ if err = os.WriteFile(filepath.Join(l.Binding().Home, provider.TokenFile), []byte("x"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if got := sanitize(l.CheckCopy(context.Background())); got != "provider_account_containment: runtime_token_credential" {
+ t.Fatalf("logged %q", got)
+ }
+ if got := sanitize(provider.ErrPolicy); got != "provider_policy_rejected" {
+ t.Fatalf("logged %q", got)
+ }
+}
diff --git a/internal/runner/thin/forge.go b/internal/runner/thin/forge.go
index 58d48d16..2baf2817 100644
--- a/internal/runner/thin/forge.go
+++ b/internal/runner/thin/forge.go
@@ -35,7 +35,8 @@ type Forge interface {
Remote(ctx context.Context, repo string) (workspace.Remote, error)
// CreateIn lists namespaces the runner's agent may create repositories in.
CreateIn(ctx context.Context) []string
- // Create makes a new private repository and adds it to Repos.
+ // Create makes a new private repository and adds it to Repos. One that
+ // exists already is added too, with ErrAdopted: it is not this runner's.
Create(ctx context.Context, repo string) error
// Reachable lists every repository the agent can reach, for the
// context index. It includes Repos.
@@ -54,6 +55,11 @@ type Forge interface {
// ErrNoCreate means repositories cannot be created in that namespace.
var ErrNoCreate = errors.New("repository creation is not available here")
+// ErrAdopted means Create did not make the repository: it existed, or the
+// hub's answer was lost and it exists now. It is adopted, and is not this
+// runner's to start.
+var ErrAdopted = errors.New("the repository already exists; adopted")
+
// ErrEmptyRepo means the forge serves the repository and it has no
// commits yet: no branch, nothing to read. It is not an access failure.
var ErrEmptyRepo = errors.New("the repository has no commits yet")
@@ -263,6 +269,8 @@ func (f *fileForge) Exists(ctx context.Context, repo string) (bool, error) {
// Create makes repo once: an existing one (an earlier answer was lost) is
// adopted, and after any failure the hub is asked again before giving up.
+// Only the hub's own "created" answer makes it this runner's; an adopted
+// one returns ErrAdopted.
func (f *fileForge) Create(ctx context.Context, repo string) error {
parts := strings.Split(strings.TrimPrefix(repo, nsPrefix), "/")
if !ValidNewRepo(repo) || !slices.Contains(f.CreateIn(ctx), parts[0]) {
@@ -271,7 +279,7 @@ func (f *fileForge) Create(ctx context.Context, repo string) error {
if ok, err := f.Exists(ctx, repo); err != nil {
return err
} else if ok {
- return f.record(repo)
+ return f.adopt(repo)
}
c, err := f.agent(ctx)
if err != nil {
@@ -288,12 +296,20 @@ func (f *fileForge) Create(ctx context.Context, repo string) error {
return f.record(repo)
}
}
+ // "Already exists", or no answer: someone else's, or not known to be ours.
if ok, xerr := f.Exists(ctx, repo); xerr == nil && ok {
- return f.record(repo)
+ return f.adopt(repo)
}
return ErrNoCreate
}
+func (f *fileForge) adopt(repo string) error {
+ if err := f.record(repo); err != nil {
+ return err
+ }
+ return ErrAdopted
+}
+
// Merge sends the hub the merge request with the agent's credential for
// repo (its own entry, or the agent-wide one).
func (f *fileForge) Merge(ctx context.Context, repo, branch string, req forge.HubMergeRequest) (forge.HubMergeResult, error) {
@@ -397,20 +413,9 @@ func (c *Clones) fetch(ctx context.Context, repo string, shallow bool, branch st
if err != nil {
return err
}
- env := workspace.GitEnvironment()
- env["HOME"] = "/nonexistent"
- protocol := "https"
- if filepath.IsAbs(remote.URL) {
- protocol = "file"
- if remote.GitPassword != "" {
- return ErrNoCreate
- }
- } else if remote.GitPassword == "" || !strings.HasPrefix(remote.URL, "https://") {
- return workspace.ErrGitPassword
- } else {
- env["GIT_CONFIG_COUNT"] = "10"
- env["GIT_CONFIG_KEY_9"] = "http.extraHeader"
- env["GIT_CONFIG_VALUE_9"] = "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte("x:"+remote.GitPassword))
+ env, protocol, err := remoteEnv(remote)
+ if err != nil {
+ return err
}
dir := c.Path(repo)
if err = os.MkdirAll(filepath.Dir(dir), 0700); err != nil {
@@ -475,6 +480,148 @@ func groupCommand(ctx context.Context, name string, args ...string) *exec.Cmd {
return cmd
}
+// remoteEnv is git's environment for a resolved remote: no home, and the
+// password only in a header. A local path takes no password; an https
+// remote needs one.
+func remoteEnv(remote workspace.Remote) (map[string]string, string, error) {
+ env := workspace.GitEnvironment()
+ env["HOME"] = "/nonexistent"
+ if filepath.IsAbs(remote.URL) {
+ if remote.GitPassword != "" {
+ return nil, "", ErrNoCreate
+ }
+ return env, "file", nil
+ }
+ if remote.GitPassword == "" || !strings.HasPrefix(remote.URL, "https://") {
+ return nil, "", workspace.ErrGitPassword
+ }
+ env["GIT_CONFIG_COUNT"] = "10"
+ env["GIT_CONFIG_KEY_9"] = "http.extraHeader"
+ env["GIT_CONFIG_VALUE_9"] = "Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte("x:"+remote.GitPassword))
+ return env, "https", nil
+}
+
+// startDefaultGap runs between StartDefault's emptiness check and its
+// push; tests put another writer there.
+var startDefaultGap = func() {}
+
+// startDate makes the start commit the same bytes every time.
+const startDate = "2026-01-01T00:00:00+0000"
+
+// lsRefs reads ls-remote's lines: each ref once, without HEAD and without
+// the peeled lines of annotated tags (refs/tags/v1^{}), which are no refs
+// of their own.
+func lsRefs(out string) map[string]string {
+ got := map[string]string{}
+ for _, line := range strings.Split(out, "\n") {
+ if sha, ref, ok := strings.Cut(line, "\t"); ok && ref != "HEAD" && !strings.HasSuffix(ref, "^{}") {
+ got[ref] = sha
+ }
+ }
+ return got
+}
+
+// StartDefault gives a repository this runner just created its default
+// branch before any task branch exists: main, at an empty first commit
+// with no parent. Task branches then start from main, and every merge
+// targets it. Left unborn, the hub made the first task branch pushed the
+// default, and a later task's merge was asked to merge into that
+// unrelated branch. A repository with any ref at all is left alone.
+//
+// Another writer may push between the check and the push. The start
+// commit is deterministic (fixed dates), so main is recognisable as this
+// start, and it is pushed create-only (an empty lease): a main of theirs
+// is never replaced, and is the default. Any other ref that does not
+// start from this main fails the start, now and on every retry; main is
+// withdrawn when the forge allows (only while it is still the start), so
+// no main unrelated to their work is left behind quietly.
+func (c *Clones) StartDefault(ctx context.Context, repo string) error {
+ if !repoKey.MatchString(repo) {
+ return ErrNoCreate
+ }
+ remote, err := readRemote(ctx, c.Forge, repo)
+ if err != nil {
+ return err
+ }
+ refs := func() (map[string]string, error) {
+ out, err := c.lsRemote(ctx, remote, "--", remote.URL)
+ if err != nil {
+ return nil, err
+ }
+ return lsRefs(string(out)), nil
+ }
+ env, protocol, err := remoteEnv(remote)
+ if err != nil {
+ return err
+ }
+ dir, err := os.MkdirTemp(c.Root, "start-")
+ if err != nil {
+ return err
+ }
+ defer os.RemoveAll(dir)
+ for k, v := range map[string]string{"GIT_DIR": dir, "GIT_AUTHOR_NAME": commitName, "GIT_AUTHOR_EMAIL": commitEmail, "GIT_COMMITTER_NAME": commitName, "GIT_COMMITTER_EMAIL": commitEmail, "GIT_AUTHOR_DATE": startDate, "GIT_COMMITTER_DATE": startDate} {
+ env[k] = v
+ }
+ git := func(stdin string, args ...string) (string, error) {
+ cmd := groupCommand(ctx, c.Git, append([]string{"-c", "protocol." + protocol + ".allow=always", "-c", "http.followRedirects=false"}, args...)...)
+ cmd.Dir = dir
+ for k, v := range env {
+ cmd.Env = append(cmd.Env, k+"="+v)
+ }
+ cmd.Stdin, cmd.Stderr = strings.NewReader(stdin), io.Discard
+ out, err := cmd.Output()
+ return strings.TrimSpace(string(out)), err
+ }
+ if _, err := git("", "init", "-q", "--bare", "--template=", dir); err != nil {
+ return err
+ }
+ tree, err := git("", "hash-object", "-t", "tree", "-w", "--stdin")
+ if err != nil {
+ return err
+ }
+ sha, err := git("Start the repository\n", "commit-tree", tree)
+ if err != nil || !shaPattern.MatchString(sha) {
+ return fmt.Errorf("start %s: no first commit", repo)
+ }
+ main := "refs/heads/" + unbornDefault
+ have, err := refs()
+ if err != nil {
+ return err
+ }
+ if len(have) == 0 {
+ startDefaultGap()
+ _, perr := git("", "push", "-q", "--no-verify", "--force-with-lease="+main+":", "--", remote.URL, sha+":"+main)
+ if have, err = refs(); err != nil {
+ return err
+ }
+ if perr != nil && have[main] == "" {
+ return fmt.Errorf("start %s: push main: %w", repo, perr)
+ }
+ }
+ if have[main] != sha {
+ return nil // refs of their own, or their main: left as they are
+ }
+ delete(have, main)
+ if len(have) == 0 {
+ return nil
+ }
+ if _, err := git("", "fetch", "-q", "--no-tags", "--", remote.URL, "+refs/*:refs/check/*"); err == nil {
+ related := true
+ for ref := range have {
+ if _, err := git("", "merge-base", "--is-ancestor", sha, "refs/check/"+strings.TrimPrefix(ref, "refs/")); err != nil {
+ related = false
+ }
+ }
+ if related {
+ return nil
+ }
+ }
+ if _, err := git("", "push", "-q", "--no-verify", "--force-with-lease="+main+":"+sha, "--", remote.URL, ":"+main); err != nil {
+ return fmt.Errorf("start %s: another writer's branch does not start from main, and main could not be withdrawn: %w", repo, err)
+ }
+ return fmt.Errorf("start %s: another writer's branch does not start from main; main withdrawn", repo)
+}
+
// DefaultBranch asks the remote which branch HEAD names.
func (c *Clones) DefaultBranch(ctx context.Context, repo string) (string, error) {
remote, err := readRemote(ctx, c.Forge, repo)
diff --git a/internal/runner/thin/start_default_test.go b/internal/runner/thin/start_default_test.go
new file mode 100644
index 00000000..7557bc28
--- /dev/null
+++ b/internal/runner/thin/start_default_test.go
@@ -0,0 +1,384 @@
+package thin
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// creatingForge makes each repository it creates as an empty bare
+// repository, the way the hub serves a new one.
+type creatingForge struct {
+ pathForge
+ t *testing.T
+ failPush bool
+}
+
+func (f *creatingForge) Create(ctx context.Context, repo string) error {
+ if err := f.countingForge.Create(ctx, repo); err != nil {
+ return err
+ }
+ gitT(f.t, filepath.Dir(f.path(repo)), "init", "-q", "--bare", "-b", "main", f.path(repo))
+ if f.failPush {
+ // The hub refuses the first push: no main, and nothing recorded.
+ os.Chmod(filepath.Join(f.path(repo), "objects"), 0500)
+ f.t.Cleanup(func() { os.Chmod(filepath.Join(f.path(repo), "objects"), 0700) })
+ }
+ return nil
+}
+
+func startRig(t *testing.T) (*creatingForge, *Clones) {
+ t.Helper()
+ root := t.TempDir()
+ f := &creatingForge{pathForge: pathForge{root: filepath.Join(root, "forge")}, t: t}
+ os.MkdirAll(f.root, 0700)
+ os.MkdirAll(filepath.Join(root, "work"), 0700)
+ return f, &Clones{Root: filepath.Join(root, "work"), Git: "git", Forge: f}
+}
+
+// A repository Equipo creates gets its default branch, main, at an empty
+// first commit before any task branch exists. Task branches then start
+// from main and every merge targets it. Without it, the hub made the
+// first task branch pushed the default, and the next task's merge was
+// asked to merge into that unrelated branch ("could not compute the
+// merge").
+func TestStartDefaultMakesMainBeforeAnyTaskBranch(t *testing.T) {
+ f, c := startRig(t)
+ const repo = "amadan.net/oficina/site"
+ ctx := context.Background()
+ if err := f.Create(ctx, repo); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := c.DefaultBranch(ctx, repo); !errors.Is(err, ErrEmptyRepo) {
+ t.Fatalf("a new repository should start empty: %v", err)
+ }
+ if err := c.StartDefault(ctx, repo); err != nil {
+ t.Fatal(err)
+ }
+ remote := f.path(repo)
+ if refs := gitT(t, remote, "for-each-ref", "--format=%(refname)"); refs != "refs/heads/main" {
+ t.Fatalf("refs after start: %q", refs)
+ }
+ main := gitT(t, remote, "rev-parse", "refs/heads/main")
+ if tree := gitT(t, remote, "rev-parse", main+"^{tree}"); tree != gitT(t, remote, "hash-object", "-t", "tree", "/dev/null") {
+ t.Fatalf("main's first commit is not empty: tree %s", tree)
+ }
+ if parents := gitT(t, remote, "rev-list", "--parents", "-n1", main); parents != main {
+ t.Fatalf("main's first commit has parents: %s", parents)
+ }
+ if def, err := c.DefaultBranch(ctx, repo); err != nil || def != "main" {
+ t.Fatalf("default after start: %q %v", def, err)
+ }
+ // Again (a resent create): nothing new.
+ if err := c.StartDefault(ctx, repo); err != nil {
+ t.Fatal(err)
+ }
+ if again := gitT(t, remote, "rev-parse", "refs/heads/main"); again != main {
+ t.Fatalf("main moved on a second start: %s -> %s", main, again)
+ }
+}
+
+// A repository with any branch already, including one holding only task
+// branches (the stuck ones), is left exactly as it is.
+func TestStartDefaultLeavesBranchesAlone(t *testing.T) {
+ f, c := startRig(t)
+ const repo = "amadan.net/oficina/stuck"
+ ctx := context.Background()
+ if err := f.Create(ctx, repo); err != nil {
+ t.Fatal(err)
+ }
+ seed := filepath.Join(t.TempDir(), "seed")
+ gitT(t, filepath.Dir(seed), "init", "-q", "-b", "equipo/tk1-demo", seed)
+ os.WriteFile(filepath.Join(seed, "index.html"), []byte("demo\n"), 0600)
+ gitT(t, seed, "add", "-A")
+ gitT(t, seed, "commit", "-q", "-m", "demo")
+ gitT(t, seed, "push", "-q", f.path(repo), "equipo/tk1-demo")
+ before := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)")
+ if err := c.StartDefault(ctx, repo); err != nil {
+ t.Fatal(err)
+ }
+ if after := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)"); after != before {
+ t.Fatalf("refs changed: %q -> %q", before, after)
+ }
+}
+
+// create_project starts main as part of creating the repository; a
+// failed start is not recorded as created, so the resent call (the
+// repository exists by then) starts it.
+func TestCreateProjectStartsMain(t *testing.T) {
+ state, err := OpenState(context.Background(), t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer state.Close()
+ f, c := startRig(t)
+ f.failPush = true
+ b := &bridge{State: state, Forge: f, Clones: c, speaks: wire.ProtocolCurrent, trip: func(_ context.Context, call wire.ToolCall) wire.ToolResult {
+ var in struct{ Repo string }
+ _ = json.Unmarshal(call.Args, &in)
+ if call.Name == wire.ToolCreateProject {
+ return wire.ToolResult{Code: "create", Repo: in.Repo}
+ }
+ return wire.ToolResult{Code: "created", Repo: in.Repo, Text: "Created."}
+ }}
+ args := json.RawMessage(`{"namespace":"oficina","name":"site"}`)
+ if _, isErr := b.Call(context.Background(), "p", "t1", 1, wire.ToolCreateProject, "toolu_1", args); !isErr {
+ t.Fatal("a repository without main was reported created")
+ }
+ remote := f.path("amadan.net/oficina/site")
+ os.Chmod(filepath.Join(remote, "objects"), 0700)
+ if text, isErr := b.Call(context.Background(), "p", "t1", 1, wire.ToolCreateProject, "toolu_1", args); isErr {
+ t.Fatalf("resent create: %s", text)
+ }
+ if f.creates != 1 {
+ t.Fatalf("created %d times", f.creates)
+ }
+ if refs := gitT(t, remote, "for-each-ref", "--format=%(refname)"); strings.TrimSpace(refs) != "refs/heads/main" {
+ t.Fatalf("refs after create: %q", refs)
+ }
+}
+
+// Only a repository this bridge created is started. One that already
+// existed, empty or holding only tags, is adopted exactly as it is.
+func TestCreateProjectAdoptsExistingRepositoriesAsTheyAre(t *testing.T) {
+ state, err := OpenState(context.Background(), t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer state.Close()
+ f, c := startRig(t)
+ b := &bridge{State: state, Forge: f, Clones: c, speaks: wire.ProtocolCurrent, trip: func(_ context.Context, call wire.ToolCall) wire.ToolResult {
+ var in struct{ Repo string }
+ _ = json.Unmarshal(call.Args, &in)
+ if call.Name == wire.ToolCreateProject {
+ return wire.ToolResult{Code: "create", Repo: in.Repo}
+ }
+ return wire.ToolResult{Code: "created", Repo: in.Repo, Text: "Created."}
+ }}
+ ctx := context.Background()
+ for i, name := range []string{"empty", "tagged"} {
+ repo := "amadan.net/oficina/" + name
+ if err := f.Create(ctx, repo); err != nil { // someone else's, before the call
+ t.Fatal(err)
+ }
+ if name == "tagged" {
+ seed := filepath.Join(t.TempDir(), "seed")
+ gitT(t, filepath.Dir(seed), "init", "-q", seed)
+ gitT(t, seed, "commit", "-q", "--allow-empty", "-m", "tagged")
+ gitT(t, seed, "push", "-q", f.path(repo), "HEAD:refs/tags/v1")
+ }
+ before := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)")
+ call := "toolu_adopt" + string(rune('0'+i))
+ if text, isErr := b.Call(ctx, "p", "t3", 1, wire.ToolCreateProject, call, json.RawMessage(`{"namespace":"oficina","name":"`+name+`"}`)); isErr {
+ t.Fatalf("adopt %s: %s", name, text)
+ }
+ if after := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)"); after != before {
+ t.Fatalf("%s changed on adoption: %q -> %q", name, before, after)
+ }
+ }
+ if f.creates != 2 {
+ t.Fatalf("adoption created repositories: %d creates", f.creates)
+ }
+}
+
+// A repository holding only tags is not empty: StartDefault leaves it.
+func TestStartDefaultLeavesTagsAlone(t *testing.T) {
+ f, c := startRig(t)
+ const repo = "amadan.net/oficina/tags"
+ ctx := context.Background()
+ if err := f.Create(ctx, repo); err != nil {
+ t.Fatal(err)
+ }
+ seed := filepath.Join(t.TempDir(), "seed")
+ gitT(t, filepath.Dir(seed), "init", "-q", seed)
+ gitT(t, seed, "commit", "-q", "--allow-empty", "-m", "tagged")
+ gitT(t, seed, "push", "-q", f.path(repo), "HEAD:refs/tags/v1")
+ if err := c.StartDefault(ctx, repo); err != nil {
+ t.Fatal(err)
+ }
+ if refs := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname)"); refs != "refs/tags/v1" {
+ t.Fatalf("refs: %q", refs)
+ }
+}
+
+// Another writer between the emptiness check and the push. A main of
+// theirs is never replaced and is the default. A branch of theirs that
+// does not start from main fails the start, every time it is retried;
+// main is withdrawn where the forge allows deleting it (git refuses to
+// delete the current branch, so both are tested).
+func TestStartDefaultConcurrentWriter(t *testing.T) {
+ for _, c := range []struct {
+ name, theirs string
+ deletable bool
+ }{{"their main", "main", false}, {"their branch", "trunk", false}, {"their branch, main withdrawn", "trunk", true}} {
+ t.Run(c.name, func(t *testing.T) {
+ f, clones := startRig(t)
+ const repo = "amadan.net/oficina/raced"
+ ctx := context.Background()
+ if err := f.Create(ctx, repo); err != nil {
+ t.Fatal(err)
+ }
+ if c.deletable {
+ gitT(t, f.path(repo), "config", "receive.denyDeleteCurrent", "false")
+ }
+ seed := filepath.Join(t.TempDir(), "seed")
+ gitT(t, filepath.Dir(seed), "init", "-q", "-b", c.theirs, seed)
+ os.WriteFile(filepath.Join(seed, "index.html"), []byte("theirs\n"), 0600)
+ gitT(t, seed, "add", "-A")
+ gitT(t, seed, "commit", "-q", "-m", "theirs")
+ tip := gitT(t, seed, "rev-parse", "HEAD")
+ old := startDefaultGap
+ t.Cleanup(func() { startDefaultGap = old })
+ startDefaultGap = func() { gitT(t, seed, "push", "-q", f.path(repo), c.theirs) }
+ err := clones.StartDefault(ctx, repo)
+ startDefaultGap = func() {}
+ again := clones.StartDefault(ctx, repo)
+ refs := gitT(t, f.path(repo), "for-each-ref", "--format=%(refname) %(objectname)")
+ theirs := "refs/heads/" + c.theirs + " " + tip
+ switch {
+ case c.theirs == "main":
+ if err != nil || again != nil || refs != theirs {
+ t.Fatalf("their main: %v / %v, refs %q", err, again, refs)
+ }
+ case c.deletable:
+ if err == nil || refs != theirs {
+ t.Fatalf("main left beside their branch: %v, refs %q", err, refs)
+ }
+ default:
+ if err == nil || again == nil || !strings.Contains(refs, theirs) {
+ t.Fatalf("a start beside their unrelated branch reported success: %v / %v, refs %q", err, again, refs)
+ }
+ }
+ })
+ }
+}
+
+// Create owns a repository only when the hub answered that it created
+// it. "Already exists", or an answer that never came while the
+// repository turns out to exist, is adopted and not this runner's.
+func TestFileForgeCreateOwnsOnlyWhatTheHubCreated(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ before bool // the repository exists before the request
+ status int // the hub's answer to the create; 0 drops it
+ afterward bool // it exists when asked again
+ want error
+ }{
+ {"created", false, http.StatusOK, true, nil},
+ {"exists already", true, 0, true, ErrAdopted},
+ {"another writer won", false, http.StatusConflict, true, ErrAdopted},
+ {"answer lost", false, 0, true, ErrAdopted},
+ {"refused", false, http.StatusForbidden, false, ErrNoCreate},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ exists, posts := c.before, 0
+ f := accessForge(t, func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos":
+ repos := `{"ns":"oficina","name":"other"}`
+ if exists {
+ repos += `,{"ns":"oficina","name":"site"}`
+ }
+ w.Write([]byte(`{"repos":[` + repos + `]}`))
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/repos":
+ posts++
+ exists = c.afterward
+ if c.status == 0 {
+ hj, _ := w.(http.Hijacker)
+ conn, _, _ := hj.Hijack()
+ conn.Close()
+ return
+ }
+ w.WriteHeader(c.status)
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ })
+ err := f.Create(context.Background(), "amadan.net/oficina/site")
+ if !errors.Is(err, c.want) || c.want == nil && err != nil {
+ t.Fatalf("Create = %v, want %v", err, c.want)
+ }
+ if c.before && posts != 0 {
+ t.Fatal("asked the hub to create a repository that exists")
+ }
+ })
+ }
+}
+
+// Another writer creates the repository between Exists and Create:
+// create_project adopts it and never starts main in it, then or on retry.
+func TestCreateProjectNeverStartsARepositoryItDidNotMake(t *testing.T) {
+ state, err := OpenState(context.Background(), t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer state.Close()
+ f, c := startRig(t)
+ lost := &adoptingForge{creatingForge: f}
+ b := &bridge{State: state, Forge: lost, Clones: c, speaks: wire.ProtocolCurrent, trip: func(_ context.Context, call wire.ToolCall) wire.ToolResult {
+ var in struct{ Repo string }
+ _ = json.Unmarshal(call.Args, &in)
+ if call.Name == wire.ToolCreateProject {
+ return wire.ToolResult{Code: "create", Repo: in.Repo}
+ }
+ return wire.ToolResult{Code: "created", Repo: in.Repo, Text: "Created."}
+ }}
+ args := json.RawMessage(`{"namespace":"oficina","name":"site"}`)
+ for range 2 {
+ if text, isErr := b.Call(context.Background(), "p", "t4", 1, wire.ToolCreateProject, "toolu_4", args); isErr {
+ t.Fatalf("adopt: %s", text)
+ }
+ if refs := gitT(t, f.path("amadan.net/oficina/site"), "for-each-ref"); refs != "" {
+ t.Fatalf("main started in someone else's repository: %q", refs)
+ }
+ }
+}
+
+// adoptingForge loses the race: the repository is made, by someone else.
+type adoptingForge struct{ *creatingForge }
+
+func (f *adoptingForge) Create(ctx context.Context, repo string) error {
+ if err := f.creatingForge.Create(ctx, repo); err != nil {
+ return err
+ }
+ return ErrAdopted
+}
+
+// An annotated tag on the start commit: ls-remote lists it peeled too
+// (refs/tags/v1^{}), and neither line is someone else's unrelated work.
+func TestStartDefaultAnnotatedTagOnMain(t *testing.T) {
+ f, c := startRig(t)
+ const repo = "amadan.net/oficina/tagged-main"
+ ctx := context.Background()
+ if err := f.Create(ctx, repo); err != nil {
+ t.Fatal(err)
+ }
+ if err := c.StartDefault(ctx, repo); err != nil {
+ t.Fatal(err)
+ }
+ main := gitT(t, f.path(repo), "rev-parse", "refs/heads/main")
+ gitT(t, f.path(repo), "tag", "-a", "-m", "first", "v1", main)
+ if err := c.StartDefault(ctx, repo); err != nil {
+ t.Fatalf("an annotated tag on main failed the start: %v", err)
+ }
+ if again := gitT(t, f.path(repo), "rev-parse", "refs/heads/main"); again != main {
+ t.Fatalf("main changed: %s -> %s", main, again)
+ }
+}
+
+// lsRefs keeps each ref once: HEAD and the peeled lines of annotated tags
+// (refs/tags/v1^{}) are not refs of their own.
+func TestLsRefsSkipsHeadAndPeeledTags(t *testing.T) {
+ a, b := strings.Repeat("a", 40), strings.Repeat("b", 40)
+ got := lsRefs(a + "\tHEAD\n" + a + "\trefs/heads/main\n" + b + "\trefs/tags/v1\n" + a + "\trefs/tags/v1^{}\n")
+ if len(got) != 2 || got["refs/heads/main"] != a || got["refs/tags/v1"] != b {
+ t.Fatalf("lsRefs = %v", got)
+ }
+}
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go
index 304b6de2..e215ddc2 100644
--- a/internal/runner/thin/state.go
+++ b/internal/runner/thin/state.go
@@ -303,7 +303,9 @@ type run struct {
}
// creation is how far a create_project call got: "" (not started),
-// "created" (the repository exists) or "done" (the instance has it).
+// "made" (the hub answered that this call created it, so it is ours to
+// start), "created" (the repository exists, started) or "done" (the
+// instance has it).
func (s *State) creation(ctx context.Context, callID, repo string) (string, error) {
var state, got string
err := s.db.QueryRowContext(ctx, "SELECT repo, state FROM creations WHERE call_id=?", callID).Scan(&got, &state)
diff --git a/internal/thintest/batching_contract_test.go b/internal/thintest/batching_contract_test.go
index ef5e7a36..3d6849fd 100644
--- a/internal/thintest/batching_contract_test.go
+++ b/internal/thintest/batching_contract_test.go
@@ -3,6 +3,7 @@ package thintest
import (
"context"
"fmt"
+ "strconv"
"strings"
"testing"
"time"
@@ -71,6 +72,14 @@ func (r *rig) turnIs(id, state string) wire.Turn {
// batchFrame expects the next message frame to be the batch: the three
// messages apart and in order, and nothing else.
func (r *rig) batchFrame(runner *FakeRunner, batch string, texts ...string) wire.Frame {
+ r.t.Helper()
+ return r.batchFrameCarrying(runner, batch, nil, texts...)
+}
+
+// batchFrameCarrying is batchFrame for a batch after failed turns: their
+// person's words (carried) come first in PersonText, marked unanswered
+// in Text before the batch.
+func (r *rig) batchFrameCarrying(runner *FakeRunner, batch string, carried []string, texts ...string) wire.Frame {
r.t.Helper()
ctx, cancel := context.WithTimeout(r.ctx, 10*time.Second)
defer cancel()
@@ -79,13 +88,20 @@ func (r *rig) batchFrame(runner *FakeRunner, batch string, texts ...string) wire
r.t.Fatalf("no next turn: %v", err)
}
cmd := body.(*wire.MessageCommand)
- if cmd.TurnID != batch || len(cmd.PersonText) != len(texts) {
+ if cmd.TurnID != batch || len(cmd.PersonText) != len(carried)+len(texts) {
r.t.Fatalf("next turn %s carries %q, not the batch %s", cmd.TurnID, cmd.PersonText, batch)
}
at := -1
+ for i, text := range carried {
+ n := strings.Index(cmd.Text, "Not yet answered, the person's words: "+strconv.Quote(text))
+ if n <= at || cmd.PersonText[i] != text {
+ r.t.Fatalf("batch lacks unanswered %q in place:\n%s", text, cmd.Text)
+ }
+ at = n
+ }
for i, text := range texts {
n := strings.Index(cmd.Text, "Message "+string(rune('1'+i))+" of "+string(rune('0'+len(texts)))+":\n"+text)
- if n <= at || cmd.PersonText[i] != text {
+ if n <= at || cmd.PersonText[len(carried)+i] != text {
r.t.Fatalf("batch lacks %q in place:\n%s", text, cmd.Text)
}
at = n
@@ -192,7 +208,7 @@ func TestBatchStrandedRecovers(t *testing.T) {
r.inst.Restart(t)
again := r.dial(runner.Welcome.Generation)
again.Send(r.ctx, "s1", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}})
- f := r.batchFrame(again, batch, "alpha", "bravo", "charlie")
+ f := r.batchFrameCarrying(again, batch, []string{"one"}, "alpha", "bravo", "charlie")
again.Send(r.ctx, "s2", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}})
again.Send(r.ctx, "ab", wire.FrameAck, wire.Ack{ID: f.ID})
r.turnIs(batch, wire.TurnRunning)
@@ -200,8 +216,9 @@ func TestBatchStrandedRecovers(t *testing.T) {
}
// However the running turn ends (failed, cancelled, or lost across a
-// runner reconnect), the batch goes next, once, and the failed turn's own
-// message is not answered again inside it.
+// runner reconnect), the batch goes next, once, and the ended turn keeps
+// its own message. A failed turn's words ride before the batch, marked
+// unanswered; a cancelled turn's do not (the person stopped it).
func TestBatchAfterTurnEnds(t *testing.T) {
for _, end := range []string{"failed", "cancelled", "interrupted"} {
t.Run(end, func(t *testing.T) {
@@ -226,7 +243,11 @@ func TestBatchAfterTurnEnds(t *testing.T) {
runner = r.dial(0)
runner.Send(r.ctx, "e1", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}})
}
- r.batchFrame(runner, batch, "alpha", "bravo", "charlie")
+ var carried []string
+ if end != "cancelled" {
+ carried = []string{"one"}
+ }
+ r.batchFrameCarrying(runner, batch, carried, "alpha", "bravo", "charlie")
if st, _ := r.client.Turn(r.ctx, busy.Turn.ID); !wire.Terminal(st.State) || len(st.MessageIDs) != 1 {
t.Fatalf("ended turn %+v", st)
}
diff --git a/internal/thintest/carried_contract_test.go b/internal/thintest/carried_contract_test.go
new file mode 100644
index 00000000..e0aa0c81
--- /dev/null
+++ b/internal/thintest/carried_contract_test.go
@@ -0,0 +1,138 @@
+package thintest
+
+import (
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Words a failed turn carries into the next (dispatch's unanswered):
+// only a plain message the coordinator never saw, and in the turn that
+// carries them they are the person's words for team_request too.
+
+// failTurn reports id failed at attempt 1 and waits for it to end.
+func (r *rig) failTurn(runner *FakeRunner, id string) {
+ r.t.Helper()
+ if err := runner.Send(r.ctx, "e-"+id, wire.FrameTurn, wire.TurnReport{TurnID: id, Attempt: 1, State: wire.TurnFailed, Reason: "policy_rejected"}); err != nil {
+ r.t.Fatal(err)
+ }
+ for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
+ var state string
+ if err := r.inst.DB.Writer().QueryRow("SELECT state FROM chat_turns WHERE id = ?", id).Scan(&state); err == nil && state == wire.TurnFailed {
+ return
+ }
+ }
+ r.t.Fatalf("turn %s did not fail", id)
+}
+
+// A turn that reached the model (a delta or a thinking or tool activity
+// was recorded for it) is not carried: its words may already be in a
+// resumed session's transcript. One that failed before is.
+func TestContractCarriedOnlyBeforeTheModel(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ turn := func(text, key string) (wire.Sent, *wire.MessageCommand) {
+ t.Helper()
+ sent, err := r.client.Send(r.ctx, text, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, body, err := runner.Expect(r.ctx, wire.FrameMessage)
+ if err != nil {
+ t.Fatal(err)
+ }
+ runner.Send(r.ctx, "a-"+key, wire.FrameAck, wire.Ack{ID: f.ID})
+ r.wait("running", func(c *Conversation) bool { return c.Turns[sent.Turn.ID].State == wire.TurnRunning })
+ return sent, body.(*wire.MessageCommand)
+ }
+ // Frames apply in order: each report lands before the failure after it.
+ streamed, _ := turn("streamed words", "k1")
+ runner.Send(r.ctx, "d1", wire.FrameDelta, wire.DeltaReport{TurnID: streamed.Turn.ID, Attempt: 1, Text: "Looking"})
+ r.failTurn(runner, streamed.Turn.ID)
+ thought, cmd := turn("thought words", "k2")
+ if slices.Contains(cmd.PersonText, "streamed words") {
+ t.Fatalf("a turn that streamed was carried %q", cmd.PersonText)
+ }
+ runner.Send(r.ctx, "t2", wire.FrameActivity, wire.ActivityReport{TurnID: thought.Turn.ID, Attempt: 1, Kind: wire.ActivityThink})
+ r.failTurn(runner, thought.Turn.ID)
+ early, cmd := turn("early words", "k3")
+ if len(cmd.PersonText) != 1 || strings.Contains(cmd.Text, "Not yet answered") {
+ t.Fatalf("a turn that reached the model was carried %q", cmd.PersonText)
+ }
+ r.failTurn(runner, early.Turn.ID)
+ last, cmd := turn("last", "k4")
+ if strings.Join(cmd.PersonText, "|") != "early words|last" {
+ t.Fatalf("a turn that failed before the model was not carried %q", cmd.PersonText)
+ }
+ // The turn that carried them reached the model: they are in its
+ // transcript now, and ride no further.
+ runner.Send(r.ctx, "d4", wire.FrameDelta, wire.DeltaReport{TurnID: last.Turn.ID, Attempt: 1, Text: "On it"})
+ r.failTurn(runner, last.Turn.ID)
+ if _, cmd = turn("final", "k5"); len(cmd.PersonText) != 1 {
+ t.Fatalf("carried past a turn that reached the model %q", cmd.PersonText)
+ }
+}
+
+// A typed answer to a card is not carried as a plain message: bare,
+// "the second one" means nothing without the question it answers.
+func TestContractCarriedSkipsCardAnswers(t *testing.T) {
+ r := newToolRig(t)
+ if res := r.call("q1", wire.ToolAskPerson, map[string]any{"question": "Which one do you mean?"}); res.Code != "asked" {
+ t.Fatalf("ask_person %+v", res)
+ }
+ r.runner.Send(r.ctx, "rep1", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Which day suits?"})
+ var card wire.Card
+ r.wait("question card", func(c *Conversation) bool {
+ for _, k := range c.Cards {
+ if k.Kind == wire.CardQuestion && k.State == wire.CardOpen {
+ card = k
+ return true
+ }
+ }
+ return false
+ })
+ answered, err := r.client.Answer(r.ctx, card.ID, "the second one", card.Revision)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, _, err := r.runner.Expect(r.ctx, wire.FrameMessage)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.runner.Send(r.ctx, "a-ans", wire.FrameAck, wire.Ack{ID: f.ID})
+ r.failTurn(r.runner, answered.Turn.ID)
+ if _, err = r.client.Send(r.ctx, "next", "k-next"); err != nil {
+ t.Fatal(err)
+ }
+ _, body, err := r.runner.Expect(r.ctx, wire.FrameMessage)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cmd := body.(*wire.MessageCommand); len(cmd.PersonText) != 1 || strings.Contains(cmd.Text, "Not yet answered") {
+ t.Fatalf("a card answer was carried bare %q %q", cmd.PersonText, cmd.Text)
+ }
+}
+
+// Words a failed Assistant turn left unanswered ride in the next turn,
+// and there team_request takes them as the person's: the hand-off is
+// their message, as written. Words from no message of theirs still are
+// not theirs.
+func TestContractCarriedWordsHandOver(t *testing.T) {
+ o := newTeamRig(t)
+ lost := o.ask("Can we fix a bug in Tito? Login is broken")
+ o.failTurn(o.runner, lost)
+ o.ask("Please continue")
+ if res := o.use("tr-not", "team_request", map[string]any{"words": "The checkout page is broken"}); !res.IsError || res.Code != "not_their_words" {
+ t.Fatalf("words from no message %+v", res)
+ }
+ request, cmd := o.handoff("tr1", "Login is broken", "")
+ if !strings.HasPrefix(cmd.Text, "Login is broken") {
+ t.Fatalf("thread frame %q", cmd.Text)
+ }
+ if thread := o.thread(request); len(thread) != 1 || thread[0].Text != "Login is broken" || thread[0].Role != wire.RolePerson {
+ t.Fatalf("thread %+v", thread)
+ }
+}
diff --git a/internal/thintest/instance_contract_test.go b/internal/thintest/instance_contract_test.go
index a26ba7dc..ca6505c4 100644
--- a/internal/thintest/instance_contract_test.go
+++ b/internal/thintest/instance_contract_test.go
@@ -4,9 +4,11 @@ import (
"amadan.net/oficina/equipo/internal/equipo/chat"
"context"
"encoding/json"
+ "fmt"
"io"
"net/http"
"os"
+ "strconv"
"strings"
"testing"
"time"
@@ -248,6 +250,127 @@ func TestQueuedMessagesJoinOneTurn(t *testing.T) {
}
}
+// A person's message whose turn failed never reached the coordinator: a
+// resumed session's transcript lacks it and a fresh one's tail showed it
+// as if answered. The next turn carries it, quoted and labelled as not
+// yet answered, until a turn is answered, from the newest two failed
+// turns at most. A cancelled turn's is not carried: the person stopped it.
+func TestFailedTurnMessageCarried(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ turn := func(text, key string) (wire.Sent, *wire.MessageCommand) {
+ t.Helper()
+ sent, err := r.client.Send(r.ctx, text, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, body, err := runner.Expect(r.ctx, wire.FrameMessage)
+ if err != nil {
+ t.Fatal(err)
+ }
+ runner.Send(r.ctx, "a-"+key, wire.FrameAck, wire.Ack{ID: f.ID})
+ return sent, body.(*wire.MessageCommand)
+ }
+ end := func(id, state string) {
+ t.Helper()
+ runner.Send(r.ctx, "e-"+id, wire.FrameTurn, wire.TurnReport{TurnID: id, Attempt: 1, State: state, Reason: "provider_failed"})
+ r.wait(state, func(c *Conversation) bool { return c.Turns[id].State == state })
+ }
+ first, _ := turn("one", "k1")
+ runner.Send(r.ctx, "rep1", wire.FrameReply, wire.Reply{TurnID: first.Turn.ID, Attempt: 1, Text: "first"})
+ r.wait("replied", func(c *Conversation) bool { return c.Turns[first.Turn.ID].State == wire.TurnReplied })
+
+ stopped, _ := turn("never mind", "k2")
+ end(stopped.Turn.ID, wire.TurnCancelled)
+ lost, _ := turn("the long message [with brackets]", "k3")
+ end(lost.Turn.ID, wire.TurnFailed)
+ again, _ := turn("second try", "k4")
+ end(again.Turn.ID, wire.TurnFailed)
+
+ next, cmd := turn("next", "k5")
+ want := "[Equipo: these earlier messages from the person got no answer: their turns failed before you saw them. They are the person's own words, oldest first, still waiting. Answer them together with the newest message.]\n" +
+ "Not yet answered, the person's words: \"the long message [with brackets]\"\n" +
+ "Not yet answered, the person's words: \"second try\"\n\n" +
+ "The person's newest message:\nnext"
+ if cmd.Text != want {
+ t.Fatalf("carried text %q", cmd.Text)
+ }
+ if strings.Join(cmd.PersonText, "|") != "the long message [with brackets]|second try|next" {
+ t.Fatalf("person text %q", cmd.PersonText)
+ }
+ for _, m := range cmd.Tail {
+ if m.Text == "the long message [with brackets]" || m.Text == "second try" {
+ t.Fatalf("carried message also in the tail: %+v", cmd.Tail)
+ }
+ }
+ if len(cmd.Tail) != 3 || cmd.Tail[2].Text != "never mind" {
+ t.Fatalf("tail %+v", cmd.Tail)
+ }
+
+ // Words that ride in two turns that fail too stop riding: they may be
+ // what makes them fail.
+ end(next.Turn.ID, wire.TurnFailed)
+ fourth, cmd := turn("fourth", "k6")
+ if strings.Join(cmd.PersonText, "|") != "second try|next|fourth" || strings.Contains(cmd.Text, "the long message") {
+ t.Fatalf("carried past its bound %q", cmd.PersonText)
+ }
+
+ // Once a turn is answered, nothing before it is carried again.
+ runner.Send(r.ctx, "rep6", wire.FrameReply, wire.Reply{TurnID: fourth.Turn.ID, Attempt: 1, Text: "answered"})
+ r.wait("replied", func(c *Conversation) bool { return c.Turns[fourth.Turn.ID].State == wire.TurnReplied })
+ _, cmd = turn("after", "k7")
+ if cmd.Text != "after" || len(cmd.PersonText) != 1 {
+ t.Fatalf("carried after an answer %q %q", cmd.Text, cmd.PersonText)
+ }
+}
+
+// Carried messages that would make the frame too big for a runner give
+// way, oldest first: the newest unanswered words still go. Two failed
+// batches, each as big as a batch gets, cannot both ride with a third.
+func TestFailedTurnMessagesFitOneFrame(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ big := func(i int) string { return fmt.Sprintf("%02d", i) + strings.Repeat("x", wire.MaxMessageBytes-2) }
+ first, err := r.client.Send(r.ctx, "a", "k-a")
+ if err != nil {
+ t.Fatal(err)
+ }
+ turns := []string{first.Turn.ID}
+ for i := range 10 {
+ sent, err := r.client.Send(r.ctx, big(i), "k"+strconv.Itoa(i))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if turns[len(turns)-1] != sent.Turn.ID {
+ turns = append(turns, sent.Turn.ID)
+ }
+ }
+ if len(turns) != 3 {
+ t.Fatalf("batches %v", turns)
+ }
+ var cmd *wire.MessageCommand
+ for i, id := range turns {
+ f, body, err := runner.Expect(r.ctx, wire.FrameMessage)
+ if err != nil {
+ t.Fatal(err)
+ }
+ runner.Send(r.ctx, "a-"+id, wire.FrameAck, wire.Ack{ID: f.ID})
+ if cmd = body.(*wire.MessageCommand); cmd.TurnID != id {
+ t.Fatalf("turn %s, want %s", cmd.TurnID, id)
+ }
+ if i < 2 {
+ runner.Send(r.ctx, "e-"+id, wire.FrameTurn, wire.TurnReport{TurnID: id, Attempt: 1, State: wire.TurnFailed, Reason: "provider_failed"})
+ }
+ }
+ if raw, _ := json.Marshal(cmd); len(raw) > wire.MaxFrameBytes-1<<10 {
+ t.Fatalf("frame %d bytes", len(raw))
+ }
+ n := len(cmd.PersonText)
+ if n < 6 || n >= 11 || cmd.PersonText[0] == "a" || cmd.PersonText[n-6] != big(4) || cmd.PersonText[n-1] != big(9) {
+ t.Fatalf("carried %d messages", n)
+ }
+}
+
func TestCancel(t *testing.T) {
r := newRig(t)
runner := r.dial(0)
diff --git a/internal/thintest/thinking_browser_test.go b/internal/thintest/thinking_browser_test.go
index ff921bfc..8ea337d5 100644
--- a/internal/thintest/thinking_browser_test.go
+++ b/internal/thintest/thinking_browser_test.go
@@ -7,6 +7,7 @@ import (
"encoding/json"
"fmt"
"testing"
+ "time"
"amadan.net/oficina/equipo/internal/wire"
"github.com/chromedp/cdproto/cdp"
@@ -97,7 +98,8 @@ func TestBrowserThinkingWords(t *testing.T) {
// phrases come from a shuffled deck, none again until all have shown,
// across two turns (a reload keeps only localStorage); after the deck runs
// out the next is none of the last three; a tool shows its plain label
-// at once; under reduced motion the thinking words still change.
+// once the phrase before has had its 1.5 s; under reduced motion the
+// thinking words still change.
//
// The page's clock stands still but for the test (clock below): each
// phrase is held to just under its minimum while the phrase timer looks,
@@ -217,11 +219,11 @@ func TestBrowserThinkingCycles(t *testing.T) {
}
}
dwelt(from)
- // A tool activity: its plain label at once.
+ // A tool activity: its plain label, after the phrase's dwell.
if err := r.runner.Send(r.ctx, "cyc-read-"+motion, wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: wire.ActivityTool, Tool: wire.ToolReadFile}); err != nil {
t.Fatal(err)
}
- p.wait(phrase+`==='Reading the code…'`, "a plain reading label at once")
+ p.wait(phrase+`==='Reading the code…'`, "a plain reading label after the dwell")
if motion == "reduce" {
p.check(`getComputedStyle(document.querySelector('[equipo-sparkle] path')).animationName==='none'`, "the mark moves under reduced motion")
}
@@ -231,3 +233,105 @@ func TestBrowserThinkingCycles(t *testing.T) {
}
}
}
+
+// TestBrowserThinkingSteady: Paul on staging, 2026-11-20: "When it was
+// responding, the thinking kept flashing quite quickly." A turn's first
+// moments bring a burst: thinking, the runner's tool label and then the
+// instance's named one, and cards whose refreshes re-rendered the feed.
+// Every activity drew a phrase at once over the ones still fading, and
+// each refresh took the line out and put it back, so every fading phrase
+// started its animation again on top of the new one. Now each phrase
+// stays at least 1.5 s and the latest waiting one follows, one phrase
+// shows at a time, a refresh leaves the line where it is, and the timer
+// counts the whole turn.
+func TestBrowserThinkingSteady(t *testing.T) {
+ r := newToolRig(t)
+ if err := r.runner.Send(r.ctx, "r-first", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "First."}); err != nil {
+ t.Fatal(err)
+ }
+ r.wait("replied", func(c *Conversation) bool { return c.Turns[r.turn].State == wire.TurnReplied })
+ // The page's record: each phrase drawn, the most phrases visible at
+ // once (letters a new phrase keeps from the old one are the old
+ // ones'), how often a phrase's animation started again, and the timer
+ // each frame.
+ const watch = `(()=>{window.__drawn=[];window.__most=0;window.__again=0;window.__timer=[];const once=new WeakSet(),began=new WeakMap();` +
+ `new MutationObserver(()=>{for(const e of document.querySelectorAll('[equipo-phrase] > [data-in]'))if(!once.has(e)&&once.add(e))__drawn.push({text:e.textContent,at:performance.now()})}).observe(document,{childList:true,subtree:true});` +
+ `const frame=()=>{const layers=[...document.querySelectorAll('[equipo-phrase] > [data-in], [equipo-phrase] > [data-out]')];__most=Math.max(__most,layers.filter(l=>[...l.children].some(c=>{const s=getComputedStyle(c);return !c.hasAttribute('data-keep')&&s.visibility!=='hidden'&&Number(s.opacity)>.1})).length);` +
+ `for(const l of layers){const w=l.firstElementChild?.getAnimations().find(a=>a.animationName==='equipo-wave');if(!w||w.startTime===null)continue;if(!began.has(l))began.set(l,w.startTime);else if(began.get(l)!==w.startTime){began.set(l,w.startTime);__again++}}` +
+ `const e=document.querySelector('[equipo-elapsed]');if(e&&e.textContent)__timer.push(parseInt(e.textContent));requestAnimationFrame(frame)};requestAnimationFrame(frame)})()`
+ p := openInner(t, r.inst.URL, r.inst.Cookie(), 1280, 900, false, "light", "no-preference")
+ defer p.stop()
+ p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
+ _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: watch})
+ return err
+ }))
+ p.open("/conversation")
+ p.wait(`document.querySelector('#composer textarea')`, "the composer")
+ sent := time.Now()
+ p.check(`(()=>{const box=document.querySelector('#composer textarea');box.value='Fix the swipe';box.dispatchEvent(new Event('input'));document.querySelector('#composer').requestSubmit();return true})()`, "send")
+ f, body, err := r.runner.Expect(r.ctx, wire.FrameMessage)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := r.runner.Send(r.ctx, "a-fix", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil {
+ t.Fatal(err)
+ }
+ r.turn = body.(*wire.MessageCommand).TurnID
+ p.wait(`document.querySelector('[equipo-thinking][data-turn=`+jsString(r.turn)+`]')`, "the turn's line")
+ act := func(id, kind, tool string) {
+ t.Helper()
+ if err := r.runner.Send(r.ctx, id, wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: kind, Tool: tool}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ from := eval[int](p, `__drawn.length`)
+ burst := time.Now()
+ act("s1", wire.ActivityThink, "")
+ act("s2", wire.ActivityTool, wire.ToolRecordTask)
+ task := taskID(t, r.call("s-rec", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Swipe back", "brief": "x"}))
+ act("s3", wire.ActivityThink, "")
+ act("s4", wire.ActivityTool, wire.ToolStartTask)
+ r.call("s-start", wire.ToolStartTask, map[string]string{"task": task, "brief": "go"})
+ r.expect(wire.FrameDispatch)
+ act("s5", wire.ActivityThink, "")
+ took := time.Since(burst)
+ words, _ := r.client.Thinking(r.ctx)
+ var think []string
+ for _, s := range words.Sets {
+ if s.ID == wire.DefaultThinking {
+ think = s.Phrases["think"]
+ }
+ }
+ thinks, _ := json.Marshal(think)
+ line := `document.querySelector('[equipo-thinking][data-turn=` + jsString(r.turn) + `]')`
+ p.wait(line+`?.querySelector('[equipo-activity]').textContent==='Thinking' && document.querySelector('[data-card]')`, "the latest activity for screen readers, and the task's card")
+ // The latest waiting phrase comes once the one before has had its time.
+ p.wait(`(()=>{const d=__drawn.slice(`+fmt.Sprint(from)+`);return d.length>0 && performance.now()-d[d.length-1].at>1700 && `+string(thinks)+`.includes(d[d.length-1].text)})()`, "the burst settles on a thinking phrase")
+ drawn := eval[[]map[string]any](p, `__drawn.slice(`+fmt.Sprint(from)+`)`)
+ if most := 2 + int(took/(1500*time.Millisecond)); len(drawn) > most {
+ t.Fatalf("%d phrases for a burst of %s, want at most %d: %v", len(drawn), took, most, drawn)
+ }
+ all := eval[[]map[string]any](p, `__drawn`)
+ for i := 1; i < len(all); i++ {
+ if gap := all[i]["at"].(float64) - all[i-1]["at"].(float64); gap < 1450 {
+ t.Fatalf("%q came %.0f ms after %q: %v", all[i]["text"], gap, all[i-1]["text"], all)
+ }
+ }
+ if most := eval[int](p, `__most`); most > 1 {
+ t.Fatalf("%d phrases visible at once", most)
+ }
+ if again := eval[int](p, `__again`); again > 0 {
+ t.Fatalf("a phrase's animation started again %d times while the turn ran", again)
+ }
+ timer := eval[[]int](p, `__timer`)
+ for i := 1; i < len(timer); i++ {
+ if timer[i] < timer[i-1] {
+ t.Fatalf("the timer went from %ds to %ds", timer[i-1], timer[i])
+ }
+ }
+ // It shows whole seconds, a tick a second: up to two behind.
+ if got, since := timer[len(timer)-1], time.Since(sent); got < int(since.Seconds())-2 {
+ t.Fatalf("the timer shows %ds, %s after the send", got, since)
+ }
+ p.stayed("the burst")
+}
diff --git a/internal/thintest/track_pulse_browser_test.go b/internal/thintest/track_pulse_browser_test.go
new file mode 100644
index 00000000..fbc4bc74
--- /dev/null
+++ b/internal/thintest/track_pulse_browser_test.go
@@ -0,0 +1,143 @@
+//go:build browser
+
+package thintest
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "github.com/chromedp/chromedp"
+)
+
+// TestBrowserTrackPulse: the stage track's current stop pulses while a
+// specialist works on it, on the conversation's report card and on the
+// task page, and is still while the task waits or nothing runs. Reduced
+// motion keeps a still ring. A step starting and stopping starts and
+// stops the pulse live, with no reload.
+func TestBrowserTrackPulse(t *testing.T) {
+ g := newGallery(t)
+ a := g.a
+ report := func(id string) string {
+ return `document.querySelector('[equipo-roster-report] [data-track-task="` + id + `"]')`
+ }
+ cur := func(track string) string { return track + `?.querySelector('[aria-current="step"]')` }
+ ring := func(track string) string {
+ return `getComputedStyle(` + cur(track) + `.querySelector('[equipo-dot]'),'::before')`
+ }
+ cue := func(track string) string {
+ return `getComputedStyle(` + cur(track) + `.querySelector('[data-working-cue]')).display`
+ }
+ for _, motion := range []string{"no-preference", "reduce"} {
+ for _, scheme := range []string{"light", "dark"} {
+ t.Run(motion+"-"+scheme, func(t *testing.T) {
+ p := openInner(t, a.inst.URL, a.inst.Cookie(), 1280, 900, false, scheme, motion)
+ defer p.stop()
+ p.open("/conversation")
+ run := report(g.running)
+ p.wait(cur(run), "the running task's report")
+ p.check(cur(run)+`.hasAttribute('data-working') && `+cue(run)+`!=='none'`, "the running stop is not working")
+ p.check(`(()=>{const w=[...document.querySelectorAll('[equipo-roster-report] [data-track] [data-working]')];return w.length>0 && w.every(li=>li.matches('[aria-current="step"]') && ['`+g.running+`','`+g.merging+`'].includes(li.parentElement.dataset.trackTask))})()`, "a stop with nobody at work pulses")
+ p.check(`[...document.querySelectorAll('[equipo-roster-report] [data-track] [aria-current="step"]:not([data-working])')].every(li=>getComputedStyle(li.querySelector('[equipo-dot]'),'::before').content==='none' && getComputedStyle(li.querySelector('[data-working-cue]')).display==='none')`, "an idle stop draws the ring or the cue")
+ if motion == "reduce" {
+ p.check(ring(run)+`.animationName==='none' && `+ring(run)+`.opacity==='0.6' && `+ring(run)+`.transform!=='none'`, "reduced motion lost the still ring")
+ p.check(`getComputedStyle(`+cur(run)+`.previousElementSibling,'::before').animationName==='none'`, "the line moves under reduced motion")
+ } else {
+ p.check(ring(run)+`.animationName==='equipo-tl-ring' && `+ring(run)+`.animationDuration==='2.4s'`, "the working stop does not pulse")
+ p.check(`getComputedStyle(`+cur(run)+`.previousElementSibling,'::before').animationName==='equipo-tl-flow'`, "the line into the working stop is still")
+ p.check(`document.getAnimations().filter(x=>x.animationName==='equipo-tl-ring').every(x=>x.startTime===0)`, "pulses out of phase")
+ }
+ // The task page's track: the living mark, and the ring.
+ p.open("/tasks/" + g.running)
+ full := `document.querySelector('[equipo-track-full]')`
+ p.check(cur(full)+`.hasAttribute('data-working') && !!`+cur(full)+`.querySelector('[equipo-mark]') && `+cue(full)+`!=='none'`, "the task page's stop is not working")
+ if motion == "reduce" {
+ p.check(ring(full)+`.animationName==='none' && `+ring(full)+`.opacity==='0.6'`, "task page: reduced motion lost the still ring")
+ } else {
+ p.check(ring(full)+`.animationName==='equipo-tl-ring'`, "task page: the working stop does not pulse")
+ }
+
+ })
+ }
+ }
+
+ // Live, light and dark side by side: a new task's step queues, runs
+ // and stops, and its card's pulse follows with no reload.
+ pages := map[string]*innerPage{}
+ for _, scheme := range []string{"light", "dark"} {
+ p := openInner(t, a.inst.URL, a.inst.Cookie(), 1280, 900, false, scheme, "no-preference")
+ defer p.stop()
+ pages[scheme] = p
+ }
+ each := func(f func(scheme string, p *innerPage)) {
+ for _, scheme := range []string{"light", "dark"} {
+ f(scheme, pages[scheme])
+ }
+ }
+ task := taskID(t, a.call("tp-rec", wire.ToolRecordTask, map[string]any{"repo": "oficina/equipo", "title": "Keep the filter when the list refreshes", "brief": "The task filter resets when the list refreshes itself.", "separate": true}))
+ track := report(task)
+ card := `[data-card]:has([data-track-task="` + task + `"])`
+ show := `(()=>{` + cur(track) + `.closest('[data-card]').scrollIntoView({block:'center'});return true})()`
+ each(func(_ string, p *innerPage) {
+ p.open("/conversation")
+ p.wait(cur(track), "the new task's report")
+ p.check(`!`+cur(track)+`.hasAttribute('data-working') && `+ring(track)+`.content==='none'`, "a noted task pulses")
+ })
+ a.call("tp-start", wire.ToolStartTask, map[string]string{"task": task, "brief": "Keep the filter."})
+ _, body := a.expect(wire.FrameDispatch)
+ d := body.(*wire.DispatchCommand)
+ each(func(_ string, p *innerPage) {
+ p.wait(cur(track)+`?.hasAttribute('data-working')`, "the queued step's pulse")
+ })
+ a.step("tp-run", wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: strings.Repeat("8", 40), Family: "claude", Account: "claude-a"})
+ each(func(scheme string, p *innerPage) {
+ p.wait(cur(track)+`?.hasAttribute('data-working') && `+cur(track)+`.textContent.startsWith('In progress')`, "the running step's pulse")
+ p.check(ring(track)+`.animationName==='equipo-tl-ring'`, "the running card does not pulse")
+ p.check(show, "show the card")
+ p.cardShot(card, "track-pulse-running-"+scheme)
+ })
+ a.step("tp-fail", wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true})
+ each(func(scheme string, p *innerPage) {
+ p.wait(cur(track)+` && !`+cur(track)+`.hasAttribute('data-working') && `+ring(track)+`.content==='none' && `+cue(track)+`==='none'`, "the pulse stopped")
+ p.stayed("conversation")
+ p.check(show, "show the card")
+ p.cardShot(card, "track-pulse-idle-"+scheme)
+ })
+}
+
+// cardShot saves the element sel at twice its size when
+// EQUIPO_BROWSER_ARTIFACTS names a directory.
+func (p *innerPage) cardShot(sel, name string) {
+ p.t.Helper()
+ dir := os.Getenv("EQUIPO_BROWSER_ARTIFACTS")
+ if dir == "" {
+ return
+ }
+ // A live refresh may swap the card mid-capture: settle, then retry.
+ var buf []byte
+ var err error
+ for try := 0; try < 4; try++ {
+ time.Sleep(700 * time.Millisecond)
+ err = chromedp.Do(p.ctx, chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
+ var err error
+ buf, err = chromedp.ScreenshotScale(chromedp.CSS(sel), 2)(ctx, target)
+ return err
+ }))
+ if err == nil {
+ break
+ }
+ }
+ if err != nil {
+ p.t.Fatal(err)
+ }
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ p.t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, name+".png"), buf, 0600); err != nil {
+ p.t.Fatal(err)
+ }
+}
diff --git a/scripts/staging-thin.py b/scripts/staging-thin.py
index 89d32152..b5b03b69 100755
--- a/scripts/staging-thin.py
+++ b/scripts/staging-thin.py
@@ -585,7 +585,11 @@ def suite_run(only, run_id, token):
# real bug in a repository the agent reaches; the step pushes
# its own branch and nothing merges.
EQUIPO_STAGING_WITNESS=os.environ.get('EQUIPO_STAGING_WITNESS', 'Bug in oficina/equipo: README.md never links to the API reference, so device developers cannot find it. Add one line to the README pointing to docs/api/equipo-v1.md. Change only README.md.'),
- EQUIPO_STAGING_CRASH_WITNESS=os.environ.get('EQUIPO_STAGING_CRASH_WITNESS', ''),
+ # The step crash and the step cancel each ask for their own
+ # small, true change, so no two of a run's tasks read alike
+ # (similar tasks are combined). The cancelled one never pushes.
+ EQUIPO_STAGING_CRASH_WITNESS=os.environ.get('EQUIPO_STAGING_CRASH_WITNESS', 'Bug in oficina/equipo: docs/plan-3-acceptance.md has no title; its first line is the copy marker. Add the line "# Plan 3 acceptance" above that marker and keep the marker as it is. Change only docs/plan-3-acceptance.md.'),
+ EQUIPO_STAGING_CANCEL_WITNESS=os.environ.get('EQUIPO_STAGING_CANCEL_WITNESS', 'Bug in oficina/equipo: docs/mac-runner.md has no list of its sections, so a person cannot see the steps and the troubleshooting at a glance. Add a short list of its three section headings after the opening paragraphs. Change only docs/mac-runner.md.'),
# Slice 4: tasks already pushed that the upgrade judges (no
# new message), and what the person says in the live review
# and checks scenario.