From 7db3da696a2808d0a4fabd50e5cc2b1519dee6e7 Mon Sep 17 00:00:00 2001 From: Alexei Ledenev Date: Tue, 24 Nov 2026 14:35:46 +0200 Subject: [PATCH 1/9] fix(status): return an error from Run so archfit status runs kong requires a Run method to return error and checks it only when it calls it, so archfit status always exited 2. A test now checks every command's Run signature and --help. --- cmd/archfit/status.go | 3 +- cmd/archfit/status_test.go | 62 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 cmd/archfit/status_test.go diff --git a/cmd/archfit/status.go b/cmd/archfit/status.go index d5a3f408..35f0e0ef 100644 --- a/cmd/archfit/status.go +++ b/cmd/archfit/status.go @@ -11,7 +11,7 @@ type StatusCmd struct { Dir string `short:"C" name:"directory" help:"Run in DIR instead of the current directory." placeholder:"DIR"` } -func (c *StatusCmd) Run(deps *appDeps) { +func (c *StatusCmd) Run(deps *appDeps) error { ctx := deps.runContext() in := request.StatusInput{} co, err := openCheckout(ctx, deps, dirOr(c.Dir)) @@ -27,4 +27,5 @@ func (c *StatusCmd) Run(deps *appDeps) { for _, line := range request.Status(in) { _, _ = fmt.Fprintln(deps.Stdout, line) } + return nil } diff --git a/cmd/archfit/status_test.go b/cmd/archfit/status_test.go new file mode 100644 index 00000000..a73a19ad --- /dev/null +++ b/cmd/archfit/status_test.go @@ -0,0 +1,62 @@ +package main + +import ( + "reflect" + "strings" + "testing" + + "github.com/alecthomas/kong" +) + +// TestStatusRunsThroughTheCLI: status runs through the real entry point (N2). +func TestStatusRunsThroughTheCLI(t *testing.T) { + t.Parallel() + code, stdout, stderr := runArchfit(t, "status", "-C", t.TempDir()) + if code != 0 || stderr != "" || stdout != "✓ change ○ check\nnext: run archfit check\n" { + t.Fatalf("exit %d, stdout %q, stderr %q", code, stdout, stderr) + } +} + +// TestEveryCommandRunReturnsError: kong checks a Run method only when it calls +// it, so a Run that returns no error crashes the command at run time. Running +// every command for real would push, post or install; the signature check +// stands in for that, and --help proves each command parses. +func TestEveryCommandRunReturnsError(t *testing.T) { + t.Parallel() + parser, err := kong.New(&cli{}, kong.Name("archfit")) + if err != nil { + t.Fatal(err) + } + errorType := reflect.TypeFor[error]() + var leaves int + var walk func(n *kong.Node, path []string) + walk = func(n *kong.Node, path []string) { + for _, child := range n.Children { + if child.Type != kong.CommandNode { + continue + } + args := append(append([]string{}, path...), child.Name) + if !child.Leaf() { + walk(child, args) + continue + } + leaves++ + target := child.Target + if target.Kind() != reflect.Pointer { + target = target.Addr() + } + run := target.MethodByName("Run") + if !run.IsValid() || run.Type().NumOut() != 1 || run.Type().Out(0) != errorType { + t.Errorf("%s: Run must return exactly error, got %v", strings.Join(args, " "), run) + } + code, stdout, stderr := runArchfit(t, append(args, flagHelp)...) + if code != 0 || stderr != "" || stdout == "" { + t.Errorf("%s --help: exit %d, stderr %q", strings.Join(args, " "), code, stderr) + } + } + } + walk(parser.Model.Node, nil) + if leaves < 10 { + t.Fatalf("walked %d commands; the walk missed the command tree", leaves) + } +} From be699a591fa6e9b1eb99b2b380eca5b40f64a010 Mon Sep 17 00:00:00 2001 From: Alexei Ledenev Date: Tue, 24 Nov 2026 14:39:00 +0200 Subject: [PATCH 2/9] fix(setup): trust the archfit/gate check of the build's App Setup and status matched the check run by the hard-coded slug archfit-review, so a build for another App, such as staging, never saw its check. The slug now comes from setup.InstallURL, which a candidate build sets, and defaults to archfit-review. --- cmd/archfit/setup_wiring.go | 2 +- cmd/archfit/status.go | 3 +- internal/application/setup/setup.go | 19 ++++++++++ internal/application/setup/setup_test.go | 18 ++++++++++ internal/history/github/status.go | 7 ++-- internal/history/github/status_test.go | 40 +++++++++++++++------- internal/history/setupgit/github.go | 6 ++-- internal/history/setupgit/setupgit_test.go | 23 +++++++++---- 8 files changed, 92 insertions(+), 26 deletions(-) diff --git a/cmd/archfit/setup_wiring.go b/cmd/archfit/setup_wiring.go index 033fd897..c2c8090a 100644 --- a/cmd/archfit/setup_wiring.go +++ b/cmd/archfit/setup_wiring.go @@ -38,7 +38,7 @@ func setupDependencies(deps *appDeps, dir string, noHooks bool) (setup.Dependenc PolicyPath: defaultConfigPath, WorkflowsDir: workflowsDir, Policy: files.ValidPolicy, UsesAction: setupUsesAction, } - gh := setupGH{setupgit.GitHub{Root: co.root, Runner: local.Runner, BodyPath: setup.BodyPath}} + gh := setupGH{setupgit.GitHub{Root: co.root, Runner: local.Runner, BodyPath: setup.BodyPath, AppSlug: setup.AppSlug()}} return setup.Dependencies{ Files: files, Git: git, GitHub: gh, Version: version, ActionRef: actionRef, ActionRefNote: actionRefNote, diff --git a/cmd/archfit/status.go b/cmd/archfit/status.go index 35f0e0ef..237102e5 100644 --- a/cmd/archfit/status.go +++ b/cmd/archfit/status.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/coupling-dev/archfit/internal/application/request" + "github.com/coupling-dev/archfit/internal/application/setup" requestsend "github.com/coupling-dev/archfit/internal/history/github" ) @@ -22,7 +23,7 @@ func (c *StatusCmd) Run(deps *appDeps) error { in.Fresh = true in.Verdict = last.Check.Status } - in.StoryText, _ = requestsend.StoryText(ctx, co.root, co.runner) + in.StoryText, _ = requestsend.StoryText(ctx, co.root, co.runner, setup.AppSlug()) } for _, line := range request.Status(in) { _, _ = fmt.Fprintln(deps.Stdout, line) diff --git a/internal/application/setup/setup.go b/internal/application/setup/setup.go index ba87885b..ace2d5eb 100644 --- a/internal/application/setup/setup.go +++ b/internal/application/setup/setup.go @@ -30,6 +30,25 @@ var ( InstallURL = "https://github.com/apps/archfit-review/installations/new" ) +const ( + defaultAppSlug = "archfit-review" + appsPrefix = "https://github.com/apps/" +) + +// AppSlug is the App whose archfit/gate check this build trusts: the slug in +// InstallURL, so a candidate build that installs another App also reads its +// check. +func AppSlug() string { return appSlug(InstallURL) } + +func appSlug(installURL string) string { + rest, ok := strings.CutPrefix(installURL, appsPrefix) + slug, _, found := strings.Cut(rest, "/") + if !ok || !found || slug == "" { + return defaultAppSlug + } + return slug +} + // Files reads and writes onboarding files in the current checkout. type Files interface { SafePaths() (string, error) diff --git a/internal/application/setup/setup_test.go b/internal/application/setup/setup_test.go index 256ea30c..f81753c3 100644 --- a/internal/application/setup/setup_test.go +++ b/internal/application/setup/setup_test.go @@ -107,3 +107,21 @@ func TestShellQuote(t *testing.T) { t.Fatalf("unsafe quoting: %q", got) } } + +func TestAppSlugComesFromTheInstallURL(t *testing.T) { + for _, tc := range []struct{ url, want string }{ + {"https://github.com/apps/archfit-review/installations/new", "archfit-review"}, + {"https://github.com/apps/archfit-review-staging/installations/new", "archfit-review-staging"}, + {"https://github.com/apps/archfit-review-staging", defaultAppSlug}, + {"https://github.com/apps//installations/new", defaultAppSlug}, + {"https://example.com/apps/x/installations/new", defaultAppSlug}, + {"", defaultAppSlug}, + } { + if got := appSlug(tc.url); got != tc.want { + t.Errorf("appSlug(%q) = %q, want %q", tc.url, got, tc.want) + } + } + if AppSlug() != "archfit-review" { + t.Errorf("default build trusts %q", AppSlug()) + } +} diff --git a/internal/history/github/status.go b/internal/history/github/status.go index 6039fa4f..30b409fa 100644 --- a/internal/history/github/status.go +++ b/internal/history/github/status.go @@ -8,8 +8,9 @@ import ( "github.com/coupling-dev/archfit/internal/toolrun" ) -// StoryText reads the latest gate check for the branch's pull request. -func StoryText(ctx context.Context, dir string, runner toolrun.Runner) (string, string) { +// StoryText reads the latest gate check of the App appSlug for the branch's +// pull request. An empty appSlug trusts no App. +func StoryText(ctx context.Context, dir string, runner toolrun.Runner, appSlug string) (string, string) { const notReady = "gh not ready" run := func(args ...string) ([]byte, bool) { out, err := runner.Run(ctx, toolrun.ToolCmd{Name: "gh", Args: args, WorkDir: dir, Timeout: 10 * time.Second}) @@ -50,7 +51,7 @@ func StoryText(ctx context.Context, dir string, runner toolrun.Runner) (string, var latest time.Time var text string for _, check := range checks.Runs { - if check.App.Slug == "archfit-review" && (latest.IsZero() || check.StartedAt.After(latest)) { + if appSlug != "" && check.App.Slug == appSlug && (latest.IsZero() || check.StartedAt.After(latest)) { latest = check.StartedAt text = check.Output.Text } diff --git a/internal/history/github/status_test.go b/internal/history/github/status_test.go index e9855c6d..eea1fd47 100644 --- a/internal/history/github/status_test.go +++ b/internal/history/github/status_test.go @@ -21,23 +21,37 @@ func TestStoryText(t *testing.T) { } return toolrun.Output{Stdout: []byte(`{"check_runs":[{"app":{"slug":"archfit-review"},"started_at":"2026-01-01T00:00:00Z","output":{"text":"old"}},{"app":{"slug":"archfit-review"},"started_at":"2026-01-02T00:00:00Z","output":{"text":"new"}}]}`)}, nil }} - got, state := requestsend.StoryText(context.Background(), ".", runner) + got, state := requestsend.StoryText(context.Background(), ".", runner, "archfit-review") if got != "new" || state != "" || calls != 2 { t.Errorf("got %q, %q, %d calls", got, state, calls) } } -func TestStoryTextIgnoresOtherApps(t *testing.T) { - calls := 0 - runner := &toolrun.RunnerMock{RunFunc: func(_ context.Context, _ toolrun.ToolCmd) (toolrun.Output, error) { - calls++ - if calls == 1 { - return toolrun.Output{Stdout: []byte(`{"number":1,"headRefOid":"abc"}`)}, nil - } - return toolrun.Output{Stdout: []byte(`{"check_runs":[{"app":{"slug":"other"},"started_at":"2026-01-01T00:00:00Z","output":{"text":"malicious"}}]}`)}, nil - }} - text, state := requestsend.StoryText(context.Background(), ".", runner) - if text != "" || state != "" { - t.Errorf("got %q, %q", text, state) +// TestStoryTextReadsOnlyTheBuildsApp: status reads the check of the App this +// build trusts, staging included, and no other App's text (N1). +func TestStoryTextReadsOnlyTheBuildsApp(t *testing.T) { + const runs = `{"check_runs":[{"app":{"slug":"other"},"started_at":"2026-01-03T00:00:00Z","output":{"text":"malicious"}},` + + `{"app":{"slug":"archfit-review"},"started_at":"2026-01-02T00:00:00Z","output":{"text":"production"}},` + + `{"app":{"slug":"archfit-review-staging"},"started_at":"2026-01-01T00:00:00Z","output":{"text":"staging"}},` + + `{"app":{"slug":""},"started_at":"2026-01-04T00:00:00Z","output":{"text":"no app"}}]}` + for _, tc := range []struct{ slug, want string }{ + {"archfit-review", "production"}, + {"archfit-review-staging", "staging"}, + {"", ""}, + } { + t.Run(tc.slug, func(t *testing.T) { + calls := 0 + runner := &toolrun.RunnerMock{RunFunc: func(_ context.Context, _ toolrun.ToolCmd) (toolrun.Output, error) { + calls++ + if calls == 1 { + return toolrun.Output{Stdout: []byte(`{"number":1,"headRefOid":"abc"}`)}, nil + } + return toolrun.Output{Stdout: []byte(runs)}, nil + }} + text, state := requestsend.StoryText(context.Background(), ".", runner, tc.slug) + if text != tc.want || state != "" { + t.Errorf("got %q, %q; want %q", text, state, tc.want) + } + }) } } diff --git a/internal/history/setupgit/github.go b/internal/history/setupgit/github.go index fcc5ff4b..abad268f 100644 --- a/internal/history/setupgit/github.go +++ b/internal/history/setupgit/github.go @@ -13,11 +13,13 @@ import ( "github.com/coupling-dev/archfit/internal/toolrun" ) -// GitHub runs gh without prompts and leaves the credentials with gh. +// GitHub runs gh without prompts and leaves the credentials with gh. AppSlug +// is the App whose archfit/gate check setup trusts; empty trusts none. type GitHub struct { Root string Runner toolrun.Runner BodyPath string + AppSlug string } // PullRequest describes the setup pull request and its Git head. @@ -201,7 +203,7 @@ func (g GitHub) Check(ctx context.Context, repo, head string) (AppCheck, error) return AppCheck{}, err } for _, c := range data.Runs { - if c.App.Slug == "archfit-review" { + if g.AppSlug != "" && c.App.Slug == g.AppSlug { return AppCheck{Status: c.Status, Conclusion: c.Conclusion, HTMLURL: c.HTMLURL, Title: c.Output.Title}, nil } } diff --git a/internal/history/setupgit/setupgit_test.go b/internal/history/setupgit/setupgit_test.go index 8e67ffa0..7e6ee14a 100644 --- a/internal/history/setupgit/setupgit_test.go +++ b/internal/history/setupgit/setupgit_test.go @@ -137,19 +137,30 @@ func TestPullRequestLookupErrorOmitsTheURL(t *testing.T) { } } +// TestAppCheckIgnoresOtherApps: setup trusts only the App of its build, so a +// staging build reads the staging App's check and never the production one (N1). func TestAppCheckIgnoresOtherApps(t *testing.T) { + const production, staging = "archfit-review", "archfit-review-staging" + run := func(slug string) string { + return `{"app":{"slug":"` + slug + `"},"status":"completed","conclusion":"neutral","html_url":"https://github.com/o/r/runs/7","output":{"title":"merge to start"}}` + } + found := AppCheck{Status: "completed", Conclusion: "neutral", HTMLURL: "https://github.com/o/r/runs/7", Title: "merge to start"} for _, tc := range []struct { - name, second string - want AppCheck + name, slug, runs string + want AppCheck }{ - {"none", "", AppCheck{}}, - {"matched", `, {"app":{"slug":"archfit-review"},"status":"completed","conclusion":"neutral","html_url":"https://github.com/o/r/runs/7","output":{"title":"merge to start"}}`, - AppCheck{Status: "completed", Conclusion: "neutral", HTMLURL: "https://github.com/o/r/runs/7", Title: "merge to start"}}, + {"none", production, "", AppCheck{}}, + {"production", production, ", " + run(production), found}, + {"staging", staging, ", " + run(staging), found}, + {"staging ignores production", staging, ", " + run(production), AppCheck{}}, + {"production ignores staging", production, ", " + run(staging), AppCheck{}}, + {"no slug trusts nothing", "", ", " + run(""), AppCheck{}}, } { t.Run(tc.name, func(t *testing.T) { gh := mockGH(t, "api --hostname github.com repos/o/r/commits/abc/check-runs?check_name=archfit%2Fgate", `{ - "check_runs":[{"app":{"slug":"someone-else"},"status":"completed","conclusion":"success"}`+tc.second+`] + "check_runs":[{"app":{"slug":"someone-else"},"status":"completed","conclusion":"success"}`+tc.runs+`] }`, "", 0) + gh.AppSlug = tc.slug got, err := gh.Check(t.Context(), repo, "abc") if err != nil || got != tc.want { t.Errorf("App check %+v, %v; want %+v", got, err, tc.want) From 9e2c28055b78577d5d075d1562a6a42172f86c87 Mon Sep 17 00:00:00 2001 From: Alexei Ledenev Date: Tue, 24 Nov 2026 14:44:01 +0200 Subject: [PATCH 3/9] fix(request): find the pull request of a branch with no remote-tracking ref A clone made with --single-branch keeps no remote-tracking ref for a branch pushed with -u, so @{upstream} does not resolve and archfit request told the author to push again. It now looks up the pull request by the branch's name on the push remote and posts only when that pull request's head is HEAD. The no-upstream answer stays for a branch that is not on GitHub. --- cmd/archfit/request_send_test.go | 58 ++++++++ docs/commands.md | 2 +- internal/history/github/git_test.go | 22 ++- internal/history/github/regression_test.go | 6 +- internal/history/github/sender.go | 159 +++++++++++++++++---- internal/history/github/sender_test.go | 127 ++++++++++++++-- 6 files changed, 325 insertions(+), 49 deletions(-) diff --git a/cmd/archfit/request_send_test.go b/cmd/archfit/request_send_test.go index 656cb466..0f7c9cf8 100644 --- a/cmd/archfit/request_send_test.go +++ b/cmd/archfit/request_send_test.go @@ -69,6 +69,10 @@ func TestRequestSendsFromCLI(t *testing.T) { if r.Header.Get("Authorization") != "Bearer "+token { t.Error("missing credential") } + if r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/branches/") { + w.WriteHeader(http.StatusNotFound) + return + } if r.Method == http.MethodGet { _, _ = fmt.Fprint(w, tc.pulls) return @@ -149,3 +153,57 @@ func TestRequestSendsFromCLI(t *testing.T) { type requestTransport func(*http.Request) (*http.Response, error) func (f requestTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +// TestRequestFindsThePullRequestWithoutATrackingRef: a single-branch clone +// pushed with -u records the upstream but keeps no remote-tracking ref. The +// request still reaches the branch's pull request when its head is HEAD (N3). +func TestRequestFindsThePullRequestWithoutATrackingRef(t *testing.T) { + const token = "cli-secret-token" + const receipt = "https://github.com/acme/shop/pull/431#issuecomment-7" + t.Setenv("GH_TOKEN", token) + t.Setenv("GITHUB_TOKEN", "") + dir := fixtureRepo(t, fixtureFiles(), map[string]string{tcNetem: tcImportsUtil}) + gitFixture(t, dir, "remote", "add", "origin", "https://github.com/acme/shop.git") + branch := strings.TrimSpace(gitOutput(t, dir, "symbolic-ref", "--short", "HEAD")) + gitFixture(t, dir, "config", "branch."+branch+".remote", "origin") + gitFixture(t, dir, "config", "branch."+branch+".merge", "refs/heads/"+branch) + head := strings.TrimSpace(gitOutput(t, dir, "rev-parse", "HEAD")) + runCLI(t, fixtureDate, cmdCheck, "-C", dir) + var posted []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + if r.URL.Path != "/repos/acme/shop/pulls" || r.URL.Query().Get("head") != "acme:"+branch { + t.Errorf("lookup %s", r.URL) + } + _, _ = fmt.Fprintf(w, `[{"number":431,"head":{"sha":%q}}]`, head) + return + } + posted = append(posted, r.URL.Path) + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(map[string]any{"number": 431, "id": 7, "html_url": receipt}) + })) + defer server.Close() + target, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + transport := http.DefaultTransport.(*http.Transport).Clone() + defer transport.CloseIdleConnections() + client := &http.Client{Transport: requestTransport(func(r *http.Request) (*http.Response, error) { + r = r.Clone(r.Context()) + r.URL.Scheme, r.URL.Host = target.Scheme, target.Host + return transport.RoundTrip(r) + })} + processRunner := toolrun.New() + runner := &toolrun.RunnerMock{RunFunc: func(ctx context.Context, cmd toolrun.ToolCmd) (toolrun.Output, error) { + if cmd.Name == "gh" { + return toolrun.Output{ExitCode: 1}, nil + } + return processRunner.Run(ctx, cmd) + }} + var stdout, stderr bytes.Buffer + code := runDeps([]string{cmdRequest, "-C", dir, "-m", whyGraph}, &appDeps{Runner: runner, Stdout: &stdout, Stderr: &stderr, requestClient: client, now: day(fixtureDate)}) + if code != 0 || stdout.String() != receipt+"\n" || stderr.Len() != 0 || len(posted) != 1 || posted[0] != "/repos/acme/shop/issues/431/comments" { + t.Fatalf("exit %d, posted %v, stdout %q, stderr %q", code, posted, stdout.String(), stderr.String()) + } +} diff --git a/docs/commands.md b/docs/commands.md index 9cf91c48..271edcf7 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -135,7 +135,7 @@ Only an error whose `next` is `archfit request` joins the request: an error of a A use past the surface asks one question: should its package be part of the surface? The printed request shows it on a `question:` line; the App asks the owner to declare the package `public` or `model`, or to reject the request. -With a GitHub remote, `archfit request` posts `/archfit request [--expires DATE]` as a comment on the one open pull request for the current branch. The target repository is `origin`, or a configured GitHub `upstream` for a fork. The head uses the push remote's owner, falling back to the `origin` owner. Several matching pull requests means nothing is sent: the error names their numbers. A detached HEAD or a branch without an upstream names no pull request: the error says which, and for a branch without an upstream `next: git push -u HEAD`. +With a GitHub remote, `archfit request` posts `/archfit request [--expires DATE]` as a comment on the one open pull request for the current branch. The target repository is `origin`, or a configured GitHub `upstream` for a fork. The head uses the push remote's owner, falling back to the `origin` owner. Several matching pull requests means nothing is sent: the error names their numbers. A detached HEAD names no pull request: the error says so. When Git keeps no remote-tracking ref for the branch, as in a clone made with `--single-branch`, the request looks for the pull request by the branch's name on the push remote. It posts only when that pull request's head is the current commit; otherwise it names both commits and sends nothing, with `next: git push`. When the branch is not on GitHub at all, the error says the branch has no upstream branch, with `next: git push -u HEAD`. Without a pull request, only a request from `archfit can` opens an issue. Its body holds the request line and the `can` record; the App marks the numbers "as reported" until a pull request confirms them. With `check` output, nothing is opened: `no open pull request for :` and `next: open a pull request first`. diff --git a/internal/history/github/git_test.go b/internal/history/github/git_test.go index 90a49625..dab3a390 100644 --- a/internal/history/github/git_test.go +++ b/internal/history/github/git_test.go @@ -29,13 +29,23 @@ func TestRoutingWithRealGit(t *testing.T) { git("config", "branch.feature.pushRemote", "fork") git("config", "push.default", "current") s := New(dir, runner) - repo, head, noHead, err := s.repository(t.Context()) - if err != nil || repo != testRepo || head != forkHead || noHead != nil { - t.Fatalf("repo=%q head=%q noHead=%v err=%v", repo, head, noHead, err) + at, err := s.repository(t.Context()) + if err != nil || at.repo != testRepo || at.head != forkHead || at.noHead != nil || at.untracked != nil { + t.Fatalf("target=%+v err=%v", at, err) + } + // A single-branch clone pushed with -u: Git records the upstream but keeps + // no remote-tracking ref, so @{upstream} does not resolve (N3). + git("checkout", "-q", "-b", "solo") + git("config", "branch.solo.remote", "origin") + git("config", "branch.solo.merge", "refs/heads/solo-remote") + at, err = s.repository(t.Context()) + if err != nil || at.repo != testRepo || at.head != "acme:solo-remote" || at.untracked == nil || + at.untracked.pushRepo != testRepo || at.untracked.branch != "solo-remote" { + t.Fatalf("untracked: target=%+v err=%v", at, err) } git("checkout", "--detach", "-q") - repo, head, noHead, err = s.repository(t.Context()) - if err != nil || repo != testRepo || head != "" || !errors.Is(noHead, errDetached) { - t.Fatalf("detached: repo=%q head=%q noHead=%v err=%v", repo, head, noHead, err) + at, err = s.repository(t.Context()) + if err != nil || at.repo != testRepo || at.head != "" || !errors.Is(at.noHead, errDetached) { + t.Fatalf("detached: target=%+v err=%v", at, err) } } diff --git a/internal/history/github/regression_test.go b/internal/history/github/regression_test.go index 588a8a3d..062769d1 100644 --- a/internal/history/github/regression_test.go +++ b/internal/history/github/regression_test.go @@ -26,9 +26,9 @@ func TestEffectivePushURLAndTrackingBranch(t *testing.T) { }, "acme:feature/part"}, } { t.Run(tc.name, func(t *testing.T) { - _, head, _, err := New(".", gitRunner(t, tc.override)).repository(t.Context()) - if err != nil || head != tc.want { - t.Fatalf("head=%q err=%v, want %q", head, err, tc.want) + at, err := New(".", gitRunner(t, tc.override)).repository(t.Context()) + if err != nil || at.head != tc.want { + t.Fatalf("head=%q err=%v, want %q", at.head, err, tc.want) } }) } diff --git a/internal/history/github/sender.go b/internal/history/github/sender.go index 0b8d31f9..a176a3dc 100644 --- a/internal/history/github/sender.go +++ b/internal/history/github/sender.go @@ -38,24 +38,23 @@ func New(dir string, runner toolrun.Runner) *Sender { // Send finds exactly one open pull request and posts one comment. Without a // pull request, only a can answer may open an issue. POST is never retried. func (s *Sender) Send(ctx context.Context, r Input) (Outcome, error) { - repo, head, noHead, err := s.repository(ctx) + at, err := s.repository(ctx) if err != nil { return Outcome{}, err } - if repo == "" { + if at.repo == "" { return Outcome{}, nil } + head := at.head if head == "" && r.Can == nil { - return Outcome{}, noHead + return Outcome{}, at.noHead } token, err := s.credentials(ctx) if err != nil { return Outcome{}, err } - path := "/repos/" + repo - var pulls []struct { - Number int `json:"number"` - } + path := "/repos/" + at.repo + var pulls []pull if head != "" { q := url.Values{"state": {"open"}, "head": {head}, "per_page": {"100"}} more, err := s.call(ctx, token, http.MethodGet, path+"/pulls?"+q.Encode(), nil, &pulls) @@ -72,6 +71,11 @@ func (s *Sender) Send(ctx context.Context, r Input) (Outcome, error) { } return Outcome{}, notSent(fmt.Sprintf("several open pull requests match: %s; nothing sent", strings.Join(numbers, ", "))) } + if at.untracked != nil { + if err := s.untracked(ctx, token, *at.untracked, pulls, r.Can != nil); err != nil { + return Outcome{}, err + } + } } var payload any if len(pulls) == 1 { @@ -106,7 +110,7 @@ func (s *Sender) Send(ctx context.Context, r Input) (Outcome, error) { number = pulls[0].Number } u, err := url.Parse(sent.URL) - repoPath := "/" + repo + "/" + repoPath := "/" + at.repo + "/" if err != nil || u.Scheme != "https" || u.Host != "github.com" || u.User != nil || u.RawQuery != "" || len(u.Path) < len(repoPath) || !strings.EqualFold(u.Path[:len(repoPath)], repoPath) || strings.Contains(sent.URL, token) || strings.Contains(u.Path+"#"+u.Fragment, token) || number < 1 { @@ -115,6 +119,60 @@ func (s *Sender) Send(ctx context.Context, r Input) (Outcome, error) { return Outcome{Number: number, URL: sent.URL}, nil } +// pull is an open pull request from the lookup. +type pull struct { + Number int `json:"number"` + Head struct { + SHA string `json:"sha"` + } `json:"head"` +} + +// guess is a pull request head read from the branch name, because Git keeps +// no remote-tracking ref for the branch: a single-branch clone pushed with -u. +type guess struct { + pushRepo, branch string + // notPushed is the answer when the branch is not on the push remote. + notPushed error +} + +// untracked guards a guessed head. It posts only on a pull request whose head +// is this checkout's HEAD, so a same-named branch of another pull request never +// gets the comment. Without a pull request it says there is no upstream when +// the branch is not on GitHub; a can answer still opens an issue. +func (s *Sender) untracked(ctx context.Context, token string, g guess, pulls []pull, can bool) error { + if len(pulls) == 1 { + local, code, err := s.git(ctx, "rev-parse", "HEAD") + if err != nil { + return err + } + if code != 0 || local == "" { + return notSent("cannot read HEAD; nothing sent") + } + if pulls[0].Head.SHA != local { + return notSent(fmt.Sprintf("pull request #%d is at %.7s, this checkout is at %.7s; nothing sent\nnext: git push", + pulls[0].Number, pulls[0].Head.SHA, local)) + } + return nil + } + if can { + return nil + } + segments := strings.Split(g.branch, "/") + for i, segment := range segments { + segments[i] = url.PathEscape(segment) + } + var branch struct { + Name string `json:"name"` + } + if _, err := s.call(ctx, token, http.MethodGet, "/repos/"+g.pushRepo+"/branches/"+strings.Join(segments, "/"), nil, &branch); err != nil { + if errors.Is(err, errNotFound) { + return g.notPushed + } + return err + } + return nil +} + // NothingSent marks an error after which nothing reached GitHub, so the // request may be posted another way without a duplicate. type nothingSent string @@ -128,6 +186,7 @@ func notSent(message string) error { return nothingSent(message) } // Why the current checkout names no pull request head. var ( + errNotFound = notSent("GitHub returned HTTP 404; nothing sent") errDetached = notSent("HEAD is not on a branch, so archfit cannot find its pull request; nothing sent\nnext: switch to the branch of the pull request") remoteName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) ) @@ -221,6 +280,9 @@ func (s *Sender) call(ctx context.Context, token, method, path string, payload, if method == http.MethodPost && (response.StatusCode < 400 || response.StatusCode >= 500) { return false, fmt.Errorf("GitHub returned HTTP %d; outcome unknown: check GitHub before trying again (not retried)", response.StatusCode) } + if response.StatusCode == http.StatusNotFound { + return false, errNotFound + } return false, notSent(fmt.Sprintf("GitHub returned HTTP %d; nothing sent", response.StatusCode)) } dec := json.NewDecoder(io.LimitReader(response.Body, 1<<20)) @@ -249,67 +311,102 @@ func (s *Sender) git(ctx context.Context, args ...string) (string, int, error) { return strings.TrimSpace(string(out.Stdout)), out.ExitCode, nil } -// repository returns the target repository and the pull request head. When -// the checkout names no head, noHead says why; a can answer still opens an -// issue then. -func (s *Sender) repository(ctx context.Context) (repo, head string, noHead, err error) { +// target is where Send looks for the pull request. +type target struct { + // repo is the repository of the pull request; empty for a checkout + // without a GitHub origin. + repo string + // head is owner:branch. Empty when noHead says why; a can answer still + // opens an issue then. + head string + noHead error + // untracked is set when head is guessed from the branch name. + untracked *guess +} + +// repository returns the target repository and the pull request head. +func (s *Sender) repository(ctx context.Context) (target, error) { origin, code, err := s.git(ctx, "config", "--get", "remote.origin.url") if err != nil { - return "", "", nil, err + return target{}, err } if code != 0 && code != 1 { - return "", "", nil, notSent("cannot read origin; nothing sent") + return target{}, notSent("cannot read origin; nothing sent") } - repo = githubRepository(origin) + repo := githubRepository(origin) if repo == "" { - return "", "", nil, nil + return target{}, nil } - target, _, err := s.git(ctx, "config", "--get", "remote.upstream.url") + upstreamURL, _, err := s.git(ctx, "config", "--get", "remote.upstream.url") if err != nil { - return "", "", nil, err + return target{}, err } - if upstream := githubRepository(target); upstream != "" { + if upstream := githubRepository(upstreamURL); upstream != "" { repo = upstream } branch, code, err := s.git(ctx, "symbolic-ref", "--quiet", "--short", "HEAD") if err != nil { - return "", "", nil, err + return target{}, err } if code == 1 { - return repo, "", errDetached, nil + return target{repo: repo, noHead: errDetached}, nil } if code != 0 { - return "", "", nil, notSent("cannot read current branch; nothing sent") + return target{}, notSent("cannot read current branch; nothing sent") } upstream, code, err := s.git(ctx, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}") if err != nil { - return "", "", nil, err + return target{}, err } hasUpstream := code == 0 pushRemote, _, err := s.git(ctx, "for-each-ref", "--format=%(push:remotename)", "refs/heads/"+branch) if err != nil { - return "", "", nil, err + return target{}, err } if pushRemote == "" { pushRemote = "origin" } - if !hasUpstream { - return repo, "", noUpstream(pushRemote), nil - } remote, code, err := s.git(ctx, "remote", "get-url", "--push", pushRemote) if err != nil { - return "", "", nil, err + return target{}, err } pushRepo := githubRepository(remote) + if !hasUpstream { + if code != 0 || pushRepo == "" { + return target{repo: repo, noHead: noUpstream(pushRemote)}, nil + } + name, err := s.pushedName(ctx, branch, pushRemote) + if err != nil { + return target{}, err + } + owner, _, _ := strings.Cut(pushRepo, "/") + return target{repo: repo, head: owner + ":" + name, + untracked: &guess{pushRepo: pushRepo, branch: name, notPushed: noUpstream(pushRemote)}}, nil + } if code != 0 || pushRepo == "" { - return "", "", nil, notSent("cannot identify the GitHub push destination; nothing sent") + return target{}, notSent("cannot identify the GitHub push destination; nothing sent") } _, remoteBranch, ok := strings.Cut(upstream, "/") if !ok || remoteBranch == "" { - return "", "", nil, notSent("cannot identify the upstream branch; nothing sent") + return target{}, notSent("cannot identify the upstream branch; nothing sent") } owner, _, _ := strings.Cut(pushRepo, "/") - return repo, owner + ":" + remoteBranch, nil, nil + return target{repo: repo, head: owner + ":" + remoteBranch}, nil +} + +// pushedName is the branch's name on the push remote: the merge ref that +// `git push -u` records, when it records it for that remote, else the local +// name. A merge ref of another remote is never paired with the push owner. +func (s *Sender) pushedName(ctx context.Context, branch, pushRemote string) (string, error) { + remote, _, err := s.git(ctx, "config", "--get", "branch."+branch+".remote") + if err != nil || remote != pushRemote { + return branch, err + } + merge, _, err := s.git(ctx, "config", "--get", "branch."+branch+".merge") + if name, ok := strings.CutPrefix(merge, "refs/heads/"); err == nil && ok && name != "" { + return name, nil + } + return branch, err } // githubRepository accepts GitHub HTTPS, SSH and scp-style clone URLs. Reject diff --git a/internal/history/github/sender_test.go b/internal/history/github/sender_test.go index 5d6237c2..0e770d4f 100644 --- a/internal/history/github/sender_test.go +++ b/internal/history/github/sender_test.go @@ -30,6 +30,10 @@ const ( upstreamCommand = "git rev-parse --abbrev-ref --symbolic-full-name @{upstream}" branchCommand = "git symbolic-ref --quiet --short HEAD" pushRemoteCommand = "git for-each-ref --format=%(push:remotename) refs/heads/feature" + branchRemote = "git config --get branch.feature.remote" + branchMerge = "git config --get branch.feature.merge" + headCommand = "git rev-parse HEAD" + localSHA = "2222222222222222222222222222222222222222" ) const testToken = "secret-test-token" @@ -227,16 +231,32 @@ func TestRepositoryRouting(t *testing.T) { originCommand: {Stdout: []byte("https://github.com/worker/shop.git")}, "git config --get remote.upstream.url": {Stdout: []byte("https://github.com/acme/shop.git")}, }, testRepo, forkHead}, - {"no upstream", map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}}, testRepo, ""}, + {"no upstream: the local name", map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}}, testRepo, "acme:feature"}, + {"no tracking ref: the merge ref of the push remote", map[string]toolrun.Output{ + upstreamCommand: {ExitCode: 128}, + branchRemote: {Stdout: []byte("origin\n")}, + branchMerge: {Stdout: []byte("refs/heads/work/part\n")}, + }, testRepo, "acme:work/part"}, + {"no tracking ref: a merge ref of another remote is not paired with the push owner", map[string]toolrun.Output{ + upstreamCommand: {ExitCode: 128}, + pushRemoteCommand: {Stdout: []byte("fork\n")}, + "git remote get-url --push fork": {Stdout: []byte("git@github.com:worker/shop.git\n")}, + branchRemote: {Stdout: []byte("origin\n")}, + }, testRepo, forkHead}, + {"no upstream, push remote not on GitHub", map[string]toolrun.Output{ + upstreamCommand: {ExitCode: 128}, + pushURLCommand: {Stdout: []byte("git@gitlab.com:acme/shop.git\n")}, + }, testRepo, ""}, {"detached", map[string]toolrun.Output{branchCommand: {ExitCode: 1}}, testRepo, ""}, {"non GitHub", map[string]toolrun.Output{originCommand: {Stdout: []byte("git@gitlab.com:acme/shop.git")}}, "", ""}, {"no origin", map[string]toolrun.Output{originCommand: {ExitCode: 1}}, "", ""}, } { t.Run(tc.name, func(t *testing.T) { s := New(".", gitRunner(t, tc.override)) - repo, head, _, err := s.repository(t.Context()) - if err != nil || repo != tc.repo || head != tc.head { - t.Fatalf("repo=%q head=%q err=%v", repo, head, err) + at, err := s.repository(t.Context()) + guessed := tc.override[upstreamCommand].ExitCode != 0 && tc.head != "" + if err != nil || at.repo != tc.repo || at.head != tc.head || (at.untracked != nil) != guessed { + t.Fatalf("target=%+v err=%v", at, err) } }) } @@ -250,11 +270,10 @@ func TestNoHeadSaysWhy(t *testing.T) { override map[string]toolrun.Output want string }{ - {"no upstream", map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}}, + {"no upstream, push remote not on GitHub", map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}, pushURLCommand: {Stdout: []byte("/srv/shop.git\n")}}, "this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: git push -u origin HEAD"}, - {"no upstream, fork push remote", map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}, pushRemoteCommand: {Stdout: []byte("fork\n")}}, - "this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: git push -u fork HEAD"}, - {"no upstream, unsafe remote name", map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}, pushRemoteCommand: {Stdout: []byte("$(touch x)\n")}}, + {"no upstream, unsafe remote name", map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}, pushRemoteCommand: {Stdout: []byte("$(touch x)\n")}, + "git remote get-url --push $(touch x)": {ExitCode: 2}}, "this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: push the branch with -u to its remote"}, {"detached", map[string]toolrun.Output{branchCommand: {ExitCode: 1}}, "HEAD is not on a branch, so archfit cannot find its pull request; nothing sent\nnext: switch to the branch of the pull request"}, @@ -270,6 +289,95 @@ func TestNoHeadSaysWhy(t *testing.T) { } } +// TestUntrackedBranchFindsItsPullRequest: a single-branch clone pushed with +// -u keeps no remote-tracking ref. The pull request is found by the branch +// name and gets the comment only when its head is HEAD; the no-upstream +// answer is kept for a branch that is not on GitHub (N3). +func TestUntrackedBranchFindsItsPullRequest(t *testing.T) { + const noUpstream = "this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: git push -u " + untracked := map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}} + forkPush := map[string]toolrun.Output{ + upstreamCommand: {ExitCode: 128}, + pushRemoteCommand: {Stdout: []byte("fork\n")}, + "git remote get-url --push fork": {Stdout: []byte("git@github.com:worker/shop.git\n")}, + } + for _, tc := range []struct { + name string + override map[string]toolrun.Output + can bool + head, pulls string + branchStatus int + branchPath string + wantPost string + wantError string + }{ + {"its pull request at HEAD gets the comment", untracked, false, "acme:feature", + `[{"number":431,"head":{"sha":"` + localSHA + `"}}]`, 0, "", "/repos/acme/shop/issues/431/comments", ""}, + {"a pull request at another commit gets nothing", untracked, false, "acme:feature", + `[{"number":431,"head":{"sha":"1111111111111111111111111111111111111111"}}]`, 0, "", "", + "pull request #431 is at 1111111, this checkout is at 2222222; nothing sent\nnext: git push"}, + {"a can answer also needs HEAD", untracked, true, "acme:feature", + `[{"number":431,"head":{"sha":"1111111111111111111111111111111111111111"}}]`, 0, "", "", "pull request #431 is at 1111111"}, + {"not on GitHub: no upstream", untracked, false, "acme:feature", "[]", + http.StatusNotFound, "/repos/acme/shop/branches/feature", "", noUpstream + "origin HEAD"}, + {"not on the fork: no upstream", forkPush, false, forkHead, "[]", + http.StatusNotFound, "/repos/worker/shop/branches/feature", "", noUpstream + "fork HEAD"}, + {"on GitHub without a pull request", map[string]toolrun.Output{ + upstreamCommand: {ExitCode: 128}, + branchRemote: {Stdout: []byte("origin\n")}, + branchMerge: {Stdout: []byte("refs/heads/feature/part\n")}, + }, false, "acme:feature/part", "[]", http.StatusOK, "/repos/acme/shop/branches/feature/part", "", + "no open pull request for acme:feature/part; nothing sent\nnext: open a pull request first"}, + {"a failed branch lookup says so", untracked, false, "acme:feature", "[]", + http.StatusBadGateway, "/repos/acme/shop/branches/feature", "", "GitHub returned HTTP 502; nothing sent"}, + {"a can answer without a pull request opens an issue", untracked, true, "acme:feature", "[]", 0, "", "/repos/acme/shop/issues", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("GH_TOKEN", testToken) + r := Input{Reason: testReason} + if tc.can { + r.Can = canAnswer() + } + var posts, branchLookups []string + s := fakeSender(t, tc.override, func(w http.ResponseWriter, req *http.Request) { + switch { + case req.Method == http.MethodGet && req.URL.Path == "/repos/acme/shop/pulls": + if got := req.URL.Query().Get("head"); got != tc.head { + t.Errorf("lookup head %q, want %q", got, tc.head) + } + _, _ = fmt.Fprint(w, tc.pulls) + case req.Method == http.MethodGet: + branchLookups = append(branchLookups, req.URL.Path) + w.WriteHeader(tc.branchStatus) + _, _ = fmt.Fprint(w, `{"name":"feature"}`) + default: + posts = append(posts, req.URL.Path) + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(map[string]any{"number": 431, "id": 9, "html_url": commentURL}) + } + }) + _, err := s.Send(t.Context(), r) + wantLookups := []string(nil) + if tc.branchPath != "" { + wantLookups = []string{tc.branchPath} + } + if !reflect.DeepEqual(branchLookups, wantLookups) { + t.Errorf("branch lookups %v, want %v", branchLookups, wantLookups) + } + if tc.wantError != "" { + var marked interface{ NothingSent() } + if err == nil || !strings.HasPrefix(err.Error(), tc.wantError) || !errors.As(err, &marked) || len(posts) != 0 { + t.Fatalf("err=%v posts=%v, want %q", err, posts, tc.wantError) + } + return + } + if err != nil || !reflect.DeepEqual(posts, []string{tc.wantPost}) { + t.Fatalf("err=%v posts=%v, want %s", err, posts, tc.wantPost) + } + }) + } +} + // TestUnreachableGitHubNamesTheCause: a lookup that never reaches GitHub // says so with the network error, never the URL or the token (B6). func TestUnreachableGitHubNamesTheCause(t *testing.T) { @@ -400,6 +508,9 @@ func gitRunner(t *testing.T, override map[string]toolrun.Output) *toolrun.Runner branchCommand: {Stdout: []byte("feature\n")}, upstreamCommand: {Stdout: []byte("origin/feature\n")}, pushRemoteCommand: {}, + branchRemote: {ExitCode: 1}, + branchMerge: {ExitCode: 1}, + headCommand: {Stdout: []byte(localSHA + "\n")}, } for key, value := range override { commands[key] = value From 0df7ae688d958ac1947f91a4402153d24225a2e6 Mon Sep 17 00:00:00 2001 From: Alexei Ledenev Date: Tue, 24 Nov 2026 14:46:11 +0200 Subject: [PATCH 4/9] fix(check): say the target changed the policy when the branch did not After an owner's policy change merges into the target branch, a branch made before it got "why: only owners change the policy", which reads as if the author edited the file. When the branch's file is the one at the merge base, the record now says the policy changed on the target branch and that the check uses that policy. A branch that edited the file keeps the old record. --- docs/agents.md | 6 ++++-- docs/results.md | 8 +++++++- docs/troubleshooting.md | 10 +++++++++- internal/application/changecheck/changecheck.go | 17 +++++++++++------ .../application/changecheck/changecheck_test.go | 12 ++++++++---- internal/history/github/sender_test.go | 4 ++++ 6 files changed, 43 insertions(+), 14 deletions(-) diff --git a/docs/agents.md b/docs/agents.md index 6c359efb..878b4fd1 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -180,8 +180,10 @@ results need one: - A `fail` whose `next:` is `archfit request`: the policy does not allow the change. Only an owner can change that. -- An `unknown` whose cause is `policy`: the policy differs from the target - branch. An owner approves a policy change. +- An `unknown` whose cause is `policy` and whose `why:` is `only owners change + the policy`: the branch changed the policy. An owner approves a policy change. + When the record says the policy changed on the target branch instead, merge + the target branch and run the check again. An `unknown` whose `next:` names a tool or a `git fetch` is yours to clear. diff --git a/docs/results.md b/docs/results.md index e1448616..64fb24ef 100644 --- a/docs/results.md +++ b/docs/results.md @@ -43,7 +43,13 @@ $ archfit check archfit: unknown, no verdict ``` -This branch changed `.archfit.yaml`, so `next` restores the file. When the branch's file is still the one at the merge base and an owner changed the policy on the target branch, `next` is `git merge origin/main, then run archfit check again`. +This branch changed `.archfit.yaml`, so `next` restores the file. When the branch's file is still the one at the merge base, an owner changed the policy on the target branch, and the record says so: + +```text +.archfit.yaml: policy: changed on origin/main since this branch started + why: the check uses the policy on origin/main + next: git merge origin/main, then run archfit check again +``` - `next` is `fix the code`, a command to run, `wait for an owner: #n`, or a short instruction such as `git fetch --unshallow`. A note in parentheses can follow it. - An error with no file, such as an expired exception, names `.archfit.yaml` and no line. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 29283b22..21dedb8e 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -34,7 +34,15 @@ The keys are a top-level `coupling` or `ai`, a `type` in a rule, and `scip` or ` ## Policy differs from the target -A code change cannot judge itself under a policy it changes. Open a separate policy pull request for an owner, and restore the file on your branch: the record names the command. When an owner changed the policy on the target branch after you made your branch, the record says so with its `next` line: merge the target branch into your branch (`git merge origin/main`) and run `archfit check` again. +A code change cannot judge itself under a policy it changes. Open a separate policy pull request for an owner, and restore the file on your branch: the record names the command. When an owner changed the policy on the target branch after you made your branch, the record says so: + +```text +.archfit.yaml: policy: changed on origin/main since this branch started + why: the check uses the policy on origin/main + next: git merge origin/main, then run archfit check again +``` + +Merge the target branch into your branch and run `archfit check` again. An owner can preview a candidate with `archfit check --policy candidate.yaml`. A preview gives no verdict and saves no output for `archfit request`. diff --git a/internal/application/changecheck/changecheck.go b/internal/application/changecheck/changecheck.go index e205a954..0f8463d2 100644 --- a/internal/application/changecheck/changecheck.go +++ b/internal/application/changecheck/changecheck.go @@ -185,6 +185,7 @@ type Outcome struct { const ( whyCompare = "the check compares the change with the merge base of its target branch" whyDiffers = "only owners change the policy" + whyMoved = "the check uses the policy on %s" whyInvalid = "the check cannot judge with a policy that is not valid" whyTree = "the policy does not fit the files of the tree" whyTargetBad = "the policy on %s is not valid" @@ -195,6 +196,7 @@ const ( whatNoBase = "HEAD and %s have no merge base in this clone" whatNoParent = "HEAD is the tip of %s and its parent is not in this clone" whatDiffers = "differs from %s" + whatMoved = "changed on %s since this branch started" whatNoPolicy = "no policy file" nextBaseFlag = "pass --base " nextFetch = "git fetch" @@ -479,18 +481,21 @@ func (s Service) compare(ctx context.Context, r *run, ref, commit string) (compa case t.Err != nil: r.stopLines(t.Err, fmt.Sprintf(whyTargetBad, ref), result.NextRestore, fmt.Sprintf(nextAskOwner, ref)) case r.differs: - next := fmt.Sprintf(nextRestore, ref) moved, err := s.targetMoved(ctx, r, commit) if err != nil { return false, err } + // A branch that edited the file must restore it; a branch the target + // moved past only needs the target's policy, so it is not told that + // only owners change the policy. + why := reason{ + path: PolicyPath, cause: result.CausePolicy, what: fmt.Sprintf(whatDiffers, ref), why: whyDiffers, + kind: result.NextRestore, next: fmt.Sprintf(nextRestore, ref), + } if moved { - next = fmt.Sprintf(nextMerge, ref) + why.what, why.why, why.next = fmt.Sprintf(whatMoved, ref), fmt.Sprintf(whyMoved, ref), fmt.Sprintf(nextMerge, ref) } - r.stop(reason{ - path: PolicyPath, cause: result.CausePolicy, what: fmt.Sprintf(whatDiffers, ref), why: whyDiffers, - kind: result.NextRestore, next: next, - }) + r.stop(why) } return true, nil } diff --git a/internal/application/changecheck/changecheck_test.go b/internal/application/changecheck/changecheck_test.go index 5adb047e..d5e01811 100644 --- a/internal/application/changecheck/changecheck_test.go +++ b/internal/application/changecheck/changecheck_test.go @@ -543,7 +543,7 @@ func TestCheck(t *testing.T) { name: "a policy the target changed after the merge base names the merge", setup: func(w *world) { w.policies.target[mainSHA] = file(policyYAML + "# owner\n") }, want: want{ - record: ".archfit.yaml: policy: differs from origin/main\n why: only owners change the policy\n" + + record: ".archfit.yaml: policy: changed on origin/main since this branch started\n why: the check uses the policy on origin/main\n" + " next: git merge origin/main, then run archfit check again\n" + noVerdict, target: mainRef, differs: true, base: baseSHA, stored: true, }, @@ -556,7 +556,7 @@ func TestCheck(t *testing.T) { w.policies.target[mainSHA] = file(policyYAML + "# owner\n") }, want: want{ - record: ".archfit.yaml: policy: differs from origin/main\n why: only owners change the policy\n" + + record: ".archfit.yaml: policy: changed on origin/main since this branch started\n why: the check uses the policy on origin/main\n" + " next: git merge origin/main, then run archfit check again\n" + noVerdict, target: mainRef, differs: true, base: headSHA, stored: true, }, @@ -568,7 +568,7 @@ func TestCheck(t *testing.T) { delete(w.policies.target, baseSHA) }, want: want{ - record: ".archfit.yaml: policy: differs from origin/main\n why: only owners change the policy\n" + + record: ".archfit.yaml: policy: changed on origin/main since this branch started\n why: the check uses the policy on origin/main\n" + " next: git merge origin/main, then run archfit check again\n" + noVerdict, target: mainRef, differs: true, base: baseSHA, stored: true, }, @@ -715,7 +715,11 @@ func TestCheck(t *testing.T) { w := newWorld() tt.setup(w) out := w.check(t, tt.opts) - if got := render(t, out.Result); got != tt.want.record { + got := render(t, out.Result) + if words := testutil.StoryNotUsedIn(got); tt.want.differs && len(words) > 0 { + t.Errorf("the policy record uses %v:\n%s", words, got) + } + if got != tt.want.record { t.Errorf("record:\n--- got\n%s--- want\n%s", got, tt.want.record) } for _, note := range out.Notes { diff --git a/internal/history/github/sender_test.go b/internal/history/github/sender_test.go index 0e770d4f..1aa07f45 100644 --- a/internal/history/github/sender_test.go +++ b/internal/history/github/sender_test.go @@ -15,6 +15,7 @@ import ( "sync/atomic" "testing" + "github.com/coupling-dev/archfit/internal/testutil" "github.com/coupling-dev/archfit/internal/toolrun" ) @@ -369,6 +370,9 @@ func TestUntrackedBranchFindsItsPullRequest(t *testing.T) { if err == nil || !strings.HasPrefix(err.Error(), tc.wantError) || !errors.As(err, &marked) || len(posts) != 0 { t.Fatalf("err=%v posts=%v, want %q", err, posts, tc.wantError) } + if words := testutil.StoryNotUsedIn(err.Error()); len(words) > 0 { + t.Errorf("%q uses %v", err, words) + } return } if err != nil || !reflect.DeepEqual(posts, []string{tc.wantPost}) { From 2a651cc30c4c205c2bc4691cc96eaf84cffd218e Mon Sep 17 00:00:00 2001 From: Alexei Ledenev Date: Tue, 24 Nov 2026 14:46:23 +0200 Subject: [PATCH 5/9] docs(ci): a candidate build reads the check of its own App --- docs/ci.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/ci.md b/docs/ci.md index 2fb00ea5..5e69b6b0 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -13,6 +13,7 @@ Run [`archfit setup`](commands.md#setup) to write this workflow. Setup substitut `main` and the commit SHA of the Action tag that matches the installed Archfit release. For an annotated tag, it uses the commit the tag points to. Development builds cannot pin an Action release. A candidate build, made for testing before a release, pins an Action commit and marks it `# candidate` instead of a tag. +A candidate build can also name another App, such as a staging App. `archfit setup` and `archfit status` then read the `archfit/gate` check of that App only. Setup does not replace an existing workflow. The Action checks out the repository itself. ```yaml From cba2e46282bf26b8e37ac93d1cd3df1e937ac8f0 Mon Sep 17 00:00:00 2001 From: Alexei Ledenev Date: Tue, 24 Nov 2026 14:50:45 +0200 Subject: [PATCH 6/9] test: name repeated request test values and report a failed status write Lint flagged repeated literals, the CLI test's complexity and a Run that always returned nil. The status command now returns a stdout write failure. --- cmd/archfit/request_send_test.go | 16 ++++-- cmd/archfit/status.go | 4 +- internal/history/github/regression_test.go | 4 +- internal/history/github/sender_test.go | 62 ++++++++++++---------- 4 files changed, 50 insertions(+), 36 deletions(-) diff --git a/cmd/archfit/request_send_test.go b/cmd/archfit/request_send_test.go index 0f7c9cf8..cf831d0d 100644 --- a/cmd/archfit/request_send_test.go +++ b/cmd/archfit/request_send_test.go @@ -69,12 +69,8 @@ func TestRequestSendsFromCLI(t *testing.T) { if r.Header.Get("Authorization") != "Bearer "+token { t.Error("missing credential") } - if r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/branches/") { - w.WriteHeader(http.StatusNotFound) - return - } if r.Method == http.MethodGet { - _, _ = fmt.Fprint(w, tc.pulls) + answerLookup(w, r, tc.pulls) return } posts++ @@ -154,6 +150,16 @@ type requestTransport func(*http.Request) (*http.Response, error) func (f requestTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } +// answerLookup answers the pull request lookup with pulls. The branch is not +// on GitHub, so a branch lookup is 404. +func answerLookup(w http.ResponseWriter, r *http.Request, pulls string) { + if strings.Contains(r.URL.Path, "/branches/") { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = fmt.Fprint(w, pulls) +} + // TestRequestFindsThePullRequestWithoutATrackingRef: a single-branch clone // pushed with -u records the upstream but keeps no remote-tracking ref. The // request still reaches the branch's pull request when its head is HEAD (N3). diff --git a/cmd/archfit/status.go b/cmd/archfit/status.go index 237102e5..b5d0921f 100644 --- a/cmd/archfit/status.go +++ b/cmd/archfit/status.go @@ -26,7 +26,9 @@ func (c *StatusCmd) Run(deps *appDeps) error { in.StoryText, _ = requestsend.StoryText(ctx, co.root, co.runner, setup.AppSlug()) } for _, line := range request.Status(in) { - _, _ = fmt.Fprintln(deps.Stdout, line) + if _, err := fmt.Fprintln(deps.Stdout, line); err != nil { + return err + } } return nil } diff --git a/internal/history/github/regression_test.go b/internal/history/github/regression_test.go index 062769d1..af6d5093 100644 --- a/internal/history/github/regression_test.go +++ b/internal/history/github/regression_test.go @@ -1,7 +1,6 @@ package requestsend import ( - "encoding/json" "fmt" "net/http" "testing" @@ -53,8 +52,7 @@ func TestCanonicalReceiptCasing(t *testing.T) { if can { receipt = issueURL } - w.WriteHeader(http.StatusCreated) - _ = json.NewEncoder(w).Encode(map[string]any{"number": 431, "id": 9, "html_url": receipt}) + created(w, receipt) }) in := Input{Reason: testReason} if can { diff --git a/internal/history/github/sender_test.go b/internal/history/github/sender_test.go index 1aa07f45..332d4eb6 100644 --- a/internal/history/github/sender_test.go +++ b/internal/history/github/sender_test.go @@ -35,6 +35,10 @@ const ( branchMerge = "git config --get branch.feature.merge" headCommand = "git rev-parse HEAD" localSHA = "2222222222222222222222222222222222222222" + forkPushURL = "git remote get-url --push fork" + originHead = "acme:feature" + commentsPath = "/repos/acme/shop/issues/431/comments" + issuesPath = "/repos/acme/shop/issues" ) const testToken = "secret-test-token" @@ -50,9 +54,9 @@ func TestSendPaths(t *testing.T) { wantPath, wantURL string wantError string }{ - {"check comment", false, onePull, "/repos/acme/shop/issues/431/comments", commentURL, ""}, - {"can comment", true, onePull, "/repos/acme/shop/issues/431/comments", commentURL, ""}, - {"can issue", true, "[]", "/repos/acme/shop/issues", issueURL, ""}, + {"check comment", false, onePull, commentsPath, commentURL, ""}, + {"can comment", true, onePull, commentsPath, commentURL, ""}, + {"can issue", true, "[]", issuesPath, issueURL, ""}, {"check without pull", false, "[]", "", "", "no open pull request for acme:feature; nothing sent\nnext: open a pull request first"}, {"ambiguous", false, "[{\"number\":431},{\"number\":432}]", "", "", "#431, #432"}, } { @@ -68,7 +72,7 @@ func TestSendPaths(t *testing.T) { t.Error("missing credential") } if req.Method == http.MethodGet { - if req.URL.Path != "/repos/acme/shop/pulls" || req.URL.Query().Get("state") != "open" || req.URL.Query().Get("head") != "acme:feature" { + if req.URL.Path != "/repos/acme/shop/pulls" || req.URL.Query().Get("state") != "open" || req.URL.Query().Get("head") != originHead { t.Errorf("lookup: %s", req.URL) } _, _ = fmt.Fprint(w, tc.pulls) @@ -82,15 +86,14 @@ func TestSendPaths(t *testing.T) { if err := json.NewDecoder(req.Body).Decode(&payload); err != nil { t.Error(err) } - if tc.wantPath == "/repos/acme/shop/issues" { + if tc.wantPath == issuesPath { if payload.Title != "archfit request: a -> b" || payload.Body != issueBody(r) { t.Errorf("issue: %+v", payload) } } else if payload.Body != Line(r) || payload.Title != "" { t.Errorf("comment: %+v", payload) } - w.WriteHeader(http.StatusCreated) - _ = json.NewEncoder(w).Encode(map[string]any{"number": 431, "id": 9, "html_url": tc.wantURL}) + created(w, tc.wantURL) }) got, err := s.Send(t.Context(), r) if tc.wantError != "" { @@ -223,26 +226,26 @@ func TestRepositoryRouting(t *testing.T) { override map[string]toolrun.Output repo, head string }{ - {"origin", nil, testRepo, "acme:feature"}, + {"origin", nil, testRepo, originHead}, {"fork push", map[string]toolrun.Output{ - pushRemoteCommand: {Stdout: []byte("fork\n")}, - "git remote get-url --push fork": {Stdout: []byte("git@github.com:worker/shop.git\n")}, + pushRemoteCommand: {Stdout: []byte("fork\n")}, + forkPushURL: {Stdout: []byte("git@github.com:worker/shop.git\n")}, }, testRepo, forkHead}, {"origin fork upstream", map[string]toolrun.Output{ originCommand: {Stdout: []byte("https://github.com/worker/shop.git")}, "git config --get remote.upstream.url": {Stdout: []byte("https://github.com/acme/shop.git")}, }, testRepo, forkHead}, - {"no upstream: the local name", map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}}, testRepo, "acme:feature"}, + {"no upstream: the local name", map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}}, testRepo, originHead}, {"no tracking ref: the merge ref of the push remote", map[string]toolrun.Output{ upstreamCommand: {ExitCode: 128}, branchRemote: {Stdout: []byte("origin\n")}, branchMerge: {Stdout: []byte("refs/heads/work/part\n")}, }, testRepo, "acme:work/part"}, {"no tracking ref: a merge ref of another remote is not paired with the push owner", map[string]toolrun.Output{ - upstreamCommand: {ExitCode: 128}, - pushRemoteCommand: {Stdout: []byte("fork\n")}, - "git remote get-url --push fork": {Stdout: []byte("git@github.com:worker/shop.git\n")}, - branchRemote: {Stdout: []byte("origin\n")}, + upstreamCommand: {ExitCode: 128}, + pushRemoteCommand: {Stdout: []byte("fork\n")}, + forkPushURL: {Stdout: []byte("git@github.com:worker/shop.git\n")}, + branchRemote: {Stdout: []byte("origin\n")}, }, testRepo, forkHead}, {"no upstream, push remote not on GitHub", map[string]toolrun.Output{ upstreamCommand: {ExitCode: 128}, @@ -298,9 +301,9 @@ func TestUntrackedBranchFindsItsPullRequest(t *testing.T) { const noUpstream = "this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: git push -u " untracked := map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}} forkPush := map[string]toolrun.Output{ - upstreamCommand: {ExitCode: 128}, - pushRemoteCommand: {Stdout: []byte("fork\n")}, - "git remote get-url --push fork": {Stdout: []byte("git@github.com:worker/shop.git\n")}, + upstreamCommand: {ExitCode: 128}, + pushRemoteCommand: {Stdout: []byte("fork\n")}, + forkPushURL: {Stdout: []byte("git@github.com:worker/shop.git\n")}, } for _, tc := range []struct { name string @@ -312,14 +315,14 @@ func TestUntrackedBranchFindsItsPullRequest(t *testing.T) { wantPost string wantError string }{ - {"its pull request at HEAD gets the comment", untracked, false, "acme:feature", - `[{"number":431,"head":{"sha":"` + localSHA + `"}}]`, 0, "", "/repos/acme/shop/issues/431/comments", ""}, - {"a pull request at another commit gets nothing", untracked, false, "acme:feature", + {"its pull request at HEAD gets the comment", untracked, false, originHead, + `[{"number":431,"head":{"sha":"` + localSHA + `"}}]`, 0, "", commentsPath, ""}, + {"a pull request at another commit gets nothing", untracked, false, originHead, `[{"number":431,"head":{"sha":"1111111111111111111111111111111111111111"}}]`, 0, "", "", "pull request #431 is at 1111111, this checkout is at 2222222; nothing sent\nnext: git push"}, - {"a can answer also needs HEAD", untracked, true, "acme:feature", + {"a can answer also needs HEAD", untracked, true, originHead, `[{"number":431,"head":{"sha":"1111111111111111111111111111111111111111"}}]`, 0, "", "", "pull request #431 is at 1111111"}, - {"not on GitHub: no upstream", untracked, false, "acme:feature", "[]", + {"not on GitHub: no upstream", untracked, false, originHead, "[]", http.StatusNotFound, "/repos/acme/shop/branches/feature", "", noUpstream + "origin HEAD"}, {"not on the fork: no upstream", forkPush, false, forkHead, "[]", http.StatusNotFound, "/repos/worker/shop/branches/feature", "", noUpstream + "fork HEAD"}, @@ -329,9 +332,9 @@ func TestUntrackedBranchFindsItsPullRequest(t *testing.T) { branchMerge: {Stdout: []byte("refs/heads/feature/part\n")}, }, false, "acme:feature/part", "[]", http.StatusOK, "/repos/acme/shop/branches/feature/part", "", "no open pull request for acme:feature/part; nothing sent\nnext: open a pull request first"}, - {"a failed branch lookup says so", untracked, false, "acme:feature", "[]", + {"a failed branch lookup says so", untracked, false, originHead, "[]", http.StatusBadGateway, "/repos/acme/shop/branches/feature", "", "GitHub returned HTTP 502; nothing sent"}, - {"a can answer without a pull request opens an issue", untracked, true, "acme:feature", "[]", 0, "", "/repos/acme/shop/issues", ""}, + {"a can answer without a pull request opens an issue", untracked, true, originHead, "[]", 0, "", issuesPath, ""}, } { t.Run(tc.name, func(t *testing.T) { t.Setenv("GH_TOKEN", testToken) @@ -353,8 +356,7 @@ func TestUntrackedBranchFindsItsPullRequest(t *testing.T) { _, _ = fmt.Fprint(w, `{"name":"feature"}`) default: posts = append(posts, req.URL.Path) - w.WriteHeader(http.StatusCreated) - _ = json.NewEncoder(w).Encode(map[string]any{"number": 431, "id": 9, "html_url": commentURL}) + created(w, commentURL) } }) _, err := s.Send(t.Context(), r) @@ -477,6 +479,12 @@ type roundTripFunc func(*http.Request) (*http.Response, error) func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } +// created answers a POST with the receipt of comment 9 on pull request 431. +func created(w http.ResponseWriter, receipt string) { + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(map[string]any{"number": 431, "id": 9, "html_url": receipt}) +} + func fakeSender(t *testing.T, override map[string]toolrun.Output, handler http.HandlerFunc) *Sender { t.Helper() var logs bytes.Buffer From 099fb70464c7527dc3006cb00be5c3cdf80248d2 Mon Sep 17 00:00:00 2001 From: Alexei Ledenev Date: Tue, 24 Nov 2026 14:59:30 +0200 Subject: [PATCH 7/9] fix(request,setup): name the push that works and trust no App for an unknown link Review findings: on the local-name fallback a head mismatch advised git push, which fails without an upstream; it now advises git push -u HEAD. An install link with no App slug fell back to the production App; it now trusts no App. --- docs/ci.md | 2 +- docs/commands.md | 2 +- internal/application/setup/setup.go | 14 +++++----- internal/application/setup/setup_test.go | 8 +++--- internal/history/github/sender.go | 33 ++++++++++++++++-------- internal/history/github/sender_test.go | 22 +++++++++++----- 6 files changed, 50 insertions(+), 31 deletions(-) diff --git a/docs/ci.md b/docs/ci.md index 5e69b6b0..bc308c02 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -13,7 +13,7 @@ Run [`archfit setup`](commands.md#setup) to write this workflow. Setup substitut `main` and the commit SHA of the Action tag that matches the installed Archfit release. For an annotated tag, it uses the commit the tag points to. Development builds cannot pin an Action release. A candidate build, made for testing before a release, pins an Action commit and marks it `# candidate` instead of a tag. -A candidate build can also name another App, such as a staging App. `archfit setup` and `archfit status` then read the `archfit/gate` check of that App only. +A candidate build can also name another App, such as a staging App, in its install link. `archfit setup` and `archfit status` then read the `archfit/gate` check of that App only. A build whose install link names no App reads no check. Setup does not replace an existing workflow. The Action checks out the repository itself. ```yaml diff --git a/docs/commands.md b/docs/commands.md index 271edcf7..4e3eb60f 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -135,7 +135,7 @@ Only an error whose `next` is `archfit request` joins the request: an error of a A use past the surface asks one question: should its package be part of the surface? The printed request shows it on a `question:` line; the App asks the owner to declare the package `public` or `model`, or to reject the request. -With a GitHub remote, `archfit request` posts `/archfit request [--expires DATE]` as a comment on the one open pull request for the current branch. The target repository is `origin`, or a configured GitHub `upstream` for a fork. The head uses the push remote's owner, falling back to the `origin` owner. Several matching pull requests means nothing is sent: the error names their numbers. A detached HEAD names no pull request: the error says so. When Git keeps no remote-tracking ref for the branch, as in a clone made with `--single-branch`, the request looks for the pull request by the branch's name on the push remote. It posts only when that pull request's head is the current commit; otherwise it names both commits and sends nothing, with `next: git push`. When the branch is not on GitHub at all, the error says the branch has no upstream branch, with `next: git push -u HEAD`. +With a GitHub remote, `archfit request` posts `/archfit request [--expires DATE]` as a comment on the one open pull request for the current branch. The target repository is `origin`, or a configured GitHub `upstream` for a fork. The head uses the push remote's owner, falling back to the `origin` owner. Several matching pull requests means nothing is sent: the error names their numbers. A detached HEAD names no pull request: the error says so. When Git keeps no remote-tracking ref for the branch, as in a clone made with `--single-branch`, the request looks for the pull request by the branch's name on the push remote. It posts only when that pull request's head is the current commit; otherwise it names both commits and sends nothing, with `next: git push`, or `next: git push -u HEAD` when Git records no upstream for the branch. When the branch is not on GitHub at all, the error says the branch has no upstream branch, with `next: git push -u HEAD`. Without a pull request, only a request from `archfit can` opens an issue. Its body holds the request line and the `can` record; the App marks the numbers "as reported" until a pull request confirms them. With `check` output, nothing is opened: `no open pull request for :` and `next: open a pull request first`. diff --git a/internal/application/setup/setup.go b/internal/application/setup/setup.go index ace2d5eb..6da0e27a 100644 --- a/internal/application/setup/setup.go +++ b/internal/application/setup/setup.go @@ -30,21 +30,19 @@ var ( InstallURL = "https://github.com/apps/archfit-review/installations/new" ) -const ( - defaultAppSlug = "archfit-review" - appsPrefix = "https://github.com/apps/" -) +const appsPrefix = "https://github.com/apps/" // AppSlug is the App whose archfit/gate check this build trusts: the slug in // InstallURL, so a candidate build that installs another App also reads its -// check. +// check. An InstallURL with no slug trusts no App: falling back to the +// production App would read a check the build does not send users to. func AppSlug() string { return appSlug(InstallURL) } func appSlug(installURL string) string { rest, ok := strings.CutPrefix(installURL, appsPrefix) - slug, _, found := strings.Cut(rest, "/") - if !ok || !found || slug == "" { - return defaultAppSlug + slug, _, _ := strings.Cut(rest, "/") + if !ok { + return "" } return slug } diff --git a/internal/application/setup/setup_test.go b/internal/application/setup/setup_test.go index f81753c3..a0431826 100644 --- a/internal/application/setup/setup_test.go +++ b/internal/application/setup/setup_test.go @@ -112,10 +112,10 @@ func TestAppSlugComesFromTheInstallURL(t *testing.T) { for _, tc := range []struct{ url, want string }{ {"https://github.com/apps/archfit-review/installations/new", "archfit-review"}, {"https://github.com/apps/archfit-review-staging/installations/new", "archfit-review-staging"}, - {"https://github.com/apps/archfit-review-staging", defaultAppSlug}, - {"https://github.com/apps//installations/new", defaultAppSlug}, - {"https://example.com/apps/x/installations/new", defaultAppSlug}, - {"", defaultAppSlug}, + {"https://github.com/apps/archfit-review-staging", "archfit-review-staging"}, + {"https://github.com/apps//installations/new", ""}, + {"https://example.com/apps/x/installations/new", ""}, + {"", ""}, } { if got := appSlug(tc.url); got != tc.want { t.Errorf("appSlug(%q) = %q, want %q", tc.url, got, tc.want) diff --git a/internal/history/github/sender.go b/internal/history/github/sender.go index a176a3dc..5fb6c9d9 100644 --- a/internal/history/github/sender.go +++ b/internal/history/github/sender.go @@ -133,6 +133,9 @@ type guess struct { pushRepo, branch string // notPushed is the answer when the branch is not on the push remote. notPushed error + // push is the command that sends HEAD to the pull request: `git push` + // when Git records the branch's upstream, else it must also set it. + push string } // untracked guards a guessed head. It posts only on a pull request whose head @@ -149,8 +152,8 @@ func (s *Sender) untracked(ctx context.Context, token string, g guess, pulls []p return notSent("cannot read HEAD; nothing sent") } if pulls[0].Head.SHA != local { - return notSent(fmt.Sprintf("pull request #%d is at %.7s, this checkout is at %.7s; nothing sent\nnext: git push", - pulls[0].Number, pulls[0].Head.SHA, local)) + return notSent(fmt.Sprintf("pull request #%d is at %.7s, this checkout is at %.7s; nothing sent\nnext: %s", + pulls[0].Number, pulls[0].Head.SHA, local, g.push)) } return nil } @@ -194,11 +197,14 @@ var ( // noUpstream names the push remote in the command only when the name is safe // to paste into a shell. func noUpstream(remote string) error { - next := "push the branch with -u to its remote" + return notSent("this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: " + pushUpstream(remote)) +} + +func pushUpstream(remote string) string { if remoteName.MatchString(remote) { - next = "git push -u " + remote + " HEAD" + return "git push -u " + remote + " HEAD" } - return notSent("this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: " + next) + return "push the branch with -u to its remote" } // transportCause is the first line of the network error under err, never the @@ -375,13 +381,17 @@ func (s *Sender) repository(ctx context.Context) (target, error) { if code != 0 || pushRepo == "" { return target{repo: repo, noHead: noUpstream(pushRemote)}, nil } - name, err := s.pushedName(ctx, branch, pushRemote) + name, recorded, err := s.pushedName(ctx, branch, pushRemote) if err != nil { return target{}, err } + push := pushUpstream(pushRemote) + if recorded { + push = "git push" + } owner, _, _ := strings.Cut(pushRepo, "/") return target{repo: repo, head: owner + ":" + name, - untracked: &guess{pushRepo: pushRepo, branch: name, notPushed: noUpstream(pushRemote)}}, nil + untracked: &guess{pushRepo: pushRepo, branch: name, notPushed: noUpstream(pushRemote), push: push}}, nil } if code != 0 || pushRepo == "" { return target{}, notSent("cannot identify the GitHub push destination; nothing sent") @@ -397,16 +407,17 @@ func (s *Sender) repository(ctx context.Context) (target, error) { // pushedName is the branch's name on the push remote: the merge ref that // `git push -u` records, when it records it for that remote, else the local // name. A merge ref of another remote is never paired with the push owner. -func (s *Sender) pushedName(ctx context.Context, branch, pushRemote string) (string, error) { +// recorded says whether Git records that upstream. +func (s *Sender) pushedName(ctx context.Context, branch, pushRemote string) (name string, recorded bool, err error) { remote, _, err := s.git(ctx, "config", "--get", "branch."+branch+".remote") if err != nil || remote != pushRemote { - return branch, err + return branch, false, err } merge, _, err := s.git(ctx, "config", "--get", "branch."+branch+".merge") if name, ok := strings.CutPrefix(merge, "refs/heads/"); err == nil && ok && name != "" { - return name, nil + return name, true, nil } - return branch, err + return branch, false, err } // githubRepository accepts GitHub HTTPS, SSH and scp-style clone URLs. Reject diff --git a/internal/history/github/sender_test.go b/internal/history/github/sender_test.go index 332d4eb6..41689c5f 100644 --- a/internal/history/github/sender_test.go +++ b/internal/history/github/sender_test.go @@ -298,8 +298,17 @@ func TestNoHeadSaysWhy(t *testing.T) { // name and gets the comment only when its head is HEAD; the no-upstream // answer is kept for a branch that is not on GitHub (N3). func TestUntrackedBranchFindsItsPullRequest(t *testing.T) { - const noUpstream = "this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: git push -u " + const ( + noUpstream = "this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: git push -u " + otherCommit = `[{"number":431,"head":{"sha":"1111111111111111111111111111111111111111"}}]` + atOtherCommit = "pull request #431 is at 1111111, this checkout is at 2222222; nothing sent\nnext: " + ) untracked := map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}} + recorded := map[string]toolrun.Output{ + upstreamCommand: {ExitCode: 128}, + branchRemote: {Stdout: []byte("origin\n")}, + branchMerge: {Stdout: []byte("refs/heads/feature\n")}, + } forkPush := map[string]toolrun.Output{ upstreamCommand: {ExitCode: 128}, pushRemoteCommand: {Stdout: []byte("fork\n")}, @@ -317,11 +326,12 @@ func TestUntrackedBranchFindsItsPullRequest(t *testing.T) { }{ {"its pull request at HEAD gets the comment", untracked, false, originHead, `[{"number":431,"head":{"sha":"` + localSHA + `"}}]`, 0, "", commentsPath, ""}, - {"a pull request at another commit gets nothing", untracked, false, originHead, - `[{"number":431,"head":{"sha":"1111111111111111111111111111111111111111"}}]`, 0, "", "", - "pull request #431 is at 1111111, this checkout is at 2222222; nothing sent\nnext: git push"}, + {"a pull request at another commit gets nothing; push sets the upstream", untracked, false, originHead, + otherCommit, 0, "", "", atOtherCommit + "git push -u origin HEAD"}, + {"a recorded upstream only needs a push", recorded, false, originHead, + otherCommit, 0, "", "", atOtherCommit + "git push"}, {"a can answer also needs HEAD", untracked, true, originHead, - `[{"number":431,"head":{"sha":"1111111111111111111111111111111111111111"}}]`, 0, "", "", "pull request #431 is at 1111111"}, + otherCommit, 0, "", "", atOtherCommit + "git push -u origin HEAD"}, {"not on GitHub: no upstream", untracked, false, originHead, "[]", http.StatusNotFound, "/repos/acme/shop/branches/feature", "", noUpstream + "origin HEAD"}, {"not on the fork: no upstream", forkPush, false, forkHead, "[]", @@ -369,7 +379,7 @@ func TestUntrackedBranchFindsItsPullRequest(t *testing.T) { } if tc.wantError != "" { var marked interface{ NothingSent() } - if err == nil || !strings.HasPrefix(err.Error(), tc.wantError) || !errors.As(err, &marked) || len(posts) != 0 { + if err == nil || err.Error() != tc.wantError || !errors.As(err, &marked) || len(posts) != 0 { t.Fatalf("err=%v posts=%v, want %q", err, posts, tc.wantError) } if words := testutil.StoryNotUsedIn(err.Error()); len(words) > 0 { From c7181c26ef17af75ab2f532b8a068bde73ed43e9 Mon Sep 17 00:00:00 2001 From: Alexei Ledenev Date: Tue, 24 Nov 2026 15:06:45 +0200 Subject: [PATCH 8/9] fix(request): advise a push that names the remote and the branch Review: choosing between git push and git push -u from the upstream config was wrong for a renamed upstream and rewrote a fork's pull upstream. On a head mismatch the next line is now git push HEAD:, which works whatever upstream Git records and changes no configuration. --- docs/commands.md | 2 +- internal/history/github/sender.go | 32 ++++++++++++------------ internal/history/github/sender_test.go | 34 +++++++++++++++++++------- 3 files changed, 41 insertions(+), 27 deletions(-) diff --git a/docs/commands.md b/docs/commands.md index 4e3eb60f..a20a7246 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -135,7 +135,7 @@ Only an error whose `next` is `archfit request` joins the request: an error of a A use past the surface asks one question: should its package be part of the surface? The printed request shows it on a `question:` line; the App asks the owner to declare the package `public` or `model`, or to reject the request. -With a GitHub remote, `archfit request` posts `/archfit request [--expires DATE]` as a comment on the one open pull request for the current branch. The target repository is `origin`, or a configured GitHub `upstream` for a fork. The head uses the push remote's owner, falling back to the `origin` owner. Several matching pull requests means nothing is sent: the error names their numbers. A detached HEAD names no pull request: the error says so. When Git keeps no remote-tracking ref for the branch, as in a clone made with `--single-branch`, the request looks for the pull request by the branch's name on the push remote. It posts only when that pull request's head is the current commit; otherwise it names both commits and sends nothing, with `next: git push`, or `next: git push -u HEAD` when Git records no upstream for the branch. When the branch is not on GitHub at all, the error says the branch has no upstream branch, with `next: git push -u HEAD`. +With a GitHub remote, `archfit request` posts `/archfit request [--expires DATE]` as a comment on the one open pull request for the current branch. The target repository is `origin`, or a configured GitHub `upstream` for a fork. The head uses the push remote's owner, falling back to the `origin` owner. Several matching pull requests means nothing is sent: the error names their numbers. A detached HEAD names no pull request: the error says so. When Git keeps no remote-tracking ref for the branch, as in a clone made with `--single-branch`, the request looks for the pull request by the branch's name on the push remote. It posts only when that pull request's head is the current commit; otherwise it names both commits and sends nothing, with `next: git push HEAD:`. When the branch is not on GitHub at all, the error says the branch has no upstream branch, with `next: git push -u HEAD`. Without a pull request, only a request from `archfit can` opens an issue. Its body holds the request line and the `can` record; the App marks the numbers "as reported" until a pull request confirms them. With `check` output, nothing is opened: `no open pull request for :` and `next: open a pull request first`. diff --git a/internal/history/github/sender.go b/internal/history/github/sender.go index 5fb6c9d9..5b8ed7c0 100644 --- a/internal/history/github/sender.go +++ b/internal/history/github/sender.go @@ -133,8 +133,9 @@ type guess struct { pushRepo, branch string // notPushed is the answer when the branch is not on the push remote. notPushed error - // push is the command that sends HEAD to the pull request: `git push` - // when Git records the branch's upstream, else it must also set it. + // push is the command that sends HEAD to the pull request's branch. It + // names the remote and the branch, so it works whatever upstream Git + // records and changes no configuration. push string } @@ -192,19 +193,17 @@ var ( errNotFound = notSent("GitHub returned HTTP 404; nothing sent") errDetached = notSent("HEAD is not on a branch, so archfit cannot find its pull request; nothing sent\nnext: switch to the branch of the pull request") remoteName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) + branchName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._/-]*$`) ) // noUpstream names the push remote in the command only when the name is safe // to paste into a shell. func noUpstream(remote string) error { - return notSent("this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: " + pushUpstream(remote)) -} - -func pushUpstream(remote string) string { + next := "push the branch with -u to its remote" if remoteName.MatchString(remote) { - return "git push -u " + remote + " HEAD" + next = "git push -u " + remote + " HEAD" } - return "push the branch with -u to its remote" + return notSent("this branch has no upstream branch, so archfit cannot find its pull request; nothing sent\nnext: " + next) } // transportCause is the first line of the network error under err, never the @@ -381,13 +380,13 @@ func (s *Sender) repository(ctx context.Context) (target, error) { if code != 0 || pushRepo == "" { return target{repo: repo, noHead: noUpstream(pushRemote)}, nil } - name, recorded, err := s.pushedName(ctx, branch, pushRemote) + name, err := s.pushedName(ctx, branch, pushRemote) if err != nil { return target{}, err } - push := pushUpstream(pushRemote) - if recorded { - push = "git push" + push := "push this commit to the branch of the pull request" + if remoteName.MatchString(pushRemote) && branchName.MatchString(name) { + push = "git push " + pushRemote + " HEAD:" + name } owner, _, _ := strings.Cut(pushRepo, "/") return target{repo: repo, head: owner + ":" + name, @@ -407,17 +406,16 @@ func (s *Sender) repository(ctx context.Context) (target, error) { // pushedName is the branch's name on the push remote: the merge ref that // `git push -u` records, when it records it for that remote, else the local // name. A merge ref of another remote is never paired with the push owner. -// recorded says whether Git records that upstream. -func (s *Sender) pushedName(ctx context.Context, branch, pushRemote string) (name string, recorded bool, err error) { +func (s *Sender) pushedName(ctx context.Context, branch, pushRemote string) (string, error) { remote, _, err := s.git(ctx, "config", "--get", "branch."+branch+".remote") if err != nil || remote != pushRemote { - return branch, false, err + return branch, err } merge, _, err := s.git(ctx, "config", "--get", "branch."+branch+".merge") if name, ok := strings.CutPrefix(merge, "refs/heads/"); err == nil && ok && name != "" { - return name, true, nil + return name, nil } - return branch, false, err + return branch, err } // githubRepository accepts GitHub HTTPS, SSH and scp-style clone URLs. Reject diff --git a/internal/history/github/sender_test.go b/internal/history/github/sender_test.go index 41689c5f..a4049dea 100644 --- a/internal/history/github/sender_test.go +++ b/internal/history/github/sender_test.go @@ -304,11 +304,23 @@ func TestUntrackedBranchFindsItsPullRequest(t *testing.T) { atOtherCommit = "pull request #431 is at 1111111, this checkout is at 2222222; nothing sent\nnext: " ) untracked := map[string]toolrun.Output{upstreamCommand: {ExitCode: 128}} - recorded := map[string]toolrun.Output{ - upstreamCommand: {ExitCode: 128}, - branchRemote: {Stdout: []byte("origin\n")}, - branchMerge: {Stdout: []byte("refs/heads/feature\n")}, + recorded := func(remote, merge string, more map[string]toolrun.Output) map[string]toolrun.Output { + out := map[string]toolrun.Output{ + upstreamCommand: {ExitCode: 128}, + branchRemote: {Stdout: []byte(remote + "\n")}, + branchMerge: {Stdout: []byte(merge + "\n")}, + } + for key, value := range more { + out[key] = value + } + return out } + renamed := recorded("origin", "refs/heads/feature-x", nil) + unsafeName := recorded("origin", "refs/heads/$(touch x)", nil) + forkPullUpstream := recorded("upstream", "refs/heads/feature", map[string]toolrun.Output{ + pushRemoteCommand: {Stdout: []byte("fork\n")}, + forkPushURL: {Stdout: []byte("git@github.com:worker/shop.git\n")}, + }) forkPush := map[string]toolrun.Output{ upstreamCommand: {ExitCode: 128}, pushRemoteCommand: {Stdout: []byte("fork\n")}, @@ -326,12 +338,16 @@ func TestUntrackedBranchFindsItsPullRequest(t *testing.T) { }{ {"its pull request at HEAD gets the comment", untracked, false, originHead, `[{"number":431,"head":{"sha":"` + localSHA + `"}}]`, 0, "", commentsPath, ""}, - {"a pull request at another commit gets nothing; push sets the upstream", untracked, false, originHead, - otherCommit, 0, "", "", atOtherCommit + "git push -u origin HEAD"}, - {"a recorded upstream only needs a push", recorded, false, originHead, - otherCommit, 0, "", "", atOtherCommit + "git push"}, + {"a pull request at another commit gets nothing", untracked, false, originHead, + otherCommit, 0, "", "", atOtherCommit + "git push origin HEAD:feature"}, + {"the push names a recorded upstream of another name", renamed, false, "acme:feature-x", + otherCommit, 0, "", "", atOtherCommit + "git push origin HEAD:feature-x"}, + {"the push to a fork keeps the pull upstream", forkPullUpstream, false, forkHead, + otherCommit, 0, "", "", atOtherCommit + "git push fork HEAD:feature"}, + {"a branch name unsafe to paste is described", unsafeName, false, "acme:$(touch x)", + otherCommit, 0, "", "", atOtherCommit + "push this commit to the branch of the pull request"}, {"a can answer also needs HEAD", untracked, true, originHead, - otherCommit, 0, "", "", atOtherCommit + "git push -u origin HEAD"}, + otherCommit, 0, "", "", atOtherCommit + "git push origin HEAD:feature"}, {"not on GitHub: no upstream", untracked, false, originHead, "[]", http.StatusNotFound, "/repos/acme/shop/branches/feature", "", noUpstream + "origin HEAD"}, {"not on the fork: no upstream", forkPush, false, forkHead, "[]", From 72b673d22dcc45e367131c27995f6cff0b8bfee9 Mon Sep 17 00:00:00 2001 From: Alexei Ledenev Date: Tue, 24 Nov 2026 15:12:45 +0200 Subject: [PATCH 9/9] fix(request): push to the full branch ref in the hint Review: a short destination is ambiguous when the remote has a tag of the same name, so the hint now names refs/heads/. --- docs/commands.md | 2 +- internal/history/github/sender.go | 3 ++- internal/history/github/sender_test.go | 8 ++++---- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/commands.md b/docs/commands.md index a20a7246..0b1b4ffb 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -135,7 +135,7 @@ Only an error whose `next` is `archfit request` joins the request: an error of a A use past the surface asks one question: should its package be part of the surface? The printed request shows it on a `question:` line; the App asks the owner to declare the package `public` or `model`, or to reject the request. -With a GitHub remote, `archfit request` posts `/archfit request [--expires DATE]` as a comment on the one open pull request for the current branch. The target repository is `origin`, or a configured GitHub `upstream` for a fork. The head uses the push remote's owner, falling back to the `origin` owner. Several matching pull requests means nothing is sent: the error names their numbers. A detached HEAD names no pull request: the error says so. When Git keeps no remote-tracking ref for the branch, as in a clone made with `--single-branch`, the request looks for the pull request by the branch's name on the push remote. It posts only when that pull request's head is the current commit; otherwise it names both commits and sends nothing, with `next: git push HEAD:`. When the branch is not on GitHub at all, the error says the branch has no upstream branch, with `next: git push -u HEAD`. +With a GitHub remote, `archfit request` posts `/archfit request [--expires DATE]` as a comment on the one open pull request for the current branch. The target repository is `origin`, or a configured GitHub `upstream` for a fork. The head uses the push remote's owner, falling back to the `origin` owner. Several matching pull requests means nothing is sent: the error names their numbers. A detached HEAD names no pull request: the error says so. When Git keeps no remote-tracking ref for the branch, as in a clone made with `--single-branch`, the request looks for the pull request by the branch's name on the push remote. It posts only when that pull request's head is the current commit; otherwise it names both commits and sends nothing, with `next: git push HEAD:refs/heads/`. When the branch is not on GitHub at all, the error says the branch has no upstream branch, with `next: git push -u HEAD`. Without a pull request, only a request from `archfit can` opens an issue. Its body holds the request line and the `can` record; the App marks the numbers "as reported" until a pull request confirms them. With `check` output, nothing is opened: `no open pull request for :` and `next: open a pull request first`. diff --git a/internal/history/github/sender.go b/internal/history/github/sender.go index 5b8ed7c0..5f797be7 100644 --- a/internal/history/github/sender.go +++ b/internal/history/github/sender.go @@ -386,7 +386,8 @@ func (s *Sender) repository(ctx context.Context) (target, error) { } push := "push this commit to the branch of the pull request" if remoteName.MatchString(pushRemote) && branchName.MatchString(name) { - push = "git push " + pushRemote + " HEAD:" + name + // A full ref: a short name is ambiguous when a tag has it too. + push = "git push " + pushRemote + " HEAD:refs/heads/" + name } owner, _, _ := strings.Cut(pushRepo, "/") return target{repo: repo, head: owner + ":" + name, diff --git a/internal/history/github/sender_test.go b/internal/history/github/sender_test.go index a4049dea..0da33fc0 100644 --- a/internal/history/github/sender_test.go +++ b/internal/history/github/sender_test.go @@ -339,15 +339,15 @@ func TestUntrackedBranchFindsItsPullRequest(t *testing.T) { {"its pull request at HEAD gets the comment", untracked, false, originHead, `[{"number":431,"head":{"sha":"` + localSHA + `"}}]`, 0, "", commentsPath, ""}, {"a pull request at another commit gets nothing", untracked, false, originHead, - otherCommit, 0, "", "", atOtherCommit + "git push origin HEAD:feature"}, + otherCommit, 0, "", "", atOtherCommit + "git push origin HEAD:refs/heads/feature"}, {"the push names a recorded upstream of another name", renamed, false, "acme:feature-x", - otherCommit, 0, "", "", atOtherCommit + "git push origin HEAD:feature-x"}, + otherCommit, 0, "", "", atOtherCommit + "git push origin HEAD:refs/heads/feature-x"}, {"the push to a fork keeps the pull upstream", forkPullUpstream, false, forkHead, - otherCommit, 0, "", "", atOtherCommit + "git push fork HEAD:feature"}, + otherCommit, 0, "", "", atOtherCommit + "git push fork HEAD:refs/heads/feature"}, {"a branch name unsafe to paste is described", unsafeName, false, "acme:$(touch x)", otherCommit, 0, "", "", atOtherCommit + "push this commit to the branch of the pull request"}, {"a can answer also needs HEAD", untracked, true, originHead, - otherCommit, 0, "", "", atOtherCommit + "git push origin HEAD:feature"}, + otherCommit, 0, "", "", atOtherCommit + "git push origin HEAD:refs/heads/feature"}, {"not on GitHub: no upstream", untracked, false, originHead, "[]", http.StatusNotFound, "/repos/acme/shop/branches/feature", "", noUpstream + "origin HEAD"}, {"not on the fork: no upstream", forkPush, false, forkHead, "[]",