oficina / equipo Public

Mac slice F task 13: ask the implementer, pinned exactly

A question about an Engineering step is frozen when it is made to the
attempt, account, kept session, runner, base and candidate it is about
(chat_questions, migration 0120). Dispatch, cancel, replies and a
reconnect's sync use the frozen values, never the step as it stands.
The step stores the kept session id an Askable Engineering report names
(a plain id only); the Linux primary now reports it too.

The runner binds a pinned question to exactly that attempt's kept
session (keptForAsk); a different account or session is refused. A Mac
worker now answers asks (Worker.ask, wired in runWorker). It needs the
whole pinning and the store's candidate ref. It runs in the Mac's OpAsk
turn, with the darwin read-only answer settings, a fresh tree of the
candidate, and git_log, git_diff and git_show over its store. The answer
and its stream are redacted of known secrets across chunks.

The worker's owners include its enrolled person, as on the primary, so
a Mac started before its first connection takes Engineering and asks.

Tests first: TestContractAskBindsTheSession,
TestContractQuestionLifecycleFrozen, TestContractAskMacOffline,
TestWorkerAskAnswersFromKeptSession, TestWorkerAskRefusesMismatch,
TestWorkerAskCannotWrite, TestWorkerAskRedactsKnownSecrets,
TestWorkerRunAnswersAsks, TestKeptSessionID, plus headless 4b_ask's pin.
27 mutations, 26 killed by named tests; see the task 13 report.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev b3eebcc6dcc2c242ad3e27a620a7d15884d01e81 parent 9dab991
18 files changed, +1,046 −45
  • .rastrillo/budgets.txt +4 −4
  • internal/equipo/chat/questions.go +56 −15
  • internal/equipo/chat/questions_pin_test.go +26 −0
  • internal/equipo/chat/tasks.go +8 −1
  • internal/fakeclaude/fake.go +5 −5
  • internal/headless/ask_test.go +5 −0
  • internal/headless/env_test.go +17 −0
  • internal/runner/thin/ask.go +30 −3
  • internal/runner/thin/ask_test.go +74 −0
  • internal/runner/thin/askmetered.go +1 −1
  • internal/runner/thin/engineer.go +5 −0
  • internal/runner/thin/maccreds_test.go +1 −0
  • internal/runner/thin/pistep.go +2 −2
  • internal/runner/thin/run.go +7 −3
  • internal/runner/thin/worker_ask.go +242 −0
  • internal/runner/thin/worker_ask_test.go +281 −0
  • internal/runner/thin/worker_launch.go +28 −11
  • internal/thintest/mac_ask_contract_test.go +254 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 8ee440b0..545146f6 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -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 33402 30015 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials, worker conns, worker Engineering; measured 33402/30015.
