Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions backend/internal/adapters/scm/github/discover.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package github

import (
"context"
"encoding/json"
"fmt"
"net/http"
neturl "net/url"
)

// FindPRForBranch resolves the open pull request whose head is the given
// branch in owner/repo, returning its github.com URL. found=false (with a nil
// error) means the branch has no open PR yet — the normal pre-PR state of a
// fresh session, not a failure. Network/auth/rate-limit errors are returned as
// errors so the poller can back off rather than treat them as "no PR".
//
// The head filter is owner:branch, which matches same-repo branches (the AO
// worktree model). Cross-fork PRs from a different head owner are out of scope
// for v1.
func (p *Provider) FindPRForBranch(ctx context.Context, owner, repo, branch string) (url string, found bool, err error) {
if owner == "" || repo == "" || branch == "" {
return "", false, fmt.Errorf("github scm: owner, repo, and branch are required")
}
q := neturl.Values{}
q.Set("head", owner+":"+branch)
q.Set("state", "open")
q.Set("per_page", "1")

resp, err := p.client.doREST(ctx, http.MethodGet, repoPath(owner, repo, "pulls"), q, nil)
if err != nil {
return "", false, err
}
var pulls []struct {
HTMLURL string `json:"html_url"`
URL string `json:"url"`
}
if len(resp.Body) > 0 {
if err := json.Unmarshal(resp.Body, &pulls); err != nil {
return "", false, fmt.Errorf("github scm: decode pulls list: %w", err)
}
}
if len(pulls) == 0 {
return "", false, nil
}
if pulls[0].HTMLURL != "" {
return pulls[0].HTMLURL, true, nil
}
return pulls[0].URL, true, nil
}
74 changes: 74 additions & 0 deletions backend/internal/adapters/scm/github/discover_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package github

import (
"net/http"
"testing"
)

func TestFindPRForBranch_Found(t *testing.T) {
f := newFakeGH(t)
f.on(http.MethodGet, "/repos/octocat/hello/pulls", func(w http.ResponseWriter, r *http.Request) {
if got := r.URL.Query().Get("head"); got != "octocat:feature-x" {
t.Errorf("head = %q, want octocat:feature-x", got)
}
if got := r.URL.Query().Get("state"); got != "open" {
t.Errorf("state = %q, want open", got)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[{"html_url":"https://github.com/octocat/hello/pull/42","url":"https://api.github.com/repos/octocat/hello/pulls/42"}]`))
})
p := newProviderForTest(t, f)

url, found, err := p.FindPRForBranch(ctx(), "octocat", "hello", "feature-x")
if err != nil {
t.Fatalf("FindPRForBranch: %v", err)
}
if !found {
t.Fatal("found = false, want true")
}
if url != "https://github.com/octocat/hello/pull/42" {
t.Fatalf("url = %q", url)
}
}

func TestFindPRForBranch_NoOpenPR(t *testing.T) {
f := newFakeGH(t)
f.on(http.MethodGet, "/repos/octocat/hello/pulls", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[]`))
})
p := newProviderForTest(t, f)

url, found, err := p.FindPRForBranch(ctx(), "octocat", "hello", "feature-x")
if err != nil {
t.Fatalf("FindPRForBranch: %v", err)
}
if found {
t.Fatalf("found = true (url %q), want false for empty list", url)
}
}

func TestFindPRForBranch_AuthErrorSurfaces(t *testing.T) {
f := newFakeGH(t)
f.on(http.MethodGet, "/repos/octocat/hello/pulls", func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, `{"message":"Bad credentials"}`, http.StatusUnauthorized)
})
p := newProviderForTest(t, f)

if _, _, err := p.FindPRForBranch(ctx(), "octocat", "hello", "feature-x"); err == nil {
t.Fatal("expected error for 401, got nil")
}
}

