package plan3test import ( "context" "crypto/rand" "encoding/json" "errors" "fmt" "io" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type ContinuityFactory func(*testing.T, func(provider.ProcessHost) provider.ProcessHost, provider.CaptureFactory, provider.Binding) (provider.Launcher, provider.Launch, func() error, func()) type continuityHost struct { provider.ProcessHost j *runner.Journal processes []*continuityProcess } type continuityProcess struct { provider.Process record containment.Record } type continuityInput struct{ io.WriteCloser } func (w continuityInput) Close() error { err := w.WriteCloser.Close() if errors.Is(err, os.ErrClosed) { return nil } return err } func (p *continuityProcess) Stdin() io.WriteCloser { return continuityInput{p.Process.Stdin()} } func (p *continuityProcess) ID() string { return p.record.ID } func (p *continuityProcess) Record() containment.Record { return p.record } func (p *continuityProcess) Contain(ctx context.Context) error { _ = p.Stdin().Close() _, err := p.Wait(ctx) return err } func (h *continuityHost) Start(ctx context.Context, l provider.Launch, args []string) (provider.Process, error) { record := containment.Record{ID: rand.Text(), AttemptKey: l.AttemptKey, ManifestHash: l.Policy.ManifestHash, PolicyHash: l.Policy.Hash} if err := h.j.RecordDirectLaunch(ctx, l, record); err != nil { return nil, err } p, err := h.ProcessHost.Start(ctx, l, args) if err != nil { return nil, err } wrapped := &continuityProcess{p, record} h.processes = append(h.processes, wrapped) return wrapped, nil } type continuityAPI struct { claim runnerproto.CoordinatorClaim delivered bool session string receipt bool offered bool } func (a *continuityAPI) CoordinatorCall(_ context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { switch op { case "poll": if !a.offered { *out.(*[]runnerproto.CoordinatorTurn) = []runnerproto.CoordinatorTurn{a.claim.Turn} a.offered = true } case "claim": *out.(*runnerproto.CoordinatorClaim) = a.claim case "renew": *out.(*time.Time) = time.Now().Add(time.Minute) case "event": switch q.Event.Kind { case "session.bound": a.session = q.Event.SessionID case "turn.completed": a.receipt = true case "coordinator.delivery": if !a.receipt { return fmt.Errorf("delivery lacks trusted receipt") } a.delivered = true } case "tool": *out.(*runnerproto.CoordinatorToolResult) = runnerproto.CoordinatorToolResult{ResourceID: "message", Revision: 1, Value: json.RawMessage(`{"tool":"post_message"}`)} case "containment": default: return fmt.Errorf("unexpected fixture call %s", op) } return nil } type continuityLauncher struct { provider.Launcher proxy **runner.ToolProxy t *testing.T prompts *[]string } func (l *continuityLauncher) StartTurn(ctx context.Context, s provider.Session, t provider.Turn) error { *l.prompts = append(*l.prompts, t.Prompt) if err := l.Launcher.StartTurn(ctx, s, t); err != nil { return err } // The recorded CLIs complete without a network tool server. Exercise the real // coordinator broker after their durable stdin barrier, before draining frames. _, err := (*l.proxy).CallCoordinatorTool(ctx, runnerproto.CoordinatorToolCall{RequestID: "post", Name: "post_message", Arguments: json.RawMessage(`{"body":"fixture answer","source_refs":[]}`)}) return err } // RunCoordinatorSessionContinuity uses the real provider adapters and the runner // service, journal, capture and tool broker. Only process and instance I/O are fixtures. func RunCoordinatorSessionContinuity(t *testing.T, name string, factory ContinuityFactory) { t.Helper() ctx := context.Background() path := filepath.Join(t.TempDir(), "private", "journal.db") var source provider.Binding var prior string var prompts []string f, instance, principal, binding := coordinatorFixture(t) if name != binding.ConnectionID { _, err := f.Store.SaveCoordinatorBinding(ctx, owner, principal.RunnerID, name, equipo.Mutation{RequestID: "fixture-provider", Revision: binding.Revision}) must(t, err) } t.Cleanup(schema.Remove) f.exec(t, "UPDATE projects SET name='revoked source'") var revokedProject int64 must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&revokedProject)) retained := equipo.Project{Name: "current scoped source", Repository: "amadan.net/test/retained", DefaultBranch: "main", Kind: equipo.ProjectRepository, Revision: 1, GrantVersion: 1} must(t, f.DB.G.Create(&retained).Error) 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) 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) f.exec(t, "INSERT INTO plan_revisions(task_id,revision,plan) VALUES('confirmed-work',1,'confirmed decision')") 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) f.exec(t, "UPDATE connection_choices SET pinned_id=?", name) pref, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: "deleted preference"}, equipo.Mutation{RequestID: "continuity-preference"}) must(t, err) var conversationID string for i := 0; i < 3; i++ { if i > 0 { credential := "auth.json" if name == "claude" { credential = ".credentials.json" } if err := os.WriteFile(filepath.Join(source.Home, credential), []byte(`{"fake":"same-identity-refresh"}`), 0600); err != nil { t.Fatal(err) } } j, err := runner.OpenJournal(ctx, path) if err != nil { t.Fatal(err) } var host *continuityHost launcher, launch, release, verify := factory(t, func(h provider.ProcessHost) provider.ProcessHost { host = &continuityHost{ProcessHost: h, j: j} return host }, runner.NewCaptureFactory(j), source) b := launch.Binding source = provider.Binding{ID: b.ID, Home: b.CredentialHome, AccountID: b.AccountID, Provider: b.Provider, Expected: b.Expected, RuntimeRoot: b.RuntimeRoot} if other, err := provider.OpenAccount(ctx, source); !errors.Is(err, provider.ErrAccountBusy) { if other != nil { other.Close() } t.Fatal("specialist overlapped coordinator account lease", err) } 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)} 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"}} if i == 1 { pref.Text = "corrected preference" pref, err = f.Store.SetPreference(ctx, owner, pref, equipo.Mutation{RequestID: "continuity-edit", Revision: pref.Revision}) must(t, err) other := "codex" if name == "codex" { other = "claude" } choices, err := json.Marshal([]string{other}) must(t, err) f.exec(t, "UPDATE connection_choices SET connection_ids_json=?,pinned_id=? WHERE project_id=?", string(choices), other, revokedProject) } if i == 2 { must(t, f.Store.DeletePreference(ctx, owner, pref.ID, equipo.Mutation{RequestID: "continuity-delete", Revision: pref.Revision})) } turn := queueCoordinator(t, f, "bounded recent history", fmt.Sprint(i)) claim, err := instance.ClaimCoordinator(ctx, principal, turn.ID, turn.Revision) must(t, err) contextValue := claim.Context if i == 0 { conversationID = contextValue.ConversationID } if contextValue.ConversationID != conversationID { t.Fatal("instance replaced conversation") } c.Context, err = runnerproto.BoundCoordinatorContext(contextValue) must(t, err) // The real instance snapshot is now complete; provider fixture I/O supplies // the runner's ticket/session identities independently below. f.exec(t, "UPDATE coordinator_turns SET state='delivered' WHERE id=?", turn.ID) instance.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) must(t, instance.ContainCoordinator(ctx, principal, claim, runnerproto.ContainmentProof{Scope: claim.Scope, Handle: claim.Handle})) c.Turn.ContextHash = c.Context.Hash 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} api := &continuityAPI{claim: c} var proxy *runner.ToolProxy service := &runner.CoordinatorService{Journal: j, API: api, Launchers: map[string]provider.Launcher{name: &continuityLauncher{Launcher: launcher, proxy: &proxy, t: t, prompts: &prompts}}} service.OpenLaunch = func(_ context.Context, _ runnerproto.CoordinatorClaim, p *runner.ToolProxy) (provider.Launch, func() error, error) { proxy = p launch.ToolSocket = p.SocketPath return launch, release, nil } service.Contain = func(ctx context.Context, c runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) { for _, p := range host.processes { if _, err := p.Wait(ctx); err != nil { return runnerproto.ContainmentProof{}, err } } return runnerproto.ContainmentProof{Version: 2, Scope: c.Scope, Handle: c.Handle, CheckedAt: time.Now()}, nil } if err = service.Poll(ctx); err != nil { j.Close() t.Fatal(name, err) } if !api.delivered || api.session == "" || api.session == prior { t.Fatal("service failed fresh-session delivery", api.session, prior) } if launch.ResumeSessionID != "" { t.Fatal("cross-turn resume requested") } prior = api.session verify() entries, err := os.ReadDir(launch.Binding.RuntimeRoot) if err != nil || len(entries) != 0 { t.Fatal("runtime/config directories survived turn", entries, err) } if _, err = os.Stat(launch.Binding.Home); !os.IsNotExist(err) { t.Fatal("runtime home survived turn", err) } if _, err = os.Stat(proxy.SocketPath); !os.IsNotExist(err) { t.Fatal("tool endpoint survived turn", err) } specialist, err := provider.OpenAccount(ctx, source) if err != nil { t.Fatal("coordinator retained shared home", err) } if other, err := provider.OpenAccount(ctx, source); !errors.Is(err, provider.ErrAccountBusy) { if other != nil { other.Close() } specialist.Close() t.Fatal("coordinator overlapped specialist account lease", err) } if err = specialist.Close(); err != nil { t.Fatal(err) } if err = j.Close(); err != nil { t.Fatal(err) } } for i, prompt := range prompts { if !strings.Contains(prompt, conversationID) || !strings.Contains(prompt, "bounded recent history") || !strings.Contains(prompt, "confirmed decision") || !strings.Contains(prompt, "current scoped source") { t.Fatal("fresh prompt lost instance context") } if i == 0 && (!strings.Contains(prompt, "deleted preference") || !strings.Contains(prompt, "revoked source")) { t.Fatal("first snapshot omitted fixture preference/source") } if i > 0 && (strings.Contains(prompt, "deleted preference") || strings.Contains(prompt, "revoked source")) { t.Fatal("fresh turn retained revoked context") } if i == 1 && !strings.Contains(prompt, "corrected preference") { t.Fatal("fresh session missed correction") } if i == 2 && strings.Contains(prompt, "corrected preference") { t.Fatal("fresh session retained deleted preference") } } }