+size internal/runner/thin 33697 30371 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials, worker conns, Engineering and asks; measured 33697/30371.
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 45s Real processes killed and proven gone: groups, sessions, the runner-user sweep, turns, restarts; probes end to end. Measured 29.3s locally.
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 39212 12096 File facts/diffs, previews, merge authority, unfinished work, CI feedback, notification receipts, Assistant files, places, waiting cards, Mac waits, Mac Engineering, Mac conns; measured 39212/12096.
+size internal/equipo/chat 39260 12122 File facts/diffs, previews, merge authority, unfinished work, CI feedback, notification receipts, Assistant files, places, waiting cards, Mac waits, Engineering, conns, asks; measured 39260/12122.
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 - 11977 Grant scenarios (#48); sign-in email at 1280 and 390; Assistant files end to end; the restart wait; the live site waits for a place; a card answer settles at the bottom; measured 11977 test lines.
-size internal/thintest - 39628 Protocol 31 contracts, 35 diffs, stuck tasks, no-access merges, held retries, unfinished work, free rounds, previews, Assistant files, places, Mac waits, Mac Engineering, Mac conns; measured 39628.
+size internal/headless - 11999 Grant scenarios (#48); sign-in email at 1280 and 390; Assistant files end to end; the restart wait; the live site waits for a place; a card answer settles at the bottom; measured 11999 test lines.
+size internal/thintest - 39882 Protocol 31 contracts, 35 diffs, stuck tasks, no-access merges, held retries, unfinished work, free rounds, previews, Assistant files, places, Mac waits, Mac Engineering, conns, asks; measured 39882.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage.
diff --git a/internal/equipo/chat/questions.go b/internal/equipo/chat/questions.go
index 99758528..96ab288e 100644
--- a/internal/equipo/chat/questions.go
+++ b/internal/equipo/chat/questions.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "regexp"
"strings"
"time"
"unicode/utf8"
@@ -43,10 +44,11 @@ type questionRecord struct {
Revision int64
CreatedAt time.Time
UpdatedAt time.Time
- // The Engineering attempt, account binding, kept session and runner
- // an Engineering question is pinned to, with the pair it is about,
- // frozen when the question is created (migration 0120; set from plan
- // task 13). Zero on every question made before.
+ // The runner a question is asked of and the pair it is about, and for
+ // an Engineering question the attempt, account binding and kept
+ // session it resumes: frozen when the question is created (migration
+ // 0120, Mac runners slice F), never moved with its step. Zero on every
+ // question made before; those read the step (questionRunner).
EngAttempt int64
EngAccount string
EngSession string
@@ -193,7 +195,13 @@ func (s *Store) Ask(ctx context.Context, person, taskID string, in wire.AskQuest
return ErrInvalid
}
now := t.now()
- q := questionRecord{ID: newID("q_"), TaskID: k.ID, Asker: person, IdempotencyKey: in.IdempotencyKey, StepID: target.ID, Specialist: target.Specialist, Chosen: in.Specialist, Text: text, State: wire.QuestionQueued, Attempt: 1, Revision: 1, CreatedAt: now, UpdatedAt: now}
+ q := questionRecord{ID: newID("q_"), TaskID: k.ID, Asker: person, IdempotencyKey: in.IdempotencyKey, StepID: target.ID, Specialist: target.Specialist, Chosen: in.Specialist, Text: text, State: wire.QuestionQueued, Attempt: 1, Revision: 1, CreatedAt: now, UpdatedAt: now,
+ RunnerID: target.RunnerID, BaseSHA: askBase(k, target), CandidateSHA: target.CandidateSHA}
+ if target.Specialist == wire.SpecialistEngineering {
+ // Exactly the attempt asked about: its account and the session
+ // it kept, whatever the step does after.
+ q.EngAttempt, q.EngAccount, q.EngSession = target.Attempt, target.Account, target.SessionID
+ }
if err := t.db.Create(&q).Error; err != nil {
return err
}
@@ -241,19 +249,52 @@ func (t *txn) nextQuestion(k taskRecord) error {
if err := t.db.Where("id = ?", k.ProjectID).First(&p).Error; err != nil {
return err
}
- base := k.BaseSHA
- if s.BaseSHA != "" && s.Specialist == wire.SpecialistEngineering {
- base = s.BaseSHA
+ base, candidate := q.BaseSHA, q.CandidateSHA
+ if q.RunnerID == "" {
+ // Asked before questions were frozen: the step as it stands.
+ base, candidate = askBase(k, s), s.CandidateSHA
}
- cmd := wire.AskCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, QuestionID: q.ID, Attempt: q.Attempt, Specialist: s.Specialist, Repo: p.Repo, Branch: k.Branch, BaseSHA: base, CandidateSHA: s.CandidateSHA, Title: k.Title, Text: q.Text}
- // Asked of the runner that holds the step's session, never another.
- if err := t.commandTo(s.RunnerID, s.Person, wire.FrameAsk, cmd); err != nil {
+ cmd := wire.AskCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, QuestionID: q.ID, Attempt: q.Attempt, Specialist: s.Specialist, Repo: p.Repo, Branch: k.Branch, BaseSHA: base, CandidateSHA: candidate, Title: k.Title, Text: q.Text,
+ EngAttempt: q.EngAttempt, EngAccount: q.EngAccount, EngSession: q.EngSession}
+ // Asked of the runner that holds the session, never another.
+ if err := t.commandTo(questionRunner(q, s), s.Person, wire.FrameAsk, cmd); err != nil {
return err
}
q.Dispatched = true
return t.saveQuestion(&q)
}
+// askBase is the commit a question's change starts from: an Engineering
+// step's own base, else the task's.
+func askBase(k taskRecord, s stepRecord) string {
+ if s.BaseSHA != "" && s.Specialist == wire.SpecialistEngineering {
+ return s.BaseSHA
+ }
+ return k.BaseSHA
+}
+
+// sessionIDPattern is a kept session's id as a runner names it: a Claude
+// UUID, a Pi or OpenCode session id.
+var sessionIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`)
+
+// keptSessionID is the kept session id a runner reported, as stored: a
+// plain id, else none.
+func keptSessionID(id string) string {
+ if !sessionIDPattern.MatchString(id) {
+ return ""
+ }
+ return id
+}
+
+// questionRunner is the runner a question is asked of: the one frozen
+// when it was created, or the step's for a question made before.
+func questionRunner(q questionRecord, s stepRecord) string {
+ if q.RunnerID != "" {
+ return q.RunnerID
+ }
+ return s.RunnerID
+}
+
// Question reads one question.
func (s *Store) Question(ctx context.Context, person, id string) (out wire.Question, err error) {
err = s.read(ctx, func(tx *gorm.DB) error {
@@ -309,7 +350,7 @@ func (t *txn) stopQuestion(q *questionRecord, reason string) error {
if err := t.db.Where("id = ?", q.StepID).First(&s).Error; err != nil {
return err
}
- return t.commandTo(s.RunnerID, s.Person, wire.FrameCancelAsk, wire.CancelAskCommand{Person: s.Person, TaskID: q.TaskID, QuestionID: q.ID, Attempt: q.Attempt})
+ return t.commandTo(questionRunner(*q, s), s.Person, wire.FrameCancelAsk, wire.CancelAskCommand{Person: s.Person, TaskID: q.TaskID, QuestionID: q.ID, Attempt: q.Attempt})
}
// ownQuestion loads a question for a runner frame: only the step's
@@ -328,8 +369,8 @@ func (t *txn) ownQuestion(l Lease, id string) (questionRecord, error) {
if s.Person != l.Runner.Person {
return q, ErrNotFound
}
- // Only the runner that holds the step's session answers for it.
- if s.RunnerID != l.Runner.RunnerID {
+ // Only the runner that holds the question's session answers for it.
+ if questionRunner(q, s) != l.Runner.RunnerID {
return q, ErrRefused
}
return q, nil
@@ -507,7 +548,7 @@ func (t *txn) syncQuestions(l Lease, held []wire.AskRun) error {
if err := t.db.Where("id = ?", q.StepID).First(&s).Error; err != nil {
return err
}
- if s.Person != l.Runner.Person || s.RunnerID != l.Runner.RunnerID {
+ if s.Person != l.Runner.Person || questionRunner(q, s) != l.Runner.RunnerID {
continue
}
var unacked int64
diff --git a/internal/equipo/chat/questions_pin_test.go b/internal/equipo/chat/questions_pin_test.go
new file mode 100644
index 00000000..d9983995
--- /dev/null
+++ b/internal/equipo/chat/questions_pin_test.go
@@ -0,0 +1,26 @@
+package chat
+
+import (
+ "strings"
+ "testing"
+)
+
+// The kept session id a runner reports is stored only as a plain id: a
+// Claude UUID, a Pi or OpenCode session id; anything else (a path, a
+// line, something long) is no session.
+func TestKeptSessionID(t *testing.T) {
+ for in, want := range map[string]string{
+ "292f17ae-3f37-428e-b63e-8c7f9d178237": "292f17ae-3f37-428e-b63e-8c7f9d178237",
+ "ses_0123456789abcdef": "ses_0123456789abcdef",
+ "": "",
+ "../../etc/passwd": "",
+ "a b": "",
+ "id\nnext": "",
+ strings.Repeat("a", 129): "",
+ strings.Repeat("a", 128): strings.Repeat("a", 128),
+ } {
+ if got := keptSessionID(in); got != want {
+ t.Errorf("keptSessionID(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index 37c3a9a9..09b9024c 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -812,7 +812,7 @@ func (t *txn) writeStep(s *stepRecord) error {
}
s.Revision++
s.UpdatedAt = t.now()
- if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("base_checks", "base_checks_sha", "copy_owner", "copy_revision", "copy_result", "failure_signature", "state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_files", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci", "kind", "note", "sandbox_runner", "unsandboxed_by", "unsandboxed_at", "unsandboxed_attempt", "unsandboxed_runner", "has_preview", "preview", "boundary", "question", "request_turn", "sources_card", "sources_hash", "research_grant", "research_grant_revision", "hold", "housekeeping_attempt", "coordinator_attempt", "held_at", "publish", "model", "xcode_access", "outcome_phase", "publication_runner").Updates(s).Error; err != nil {
+ if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("base_checks", "base_checks_sha", "copy_owner", "copy_revision", "copy_result", "failure_signature", "state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_files", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci", "kind", "note", "sandbox_runner", "unsandboxed_by", "unsandboxed_at", "unsandboxed_attempt", "unsandboxed_runner", "has_preview", "preview", "boundary", "question", "request_turn", "sources_card", "sources_hash", "research_grant", "research_grant_revision", "hold", "housekeeping_attempt", "coordinator_attempt", "held_at", "publish", "model", "xcode_access", "outcome_phase", "session_id", "publication_runner").Updates(s).Error; err != nil {
return err
}
if s.Retired {
@@ -1666,6 +1666,12 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error {
}
s.Apple = v.Apple
s.Askable = v.Askable
+ // The kept session the runner names (protocol 37): a question
+ // about this attempt resumes exactly it.
+ s.SessionID = ""
+ if v.Askable {
+ s.SessionID = keptSessionID(v.SessionID)
+ }
if s.Rebase && s.BaseSHA != "" {
// The change sits on the new tip now: review reads it from
// there, and a later rebase starts from there.
@@ -2258,6 +2264,7 @@ func (t *txn) retryStepOf(k *taskRecord, person, step string, coordinator bool)
st.State, st.Reason, st.Pushed, st.Terminated, st.Summary, st.LogTail, st.StartedAt, st.FinishedAt = wire.StepQueued, "", false, false, "", "", nil, nil
st.Headline = ""
st.Verdict, st.ReviewLabel, st.Findings, st.Checks, st.Gate, st.ExitCode, st.Output, st.Askable = "", "", "", "", "", nil, "", false
+ st.SessionID = ""
st.Activity = ""
if st.Specialist == wire.SpecialistEngineering && !republish {
// Engineering runs again from the step's base: a new candidate.
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go
index a0b223b7..f2be18e9 100644
--- a/internal/fakeclaude/fake.go
+++ b/internal/fakeclaude/fake.go
@@ -99,9 +99,9 @@
// the last reply the transcript holds, so a test sees the session was
// the step's own. In the question (after "Question: "): "ask:git" calls
// git_diff and quotes the change's first added line, "ask:read:<path>"
-// asks to Read /workspace/<path> and quotes its first line,
-// "ask:write:<path>" asks to Write it and reports the answer,
-// "asksleep:<ms>" pauses before the reply.
+// asks to Read /workspace/<path> (on a darwin launch, the worktree) and
+// quotes its first line, "ask:write:<path>" asks to Write it and reports
+// the answer, "asksleep:<ms>" pauses before the reply.
// Research: a prompt starting "[Equipo: research]" is a Research step.
// Each "keep:<source>|<role>|<description>" (the description ends at ";"
// or the line's end) calls keep_image; then one submit_findings carries
@@ -962,7 +962,7 @@ func (f *fake) answer(question string, turn int, emit func(any)) string {
}
for i, m := range askRead.FindAllStringSubmatch(question, -1) {
id := fmt.Sprintf("toolu_fake_%d_ar%d", turn, i)
- input := map[string]any{"file_path": filepath.Join("/workspace", filepath.Clean("/"+m[1]))}
+ input := map[string]any{"file_path": filepath.Join(workspaceRoot(), filepath.Clean("/"+m[1]))}
use(id, "Read", input)
if !allowed(id, "Read", input) {
parts = append(parts, "Read of "+m[1]+" was denied.")
@@ -977,7 +977,7 @@ func (f *fake) answer(question string, turn int, emit func(any)) string {
}
for i, m := range askWrite.FindAllStringSubmatch(question, -1) {
id := fmt.Sprintf("toolu_fake_%d_aw%d", turn, i)
- input := map[string]any{"file_path": filepath.Join("/workspace", filepath.Clean("/"+m[1])), "content": "x"}
+ input := map[string]any{"file_path": filepath.Join(workspaceRoot(), filepath.Clean("/"+m[1])), "content": "x"}
use(id, "Write", input)
if allowed(id, "Write", input) {
if os.WriteFile(m[1], []byte("x"), 0644) == nil {
diff --git a/internal/headless/ask_test.go b/internal/headless/ask_test.go
index 40b020af..9a40bc58 100644
--- a/internal/headless/ask_test.go
+++ b/internal/headless/ask_test.go
@@ -105,6 +105,11 @@ func scenarioAsk(t *testing.T, env *Env) {
if !strings.HasPrefix(q1.Answer, "From my session: Headline: "+eng.Headline+"\n\n"+eng.Summary) || !strings.Contains(q1.Answer, "The change: +") || !strings.Contains(q1.Answer, "the panes") || !strings.Contains(q1.Answer, "README.md starts: ") {
t.Fatalf("engineering answer %q (its step said %q)", q1.Answer, eng.Summary)
}
+ // Pinned to the attempt it asked about and the session the runner
+ // named for it (Mac runners slice F, task 13).
+ if attempt, session, kept := env.AskPin(t, q1.ID); attempt != eng.Attempt || session == "" || session != kept {
+ t.Fatalf("question pinned to attempt %d session %q; the runner kept %q", attempt, session, kept)
+ }
// The answer's usage is recorded, as a turn's is.
if got := env.AskUsage(t, q1.ID); len(got) != 1 || got[0] != "replied/true" {
t.Fatalf("answer usage %v", got)
diff --git a/internal/headless/env_test.go b/internal/headless/env_test.go
index 7830e32f..dde6a0ce 100644
--- a/internal/headless/env_test.go
+++ b/internal/headless/env_test.go
@@ -132,6 +132,10 @@ type Env struct {
// AskUsage is the outcomes of a question's recorded usage rows, with
// whether each carried figures (local only).
AskUsage func(t *testing.T, question string) []string
+ // AskPin is the Engineering attempt and session the instance froze on
+ // a question, and the session the runner kept for that attempt
+ // (local only).
+ AskPin func(t *testing.T, question string) (attempt int64, session, kept string)
// Usage is every usage row of a task and of one coordinator turn, as
// role/round/turns=<known>/cached=<any>, by role and round (local only).
Usage func(t *testing.T, task, turn string) []string
@@ -351,6 +355,19 @@ func localEnv(t *testing.T) (*Env, *thintest.Instance, *localRunner) {
}
return ns
},
+ AskPin: func(t *testing.T, question string) (attempt int64, session, kept string) {
+ var step string
+ if err := inst.DB.Writer().QueryRow("SELECT step_id, coalesce(eng_attempt, 0), coalesce(eng_session, '') FROM chat_questions WHERE id = ?", question).Scan(&step, &attempt, &session); err != nil {
+ t.Fatal(err)
+ }
+ d, err := sql.Open("sqlite", "file:"+filepath.Join(state, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ _ = d.QueryRow("SELECT session_id FROM kept_sessions WHERE step_id=? AND attempt=?", step, attempt).Scan(&kept)
+ return attempt, session, kept
+ },
AskUsage: func(t *testing.T, question string) []string {
rows, err := inst.DB.Writer().Query("SELECT outcome, input_tokens IS NOT NULL FROM chat_usage WHERE step_id = ? AND role = 'ask' ORDER BY attempt", question)
if err != nil {
diff --git a/internal/runner/thin/ask.go b/internal/runner/thin/ask.go
index b3582b08..cb9ae32e 100644
--- a/internal/runner/thin/ask.go
+++ b/internal/runner/thin/ask.go
@@ -95,6 +95,32 @@ func (s *State) keptSessionFor(ctx context.Context, stepID string) (keptSession,
return k, err == nil, err
}
+// keptAttempt is the session one attempt of a step kept.
+func (s *State) keptAttempt(ctx context.Context, stepID string, attempt int64) (keptSession, bool, error) {
+ var k keptSession
+ err := s.db.QueryRowContext(ctx, "SELECT step_id, attempt, task_id, person, specialist, account, session_id, dir, candidate_sha, bytes, model, family FROM kept_sessions WHERE step_id=? AND attempt=?", stepID, attempt).Scan(&k.StepID, &k.Attempt, &k.TaskID, &k.Person, &k.Specialist, &k.Account, &k.SessionID, &k.Dir, &k.Candidate, &k.Bytes, &k.Model, &k.Family)
+ if errors.Is(err, sql.ErrNoRows) {
+ return k, false, nil
+ }
+ return k, err == nil, err
+}
+
+// keptForAsk is the kept session a question resumes: exactly the
+// Engineering attempt the instance froze on it (protocol 37), whose
+// account and session must be the ones frozen (mismatch otherwise); a
+// question that pins no attempt (Review, or an older instance's) has the
+// step's newest.
+func (s *State) keptForAsk(ctx context.Context, a wire.AskCommand) (k keptSession, found, mismatch bool, err error) {
+ if a.EngAttempt < 1 {
+ k, found, err = s.keptSessionFor(ctx, a.StepID)
+ return k, found, false, err
+ }
+ if k, found, err = s.keptAttempt(ctx, a.StepID, a.EngAttempt); err != nil || !found {
+ return k, found, false, err
+ }
+ return k, true, a.EngAccount != "" && k.Account != a.EngAccount || a.EngSession != "" && k.SessionID != a.EngSession, nil
+}
+
// keptCommit is the newest kept session of the task's specialist (for
// the person) that made or judged the commit sha.
func (s *State) keptCommit(ctx context.Context, task, person, specialist, sha string) (keptSession, bool, error) {
@@ -766,17 +792,18 @@ func (e *Engineer) answer(ctx context.Context, a askRow, progress func(wire.Answ
if !slices.Contains(e.Owners, a.Person) || !forgekey.ValidHub(a.Repo) || !wire.ValidTaskBranch(a.Branch) || !shaPattern.MatchString(a.CandidateSHA) || a.BaseSHA != "" && !shaPattern.MatchString(a.BaseSHA) {
return fail("policy_rejected")
}
- kept, found, err := e.O.State.keptSessionFor(ctx, a.StepID)
+ kept, found, mismatch, err := e.O.State.keptForAsk(ctx, a.AskCommand)
if err != nil {
e.log("ask session", err)
return fail("provider_failed")
}
// Only the step's own session, for this task and person, on the
- // commit the step made or judged.
+ // commit the step made or judged: for Engineering, exactly the
+ // attempt, account and session the question was asked about.
if !found || kept.TaskID != a.TaskID || kept.Person != a.Person || kept.Specialist != a.Specialist {
return fail("session_gone")
}
- if kept.Candidate != a.CandidateSHA {
+ if mismatch || kept.Candidate != a.CandidateSHA {
return fail("policy_rejected")
}
if _, err := os.Stat(keptTranscript(kept.Dir, kept.SessionID)); err != nil {
diff --git a/internal/runner/thin/ask_test.go b/internal/runner/thin/ask_test.go
index 5197383c..d5be7bae 100644
--- a/internal/runner/thin/ask_test.go
+++ b/internal/runner/thin/ask_test.go
@@ -2,6 +2,7 @@ package thin
import (
"context"
+ "encoding/hex"
"encoding/json"
"os"
"os/exec"
@@ -354,3 +355,76 @@ func TestMergedSessionOutlivesIdleExpiry(t *testing.T) {
t.Fatalf("a merged session went %v before its 14 days", dirs)
}
}
+
+// A question pinned to an Engineering attempt (protocol 37) is bound to
+// that attempt's kept session, never the step's newest; one whose account
+// or session differs from what that attempt kept is a mismatch. One that
+// pins nothing (Review, an older instance) has the step's newest.
+func TestKeptForAskBindsTheAttempt(t *testing.T) {
+ ctx := context.Background()
+ s, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ for i, session := range []string{"00000000-0000-4000-8000-000000000001", "00000000-0000-4000-8000-000000000002"} {
+ r := stepRow{DispatchCommand: dispatchFor("tk1", "s1", int64(i+1))}
+ if err := s.keepSession(ctx, r, wire.SpecialistEngineering, "claude-"+itoa(int64(i+1)), "", "", session, "/root/a/steps/"+itoa(int64(i+1)), strings.Repeat("c", 40), 10); err != nil {
+ t.Fatal(err)
+ }
+ }
+ ask := wire.AskCommand{StepID: "s1", EngAttempt: 1, EngAccount: "claude-1", EngSession: "00000000-0000-4000-8000-000000000001"}
+ if k, found, mismatch, err := s.keptForAsk(ctx, ask); err != nil || !found || mismatch || k.Attempt != 1 || k.Dir != "/root/a/steps/1" {
+ t.Fatalf("pinned to attempt 1: %+v %v %v %v", k, found, mismatch, err)
+ }
+ for name, edit := range map[string]func(*wire.AskCommand){
+ "account": func(a *wire.AskCommand) { a.EngAccount = "claude-2" },
+ "session": func(a *wire.AskCommand) { a.EngSession = "00000000-0000-4000-8000-000000000002" },
+ } {
+ a := ask
+ edit(&a)
+ if _, found, mismatch, _ := s.keptForAsk(ctx, a); !found || !mismatch {
+ t.Errorf("another %s is not a mismatch", name)
+ }
+ }
+ if _, found, _, _ := s.keptForAsk(ctx, wire.AskCommand{StepID: "s1", EngAttempt: 3}); found {
+ t.Fatal("an attempt that kept nothing found a session")
+ }
+ if k, found, _, _ := s.keptForAsk(ctx, wire.AskCommand{StepID: "s1"}); !found || k.Attempt != 2 {
+ t.Fatalf("unpinned: %+v", k)
+ }
+}
+
+// However a streamed answer is cut into chunks, what a reader assembles
+// is at every moment a prefix of the whole answer redacted, and at the end
+// all of it: a known secret (any form) split across chunks never leaves.
+func TestRedactedStreamAcrossChunks(t *testing.T) {
+ secret := "sk-ant-oat01-fake-0123456789abcdefghij"
+ forms := secretForms([]string{secret})
+ full := "I read " + secret + " in the file, hex " + hex.EncodeToString([]byte(secret)) + ", and moved on."
+ want := redactText(full, forms)
+ if strings.Contains(want, secret) {
+ t.Fatal("the redaction leaves the secret")
+ }
+ for i := 1; i < len(full); i++ {
+ for j := i; j < len(full); j += 7 {
+ var draft strings.Builder
+ s := newRedactedStream(forms, func(offset int64, text string) {
+ if int(offset) != draft.Len() {
+ t.Fatalf("cut %d,%d: offset %d after %d bytes", i, j, offset, draft.Len())
+ }
+ draft.WriteString(text)
+ if !strings.HasPrefix(want, draft.String()) {
+ t.Fatalf("cut %d,%d: %q is not a prefix of %q", i, j, draft.String(), want)
+ }
+ })
+ s.add(full[:i])
+ s.add(full[i:j])
+ s.add(full[j:])
+ s.flush()
+ if draft.String() != want {
+ t.Fatalf("cut %d,%d: %q", i, j, draft.String())
+ }
+ }
+ }
+}
diff --git a/internal/runner/thin/askmetered.go b/internal/runner/thin/askmetered.go
index 86ba8cc8..7407252f 100644
--- a/internal/runner/thin/askmetered.go
+++ b/internal/runner/thin/askmetered.go
@@ -35,7 +35,7 @@ func (e *StepEngine) meteredAsk(ctx context.Context, a askRow) (string, string,
if e.Meter == nil {
return "", "", false
}
- kept, found, err := e.State.keptSessionFor(ctx, a.StepID)
+ kept, found, _, err := e.State.keptForAsk(ctx, a.AskCommand)
if err != nil || !found {
return "", "", false
}
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go
index 7d091a27..650a339b 100644
--- a/internal/runner/thin/engineer.go
+++ b/internal/runner/thin/engineer.go
@@ -410,6 +410,11 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR
rep = withCommitReason(e.publish(ctx, r, rep), phase)
// The person can ask Engineering about the change it pushed.
rep.Askable = kept && rep.Pushed
+ if rep.Askable {
+ // The session a question about this attempt resumes (protocol 37;
+ // Encode drops it below).
+ rep.SessionID = res.session
+ }
return rep
}
diff --git a/internal/runner/thin/maccreds_test.go b/internal/runner/thin/maccreds_test.go
index a4a170d0..efe47599 100644
--- a/internal/runner/thin/maccreds_test.go
+++ b/internal/runner/thin/maccreds_test.go
@@ -47,6 +47,7 @@ d=%[1]s
env > "$d/bin/launch.$$.env"
pwd > "$d/bin/launch.$$.cwd"
echo "$*" > "$d/bin/launch.$$.argv"
+[ -f "$CLAUDE_CONFIG_DIR/equipo-settings.json" ] && cp "$CLAUDE_CONFIG_DIR/equipo-settings.json" "$d/bin/launch.$$.settings"
if [ "$1" = "-p" ] && [ -e "$d/hang" ]; then echo $$ > "$d/hang.pid"; exec /bin/sleep 600; fi
if [ -e "$d/linger" ] && [ "$1" = "$(cat "$d/linger")" ]; then (trap "" TERM HUP; exec /bin/sleep 5) & echo $! > "$d/linger.pid"; fi
exec "$d/bin/claude" "$@"
diff --git a/internal/runner/thin/pistep.go b/internal/runner/thin/pistep.go
index b7519771..ab38aa9f 100644
--- a/internal/runner/thin/pistep.go
+++ b/internal/runner/thin/pistep.go
@@ -559,14 +559,14 @@ func (e *Engineer) askPi(ctx context.Context, a askRow, l metered.Launch, progre
if !slices.Contains(e.Owners, a.Person) || !forgekey.ValidHub(a.Repo) || !wire.ValidTaskBranch(a.Branch) || !shaPattern.MatchString(a.CandidateSHA) || a.BaseSHA != "" && !shaPattern.MatchString(a.BaseSHA) {
return fail("policy_rejected")
}
- kept, found, err := e.O.State.keptSessionFor(ctx, a.StepID)
+ kept, found, mismatch, err := e.O.State.keptForAsk(ctx, a.AskCommand)
if err != nil {
return fail("provider_failed")
}
if !found || kept.TaskID != a.TaskID || kept.Person != a.Person || kept.Specialist != a.Specialist || !hasKeptSession(kept.Dir, kept.SessionID) {
return fail("session_gone")
}
- if kept.Candidate != a.CandidateSHA {
+ if mismatch || kept.Candidate != a.CandidateSHA {
return fail("policy_rejected")
}
b, ok := e.askBinding(ctx, a.Person, kept.Account)
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index 8adb2256..4d0849c1 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -776,8 +776,10 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl
}
return h
}
- engineer := &Engineer{O: o.Claude, Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, Owners: coordinatorPersons(c)(), MaxStep: o.MaxStep, Host: c.MachineLabel, Note: o.StepNote, Retention: o.KeptRetention,
- Spoken: func() int { p, _ := link.Spoken(); return p }}
+ // Its owners include the person it is enrolled for, as on the primary:
+ // before their first connection here they have no binding.
+ engineer := &Engineer{O: o.Claude, Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), MaxStep: o.MaxStep, Host: c.MachineLabel, Note: o.StepNote, Retention: o.KeptRetention,
+ Spoken: func() int { p, _ := link.Spoken(); return p }, Delta: link.Delta, Activity: link.Activity}
engineer.O.Runner, engineer.O.State, engineer.O.Logger = c, state, o.Logger
if own != nil {
// Engineering on a Mac picks among the worker's own connections.
@@ -826,7 +828,9 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl
w.started(ctx, func() { caps.Stale(); link.HelloSoon() })
}
tags := func() []string { return caps.Get(ctx).Tags }
- steps := &StepEngine{State: state, Exec: placementGuard(tags, caps.Stale, worker.Exec), Notify: link.Notify, Logger: o.Logger,
+ // Questions about the Engineering it ran are answered here, from the
+ // sessions it kept (worker_ask.go).
+ steps := &StepEngine{State: state, Exec: placementGuard(tags, caps.Stale, worker.Exec), Ask: worker.ask, Notify: link.Notify, Logger: o.Logger,
Sweep: worker.sweep,
Verify: func(_ context.Context, id string) bool { return w.gate.Verify(workerRecord(id)) }, TerminationKind: wire.TerminationProcessGroup}
link.Steps = steps
diff --git a/internal/runner/thin/worker_ask.go b/internal/runner/thin/worker_ask.go
new file mode 100644
index 00000000..9c663a5e
--- /dev/null
+++ b/internal/runner/thin/worker_ask.go
@@ -0,0 +1,242 @@
+package thin
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+ "unicode/utf8"
+
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runner/mac"
+ "amadan.net/oficina/equipo/internal/runner/provider/claude"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/wire"
+ "amadan.net/oficina/equipo/internal/wire/forgekey"
+)
+
+// Ask the implementer on a Mac worker (Mac runners slice F, task 13).
+// The worker kept each Engineering attempt's session (kept_sessions, one
+// per step and attempt, with its account and session id) and pinned its
+// candidate in its store (candidateRef). A question resumes exactly the
+// session the instance froze on it: that step, attempt, account and
+// session id, on the commit it made; anything else is refused before
+// anything runs. It runs in the Mac's turn (OpAsk), through the darwin
+// launch with the read-only answer settings (task 8), in a fresh tree of
+// the candidate under the scratch root, and git_log, git_diff and
+// git_show read the change from the store (its shallow boundaries end
+// the history at the base). The answer passes the known-secret redaction
+// before it leaves.
+
+// ask answers one question attempt about an Engineering step this worker
+// ran; terminated is false only when its launch started and its end was
+// not proven.
+func (w *Worker) ask(ctx context.Context, a askRow, progress func(wire.AnswerReport)) askResult {
+ terminated := true
+ rep := w.answer(ctx, a, progress, &terminated)
+ return askResult{Report: rep, Terminated: terminated}
+}
+
+func (w *Worker) answer(ctx context.Context, a askRow, progress func(wire.AnswerReport), terminated *bool) (rep wire.AnswerReport) {
+ e := w.Engine
+ received := time.Now()
+ rep = wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt}
+ fail := func(reason string) wire.AnswerReport {
+ rep.State, rep.Reason = wire.QuestionFailed, reason
+ if ctx.Err() != nil {
+ rep.State, rep.Reason = wire.QuestionCancelled, "cancelled"
+ }
+ return rep
+ }
+ // The instance's pinning, whole: a worker answers only about the
+ // Engineering it ran, and only for the attempt, account and session
+ // frozen on the question.
+ if !slices.Contains(e.Owners, a.Person) || !forgekey.ValidHub(a.Repo) || !wire.ValidTaskBranch(a.Branch) || !refName.MatchString(a.TaskID) || !refName.MatchString(a.StepID) ||
+ !wire.ValidCommitSHA(a.CandidateSHA) || !wire.ValidCommitSHA(a.BaseSHA) || a.Specialist != wire.SpecialistEngineering || a.EngAttempt < 1 || a.EngAccount == "" || a.EngSession == "" {
+ return fail("policy_rejected")
+ }
+ kept, found, err := w.State.keptAttempt(ctx, a.StepID, a.EngAttempt)
+ if err != nil {
+ e.log("ask session", err)
+ return fail("provider_failed")
+ }
+ if !found || kept.TaskID != a.TaskID || kept.Person != a.Person || kept.Specialist != wire.SpecialistEngineering {
+ return fail("session_gone")
+ }
+ if kept.Account != a.EngAccount || kept.SessionID != a.EngSession || kept.Candidate != a.CandidateSHA {
+ return fail("policy_rejected")
+ }
+ if _, err := os.Stat(keptTranscript(kept.Dir, kept.SessionID)); err != nil {
+ return fail("session_gone")
+ }
+ if w.Eng == nil || w.Eng.Creds == nil || w.Eng.Status == nil || w.Eng.Secrets == nil || e.Conns == nil {
+ return fail("account_unavailable")
+ }
+ // The session's own connection, while it can run; never another.
+ var b runner.AccountBinding
+ if i := slices.IndexFunc(e.Conns.Mine(a.Person), func(c runner.AccountBinding) bool {
+ return c.Provider == wire.ProviderClaude && c.LocalID == kept.Account
+ }); i >= 0 {
+ b = e.Conns.Mine(a.Person)[i]
+ }
+ if b.ID == "" || e.Healthy != nil && !e.Healthy(b.ID) {
+ return fail("account_unavailable")
+ }
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if ctx.Err() != nil {
+ return fail("cancelled")
+ }
+ m := w.Eng.Creds
+ if m.turns != nil {
+ u, err := m.turns.Take(ctx, mac.OpAsk)
+ if err != nil {
+ e.log("worker ask turn", err)
+ return fail("account_unavailable")
+ }
+ defer u.Give()
+ ctx = u.Context(ctx)
+ }
+ secrets, err := w.Eng.Secrets(ctx)
+ if err != nil {
+ // What it cannot name it cannot keep from leaving: nothing runs.
+ e.log("worker secrets", err)
+ return fail("account_unavailable")
+ }
+ known := secretForms(secrets)
+ defer func() { rep.Text = redactText(rep.Text, known) }()
+ marker := engineeringMarker("ask/" + a.QuestionID + "/" + itoa(a.Attempt))
+ w.marker = marker
+ defer func() { w.marker = "" }()
+ if err := w.State.setAskNamespace(ctx, a, mac.RecordID(0, marker)); err != nil {
+ e.log("worker record", err)
+ return fail("provider_failed")
+ }
+ // The candidate as the store pins it for that attempt.
+ store := w.objects(a.Repo)
+ ref := candidateRef(stepRow{DispatchCommand: wire.DispatchCommand{TaskID: a.TaskID, StepID: a.StepID, Attempt: a.EngAttempt}})
+ if tip, err := w.git(ctx, nil, "--git-dir="+store, "rev-parse", "--verify", "--end-of-options", ref+"^{commit}"); err != nil || tip != a.CandidateSHA {
+ return fail("candidate_unavailable")
+ }
+ r := stepRow{DispatchCommand: wire.DispatchCommand{Person: a.Person, TaskID: a.TaskID, StepID: a.QuestionID, Attempt: a.Attempt, Specialist: wire.SpecialistEngineering, Repo: a.Repo, Branch: a.Branch, BaseSHA: a.BaseSHA, CandidateSHA: a.CandidateSHA}, Question: true}
+ dir := filepath.Join(w.stepsDir(), "ask-"+stepKey(r))
+ defer os.RemoveAll(dir)
+ tree, err := workspace.PrepareTaskTree(ctx, e.O.Runner.GitPath, store, a.CandidateSHA, a.Branch, filepath.Join(dir, "tree"), filepath.Join(dir, "git"))
+ if err != nil {
+ e.log("worker ask tree", err)
+ return fail("candidate_unavailable")
+ }
+ rep.State = wire.QuestionRunning
+ progress(rep)
+ stream := &answerStream{}
+ if e.Delta != nil {
+ // A secret can arrive split across chunks: the text is redacted
+ // whole as it grows (redactedStream).
+ held := newRedactedStream(known, func(offset int64, text string) {
+ e.Delta(wire.DeltaReport{TurnID: a.QuestionID, Attempt: a.Attempt, Offset: offset, Text: text})
+ })
+ stream.delta = func(_ int64, text string) { held.add(text) }
+ defer held.flush()
+ }
+ if e.Activity != nil {
+ stream.activity = func(kind, tool string) {
+ e.Activity(wire.ActivityReport{TurnID: a.QuestionID, Attempt: a.Attempt, Kind: kind, Tool: tool})
+ }
+ }
+ var mu sync.Mutex
+ call := func(cctx context.Context, name, _ string, args json.RawMessage) (string, bool) {
+ mu.Lock()
+ defer mu.Unlock()
+ return answerGit(cctx, tree.Git, tree.GitDir, a.BaseSHA, a.CandidateSHA, name, args)
+ }
+ limit := e.MaxAnswer
+ if limit <= 0 {
+ limit = maxAnswer
+ }
+ res := w.launch(ctx, r, tree, specialistRun{action: "answer", binding: b, tools: answerTools, names: []string{"git_log", "git_diff", "git_show"}, permission: claude.ReadPermission, call: call, prompt: e.askPrompt(a, tree.Dir), resume: kept.SessionID, keep: kept.Dir, stream: stream, limit: limit, noLog: true,
+ record: func(ctx context.Context, id string) error { return w.State.setAskNamespace(ctx, a, id) }}, marker, known)
+ *terminated = res.terminated
+ if res.kept > 0 {
+ e.log("kept sessions", w.State.touchKept(context.WithoutCancel(ctx), kept, res.kept))
+ }
+ switch {
+ case ctx.Err() != nil:
+ rep.State, rep.Reason = wire.QuestionCancelled, "cancelled"
+ case res.reason == "step_timeout":
+ rep.State, rep.Reason = wire.QuestionFailed, "turn_timeout"
+ case res.reason != "":
+ if !wire.AnswerReasons[res.reason] {
+ res.reason = "provider_failed"
+ }
+ rep.State, rep.Reason = wire.QuestionFailed, res.reason
+ case strings.TrimSpace(res.summary) == "":
+ rep.State, rep.Reason = wire.QuestionFailed, "provider_failed"
+ default:
+ rep.State, rep.Text = wire.QuestionAnswered, clip(strings.TrimSpace(res.summary), wire.MaxAnswerText)
+ t := stream.timing
+ t.Cold = true
+ if !stream.stdin.IsZero() {
+ t.StartMs = stream.stdin.Sub(received).Milliseconds()
+ }
+ rep.Timing = &t
+ }
+ outcome := wire.OutcomeFailed
+ switch rep.State {
+ case wire.QuestionAnswered:
+ outcome = wire.OutcomeReplied
+ case wire.QuestionCancelled:
+ outcome = wire.OutcomeCancelled
+ }
+ rep.Usage = usageRows(res.tokens, b, a.Attempt, outcome)
+ return rep
+}
+
+// redactedStream sends a session's streamed text with every known secret
+// redacted, whichever chunks it arrives in: the text so far is redacted
+// whole, and its last hold bytes (room for the longest form of a secret
+// to complete) wait for the next chunk or the flush. A form can only
+// match where new text ends it, so what was sent stays a prefix of what
+// the whole text redacts to. Offsets are the redacted text's.
+type redactedStream struct {
+ forms [][]byte
+ hold int
+ raw strings.Builder
+ sent int
+ send func(offset int64, text string)
+}
+
+func newRedactedStream(forms [][]byte, send func(offset int64, text string)) *redactedStream {
+ hold := 64
+ for _, f := range forms {
+ hold = max(hold, len(f))
+ }
+ return &redactedStream{forms: forms, hold: hold, send: send}
+}
+
+func (r *redactedStream) add(text string) {
+ r.raw.WriteString(text)
+ r.emit(false)
+}
+
+// flush sends what is held, once the session has said everything.
+func (r *redactedStream) flush() { r.emit(true) }
+
+func (r *redactedStream) emit(all bool) {
+ out := redactText(r.raw.String(), r.forms)
+ end := len(out)
+ if !all {
+ end -= r.hold
+ }
+ for end > r.sent && end < len(out) && !utf8.RuneStart(out[end]) {
+ end--
+ }
+ if end <= r.sent {
+ return
+ }
+ r.send(int64(r.sent), out[r.sent:end])
+ r.sent = end
+}
diff --git a/internal/runner/thin/worker_ask_test.go b/internal/runner/thin/worker_ask_test.go
new file mode 100644
index 00000000..92bef28a
--- /dev/null
+++ b/internal/runner/thin/worker_ask_test.go
@@ -0,0 +1,281 @@
+//go:build testbuild
+
+package thin
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Ask the implementer on a Mac worker (Mac runners slice F, task 13), on
+// Linux through the darwin launch of the pinned stand-in: a question is
+// bound to exactly the (step, attempt, account, session) the instance
+// froze, resumes that kept session with the read-only answer settings,
+// and reads the change with git over the worker's store.
+
+// askedRound runs one Engineering round on the worker to its publication
+// and returns its final report (its kept session named).
+func askedRound(t *testing.T, x *engRig) wire.StepReport {
+ t.Helper()
+ x.note("edit:Swipe.swift|false|true")
+ rep := x.round(t)
+ if rep.SessionID == "" || !rep.Askable || rep.Account == "" {
+ t.Fatalf("no kept session reported: %+v", rep)
+ }
+ return rep
+}
+
+// askAbout is the instance's ask for the round rep, pinned to it.
+func askAbout(x *engRig, rep wire.StepReport, id, text string) askRow {
+ return askRow{AskCommand: wire.AskCommand{Person: connPerson, TaskID: rep.TaskID, StepID: rep.StepID, QuestionID: id, Attempt: 1, Specialist: wire.SpecialistEngineering, Repo: x.r.Repo, Branch: x.r.Branch, BaseSHA: rep.BaseSHA, CandidateSHA: rep.CandidateSHA, Title: "Swipe back", Text: text,
+ EngAttempt: rep.Attempt, EngAccount: rep.Account, EngSession: rep.SessionID}}
+}
+
+// asked runs a on the worker as the step engine does: accepted, started,
+// answered; it returns the final report and the running reports said.
+func (x *engRig) asked(t *testing.T, a askRow) (wire.AnswerReport, []wire.AnswerReport) {
+ t.Helper()
+ ctx := context.Background()
+ if err := x.state.AcceptAsk(ctx, "f-"+a.QuestionID, a.AskCommand); err != nil {
+ t.Fatal(err)
+ }
+ if err := x.state.startAsk(ctx, a); err != nil {
+ t.Fatal(err)
+ }
+ var said []wire.AnswerReport
+ res := x.w.ask(ctx, a, func(p wire.AnswerReport) { said = append(said, p) })
+ if !res.Terminated {
+ t.Fatalf("the answer's end was not proven: %+v", res.Report)
+ }
+ if !x.turnFree() {
+ t.Fatal("the Mac's turn is still held")
+ }
+ return res.Report, said
+}
+
+// newest is the newest step-shaped launch of the pinned CLI (-p; auth
+// status reads are not).
+func (x *engRig) newest(t *testing.T) launched {
+ t.Helper()
+ var best launched
+ var at time.Time
+ for _, l := range x.launches() {
+ info, err := os.Stat(filepath.Join(x.dir, "bin", "launch."+itoa(int64(l.pid))+".argv"))
+ if err == nil && strings.HasPrefix(l.argv, "-p ") && info.ModTime().After(at) {
+ best, at = l, info.ModTime()
+ }
+ }
+ if at.IsZero() {
+ t.Fatal("no launch")
+ }
+ return best
+}
+
+// keepAnother records a kept session for another attempt of rep's step,
+// on the same candidate, whose transcript's last reply is said.
+func (x *engRig) keepAnother(t *testing.T, rep wire.StepReport, attempt int64, account, session, said string) {
+ t.Helper()
+ r := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: rep.TaskID, StepID: rep.StepID, Attempt: attempt, Specialist: wire.SpecialistEngineering}}
+ dir := x.w.Engine.keepDir(r)
+ line, _ := json.Marshal(map[string]string{"type": "assistant", "text": said})
+ if err := os.MkdirAll(filepath.Dir(keptTranscript(dir, session)), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(keptTranscript(dir, session), append(line, '\n'), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := x.state.keepSession(context.Background(), r, wire.SpecialistEngineering, account, "", "", session, dir, rep.CandidateSHA, int64(len(line))); err != nil {
+ t.Fatal(err)
+ }
+ // Its candidate pinned in the store, as its commit would be.
+ if out, err := x.store(t, "update-ref", candidateRef(r), rep.CandidateSHA); err != nil {
+ t.Fatalf("pin %v %s", err, out)
+ }
+}
+
+// The answer comes from exactly the bound kept session: a newer attempt
+// of the same step with the same candidate kept on the worker is not the
+// one asked about. It resumes that session read-only, streams, and its
+// git_diff reads the change from the worker's store.
+func TestWorkerAskAnswersFromKeptSession(t *testing.T) {
+ x := newEngRig(t)
+ rep := askedRound(t, x)
+ const later = "00000000-0000-4000-8000-0000000000a2"
+ x.keepAnother(t, rep, rep.Attempt+1, rep.Account, later, "Attempt two's own words.")
+ var deltas []wire.DeltaReport
+ x.w.Engine.Delta = func(d wire.DeltaReport) { deltas = append(deltas, d) }
+ launched := x.steps()
+ got, said := x.asked(t, askAbout(x, rep, "q1", "What did you change? ask:git"))
+ if got.State != wire.QuestionAnswered || !strings.HasPrefix(got.Text, "From my session: ") || strings.Contains(got.Text, "Attempt two") || !strings.Contains(got.Text, "The change: +let back = true") {
+ t.Fatalf("answer %+v\n%s", got, x.logs.String())
+ }
+ if len(said) != 1 || said[0].State != wire.QuestionRunning {
+ t.Fatalf("running reports %+v", said)
+ }
+ if len(deltas) == 0 || deltas[0].TurnID != "q1" {
+ t.Fatalf("nothing streamed: %+v", deltas)
+ }
+ if x.steps() != launched+1 {
+ t.Fatalf("%d launches for one question", x.steps()-launched)
+ }
+ l := x.newest(t)
+ if !strings.Contains(l.argv, "--resume "+rep.SessionID) || strings.Contains(l.argv, later) {
+ t.Fatalf("not the bound session (%s): %s", rep.SessionID, l.argv)
+ }
+ // Asked about the later attempt, the later session answers.
+ a := askAbout(x, rep, "q2", "And then?")
+ a.EngAttempt, a.EngSession = rep.Attempt+1, later
+ if got, _ := x.asked(t, a); got.State != wire.QuestionAnswered || !strings.Contains(got.Text, "Attempt two's own words.") {
+ t.Fatalf("later attempt's answer %+v", got)
+ }
+ if l := x.newest(t); !strings.Contains(l.argv, "--resume "+later) {
+ t.Fatalf("not the later session: %s", l.argv)
+ }
+}
+
+// A question that does not match a kept session exactly is refused
+// before anything runs: another account, another session, an attempt
+// this worker kept nothing for, another step, another candidate, no
+// pinning at all, or a specialist a worker never runs.
+func TestWorkerAskRefusesMismatch(t *testing.T) {
+ x := newEngRig(t)
+ rep := askedRound(t, x)
+ cases := map[string]struct {
+ edit func(*askRow)
+ reason string
+ }{
+ "another account": {func(a *askRow) { a.EngAccount = "c9" }, "policy_rejected"},
+ "another session": {func(a *askRow) { a.EngSession = "00000000-0000-4000-8000-0000000000ff" }, "policy_rejected"},
+ "another attempt": {func(a *askRow) { a.EngAttempt = rep.Attempt + 5 }, "session_gone"},
+ "another step": {func(a *askRow) { a.StepID = "s9" }, "session_gone"},
+ "another candidate": {func(a *askRow) { a.CandidateSHA = strings.Repeat("a", 40) }, "policy_rejected"},
+ "not pinned": {func(a *askRow) { a.EngAttempt, a.EngAccount, a.EngSession = 0, "", "" }, "policy_rejected"},
+ "no session": {func(a *askRow) { a.EngSession = "" }, "policy_rejected"},
+ "review": {func(a *askRow) { a.Specialist = wire.SpecialistReview }, "policy_rejected"},
+ }
+ n := 0
+ for name, c := range cases {
+ n++
+ a := askAbout(x, rep, "q"+itoa(int64(n)), "Why?")
+ c.edit(&a)
+ before := x.steps()
+ got, said := x.asked(t, a)
+ if got.State != wire.QuestionFailed || got.Reason != c.reason || len(said) != 0 || x.steps() != before {
+ t.Errorf("%s: %+v, said %+v, %d launches", name, got, said, x.steps()-before)
+ }
+ }
+ // The exact pinning still answers.
+ if got, _ := x.asked(t, askAbout(x, rep, "q-ok", "Why?")); got.State != wire.QuestionAnswered {
+ t.Fatalf("pinned answer %+v\n%s", got, x.logs.String())
+ }
+ // With the attempt's candidate no longer pinned in the store (its keep
+ // ended), nothing runs.
+ ref := candidateRef(stepRow{DispatchCommand: wire.DispatchCommand{TaskID: rep.TaskID, StepID: rep.StepID, Attempt: rep.Attempt}})
+ if out, err := x.store(t, "update-ref", "-d", ref); err != nil {
+ t.Fatalf("drop %v %s", err, out)
+ }
+ before := x.steps()
+ if got, _ := x.asked(t, askAbout(x, rep, "q-gone", "Why?")); got.State != wire.QuestionFailed || got.Reason != "candidate_unavailable" || x.steps() != before {
+ t.Fatalf("without its candidate: %+v", got)
+ }
+}
+
+// A known secret in what the session says (here, its own transcript
+// quoting the connection's token) never leaves the Mac: the answer and
+// its streamed text are redacted.
+func TestWorkerAskRedactsKnownSecrets(t *testing.T) {
+ x := newEngRig(t)
+ rep := askedRound(t, x)
+ const later = "00000000-0000-4000-8000-0000000000b2"
+ x.keepAnother(t, rep, rep.Attempt+1, rep.Account, later, "I saw "+x.tokens[0]+" there.")
+ var deltas []string
+ x.w.Engine.Delta = func(d wire.DeltaReport) { deltas = append(deltas, d.Text) }
+ a := askAbout(x, rep, "q1", "What did you see?")
+ a.EngAttempt, a.EngSession = rep.Attempt+1, later
+ got, _ := x.asked(t, a)
+ if got.State != wire.QuestionAnswered || !strings.HasPrefix(got.Text, "From my session: I saw ") || strings.Contains(got.Text, x.tokens[0]) {
+ t.Fatalf("answer %+v", got)
+ }
+ if len(deltas) == 0 || strings.Contains(strings.Join(deltas, ""), x.tokens[0]) {
+ t.Fatalf("streamed %q", deltas)
+ }
+}
+
+// The answer runs with the read-only darwin settings: Read, Glob and
+// Grep only, the worktree denied to writes and not writable, partial
+// messages on; a Write is refused, and nothing reaches the store.
+func TestWorkerAskCannotWrite(t *testing.T) {
+ x := newEngRig(t)
+ rep := askedRound(t, x)
+ ref := candidateRef(stepRow{DispatchCommand: wire.DispatchCommand{TaskID: rep.TaskID, StepID: rep.StepID, Attempt: rep.Attempt}})
+ got, _ := x.asked(t, askAbout(x, rep, "q1", "Fix it? ask:write:Swipe.swift"))
+ if got.State != wire.QuestionAnswered || !strings.Contains(got.Text, "Write to Swipe.swift was denied") {
+ t.Fatalf("answer %+v\n%s", got, x.logs.String())
+ }
+ l := x.newest(t)
+ if !strings.Contains(l.argv, "--tools Read,Glob,Grep ") || !strings.Contains(l.argv, "--include-partial-messages") {
+ t.Fatalf("not the answer profile: %s", l.argv)
+ }
+ raw, err := os.ReadFile(filepath.Join(x.dir, "bin", "launch."+itoa(int64(l.pid))+".settings"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var s struct {
+ Sandbox struct {
+ Filesystem struct {
+ AllowWrite, DenyWrite []string
+ }
+ }
+ Permissions struct{ Allow []string }
+ }
+ if err := json.Unmarshal(raw, &s); err != nil {
+ t.Fatal(err)
+ }
+ for _, tool := range s.Permissions.Allow {
+ if strings.HasPrefix(tool, "Write") || strings.HasPrefix(tool, "Edit") || strings.HasPrefix(tool, "Bash") {
+ t.Fatalf("the ask settings allow %s: %s", tool, raw)
+ }
+ }
+ if slices.Contains(s.Sandbox.Filesystem.AllowWrite, l.cwd) || !slices.Contains(s.Sandbox.Filesystem.DenyWrite, l.cwd) {
+ t.Fatalf("the worktree %s is writable: %s", l.cwd, raw)
+ }
+ if tip, err := x.store(t, "rev-parse", ref); err != nil || tip != rep.CandidateSHA {
+ t.Fatalf("the candidate's ref moved: %q %v", tip, err)
+ }
+ if body, err := x.store(t, "show", rep.CandidateSHA+":Swipe.swift"); err != nil || body != "let back = true" {
+ t.Fatalf("the candidate changed: %q %v", body, err)
+ }
+}
+
+// The worker as it runs answers the asks it is sent: one about a session
+// it does not hold ends at once, failed, with nothing launched (an ask
+// the step engine had no answerer for would wait for ever). The person it
+// is enrolled for is one of its owners before their first connection
+// here, as on the primary: nothing waits for a restart.
+func TestWorkerRunAnswersAsks(t *testing.T) {
+ r := newDarwinRig(t)
+ r.machineKey()
+ r.workerCredential()
+ inst := newWorkerInstance(t)
+ stop := r.runWorker(inst, 0)
+ defer stop()
+ inst.welcome(wire.ProtocolMacEngineering)
+ launches := len(r.launches())
+ inst.send(wire.FrameAsk, wire.AskCommand{Person: connPerson, TaskID: "tk1", StepID: "s1", QuestionID: "q1", Attempt: 1, Specialist: wire.SpecialistEngineering, Repo: "amadan.net/oficina/sample", Branch: relayBranch, BaseSHA: strings.Repeat("1", 40), CandidateSHA: strings.Repeat("2", 40), Title: "Swipe back", Text: "Why?",
+ EngAttempt: 1, EngAccount: "c1", EngSession: "00000000-0000-4000-8000-000000000001"})
+ a := inst.next(wire.FrameAnswer, func(b any) bool {
+ v := b.(*wire.AnswerReport)
+ return v.QuestionID == "q1" && wire.QuestionTerminal(v.State)
+ }).(*wire.AnswerReport)
+ if a.State != wire.QuestionFailed || a.Reason != "session_gone" || len(r.launches()) != launches {
+ t.Fatalf("answer %+v, %d launches", a, len(r.launches())-launches)
+ }
+}
diff --git a/internal/runner/thin/worker_launch.go b/internal/runner/thin/worker_launch.go
index 8b5fa475..34eb9409 100644
--- a/internal/runner/thin/worker_launch.go
+++ b/internal/runner/thin/worker_launch.go
@@ -25,8 +25,8 @@ import (
var macStopLimit = 30*time.Second + simShutdownLimit + 30*time.Second
// launch is Engineer.run on a Mac worker: the pinned CLI through the
-// darwin launch (mac.Starter), its implement policy for the worktree at
-// its real path, the connection's runtime copy as its config dir and the
+// darwin launch (mac.Starter), its implement policy (or, for a question,
+// the read-only answer policy) for the worktree at its real path, the connection's runtime copy as its config dir and the
// token by descriptor, watched for a Keychain item as a sign-in is. ctx
// holds the Mac's turn. A start whose record was lost (ErrRecord) or
// whose stop was not proven (ErrUnproven) ends unproven: not terminated,
@@ -102,10 +102,16 @@ func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree,
session, resume = spec.resume, true
}
model := firstNonEmpty(b.Model, firstNonEmpty(o.Runner.ClaudeModel, DefaultModels[wire.ProviderClaude]))
- in := mac.EngineeringInput{Paths: m.paths, Action: claude.DarwinImplement, Model: model, Worktree: tree.Dir, Scratch: scratch, Runner: m.runner, ToolRoot: root, Socket: tool.Path,
- ConfigDir: binding.Home, CredentialHome: b.ProviderHome, RuntimeRoot: direct.RuntimeRoot, XcodeAccess: r.XcodeAccess, DeveloperDir: w.Eng.DeveloperDir, Attempt: marker, SessionID: session, Resume: resume}
+ action, xcode := claude.DarwinImplement, r.XcodeAccess
+ if spec.action == "answer" {
+ // A question: Read, Glob and Grep, the worktree read-only, never
+ // with Xcode.
+ action, xcode = claude.DarwinAnswer, ""
+ }
+ in := mac.EngineeringInput{Paths: m.paths, Action: action, Model: model, Worktree: tree.Dir, Scratch: scratch, Runner: m.runner, ToolRoot: root, Socket: tool.Path,
+ ConfigDir: binding.Home, CredentialHome: b.ProviderHome, RuntimeRoot: direct.RuntimeRoot, XcodeAccess: xcode, DeveloperDir: w.Eng.DeveloperDir, Attempt: marker, SessionID: session, Resume: resume}
exec := m.exec
- if r.XcodeAccess != "" {
+ if xcode != "" {
in.Mach = mac.CheckMachServices
if w.Eng.XcodeExec != nil {
exec = w.Eng.XcodeExec
@@ -118,7 +124,11 @@ func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree,
if err = lease.CheckCopy(ctx); err != nil {
return done(reasonFor(err))
}
- limit := min(e.maxStep(), time.Until(lease.FreshUntil())-o.Margin)
+ limit := e.maxStep()
+ if spec.limit > 0 {
+ limit = spec.limit
+ }
+ limit = min(limit, time.Until(lease.FreshUntil())-o.Margin)
if limit < minTurn {
return done("account_unavailable")
}
@@ -146,6 +156,10 @@ func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree,
if err := m.keychain.Ran(marker, rec.ID); err != nil {
return err
}
+ if spec.record != nil {
+ // A question's attempt keeps its own record.
+ return spec.record(context.WithoutCancel(rctx), rec.ID)
+ }
return w.State.setStepNamespace(context.WithoutCancel(rctx), r, rec.ID)
})
if err != nil {
@@ -174,12 +188,15 @@ func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree,
}
}
}()
- // The step log keeps only redacted frames.
- raw := e.openLog(r)
- defer raw.Close()
- logFile := redactingWriter{w: raw, forms: forms}
+ // The step log keeps only redacted frames; a question keeps none.
+ var logFile io.Writer = io.Discard
+ if !spec.noLog {
+ raw := e.openLog(r)
+ defer raw.Close()
+ logFile = redactingWriter{w: raw, forms: forms}
+ }
var shell shellUse
- res := e.converse(ctx, proc, session, policy, model, frames, logFile, limit, spec.prompt, nil, nil, spec.activity, &shell)
+ res := e.converse(ctx, proc, session, policy, model, frames, logFile, limit, spec.prompt, nil, spec.stream, spec.activity, &shell)
res.session, res.refused, res.noShell = session, refused.Load(), shell.none()
res.terminated = stopStep(func() { proc.Stdin().Close() }, exited, kill, ctx.Err() == nil && res.reason == "", 10*time.Second, macStopLimit)
if !res.terminated {
diff --git a/internal/thintest/mac_ask_contract_test.go b/internal/thintest/mac_ask_contract_test.go
new file mode 100644
index 00000000..f90140d2
--- /dev/null
+++ b/internal/thintest/mac_ask_contract_test.go
@@ -0,0 +1,254 @@
+package thintest
+
+import (
+ "context"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Ask the implementer, pinned exactly (Mac runners slice F, plan task
+// 13): a question about an Engineering step is frozen, when it is asked,
+// to the attempt, account, kept session, runner, base and candidate it is
+// about. Dispatch, cancel, the runner's replies and a reconnect's sync
+// all use those frozen values, never the step as it stands later.
+
+// askableOn runs w's Engineering attempt d to a commit of cand made on
+// account, done with its session kept (session), and the primary
+// publishes it.
+func (r *runnersRig) askableOn(w *peer, d *wire.DispatchCommand, cand, account, session string) {
+ r.t.Helper()
+ if !w.lease(d.StepID, d.Attempt) {
+ r.t.Fatal("start refused")
+ }
+ w.send(wire.FrameStep, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, BaseSHA: d.BaseSHA, Family: "claude", Account: account, Findings: []wire.Finding{}})
+ w.send(wire.FrameStep, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, CandidateSHA: cand, Phase: wire.OutcomeCommitted, Findings: []wire.Finding{}})
+ _, body := w.expect(wire.FrameSendPack)
+ h := body.(*wire.SendPackCommand).Transfer
+ w.send(wire.FrameStep, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, CandidateSHA: cand, Termination: true, TerminationKind: wire.TerminationProcessGroup, Family: "claude", Account: account, Askable: true, SessionID: session, Findings: []wire.Finding{}})
+ w.send(wire.FrameBlob, chunk(h, []byte("PACK commit")))
+ r.fromPrimary(wire.FrameBlob)
+ pub := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand)
+ r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: cand, Pushed: true})
+ if s := r.engineeringStep(d.TaskID); s.State != wire.StepDone || !s.Askable || s.Attempt != d.Attempt || s.CandidateSHA != cand {
+ r.t.Fatalf("not askable: %+v", s)
+ }
+}
+
+// frozen is what a question row holds of the attempt it is about.
+type frozen struct {
+ attempt int64
+ account, session, runner, base, candidate string
+}
+
+func (r *runnersRig) frozenOf(q string) frozen {
+ r.t.Helper()
+ var f frozen
+ if err := r.inst.DB.Writer().QueryRow("SELECT coalesce(eng_attempt, 0), coalesce(eng_account, ''), coalesce(eng_session, ''), coalesce(runner_id, ''), coalesce(base_sha, ''), coalesce(candidate_sha, '') FROM chat_questions WHERE id = ?", q).Scan(&f.attempt, &f.account, &f.session, &f.runner, &f.base, &f.candidate); err != nil {
+ r.t.Fatal(err)
+ }
+ return f
+}
+
+// moveStep stands for any later path that moves a done Engineering step
+// on after a question was asked (no path does today: a done step's Retry
+// is a republish of the same attempt, and a fix round is a new step): a
+// new attempt on runner, with a new base, candidate, account and session.
+func (r *runnersRig) moveStep(step string, attempt int64, runner, base, cand string) {
+ r.t.Helper()
+ if _, err := r.inst.DB.Writer().Exec("UPDATE chat_steps SET attempt = ?, runner_id = ?, base_sha = ?, candidate_sha = ?, account = 'moved-account', session_id = 'moved-session' WHERE id = ?", attempt, runner, base, cand, step); err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+// askIs checks an ask command against what its question froze.
+func askIs(t *testing.T, a *wire.AskCommand, q, step string, attempt int64, account, session, base, cand string) {
+ t.Helper()
+ if a.QuestionID != q || a.StepID != step || a.Specialist != wire.SpecialistEngineering || a.EngAttempt != attempt || a.EngAccount != account || a.EngSession != session || a.BaseSHA != base || a.CandidateSHA != cand {
+ t.Fatalf("ask %+v, want %s on attempt %d (%s, %s) of %s..%s", a, q, attempt, account, session, base, cand)
+ }
+}
+
+// A question created after a newer attempt made the same candidate is
+// bound to the attempt it was asked about (the newer one: its account and
+// session), never found by its commit; the step moving on later does not
+// change the runner, base or candidate a waiting question goes to, and a
+// reply from the runner the step moved to is refused.
+func TestContractAskBindsTheSession(t *testing.T) {
+ r := newMacRig(t)
+ a := r.newMacEngineer("Tito Studio", wire.EngineeringReady)
+ base, cand := sha(1), sha(0xc1)
+ task, d1 := r.macDispatch(a, "iOS asked", base)
+ // Attempt 1 commits cand on one account, then fails.
+ if !a.lease(d1.StepID, 1) {
+ t.Fatal("start refused")
+ }
+ a.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d1.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "mac-c1", Findings: []wire.Finding{}})
+ a.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d1.StepID, Attempt: 1, State: wire.StepRunning, CandidateSHA: cand, Phase: wire.OutcomeCommitted, Findings: []wire.Finding{}})
+ a.expect(wire.FrameSendPack)
+ a.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d1.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true, TerminationKind: wire.TerminationProcessGroup, Account: "mac-c1", SessionID: "sess-1", Findings: []wire.Finding{}})
+ if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 {
+ t.Fatalf("retry %+v %v", acc, err)
+ }
+ _, body := a.expect(wire.FrameDispatch)
+ d2 := body.(*wire.DispatchCommand)
+ if d2.StepID != d1.StepID || d2.Attempt != 2 {
+ t.Fatalf("retry %+v", d2)
+ }
+ r.engineeringTransfer(a, d2)
+ // Attempt 2 makes the same commit, on another account, its session kept.
+ r.askableOn(a, d2, cand, "mac-c2", "sess-2")
+
+ q1, err := r.client.Ask(r.ctx, task, "What did you change?", "", "b1")
+ if err != nil || q1.StepID != d1.StepID {
+ t.Fatalf("ask %+v %v", q1, err)
+ }
+ want := frozen{2, "mac-c2", "sess-2", a.fr.Welcome.RunnerID, base, cand}
+ if got := r.frozenOf(q1.ID); got != want {
+ t.Fatalf("frozen %+v, want %+v", got, want)
+ }
+ _, body = a.expect(wire.FrameAsk)
+ askIs(t, body.(*wire.AskCommand), q1.ID, d1.StepID, 2, "mac-c2", "sess-2", base, cand)
+ r.primary.none(wire.FrameAsk, 0)
+ // A second question waits for the first.
+ q2, err := r.client.Ask(r.ctx, task, "And the tests?", "", "b2")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := r.frozenOf(q2.ID); got != want {
+ t.Fatalf("second frozen %+v, want %+v", got, want)
+ }
+
+ // The step moves on, to another Mac.
+ b := r.newMacEngineer("Mac B", wire.EngineeringReady)
+ r.moveStep(d1.StepID, 3, b.fr.Welcome.RunnerID, sha(9), sha(0xc9))
+ // Mac B's reply is refused; Mac A's is the answer.
+ b.send(wire.FrameAnswer, wire.AnswerReport{TaskID: task, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "Not mine."})
+ if q, _ := r.client.Question(r.ctx, q1.ID); q.State != wire.QuestionQueued || q.Answer != "" {
+ t.Fatalf("the other Mac answered: %+v", q)
+ }
+ a.send(wire.FrameAnswer, wire.AnswerReport{TaskID: task, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "The swipe."})
+ if q, _ := r.client.Question(r.ctx, q1.ID); q.State != wire.QuestionAnswered || q.Answer != "The swipe." {
+ t.Fatalf("answer %+v", q)
+ }
+ // The waiting question goes where it was asked, as it was asked.
+ _, body = a.expect(wire.FrameAsk)
+ askIs(t, body.(*wire.AskCommand), q2.ID, d1.StepID, 2, "mac-c2", "sess-2", base, cand)
+ b.none(wire.FrameAsk, 50*time.Millisecond)
+ r.primary.none(wire.FrameAsk, 0)
+ if got := r.frozenOf(q2.ID); got != want {
+ t.Fatalf("the move changed the question: %+v", got)
+ }
+}
+
+// Cancel, a reply and a reconnect's sync after the step moved to a new
+// attempt on another runner all address the runner and attempt the
+// question was frozen to.
+func TestContractQuestionLifecycleFrozen(t *testing.T) {
+ r := newMacRig(t)
+ a := r.newMacEngineer("Tito Studio", wire.EngineeringReady)
+ base, cand := sha(1), sha(0xc1)
+ task, d := r.macDispatch(a, "iOS lifecycle", base)
+ r.askableOn(a, d, cand, "mac-c1", "sess-1")
+ q1, err := r.client.Ask(r.ctx, task, "What did you change?", "", "l1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, body := a.expect(wire.FrameAsk)
+ askIs(t, body.(*wire.AskCommand), q1.ID, d.StepID, 1, "mac-c1", "sess-1", base, cand)
+ q2, err := r.client.Ask(r.ctx, task, "Why that way?", "", "l2")
+ if err != nil {
+ t.Fatal(err)
+ }
+ b := r.newMacEngineer("Mac B", wire.EngineeringReady)
+ r.moveStep(d.StepID, 2, b.fr.Welcome.RunnerID, sha(9), sha(0xc9))
+
+ // Cancel goes to Mac A, for the question's attempt.
+ if _, err := r.client.CancelQuestion(r.ctx, q1.ID); err != nil {
+ t.Fatal(err)
+ }
+ _, body = a.expect(wire.FrameCancelAsk)
+ if c := body.(*wire.CancelAskCommand); c.QuestionID != q1.ID || c.Attempt != 1 {
+ t.Fatalf("cancel_ask %+v", c)
+ }
+ b.none(wire.FrameCancelAsk, 50*time.Millisecond)
+ r.primary.none(wire.FrameCancelAsk, 0)
+ // Mac B cannot end it; Mac A does.
+ b.send(wire.FrameAnswer, wire.AnswerReport{TaskID: task, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionCancelled, Reason: "cancelled"})
+ if q, _ := r.client.Question(r.ctx, q1.ID); q.State != wire.QuestionQueued {
+ t.Fatalf("the other Mac ended it: %+v", q)
+ }
+ a.send(wire.FrameAnswer, wire.AnswerReport{TaskID: task, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionCancelled, Reason: "cancelled"})
+ if q, _ := r.client.Question(r.ctx, q1.ID); q.State != wire.QuestionCancelled {
+ t.Fatalf("cancelled %+v", q)
+ }
+ // The next question goes to Mac A, frozen.
+ _, body = a.expect(wire.FrameAsk)
+ askIs(t, body.(*wire.AskCommand), q2.ID, d.StepID, 1, "mac-c1", "sess-1", base, cand)
+ b.none(wire.FrameAsk, 0)
+ // Mac B's sync, which does not hold it, does not end it; Mac A's does.
+ b.send(wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}})
+ if q, _ := r.client.Question(r.ctx, q2.ID); q.State != wire.QuestionQueued {
+ t.Fatalf("the other Mac's sync ended it: %+v", q)
+ }
+ a.send(wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}})
+ r.wait("interrupted", func(c *Conversation) bool {
+ q := c.Questions[q2.ID]
+ return q.State == wire.QuestionFailed && q.Reason == "interrupted"
+ })
+}
+
+// Asking about a Mac-made step while that Mac is offline is answered at
+// once (runner_offline), even with the primary online, and nothing
+// queues; once the Mac is back, the question is asked of it.
+func TestContractAskMacOffline(t *testing.T) {
+ r := newMacRig(t)
+ a := r.newMacEngineer("Tito Studio", wire.EngineeringReady)
+ base, cand := sha(1), sha(0xc1)
+ task, d := r.macDispatch(a, "iOS offline", base)
+ r.askableOn(a, d, cand, "mac-c1", "sess-1")
+ a.fr.Close()
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ rs, err := r.client.Runners(context.Background())
+ online := map[string]bool{}
+ for _, x := range rs.Items {
+ online[x.ID] = x.Online
+ }
+ if err == nil && !online[a.fr.Welcome.RunnerID] && online[r.primary.fr.Welcome.RunnerID] {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("Mac still online: %+v %v", rs, err)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ if _, err := r.client.Ask(r.ctx, task, "What did you change?", "", "o1"); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "runner_offline") {
+ t.Fatalf("ask of an offline Mac: %v", err)
+ }
+ if k := r.task(task); len(k.Questions) != 0 {
+ t.Fatalf("a question queued for an offline Mac: %+v", k.Questions)
+ }
+ r.primary.none(wire.FrameAsk, 0)
+ if n := r.mailbox(a.fr.Welcome.RunnerID, wire.FrameAsk); n != 0 {
+ t.Fatalf("%d asks wait for the offline Mac", n)
+ }
+ c := r.creds[a.fr]
+ wh := macEngineerHello(c[1], wire.EngineeringReady, wire.ProtocolMacEngineering, false)
+ wh.Generation = a.fr.Welcome.Generation
+ fr, err := DialRunnerHello(r.ctx, r.inst.URL, c[0], wh)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(fr.Close)
+ back := &peer{t: t, r: r.toolRig, fr: fr}
+ q, err := r.client.Ask(r.ctx, task, "What did you change?", "", "o2")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, body := back.expect(wire.FrameAsk)
+ askIs(t, body.(*wire.AskCommand), q.ID, d.StepID, 1, "mac-c1", "sess-1", base, cand)
+}