oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package plan3test
2
3import (
4 "context"
5 "crypto/rand"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "path/filepath"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/equipo"
17 "amadan.net/oficina/equipo/internal/equipo/team"
18 "amadan.net/oficina/equipo/internal/runner"
19 "amadan.net/oficina/equipo/internal/runner/containment"
20 "amadan.net/oficina/equipo/internal/runner/provider"
21 "amadan.net/oficina/equipo/internal/runnerproto"
22)
23
24type ContinuityFactory func(*testing.T, func(provider.ProcessHost) provider.ProcessHost, provider.CaptureFactory, provider.Binding) (provider.Launcher, provider.Launch, func() error, func())
25type continuityHost struct {
26 provider.ProcessHost
27 j *runner.Journal
28 processes []*continuityProcess
29}
30type continuityProcess struct {
31 provider.Process
32 record containment.Record
33}
34type continuityInput struct{ io.WriteCloser }
35
36func (w continuityInput) Close() error {
37 err := w.WriteCloser.Close()
38 if errors.Is(err, os.ErrClosed) {
39 return nil
40 }
41 return err
42}
43func (p *continuityProcess) Stdin() io.WriteCloser { return continuityInput{p.Process.Stdin()} }
44
45func (p *continuityProcess) ID() string { return p.record.ID }
46func (p *continuityProcess) Record() containment.Record { return p.record }
47func (p *continuityProcess) Contain(ctx context.Context) error {
48 _ = p.Stdin().Close()
49 _, err := p.Wait(ctx)
50 return err
51}
52func (h *continuityHost) Start(ctx context.Context, l provider.Launch, args []string) (provider.Process, error) {
53 record := containment.Record{ID: rand.Text(), AttemptKey: l.AttemptKey, ManifestHash: l.Policy.ManifestHash, PolicyHash: l.Policy.Hash}
54 if err := h.j.RecordDirectLaunch(ctx, l, record); err != nil {
55 return nil, err
56 }
57 p, err := h.ProcessHost.Start(ctx, l, args)
58 if err != nil {
59 return nil, err
60 }
61 wrapped := &continuityProcess{p, record}
62 h.processes = append(h.processes, wrapped)
63 return wrapped, nil
64}
65
66type continuityAPI struct {
67 claim runnerproto.CoordinatorClaim
68 delivered bool
69 session string
70 receipt bool
71 offered bool
72}
73
74func (a *continuityAPI) CoordinatorCall(_ context.Context, op string, q runnerproto.CoordinatorRequest, out any) error {
75 switch op {
76 case "poll":
77 if !a.offered {
78 *out.(*[]runnerproto.CoordinatorTurn) = []runnerproto.CoordinatorTurn{a.claim.Turn}
79 a.offered = true
80 }
81 case "claim":
82 *out.(*runnerproto.CoordinatorClaim) = a.claim
83 case "renew":
84 *out.(*time.Time) = time.Now().Add(time.Minute)
85 case "event":
86 switch q.Event.Kind {
87 case "session.bound":
88 a.session = q.Event.SessionID
89 case "turn.completed":
90 a.receipt = true
91 case "coordinator.delivery":
92 if !a.receipt {
93 return fmt.Errorf("delivery lacks trusted receipt")
94 }
95 a.delivered = true
96 }
97 case "tool":
98 *out.(*runnerproto.CoordinatorToolResult) = runnerproto.CoordinatorToolResult{ResourceID: "message", Revision: 1, Value: json.RawMessage(`{"tool":"post_message"}`)}
99 case "containment":
100 default:
101 return fmt.Errorf("unexpected fixture call %s", op)
102 }
103 return nil
104}
105
106type continuityLauncher struct {
107 provider.Launcher
108 proxy **runner.ToolProxy
109 t *testing.T
110 prompts *[]string
111}
112
113func (l *continuityLauncher) StartTurn(ctx context.Context, s provider.Session, t provider.Turn) error {
114 *l.prompts = append(*l.prompts, t.Prompt)
115 if err := l.Launcher.StartTurn(ctx, s, t); err != nil {
116 return err
117 }
118 // The recorded CLIs complete without a network tool server. Exercise the real
119 // coordinator broker after their durable stdin barrier, before draining frames.
120 _, err := (*l.proxy).CallCoordinatorTool(ctx, runnerproto.CoordinatorToolCall{RequestID: "post", Name: "post_message", Arguments: json.RawMessage(`{"body":"fixture answer","source_refs":[]}`)})
121 return err
122}
123
124// RunCoordinatorSessionContinuity uses the real provider adapters and the runner
125// service, journal, capture and tool broker. Only process and instance I/O are fixtures.
126func RunCoordinatorSessionContinuity(t *testing.T, name string, factory ContinuityFactory) {
127 t.Helper()
128 ctx := context.Background()
129 path := filepath.Join(t.TempDir(), "private", "journal.db")
130 var source provider.Binding
131 var prior string
132 var prompts []string
133 f, instance, principal, binding := coordinatorFixture(t)
134 if name != binding.ConnectionID {
135 _, err := f.Store.SaveCoordinatorBinding(ctx, owner, principal.RunnerID, name, equipo.Mutation{RequestID: "fixture-provider", Revision: binding.Revision})
136 must(t, err)
137 }
138 t.Cleanup(schema.Remove)
139 f.exec(t, "UPDATE projects SET name='revoked source'")
140 var revokedProject int64
141 must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&revokedProject))
142 retained := equipo.Project{Name: "current scoped source", Repository: "amadan.net/test/retained", DefaultBranch: "main", Kind: equipo.ProjectRepository, Revision: 1, GrantVersion: 1}
143 must(t, f.DB.G.Create(&retained).Error)
144 f.exec(t, `INSERT INTO connection_choices(person,project_id,revision,connection_ids_json,pinned_id) VALUES(?,?,1,'["claude","codex"]','claude')`, owner.Address, retained.ID)
145 f.exec(t, "INSERT INTO tasks(id,requester,request_id,project_id,team_id,state,kind,plan_revision,approval_revision,revision) VALUES('confirmed-work',?,'confirmed-work',?,?,'proposed','bug',1,1,1)", owner.Address, retained.ID, f.TeamID)
146 f.exec(t, "INSERT INTO plan_revisions(task_id,revision,plan) VALUES('confirmed-work',1,'confirmed decision')")
147 f.exec(t, `INSERT INTO plan_requests(principal,operation,resource,request_id,result) VALUES(?,'plan.approve','confirmed-work','approved','{"ApprovalRevision":1,"PlanRevision":1}')`, owner.Address)
148 f.exec(t, "UPDATE connection_choices SET pinned_id=?", name)
149 pref, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: "deleted preference"}, equipo.Mutation{RequestID: "continuity-preference"})
150 must(t, err)
151 var conversationID string
152 for i := 0; i < 3; i++ {
153 if i > 0 {
154 credential := "auth.json"
155 if name == "claude" {
156 credential = ".credentials.json"
157 }
158 if err := os.WriteFile(filepath.Join(source.Home, credential), []byte(`{"fake":"same-identity-refresh"}`), 0600); err != nil {
159 t.Fatal(err)
160 }
161 }
162 j, err := runner.OpenJournal(ctx, path)
163 if err != nil {
164 t.Fatal(err)
165 }
166 var host *continuityHost
167 launcher, launch, release, verify := factory(t, func(h provider.ProcessHost) provider.ProcessHost {
168 host = &continuityHost{ProcessHost: h, j: j}
169 return host
170 }, runner.NewCaptureFactory(j), source)
171 b := launch.Binding
172 source = provider.Binding{ID: b.ID, Home: b.CredentialHome, AccountID: b.AccountID, Provider: b.Provider, Expected: b.Expected, RuntimeRoot: b.RuntimeRoot}
173 if other, err := provider.OpenAccount(ctx, source); !errors.Is(err, provider.ErrAccountBusy) {
174 if other != nil {
175 other.Close()
176 }
177 t.Fatal("specialist overlapped coordinator account lease", err)
178 }
179 c := runnerproto.CoordinatorClaim{Binding: runnerproto.CoordinatorBinding{ID: "binding", Person: "person", Generation: 1}, Turn: runnerproto.CoordinatorTurn{ID: fmt.Sprint(i), Revision: 1, Generation: 1}, Scope: team.Scope{Account: "team", Job: team.JobID(i + 1)}, Handle: team.Handle{Attempt: team.AttemptID(i + 1), Fence: 1, Runner: "runner"}, LeaseDeadline: time.Now().Add(time.Minute), AttemptDeadline: time.Now().Add(time.Minute)}
180 c.Brief.Selection = runnerproto.Selection{Provider: launch.Selection.Provider, Model: launch.Selection.Model, Family: launch.Selection.Family, AccountID: launch.Selection.AccountID, Isolation: team.IsolationSnapshot{Status: "confined"}}
181 if i == 1 {
182 pref.Text = "corrected preference"
183 pref, err = f.Store.SetPreference(ctx, owner, pref, equipo.Mutation{RequestID: "continuity-edit", Revision: pref.Revision})
184 must(t, err)
185 other := "codex"
186 if name == "codex" {
187 other = "claude"
188 }
189 choices, err := json.Marshal([]string{other})
190 must(t, err)
191 f.exec(t, "UPDATE connection_choices SET connection_ids_json=?,pinned_id=? WHERE project_id=?", string(choices), other, revokedProject)
192 }
193 if i == 2 {
194 must(t, f.Store.DeletePreference(ctx, owner, pref.ID, equipo.Mutation{RequestID: "continuity-delete", Revision: pref.Revision}))
195 }
196 turn := queueCoordinator(t, f, "bounded recent history", fmt.Sprint(i))
197 claim, err := instance.ClaimCoordinator(ctx, principal, turn.ID, turn.Revision)
198 must(t, err)
199 contextValue := claim.Context
200 if i == 0 {
201 conversationID = contextValue.ConversationID
202 }
203 if contextValue.ConversationID != conversationID {
204 t.Fatal("instance replaced conversation")
205 }
206 c.Context, err = runnerproto.BoundCoordinatorContext(contextValue)
207 must(t, err)
208 // The real instance snapshot is now complete; provider fixture I/O supplies
209 // the runner's ticket/session identities independently below.
210 f.exec(t, "UPDATE coordinator_turns SET state='delivered' WHERE id=?", turn.ID)
211 instance.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
212 must(t, instance.ContainCoordinator(ctx, principal, claim, runnerproto.ContainmentProof{Scope: claim.Scope, Handle: claim.Handle}))
213 c.Turn.ContextHash = c.Context.Hash
214 c.Admission = team.AdmissionTicket{Scope: c.Scope, Handle: c.Handle, Dispatch: team.Dispatch{Action: team.ActionID(i + 1)}, ExpiresAt: time.Now().Add(5 * time.Second), Incarnation: 1}
215 api := &continuityAPI{claim: c}
216 var proxy *runner.ToolProxy
217 service := &runner.CoordinatorService{Journal: j, API: api, Launchers: map[string]provider.Launcher{name: &continuityLauncher{Launcher: launcher, proxy: &proxy, t: t, prompts: &prompts}}}
218 service.OpenLaunch = func(_ context.Context, _ runnerproto.CoordinatorClaim, p *runner.ToolProxy) (provider.Launch, func() error, error) {
219 proxy = p
220 launch.ToolSocket = p.SocketPath
221 return launch, release, nil
222 }
223 service.Contain = func(ctx context.Context, c runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) {
224 for _, p := range host.processes {
225 if _, err := p.Wait(ctx); err != nil {
226 return runnerproto.ContainmentProof{}, err
227 }
228 }
229 return runnerproto.ContainmentProof{Version: 2, Scope: c.Scope, Handle: c.Handle, CheckedAt: time.Now()}, nil
230 }
231 if err = service.Poll(ctx); err != nil {
232 j.Close()
233 t.Fatal(name, err)
234 }
235 if !api.delivered || api.session == "" || api.session == prior {
236 t.Fatal("service failed fresh-session delivery", api.session, prior)
237 }
238 if launch.ResumeSessionID != "" {
239 t.Fatal("cross-turn resume requested")
240 }
241 prior = api.session
242 verify()
243 entries, err := os.ReadDir(launch.Binding.RuntimeRoot)
244 if err != nil || len(entries) != 0 {
245 t.Fatal("runtime/config directories survived turn", entries, err)
246 }
247 if _, err = os.Stat(launch.Binding.Home); !os.IsNotExist(err) {
248 t.Fatal("runtime home survived turn", err)
249 }
250 if _, err = os.Stat(proxy.SocketPath); !os.IsNotExist(err) {
251 t.Fatal("tool endpoint survived turn", err)
252 }
253 specialist, err := provider.OpenAccount(ctx, source)
254 if err != nil {
255 t.Fatal("coordinator retained shared home", err)
256 }
257 if other, err := provider.OpenAccount(ctx, source); !errors.Is(err, provider.ErrAccountBusy) {
258 if other != nil {
259 other.Close()
260 }
261 specialist.Close()
262 t.Fatal("coordinator overlapped specialist account lease", err)
263 }
264 if err = specialist.Close(); err != nil {
265 t.Fatal(err)
266 }
267 if err = j.Close(); err != nil {
268 t.Fatal(err)
269 }
270 }
271 for i, prompt := range prompts {
272 if !strings.Contains(prompt, conversationID) || !strings.Contains(prompt, "bounded recent history") || !strings.Contains(prompt, "confirmed decision") || !strings.Contains(prompt, "current scoped source") {
273 t.Fatal("fresh prompt lost instance context")
274 }
275 if i == 0 && (!strings.Contains(prompt, "deleted preference") || !strings.Contains(prompt, "revoked source")) {
276 t.Fatal("first snapshot omitted fixture preference/source")
277 }
278 if i > 0 && (strings.Contains(prompt, "deleted preference") || strings.Contains(prompt, "revoked source")) {
279 t.Fatal("fresh turn retained revoked context")
280 }
281 if i == 1 && !strings.Contains(prompt, "corrected preference") {
282 t.Fatal("fresh session missed correction")
283 }
284 if i == 2 && strings.Contains(prompt, "corrected preference") {
285 t.Fatal("fresh session retained deleted preference")
286 }
287 }
288}
289