| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "database/sql" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "log/slog" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/fakepi" |
| 18 | "amadan.net/oficina/equipo/internal/runner" |
| 19 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 20 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 21 | "amadan.net/oficina/equipo/internal/runner/metered" |
| 22 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 23 | "amadan.net/oficina/equipo/internal/runner/provider/pi" |
| 24 | "amadan.net/oficina/equipo/internal/testci" |
| 25 | "amadan.net/oficina/equipo/internal/wire" |
| 26 | ) |
| 27 | |
| 28 | const piLocal = "tensorx-abcdef012345" |
| 29 | |
| 30 | // piRig is a runner with one Claude connection, Engineering's (limited |
| 31 | // now), and one metered TensorX connection run by Pi, in the real |
| 32 | // containment; a task branch with one change for Review to judge. |
| 33 | type piRig struct { |
| 34 | // local is the metered connection's local id (piLocal for TensorX). |
| 35 | local string |
| 36 | t *testing.T |
| 37 | ctx context.Context |
| 38 | e *Engineer |
| 39 | state *State |
| 40 | conns *Conns |
| 41 | review stepRow |
| 42 | } |
| 43 | |
| 44 | func copySelf(t *testing.T, dir, name string) string { |
| 45 | t.Helper() |
| 46 | self, err := os.Executable() |
| 47 | if err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | raw, err := os.ReadFile(self) |
| 51 | if err != nil { |
| 52 | t.Fatal(err) |
| 53 | } |
| 54 | p := filepath.Join(dir, name) |
| 55 | if err := os.WriteFile(p, raw, 0755); err != nil { |
| 56 | t.Fatal(err) |
| 57 | } |
| 58 | return p |
| 59 | } |
| 60 | |
| 61 | // fakePiInstall is fakepi as the Pi CLI, run by a copy of this binary as |
| 62 | // Node, with its own digests as the pins. |
| 63 | func fakePiInstall(t *testing.T) pi.Install { |
| 64 | t.Helper() |
| 65 | dir := t.TempDir() |
| 66 | node := copySelf(t, dir, "node") |
| 67 | tree := filepath.Join(dir, "pi", "node_modules") |
| 68 | cli := filepath.Join(tree, "@earendil-works/pi-coding-agent/dist/bundle/cli.js") |
| 69 | os.MkdirAll(filepath.Dir(cli), 0755) |
| 70 | if err := os.WriteFile(cli, []byte("// fakepi\n"), 0644); err != nil { |
| 71 | t.Fatal(err) |
| 72 | } |
| 73 | if err := pi.Seal(tree); err != nil { |
| 74 | t.Fatal(err) |
| 75 | } |
| 76 | t.Cleanup(func() { |
| 77 | filepath.Walk(tree, func(p string, info os.FileInfo, err error) error { |
| 78 | if err == nil && info.IsDir() { |
| 79 | os.Chmod(p, 0755) |
| 80 | } |
| 81 | return nil |
| 82 | }) |
| 83 | }) |
| 84 | sum, err := pi.TreeSHA256(tree) |
| 85 | if err != nil { |
| 86 | t.Fatal(err) |
| 87 | } |
| 88 | raw, _ := os.ReadFile(node) |
| 89 | return pi.Install{Node: node, Tree: tree, NodeSHA256: sha256Hex(raw), TreeSHA256: sum} |
| 90 | } |
| 91 | |
| 92 | // realPiInstall is the pinned Pi this machine has (EQUIPO_PI_ROOT). |
| 93 | func realPiInstall(t *testing.T) pi.Install { |
| 94 | t.Helper() |
| 95 | root := os.Getenv("EQUIPO_PI_ROOT") |
| 96 | if root == "" { |
| 97 | testci.Absent(t, "the pinned Pi (EQUIPO_PI_ROOT) is absent") |
| 98 | } |
| 99 | testci.Tools(t, "pi") |
| 100 | node, tree := pi.Paths(root) |
| 101 | inst, ok := pi.Install{Node: node, Tree: tree}.Pinned() |
| 102 | if !ok { |
| 103 | t.Skip("no Pi pins for this platform") |
| 104 | } |
| 105 | return inst |
| 106 | } |
| 107 | |
| 108 | func newPiRig(t *testing.T, inst pi.Install, budget wire.Budget) *piRig { |
| 109 | t.Helper() |
| 110 | return newMeteredRig(t, budget, rigConn{local: piLocal, provider: wire.ProviderTensorX, harness: wire.HarnessPi, upstream: "https://api.tensorx.ai", model: "z-ai/glm-5.3", key: fakepi.TestKey}, func(e *Engineer) { e.Pi = PiOptions{Install: inst} }) |
| 111 | } |
| 112 | |
| 113 | // rigConn is a metered rig's one metered connection. |
| 114 | type rigConn struct { |
| 115 | local, provider, harness, upstream, model, key string |
| 116 | } |
| 117 | |
| 118 | // newMeteredRig is the rig with conn as its metered connection, its |
| 119 | // harness's install set by install. |
| 120 | func newMeteredRig(t *testing.T, budget wire.Budget, conn rigConn, install func(*Engineer)) *piRig { |
| 121 | t.Helper() |
| 122 | testci.Tools(t, "bwrap", "git") |
| 123 | if _, err := os.Stat("/usr/bin/bwrap"); err != nil { |
| 124 | testci.Absent(t, "bubblewrap is absent") |
| 125 | } |
| 126 | // A short root: the tool socket's path must fit a socket address. |
| 127 | root, err := os.MkdirTemp("", "pi-") |
| 128 | if err != nil { |
| 129 | t.Fatal(err) |
| 130 | } |
| 131 | t.Cleanup(func() { os.RemoveAll(root) }) |
| 132 | for _, d := range []string{"state", "work", "scratch", "sessions", "bin", "clones"} { |
| 133 | if err := os.MkdirAll(filepath.Join(root, d), 0700); err != nil { |
| 134 | t.Fatal(err) |
| 135 | } |
| 136 | } |
| 137 | // The repository: main at base, the task branch one change on. |
| 138 | seed := filepath.Join(root, "seed") |
| 139 | gitOut(t, root, "init", "-q", "-b", "main", seed) |
| 140 | os.WriteFile(filepath.Join(seed, "README.md"), []byte("teh panes\n"), 0644) |
| 141 | gitOut(t, seed, "add", "-A") |
| 142 | gitOut(t, seed, "commit", "-q", "-m", "base") |
| 143 | base := gitOut(t, seed, "rev-parse", "HEAD") |
| 144 | gitOut(t, seed, "checkout", "-q", "-b", "equipo/tk1-fix-typo") |
| 145 | os.WriteFile(filepath.Join(seed, "README.md"), []byte("the panes\n"), 0644) |
| 146 | gitOut(t, seed, "commit", "-q", "-am", "fix") |
| 147 | cand := gitOut(t, seed, "rev-parse", "HEAD") |
| 148 | remote := filepath.Join(root, "remote.git") |
| 149 | gitOut(t, root, "clone", "-q", "--bare", seed, remote) |
| 150 | state, err := OpenState(context.Background(), filepath.Join(root, "state")) |
| 151 | if err != nil { |
| 152 | t.Fatal(err) |
| 153 | } |
| 154 | t.Cleanup(func() { state.Close() }) |
| 155 | // Engineering's connection: Claude, limited now. |
| 156 | home := filepath.Join(root, "accounts", "claude-a") |
| 157 | os.MkdirAll(home, 0700) |
| 158 | identity := map[string]string{"account_id": "a@example.com", "home_id": "h-a", "provider_version": "1"} |
| 159 | raw, _ := json.Marshal([]map[string]any{{"id": "claude-a", "local_id": "claude-a", "label": "claude-a", "person_id": connPerson, "provider": "claude", "family": "claude", "model": "claude-opus-5-5", "account_id": "a@example.com", "provider_home": home, "kind": "subscription", "expected_identity": identity}}) |
| 160 | bindings := filepath.Join(root, "bindings.json") |
| 161 | os.WriteFile(bindings, raw, 0600) |
| 162 | self, _ := os.Executable() |
| 163 | cfg := runner.Config{AccountBindingsPath: bindings, ClaudePath: "/bin/true", CodexPath: "/bin/true", StateDir: filepath.Join(root, "state"), WorkspaceRoot: filepath.Join(root, "work"), ScratchRoot: filepath.Join(root, "scratch"), GitPath: "/usr/bin/git", BwrapPath: "/usr/bin/bwrap", ToolProxyPath: copySelf(t, filepath.Join(root, "bin"), "equipo-tool-proxy")} |
| 164 | m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: cfg.ScratchRoot}) |
| 165 | if err != nil { |
| 166 | testci.Absent(t, "namespaces are unavailable: "+err.Error()) |
| 167 | } |
| 168 | conns := &Conns{Runner: cfg, State: state} |
| 169 | conns.Meter = &metered.Meter{DB: state.db} |
| 170 | conns.Validated("claude-a") |
| 171 | conns.Limit("claude-a", connect.Limit{Limited: true, ResetsAt: time.Now().Add(time.Hour)}) |
| 172 | // The metered connection, its key 0600 in its home. |
| 173 | keyHome := filepath.Join(root, "accounts", conn.local) |
| 174 | os.MkdirAll(keyHome, 0700) |
| 175 | if err := os.WriteFile(filepath.Join(keyHome, provider.TokenFile), []byte(conn.key), 0600); err != nil { |
| 176 | t.Fatal(err) |
| 177 | } |
| 178 | ctx, cancel := context.WithCancel(context.Background()) |
| 179 | t.Cleanup(cancel) |
| 180 | err = state.tx(ctx, func(tx *sql.Tx) error { |
| 181 | if err := metered.Add(ctx, tx, metered.Conn{Connection: "cn_tx", LocalID: conn.local, Person: connPerson, Provider: conn.provider, Harness: conn.harness, Upstream: conn.upstream, Billing: wire.BillingMetered, Model: conn.model, Home: keyHome, Currency: "USD", PriceVersion: metered.Current[conn.provider], Budget: budget}, time.Now()); err != nil { |
| 182 | return err |
| 183 | } |
| 184 | if err := metered.Checked(ctx, tx, conn.local, true); err != nil { |
| 185 | return err |
| 186 | } |
| 187 | // A connection as S1 made it, migrated (§16.5): its one model, |
| 188 | // proven. |
| 189 | return provenModels(ctx, tx, conn.local, conn.model) |
| 190 | }) |
| 191 | if err != nil { |
| 192 | t.Fatal(err) |
| 193 | } |
| 194 | f := &hubForge{dir: remote} |
| 195 | e := &Engineer{O: ClaudeOptions{Runner: cfg, Manager: m, State: state, SessionRoot: filepath.Join(root, "sessions"), Logger: slog.New(slog.NewTextHandler(testWriter{t}, nil))}, Clones: &Clones{Root: filepath.Join(root, "clones"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{connPerson}, MaxStep: 2 * time.Minute, Conns: conns, Host: "test"} |
| 196 | install(e) |
| 197 | review := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk1", StepID: "rv1", Attempt: 1, Specialist: wire.SpecialistReview, Repo: "amadan.net/oficina/sample", Branch: "equipo/tk1-fix-typo", BaseSHA: base, CandidateSHA: cand, AvoidAccount: "claude-a", Title: "Fix the typo", Findings: []wire.Finding{}}} |
| 198 | return &piRig{local: conn.local, t: t, ctx: ctx, e: e, state: state, conns: conns, review: review} |
| 199 | } |
| 200 | |
| 201 | // urgent gives the rig's steps leave to spend the way S3 gives it: the |
| 202 | // task is urgent (the person's tap). |
| 203 | func (r *piRig) urgent() { r.review.Priority = wire.PriorityUrgent } |
| 204 | |
| 205 | func (r *piRig) runReview(brief string, attempt int64) wire.StepReport { |
| 206 | r.t.Helper() |
| 207 | row := r.review |
| 208 | // One running step per task: each run is its own task's. |
| 209 | row.Brief, row.StepID, row.TaskID = brief, row.StepID+"-"+itoa(attempt), row.TaskID+"-"+itoa(attempt) |
| 210 | if err := r.state.AcceptDispatch(r.ctx, "f-"+row.StepID, row.DispatchCommand); err != nil { |
| 211 | r.t.Fatal(err) |
| 212 | } |
| 213 | return r.e.review(r.ctx, row, func(wire.StepReport) {}) |
| 214 | } |
| 215 | |
| 216 | func (r *piRig) conn() metered.Conn { |
| 217 | r.t.Helper() |
| 218 | c, ok, err := metered.Get(r.ctx, r.state.db, r.local) |
| 219 | if err != nil || !ok { |
| 220 | r.t.Fatal(err) |
| 221 | } |
| 222 | return c |
| 223 | } |
| 224 | |
| 225 | func (r *piRig) charges() int { |
| 226 | var n int |
| 227 | if err := r.state.db.QueryRow("SELECT count(*) FROM budget_charge WHERE connection=?", r.local).Scan(&n); err != nil { |
| 228 | r.t.Fatal(err) |
| 229 | } |
| 230 | return n |
| 231 | } |
| 232 | |
| 233 | func (r *piRig) slotFree() bool { |
| 234 | var holder string |
| 235 | if err := r.state.db.QueryRow("SELECT holder FROM metered_slot WHERE local_id=?", r.local).Scan(&holder); err != nil && err != sql.ErrNoRows { |
| 236 | r.t.Fatal(err) |
| 237 | } |
| 238 | return holder == "" |
| 239 | } |
| 240 | |
| 241 | var bigBudget = wire.Budget{Day: 1_000_000, Month: 10_000_000, Revision: 1} |
| 242 | |
| 243 | // provenModels gives a metered connection the allowed set models at |
| 244 | // revision 1, each proven healthy, as the S5b migration leaves an S1 |
| 245 | // connection (§16.5). |
| 246 | func provenModels(ctx context.Context, tx *sql.Tx, local string, models ...string) error { |
| 247 | if err := metered.InitModels(ctx, tx, local, models, 1); err != nil { |
| 248 | return err |
| 249 | } |
| 250 | for _, m := range models { |
| 251 | if err := metered.MarkModel(ctx, tx, local, m, wire.ModelHealthy, "", time.Now()); err != nil { |
| 252 | return err |
| 253 | } |
| 254 | } |
| 255 | return nil |
| 256 | } |
| 257 | |
| 258 | // A Review step of a Claude change runs on TensorX through Pi when the |
| 259 | // step has leave to spend and no subscription can review: other_family, |
| 260 | // judged on the model that ran (glm), its verdict through Equipo's |
| 261 | // tool, its usage priced and charged once, the slot released after the |
| 262 | // proof, and its session kept so the person can ask it. |
| 263 | func TestPiReviewStep(t *testing.T) { |
| 264 | r := newPiRig(t, fakePiInstall(t), bigBudget) |
| 265 | r.urgent() |
| 266 | rep := r.runReview("", 1) |
| 267 | if rep.State != wire.StepDone || rep.Verdict != wire.VerdictApprove || rep.ReviewLabel != wire.ReviewOtherFamily || rep.Family != "glm" || rep.Account != piLocal || !rep.Termination { |
| 268 | t.Fatalf("report %+v", rep) |
| 269 | } |
| 270 | if !rep.Askable { |
| 271 | t.Fatal("the session was not kept for questions") |
| 272 | } |
| 273 | if len(rep.Usage) != 1 || rep.Usage[0].Provider != wire.ProviderTensorX || rep.Usage[0].Connection != piLocal || !rep.Usage[0].Complete || rep.Usage[0].CostMicros == nil || *rep.Usage[0].CostMicros <= 0 { |
| 274 | t.Fatalf("usage %+v", rep.Usage) |
| 275 | } |
| 276 | if n := r.charges(); n != 1 || !r.slotFree() || r.conn().SpendUnknown { |
| 277 | t.Fatalf("charges %d, slot free %v, spend unknown %v", n, r.slotFree(), r.conn().SpendUnknown) |
| 278 | } |
| 279 | // Admitted through the scheduler, in the guard's transaction: the |
| 280 | // urgent task's leave. |
| 281 | var reason, conn string |
| 282 | if err := r.state.db.QueryRow("SELECT reason, connection FROM admissions WHERE step_id='rv1-1'").Scan(&reason, &conn); err != nil || reason != "metered_urgent" || conn != piLocal { |
| 283 | t.Fatalf("admission %q on %q: %v", reason, conn, err) |
| 284 | } |
| 285 | // A resent usage row charges once. |
| 286 | if err := r.conns.Meter.Finish(r.ctx, piLocal, metered.Holder{Step: "rv1-1", Attempt: 1, Role: metered.RoleReview}, metered.Result{Usage: rep.Usage}, nil); err != nil { |
| 287 | t.Fatal(err) |
| 288 | } |
| 289 | if n := r.charges(); n != 1 { |
| 290 | t.Fatalf("a resent row charged again: %d", n) |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | // Without leave to spend (a normal task, no Run now), Review is never |
| 295 | // chosen onto the metered connection: with Engineering's connection |
| 296 | // limited it is held for headroom on it, and nothing runs. |
| 297 | func TestPiReviewWithoutLeaveToSpend(t *testing.T) { |
| 298 | r := newPiRig(t, fakePiInstall(t), bigBudget) |
| 299 | rep := r.runReview("", 1) |
| 300 | if rep.State != stepDeferred || rep.Hold == nil || rep.Hold.Reason != wire.HoldHeadroom || rep.Hold.Connection != "claude-a" || r.charges() != 0 { |
| 301 | t.Fatalf("report %+v, hold %+v, charges %d", rep, rep.Hold, r.charges()) |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | // The budget stops the next step: once the reported spend reaches it, |
| 306 | // the next Review is held (deferred), not run. |
| 307 | func TestPiBudgetHoldsTheNextStep(t *testing.T) { |
| 308 | r := newPiRig(t, fakePiInstall(t), wire.Budget{Day: 1, Month: 1_000, Revision: 1}) |
| 309 | r.urgent() |
| 310 | if rep := r.runReview("", 1); rep.State != wire.StepDone { |
| 311 | t.Fatalf("first: %+v", rep) |
| 312 | } |
| 313 | rep := r.runReview("", 2) |
| 314 | if rep.State != stepDeferred || r.charges() != 1 { |
| 315 | t.Fatalf("after the budget: %+v, charges %d", rep, r.charges()) |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | // A step with no usage figure (Pi ended before its message_end) pauses |
| 320 | // the connection: spend unknown, and nothing more is admitted. |
| 321 | func TestPiNoUsagePausesTheConnection(t *testing.T) { |
| 322 | r := newPiRig(t, fakePiInstall(t), bigBudget) |
| 323 | r.urgent() |
| 324 | rep := r.runReview("nousage", 1) |
| 325 | if rep.State != wire.StepFailed || !r.conn().SpendUnknown || !r.slotFree() { |
| 326 | t.Fatalf("report %s %s, spend unknown %v slot free %v", rep.State, rep.Reason, r.conn().SpendUnknown, r.slotFree()) |
| 327 | } |
| 328 | if rep := r.runReview("", 2); rep.State != stepDeferred { |
| 329 | t.Fatalf("admitted while spend unknown: %+v", rep) |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | // A key TensorX refuses (a revoked key, or a balance under $0.05) marks |
| 334 | // the connection refused: sign in again, never limited. |
| 335 | func TestPiKeyRefused(t *testing.T) { |
| 336 | r := newPiRig(t, fakePiInstall(t), bigBudget) |
| 337 | r.urgent() |
| 338 | rep := r.runReview("keyrefused", 1) |
| 339 | if rep.State == wire.StepDone || !r.conn().Refused { |
| 340 | t.Fatalf("report %+v, refused %v", rep, r.conn().Refused) |
| 341 | } |
| 342 | if rep.Switched == nil || rep.Switched.From != wire.ProviderTensorX { |
| 343 | t.Fatalf("switched %+v", rep.Switched) |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | // The S2 finish line, in CI: the same Review step with the real pinned |
| 348 | // Pi against a fake TensorX on 127.0.0.1, recorded other_family. |
| 349 | func TestPiReviewStepRealPi(t *testing.T) { |
| 350 | inst := realPiInstall(t) |
| 351 | tensorx := fakepi.StartTensorX(t) |
| 352 | was := testPiCA |
| 353 | testPiCA = func() string { return tensorx.CA } |
| 354 | t.Cleanup(func() { testPiCA = was }) |
| 355 | r := newPiRig(t, inst, bigBudget) |
| 356 | r.urgent() |
| 357 | rep := r.runReview("", 1) |
| 358 | if rep.State != wire.StepDone || rep.Verdict != wire.VerdictApprove || rep.ReviewLabel != wire.ReviewOtherFamily || rep.Family != "glm" || !strings.Contains(rep.Summary, "TensorX") { |
| 359 | t.Fatalf("report %+v", rep) |
| 360 | } |
| 361 | if len(rep.Usage) != 1 || !rep.Usage[0].Complete || rep.Usage[0].CostMicros == nil || r.charges() != 1 || !r.slotFree() { |
| 362 | t.Fatalf("usage %+v charges %d", rep.Usage, r.charges()) |
| 363 | } |
| 364 | seen := tensorx.Seen() |
| 365 | if len(seen) == 0 || seen[0].Auth != "Bearer "+fakepi.TestKey { |
| 366 | t.Fatalf("provider saw %+v", seen) |
| 367 | } |
| 368 | for _, req := range seen { |
| 369 | for _, tool := range req.Tools { |
| 370 | if tool == "bash" || tool == "write" || tool == "edit" { |
| 371 | t.Fatalf("Review declared %v", req.Tools) |
| 372 | } |
| 373 | } |
| 374 | } |
| 375 | // A question resumes the Review's own session on its connection: Pi |
| 376 | // sends the Review's history with it. |
| 377 | a := askRow{AskCommand: wire.AskCommand{Person: connPerson, TaskID: rep.TaskID, StepID: rep.StepID, QuestionID: "q1", Attempt: 1, Specialist: wire.SpecialistReview, Repo: r.review.Repo, Branch: r.review.Branch, BaseSHA: r.review.BaseSHA, CandidateSHA: r.review.CandidateSHA, Title: "Fix the typo", Text: "Why approve?"}} |
| 378 | if err := r.state.AcceptAsk(r.ctx, "f-q1", a.AskCommand); err != nil { |
| 379 | t.Fatal(err) |
| 380 | } |
| 381 | se := &StepEngine{State: r.state, Meter: r.conns.Meter, MeteredAsk: r.e.askPi, Notify: func() {}} |
| 382 | se.askMetered(r.ctx, r.ctx, a, piLocal, r.conn().Model, func(wire.AnswerReport) {}) |
| 383 | after := tensorx.Seen() |
| 384 | if len(after) <= len(seen) || after[len(after)-1].Messages <= seen[len(seen)-1].Messages || r.charges() != 2 { |
| 385 | t.Fatalf("the question did not resume the session: %d then %d messages, charges %d", seen[len(seen)-1].Messages, after[len(after)-1].Messages, r.charges()) |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | func sha256Hex(raw []byte) string { |
| 390 | sum := sha256.Sum256(raw) |
| 391 | return hex.EncodeToString(sum[:]) |
| 392 | } |
| 393 | |
| 394 | // testWriter sends the runner's log lines to the test's log. |
| 395 | type testWriter struct{ t *testing.T } |
| 396 | |
| 397 | func (w testWriter) Write(p []byte) (int, error) { |
| 398 | w.t.Log(strings.TrimSpace(string(p))) |
| 399 | return len(p), nil |
| 400 | } |
| 401 | |
| 402 | // A question about a Review that ran on Pi stays on its step's own |
| 403 | // session and connection (connectors spec §7): through the metered |
| 404 | // guard, the kept session resumed (Pi sees the review in it), the |
| 405 | // answer charged. |
| 406 | func TestPiAskKeptSession(t *testing.T) { |
| 407 | r := newPiRig(t, fakePiInstall(t), bigBudget) |
| 408 | r.urgent() |
| 409 | rep := r.runReview("", 1) |
| 410 | if !rep.Askable { |
| 411 | t.Fatalf("not askable: %+v", rep) |
| 412 | } |
| 413 | a := askRow{AskCommand: wire.AskCommand{Person: connPerson, TaskID: rep.TaskID, StepID: rep.StepID, QuestionID: "q1", Attempt: 1, Specialist: wire.SpecialistReview, Repo: r.review.Repo, Branch: r.review.Branch, BaseSHA: r.review.BaseSHA, CandidateSHA: r.review.CandidateSHA, Title: "Fix the typo", Text: "Why approve?"}} |
| 414 | if err := r.state.AcceptAsk(r.ctx, "f-q1", a.AskCommand); err != nil { |
| 415 | t.Fatal(err) |
| 416 | } |
| 417 | se := &StepEngine{State: r.state, Meter: r.conns.Meter, MeteredAsk: r.e.askPi, Notify: func() {}} |
| 418 | local, model, ok := se.meteredAsk(r.ctx, a) |
| 419 | if !ok || local != piLocal { |
| 420 | t.Fatalf("the question is not on its metered connection: %q %v", local, ok) |
| 421 | } |
| 422 | se.askMetered(r.ctx, r.ctx, a, local, model, func(wire.AnswerReport) {}) |
| 423 | frames, _, err := r.state.Unacked(r.ctx, 0) |
| 424 | if err != nil { |
| 425 | t.Fatal(err) |
| 426 | } |
| 427 | var answer wire.AnswerReport |
| 428 | for _, f := range frames { |
| 429 | var v wire.AnswerReport |
| 430 | if f.Type == wire.FrameAnswer && json.Unmarshal(f.Data, &v) == nil && v.QuestionID == "q1" && v.State == wire.QuestionAnswered { |
| 431 | answer = v |
| 432 | } |
| 433 | } |
| 434 | if !strings.Contains(answer.Text, "message 2") || len(answer.Usage) != 1 || answer.Usage[0].CostMicros == nil { |
| 435 | t.Fatalf("answer %+v", answer) |
| 436 | } |
| 437 | if n := r.charges(); n != 2 || !r.slotFree() { |
| 438 | t.Fatalf("charges %d slot free %v", n, r.slotFree()) |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | // Engineering on Pi: its tools inside the namespace, the workspace |
| 443 | // writable, charged as an Engineering attempt. |
| 444 | func TestPiEngineeringRun(t *testing.T) { |
| 445 | r := newPiRig(t, fakePiInstall(t), bigBudget) |
| 446 | work := t.TempDir() |
| 447 | os.WriteFile(filepath.Join(work, "README.md"), []byte("teh panes\n"), 0644) |
| 448 | b := r.conns.MeteredMine(r.ctx, connPerson) |
| 449 | if len(b) != 1 || b[0].Family != "glm" || !Metered(b[0]) { |
| 450 | t.Fatalf("metered bindings %+v", b) |
| 451 | } |
| 452 | row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk9", StepID: "en1", Attempt: 1, Specialist: wire.SpecialistEngineering}} |
| 453 | res := r.e.run(r.ctx, row, workspace.TaskTree{Dir: work}, specialistRun{action: "implement", binding: b[0], tools: stepTools, names: []string{"submit_candidate", "ask_person", "submit_render"}, call: func(context.Context, string, string, json.RawMessage) (string, bool) { return stepToolText, false }, prompt: "[Equipo: engineering] edit:README.md|teh|the"}) |
| 454 | raw, _ := os.ReadFile(filepath.Join(work, "README.md")) |
| 455 | if res.reason != "" || !res.terminated || string(raw) != "the panes\n" { |
| 456 | t.Fatalf("run %+v; README %q", res, raw) |
| 457 | } |
| 458 | var role string |
| 459 | if err := r.state.db.QueryRow("SELECT holder FROM budget_charge WHERE connection=?", piLocal).Scan(&role); err != nil || !strings.HasPrefix(role, metered.RoleEngineering+"|") { |
| 460 | t.Fatalf("charged as %q: %v", role, err) |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | // Review's independence is judged on the model that ran (connectors spec |
| 465 | // §3, "Families"): Engineering ran on this same TensorX connection (glm), |
| 466 | // so Review there is the same account, unless another family's model |
| 467 | // answered. |
| 468 | func TestPiReviewFamilyFromTheModelThatRan(t *testing.T) { |
| 469 | r := newPiRig(t, fakePiInstall(t), bigBudget) |
| 470 | r.urgent() |
| 471 | r.review.AvoidAccount = piLocal |
| 472 | if rep := r.runReview("", 1); rep.State != wire.StepDone || rep.ReviewLabel != wire.ReviewSameAccount || rep.Family != "glm" { |
| 473 | t.Fatalf("same model: %+v", rep) |
| 474 | } |
| 475 | rep := r.runReview("answeredby:deepseek/deepseek-v4-pro-0813", 2) |
| 476 | if rep.State != wire.StepDone || rep.ReviewLabel != wire.ReviewOtherFamily || rep.Family != "deepseek" { |
| 477 | t.Fatalf("another model: %+v", rep) |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | // In a step nobody can answer the extension's question: a call it asks |
| 482 | // about is refused, and the step goes on. |
| 483 | func TestPiStepRefusesAsks(t *testing.T) { |
| 484 | r := newPiRig(t, fakePiInstall(t), bigBudget) |
| 485 | r.urgent() |
| 486 | rep := r.runReview("read:/etc/hostname", 1) |
| 487 | if rep.State != wire.StepDone || !strings.Contains(rep.LogTail, "Refused a call") || !strings.Contains(rep.LogTail, "read /etc/hostname refused") { |
| 488 | t.Fatalf("report %+v", rep) |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | // An Engineering step the metered guard holds waits, deferred: here the |
| 493 | // budget, which the Review before it reached. |
| 494 | func TestPiEngineeringHeldIsDeferred(t *testing.T) { |
| 495 | r := newPiRig(t, fakePiInstall(t), wire.Budget{Day: 1, Month: 1_000, Revision: 1}) |
| 496 | r.urgent() |
| 497 | if rep := r.runReview("", 1); rep.State != wire.StepDone { |
| 498 | t.Fatalf("review: %+v", rep) |
| 499 | } |
| 500 | row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk5", StepID: "en5", Attempt: 1, Specialist: wire.SpecialistEngineering, Repo: r.review.Repo, Branch: "equipo/tk5-x", BaseSHA: r.review.BaseSHA, Title: "Do the thing", Findings: []wire.Finding{}, Priority: r.review.Priority}} |
| 501 | if err := r.state.AcceptDispatch(r.ctx, "f-en5", row.DispatchCommand); err != nil { |
| 502 | t.Fatal(err) |
| 503 | } |
| 504 | row.Base = r.review.BaseSHA |
| 505 | rep := r.e.Exec(r.ctx, row, func(wire.StepReport) {}) |
| 506 | if rep.State != stepDeferred || r.charges() != 1 { |
| 507 | t.Fatalf("report %+v, charges %d", rep, r.charges()) |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | // A run that ends properly (agent_end) with no usage figure is unknown |
| 512 | // spend too, never a charge of zero. |
| 513 | func TestPiEndWithoutUsagePausesTheConnection(t *testing.T) { |
| 514 | r := newPiRig(t, fakePiInstall(t), bigBudget) |
| 515 | r.urgent() |
| 516 | r.runReview("endnousage", 1) |
| 517 | if !r.conn().SpendUnknown || !r.slotFree() { |
| 518 | t.Fatalf("spend unknown %v, slot free %v", r.conn().SpendUnknown, r.slotFree()) |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | // A reply over the text the runner keeps ends the run, its usage |
| 523 | // incomplete, so the connection's spend is unknown. (Review's verdict, |
| 524 | // given through Equipo's tool before the flood, still stands.) |
| 525 | func TestPiOversizedReply(t *testing.T) { |
| 526 | was := piTextLimit |
| 527 | piTextLimit = 1000 |
| 528 | t.Cleanup(func() { piTextLimit = was }) |
| 529 | r := newPiRig(t, fakePiInstall(t), bigBudget) |
| 530 | r.urgent() |
| 531 | rep := r.runReview("flood:50000", 1) |
| 532 | if !strings.Contains(rep.LogTail, "The reply was too long") || !r.conn().SpendUnknown || len(rep.Summary) > 1000 { |
| 533 | t.Fatalf("report %s %s summary %d, spend unknown %v", rep.State, rep.Reason, len(rep.Summary), r.conn().SpendUnknown) |
| 534 | } |
| 535 | } |
| 536 | |
| 537 | // A step can read the key (connectors spec §2.1), so whatever Pi says is |
| 538 | // redacted before the runner logs or reports it: the reply (the key split |
| 539 | // across two deltas), the verdict it records through Equipo's tool, the |
| 540 | // tail and the step's log. |
| 541 | func TestPiRedactsTheKey(t *testing.T) { |
| 542 | r := newPiRig(t, fakePiInstall(t), bigBudget) |
| 543 | r.urgent() |
| 544 | var logs strings.Builder |
| 545 | r.e.O.Logger = slog.New(slog.NewTextHandler(&logs, nil)) |
| 546 | rep := r.runReview("echokey", 1) |
| 547 | if rep.State != wire.StepDone { |
| 548 | t.Fatalf("report %+v", rep) |
| 549 | } |
| 550 | raw, _ := json.Marshal(rep) |
| 551 | steps, _ := os.ReadDir(r.e.root()) |
| 552 | var stepLog []byte |
| 553 | for _, d := range steps { |
| 554 | b, _ := os.ReadFile(filepath.Join(r.e.root(), d.Name(), "log.jsonl")) |
| 555 | stepLog = append(stepLog, b...) |
| 556 | } |
| 557 | for what, text := range map[string]string{"the report": string(raw), "the step log": string(stepLog), "the runner log": logs.String()} { |
| 558 | if strings.Contains(text, fakepi.TestKey) { |
| 559 | t.Errorf("%s holds the key", what) |
| 560 | } |
| 561 | } |
| 562 | if !strings.Contains(string(stepLog), "[redacted]") || !strings.Contains(rep.Summary+rep.Headline, "[redacted]") { |
| 563 | t.Fatalf("nothing was redacted: summary %q headline %q", rep.Summary, rep.Headline) |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | // A kept Pi Engineering session stays put (spec §7, rule 1): its fix |
| 568 | // round resumes on the metered connection even when a subscription is |
| 569 | // usable again; when the guard bars spending there (a busy slot, the |
| 570 | // budget), the round is held on it, never moved. |
| 571 | func TestPiKeptSessionStaysPut(t *testing.T) { |
| 572 | r := newPiRig(t, fakePiInstall(t), wire.Budget{Day: 1, Month: 1_000, Revision: 1}) |
| 573 | r.urgent() |
| 574 | // Round 0 ran on TensorX and kept its Pi session. |
| 575 | dir := filepath.Join(t.TempDir(), "kept") |
| 576 | os.MkdirAll(dir, 0700) |
| 577 | session := pi.NewSessionID() |
| 578 | if err := os.WriteFile(filepath.Join(dir, "2026-11-12T00-00-00-000Z_"+session+".jsonl"), []byte(`{"type":"session"}`+"\n"), 0600); err != nil { |
| 579 | t.Fatal(err) |
| 580 | } |
| 581 | base := r.review.CandidateSHA |
| 582 | round0 := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk7", StepID: "e0", Attempt: 1, Specialist: wire.SpecialistEngineering}} |
| 583 | if err := r.state.keepSession(r.ctx, round0, wire.SpecialistEngineering, piLocal, "z-ai/glm-5.3", "glm", session, dir, base, 10); err != nil { |
| 584 | t.Fatal(err) |
| 585 | } |
| 586 | // Claude is usable again: its limit's reset (an hour on) has passed. |
| 587 | r.conns.now = func() time.Time { return time.Now().Add(2 * time.Hour) } |
| 588 | if _, _, err := r.conns.Choose(r.ctx, connPerson, connect.RoleEngineering, "", nil); err != nil { |
| 589 | t.Fatalf("Claude is not usable: %v", err) |
| 590 | } |
| 591 | row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk7", StepID: "e1", Attempt: 1, Specialist: wire.SpecialistEngineering, Repo: r.review.Repo, Branch: "equipo/tk7-x", BaseSHA: base, Round: 1, Feedback: "Fix round 1 of 2. Review asked for changes.", Findings: []wire.Finding{}, Priority: r.review.Priority}, Base: base} |
| 592 | plan := func() (string, bool) { |
| 593 | t.Helper() |
| 594 | kept, ok := r.e.fixSession(r.ctx, row, base) |
| 595 | if !ok { |
| 596 | t.Fatal("the kept Pi session was not found") |
| 597 | } |
| 598 | b, resume, hold, _, err := r.e.fixPlan(r.ctx, row, nil, kept, ok) |
| 599 | if err != nil { |
| 600 | t.Fatal(err) |
| 601 | } |
| 602 | if hold != nil { |
| 603 | return hold.Connection, false |
| 604 | } |
| 605 | return b.ID, resume |
| 606 | } |
| 607 | if id, resume := plan(); id != piLocal || !resume { |
| 608 | t.Fatalf("the round moved: %s resume %v", id, resume) |
| 609 | } |
| 610 | // Busy: another attempt holds the slot. The round is held there. |
| 611 | err := r.state.tx(r.ctx, func(tx *sql.Tx) error { |
| 612 | _, err := metered.Admit(r.ctx, tx, piLocal, metered.Holder{Step: "other", Attempt: 1, Role: metered.RoleReview, Model: "z-ai/glm-5.3"}, time.Now()) |
| 613 | return err |
| 614 | }) |
| 615 | if err != nil { |
| 616 | t.Fatal(err) |
| 617 | } |
| 618 | if err := r.state.AcceptDispatch(r.ctx, "f-e1", row.DispatchCommand); err != nil { |
| 619 | t.Fatal(err) |
| 620 | } |
| 621 | if rep := r.e.Exec(r.ctx, row, func(wire.StepReport) {}); rep.State != stepDeferred { |
| 622 | t.Fatalf("busy: %+v", rep) |
| 623 | } |
| 624 | if id, _ := plan(); id != piLocal { |
| 625 | t.Fatalf("after a hold the round moved to %s", id) |
| 626 | } |
| 627 | // The budget: the slot free again, today's spend past the budget. Held |
| 628 | // there again. |
| 629 | other := metered.Holder{Step: "other", Attempt: 1, Role: metered.RoleReview, Model: "z-ai/glm-5.3"} |
| 630 | in, out := int64(1_000_000), int64(1_000) |
| 631 | err = r.state.tx(r.ctx, func(tx *sql.Tx) error { |
| 632 | if _, err := metered.Charge(r.ctx, tx, piLocal, other, []wire.Usage{{Provider: wire.ProviderTensorX, Connection: piLocal, Model: "z-ai/glm-5.3", Attempt: 1, Complete: true, InputTokens: &in, OutputTokens: &out}}, time.Now()); err != nil { |
| 633 | return err |
| 634 | } |
| 635 | return metered.Settle(r.ctx, tx, piLocal, other, metered.Ending{Proven: true}) |
| 636 | }) |
| 637 | if err != nil { |
| 638 | t.Fatal(err) |
| 639 | } |
| 640 | if !r.slotFree() || r.charges() != 1 { |
| 641 | t.Fatalf("slot free %v charges %d", r.slotFree(), r.charges()) |
| 642 | } |
| 643 | if rep := r.e.Exec(r.ctx, row, func(wire.StepReport) {}); rep.State != stepDeferred { |
| 644 | t.Fatalf("budget: %+v", rep) |
| 645 | } |
| 646 | if id, _ := plan(); id != piLocal { |
| 647 | t.Fatalf("after the budget hold the round moved to %s", id) |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | // Security round #6: a Review failover attempt whose admission the |
| 652 | // metered guard refuses (its slot taken between the decision and the |
| 653 | // admission) is held there, with its hold, as the first attempt is: never |
| 654 | // a terminal failure. |
| 655 | func TestPiReviewFailoverHeldByTheGuard(t *testing.T) { |
| 656 | r := newPiRig(t, fakePiInstall(t), bigBudget) |
| 657 | r.urgent() |
| 658 | const second = "tensorx-second000000" |
| 659 | home := filepath.Join(t.TempDir(), second) |
| 660 | os.MkdirAll(home, 0700) |
| 661 | os.WriteFile(filepath.Join(home, provider.TokenFile), []byte(fakepi.TestKey), 0600) |
| 662 | err := r.state.tx(r.ctx, func(tx *sql.Tx) error { |
| 663 | if err := metered.Add(r.ctx, tx, metered.Conn{Connection: "cn_tx2", LocalID: second, Person: connPerson, Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Home: home, Currency: "USD", PriceVersion: metered.Current[wire.ProviderTensorX], Budget: bigBudget}, time.Now()); err != nil { |
| 664 | return err |
| 665 | } |
| 666 | if err := metered.Checked(r.ctx, tx, second, true); err != nil { |
| 667 | return err |
| 668 | } |
| 669 | return provenModels(r.ctx, tx, second, "z-ai/glm-5.3") |
| 670 | }) |
| 671 | if err != nil { |
| 672 | t.Fatal(err) |
| 673 | } |
| 674 | // The first attempt runs on one TensorX key, which is refused; the |
| 675 | // failover is decided onto the other, whose slot another attempt takes |
| 676 | // just before its admission. |
| 677 | r.e.beforeAdmit = func(local string) { |
| 678 | if local != second { |
| 679 | return |
| 680 | } |
| 681 | r.state.tx(r.ctx, func(tx *sql.Tx) error { |
| 682 | _, err := metered.Admit(r.ctx, tx, local, metered.Holder{Step: "other", Attempt: 1, Role: metered.RoleReview, Model: "z-ai/glm-5.3"}, time.Now()) |
| 683 | return err |
| 684 | }) |
| 685 | } |
| 686 | rep := r.runReview("keyrefused", 1) |
| 687 | if rep.State != stepDeferred || rep.Hold == nil || rep.Hold.Reason != wire.HoldBusy || rep.Hold.Connection != second || rep.Attempt != 2 { |
| 688 | t.Fatalf("report %+v, hold %+v", rep, rep.Hold) |
| 689 | } |
| 690 | } |
| 691 | |