package runner import ( "context" "encoding/json" "fmt" "os" "path/filepath" "strings" "sync" "testing" "amadan.net/oficina/equipo/internal/runner/egress" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/workspace" ) type graphCLI struct { j *Journal host provider.ProcessHost mu sync.Mutex sessions map[string]*graphCLISession proxies map[string]*ToolProxy } type graphCLISession struct { session provider.Session capture *provider.Capture events chan provider.Event turn string mu sync.Mutex } func fakeDirectGraph(t *testing.T, j *Journal, host provider.ProcessHost, root, scratch, helper string, progressFrames int) (map[string]provider.Launcher, func(context.Context, RunClaim, workspace.Workspace, *ToolProxy) (provider.Launch, func() error, error)) { f := &graphCLI{j: j, host: host, sessions: map[string]*graphCLISession{}, proxies: map[string]*ToolProxy{}} binary := filepath.Join(root, "fake-cli") script := strings.ReplaceAll(graphScript, "PROGRESS_FRAMES", fmt.Sprint(progressFrames)) wfMust(t, os.WriteFile(binary, []byte(script), 0700)) launch := func(ctx context.Context, c RunClaim, ws workspace.Workspace, proxy *ToolProxy) (provider.Launch, func() error, error) { name := c.Assignment.Selection.Provider home := filepath.Join(root, "fixture-account-"+c.Assignment.StepKey) wfMust(t, os.Mkdir(home, 0700)) id := provider.Identity{AccountID: "account", HomeID: "fake-" + c.Assignment.StepKey, ProviderVersion: map[string]string{"claude": "2.1.312", "codex": "0.165.0"}[name]} wfMust(t, os.WriteFile(filepath.Join(home, provider.IdentityFile), marshal(id), 0600)) credential := map[string]string{"claude": ".credentials.json", "codex": "auth.json"}[name] wfMust(t, os.WriteFile(filepath.Join(home, credential), []byte(`{"fixture":true}`), 0600)) lease, err := provider.OpenAccount(ctx, provider.Binding{ID: "fake-binding", Home: home, Provider: name, AccountID: "account", Expected: id, RuntimeRoot: filepath.Join(scratch, "homes")}) if err != nil { return provider.Launch{}, nil, err } err = lease.Preflight(ctx, func(context.Context, provider.Binding) (provider.Identity, error) { return id, nil }) if err != nil { return provider.Launch{}, lease.Close, err } binding := lease.Binding() network, err := egress.ProviderPolicy(provider.NetworkContract{Provider: name}, true) if err != nil { return provider.Launch{}, lease.Close, err } policyScratch, err := os.MkdirTemp(scratch, "policy-") if err != nil { return provider.Launch{}, lease.Close, err } policy, err := provider.BuildPolicy(binding, provider.PolicyInputs{Action: c.Brief.Step.Action, Workspace: ws.Path, Scratch: policyScratch, ProviderVersion: id.ProviderVersion, LauncherVersion: "fixture", BwrapVersion: "0.11.0", Argv: []string{"/opt/fake-cli", name}, RuntimeFiles: []provider.Mount{{Source: binary, Target: "/opt/fake-cli", ReadOnly: true}, {Source: helper, Target: "/opt/helper", ReadOnly: true}, {Source: "/usr/bin/bwrap", Target: "/opt/bwrap", ReadOnly: true}}, EgressHosts: network.Hosts}) if err != nil { return provider.Launch{}, lease.Close, err } l := provider.Launch{AttemptKey: attemptKey(c.Scope, c.Handle) + "/model", Workspace: ws.Path, Selection: provider.Selection{Provider: name, AccountID: "account", Family: c.Assignment.Selection.Family, Model: "model", ConnectionID: c.Assignment.Selection.ConnectionID}, Binding: binding, Policy: policy} f.proxies[l.AttemptKey] = proxy return l, lease.Close, nil } return map[string]provider.Launcher{"claude": f, "codex": f}, launch } func (f *graphCLI) Preflight(context.Context, provider.Binding, provider.Policy) (provider.Identity, error) { return provider.Identity{}, nil } func (f *graphCLI) Open(ctx context.Context, l provider.Launch) (provider.Session, error) { p, err := f.host.Start(ctx, l, []string{"/opt/fake-cli", l.Selection.Provider}) if err != nil { return provider.Session{}, err } c, err := NewCaptureFactory(f.j).Open(ctx, p, l) if err != nil { return provider.Session{}, err } session := provider.Session{ID: l.AttemptKey + "-session", AttemptKey: l.AttemptKey, Provider: l.Selection.Provider, AccountID: l.Selection.AccountID, Model: l.Selection.Model, Family: l.Selection.Family} if err = f.j.BindSession(ctx, session); err != nil { return session, err } s := &graphCLISession{session: session, capture: c, events: make(chan provider.Event, 64)} f.mu.Lock() f.sessions[l.AttemptKey] = s f.mu.Unlock() go func() { defer close(s.events) for frame := range c.Frames { s.mu.Lock() turn := s.turn s.mu.Unlock() var payload struct { Tool string Arguments json.RawMessage Final bool } if json.Unmarshal(frame.Bytes, &payload) != nil { return } kind := "timeline" if payload.Tool != "" { if err := f.proxies[l.AttemptKey].submit(ctx, payload.Tool, payload.Tool, payload.Arguments); err != nil { s.events <- provider.Event{SessionID: session.ID, TurnID: turn, Kind: "turn.failed"} return } } if payload.Tool == "ask_person" { proxy := f.proxies[l.AttemptKey] proxy.broker.mu.Lock() bound := proxy.broker.binding proxy.broker.mu.Unlock() if _, err := bound.Ask(ctx, bound, payload.Tool, payload.Arguments); err != nil { s.events <- provider.Event{SessionID: session.ID, TurnID: turn, Kind: "turn.failed"} return } } if payload.Final { kind = "turn.completed" } e := provider.Event{Sequence: frame.Sequence, SessionID: session.ID, TurnID: turn, Kind: kind, Payload: frame.Bytes} select { case s.events <- e: case <-ctx.Done(): return } } }() return session, nil } func (f *graphCLI) Events(_ context.Context, s provider.Session) (<-chan provider.Event, error) { return f.sessions[s.AttemptKey].events, nil } func (f *graphCLI) StartTurn(ctx context.Context, session provider.Session, t provider.Turn) error { s := f.sessions[session.AttemptKey] s.mu.Lock() s.turn = t.ID s.mu.Unlock() if err := f.j.BeginTurn(ctx, session, t); err != nil { return err } var raw []byte if session.Provider == "claude" { raw = marshal(map[string]any{"type": "user", "session_id": session.ID, "message": map[string]string{"role": "user", "content": t.Prompt}}) } else { raw = marshal(map[string]any{"method": "turn/start", "params": map[string]any{"threadId": session.ID, "input": []any{map[string]string{"type": "text", "text": t.Prompt}}}}) } _, err := s.capture.Input.Write(append(raw, '\n')) return err } func (f *graphCLI) Respond(context.Context, provider.Session, provider.Answer) error { return fmt.Errorf("unexpected answer") } func (f *graphCLI) Interrupt(context.Context, provider.Session) error { return nil } func (f *graphCLI) Close(_ context.Context, s provider.Session) error { c := f.sessions[s.AttemptKey].capture c.Input.Close() return <-c.Done } const graphScript = `#!/usr/bin/python3 import sys,json,subprocess,os,base64 def git(*args): env={'PATH':'/usr/bin:/bin','GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null','GIT_AUTHOR_NAME':'fixture','GIT_AUTHOR_EMAIL':'fixture@example.test','GIT_COMMITTER_NAME':'fixture','GIT_COMMITTER_EMAIL':'fixture@example.test'} return subprocess.check_output(['git',*args],env=env,stderr=subprocess.DEVNULL).decode().strip() for line in sys.stdin: v=json.loads(line) message=json.loads(v['message']['content'] if sys.argv[1]=='claude' else v['params']['input'][0]['text']) step=message.get('Action') or message['Step'] if step in ['reproduce','scope']: print(json.dumps({'tool':'ask_person','arguments':{'question':'Which case?'}}),flush=True) tool='submit_acceptance' if step=='scope' else 'submit_reproduction' args={'expected_symptom':'wrong value','files':[{'path':'bug_test.go','bytes':base64.b64encode(b'package fixture\nimport "testing"\nfunc TestBug(t *testing.T){if Value()!=2 {t.Fatal("wrong value")}}\n').decode()}],'test_names':[{'package':'fixture','name':'TestBug'}]} elif step=='recommend': assert not os.path.exists('.git') tool='submit_answer';args={'body':'recommendation','sources':[message['sources'][0]['ref']]} elif step in ['implement','copy','design']: if step=='implement': open('value.go','w').write('package fixture\nfunc Value() int {return 2}\n') else: open(step+'.txt','w').write(step+' captured artifact') git('add','.') git('commit','-m','fix') tool='submit_candidate';args={'commit':git('rev-parse','HEAD')} else: tool='submit_review';args={'candidate':message['candidate_commit'],'decision':'approve','findings':[]} for i in range(PROGRESS_FRAMES): print(json.dumps({'progress':i}),flush=True) print(json.dumps({'tool':tool,'arguments':args}),flush=True) if tool=='submit_candidate' and message.get('render_available'): print(json.dumps({'tool':'submit_render','arguments':args}),flush=True) print(json.dumps({'final':True,'usage':{'input_tokens':2,'output_tokens':3}}),flush=True) `