oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package wire_test
2
3import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "slices"
8 "strings"
9 "testing"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/wire"
13 "amadan.net/oficina/equipo/internal/wire/wiretest"
14)
15
16// Every frame protocol 2 changes, encoded for a protocol 1 runner, is
17// exactly the slice 4 frame: the same keys as the slice 4 fixture, and a
18// slice 4 strict decoder (the v1 fixture's own key set) accepts it.
19func TestEncodeProtocol1IsTheSlice4Wire(t *testing.T) {
20 for v2, v1 := range map[string]string{
21 "frames/hello-mac.json": "frames/hello.json",
22 "frames/welcome-worker.json": "frames/welcome.json",
23 "frames/dispatch-needs.json": "frames/dispatch.json",
24 "frames/lease-step.json": "frames/lease.json",
25 "frames/step-process-group.json": "frames/step.json",
26 "frames/hello-mac-probes.json": "frames/hello.json",
27 "frames/step-mac-checks.json": "frames/step.json",
28 "frames/welcome-tainted.json": "frames/welcome.json",
29 } {
30 f, _, err := wire.ParseFrame(wiretest.Fixture(v2))
31 if err != nil {
32 t.Fatalf("%s: %v", v2, err)
33 }
34 same, err := wire.Encode(f, wire.Protocol2)
35 if err != nil || !bytes.Equal(same.Data, f.Data) {
36 t.Fatalf("%s: protocol 2 changed the frame: %v", v2, err)
37 }
38 old, err := wire.Encode(f, wire.Protocol1)
39 if err != nil {
40 t.Fatalf("%s at protocol 1: %v", v2, err)
41 }
42 raw, _ := json.Marshal(old)
43 if err := wiretest.SameShape(wiretest.Fixture(v1), raw); err != nil {
44 t.Fatalf("%s at protocol 1 is not the slice 4 %s: %v\n%s", v2, v1, err, raw)
45 }
46 if _, _, err := wire.ParseFrame(raw); err != nil {
47 t.Fatalf("%s at protocol 1 does not parse: %v", v2, err)
48 }
49 }
50 // The protocol 1 fixtures themselves pass through unchanged.
51 for _, name := range []string{"frames/hello.json", "frames/welcome.json", "frames/dispatch.json", "frames/lease.json", "frames/step.json", "frames/message.json"} {
52 f, _, err := wire.ParseFrame(wiretest.Fixture(name))
53 if err != nil {
54 t.Fatal(err)
55 }
56 out, err := wire.Encode(f, wire.Protocol1)
57 raw, _ := json.Marshal(out)
58 if err != nil || !bytes.Equal(raw, wiretest.Fixture(name)) {
59 t.Fatalf("%s changed at protocol 1: %v\n%s", name, err, raw)
60 }
61 }
62}
63
64// Frames protocol 1 does not have are never encoded for it.
65// TestWireProtocol3Downgrade: a ProtocolMergeFacts frame is unchanged
66// there; one protocol below it is exactly its protocol 2 shape (the merge_request purpose, change
67// facts, merge provenance and revert target dropped), and at 1 the slice
68// 4 shape. An old peer's strict decoder never meets a field it refuses.
69func TestWireProtocol3Downgrade(t *testing.T) {
70 for v3, v2 := range map[string]string{
71 "frames/lease-merge.json": "frames/lease-step.json",
72 "frames/step-review-facts.json": "frames/step.json",
73 "frames/step-merged-hub.json": "frames/step.json",
74 "frames/dispatch-revert.json": "frames/dispatch-needs.json",
75 } {
76 f, _, err := wire.ParseFrame(wiretest.Fixture(v3))
77 if err != nil {
78 t.Fatalf("%s: %v", v3, err)
79 }
80 same, err := wire.Encode(f, wire.ProtocolMergeFacts)
81 if err != nil || !bytes.Equal(same.Data, f.Data) {
82 t.Fatalf("%s: protocol 3 changed the frame: %v", v3, err)
83 }
84 two, err := wire.Encode(f, wire.ProtocolMergeFacts-1)
85 if err != nil {
86 t.Fatal(err)
87 }
88 raw, _ := json.Marshal(two)
89 if err := wiretest.SameShape(wiretest.Fixture(v2), raw); err != nil {
90 t.Fatalf("%s at protocol 2 is not %s: %v\n%s", v3, v2, err, raw)
91 }
92 for _, field := range []string{"purpose", "change", "merge_source", "merge_parents", "revert_sha"} {
93 if bytes.Contains(two.Data, []byte(`"`+field+`"`)) {
94 t.Fatalf("%s kept %s at protocol 2", v3, field)
95 }
96 }
97 one, err := wire.Encode(f, wire.Protocol1)
98 if err != nil {
99 t.Fatal(err)
100 }
101 if bytes.Contains(one.Data, []byte(`"purpose"`)) || bytes.Contains(one.Data, []byte(`"change"`)) || bytes.Contains(one.Data, []byte(`"revert_sha"`)) {
102 t.Fatalf("%s kept a protocol 3 field at protocol 1: %s", v3, one.Data)
103 }
104 }
105}
106
107func TestEncodeProtocol1RefusesNewFrames(t *testing.T) {
108 for _, name := range []string{"frames/blob.json", "frames/send_pack.json", "frames/publish.json", "frames/published.json", "frames/refused.json"} {
109 f, _, err := wire.ParseFrame(wiretest.Fixture(name))
110 if err != nil {
111 t.Fatal(err)
112 }
113 if _, err := wire.Encode(f, wire.Protocol1); !errors.Is(err, wire.ErrProtocol) {
114 t.Fatalf("%s encoded at protocol 1: %v", name, err)
115 }
116 if _, err := wire.Encode(f, wire.Protocol2); err != nil {
117 t.Fatalf("%s at protocol 2: %v", name, err)
118 }
119 }
120}
121
122func TestProtocolNegotiation(t *testing.T) {
123 if wire.HelloProtocol(wire.Hello{}) != 1 || wire.HelloProtocol(wire.Hello{Protocol: 2}) != 2 {
124 t.Fatal("hello protocol")
125 }
126 if wire.Spoken(1) != 1 || wire.Spoken(2) != 2 || wire.Spoken(9) != 9 || wire.Spoken(99) != wire.ProtocolCurrent || wire.Spoken(0) != 1 {
127 t.Fatal("spoken protocol is not the lower of the two")
128 }
129}
130
131func TestDurableRunnerFrames(t *testing.T) {
132 for kind, want := range map[string]bool{wire.FrameBlob: true, wire.FrameSendPack: true, wire.FramePublish: true, wire.FramePublished: true, wire.FrameRefused: false} {
133 if (wire.Frame{Type: kind}).Durable() != want {
134 t.Fatalf("%s durable=%v", kind, !want)
135 }
136 }
137}
138
139// The capability report carries no path, credential or tool output, and
140// stays inside its bounds: every string field is checked.
141func TestCapabilitiesGuard(t *testing.T) {
142 _, body, err := wire.ParseFrame(wiretest.Fixture("frames/hello-mac.json"))
143 if err != nil {
144 t.Fatal(err)
145 }
146 good := *body.(*wire.Hello).Capabilities
147 if err := wire.ValidCapabilities(good); err != nil {
148 t.Fatalf("fixture refused: %v", err)
149 }
150 if _, probed, err := wire.ParseFrame(wiretest.Fixture("frames/hello-mac-probes.json")); err != nil || wire.ValidCapabilities(*probed.(*wire.Hello).Capabilities) != nil {
151 t.Fatalf("probe report fixture refused: %v", err)
152 }
153 if err := wire.ValidCapabilities(wire.Capabilities{}); err != nil {
154 t.Fatalf("empty report refused: %v", err)
155 }
156 clone := func() wire.Capabilities {
157 raw, _ := json.Marshal(good)
158 var c wire.Capabilities
159 _ = json.Unmarshal(raw, &c)
160 return c
161 }
162 for name, bad := range map[string]func(*wire.Capabilities){
163 "path in xcode": func(c *wire.Capabilities) { c.Xcode.Version = "/Applications/Xcode.app" },
164 "home path": func(c *wire.Capabilities) { c.Toolchains.Go = "~/go/bin/go" },
165 "windows path": func(c *wire.Capabilities) { c.Harness.Claude = `C:\claude` },
166 "raw output": func(c *wire.Capabilities) { c.Xcode.Build = "Build version 16C5032a\nXcode 16.2" },
167 "credential shaped": func(c *wire.Capabilities) { c.Harness.Codex = "OPENAI_API_KEY=sk-x" },
168 "long string": func(c *wire.Capabilities) { c.Simulators[0].Name = strings.Repeat("i", wire.MaxCapabilityString+1) },
169 "path in simulator": func(c *wire.Capabilities) { c.Simulators[0].Runtime = "/Library/Developer/CoreSimulator" },
170 "unknown tag": func(c *wire.Capabilities) { c.Tags = append(c.Tags, "gpu") },
171 "too many simulators": func(c *wire.Capabilities) { c.Simulators = make([]wire.Simulator, wire.MaxSimulators+1) },
172 "over the total bound": func(c *wire.Capabilities) { c.Simulators = bigSimulators() },
173 "path in a probe": func(c *wire.Capabilities) {
174 c.Probes = []wire.Probe{{ID: "P4", Verdict: wire.ProbeFailed, Detail: "readable: /Users/paul"}}
175 },
176 "unknown probe": func(c *wire.Capabilities) { c.Probes = []wire.Probe{{ID: "P8", Verdict: wire.ProbePassed}} },
177 "probe twice": func(c *wire.Capabilities) {
178 c.Probes = []wire.Probe{{ID: "P1", Verdict: wire.ProbePassed}, {ID: "P1", Verdict: wire.ProbeFailed}}
179 },
180 "unknown verdict": func(c *wire.Capabilities) { c.Probes = []wire.Probe{{ID: "P2", Verdict: "ok"}} },
181 "denied is P2 only": func(c *wire.Capabilities) { c.Probes = []wire.Probe{{ID: "P4", Verdict: wire.ProbeDenied}} },
182 } {
183 c := clone()
184 bad(&c)
185 if err := wire.ValidCapabilities(c); !errors.Is(err, wire.ErrCapabilities) {
186 t.Fatalf("%s accepted", name)
187 }
188 }
189}
190
191func bigSimulators() []wire.Simulator {
192 out := make([]wire.Simulator, wire.MaxSimulators)
193 for i := range out {
194 out[i] = wire.Simulator{Name: strings.Repeat("n", 250), Runtime: "iOS 18.2", UDID: strings.Repeat("u", 36), State: "Shutdown"}
195 }
196 return out
197}
198
199func TestCovers(t *testing.T) {
200 if !wire.Covers([]string{"macos", "xcode"}, nil) || !wire.Covers([]string{"macos", "xcode"}, []string{"xcode"}) || wire.Covers([]string{"linux"}, []string{"macos"}) {
201 t.Fatal("covers")
202 }
203}
204
205// Protocol 3 adds a fix round's feedback (instance to runner) and the
206// turns of a usage row (runner to instance). Encoded for a protocol 2 or
207// 1 peer, whose strict decoder knows neither, they are gone and nothing
208// else changes; a frame without them is passed through as it is.
209func TestEncodeProtocol2DropsProtocol3Fields(t *testing.T) {
210 n := int64(4)
211 row := func(turns *int64) []wire.Usage {
212 return []wire.Usage{{Provider: "claude", Connection: "c1", Model: "m", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, Turns: turns}}
213 }
214 for _, c := range []struct {
215 kind string
216 new, prev any
217 }{
218 {wire.FrameDispatch, wire.DispatchCommand{TaskID: "tk", Round: 1, Brief: "Fix round 1 of 2.", Findings: []wire.Finding{}, Feedback: "Fix round 1 of 2."}, wire.DispatchCommand{TaskID: "tk", Round: 1, Brief: "Fix round 1 of 2.", Findings: []wire.Finding{}}},
219 {wire.FrameStep, wire.StepReport{TaskID: "tk", Findings: []wire.Finding{}, Usage: row(&n)}, wire.StepReport{TaskID: "tk", Findings: []wire.Finding{}, Usage: row(nil)}},
220 {wire.FrameAnswer, wire.AnswerReport{TaskID: "tk", Usage: row(&n)}, wire.AnswerReport{TaskID: "tk", Usage: row(nil)}},
221 {wire.FrameReply, wire.Reply{TurnID: "t", Usage: row(&n)}, wire.Reply{TurnID: "t", Usage: row(nil)}},
222 {wire.FrameUsage, wire.UsageReport{StepID: "s", Rows: row(&n)}, wire.UsageReport{StepID: "s", Rows: row(nil)}},
223 } {
224 f, err := wire.NewFrame("f1", c.kind, c.new)
225 if err != nil {
226 t.Fatal(err)
227 }
228 want, _ := wire.NewFrame("f1", c.kind, c.prev)
229 if same, err := wire.Encode(f, wire.ProtocolSpend); err != nil || !bytes.Equal(same.Data, f.Data) {
230 t.Fatalf("%s changed at protocol 3: %v", c.kind, err)
231 }
232 for _, p := range []int{wire.Protocol2, wire.Protocol1} {
233 old, err := wire.Encode(f, p)
234 if err != nil {
235 t.Fatal(err)
236 }
237 if !bytes.Equal(old.Data, want.Data) {
238 t.Fatalf("%s at protocol %d:\n got %s\nwant %s", c.kind, p, old.Data, want.Data)
239 }
240 }
241 // Without the new fields, a protocol 2 frame is untouched.
242 if same, err := wire.Encode(want, wire.Protocol2); err != nil || !bytes.Equal(same.Data, want.Data) {
243 t.Fatalf("%s without protocol 3 fields changed at protocol 2: %v", c.kind, err)
244 }
245 }
246}
247
248// Protocol 5 (hosted checks) adds the dispatch's offer of hosted CI and
249// a checks report's hosted binding. Encoded for an older peer, whose
250// strict decoder knows neither, the offer is gone and a hosted verdict
251// becomes checks that could not run: never a pass an old instance would
252// take without its binding. At protocol 5 both pass through.
253func TestEncodeBelowProtocol5DropsHostedChecks(t *testing.T) {
254 hosted := &wire.HostedResult{Repo: "amadan.net/oficina/sample", Branch: "equipo/tk-fix", SHA: strings.Repeat("2", 40), State: wire.HostedSuccess, ReportedAt: 1794402264, Failed: []string{}}
255 code := 0
256 for _, c := range []struct {
257 kind string
258 new, prev any
259 }{
260 {wire.FrameDispatch, wire.DispatchCommand{TaskID: "tk", Specialist: wire.SpecialistChecks, Findings: []wire.Finding{}, HostedChecks: true}, wire.DispatchCommand{TaskID: "tk", Specialist: wire.SpecialistChecks, Findings: []wire.Finding{}}},
261 {wire.FrameStep, wire.StepReport{TaskID: "tk", State: wire.StepDone, Findings: []wire.Finding{}, Checks: wire.ChecksPassed, Gate: wire.GateHosted, ExitCode: &code, Output: "Hosted CI passed.", Hosted: hosted}, wire.StepReport{TaskID: "tk", State: wire.StepDone, Findings: []wire.Finding{}, Checks: wire.ChecksCannotRun, Reason: "checks_unavailable", Output: "Hosted CI passed."}},
262 } {
263 f, err := wire.NewFrame("f1", c.kind, c.new)
264 if err != nil {
265 t.Fatal(err)
266 }
267 if same, err := wire.Encode(f, wire.ProtocolHostedChecks); err != nil || !bytes.Equal(same.Data, f.Data) {
268 t.Fatalf("%s changed at protocol 5: %v", c.kind, err)
269 }
270 want, _ := wire.NewFrame("f1", c.kind, c.prev)
271 for _, p := range []int{wire.ProtocolMergeFacts, wire.ProtocolSpend, wire.Protocol2, wire.Protocol1} {
272 old, err := wire.Encode(f, p)
273 if err != nil {
274 t.Fatal(err)
275 }
276 if p >= wire.Protocol2 && !bytes.Equal(old.Data, want.Data) {
277 t.Fatalf("%s at protocol %d:\n got %s\nwant %s", c.kind, p, old.Data, want.Data)
278 }
279 var body any = &wire.DispatchCommand{}
280 if c.kind == wire.FrameStep {
281 body = &wire.StepReport{}
282 }
283 if err := wire.Strict(old.Data, body); err != nil {
284 t.Fatalf("%s at protocol %d does not decode: %v", c.kind, p, err)
285 }
286 if strings.Contains(string(old.Data), `"hosted"`) || strings.Contains(string(old.Data), "hosted_checks") || strings.Contains(string(old.Data), wire.GateHosted) {
287 t.Fatalf("%s at protocol %d still says hosted: %s", c.kind, p, old.Data)
288 }
289 }
290 }
291}
292
293// Protocol 6 says a reachable repository is empty (no commits yet). An
294// older instance's strict decoder knows no "empty", and to it an empty
295// repository was never in the catalog: below protocol 6 its entry is
296// gone, every other entry is as it was, and a hello without one is sent
297// unchanged. WithoutEmptyRepos is the same cut, for a hello sent before
298// the instance has said which protocol it speaks.
299func TestEncodeBelowProtocol6DropsEmptyRepos(t *testing.T) {
300 full := wire.RepoInfo{Repo: "amadan.net/oficina/sample", DefaultBranch: "main", Names: []string{"sample"}, Hints: []string{}}
301 empty := wire.RepoInfo{Repo: "amadan.net/paulca/threatmin", Names: []string{"threatmin"}, Hints: []string{}, Empty: true}
302 hello := wire.Hello{Repos: []string{full.Repo, empty.Repo}, CreateIn: []string{}, Catalog: []wire.RepoInfo{full, empty}, Connections: []wire.HeldConnection{}, Protocol: wire.ProtocolCurrent}
303 f, err := wire.NewFrame("h1", wire.FrameHello, hello)
304 if err != nil {
305 t.Fatal(err)
306 }
307 if !strings.Contains(string(f.Data), `"empty":true`) {
308 t.Fatalf("the empty mark is not on the wire: %s", f.Data)
309 }
310 if same, err := wire.Encode(f, wire.ProtocolEmptyRepos); err != nil || !bytes.Equal(same.Data, f.Data) {
311 t.Fatalf("changed at protocol 6: %v", err)
312 }
313 for _, p := range []int{wire.ProtocolHostedChecks, wire.ProtocolMergeFacts, wire.ProtocolSpend, wire.Protocol2, wire.Protocol1} {
314 old, err := wire.Encode(f, p)
315 if err != nil {
316 t.Fatal(err)
317 }
318 var h wire.Hello
319 if err := wire.Strict(old.Data, &h); err != nil {
320 t.Fatalf("protocol %d does not decode: %v", p, err)
321 }
322 if strings.Contains(string(old.Data), `"empty"`) || len(h.Catalog) != 1 || h.Catalog[0].Repo != full.Repo || len(h.Repos) != 2 {
323 t.Fatalf("protocol %d: %s", p, old.Data)
324 }
325 }
326 plain, _ := wire.NewFrame("h2", wire.FrameHello, wire.Hello{Repos: []string{full.Repo}, CreateIn: []string{}, Catalog: []wire.RepoInfo{full}, Connections: []wire.HeldConnection{}, Protocol: wire.ProtocolCurrent})
327 if old, err := wire.Encode(plain, wire.ProtocolHostedChecks); err != nil || !bytes.Equal(old.Data, plain.Data) {
328 t.Fatalf("a hello without an empty repository changed: %v", err)
329 }
330 cut := hello
331 cut.Catalog = append([]wire.RepoInfo(nil), hello.Catalog...)
332 if !wire.WithoutEmptyRepos(&cut) || len(cut.Catalog) != 1 || cut.Catalog[0].Repo != full.Repo || len(hello.Catalog) != 2 {
333 t.Fatalf("handshake cut %+v", cut.Catalog)
334 }
335 if wire.WithoutEmptyRepos(&cut) {
336 t.Fatal("a second cut reported a change")
337 }
338 if wire.ProtocolPreview != 9 || wire.ProtocolEmptyMerge != 8 || wire.ProtocolSandboxConsent != 7 || wire.ProtocolEmptyRepos != 6 || wire.ProtocolHostedChecks != 5 {
339 t.Fatalf("current protocol %d", wire.ProtocolCurrent)
340 }
341}
342
343// Protocol 7 carries the person's choice to run a Mac's checks outside
344// the sandbox, and the worker's refusal without it. Below 7 the choice is
345// gone (an older peer is never consent) and the refusal is
346// placement_refused, which an older instance places elsewhere: never a
347// failure, never a taint. Other reasons and dispatches are unchanged.
348func TestEncodeBelowProtocol7DropsSandboxConsent(t *testing.T) {
349 d, _ := wire.NewFrame("c1", wire.FrameDispatch, wire.DispatchCommand{TaskID: "tk1", StepID: "s1", Attempt: 2, Specialist: wire.SpecialistChecks, Findings: []wire.Finding{}, Unsandboxed: true})
350 if same, err := wire.Encode(d, wire.ProtocolSandboxConsent); err != nil || !bytes.Equal(same.Data, d.Data) || !strings.Contains(string(d.Data), `"unsandboxed":true`) {
351 t.Fatalf("changed at protocol 7: %s %v", d.Data, err)
352 }
353 for _, p := range []int{wire.ProtocolEmptyRepos, wire.ProtocolHostedChecks, wire.Protocol2} {
354 old, err := wire.Encode(d, p)
355 if err != nil || strings.Contains(string(old.Data), "unsandboxed") {
356 t.Fatalf("protocol %d dispatch: %s %v", p, old.Data, err)
357 }
358 }
359 r, _ := wire.NewFrame("p1", wire.FrameStep, wire.StepReport{TaskID: "tk1", StepID: "s1", Attempt: 2, State: wire.StepFailed, Reason: wire.ReasonSandboxUnproven, Termination: true, Findings: []wire.Finding{}})
360 old, err := wire.Encode(r, wire.ProtocolEmptyRepos)
361 var rep wire.StepReport
362 if err != nil || wire.Strict(old.Data, &rep) != nil || rep.Reason != "placement_refused" || rep.State != wire.StepFailed || !rep.Termination {
363 t.Fatalf("refusal at protocol 6: %s %v", old.Data, err)
364 }
365 if !wire.StepReasons[wire.ReasonSandboxUnproven] {
366 t.Fatal("protocol 7 instance does not know the refusal")
367 }
368 other, _ := wire.NewFrame("p2", wire.FrameStep, wire.StepReport{TaskID: "tk1", StepID: "s1", Attempt: 2, State: wire.StepFailed, Reason: "runner_restarted", Termination: true, Findings: []wire.Finding{}})
369 if same, err := wire.Encode(other, wire.ProtocolEmptyRepos); err != nil || !bytes.Equal(same.Data, other.Data) {
370 t.Fatalf("another reason changed: %v", err)
371 }
372}
373
374// Protocol 9 (previews) adds Review's has_preview, a preview step's
375// result and the publish check's digest. Below 9 they are gone, the frame
376// decodes strictly, and a preview dispatch is never encoded at all: an
377// older runner cannot be handed a preview to run. Protocol 8 is the
378// empty-repository merge, which a peer at 8 speaks without previews.
379func TestEncodeBelowProtocol9DropsPreviews(t *testing.T) {
380 when := time.Date(2026, 11, 18, 16, 0, 0, 0, time.UTC)
381 for _, c := range []struct {
382 kind string
383 new, prev any
384 decode any
385 }{
386 {wire.FrameStep, wire.StepReport{TaskID: "tk", Findings: []wire.Finding{}, Verdict: wire.VerdictApprove, HasPreview: true, Preview: &wire.PreviewResult{Phase: wire.PreviewBuilt, Digest: strings.Repeat("d", 64), Files: 3, Bytes: 10, ExpiresAt: &when}}, wire.StepReport{TaskID: "tk", Findings: []wire.Finding{}, Verdict: wire.VerdictApprove}, &wire.StepReport{}},
387 {wire.FrameLease, wire.LeaseCheck{StepID: "s", Attempt: 1, Purpose: wire.LeasePurposePreview, Digest: strings.Repeat("d", 64)}, wire.LeaseCheck{StepID: "s", Attempt: 1, Purpose: wire.LeasePurposePreview}, &wire.LeaseCheck{}},
388 } {
389 f, err := wire.NewFrame("f1", c.kind, c.new)
390 if err != nil {
391 t.Fatal(err)
392 }
393 if same, err := wire.Encode(f, wire.ProtocolPreview); err != nil || !bytes.Equal(same.Data, f.Data) {
394 t.Fatalf("%s changed at protocol 9: %v", c.kind, err)
395 }
396 want, _ := wire.NewFrame("f1", c.kind, c.prev)
397 for _, p := range []int{wire.ProtocolEmptyMerge, wire.ProtocolSandboxConsent} {
398 old, err := wire.Encode(f, p)
399 if err != nil || !bytes.Equal(old.Data, want.Data) {
400 t.Fatalf("%s at protocol %d: %v\n got %s\nwant %s", c.kind, p, err, old.Data, want.Data)
401 }
402 if err := wire.Strict(old.Data, c.decode); err != nil {
403 t.Fatalf("%s at protocol %d does not decode: %v", c.kind, p, err)
404 }
405 }
406 }
407 d, _ := wire.NewFrame("f2", wire.FrameDispatch, wire.DispatchCommand{TaskID: "tk", Specialist: wire.SpecialistPreview, Findings: []wire.Finding{}})
408 for _, p := range []int{wire.ProtocolEmptyMerge, wire.ProtocolSandboxConsent} {
409 if _, err := wire.Encode(d, p); !errors.Is(err, wire.ErrProtocol) {
410 t.Fatalf("a preview dispatch encoded at protocol %d: %v", p, err)
411 }
412 }
413 if _, err := wire.Encode(d, wire.ProtocolPreview); err != nil {
414 t.Fatal(err)
415 }
416 if wire.ProtocolCurrent != wire.ProtocolDesign || wire.ProtocolDesign != 38 || wire.ProtocolMacEngineering != 37 || wire.ProtocolLookup != 36 || wire.ProtocolChangeDiffs != 35 || wire.ProtocolPlaces != 34 || wire.ProtocolAssistantFiles != 33 || wire.ProtocolStuckTasks != 30 || wire.ProtocolPinnedRelease != 29 || wire.ProtocolInjectionDefences != 28 || wire.ProtocolWarm != 24 || wire.ProtocolGlance != 23 || wire.ProtocolJobs != 22 || wire.ProtocolCopy != 21 || wire.ProtocolUsageRefresh != 20 || wire.ProtocolAssistant != 19 || wire.ProtocolModels != 18 || wire.ProtocolOpenCode != 17 || wire.ProtocolPublish != 16 || wire.ProtocolReadings != 15 || wire.ProtocolScheduler != 14 || wire.ProtocolResearch != 13 || wire.ProtocolMetered != 12 || wire.ProtocolPreviewHost != 11 || wire.ProtocolExplore != 10 || wire.ProtocolPreview != 9 {
417 t.Fatalf("current %d", wire.ProtocolCurrent)
418 }
419}
420
421// Protocol 8 says the hub refused a merge step because the repository's
422// default branch is unborn and the hub cannot make the first merge yet
423// (merge_unborn_default). An older instance knows no such reason: below
424// protocol 8 it is merge_failed, the hub's other refusals' reason, and a
425// report with any other reason is sent unchanged.
426func TestEncodeBelowProtocol8SaysMergeFailed(t *testing.T) {
427 if !wire.StepReasons[wire.ReasonMergeUnbornDefault] || wire.ReasonMergeUnbornDefault != "merge_unborn_default" {
428 t.Fatal("the reason is not a step reason")
429 }
430 rep := wire.StepReport{TaskID: "tk", StepID: "s", Attempt: 1, State: wire.StepFailed, Reason: wire.ReasonMergeUnbornDefault, CandidateSHA: strings.Repeat("a", 40), Findings: []wire.Finding{}, Termination: true}
431 f, err := wire.NewFrame("f1", wire.FrameStep, rep)
432 if err != nil {
433 t.Fatal(err)
434 }
435 if same, err := wire.Encode(f, wire.ProtocolEmptyMerge); err != nil || !bytes.Equal(same.Data, f.Data) {
436 t.Fatalf("changed at protocol 8: %v", err)
437 }
438 for _, p := range []int{wire.ProtocolSandboxConsent, wire.ProtocolEmptyRepos, wire.ProtocolMergeFacts, wire.Protocol2} {
439 old, err := wire.Encode(f, p)
440 if err != nil {
441 t.Fatal(err)
442 }
443 var got wire.StepReport
444 if err := wire.Strict(old.Data, &got); err != nil || got.Reason != "merge_failed" || strings.Contains(string(old.Data), "unborn") {
445 t.Fatalf("protocol %d: %s %v", p, old.Data, err)
446 }
447 }
448 other := rep
449 other.Reason = "merge_conflict"
450 g, _ := wire.NewFrame("f2", wire.FrameStep, other)
451 if old, err := wire.Encode(g, wire.ProtocolSandboxConsent); err != nil || !bytes.Equal(old.Data, g.Data) {
452 t.Fatalf("another reason changed: %v", err)
453 }
454 if wire.ProtocolEmptyMerge != 8 || wire.ProtocolCurrent <= wire.ProtocolEmptyMerge {
455 t.Fatalf("current protocol %d", wire.ProtocolCurrent)
456 }
457}
458
459// Protocols 8 (empty-repository merge) and 9 (previews) coexist, and
460// Encode chains their downgrades in front of every older one: at 9 a step
461// report keeps both its preview and the unborn-default reason; at 8 the
462// preview is gone and a preview dispatch is refused, but the reason
463// survives; at 7 both are downgraded.
464func TestEncodeChainsPreviewsAndEmptyMerge(t *testing.T) {
465 when := time.Date(2026, 11, 18, 16, 0, 0, 0, time.UTC)
466 rep := wire.StepReport{TaskID: "tk", StepID: "s", Attempt: 1, State: wire.StepFailed, Reason: wire.ReasonMergeUnbornDefault, Findings: []wire.Finding{}, HasPreview: true, Preview: &wire.PreviewResult{Phase: wire.PreviewBuilt, Digest: strings.Repeat("d", 64), Files: 3, Bytes: 10, ExpiresAt: &when}}
467 f, err := wire.NewFrame("f1", wire.FrameStep, rep)
468 if err != nil {
469 t.Fatal(err)
470 }
471 decode := func(p int) wire.StepReport {
472 t.Helper()
473 out, err := wire.Encode(f, p)
474 if err != nil {
475 t.Fatalf("protocol %d: %v", p, err)
476 }
477 var got wire.StepReport
478 if err := wire.Strict(out.Data, &got); err != nil {
479 t.Fatalf("protocol %d does not decode: %v", p, err)
480 }
481 return got
482 }
483 if got := decode(wire.Protocol9); !got.HasPreview || got.Preview == nil || got.Preview.Digest != rep.Preview.Digest || got.Reason != wire.ReasonMergeUnbornDefault {
484 t.Fatalf("protocol 9 lost a field: %+v", got)
485 }
486 if got := decode(wire.Protocol8); got.HasPreview || got.Preview != nil || got.Reason != wire.ReasonMergeUnbornDefault {
487 t.Fatalf("protocol 8: %+v", got)
488 }
489 if got := decode(wire.Protocol7); got.HasPreview || got.Preview != nil || got.Reason != "merge_failed" {
490 t.Fatalf("protocol 7: %+v", got)
491 }
492 lease, _ := wire.NewFrame("f2", wire.FrameLease, wire.LeaseCheck{StepID: "s", Attempt: 1, Purpose: wire.LeasePurposePreview, Digest: strings.Repeat("d", 64)})
493 if out, err := wire.Encode(lease, wire.Protocol9); err != nil || !bytes.Equal(out.Data, lease.Data) {
494 t.Fatalf("lease check changed at protocol 9: %v", err)
495 }
496 if out, err := wire.Encode(lease, wire.Protocol8); err != nil || strings.Contains(string(out.Data), "digest") {
497 t.Fatalf("lease check kept its digest at protocol 8: %s %v", out.Data, err)
498 }
499 d, _ := wire.NewFrame("f3", wire.FrameDispatch, wire.DispatchCommand{TaskID: "tk", Specialist: wire.SpecialistPreview, Findings: []wire.Finding{}})
500 if _, err := wire.Encode(d, wire.Protocol9); err != nil {
501 t.Fatalf("a preview dispatch refused at protocol 9: %v", err)
502 }
503 for _, p := range []int{wire.Protocol8, wire.Protocol7} {
504 if _, err := wire.Encode(d, p); !errors.Is(err, wire.ErrProtocol) {
505 t.Fatalf("a preview dispatch encoded at protocol %d: %v", p, err)
506 }
507 }
508}
509
510// TestWireExploreDowngrade: below ProtocolExplore a hello loses its
511// previews capability and record_task its kind when it says change; a
512// kind that says explore is kept, so an older instance's strict decoder
513// refuses the call and an exploration never becomes a change. At 10
514// everything passes unchanged; other tools are never touched.
515func TestWireExploreDowngrade(t *testing.T) {
516 hello := wire.Hello{Repos: []string{}, CreateIn: []string{}, Connections: []wire.HeldConnection{}, Protocol: wire.ProtocolCurrent, Capabilities: &wire.Capabilities{Simulators: []wire.Simulator{}, Tags: []string{wire.TagLinux}, Previews: true}}
517 change := wire.ToolCall{CallID: "c", TurnID: "t", Attempt: 1, Name: wire.ToolRecordTask, Args: json.RawMessage(`{"repo":"oficina/sample","title":"Fix","brief":"b","kind":"change"}`)}
518 explore := wire.ToolCall{CallID: "e", TurnID: "t", Attempt: 1, Name: wire.ToolRecordTask, Args: json.RawMessage(`{"repo":"oficina/sample","title":"Mockups","brief":"b","kind":"explore"}`)}
519 other := wire.ToolCall{CallID: "d", TurnID: "t", Attempt: 1, Name: wire.ToolAddFinding, Args: json.RawMessage(`{"task":"tk1","kind":"x"}`)}
520 enc := func(kind string, body any, p int) string {
521 t.Helper()
522 f, _ := wire.NewFrame("f", kind, body)
523 e, err := wire.Encode(f, p)
524 if err != nil {
525 t.Fatal(err)
526 }
527 return string(e.Data)
528 }
529 for _, p := range []int{wire.ProtocolExplore, wire.ProtocolPreview, wire.ProtocolMergeFacts, wire.Protocol2} {
530 keep := p >= wire.ProtocolExplore
531 if got := strings.Contains(enc(wire.FrameHello, hello, p), `"previews":true`); got != keep {
532 t.Fatalf("protocol %d: hello previews %t", p, got)
533 }
534 if got := enc(wire.FrameToolCall, change, p); strings.Contains(got, `"kind"`) != keep || !strings.Contains(got, `"title":"Fix"`) {
535 t.Fatalf("protocol %d: a change's kind: %s", p, got)
536 }
537 if got := enc(wire.FrameToolCall, explore, p); !strings.Contains(got, `"kind":"explore"`) {
538 t.Fatalf("protocol %d: an exploration's kind was dropped: %s", p, got)
539 }
540 if got := enc(wire.FrameToolCall, other, p); !strings.Contains(got, `"kind":"x"`) {
541 t.Fatalf("protocol %d: another tool changed: %s", p, got)
542 }
543 }
544 // The first hello, before the welcome: never the capability, and the
545 // caller's copy is untouched.
546 first := hello
547 if !wire.WithoutPreviews(&first) || first.Capabilities.Previews || !hello.Capabilities.Previews || wire.WithoutPreviews(&first) {
548 t.Fatal("first hello cut")
549 }
550 // A preview-step refusal below 9 and the explore drop below 10 both
551 // say they changed the frame (the flags accumulate).
552 pre := wire.StepReport{TaskID: "tk", StepID: "s", Attempt: 1, State: wire.StepDone, HasPreview: true, Findings: []wire.Finding{}}
553 if got := enc(wire.FrameStep, pre, wire.ProtocolMergeFacts); strings.Contains(got, "has_preview") {
554 t.Fatalf("has_preview below 9: %s", got)
555 }
556}
557
558// Protocol 11 says which preview host a runner is paired with (devbox or
559// Carloku temporary sites) and its domain. Below 11 only the previews
560// flag stays; the runner's first hello, sent before any welcome, carries
561// neither; and a host the instance does not know is not a valid report.
562func TestEncodeBelowProtocol11DropsPreviewHost(t *testing.T) {
563 caps := func(host *wire.PreviewHost) *wire.Capabilities {
564 return &wire.Capabilities{Simulators: []wire.Simulator{}, Tags: []string{wire.TagLinux}, Previews: true, PreviewHost: host}
565 }
566 host := &wire.PreviewHost{Kind: wire.PreviewHostDevbox, Domain: "devbox.example.com"}
567 f, _ := wire.NewFrame("h", wire.FrameHello, wire.Hello{Repos: []string{}, Capabilities: caps(host)})
568 if same, err := wire.Encode(f, wire.ProtocolPreviewHost); err != nil || !bytes.Equal(same.Data, f.Data) {
569 t.Fatalf("changed at 11: %v", err)
570 }
571 old, err := wire.Encode(f, wire.ProtocolExplore)
572 if err != nil {
573 t.Fatal(err)
574 }
575 want, _ := wire.NewFrame("h", wire.FrameHello, wire.Hello{Repos: []string{}, Capabilities: caps(nil)})
576 if !bytes.Equal(old.Data, want.Data) || wire.Strict(old.Data, &wire.Hello{}) != nil {
577 t.Fatalf("at 10:\n got %s\nwant %s", old.Data, want.Data)
578 }
579 first := wire.Hello{Capabilities: caps(host)}
580 if !wire.WithoutPreviews(&first) || first.Capabilities.Previews || first.Capabilities.PreviewHost != nil {
581 t.Fatalf("first hello %+v", first.Capabilities)
582 }
583 for _, c := range []struct {
584 host *wire.PreviewHost
585 ok bool
586 }{
587 {host, true},
588 {&wire.PreviewHost{Kind: wire.PreviewHostCarlokuTemp, Domain: "bds.oncarlos.com"}, true},
589 {&wire.PreviewHost{Kind: wire.PreviewHostDevbox}, true},
590 {&wire.PreviewHost{Kind: "s3"}, false},
591 {&wire.PreviewHost{Kind: wire.PreviewHostDevbox, Domain: "evil example"}, false},
592 } {
593 if err := wire.ValidCapabilities(*caps(c.host)); (err == nil) != c.ok {
594 t.Fatalf("%+v: %v", c.host, err)
595 }
596 }
597 noFlag := caps(host)
598 noFlag.Previews = false
599 if wire.ValidCapabilities(*noFlag) == nil {
600 t.Fatal("a preview host without previews on is valid")
601 }
602}
603
604// Protocol 12 adds metered connections (connectors spec S1, §10). An
605// older peer never sees one: below 12 the API-key connections leave
606// hello and sync, a usage row's cost goes, a probe's usage is said as a
607// check, and the model, budget and resume_spend frames and an API-key
608// connect are refused, so an older runner is refused metered
609// connections rather than downgraded.
610func TestEncodeBelowProtocol12DropsMetered(t *testing.T) {
611 claude := wire.HeldConnection{LocalID: "claude-a", Person: "p", Provider: wire.ProviderClaude, Kind: wire.KindSubscription, State: wire.ConnHealthy}
612 metered := wire.HeldConnection{LocalID: "tensorx-1", Person: "p", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Budget: &wire.Budget{Day: 1, Month: 2, Currency: "USD"}, Spend: &wire.Spend{Currency: "USD"}}
613 cost, n := int64(21), int64(9)
614 row := wire.Usage{Provider: wire.ProviderTensorX, Connection: "tensorx-1", Model: "z-ai/glm-5.3", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &n}
615 priced := row
616 priced.CostMicros, priced.Currency, priced.PriceVersion, priced.CostReportedMicros = &cost, "USD", "tensorx-2026-11-12", &cost
617 for _, c := range []struct {
618 kind string
619 new, prev any
620 decode any
621 }{
622 {wire.FrameHello, wire.Hello{Repos: []string{}, Connections: []wire.HeldConnection{claude, metered}}, wire.Hello{Repos: []string{}, Connections: []wire.HeldConnection{claude}}, &wire.Hello{}},
623 {wire.FrameSync, wire.Sync{Connections: []wire.HeldConnection{metered, claude}}, wire.Sync{Connections: []wire.HeldConnection{claude}}, &wire.Sync{}},
624 {wire.FrameUsage, wire.UsageReport{ProbeID: "pr_1", Rows: []wire.Usage{priced}}, wire.UsageReport{CheckID: "pr_1", Rows: []wire.Usage{row}}, &wire.UsageReport{}},
625 {wire.FrameStep, wire.StepReport{TaskID: "tk", Findings: []wire.Finding{}, Usage: []wire.Usage{priced}}, wire.StepReport{TaskID: "tk", Findings: []wire.Finding{}, Usage: []wire.Usage{row}}, &wire.StepReport{}},
626 {wire.FrameAnswer, wire.AnswerReport{QuestionID: "q", Usage: []wire.Usage{priced}}, wire.AnswerReport{QuestionID: "q", Usage: []wire.Usage{row}}, &wire.AnswerReport{}},
627 } {
628 f, err := wire.NewFrame("f1", c.kind, c.new)
629 if err != nil {
630 t.Fatal(err)
631 }
632 if same, err := wire.Encode(f, wire.ProtocolMetered); err != nil || !bytes.Equal(same.Data, f.Data) {
633 t.Fatalf("%s changed at protocol 12: %v", c.kind, err)
634 }
635 want, _ := wire.NewFrame("f1", c.kind, c.prev)
636 for _, p := range []int{wire.ProtocolPreviewHost, wire.ProtocolPreview, wire.ProtocolSpend + 1} {
637 old, err := wire.Encode(f, p)
638 if err != nil || !bytes.Equal(old.Data, want.Data) {
639 t.Fatalf("%s at protocol %d: %v\n got %s\nwant %s", c.kind, p, err, old.Data, want.Data)
640 }
641 if err := wire.Strict(old.Data, c.decode); err != nil {
642 t.Fatalf("%s at protocol %d does not decode: %v", c.kind, p, err)
643 }
644 if strings.Contains(string(old.Data), "cost") || strings.Contains(string(old.Data), "api_key") || strings.Contains(string(old.Data), "probe") || strings.Contains(string(old.Data), "models") {
645 t.Fatalf("%s at protocol %d still carries metered fields: %s", c.kind, p, old.Data)
646 }
647 }
648 }
649 refused := []wire.Frame{}
650 for kind, body := range map[string]any{
651 wire.FrameModel: wire.ModelCommand{Connection: "cn", Person: "p", Model: "m"},
652 wire.FrameBudget: wire.BudgetCommand{Connection: "cn", Person: "p", LocalID: "tensorx-1", Budget: wire.Budget{Day: 1, Month: 2}},
653 wire.FrameResumeSpend: wire.ResumeSpendCommand{Connection: "cn", Person: "p", LocalID: "tensorx-1", PauseRevision: 1},
654 wire.FrameConnect: wire.ConnectCommand{Connection: "cn", Person: "p", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, Billing: wire.BillingMetered},
655 } {
656 f, _ := wire.NewFrame("f-"+kind, kind, body)
657 refused = append(refused, f)
658 }
659 for _, f := range refused {
660 if _, err := wire.Encode(f, wire.ProtocolMetered); err != nil {
661 t.Fatalf("%s refused at 12: %v", f.Type, err)
662 }
663 for _, p := range []int{wire.ProtocolPreviewHost, wire.Protocol2, wire.Protocol1} {
664 if _, err := wire.Encode(f, p); !errors.Is(err, wire.ErrProtocol) {
665 t.Fatalf("%s encoded at protocol %d: %v", f.Type, p, err)
666 }
667 }
668 }
669 // A subscription connect is the old frame, unchanged.
670 sub, _ := wire.NewFrame("f2", wire.FrameConnect, wire.ConnectCommand{Connection: "cn", Person: "p", Provider: wire.ProviderCodex, Kind: wire.KindSubscription})
671 if old, err := wire.Encode(sub, wire.ProtocolPreviewHost); err != nil || !bytes.Equal(old.Data, sub.Data) {
672 t.Fatalf("a subscription connect changed: %v", err)
673 }
674 if wire.ProtocolMetered != 12 || wire.Spoken(wire.ProtocolMetered) != wire.ProtocolMetered || wire.Spoken(wire.ProtocolPreviewHost) != wire.ProtocolPreviewHost || wire.Spoken(99) != wire.ProtocolCurrent {
675 t.Fatalf("current %d", wire.ProtocolCurrent)
676 }
677}
678
679// Frozen pre-12 shapes and values (security round, finding 7): what an
680// instance at protocol 11 decodes strictly and the values it knows,
681// written down here, not taken from today's types.
682type pre12Prompt struct {
683 Kind string `json:"kind"`
684 URL string `json:"url"`
685 Code string `json:"code"`
686 Attempt int64 `json:"attempt,omitempty"`
687 WrongCode bool `json:"wrong_code,omitempty"`
688}
689
690type pre12Report struct {
691 Connection string `json:"connection"`
692 Person string `json:"person"`
693 LocalID string `json:"local_id"`
694 Provider string `json:"provider"`
695 State string `json:"state"`
696 Reason string `json:"reason"`
697 Label string `json:"label"`
698 Plan string `json:"plan"`
699 Headroom json.RawMessage `json:"headroom"`
700 Prompt *pre12Prompt `json:"prompt"`
701}
702
703type pre12Usage struct {
704 Provider string `json:"provider"`
705 Connection string `json:"connection"`
706 Model string `json:"model"`
707 Attempt int64 `json:"attempt"`
708 Outcome string `json:"outcome"`
709 Complete bool `json:"complete"`
710 InputTokens *int64 `json:"input_tokens"`
711 CachedInputTokens *int64 `json:"cached_input_tokens"`
712 CacheWriteTokens *int64 `json:"cache_write_tokens"`
713 OutputTokens *int64 `json:"output_tokens"`
714 ReasoningOutputTokens *int64 `json:"reasoning_output_tokens"`
715 Turns *int64 `json:"turns,omitempty"`
716}
717
718type pre12UsageReport struct {
719 TurnID string `json:"turn_id"`
720 StepID string `json:"step_id"`
721 QuestionID string `json:"question_id"`
722 CheckID string `json:"check_id,omitempty"`
723 Rows []pre12Usage `json:"rows"`
724}
725
726type pre12Held struct {
727 LocalID string `json:"local_id"`
728 Person string `json:"person"`
729 Provider string `json:"provider"`
730 Kind string `json:"kind"`
731 Label string `json:"label"`
732 State string `json:"state"`
733 Plan string `json:"plan"`
734 Headroom json.RawMessage `json:"headroom"`
735 ExpiresAt *time.Time `json:"expires_at,omitempty"`
736 ExpiresEstimated bool `json:"expires_estimated,omitempty"`
737}
738
739var (
740 pre12PromptKinds = map[string]bool{"device_code": true, "authorize_link": true, "token": true}
741 pre12ConnectReasons = map[string]bool{"": true, "timed_out": true, "cancelled": true, "provider_refused": true, "runner_offline": true, "identity_mismatch": true, "already_connected": true}
742 pre12AnswerReasons = map[string]bool{"": true, "cancelled": true, "interrupted": true, "runner_restarted": true, "turn_timeout": true, "provider_failed": true, "provider_rejected": true, "policy_rejected": true, "account_unavailable": true, "sign_in_again": true, "clone_failed": true, "candidate_unavailable": true, "session_gone": true, "superseded": true, "task_ended": true, "limited": true}
743 pre12AnswerStates = map[string]bool{"running": true, "answered": true, "failed": true, "cancelled": true}
744 pre12Providers = map[string]bool{"claude": true, "codex": true}
745 pre12Kinds = map[string]bool{"subscription": true, "token": true}
746)
747
748// TestEncodeBelowProtocol12AgainstFrozenSchemas: every report a metered
749// connection makes is either refused below protocol 12 or decodes, with
750// unknown fields refused, into the frozen pre-12 shape with only values
751// a protocol 11 instance knows.
752func TestEncodeBelowProtocol12AgainstFrozenSchemas(t *testing.T) {
753 cost, n := int64(5), int64(9)
754 row := wire.Usage{Provider: wire.ProviderTensorX, Connection: "tensorx-1", Model: "z-ai/glm-5.3", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &n, CostMicros: &cost, Currency: "USD", PriceVersion: "v"}
755 frames := map[string][]any{
756 wire.FrameConnection: {
757 wire.ConnectionReport{Connection: "cn", Provider: wire.ProviderTensorX, State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptAPIKey}},
758 wire.ConnectionReport{Connection: "cn", Provider: wire.ProviderTensorX, State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptModel, Models: []string{"m"}}},
759 wire.ConnectionReport{Connection: "cn", Provider: wire.ProviderTensorX, State: wire.ConnError, Reason: "key_refused"},
760 wire.ConnectionReport{Connection: "cn", Provider: wire.ProviderClaude, State: wire.ConnError, Reason: "no_priced_model"},
761 wire.ConnectionReport{Connection: "cn", Provider: wire.ProviderTensorX, State: wire.ConnHealthy, LocalID: "tensorx-1"},
762 wire.ConnectionReport{Connection: "cn", Provider: wire.ProviderClaude, State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptToken}},
763 },
764 wire.FrameAnswer: {
765 wire.AnswerReport{QuestionID: "q", Attempt: 1, State: wire.QuestionQueued, Reason: wire.HoldBudget},
766 wire.AnswerReport{QuestionID: "q", Attempt: 1, State: wire.QuestionFailed, Reason: wire.HoldSpendUnknown},
767 wire.AnswerReport{QuestionID: "q", Attempt: 1, State: wire.QuestionAnswered, Usage: []wire.Usage{row}},
768 },
769 wire.FrameUsage: {wire.UsageReport{ProbeID: "pr_1", Rows: []wire.Usage{row}}},
770 wire.FrameHello: {wire.Hello{Repos: []string{}, Connections: []wire.HeldConnection{{LocalID: "tensorx-1", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Billing: wire.BillingMetered}, {LocalID: "claude-a", Provider: "claude", Kind: wire.KindSubscription, State: wire.ConnHealthy}}}},
771 }
772 sent := 0
773 for kind, bodies := range frames {
774 for _, b := range bodies {
775 f, _ := wire.NewFrame("f", kind, b)
776 old, err := wire.Encode(f, wire.ProtocolPreviewHost)
777 if errors.Is(err, wire.ErrProtocol) {
778 continue
779 }
780 if err != nil {
781 t.Fatal(err)
782 }
783 sent++
784 switch kind {
785 case wire.FrameConnection:
786 var v pre12Report
787 if err := wire.Strict(old.Data, &v); err != nil || !pre12Providers[v.Provider] || !pre12ConnectReasons[v.Reason] || v.Prompt != nil && !pre12PromptKinds[v.Prompt.Kind] {
788 t.Fatalf("a pre-12 instance cannot read %s: %v", old.Data, err)
789 }
790 case wire.FrameAnswer:
791 var v struct {
792 TaskID string `json:"task_id"`
793 QuestionID string `json:"question_id"`
794 Attempt int64 `json:"attempt"`
795 State string `json:"state"`
796 Reason string `json:"reason"`
797 Text string `json:"text"`
798 Timing json.RawMessage `json:"timing"`
799 Usage []pre12Usage `json:"usage"`
800 }
801 if err := wire.Strict(old.Data, &v); err != nil || !pre12AnswerStates[v.State] || !pre12AnswerReasons[v.Reason] {
802 t.Fatalf("a pre-12 instance cannot read %s: %v", old.Data, err)
803 }
804 case wire.FrameUsage:
805 var v pre12UsageReport
806 if err := wire.Strict(old.Data, &v); err != nil || v.CheckID != "pr_1" {
807 t.Fatalf("a pre-12 instance cannot read %s: %v", old.Data, err)
808 }
809 case wire.FrameHello:
810 var v struct {
811 Connections []pre12Held `json:"connections"`
812 }
813 var all map[string]json.RawMessage
814 json.Unmarshal(old.Data, &all)
815 if err := wire.Strict(all["connections"], &v.Connections); err != nil {
816 t.Fatalf("a pre-12 instance cannot read %s: %v", old.Data, err)
817 }
818 for _, h := range v.Connections {
819 if !pre12Providers[h.Provider] || !pre12Kinds[h.Kind] {
820 t.Fatalf("a pre-12 hello names %s %s", h.Provider, h.Kind)
821 }
822 }
823 }
824 }
825 }
826 if sent != 4 {
827 t.Fatalf("%d reports sent below 12, want the token prompt, the answer, the usage and the hello", sent)
828 }
829}
830
831// Protocol 13 (Research) adds propose_specialist. Below 13 Encode refuses
832// the call outright (the runner answers it itself, before sending), and
833// every other frame at 12 and 11 is as it was.
834func TestEncodeBelowProtocol13RefusesResearch(t *testing.T) {
835 propose := wire.ToolCall{CallID: "c", TurnID: "t", Attempt: 1, Name: wire.ToolProposeSpecialist, Args: json.RawMessage(`{"profile":"research-v1","name":"Research","brief":"b","capabilities":["web.research"],"tools":["submit_findings","keep_image"]}`)}
836 f, _ := wire.NewFrame("p", wire.FrameToolCall, propose)
837 if same, err := wire.Encode(f, wire.ProtocolResearch); err != nil || !bytes.Equal(same.Data, f.Data) {
838 t.Fatalf("changed at 13: %v", err)
839 }
840 for _, p := range []int{wire.ProtocolMetered, wire.ProtocolPreviewHost, wire.ProtocolExplore, wire.ProtocolPreview, wire.Protocol2} {
841 if _, err := wire.Encode(f, p); !errors.Is(err, wire.ErrProtocol) {
842 t.Fatalf("propose_specialist at %d: %v", p, err)
843 }
844 }
845 // Everything else at 12 and 11 is unchanged, the hello's preview host included.
846 other, _ := wire.NewFrame("o", wire.FrameToolCall, wire.ToolCall{CallID: "d", TurnID: "t", Attempt: 1, Name: wire.ToolAskPerson, Args: json.RawMessage(`{"question":"q"}`)})
847 host := &wire.PreviewHost{Kind: wire.PreviewHostDevbox, Domain: "devbox.example.com"}
848 hello, _ := wire.NewFrame("h", wire.FrameHello, wire.Hello{Repos: []string{}, Capabilities: &wire.Capabilities{Simulators: []wire.Simulator{}, Tags: []string{wire.TagLinux}, Previews: true, PreviewHost: host}})
849 result, _ := wire.NewFrame("r", wire.FrameToolResult, wire.ToolResult{CallID: "c", Person: "owner@example.com", IsError: true, Code: "research_unsupported", Text: "x"})
850 for _, g := range []wire.Frame{other, hello, result} {
851 for _, p := range []int{wire.ProtocolMetered, wire.ProtocolPreviewHost} {
852 if same, err := wire.Encode(g, p); err != nil || !bytes.Equal(same.Data, g.Data) {
853 t.Fatalf("%s changed at %d: %v", g.Type, p, err)
854 }
855 }
856 }
857 if !slices.Contains(wire.ConverseTools, wire.ToolProposeSpecialist) || !slices.Contains(wire.WriteTools, wire.ToolProposeSpecialist) || wire.MutationKinds[wire.ToolProposeSpecialist] == "" {
858 t.Fatal("propose_specialist is not a coordinator write tool")
859 }
860 if slices.Contains(wire.MoveInTools, wire.ToolProposeSpecialist) {
861 t.Fatal("a move-in turn may propose a specialist")
862 }
863}
864