-
Notifications
You must be signed in to change notification settings - Fork 1
feat(backend): wire PR engine into the daemon #87
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Pritom14
wants to merge
2
commits into
main
Choose a base branch
from
feat/pr-engine-wiring
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
|
|
||
| // 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 | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
exec.CommandContext(...).Output()only captures stdout; whengitexits non-zero the error is justexit status 128with no diagnostic text. CapturingExitError.Stderrwould surface the actual git message, making resolver failures much easier to diagnose in production.