func TestFindPRForBranch_RequiresArgs(t *testing.T) {
p := &Provider{}
if _, _, err := p.FindPRForBranch(ctx(), "", "hello", "b"); err == nil {
t.Fatal("expected error for empty owner")
}
if _, _, err := p.FindPRForBranch(ctx(), "o", "", "b"); err == nil {
t.Fatal("expected error for empty repo")
}
if _, _, err := p.FindPRForBranch(ctx(), "o", "hello", ""); err == nil {
t.Fatal("expected error for empty branch")
}
}
18 changes: 13 additions & 5 deletions backend/internal/daemon/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,15 @@ func Run() error {
termMgr := terminal.NewManager(runtimeAdapter, cdcPipe.Broadcaster, log)
defer termMgr.Close()

// The agent messenger resolves a session's live runtime handle from the
// store and sends validated user input into its zellij pane. It backs both
// human /send and the lifecycle PR nudges, so it is built before the LCM.
messenger := newSessionMessenger(store, runtimeAdapter, log)

// Bring up the Lifecycle Manager and the reaper first: it makes the session
// lifecycle write path live (reducer write -> store -> DB trigger ->
// change_log -> poller -> broadcaster) and gives startSession the shared LCM.
lcStack := startLifecycle(ctx, store, runtimeAdapter, log)

// The agent messenger sends validated user input to the session's live
// zellij pane. Keep this path small until durable inbox semantics are needed.
messenger := newSessionMessenger(store, runtimeAdapter, log)
lcStack := startLifecycle(ctx, store, runtimeAdapter, messenger, log)

// Wire the controller-facing session service over the same store + LCM, the
// zellij runtime, a gitworktree workspace, the per-session agent resolver
Expand All @@ -99,12 +100,18 @@ func Run() error {
return fmt.Errorf("wire session service: %w", err)
}

// Start the PR observation path: discover each live session's PR from its
// branch, observe it, persist, and drive lifecycle nudges through the shared
// LCM. Degrades to a no-op when no GitHub token is configured.
prStack := startPRPoller(ctx, store, lcStack.LCM, log)

srv, err := httpd.NewWithDeps(cfg, log, termMgr, httpd.APIDeps{
Projects: projectsvc.New(store),
Sessions: sessionSvc,
})
if err != nil {
stop()
prStack.Stop()
lcStack.Stop()
if cdcErr := cdcPipe.Stop(); cdcErr != nil {
log.Error("cdc pipeline shutdown", "err", cdcErr)
Expand All @@ -119,6 +126,7 @@ func Run() error {
// via defer) avoids the LIFO trap where a Stop() that blocks on ctx-cancel
// runs before the cancel — which would hang any non-signal exit path.
stop()
prStack.Stop()
lcStack.Stop()
if err := cdcPipe.Stop(); err != nil {
log.Error("cdc pipeline shutdown", "err", err)
Expand Down
9 changes: 5 additions & 4 deletions backend/internal/daemon/lifecycle_wiring.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ type lifecycleStack struct {

// startLifecycle constructs the Lifecycle Manager over the store and starts the
// reaper. The goroutine stops when ctx is cancelled; Stop waits for it to drain.
func startLifecycle(ctx context.Context, store *sqlite.Store, runtime ports.Runtime, logger *slog.Logger) *lifecycleStack {
lcm := lifecycle.New(store, nil)
func startLifecycle(ctx context.Context, store *sqlite.Store, runtime ports.Runtime, messenger ports.AgentMessenger, logger *slog.Logger) *lifecycleStack {
lcm := lifecycle.New(store, messenger)
rp := reaper.New(lcm, store, runtime, reaper.Config{Logger: logger})
return &lifecycleStack{LCM: lcm, reaperDone: rp.Start(ctx)}
}
Expand All @@ -44,8 +44,9 @@ func (l *lifecycleStack) Stop() { <-l.reaperDone }

// startSession builds the controller-facing session service: a session manager
// over the real zellij runtime, a per-session gitworktree workspace, the shared
// store + LCM, the per-session agent resolver (AO_AGENT default), and the
// agent messenger. The returned service is mounted at httpd APIDeps.Sessions.
// store + LCM, the per-session agent resolver (AO_AGENT default), and the live
// runtime messenger so human /send reaches the agent's pane. The returned
// service is mounted at httpd APIDeps.Sessions.
func startSession(cfg config.Config, runtime ports.Runtime, store *sqlite.Store, lcm *lifecycle.Manager, messenger ports.AgentMessenger, log *slog.Logger) (*sessionsvc.Service, error) {
agents, err := buildAgentResolver(cfg.Agent, log)
if err != nil {
Expand Down
92 changes: 92 additions & 0 deletions backend/internal/daemon/pr_wiring.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package daemon

import (
"context"
"log/slog"

"github.com/aoagents/agent-orchestrator/backend/internal/adapters/scm/github"
"github.com/aoagents/agent-orchestrator/backend/internal/lifecycle"
"github.com/aoagents/agent-orchestrator/backend/internal/observe/prpoller"
prsvc "github.com/aoagents/agent-orchestrator/backend/internal/service/pr"
"github.com/aoagents/agent-orchestrator/backend/internal/storage/sqlite"
)

// prPollerStack owns the PR poller goroutine. When no GitHub token is
// configured the stack is inert (closed done channel, nothing started): PR
// observation degrades gracefully rather than failing daemon startup.
type prPollerStack struct {
done <-chan struct{}
}

// Stop waits for the poller goroutine to exit. The caller must cancel the ctx
// passed to startPRPoller first. Safe on an inert stack.
func (s *prPollerStack) Stop() {
if s == nil || s.done == nil {
return
}
<-s.done
}

// startPRPoller wires the PR observation path: a GitHub provider (token from
// env, falling back to `gh auth token`), the PR service (persist + lifecycle
// nudges over the shared store/LCM), and the poller that self-discovers each
// live session's PR from its branch. If no token resolves, the poller is
// skipped and the daemon runs without PR observation.
func startPRPoller(ctx context.Context, store *sqlite.Store, lcm *lifecycle.Manager, log *slog.Logger) *prPollerStack {
tokens := githubTokenSource()
if _, err := tokens.Token(ctx); err != nil {
log.Warn("PR poller disabled: no GitHub token (set AO_GITHUB_TOKEN/GITHUB_TOKEN or run `gh auth login`)", "err", err)
return &prPollerStack{}
}

provider, err := github.NewProvider(github.ProviderOptions{Token: tokens})
if err != nil {
log.Warn("PR poller disabled: could not build GitHub provider", "err", err)
return &prPollerStack{}
}

manager := prsvc.New(prsvc.Deps{Writer: store, Lifecycle: lcm})
resolver := gitRepoResolver{store: store}
poller := prpoller.New(store, provider, provider, manager, resolver, prpoller.Config{Logger: log})

log.Info("PR poller started", "interval", prpoller.DefaultTickInterval)
return &prPollerStack{done: poller.Start(ctx)}
}

// githubTokenSource resolves a token from env first (AO_GITHUB_TOKEN, then
// GITHUB_TOKEN via EnvTokenSource's built-in fallback), then `gh auth token`.
func githubTokenSource() github.TokenSource {
return chainTokenSource{
github.EnvTokenSource{EnvVars: []string{"AO_GITHUB_TOKEN"}},
&github.GHTokenSource{},
}
}

// chainTokenSource returns the first source that yields a token, so a CI env
// var wins but a developer's `gh` login still works with no env set up.
type chainTokenSource []github.TokenSource

func (c chainTokenSource) Token(ctx context.Context) (string, error) {
var lastErr error
for _, s := range c {
tok, err := s.Token(ctx)
if err == nil && tok != "" {
return tok, nil
}
lastErr = err
}
if lastErr == nil {
lastErr = github.ErrNoToken
}
return "", lastErr
}

// InvalidateToken forwards to any chained source that supports invalidation, so
// a rotated token is picked up on the next request.
func (c chainTokenSource) InvalidateToken() {
for _, s := range c {
if inv, ok := s.(interface{ InvalidateToken() }); ok {
inv.InvalidateToken()
}
}
}
97 changes: 97 additions & 0 deletions backend/internal/daemon/repo_resolver.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package daemon

import (
"context"
"fmt"
"os/exec"
"strings"

"github.com/aoagents/agent-orchestrator/backend/internal/domain"
)

// gitRepoResolver maps a project to its github owner/repo by reading the
// project's on-disk repo path from the store and parsing its origin remote. It
// backs the PR poller's per-project owner/repo lookup.
type gitRepoResolver struct {
store projectPathStore
// git is the shell-out hook; nil falls back to the real git binary. Tests
// inject a fake to avoid requiring a repo on disk.
git func(ctx context.Context, repoPath string) (string, error)
}

type projectPathStore interface {
GetProject(ctx context.Context, id string) (domain.ProjectRecord, bool, error)
}

// RepoIdent resolves owner/repo for projectID. It fails (rather than guessing)
// when the project is unregistered, has no repo path, or its origin remote
// isn't a parseable github URL — the poller treats a failure as "skip", so a
// non-github project simply never gets PR observations.
func (r gitRepoResolver) RepoIdent(ctx context.Context, projectID domain.ProjectID) (string, string, error) {
rec, ok, err := r.store.GetProject(ctx, string(projectID))
if err != nil {
return "", "", fmt.Errorf("look up project %q: %w", projectID, err)
}
if !ok || rec.Path == "" {
return "", "", fmt.Errorf("project %q has no repo path on record", projectID)
}
run := r.git
if run == nil {
run = gitOriginURL
}
remote, err := run(ctx, rec.Path)
if err != nil {
return "", "", fmt.Errorf("read origin remote for %q: %w", projectID, err)
}
return parseOwnerRepo(remote)
}

func gitOriginURL(ctx context.Context, repoPath string) (string, error) {
out, err := exec.CommandContext(ctx, "git", "-C", repoPath, "remote", "get-url", "origin").Output()
if err != nil {
return "", err
}
return string(out), nil
}
Comment on lines +49 to +55
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 exec.CommandContext(...).Output() only captures stdout; when git exits non-zero the error is just exit status 128 with no diagnostic text. Capturing ExitError.Stderr would surface the actual git message, making resolver failures much easier to diagnose in production.

Suggested change
func gitOriginURL(ctx context.Context, repoPath string) (string, error) {
out, err := exec.CommandContext(ctx, "git", "-C", repoPath, "remote", "get-url", "origin").Output()
if err != nil {
return "", err
}
return string(out), nil
}
func gitOriginURL(ctx context.Context, repoPath string) (string, error) {
cmd := exec.CommandContext(ctx, "git", "-C", repoPath, "remote", "get-url", "origin")
out, err := cmd.Output()
if err != nil {
if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 {
return "", fmt.Errorf("%w: %s", err, strings.TrimSpace(string(ee.Stderr)))
}
return "", err
}
return string(out), nil
}


// parseOwnerRepo extracts owner/repo from the common github remote URL shapes:
//
// https://github.com/owner/repo(.git)
// git@github.com:owner/repo(.git)
// ssh://git@github.com/owner/repo(.git)
//
// Only github hosts are accepted; anything else returns an error so the poller
// skips the project rather than POSTing to a non-github API.
func parseOwnerRepo(remote string) (string, string, error) {
s := strings.TrimSpace(remote)
if s == "" {
return "", "", fmt.Errorf("empty origin remote")
}
// Normalise scp-style (git@host:owner/repo) to a slash-delimited tail.
if !strings.Contains(s, "://") {
if at := strings.Index(s, "@"); at >= 0 {
s = s[at+1:]
}
s = strings.Replace(s, ":", "/", 1)
} else {
s = s[strings.Index(s, "://")+len("://"):]
if at := strings.Index(s, "@"); at >= 0 {
s = s[at+1:]
}
}
// s is now host/owner/repo(.git)[/...]. Require a github host.
parts := strings.Split(strings.Trim(s, "/"), "/")
if len(parts) < 3 {
return "", "", fmt.Errorf("origin remote %q is not an owner/repo url", remote)
}
host := strings.ToLower(parts[0])
if host != "github.com" && host != "www.github.com" && !strings.HasSuffix(host, ".github.com") && !strings.HasSuffix(host, ".ghe.io") {
return "", "", fmt.Errorf("origin remote host %q is not github", host)
}
owner := parts[1]
repo := strings.TrimSuffix(parts[2], ".git")
if owner == "" || repo == "" {
return "", "", fmt.Errorf("origin remote %q is missing owner or repo", remote)
}
return owner, repo, nil
}
Loading
Loading