# Org labels, milestones and cross-repository closes: implementation plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Goal:** Labels and milestones an org defines once for every repository under it, and `Closes owner/name#N` acting on another repository the actor can write to. Closes #203. **Architecture:** The existing `labels` and `milestones` tables gain an `org_id` beside a now-nullable `repo_id` (migration 0052), so `issue_labels` and the two `milestone_id` columns keep their ids. Store lookups take the `store.Repo` and match `repo_id = ? OR org_id = ?` for org-owned repositories. Seven `org label` / `org milestone` control commands manage org rows; the web gets two read pages under `/{org}/-/`. The closing-keyword pattern in `commitrefs.go` accepts an `owner/name` prefix and acts when the actor holds write on the target. **Tech Stack:** Go, SQLite via modernc (hand-written SQL, no ORM), Go `html/template`, the control registry in `internal/control`, the e2e harness in `e2e/`. **Spec:** `docs/specs/2026-09-11-org-labels-milestones-closes-design.md` ## Global Constraints - Every capability lands as a control command first; the CLI, web and API dispatch into it. New commands need a `pass()` row in `cmd/gitbay/main.go` (a coverage test enforces this) and, if `ReadOnly`, a row in `readArgs` in `e2e/readonly_test.go`. - Hand-written SQL only. No ORM. Migrations are `internal/store/migrations/NNNN_name.up.sql` and `.down.sql`, embedded, run one per transaction. - Private repositories return not-found, never a denial that confirms a namespace. Org existence is public (`org show` answers anyone). - Never mention an assistant or model anywhere: commit messages, comments, docs. - Commit messages reference the issue: `Ref #203` on each task, `Closes #203` on the last. - Run locally: `go build ./... && go vet ./...` and the unit tests of the touched packages. Run at most the one e2e test you write (`go test ./e2e -run TestOrgLabels`); CI on bay1 runs the full suite. - Style: plain sentences in comments, no dramatic framing. Match the surrounding code. - Work on branch `org-scope`, which already holds the spec. One deviation from the spec's wording: the org pages get their own small templates (`orglabels.html`, `orgmilestones.html`) rather than reusing `labels.html` and `milestones.html`, whose every URL and field is a `repoPage`. Behaviour is as specified. --- ### Task 1: Migration 0052 and the scoped structs **Files:** - Create: `internal/store/migrations/0052_org_scope.up.sql` - Create: `internal/store/migrations/0052_org_scope.down.sql` - Modify: `internal/store/labels.go:1-10` (struct) - Modify: `internal/store/milestones.go:9-20` (struct) - Test: `internal/store/store_test.go` **Interfaces:** - Produces: `labels(id, repo_id NULL, org_id NULL, name, color)` and `milestones(id, repo_id NULL, org_id NULL, title, description, due_date, state, created_at)` with `CHECK ((repo_id IS NULL) <> (org_id IS NULL))` and partial unique indexes `labels_repo_name`, `labels_org_name`, `milestones_repo_title`, `milestones_org_title`. - Produces: `store.Label{Name, Color, Org bool, Issues}` and `store.Milestone{..., RepoID, OrgID, ...}`. - [ ] **Step 1: Write the failing migration test** Append to `internal/store/store_test.go`: ```go // Migration 0052 rebuilds labels and milestones with an org scope. The // rebuild renames the old tables; since SQLite 3.26 a rename rewrites the // children's foreign keys, so issue_labels and the milestone_id columns // would follow labels_old unless legacy_alter_table is on for the script. // This checks the ids, the memberships and the foreign keys all survive. func TestMigration0052KeepsMembershipsAndForeignKeys(t *testing.T) { s := open(t) if err := s.MigrateTo(51); err != nil { t.Fatal(err) } uid, err := s.CreateUser("alice", false) if err != nil { t.Fatal(err) } rid, err := s.CreateRepo("user", uid, "app", "public") if err != nil { t.Fatal(err) } iid, err := s.CreateIssue(rid, uid, "one", "", "md") if err != nil { t.Fatal(err) } if _, err := s.DB.Exec("INSERT INTO labels (repo_id, name, color) VALUES (?, 'bug', '#ff0000')", rid); err != nil { t.Fatal(err) } if _, err := s.DB.Exec("INSERT INTO issue_labels (issue_id, label_id) SELECT ?, id FROM labels WHERE name = 'bug'", iid); err != nil { t.Fatal(err) } if _, err := s.DB.Exec("INSERT INTO milestones (repo_id, title) VALUES (?, 'v1')", rid); err != nil { t.Fatal(err) } if _, err := s.DB.Exec("UPDATE issues SET milestone_id = (SELECT id FROM milestones WHERE title = 'v1') WHERE id = ?", iid); err != nil { t.Fatal(err) } if err := s.MigrateTo(52); err != nil { t.Fatal(err) } var n int if err := s.DB.QueryRow(`SELECT COUNT(*) FROM issue_labels il JOIN labels l ON l.id = il.label_id WHERE il.issue_id = ? AND l.name = 'bug' AND l.repo_id = ? AND l.org_id IS NULL`, iid, rid).Scan(&n); err != nil || n != 1 { t.Fatalf("label membership after 0052: %d, %v", n, err) } if err := s.DB.QueryRow(`SELECT COUNT(*) FROM issues i JOIN milestones m ON m.id = i.milestone_id WHERE i.id = ? AND m.title = 'v1' AND m.repo_id = ?`, iid, rid).Scan(&n); err != nil || n != 1 { t.Fatalf("milestone attachment after 0052: %d, %v", n, err) } rows, err := s.DB.Query("PRAGMA foreign_key_check") if err != nil { t.Fatal(err) } defer rows.Close() if rows.Next() { t.Fatal("foreign_key_check reported a violation after 0052") } // The scope CHECK holds: a row with neither or both scopes is refused. if _, err := s.DB.Exec("INSERT INTO labels (name) VALUES ('neither')"); err == nil { t.Fatal("label with no scope was accepted") } if _, err := s.DB.Exec("INSERT INTO labels (repo_id, org_id, name) VALUES (?, 1, 'both')", rid); err == nil { t.Fatal("label with both scopes was accepted") } // Down refuses while an org-scoped row exists, and works once it is gone. if _, err := s.DB.Exec("INSERT INTO orgs (name) VALUES ('acme')"); err != nil { t.Fatal(err) } if _, err := s.DB.Exec("INSERT INTO labels (org_id, name) VALUES ((SELECT id FROM orgs WHERE name = 'acme'), 'org-only')"); err != nil { t.Fatal(err) } if err := s.MigrateTo(51); err == nil { t.Fatal("down migration accepted an org-scoped label") } if _, err := s.DB.Exec("DELETE FROM labels WHERE org_id IS NOT NULL"); err != nil { t.Fatal(err) } if err := s.MigrateTo(51); err != nil { t.Fatalf("down migration: %v", err) } if err := s.DB.QueryRow(`SELECT COUNT(*) FROM issue_labels il JOIN labels l ON l.id = il.label_id WHERE il.issue_id = ?`, iid).Scan(&n); err != nil || n != 1 { t.Fatalf("label membership after down: %d, %v", n, err) } } ``` - [ ] **Step 2: Run it to verify it fails** Run: `go test ./internal/store/ -run TestMigration0052 -v` Expected: FAIL, "no such schema version 52". - [ ] **Step 3: Write the up migration** `internal/store/migrations/0052_org_scope.up.sql`: ```sql -- Labels and milestones scoped to a repository or to an org (#203). -- Exactly one of repo_id and org_id is set. Uniqueness is per scope, as -- two partial indexes; the app refuses a repo name the org already holds. -- -- Both tables have children (issue_labels, issues.milestone_id, -- merge_requests.milestone_id). Since SQLite 3.26 renaming a parent -- rewrites the children's foreign keys to follow it, which would bind them -- to the *_old tables. legacy_alter_table keeps the children naming labels -- and milestones, which the new tables then are. foreign_keys stays on: -- nothing references the *_old tables, so dropping them cascades nothing. PRAGMA legacy_alter_table = ON; ALTER TABLE labels RENAME TO labels_old; CREATE TABLE labels ( id INTEGER PRIMARY KEY, repo_id INTEGER REFERENCES repos(id) ON DELETE CASCADE, org_id INTEGER REFERENCES orgs(id) ON DELETE CASCADE, name TEXT NOT NULL, color TEXT NOT NULL DEFAULT '', CHECK ((repo_id IS NULL) <> (org_id IS NULL)) ); INSERT INTO labels (id, repo_id, name, color) SELECT id, repo_id, name, color FROM labels_old; DROP TABLE labels_old; CREATE UNIQUE INDEX labels_repo_name ON labels(repo_id, name) WHERE repo_id IS NOT NULL; CREATE UNIQUE INDEX labels_org_name ON labels(org_id, name) WHERE org_id IS NOT NULL; ALTER TABLE milestones RENAME TO milestones_old; CREATE TABLE milestones ( id INTEGER PRIMARY KEY, repo_id INTEGER REFERENCES repos(id) ON DELETE CASCADE, org_id INTEGER REFERENCES orgs(id) ON DELETE CASCADE, title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', due_date TEXT NOT NULL DEFAULT '', state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open','closed')), created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), CHECK ((repo_id IS NULL) <> (org_id IS NULL)) ); INSERT INTO milestones (id, repo_id, title, description, due_date, state, created_at) SELECT id, repo_id, title, description, due_date, state, created_at FROM milestones_old; DROP TABLE milestones_old; CREATE UNIQUE INDEX milestones_repo_title ON milestones(repo_id, title) WHERE repo_id IS NOT NULL; CREATE UNIQUE INDEX milestones_org_title ON milestones(org_id, title) WHERE org_id IS NOT NULL; PRAGMA legacy_alter_table = OFF; ``` - [ ] **Step 4: Write the down migration** `internal/store/migrations/0052_org_scope.down.sql`. The copy into a `NOT NULL repo_id` column fails on any org-scoped row, which is the refusal. ```sql -- Back to per-repository rows. An org-scoped row has no repository to go -- to; the NOT NULL on repo_id refuses the copy, which fails the migration. PRAGMA legacy_alter_table = ON; ALTER TABLE labels RENAME TO labels_old; CREATE TABLE labels ( id INTEGER PRIMARY KEY, repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE, name TEXT NOT NULL, color TEXT NOT NULL DEFAULT '', UNIQUE (repo_id, name) ); INSERT INTO labels (id, repo_id, name, color) SELECT id, repo_id, name, color FROM labels_old; DROP TABLE labels_old; ALTER TABLE milestones RENAME TO milestones_old; CREATE TABLE milestones ( id INTEGER PRIMARY KEY, repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE, title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', due_date TEXT NOT NULL DEFAULT '', state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open','closed')), created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), UNIQUE (repo_id, title) ); INSERT INTO milestones (id, repo_id, title, description, due_date, state, created_at) SELECT id, repo_id, title, description, due_date, state, created_at FROM milestones_old; DROP TABLE milestones_old; PRAGMA legacy_alter_table = OFF; ``` - [ ] **Step 5: Add the struct fields** In `internal/store/labels.go` replace the `Label` struct: ```go // Label is an issue label with its colour, "" when none was set (the web // then derives one from the name), and how many issues carry it. Org is // true for a label the repository sees through its org. type Label struct { Name string `json:"name"` Color string `json:"color,omitempty"` Org bool `json:"org,omitempty"` Issues int64 `json:"issues"` } ``` In `internal/store/milestones.go` add `OrgID int64 // set instead of RepoID for an org milestone` after `RepoID`. - [ ] **Step 6: Run the test to verify it passes** Run: `go test ./internal/store/ -run TestMigration0052 -v` Expected: PASS. Then `go build ./...` still compiles (only fields were added). - [ ] **Step 7: Commit** ```bash git add internal/store/migrations/0052_org_scope.up.sql internal/store/migrations/0052_org_scope.down.sql internal/store/labels.go internal/store/milestones.go internal/store/store_test.go git commit -m "store: migration 0052 scopes labels and milestones to a repo or an org Ref #203" ``` --- ### Task 2: Store: labels by scope, org labels, promote **Files:** - Modify: `internal/store/labels.go` - Modify: `internal/store/issues.go:297-346` (`LabelColors`, `SetIssueLabel`) - Create: `internal/store/scope.go` - Test: `internal/store/labels_test.go` (new) **Interfaces:** - Produces in `scope.go`: `var ErrOrgScoped = errors.New("held by the org")`; `func scopeClause(alias string, repo Repo) (string, []any)`; `func inClause(ids []int64) (string, []any)`. - Produces in `labels.go`: - `func (s *Store) ListLabels(repo Repo, readable []int64) ([]Label, error)` — org rows first then repo rows, each by name; `Issues` counts only issues in `readable`. - `func (s *Store) LabelByName(repo Repo, name string) (Label, error)` — `ErrNotFound` when neither scope has it. - `func (s *Store) SetLabel(repo Repo, name, color string) error` — `ErrOrgScoped` when the org holds the name. - `func (s *Store) DeleteLabel(repo Repo, name string) error` — `ErrOrgScoped` for an org row, `ErrNotFound` for none. - `func (s *Store) ListOrgLabels(orgID int64, readable []int64) ([]Label, error)` - `func (s *Store) SetOrgLabel(orgID int64, name, color string) (folded int, err error)` — promotes same-named repo labels under the org; `folded` is how many repositories were folded in. - `func (s *Store) DeleteOrgLabel(orgID int64, name string) error` — `ErrNotFound` when absent. - Produces in `issues.go`: `func (s *Store) LabelColors(repo Repo) (map[string]string, error)`; `func (s *Store) SetIssueLabel(repo Repo, issueID int64, name string, add bool) error` — add resolves the org row first, else creates the repo row. - Consumes: Task 1's schema. Note that every `ON CONFLICT (repo_id, name)` must name the partial index's predicate: `ON CONFLICT (repo_id, name) WHERE repo_id IS NOT NULL`. - [ ] **Step 1: Write the failing tests** `internal/store/labels_test.go`: ```go package store import ( "errors" "testing" ) // acmeFixture: org acme owned by alice with repos acme/core and // acme/site, an issue in each, and alice's own alice/app. type acmeFixture struct { s *Store alice int64 org int64 core, site Repo app Repo coreIssue int64 siteIssue int64 } func newAcme(t *testing.T) acmeFixture { t.Helper() s := open(t) if err := s.MigrateUp(); err != nil { t.Fatal(err) } var f acmeFixture f.s = s var err error if f.alice, err = s.CreateUser("alice", false); err != nil { t.Fatal(err) } if f.org, err = s.CreateOrg("acme", f.alice); err != nil { t.Fatal(err) } mk := func(kind string, owner int64, name string) Repo { id, err := s.CreateRepo(kind, owner, name, "public") if err != nil { t.Fatal(err) } r, err := s.RepoByID(id) if err != nil { t.Fatal(err) } return r } f.core = mk("org", f.org, "core") f.site = mk("org", f.org, "site") f.app = mk("user", f.alice, "app") if f.coreIssue, err = s.CreateIssue(f.core.ID, f.alice, "c1", "", "md"); err != nil { t.Fatal(err) } if f.siteIssue, err = s.CreateIssue(f.site.ID, f.alice, "s1", "", "md"); err != nil { t.Fatal(err) } return f } func (f acmeFixture) orgRepos() []int64 { return []int64{f.core.ID, f.site.ID} } func TestOrgLabelSeenByEveryOrgRepo(t *testing.T) { f := newAcme(t) if _, err := f.s.SetOrgLabel(f.org, "bug", "#ff0000"); err != nil { t.Fatal(err) } if err := f.s.SetLabel(f.site, "docs", ""); err != nil { t.Fatal(err) } // site sees the org's bug first, then its own docs; core sees only bug; // alice/app, user-owned, sees nothing. got, err := f.s.ListLabels(f.site, f.orgRepos()) if err != nil || len(got) != 2 || got[0].Name != "bug" || !got[0].Org || got[1].Name != "docs" || got[1].Org { t.Fatalf("site labels = %+v, %v", got, err) } if got, _ := f.s.ListLabels(f.core, f.orgRepos()); len(got) != 1 || got[0].Name != "bug" { t.Fatalf("core labels = %+v", got) } if got, _ := f.s.ListLabels(f.app, []int64{f.app.ID}); len(got) != 0 { t.Fatalf("app labels = %+v", got) } colors, _ := f.s.LabelColors(f.core) if colors["bug"] != "#ff0000" { t.Fatalf("core colours = %v", colors) } } func TestIssueLabelResolvesOrgRowFirst(t *testing.T) { f := newAcme(t) if _, err := f.s.SetOrgLabel(f.org, "bug", ""); err != nil { t.Fatal(err) } if err := f.s.SetIssueLabel(f.core, f.coreIssue, "bug", true); err != nil { t.Fatal(err) } if err := f.s.SetIssueLabel(f.site, f.siteIssue, "bug", true); err != nil { t.Fatal(err) } // One org row, no repo rows were created on the fly. var n int f.s.DB.QueryRow("SELECT COUNT(*) FROM labels WHERE name = 'bug'").Scan(&n) if n != 1 { t.Fatalf("labels named bug: %d, want 1", n) } // The count spans the org's readable repos. got, _ := f.s.ListOrgLabels(f.org, f.orgRepos()) if len(got) != 1 || got[0].Issues != 2 { t.Fatalf("org labels = %+v", got) } got, _ = f.s.ListOrgLabels(f.org, []int64{f.core.ID}) if got[0].Issues != 1 { t.Fatalf("org labels over core only = %+v", got) } // A label neither scope has is still created on the fly in the repo. if err := f.s.SetIssueLabel(f.core, f.coreIssue, "adhoc", true); err != nil { t.Fatal(err) } if l, err := f.s.LabelByName(f.core, "adhoc"); err != nil || l.Org { t.Fatalf("adhoc = %+v, %v", l, err) } // Removing by name works for the org row too. if err := f.s.SetIssueLabel(f.core, f.coreIssue, "bug", false); err != nil { t.Fatal(err) } got, _ = f.s.ListOrgLabels(f.org, f.orgRepos()) if got[0].Issues != 1 { t.Fatalf("after detach: %+v", got) } } func TestRepoLabelRefusedWhenOrgHoldsName(t *testing.T) { f := newAcme(t) if _, err := f.s.SetOrgLabel(f.org, "bug", ""); err != nil { t.Fatal(err) } if err := f.s.SetLabel(f.core, "bug", "#00ff00"); !errors.Is(err, ErrOrgScoped) { t.Fatalf("SetLabel over org name: %v, want ErrOrgScoped", err) } if err := f.s.DeleteLabel(f.core, "bug"); !errors.Is(err, ErrOrgScoped) { t.Fatalf("DeleteLabel of org row: %v, want ErrOrgScoped", err) } if err := f.s.DeleteLabel(f.core, "nope"); !errors.Is(err, ErrNotFound) { t.Fatalf("DeleteLabel of nothing: %v, want ErrNotFound", err) } // A user-owned repo is unaffected by any org. if err := f.s.SetLabel(f.app, "bug", ""); err != nil { t.Fatal(err) } } func TestSetOrgLabelPromotesRepoLabels(t *testing.T) { f := newAcme(t) if err := f.s.SetIssueLabel(f.core, f.coreIssue, "bug", true); err != nil { t.Fatal(err) } if err := f.s.SetIssueLabel(f.site, f.siteIssue, "bug", true); err != nil { t.Fatal(err) } if err := f.s.SetLabel(f.app, "bug", "#123456"); err != nil { t.Fatal(err) } folded, err := f.s.SetOrgLabel(f.org, "bug", "#ff0000") if err != nil || folded != 2 { t.Fatalf("SetOrgLabel folded %d, %v; want 2", folded, err) } var n int f.s.DB.QueryRow("SELECT COUNT(*) FROM labels WHERE name = 'bug' AND org_id = ?", f.org).Scan(&n) if n != 1 { t.Fatalf("org rows named bug: %d", n) } f.s.DB.QueryRow("SELECT COUNT(*) FROM labels WHERE name = 'bug' AND repo_id IN (?, ?)", f.core.ID, f.site.ID).Scan(&n) if n != 0 { t.Fatalf("repo rows named bug left under the org: %d", n) } got, _ := f.s.ListOrgLabels(f.org, f.orgRepos()) if len(got) != 1 || got[0].Issues != 2 || got[0].Color != "#ff0000" { t.Fatalf("after promote: %+v", got) } // alice/app's own bug is another owner's and stays. if l, err := f.s.LabelByName(f.app, "bug"); err != nil || l.Color != "#123456" { t.Fatalf("app bug = %+v, %v", l, err) } // A second set only recolours. if folded, err := f.s.SetOrgLabel(f.org, "bug", "#0000ff"); err != nil || folded != 0 { t.Fatalf("second set folded %d, %v", folded, err) } if err := f.s.DeleteOrgLabel(f.org, "bug"); err != nil { t.Fatal(err) } if err := f.s.DeleteOrgLabel(f.org, "bug"); !errors.Is(err, ErrNotFound) { t.Fatalf("second delete: %v", err) } f.s.DB.QueryRow("SELECT COUNT(*) FROM issue_labels").Scan(&n) if n != 0 { t.Fatalf("memberships after org delete: %d", n) } } ``` - [ ] **Step 2: Run them to verify they fail** Run: `go test ./internal/store/ -run 'OrgLabel|IssueLabelResolves|RepoLabelRefused' -v` Expected: build failure, `SetOrgLabel`, `ListOrgLabels`, `LabelByName`, `DeleteOrgLabel`, `ErrOrgScoped` undefined. - [ ] **Step 3: Write `scope.go`** ```go package store import ( "errors" "strings" ) // ErrOrgScoped is returned when a repository-level write names a label or // milestone its org holds; the org commands manage those. var ErrOrgScoped = errors.New("held by the org") // scopeClause selects the label or milestone rows a repository sees: its // own, and its org's when an org owns it. alias is the table alias in the // query. func scopeClause(alias string, repo Repo) (string, []any) { if repo.OwnerKind == "org" { return "(" + alias + ".repo_id = ? OR " + alias + ".org_id = ?)", []any{repo.ID, repo.OwnerID} } return alias + ".repo_id = ?", []any{repo.ID} } // inClause renders ids as a parenthesised placeholder list. An empty set // yields (NULL), which matches nothing. func inClause(ids []int64) (string, []any) { if len(ids) == 0 { return "(NULL)", nil } args := make([]any, len(ids)) for i, id := range ids { args[i] = id } return "(" + strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",") + ")", args } ``` - [ ] **Step 4: Rewrite `labels.go` below the struct** ```go // labelRows lists labels under where, with use counted over the issues of // the readable repositories only, so a private repository's issues do not // show in a count someone outside it can see. func (s *Store) labelRows(where string, args []any, readable []int64) ([]Label, error) { in, inArgs := inClause(readable) q := `SELECT l.name, l.color, l.org_id IS NOT NULL, (SELECT COUNT(*) FROM issue_labels il JOIN issues i ON i.id = il.issue_id WHERE il.label_id = l.id AND i.repo_id IN ` + in + `) FROM labels l WHERE ` + where + ` ORDER BY l.org_id IS NULL, l.name` rows, err := s.DB.Query(q, append(inArgs, args...)...) if err != nil { return nil, err } defer rows.Close() var out []Label for rows.Next() { var l Label if err := rows.Scan(&l.Name, &l.Color, &l.Org, &l.Issues); err != nil { return nil, err } out = append(out, l) } return out, rows.Err() } // ListLabels lists the labels a repository sees: its org's first, then its // own, each by name. func (s *Store) ListLabels(repo Repo, readable []int64) ([]Label, error) { where, args := scopeClause("l", repo) return s.labelRows(where, args, readable) } // ListOrgLabels lists an org's labels. func (s *Store) ListOrgLabels(orgID int64, readable []int64) ([]Label, error) { return s.labelRows("l.org_id = ?", []any{orgID}, readable) } // LabelByName resolves a name the way attaching does: the org's row when // the org has it, else the repository's. func (s *Store) LabelByName(repo Repo, name string) (Label, error) { where, args := scopeClause("l", repo) var l Label err := s.DB.QueryRow(`SELECT l.name, l.color, l.org_id IS NOT NULL FROM labels l WHERE `+where+` AND l.name = ? ORDER BY l.org_id IS NULL LIMIT 1`, append(args, name)...).Scan(&l.Name, &l.Color, &l.Org) if errors.Is(err, sql.ErrNoRows) { return l, ErrNotFound } return l, err } // orgHoldsLabel reports whether the repository's org has a label of that // name; always false for a user-owned repository. func orgHoldsLabel(q interface { QueryRow(string, ...any) *sql.Row }, repo Repo, name string) (bool, error) { if repo.OwnerKind != "org" { return false, nil } var n int err := q.QueryRow("SELECT COUNT(*) FROM labels WHERE org_id = ? AND name = ?", repo.OwnerID, name).Scan(&n) return n > 0, err } // SetLabel creates the repository's label or sets its colour. A name the // org holds is refused with ErrOrgScoped. func (s *Store) SetLabel(repo Repo, name, color string) error { if held, err := orgHoldsLabel(s.DB, repo, name); err != nil || held { if err != nil { return err } return ErrOrgScoped } _, err := s.DB.Exec(`INSERT INTO labels (repo_id, name, color) VALUES (?, ?, ?) ON CONFLICT (repo_id, name) WHERE repo_id IS NOT NULL DO UPDATE SET color = excluded.color`, repo.ID, name, color) return err } // DeleteLabel removes the repository's label and takes it off every issue. // An org's label is ErrOrgScoped; no label at all is ErrNotFound. func (s *Store) DeleteLabel(repo Repo, name string) error { res, err := s.DB.Exec("DELETE FROM labels WHERE repo_id = ? AND name = ?", repo.ID, name) if err != nil { return err } if n, _ := res.RowsAffected(); n > 0 { return nil } if held, err := orgHoldsLabel(s.DB, repo, name); err != nil || held { if err != nil { return err } return ErrOrgScoped } return ErrNotFound } // SetOrgLabel creates the org's label or sets its colour. Repositories // under the org that hold the name are folded in: their issues move to // the org's row and their rows go. folded is how many were. func (s *Store) SetOrgLabel(orgID int64, name, color string) (int, error) { tx, err := s.DB.Begin() if err != nil { return 0, err } defer tx.Rollback() if _, err := tx.Exec(`INSERT INTO labels (org_id, name, color) VALUES (?, ?, ?) ON CONFLICT (org_id, name) WHERE org_id IS NOT NULL DO UPDATE SET color = excluded.color`, orgID, name, color); err != nil { return 0, err } var orgRow int64 if err := tx.QueryRow("SELECT id FROM labels WHERE org_id = ? AND name = ?", orgID, name).Scan(&orgRow); err != nil { return 0, err } rows, err := tx.Query(`SELECT l.id FROM labels l JOIN repos r ON r.id = l.repo_id WHERE r.owner_kind = 'org' AND r.owner_id = ? AND l.name = ?`, orgID, name) if err != nil { return 0, err } var repoRows []int64 for rows.Next() { var id int64 if err := rows.Scan(&id); err != nil { rows.Close() return 0, err } repoRows = append(repoRows, id) } rows.Close() for _, id := range repoRows { // OR IGNORE: an issue cannot carry both today, but the primary key // makes the move safe if it ever did. if _, err := tx.Exec("UPDATE OR IGNORE issue_labels SET label_id = ? WHERE label_id = ?", orgRow, id); err != nil { return 0, err } if _, err := tx.Exec("DELETE FROM labels WHERE id = ?", id); err != nil { return 0, err } } return len(repoRows), tx.Commit() } // DeleteOrgLabel removes an org's label from the org and from every issue // under it. func (s *Store) DeleteOrgLabel(orgID int64, name string) error { res, err := s.DB.Exec("DELETE FROM labels WHERE org_id = ? AND name = ?", orgID, name) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { return ErrNotFound } return nil } ``` Add `"database/sql"` and `"errors"` to the imports of `labels.go`. - [ ] **Step 5: Update `LabelColors` and `SetIssueLabel` in `issues.go`** Replace both functions (lines 297-346): ```go // LabelColors returns the colours of the labels a repository sees, keyed // by name. Labels with no stored colour map to "". func (s *Store) LabelColors(repo Repo) (map[string]string, error) { where, args := scopeClause("l", repo) rows, err := s.DB.Query("SELECT l.name, l.color FROM labels l WHERE "+where, args...) if err != nil { return nil, err } defer rows.Close() out := map[string]string{} for rows.Next() { var name, color string if err := rows.Scan(&name, &color); err != nil { return nil, err } out[name] = color } return out, rows.Err() } // SetIssueLabel attaches (add) or detaches a label by name. Adding // resolves the org's row when the org has the name, else the repository's, // creating that on first use. func (s *Store) SetIssueLabel(repo Repo, issueID int64, name string, add bool) error { tx, err := s.DB.Begin() if err != nil { return err } defer tx.Rollback() where, args := scopeClause("l", repo) if add { if held, err := orgHoldsLabel(tx, repo, name); err != nil { return err } else if !held { if _, err := tx.Exec(`INSERT INTO labels (repo_id, name) VALUES (?, ?) ON CONFLICT (repo_id, name) WHERE repo_id IS NOT NULL DO NOTHING`, repo.ID, name); err != nil { return err } } if _, err := tx.Exec(`INSERT INTO issue_labels (issue_id, label_id) SELECT ?, l.id FROM labels l WHERE `+where+` AND l.name = ? ORDER BY l.org_id IS NULL LIMIT 1 ON CONFLICT DO NOTHING`, append(append([]any{issueID}, args...), name)...); err != nil { return err } } else { res, err := tx.Exec(`DELETE FROM issue_labels WHERE issue_id = ? AND label_id IN (SELECT l.id FROM labels l WHERE `+where+` AND l.name = ?)`, append(append([]any{issueID}, args...), name)...) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { return fmt.Errorf("label %q: %w", name, ErrNotFound) } } return tx.Commit() } ``` SQLite needs a `WHERE` before `ON CONFLICT` after an `INSERT ... SELECT` to disambiguate; the `SELECT` above has one, so the upsert parses. If the parser rejects `ORDER BY ... LIMIT` before `ON CONFLICT`, wrap the select: `SELECT * FROM (SELECT ?, l.id FROM labels l WHERE ... ORDER BY l.org_id IS NULL LIMIT 1) WHERE true ON CONFLICT DO NOTHING`. - [ ] **Step 6: Run the store tests** Run: `go test ./internal/store/` Expected: the four new tests PASS; existing store tests still PASS. `go build ./...` now fails in `control` and `httpd` on the changed signatures, which Task 4 fixes. Do not fix them here. - [ ] **Step 7: Commit** ```bash git add internal/store/scope.go internal/store/labels.go internal/store/issues.go internal/store/labels_test.go git commit -m "store: labels resolve through the repository's org Ref #203" ``` --- ### Task 3: Store: milestones by scope, org milestones, promote **Files:** - Modify: `internal/store/milestones.go` - Test: `internal/store/milestones_test.go` (new) **Interfaces:** - Produces: - `func (s *Store) CreateMilestone(repo Repo, title, description, due string) (int64, error)` — `ErrOrgScoped` when the org holds the title; "already exists" error on a repo duplicate as today. - `func (s *Store) MilestoneByTitle(repo Repo, title string) (Milestone, error)` — org row first. - `func (s *Store) ListMilestones(repo Repo, state string, readable []int64) ([]Milestone, error)` — org rows first. - `func (s *Store) CreateOrgMilestone(orgID int64, title, description, due string) (id int64, folded int, err error)` - `func (s *Store) OrgMilestoneByTitle(orgID int64, title string) (Milestone, error)` - `func (s *Store) ListOrgMilestones(orgID int64, state string, readable []int64) ([]Milestone, error)` - `SetMilestoneState`, `SetIssueMilestone`, `SetMRMilestone` unchanged. - Consumes: `scopeClause`, `inClause`, `ErrOrgScoped` from Task 2; `Milestone.OrgID` from Task 1. - [ ] **Step 1: Write the failing tests** `internal/store/milestones_test.go`: ```go package store import ( "errors" "testing" ) func TestOrgMilestoneSpansRepos(t *testing.T) { f := newAcme(t) id, folded, err := f.s.CreateOrgMilestone(f.org, "v1", "first", "2027-01-01") if err != nil || folded != 0 || id == 0 { t.Fatalf("CreateOrgMilestone: %d, %d, %v", id, folded, err) } // Resolves from either repo, not from alice/app. m, err := f.s.MilestoneByTitle(f.core, "v1") if err != nil || m.OrgID != f.org || m.RepoID != 0 { t.Fatalf("core resolves v1 = %+v, %v", m, err) } if _, err := f.s.MilestoneByTitle(f.app, "v1"); !errors.Is(err, ErrNotFound) { t.Fatalf("app resolves v1: %v", err) } if err := f.s.SetIssueMilestone(f.coreIssue, id); err != nil { t.Fatal(err) } if err := f.s.SetIssueMilestone(f.siteIssue, id); err != nil { t.Fatal(err) } if err := f.s.SetIssueState(f.siteIssue, "closed"); err != nil { t.Fatal(err) } ms, err := f.s.ListOrgMilestones(f.org, "open", f.orgRepos()) if err != nil || len(ms) != 1 || ms[0].OpenItems != 1 || ms[0].ClosedItems != 1 { t.Fatalf("org list = %+v, %v", ms, err) } // Counts stop at what the caller can read. ms, _ = f.s.ListOrgMilestones(f.org, "open", []int64{f.core.ID}) if ms[0].OpenItems != 1 || ms[0].ClosedItems != 0 { t.Fatalf("org list over core = %+v", ms) } // A repo's list shows the org milestone first, then its own. if _, err := f.s.CreateMilestone(f.core, "core-only", "", ""); err != nil { t.Fatal(err) } ms, _ = f.s.ListMilestones(f.core, "open", f.orgRepos()) if len(ms) != 2 || ms[0].Title != "v1" || ms[0].OrgID != f.org || ms[1].Title != "core-only" || ms[1].RepoID != f.core.ID { t.Fatalf("core list = %+v", ms) } if _, err := f.s.OrgMilestoneByTitle(f.org, "core-only"); !errors.Is(err, ErrNotFound) { t.Fatalf("org resolves a repo milestone: %v", err) } } func TestRepoMilestoneRefusedWhenOrgHoldsTitle(t *testing.T) { f := newAcme(t) if _, _, err := f.s.CreateOrgMilestone(f.org, "v1", "", ""); err != nil { t.Fatal(err) } if _, err := f.s.CreateMilestone(f.core, "v1", "", ""); !errors.Is(err, ErrOrgScoped) { t.Fatalf("CreateMilestone over org title: %v", err) } if _, err := f.s.CreateMilestone(f.app, "v1", "", ""); err != nil { t.Fatalf("user repo unaffected: %v", err) } if _, _, err := f.s.CreateOrgMilestone(f.org, "v1", "", ""); err == nil { t.Fatal("duplicate org milestone accepted") } } func TestCreateOrgMilestonePromotes(t *testing.T) { f := newAcme(t) cid, err := f.s.CreateMilestone(f.core, "v1", "", "") if err != nil { t.Fatal(err) } sid, err := f.s.CreateMilestone(f.site, "v1", "", "") if err != nil { t.Fatal(err) } if err := f.s.SetIssueMilestone(f.coreIssue, cid); err != nil { t.Fatal(err) } mrID, err := f.s.CreateMR(f.site.ID, f.alice, f.site.ID, "feat", "main", "t", "", "abc", "md", false) if err != nil { t.Fatal(err) } if err := f.s.SetMRMilestone(mrID, sid); err != nil { t.Fatal(err) } id, folded, err := f.s.CreateOrgMilestone(f.org, "v1", "org wide", "2027-06-01") if err != nil || folded != 2 { t.Fatalf("promote: folded %d, %v", folded, err) } var n int f.s.DB.QueryRow("SELECT COUNT(*) FROM milestones WHERE title = 'v1'").Scan(&n) if n != 1 { t.Fatalf("milestones named v1: %d", n) } f.s.DB.QueryRow("SELECT COUNT(*) FROM issues WHERE milestone_id = ?", id).Scan(&n) if n != 1 { t.Fatalf("issues on org milestone: %d", n) } f.s.DB.QueryRow("SELECT COUNT(*) FROM merge_requests WHERE milestone_id = ?", id).Scan(&n) if n != 1 { t.Fatalf("mrs on org milestone: %d", n) } ms, _ := f.s.ListOrgMilestones(f.org, "open", f.orgRepos()) if len(ms) != 1 || ms[0].OpenItems != 2 || ms[0].Description != "org wide" || ms[0].DueDate != "2027-06-01" { t.Fatalf("after promote: %+v", ms) } } ``` - [ ] **Step 2: Run them to verify they fail** Run: `go test ./internal/store/ -run 'OrgMilestone|RepoMilestoneRefused' -v` Expected: build failure, `CreateOrgMilestone` and friends undefined. - [ ] **Step 3: Rewrite `milestones.go` from `CreateMilestone` through `ListMilestones`** ```go // orgHoldsMilestone reports whether the repository's org has a milestone // of that title; always false for a user-owned repository. func (s *Store) orgHoldsMilestone(repo Repo, title string) (bool, error) { if repo.OwnerKind != "org" { return false, nil } var n int err := s.DB.QueryRow("SELECT COUNT(*) FROM milestones WHERE org_id = ? AND title = ?", repo.OwnerID, title).Scan(&n) return n > 0, err } // CreateMilestone creates the repository's milestone. A title the org // holds is refused with ErrOrgScoped. func (s *Store) CreateMilestone(repo Repo, title, description, due string) (int64, error) { if held, err := s.orgHoldsMilestone(repo, title); err != nil || held { if err != nil { return 0, err } return 0, ErrOrgScoped } res, err := s.DB.Exec( "INSERT INTO milestones (repo_id, title, description, due_date) VALUES (?, ?, ?, ?)", repo.ID, title, description, due) if err != nil { if isUniqueErr(err) { return 0, fmt.Errorf("milestone %q already exists", title) } return 0, err } return res.LastInsertId() } // CreateOrgMilestone creates the org's milestone. Repositories under the // org that hold the title are folded in: their issues and merge requests // move to the org's row and their rows go. folded is how many were. func (s *Store) CreateOrgMilestone(orgID int64, title, description, due string) (int64, int, error) { tx, err := s.DB.Begin() if err != nil { return 0, 0, err } defer tx.Rollback() res, err := tx.Exec( "INSERT INTO milestones (org_id, title, description, due_date) VALUES (?, ?, ?, ?)", orgID, title, description, due) if err != nil { if isUniqueErr(err) { return 0, 0, fmt.Errorf("milestone %q already exists", title) } return 0, 0, err } id, err := res.LastInsertId() if err != nil { return 0, 0, err } rows, err := tx.Query(`SELECT m.id FROM milestones m JOIN repos r ON r.id = m.repo_id WHERE r.owner_kind = 'org' AND r.owner_id = ? AND m.title = ?`, orgID, title) if err != nil { return 0, 0, err } var repoRows []int64 for rows.Next() { var rid int64 if err := rows.Scan(&rid); err != nil { rows.Close() return 0, 0, err } repoRows = append(repoRows, rid) } rows.Close() for _, rid := range repoRows { for _, table := range []string{"issues", "merge_requests"} { if _, err := tx.Exec("UPDATE "+table+" SET milestone_id = ? WHERE milestone_id = ?", id, rid); err != nil { return 0, 0, err } } if _, err := tx.Exec("DELETE FROM milestones WHERE id = ?", rid); err != nil { return 0, 0, err } } return id, len(repoRows), tx.Commit() } // milestoneQuery selects milestones with their progress, counting only // items in the readable repositories. Its args come first in any query // built on it. func milestoneQuery(readable []int64) (string, []any) { in, args := inClause(readable) q := ` SELECT m.id, COALESCE(m.repo_id, 0), COALESCE(m.org_id, 0), m.title, m.description, m.due_date, m.state, m.created_at, (SELECT COUNT(*) FROM issues i WHERE i.milestone_id = m.id AND i.state = 'open' AND i.repo_id IN ` + in + `) + (SELECT COUNT(*) FROM merge_requests r WHERE r.milestone_id = m.id AND r.state IN ('open','source_gone') AND r.repo_id IN ` + in + `), (SELECT COUNT(*) FROM issues i WHERE i.milestone_id = m.id AND i.state = 'closed' AND i.repo_id IN ` + in + `) + (SELECT COUNT(*) FROM merge_requests r WHERE r.milestone_id = m.id AND r.state IN ('merged','closed') AND r.repo_id IN ` + in + `) FROM milestones m` all := make([]any, 0, 4*len(args)) for i := 0; i < 4; i++ { all = append(all, args...) } return q, all } func scanMilestone(row interface{ Scan(...any) error }) (Milestone, error) { var m Milestone err := row.Scan(&m.ID, &m.RepoID, &m.OrgID, &m.Title, &m.Description, &m.DueDate, &m.State, &m.CreatedAt, &m.OpenItems, &m.ClosedItems) return m, err } // milestoneByTitle resolves a title under where. The org's row comes // first when both scopes are in play; creation keeps that from happening. func (s *Store) milestoneByTitle(where string, args []any) (Milestone, error) { q, qargs := milestoneQuery(nil) m, err := scanMilestone(s.DB.QueryRow(q+" WHERE "+where+" ORDER BY m.org_id IS NULL LIMIT 1", append(qargs, args...)...)) if errors.Is(err, sql.ErrNoRows) { return m, ErrNotFound } return m, err } // MilestoneByTitle resolves a title the way attaching does: the org's // milestone when the org has it, else the repository's. Progress counts // are not populated here; list for those. func (s *Store) MilestoneByTitle(repo Repo, title string) (Milestone, error) { where, args := scopeClause("m", repo) return s.milestoneByTitle(where+" AND m.title = ?", append(args, title)) } func (s *Store) OrgMilestoneByTitle(orgID int64, title string) (Milestone, error) { return s.milestoneByTitle("m.org_id = ? AND m.title = ?", []any{orgID, title}) } func (s *Store) listMilestones(where string, args []any, state string, readable []int64) ([]Milestone, error) { q, qargs := milestoneQuery(readable) q += " WHERE " + where qargs = append(qargs, args...) if state != "all" { q += " AND m.state = ?" qargs = append(qargs, state) } q += " ORDER BY m.org_id IS NULL, m.due_date = '', m.due_date, m.title" rows, err := s.DB.Query(q, qargs...) if err != nil { return nil, err } defer rows.Close() var out []Milestone for rows.Next() { m, err := scanMilestone(rows) if err != nil { return nil, err } out = append(out, m) } return out, rows.Err() } // ListMilestones lists the milestones a repository sees, the org's first, // with progress counted over the readable repositories. func (s *Store) ListMilestones(repo Repo, state string, readable []int64) ([]Milestone, error) { where, args := scopeClause("m", repo) return s.listMilestones(where, args, state, readable) } // ListOrgMilestones lists an org's milestones with progress across the // readable repositories under it. func (s *Store) ListOrgMilestones(orgID int64, state string, readable []int64) ([]Milestone, error) { return s.listMilestones("m.org_id = ?", []any{orgID}, state, readable) } ``` Delete the old `milestoneSelect` constant. Keep `SetMilestoneState`, `SetIssueMilestone`, `SetMRMilestone`, `setItemMilestone` as they are. - [ ] **Step 4: Run the store tests** Run: `go test ./internal/store/` Expected: all PASS, including `TestMigration0052...` and the label tests. - [ ] **Step 5: Commit** ```bash git add internal/store/milestones.go internal/store/milestones_test.go git commit -m "store: milestones resolve through the repository's org Ref #203" ``` --- ### Task 4: Callers compile; repo-level refusals; readable-scope helper **Files:** - Create: `internal/control/scope.go` - Modify: `internal/control/label.go:33-119` - Modify: `internal/control/milestone.go:44-66, 68-88, 118-141, 181-190` - Modify: `internal/control/issue.go:391, 396` - Modify: `internal/control/ghimport.go:259` - Modify: `internal/control/migrate.go:250` - Modify: `internal/httpd/labels.go:20, 31` - Modify: `internal/httpd/web.go:705, 1606-1618, 1675, 1700, 1713` - Test: `internal/control/orgscope_test.go` (new) **Interfaces:** - Produces in `internal/control/scope.go`: - `func ReadableOrgRepoIDs(st *store.Store, user store.User, orgID int64) ([]int64, error)` — ids of the org's repositories `user` can read (`policy.CanRead` with `AccessRole`; user with ID 0 is anonymous). - `func ReadableScope(st *store.Store, user store.User, repo store.Repo) ([]int64, error)` — `ReadableOrgRepoIDs` for an org-owned repo, `[]int64{repo.ID}` otherwise. - `func orgScopedMsg(repo store.Repo, noun, name, cmd string) string` — the refusal text: `"%s is an org %s of %s; manage it with org %s %s %s"`. - Consumes: Task 2 and Task 3 signatures. - [ ] **Step 1: Write the failing tests** `internal/control/orgscope_test.go`: ```go package control import ( "bytes" "strings" "testing" "gitbay.org/gitbay/internal/config" "gitbay.org/gitbay/internal/protocol" "gitbay.org/gitbay/internal/store" ) // orgFixture: alice admins org acme with acme/core (public) and acme/priv // (private); bob is a plain member; carol is outside. alice also owns // alice/app. type orgFixture struct { st *store.Store alice, bob, carol int64 org int64 core, priv, app store.Repo } func newOrgFixture(t *testing.T) orgFixture { t.Helper() st, err := store.Open(":memory:") if err != nil { t.Fatal(err) } t.Cleanup(func() { st.Close() }) if err := st.MigrateUp(); err != nil { t.Fatal(err) } var f orgFixture f.st = st user := func(name string) int64 { id, err := st.CreateUser(name, false) if err != nil { t.Fatal(err) } return id } f.alice, f.bob, f.carol = user("alice"), user("bob"), user("carol") if f.org, err = st.CreateOrg("acme", f.alice); err != nil { t.Fatal(err) } if err := st.SetOrgMember(f.org, f.bob, "member"); err != nil { t.Fatal(err) } repo := func(kind string, owner int64, name, vis string) store.Repo { id, err := st.CreateRepo(kind, owner, name, vis) if err != nil { t.Fatal(err) } r, _ := st.RepoByID(id) return r } f.core = repo("org", f.org, "core", "public") f.priv = repo("org", f.org, "priv", "private") f.app = repo("user", f.alice, "app", "public") return f } func (f orgFixture) ctx(uid int64) (*Ctx, *bytes.Buffer) { var out bytes.Buffer name := map[int64]string{f.alice: "alice", f.bob: "bob", f.carol: "carol"}[uid] return &Ctx{ User: store.User{ID: uid, Username: name}, Scope: "full", Source: "SHA256:session", Store: f.st, Cfg: config.Config{Server: config.Server{SiteURL: "https://x.test"}}, Stdin: strings.NewReader(""), Stdout: &out, Stderr: &out, JSON: true, }, &out } func TestReadableOrgRepoIDs(t *testing.T) { f := newOrgFixture(t) ids, err := ReadableOrgRepoIDs(f.st, store.User{ID: f.bob, Username: "bob"}, f.org) if err != nil || len(ids) != 2 { t.Fatalf("member reads %v, %v; want both", ids, err) } ids, _ = ReadableOrgRepoIDs(f.st, store.User{ID: f.carol, Username: "carol"}, f.org) if len(ids) != 1 || ids[0] != f.core.ID { t.Fatalf("outsider reads %v; want core only", ids) } ids, _ = ReadableOrgRepoIDs(f.st, store.User{}, f.org) if len(ids) != 1 || ids[0] != f.core.ID { t.Fatalf("anonymous reads %v; want core only", ids) } ids, _ = ReadableScope(f.st, store.User{ID: f.alice, Username: "alice"}, f.app) if len(ids) != 1 || ids[0] != f.app.ID { t.Fatalf("user repo scope %v; want itself", ids) } } func TestRepoLabelCommandsRefuseOrgNames(t *testing.T) { f := newOrgFixture(t) if _, err := f.st.SetOrgLabel(f.org, "bug", ""); err != nil { t.Fatal(err) } c, out := f.ctx(f.alice) if code := runLabelSet(c, []string{"acme/core", "bug", "--color", "ff0000"}); code != protocol.ExitFailure || !strings.Contains(out.String(), "org label set acme bug") { t.Fatalf("label set over org name: exit %d %s", code, out.String()) } out.Reset() if code := runLabelRemove(c, []string{"acme/core", "bug"}); code != protocol.ExitFailure || !strings.Contains(out.String(), "org label remove acme bug") { t.Fatalf("label remove of org row: exit %d %s", code, out.String()) } out.Reset() // issue label --add resolves to the org row, and label list marks it. iid, _ := f.st.CreateIssue(f.core.ID, f.alice, "c1", "", "md") _ = iid if code := runIssueLabel(c, []string{"acme/core", "1", "--add", "bug"}); code != protocol.ExitOK { t.Fatalf("issue label: exit %d %s", code, out.String()) } out.Reset() if code := runLabelList(c, []string{"acme/core"}); code != protocol.ExitOK || !strings.Contains(out.String(), `"org":true`) || !strings.Contains(out.String(), `"issues":1`) { t.Fatalf("label list: exit %d %s", code, out.String()) } } func TestRepoMilestoneCommandsRefuseOrgTitles(t *testing.T) { f := newOrgFixture(t) if _, _, err := f.st.CreateOrgMilestone(f.org, "v1", "", ""); err != nil { t.Fatal(err) } c, out := f.ctx(f.alice) if code := runMilestoneCreate(c, []string{"acme/core", "v1"}); code != protocol.ExitFailure || !strings.Contains(out.String(), "org milestone create acme v1") { t.Fatalf("milestone create over org title: exit %d %s", code, out.String()) } out.Reset() if code := runMilestoneClose(c, []string{"acme/core", "v1"}); code != protocol.ExitFailure || !strings.Contains(out.String(), "org milestone close acme v1") { t.Fatalf("milestone close of org row: exit %d %s", code, out.String()) } out.Reset() // Attaching by title from a repo resolves the org milestone. f.st.CreateIssue(f.core.ID, f.alice, "c1", "", "md") if code := runIssueMilestone(c, []string{"acme/core", "1", "v1"}); code != protocol.ExitOK { t.Fatalf("issue milestone: exit %d %s", code, out.String()) } out.Reset() if code := runMilestoneList(c, []string{"acme/core"}); code != protocol.ExitOK || !strings.Contains(out.String(), `"org":true`) || !strings.Contains(out.String(), `"open":1`) { t.Fatalf("milestone list: exit %d %s", code, out.String()) } } ``` - [ ] **Step 2: Run them to verify they fail** Run: `go test ./internal/control/ -run 'ReadableOrgRepoIDs|RefuseOrg' -v` Expected: build failure (`ReadableOrgRepoIDs` undefined, plus the package does not compile against Task 2/3 signatures yet). - [ ] **Step 3: Write `internal/control/scope.go`** ```go package control import ( "fmt" "gitbay.org/gitbay/internal/policy" "gitbay.org/gitbay/internal/store" ) // ReadableOrgRepoIDs is the org's repositories user may read. Counts on // org labels and milestones are taken over these, so a private // repository's issues never show in a number someone outside it sees. A // zero user is anonymous. func ReadableOrgRepoIDs(st *store.Store, user store.User, orgID int64) ([]int64, error) { repos, err := st.ListReposForOwner("org", orgID) if err != nil { return nil, err } var ids []int64 for _, r := range repos { grant := "" if user.ID != 0 { if grant, err = st.AccessRole(r.ID, user.ID); err != nil { return nil, err } } if policy.CanRead(user, r, grant) { ids = append(ids, r.ID) } } return ids, nil } // ReadableScope is the set a repository's label and milestone counts // span: its org's readable repositories, or just itself when a user owns // it. The caller has already been allowed to read repo. func ReadableScope(st *store.Store, user store.User, repo store.Repo) ([]int64, error) { if repo.OwnerKind == "org" { return ReadableOrgRepoIDs(st, user, repo.OwnerID) } return []int64{repo.ID}, nil } // orgScopedMsg names the org command that manages a row a repository // command was asked to change. func orgScopedMsg(repo store.Repo, noun, name, verb string) string { return fmt.Sprintf("%s is an org %s of %s; manage it with org %s %s %s %s", name, noun, repo.OwnerName, noun, verb, repo.OwnerName, name) } ``` - [ ] **Step 4: Update `label.go`** In `runLabelList`, replace the `ListLabels` call: ```go readable, err := ReadableScope(c.Store, c.User, repo) if err != nil { return c.fail(protocol.ExitFailure, "%v", err) } labels, err := c.Store.ListLabels(repo, readable) ``` and print the mark in the plain output: `fmt.Fprintf(w, "%s\t%s\t%d%s\n", l.Name, l.Color, l.Issues, map[bool]string{true: "\torg"}[l.Org])`. In `runLabelSet`, replace the colour-keeping block and the store call: ```go if !colorSet { // Keep the colour it has, if any; this is "make sure it exists". if l, err := c.Store.LabelByName(repo, name); err == nil && !l.Org { color = l.Color } } if err := c.Store.SetLabel(repo, name, color); err != nil { if errors.Is(err, store.ErrOrgScoped) { return c.fail(protocol.ExitFailure, "%s", orgScopedMsg(repo, "label", name, "set")) } return c.fail(protocol.ExitFailure, "%v", err) } ``` In `runLabelRemove`: ```go if err := c.Store.DeleteLabel(repo, args[1]); err != nil { if errors.Is(err, store.ErrOrgScoped) { return c.fail(protocol.ExitFailure, "%s", orgScopedMsg(repo, "label", args[1], "remove")) } if errors.Is(err, store.ErrNotFound) { return c.fail(protocol.ExitNotFound, "no label %q in %s", args[1], repo.Path()) } return c.fail(protocol.ExitFailure, "%v", err) } ``` - [ ] **Step 5: Update `milestone.go`** `runMilestoneCreate`: ```go if _, err := c.Store.CreateMilestone(repo, title, description, due); err != nil { if errors.Is(err, store.ErrOrgScoped) { return c.fail(protocol.ExitFailure, "%s", orgScopedMsg(repo, "milestone", title, "create")) } return c.failErr(err) } ``` `runMilestoneList`: compute `readable` with `ReadableScope` as in label list, call `c.Store.ListMilestones(repo, state, readable)`, add `Org bool `json:"org,omitempty"`` to the `out` struct after `State`, fill it with `m.OrgID != 0`, and append `\torg` to the plain line when set. `setMilestoneState`, after `MilestoneByTitle(repo, args[1])`: ```go if m.OrgID != 0 { return c.fail(protocol.ExitFailure, "%s", orgScopedMsg(repo, "milestone", m.Title, verb)) } ``` `setItemMilestone`: `c.Store.MilestoneByTitle(repo, title)`. - [ ] **Step 6: Update the remaining callers** - `internal/control/issue.go:391,396`: `c.Store.SetIssueLabel(repo, issue.ID, l, true)` / `false`. - `internal/control/ghimport.go:259` and `internal/control/migrate.go:250`: `SetIssueLabel(repo, iss.ID, ...)`. Check each has a `repo store.Repo` in scope; both do, it is what `repo.ID` came from. - `internal/httpd/web.go:1606`: `func (s *Server) labelColors(repo store.Repo) map[string]template.CSS` with `s.st.LabelColors(repo)`; callers at 1675 and 1713 pass `p.Repo`. Split the colour derivation into `func colorStyles(stored map[string]string) map[string]template.CSS` (the loop body as it stands) so Task 8 can reuse it for the org page; `labelColors` becomes `stored, _ := s.st.LabelColors(repo); return colorStyles(stored)`. - `internal/httpd/web.go:705`: `readable, _ := control.ReadableOrgRepoIDs(...)` is wrong for a repo page; use `readable, err := control.ReadableScope(s.st, s.viewer(r), p.Repo)` then `s.st.ListMilestones(p.Repo, state, readable)`. Same at 1700 (`"open"`). - `internal/httpd/labels.go:20`: `readable, err := control.ReadableScope(s.st, s.viewer(r), p.Repo)` then `s.st.ListLabels(p.Repo, readable)`; line 31 `s.labelColors(p.Repo)`. `httpd` already imports `control`; `web.go` needs no new import. - [ ] **Step 7: Build, vet, test** Run: `go build ./... && go vet ./... && go test ./internal/control/ ./internal/httpd/ ./internal/store/` Expected: all PASS. `TestReadableOrgRepoIDs`, `TestRepoLabelCommandsRefuseOrgNames`, `TestRepoMilestoneCommandsRefuseOrgTitles` PASS. - [ ] **Step 8: Commit** ```bash git add internal/control/scope.go internal/control/label.go internal/control/milestone.go internal/control/issue.go internal/control/ghimport.go internal/control/migrate.go internal/httpd/labels.go internal/httpd/web.go internal/control/orgscope_test.go git commit -m "control, web: repository commands see org labels and milestones and refuse to change them Ref #203" ``` --- ### Task 5: `org label set|list|remove` **Files:** - Create: `internal/control/orglabel.go` - Modify: `cmd/gitbay/main.go:642-670` (org group) - Modify: `e2e/readonly_test.go:85+` (`readArgs`) - Test: `internal/control/orglabel_test.go` (new) **Interfaces:** - Produces: commands `org label set