package thin import ( "amadan.net/oficina/equipo/internal/runner/workspace" "context" "crypto/sha256" "database/sql" "encoding/hex" "encoding/json" "log/slog" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/fakepi" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/metered" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/pi" "amadan.net/oficina/equipo/internal/testci" "amadan.net/oficina/equipo/internal/wire" ) const piLocal = "tensorx-abcdef012345" // piRig is a runner with one Claude connection, Engineering's (limited // now), and one metered TensorX connection run by Pi, in the real // containment; a task branch with one change for Review to judge. type piRig struct { // local is the metered connection's local id (piLocal for TensorX). local string t *testing.T ctx context.Context e *Engineer state *State conns *Conns review stepRow } func copySelf(t *testing.T, dir, name string) string { t.Helper() self, err := os.Executable() if err != nil { t.Fatal(err) } raw, err := os.ReadFile(self) if err != nil { t.Fatal(err) } p := filepath.Join(dir, name) if err := os.WriteFile(p, raw, 0755); err != nil { t.Fatal(err) } return p } // fakePiInstall is fakepi as the Pi CLI, run by a copy of this binary as // Node, with its own digests as the pins. func fakePiInstall(t *testing.T) pi.Install { t.Helper() dir := t.TempDir() node := copySelf(t, dir, "node") tree := filepath.Join(dir, "pi", "node_modules") cli := filepath.Join(tree, "@earendil-works/pi-coding-agent/dist/bundle/cli.js") os.MkdirAll(filepath.Dir(cli), 0755) if err := os.WriteFile(cli, []byte("// fakepi\n"), 0644); err != nil { t.Fatal(err) } if err := pi.Seal(tree); err != nil { t.Fatal(err) } t.Cleanup(func() { filepath.Walk(tree, func(p string, info os.FileInfo, err error) error { if err == nil && info.IsDir() { os.Chmod(p, 0755) } return nil }) }) sum, err := pi.TreeSHA256(tree) if err != nil { t.Fatal(err) } raw, _ := os.ReadFile(node) return pi.Install{Node: node, Tree: tree, NodeSHA256: sha256Hex(raw), TreeSHA256: sum} } // realPiInstall is the pinned Pi this machine has (EQUIPO_PI_ROOT). func realPiInstall(t *testing.T) pi.Install { t.Helper() root := os.Getenv("EQUIPO_PI_ROOT") if root == "" { testci.Absent(t, "the pinned Pi (EQUIPO_PI_ROOT) is absent") } testci.Tools(t, "pi") node, tree := pi.Paths(root) inst, ok := pi.Install{Node: node, Tree: tree}.Pinned() if !ok { t.Skip("no Pi pins for this platform") } return inst } func newPiRig(t *testing.T, inst pi.Install, budget wire.Budget) *piRig { t.Helper() 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} }) } // rigConn is a metered rig's one metered connection. type rigConn struct { local, provider, harness, upstream, model, key string } // newMeteredRig is the rig with conn as its metered connection, its // harness's install set by install. func newMeteredRig(t *testing.T, budget wire.Budget, conn rigConn, install func(*Engineer)) *piRig { t.Helper() testci.Tools(t, "bwrap", "git") if _, err := os.Stat("/usr/bin/bwrap"); err != nil { testci.Absent(t, "bubblewrap is absent") } // A short root: the tool socket's path must fit a socket address. root, err := os.MkdirTemp("", "pi-") if err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(root) }) for _, d := range []string{"state", "work", "scratch", "sessions", "bin", "clones"} { if err := os.MkdirAll(filepath.Join(root, d), 0700); err != nil { t.Fatal(err) } } // The repository: main at base, the task branch one change on. seed := filepath.Join(root, "seed") gitOut(t, root, "init", "-q", "-b", "main", seed) os.WriteFile(filepath.Join(seed, "README.md"), []byte("teh panes\n"), 0644) gitOut(t, seed, "add", "-A") gitOut(t, seed, "commit", "-q", "-m", "base") base := gitOut(t, seed, "rev-parse", "HEAD") gitOut(t, seed, "checkout", "-q", "-b", "equipo/tk1-fix-typo") os.WriteFile(filepath.Join(seed, "README.md"), []byte("the panes\n"), 0644) gitOut(t, seed, "commit", "-q", "-am", "fix") cand := gitOut(t, seed, "rev-parse", "HEAD") remote := filepath.Join(root, "remote.git") gitOut(t, root, "clone", "-q", "--bare", seed, remote) state, err := OpenState(context.Background(), filepath.Join(root, "state")) if err != nil { t.Fatal(err) } t.Cleanup(func() { state.Close() }) // Engineering's connection: Claude, limited now. home := filepath.Join(root, "accounts", "claude-a") os.MkdirAll(home, 0700) identity := map[string]string{"account_id": "a@example.com", "home_id": "h-a", "provider_version": "1"} 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}}) bindings := filepath.Join(root, "bindings.json") os.WriteFile(bindings, raw, 0600) self, _ := os.Executable() 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")} m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: cfg.ScratchRoot}) if err != nil { testci.Absent(t, "namespaces are unavailable: "+err.Error()) } conns := &Conns{Runner: cfg, State: state} conns.Meter = &metered.Meter{DB: state.db} conns.Validated("claude-a") conns.Limit("claude-a", connect.Limit{Limited: true, ResetsAt: time.Now().Add(time.Hour)}) // The metered connection, its key 0600 in its home. keyHome := filepath.Join(root, "accounts", conn.local) os.MkdirAll(keyHome, 0700) if err := os.WriteFile(filepath.Join(keyHome, provider.TokenFile), []byte(conn.key), 0600); err != nil { t.Fatal(err) } ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) err = state.tx(ctx, func(tx *sql.Tx) error { 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 { return err } if err := metered.Checked(ctx, tx, conn.local, true); err != nil { return err } // A connection as S1 made it, migrated (§16.5): its one model, // proven. return provenModels(ctx, tx, conn.local, conn.model) }) if err != nil { t.Fatal(err) } f := &hubForge{dir: remote} 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"} install(e) 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{}}} return &piRig{local: conn.local, t: t, ctx: ctx, e: e, state: state, conns: conns, review: review} } // urgent gives the rig's steps leave to spend the way S3 gives it: the // task is urgent (the person's tap). func (r *piRig) urgent() { r.review.Priority = wire.PriorityUrgent } func (r *piRig) runReview(brief string, attempt int64) wire.StepReport { r.t.Helper() row := r.review // One running step per task: each run is its own task's. row.Brief, row.StepID, row.TaskID = brief, row.StepID+"-"+itoa(attempt), row.TaskID+"-"+itoa(attempt) if err := r.state.AcceptDispatch(r.ctx, "f-"+row.StepID, row.DispatchCommand); err != nil { r.t.Fatal(err) } return r.e.review(r.ctx, row, func(wire.StepReport) {}) } func (r *piRig) conn() metered.Conn { r.t.Helper() c, ok, err := metered.Get(r.ctx, r.state.db, r.local) if err != nil || !ok { r.t.Fatal(err) } return c } func (r *piRig) charges() int { var n int if err := r.state.db.QueryRow("SELECT count(*) FROM budget_charge WHERE connection=?", r.local).Scan(&n); err != nil { r.t.Fatal(err) } return n } func (r *piRig) slotFree() bool { var holder string if err := r.state.db.QueryRow("SELECT holder FROM metered_slot WHERE local_id=?", r.local).Scan(&holder); err != nil && err != sql.ErrNoRows { r.t.Fatal(err) } return holder == "" } var bigBudget = wire.Budget{Day: 1_000_000, Month: 10_000_000, Revision: 1} // provenModels gives a metered connection the allowed set models at // revision 1, each proven healthy, as the S5b migration leaves an S1 // connection (§16.5). func provenModels(ctx context.Context, tx *sql.Tx, local string, models ...string) error { if err := metered.InitModels(ctx, tx, local, models, 1); err != nil { return err } for _, m := range models { if err := metered.MarkModel(ctx, tx, local, m, wire.ModelHealthy, "", time.Now()); err != nil { return err } } return nil } // A Review step of a Claude change runs on TensorX through Pi when the // step has leave to spend and no subscription can review: other_family, // judged on the model that ran (glm), its verdict through Equipo's // tool, its usage priced and charged once, the slot released after the // proof, and its session kept so the person can ask it. func TestPiReviewStep(t *testing.T) { r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() rep := r.runReview("", 1) if rep.State != wire.StepDone || rep.Verdict != wire.VerdictApprove || rep.ReviewLabel != wire.ReviewOtherFamily || rep.Family != "glm" || rep.Account != piLocal || !rep.Termination { t.Fatalf("report %+v", rep) } if !rep.Askable { t.Fatal("the session was not kept for questions") } 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 { t.Fatalf("usage %+v", rep.Usage) } if n := r.charges(); n != 1 || !r.slotFree() || r.conn().SpendUnknown { t.Fatalf("charges %d, slot free %v, spend unknown %v", n, r.slotFree(), r.conn().SpendUnknown) } // Admitted through the scheduler, in the guard's transaction: the // urgent task's leave. var reason, conn string 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 { t.Fatalf("admission %q on %q: %v", reason, conn, err) } // A resent usage row charges once. 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 { t.Fatal(err) } if n := r.charges(); n != 1 { t.Fatalf("a resent row charged again: %d", n) } } // Without leave to spend (a normal task, no Run now), Review is never // chosen onto the metered connection: with Engineering's connection // limited it is held for headroom on it, and nothing runs. func TestPiReviewWithoutLeaveToSpend(t *testing.T) { r := newPiRig(t, fakePiInstall(t), bigBudget) rep := r.runReview("", 1) if rep.State != stepDeferred || rep.Hold == nil || rep.Hold.Reason != wire.HoldHeadroom || rep.Hold.Connection != "claude-a" || r.charges() != 0 { t.Fatalf("report %+v, hold %+v, charges %d", rep, rep.Hold, r.charges()) } } // The budget stops the next step: once the reported spend reaches it, // the next Review is held (deferred), not run. func TestPiBudgetHoldsTheNextStep(t *testing.T) { r := newPiRig(t, fakePiInstall(t), wire.Budget{Day: 1, Month: 1_000, Revision: 1}) r.urgent() if rep := r.runReview("", 1); rep.State != wire.StepDone { t.Fatalf("first: %+v", rep) } rep := r.runReview("", 2) if rep.State != stepDeferred || r.charges() != 1 { t.Fatalf("after the budget: %+v, charges %d", rep, r.charges()) } } // A step with no usage figure (Pi ended before its message_end) pauses // the connection: spend unknown, and nothing more is admitted. func TestPiNoUsagePausesTheConnection(t *testing.T) { r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() rep := r.runReview("nousage", 1) if rep.State != wire.StepFailed || !r.conn().SpendUnknown || !r.slotFree() { t.Fatalf("report %s %s, spend unknown %v slot free %v", rep.State, rep.Reason, r.conn().SpendUnknown, r.slotFree()) } if rep := r.runReview("", 2); rep.State != stepDeferred { t.Fatalf("admitted while spend unknown: %+v", rep) } } // A key TensorX refuses (a revoked key, or a balance under $0.05) marks // the connection refused: sign in again, never limited. func TestPiKeyRefused(t *testing.T) { r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() rep := r.runReview("keyrefused", 1) if rep.State == wire.StepDone || !r.conn().Refused { t.Fatalf("report %+v, refused %v", rep, r.conn().Refused) } if rep.Switched == nil || rep.Switched.From != wire.ProviderTensorX { t.Fatalf("switched %+v", rep.Switched) } } // The S2 finish line, in CI: the same Review step with the real pinned // Pi against a fake TensorX on 127.0.0.1, recorded other_family. func TestPiReviewStepRealPi(t *testing.T) { inst := realPiInstall(t) tensorx := fakepi.StartTensorX(t) was := testPiCA testPiCA = func() string { return tensorx.CA } t.Cleanup(func() { testPiCA = was }) r := newPiRig(t, inst, bigBudget) r.urgent() rep := r.runReview("", 1) if rep.State != wire.StepDone || rep.Verdict != wire.VerdictApprove || rep.ReviewLabel != wire.ReviewOtherFamily || rep.Family != "glm" || !strings.Contains(rep.Summary, "TensorX") { t.Fatalf("report %+v", rep) } if len(rep.Usage) != 1 || !rep.Usage[0].Complete || rep.Usage[0].CostMicros == nil || r.charges() != 1 || !r.slotFree() { t.Fatalf("usage %+v charges %d", rep.Usage, r.charges()) } seen := tensorx.Seen() if len(seen) == 0 || seen[0].Auth != "Bearer "+fakepi.TestKey { t.Fatalf("provider saw %+v", seen) } for _, req := range seen { for _, tool := range req.Tools { if tool == "bash" || tool == "write" || tool == "edit" { t.Fatalf("Review declared %v", req.Tools) } } } // A question resumes the Review's own session on its connection: Pi // sends the Review's history with it. 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?"}} if err := r.state.AcceptAsk(r.ctx, "f-q1", a.AskCommand); err != nil { t.Fatal(err) } se := &StepEngine{State: r.state, Meter: r.conns.Meter, MeteredAsk: r.e.askPi, Notify: func() {}} se.askMetered(r.ctx, r.ctx, a, piLocal, r.conn().Model, func(wire.AnswerReport) {}) after := tensorx.Seen() if len(after) <= len(seen) || after[len(after)-1].Messages <= seen[len(seen)-1].Messages || r.charges() != 2 { 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()) } } func sha256Hex(raw []byte) string { sum := sha256.Sum256(raw) return hex.EncodeToString(sum[:]) } // testWriter sends the runner's log lines to the test's log. type testWriter struct{ t *testing.T } func (w testWriter) Write(p []byte) (int, error) { w.t.Log(strings.TrimSpace(string(p))) return len(p), nil } // A question about a Review that ran on Pi stays on its step's own // session and connection (connectors spec §7): through the metered // guard, the kept session resumed (Pi sees the review in it), the // answer charged. func TestPiAskKeptSession(t *testing.T) { r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() rep := r.runReview("", 1) if !rep.Askable { t.Fatalf("not askable: %+v", rep) } 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?"}} if err := r.state.AcceptAsk(r.ctx, "f-q1", a.AskCommand); err != nil { t.Fatal(err) } se := &StepEngine{State: r.state, Meter: r.conns.Meter, MeteredAsk: r.e.askPi, Notify: func() {}} local, model, ok := se.meteredAsk(r.ctx, a) if !ok || local != piLocal { t.Fatalf("the question is not on its metered connection: %q %v", local, ok) } se.askMetered(r.ctx, r.ctx, a, local, model, func(wire.AnswerReport) {}) frames, _, err := r.state.Unacked(r.ctx, 0) if err != nil { t.Fatal(err) } var answer wire.AnswerReport for _, f := range frames { var v wire.AnswerReport if f.Type == wire.FrameAnswer && json.Unmarshal(f.Data, &v) == nil && v.QuestionID == "q1" && v.State == wire.QuestionAnswered { answer = v } } if !strings.Contains(answer.Text, "message 2") || len(answer.Usage) != 1 || answer.Usage[0].CostMicros == nil { t.Fatalf("answer %+v", answer) } if n := r.charges(); n != 2 || !r.slotFree() { t.Fatalf("charges %d slot free %v", n, r.slotFree()) } } // Engineering on Pi: its tools inside the namespace, the workspace // writable, charged as an Engineering attempt. func TestPiEngineeringRun(t *testing.T) { r := newPiRig(t, fakePiInstall(t), bigBudget) work := t.TempDir() os.WriteFile(filepath.Join(work, "README.md"), []byte("teh panes\n"), 0644) b := r.conns.MeteredMine(r.ctx, connPerson) if len(b) != 1 || b[0].Family != "glm" || !Metered(b[0]) { t.Fatalf("metered bindings %+v", b) } row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk9", StepID: "en1", Attempt: 1, Specialist: wire.SpecialistEngineering}} 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"}) raw, _ := os.ReadFile(filepath.Join(work, "README.md")) if res.reason != "" || !res.terminated || string(raw) != "the panes\n" { t.Fatalf("run %+v; README %q", res, raw) } var role string if err := r.state.db.QueryRow("SELECT holder FROM budget_charge WHERE connection=?", piLocal).Scan(&role); err != nil || !strings.HasPrefix(role, metered.RoleEngineering+"|") { t.Fatalf("charged as %q: %v", role, err) } } // Review's independence is judged on the model that ran (connectors spec // §3, "Families"): Engineering ran on this same TensorX connection (glm), // so Review there is the same account, unless another family's model // answered. func TestPiReviewFamilyFromTheModelThatRan(t *testing.T) { r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() r.review.AvoidAccount = piLocal if rep := r.runReview("", 1); rep.State != wire.StepDone || rep.ReviewLabel != wire.ReviewSameAccount || rep.Family != "glm" { t.Fatalf("same model: %+v", rep) } rep := r.runReview("answeredby:deepseek/deepseek-v4-pro-0813", 2) if rep.State != wire.StepDone || rep.ReviewLabel != wire.ReviewOtherFamily || rep.Family != "deepseek" { t.Fatalf("another model: %+v", rep) } } // In a step nobody can answer the extension's question: a call it asks // about is refused, and the step goes on. func TestPiStepRefusesAsks(t *testing.T) { r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() rep := r.runReview("read:/etc/hostname", 1) if rep.State != wire.StepDone || !strings.Contains(rep.LogTail, "Refused a call") || !strings.Contains(rep.LogTail, "read /etc/hostname refused") { t.Fatalf("report %+v", rep) } } // An Engineering step the metered guard holds waits, deferred: here the // budget, which the Review before it reached. func TestPiEngineeringHeldIsDeferred(t *testing.T) { r := newPiRig(t, fakePiInstall(t), wire.Budget{Day: 1, Month: 1_000, Revision: 1}) r.urgent() if rep := r.runReview("", 1); rep.State != wire.StepDone { t.Fatalf("review: %+v", rep) } 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}} if err := r.state.AcceptDispatch(r.ctx, "f-en5", row.DispatchCommand); err != nil { t.Fatal(err) } row.Base = r.review.BaseSHA rep := r.e.Exec(r.ctx, row, func(wire.StepReport) {}) if rep.State != stepDeferred || r.charges() != 1 { t.Fatalf("report %+v, charges %d", rep, r.charges()) } } // A run that ends properly (agent_end) with no usage figure is unknown // spend too, never a charge of zero. func TestPiEndWithoutUsagePausesTheConnection(t *testing.T) { r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() r.runReview("endnousage", 1) if !r.conn().SpendUnknown || !r.slotFree() { t.Fatalf("spend unknown %v, slot free %v", r.conn().SpendUnknown, r.slotFree()) } } // A reply over the text the runner keeps ends the run, its usage // incomplete, so the connection's spend is unknown. (Review's verdict, // given through Equipo's tool before the flood, still stands.) func TestPiOversizedReply(t *testing.T) { was := piTextLimit piTextLimit = 1000 t.Cleanup(func() { piTextLimit = was }) r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() rep := r.runReview("flood:50000", 1) if !strings.Contains(rep.LogTail, "The reply was too long") || !r.conn().SpendUnknown || len(rep.Summary) > 1000 { t.Fatalf("report %s %s summary %d, spend unknown %v", rep.State, rep.Reason, len(rep.Summary), r.conn().SpendUnknown) } } // A step can read the key (connectors spec §2.1), so whatever Pi says is // redacted before the runner logs or reports it: the reply (the key split // across two deltas), the verdict it records through Equipo's tool, the // tail and the step's log. func TestPiRedactsTheKey(t *testing.T) { r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() var logs strings.Builder r.e.O.Logger = slog.New(slog.NewTextHandler(&logs, nil)) rep := r.runReview("echokey", 1) if rep.State != wire.StepDone { t.Fatalf("report %+v", rep) } raw, _ := json.Marshal(rep) steps, _ := os.ReadDir(r.e.root()) var stepLog []byte for _, d := range steps { b, _ := os.ReadFile(filepath.Join(r.e.root(), d.Name(), "log.jsonl")) stepLog = append(stepLog, b...) } for what, text := range map[string]string{"the report": string(raw), "the step log": string(stepLog), "the runner log": logs.String()} { if strings.Contains(text, fakepi.TestKey) { t.Errorf("%s holds the key", what) } } if !strings.Contains(string(stepLog), "[redacted]") || !strings.Contains(rep.Summary+rep.Headline, "[redacted]") { t.Fatalf("nothing was redacted: summary %q headline %q", rep.Summary, rep.Headline) } } // A kept Pi Engineering session stays put (spec §7, rule 1): its fix // round resumes on the metered connection even when a subscription is // usable again; when the guard bars spending there (a busy slot, the // budget), the round is held on it, never moved. func TestPiKeptSessionStaysPut(t *testing.T) { r := newPiRig(t, fakePiInstall(t), wire.Budget{Day: 1, Month: 1_000, Revision: 1}) r.urgent() // Round 0 ran on TensorX and kept its Pi session. dir := filepath.Join(t.TempDir(), "kept") os.MkdirAll(dir, 0700) session := pi.NewSessionID() if err := os.WriteFile(filepath.Join(dir, "2026-11-12T00-00-00-000Z_"+session+".jsonl"), []byte(`{"type":"session"}`+"\n"), 0600); err != nil { t.Fatal(err) } base := r.review.CandidateSHA round0 := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk7", StepID: "e0", Attempt: 1, Specialist: wire.SpecialistEngineering}} if err := r.state.keepSession(r.ctx, round0, wire.SpecialistEngineering, piLocal, "z-ai/glm-5.3", "glm", session, dir, base, 10); err != nil { t.Fatal(err) } // Claude is usable again: its limit's reset (an hour on) has passed. r.conns.now = func() time.Time { return time.Now().Add(2 * time.Hour) } if _, _, err := r.conns.Choose(r.ctx, connPerson, connect.RoleEngineering, "", nil); err != nil { t.Fatalf("Claude is not usable: %v", err) } 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} plan := func() (string, bool) { t.Helper() kept, ok := r.e.fixSession(r.ctx, row, base) if !ok { t.Fatal("the kept Pi session was not found") } b, resume, hold, _, err := r.e.fixPlan(r.ctx, row, nil, kept, ok) if err != nil { t.Fatal(err) } if hold != nil { return hold.Connection, false } return b.ID, resume } if id, resume := plan(); id != piLocal || !resume { t.Fatalf("the round moved: %s resume %v", id, resume) } // Busy: another attempt holds the slot. The round is held there. err := r.state.tx(r.ctx, func(tx *sql.Tx) error { _, err := metered.Admit(r.ctx, tx, piLocal, metered.Holder{Step: "other", Attempt: 1, Role: metered.RoleReview, Model: "z-ai/glm-5.3"}, time.Now()) return err }) if err != nil { t.Fatal(err) } if err := r.state.AcceptDispatch(r.ctx, "f-e1", row.DispatchCommand); err != nil { t.Fatal(err) } if rep := r.e.Exec(r.ctx, row, func(wire.StepReport) {}); rep.State != stepDeferred { t.Fatalf("busy: %+v", rep) } if id, _ := plan(); id != piLocal { t.Fatalf("after a hold the round moved to %s", id) } // The budget: the slot free again, today's spend past the budget. Held // there again. other := metered.Holder{Step: "other", Attempt: 1, Role: metered.RoleReview, Model: "z-ai/glm-5.3"} in, out := int64(1_000_000), int64(1_000) err = r.state.tx(r.ctx, func(tx *sql.Tx) error { 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 { return err } return metered.Settle(r.ctx, tx, piLocal, other, metered.Ending{Proven: true}) }) if err != nil { t.Fatal(err) } if !r.slotFree() || r.charges() != 1 { t.Fatalf("slot free %v charges %d", r.slotFree(), r.charges()) } if rep := r.e.Exec(r.ctx, row, func(wire.StepReport) {}); rep.State != stepDeferred { t.Fatalf("budget: %+v", rep) } if id, _ := plan(); id != piLocal { t.Fatalf("after the budget hold the round moved to %s", id) } } // Security round #6: a Review failover attempt whose admission the // metered guard refuses (its slot taken between the decision and the // admission) is held there, with its hold, as the first attempt is: never // a terminal failure. func TestPiReviewFailoverHeldByTheGuard(t *testing.T) { r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() const second = "tensorx-second000000" home := filepath.Join(t.TempDir(), second) os.MkdirAll(home, 0700) os.WriteFile(filepath.Join(home, provider.TokenFile), []byte(fakepi.TestKey), 0600) err := r.state.tx(r.ctx, func(tx *sql.Tx) error { 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 { return err } if err := metered.Checked(r.ctx, tx, second, true); err != nil { return err } return provenModels(r.ctx, tx, second, "z-ai/glm-5.3") }) if err != nil { t.Fatal(err) } // The first attempt runs on one TensorX key, which is refused; the // failover is decided onto the other, whose slot another attempt takes // just before its admission. r.e.beforeAdmit = func(local string) { if local != second { return } r.state.tx(r.ctx, func(tx *sql.Tx) error { _, err := metered.Admit(r.ctx, tx, local, metered.Holder{Step: "other", Attempt: 1, Role: metered.RoleReview, Model: "z-ai/glm-5.3"}, time.Now()) return err }) } rep := r.runReview("keyrefused", 1) if rep.State != stepDeferred || rep.Hold == nil || rep.Hold.Reason != wire.HoldBusy || rep.Hold.Connection != second || rep.Attempt != 2 { t.Fatalf("report %+v, hold %+v", rep, rep.Hold) } }