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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ History before 0.9.0 is in [docs/archived/CHANGELOG-v0-v5.md](docs/archived/CHAN
## Unreleased

- Add `archfit setup` to write the first policy and pin the Action, then open an advisory setup pull request.
- `archfit setup` names the changes to show an owner, says what it commits and pushes before the commit, explains a `# candidate` pin in the pull request body, and no longer prints a pin line it cannot act on.

## v0.9.0

Expand Down
10 changes: 7 additions & 3 deletions cmd/archfit/setup_command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"testing"
Expand Down Expand Up @@ -241,7 +242,7 @@ func TestSetupResumesPublishedBranchWithoutMutations(t *testing.T) { //nolint:go

func TestSetupFirstPublication(t *testing.T) { //nolint:gocyclo // the process boundary enumerates each external response
old := version
version = "v0.10.0"
version = setupRelease
t.Cleanup(func() { version = old })
for _, tc := range []struct {
name string
Expand Down Expand Up @@ -346,11 +347,14 @@ func TestSetupFirstPublication(t *testing.T) { //nolint:gocyclo // the process b
t.Fatal(out)
}
}
if out := run(); !strings.Contains(out, "opened setup pull request #7") {
announce := regexp.MustCompile(`(?m)^check: .*\nsetup commits (\S+, )*\.github/workflows/archfit\.yaml(, \S+)* on archfit/setup and pushes the branch\n`)
if out := run(); !strings.Contains(out, "opened setup pull request #7") || !announce.MatchString(out) ||
!strings.Contains(out, "committed as Setup Author <author@example.invalid>") || strings.Contains(out, "add --no-hooks") {
t.Fatal(out)
}
body, err := os.ReadFile(filepath.Join(dir, ".archfit-cache/setup-pull-request.md")) //nolint:gosec // dir is a test fixture
if err != nil || !strings.Contains(string(body), "## Last 30 merged pull requests\n\n1 passed, 0 needed an owner, 1 to show an owner.") {
root := strings.TrimSpace(gitOutput(t, dir, "rev-list", "--max-parents=0", "--abbrev-commit", "--abbrev=7", headRef))
if err != nil || !strings.Contains(string(body), "## Last 30 merged pull requests\n\n1 passed, 0 needed an owner, 1 to show an owner ("+root+": unknown).") {
t.Fatalf("missing replay in PR body: %s, %v", body, err)
}
if words := testutil.StoryNotUsedIn(string(body)); len(words) > 0 {
Expand Down
18 changes: 17 additions & 1 deletion cmd/archfit/setup_files.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,16 @@ func (f setupFiles) ValidPolicy(data []byte) (valid, required bool) {
return err == nil, err == nil && policy.Gate == policyfile.GateRequired
}

func (f setupFiles) PinNote() string { return doctorPin(f.co.root, version) }
// PinNote compares the local engine with the workflow pin. Setup leaves out
// "cannot tell": nothing in setup changes it, and its causes are a candidate
// pin setup wrote itself, a development build, or a workflow without a version
// comment. doctor still reports it.
func (f setupFiles) PinNote() string {
if note := doctorPin(f.co.root, version); note != unknownWorkflowPin {
return note
}
return ""
}

func (f setupFiles) Exceptions() ([]string, error) {
data, _, err := f.co.policyAt("")
Expand Down Expand Up @@ -222,6 +231,13 @@ func (f setupFiles) Paths() []string {
return paths
}

func (f setupFiles) HookPaths() []string {
if f.noHooks {
return nil
}
return []string{harnessConfigFile(harnessClaude), harnessConfigFile(harnessCodex)}
}

func setupUsesAction(data []byte) bool {
var workflow struct {
Jobs map[string]struct {
Expand Down
6 changes: 5 additions & 1 deletion cmd/archfit/setup_wiring.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@ func setupDependencies(deps *appDeps, dir string, noHooks bool) (setup.Dependenc
svc := co.replay(&local)
svc.History = replayHistory{co: co, ref: setupgit.OriginRef(branch), noLabels: true}
r, err := svc.Run(ctx, 30)
return setup.ReplaySummary{Read: r.Read, Passed: r.Passed, NeededOwner: r.Asked, ToShowOwner: r.Look}, err
summary := setup.ReplaySummary{Read: r.Read, Passed: r.Passed, NeededOwner: r.Asked, ToShowOwner: r.Look}
for _, l := range r.LookAt {
summary.ToShow = append(summary.ToShow, l.Name+": "+l.Status)
}
return summary, err
},
Init: func(ctx context.Context) (string, error) {
return runInit(ctx, &local, co, noHooks, true)
Expand Down
44 changes: 44 additions & 0 deletions cmd/archfit/setup_workflow_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,47 @@ func TestSetupPathReadFailureSuggestsRegularFile(t *testing.T) {
t.Fatalf("next %q error %v", next, err)
}
}

func TestSetupHookPathsFollowNoHooks(t *testing.T) {
hooks := []string{harnessConfigFile(harnessClaude), harnessConfigFile(harnessCodex)}
if got := (setupFiles{workflow: fixtureSetupWorkflow}).HookPaths(); !slices.Equal(got, hooks) {
t.Errorf("HookPaths() = %v, want %v", got, hooks)
}
if got := (setupFiles{workflow: fixtureSetupWorkflow, noHooks: true}).HookPaths(); got != nil {
t.Errorf("HookPaths() with --no-hooks = %v, want none", got)
}
}

// TestSetupPinNoteLeavesOutCannotTell: setup prints the pin line only when it
// can compare; a candidate pin is "cannot tell", which only doctor reports.
// setupRelease is the engine version these setup tests pin.
const setupRelease = "v0.10.0"

func TestSetupPinNoteLeavesOutCannotTell(t *testing.T) {
old := version
version = setupRelease
t.Cleanup(func() { version = old })
sha := strings.Repeat("b", 40)
for _, tc := range []struct {
name, comment, want string
}{
{"candidate", "candidate", ""},
{"release", setupRelease, "the local engine matches the workflow pin"},
{"other release", "v0.9.0", "the local engine does not match the workflow pin (v0.10.0 vs v0.9.0)"},
} {
t.Run(tc.name, func(t *testing.T) {
root := t.TempDir()
path := filepath.Join(root, fixtureSetupWorkflow)
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(setupWorkflow("main", tc.comment, sha)), 0o600); err != nil {
t.Fatal(err)
}
f := setupFiles{co: checkout{root: root}, workflow: fixtureSetupWorkflow}
if got := f.PinNote(); got != tc.want {
t.Errorf("PinNote() = %q, want %q", got, tc.want)
}
})
}
}
9 changes: 8 additions & 1 deletion docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -238,12 +238,19 @@ Use `--no-hooks` to skip Claude Code and Codex hooks, or `-C DIR` to select a ch
| Advisory checks on | The default branch has the policy and an Archfit workflow. | Open the setup page: an owner approves the first policy there, then makes the check required. |
| Required checks on | The same, and the policy has `gate: required`. | Check that a branch ruleset requires `archfit/gate`: without it, a fail does not block a merge. |

After writing a new policy, setup shows how it would judge up to 30 recent first-parent changes. It also includes the counts in the first setup pull request body. Replay uses the local remote-tracking default branch, does not fetch PR labels or start CI, and stops after 60 seconds. If the local ref is unavailable, run `archfit replay` later.
After writing a new policy, setup shows how it would judge up to 30 recent first-parent changes. It also includes the counts in the first setup pull request body. Replay uses the local remote-tracking default branch, does not fetch pull request labels or start CI, and stops after 60 seconds. If the local ref is unavailable, run `archfit replay` later.
The replay line names up to three of the changes to show an owner, newest first, each with the status an owner would see on it, for example `1 to show an owner (#1: unknown)`.
Setup asks GitHub for no labels, so it takes the pull request number from the commit subject (`(#12)` or `Merge pull request #12`), or else names the short commit id.

Before a commit, setup runs the check against the remote default branch. A `fail` does not stop setup.
An `unknown` stops setup before the commit and shows the check's next step.
Then setup prints the files it commits on `archfit/setup` and says that it pushes the branch. It does not ask first.
The first run, which writes the policy, also says that the next run commits the Claude Code and Codex hook files.
To leave them out, run that next `archfit setup` with `--no-hooks`: once they are committed on `archfit/setup`, `--no-hooks` stops until you delete the branch.
Setup commits only changed setup paths, but includes any existing edits in those paths.
Review the pull request before merging.
A candidate build, which pins the Action by commit, adds one sentence to the pull request body that explains its `# candidate` pin.
Setup says whether the local engine matches the workflow pin only when it can tell; [`doctor`](#doctor) also reports when it cannot.

SSH pushes use the SSH key and do not require the `gh` `workflow` scope.
When `gh` does not report classic scopes, setup attempts the push and reports a permission error if Git rejects it.
Expand Down
59 changes: 50 additions & 9 deletions internal/application/replay/replay.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,20 @@ package replay
import (
"context"
"fmt"
"regexp"
"strconv"

"github.com/coupling-dev/archfit/internal/model/result"
)

// maxExamples is how many changes that would ask the result names.
// maxExamples is how many changes of each named class the result names.
const maxExamples = 3

// subjectNumber finds the pull request number GitHub writes into the subject
// of a squash merge, "Title (#12)", or of a merge commit, "Merge pull request
// #12 from ...".
var subjectNumber = regexp.MustCompile(`\(#([0-9]+)\)\s*$|^Merge pull request #([0-9]+)\b`)

// Change is one first-parent commit of the default branch.
type Change struct {
// Commit is the full commit id.
Expand All @@ -64,11 +71,26 @@ func (c Change) Label() string {
if c.PR > 0 {
return fmt.Sprintf("#%d %s", c.PR, c.Title)
}
short := c.Commit
if len(short) > 7 {
short = short[:7]
return c.short() + " " + c.Subject
}

// Name names the change in a list: "#12", the number GitHub wrote into the
// subject when no pull request is known, or else the short commit id.
func (c Change) Name() string {
if c.PR > 0 {
return "#" + strconv.Itoa(c.PR)
}
if m := subjectNumber.FindStringSubmatch(c.Subject); m != nil {
return "#" + m[1] + m[2]
}
return c.short()
}

func (c Change) short() string {
if len(c.Commit) > 7 {
return c.Commit[:7]
}
return short + " " + c.Subject
return c.Commit
}

// Source is the history a replay reads.
Expand Down Expand Up @@ -111,6 +133,15 @@ type Example struct {
What string
}

// Look is a change to look at first.
type Look struct {
// Name is Change.Name.
Name string
// Status is what an owner would see on it: fail, waiting or unknown.
// A change with no parent, or a check that could not run, is unknown.
Status string
}

// Result is what a replay found.
type Result struct {
// Source is the branch the changes were read from.
Expand All @@ -123,6 +154,8 @@ type Result struct {
Passed, Asked, Look int
// Examples are up to three of the changes that would ask, newest first.
Examples []Example
// LookAt are up to three of the changes to look at first, newest first.
LookAt []Look
// Stopped is true when the context ended before every change was read.
Stopped bool
// Incomplete is true when the clone is shallow and the history it holds
Expand Down Expand Up @@ -165,6 +198,9 @@ func (s Service) Run(ctx context.Context, n int) (Result, error) {
}
default:
res.Look++
if len(res.LookAt) < maxExamples {
res.LookAt = append(res.LookAt, Look{Name: c.Name(), Status: what})
}
}
}
return res, nil
Expand All @@ -178,14 +214,16 @@ const (
classAsked
)

// judge classifies one change. what is the first error that asks an owner.
// judge classifies one change. what is the first error that asks an owner,
// or the status of a change to look at.
func (s Service) judge(ctx context.Context, c Change) (cl class, what string, err error) {
unknown := string(result.StatusUnknown)
if c.Parent == "" {
return classLook, "", nil
return classLook, unknown, nil
}
r, err := s.Checker.Check(ctx, c)
if err != nil {
return classLook, "", err
return classLook, unknown, err
}
switch r.Status {
case result.StatusPass:
Expand All @@ -197,7 +235,10 @@ func (s Service) judge(ctx context.Context, c Change) (cl class, what string, er
}
}
}
return classLook, "", nil
if r.Status == "" {
return classLook, unknown, nil
}
return classLook, string(r.Status), nil
}

// linear reports whether the changes hold no merge commit.
Expand Down
50 changes: 50 additions & 0 deletions internal/application/replay/replay_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"errors"
"slices"
"testing"
"time"

Expand Down Expand Up @@ -274,3 +275,52 @@ func TestRunStopsWhenTheContextEndsInTheHistory(t *testing.T) {
t.Errorf("got %+v, %v; want a stopped result with nothing read", got, err)
}
}

func TestRunNamesUpToThreeChangesToLookAt(t *testing.T) {
fixOnly := result.Result{Status: result.StatusFail, Errors: []result.Error{{What: "x", Next: result.Next{Kind: result.NextFix}}}}
changes := []replay.Change{
{Commit: "c1", Parent: "p", PR: 12},
{Commit: "c2", Parent: "p", Subject: "Add billing (#11)"},
{Commit: "c3", Parent: "p", Subject: "Merge pull request #9 from a/b", Merge: true},
{Commit: "c4", Parent: "p", PR: 8},
{Commit: "c5abcdef01"},
}
svc := replay.Service{
History: &history{src: replay.Source{Changes: changes}},
Checker: &checker{
results: map[string]result.Result{"c1": fixOnly, "c3": {Status: result.StatusWaiting}, "c4": {}},
errs: map[string]error{"c2": errors.New("git worktree add failed")},
},
}
got, err := svc.Run(context.Background(), 5)
if err != nil {
t.Fatal(err)
}
want := []replay.Look{{Name: "#12", Status: "fail"}, {Name: "#11", Status: "unknown"}, {Name: "#9", Status: "waiting"}}
if got.Look != 5 || !slices.Equal(got.LookAt, want) {
t.Errorf("got %d to look at, named %+v; want 5, named %+v", got.Look, got.LookAt, want)
}
}

func TestChangeName(t *testing.T) {
const fullCommit = "abcdef0123"
cases := []struct {
name string
c replay.Change
want string
}{
{"pull request from GitHub", replay.Change{Commit: fullCommit, PR: 7, Subject: "Fix (#3)"}, "#7"},
{"squash subject", replay.Change{Commit: fullCommit, Subject: "Add the tc shaper (#431)"}, "#431"},
{"merge subject", replay.Change{Commit: fullCommit, Subject: "Merge pull request #12 from a/feature"}, "#12"},
{"number inside the subject", replay.Change{Commit: fullCommit, Subject: "Revert (#5) and more"}, "abcdef0"},
{"no number", replay.Change{Commit: fullCommit, Subject: "Initial commit"}, "abcdef0"},
{"short commit", replay.Change{Commit: "abc"}, "abc"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := tc.c.Name(); got != tc.want {
t.Errorf("Name() = %q, want %q", got, tc.want)
}
})
}
}
Loading