diff --git a/SPEC.md b/SPEC.md index 4c570c1..b5ffec7 100644 --- a/SPEC.md +++ b/SPEC.md @@ -381,12 +381,13 @@ hub). | Verb | What it does | |------|--------------| | `codecrew status` | Where the project is: open milestones, task states, raised gates. | -| `codecrew init [--hub owner/repo]` | Scaffolds a new repo: hub mode writes `.codecrew.yml` with the full `~`-routed roles table, the ROADMAP.md seed, the role contracts (embedded at the installed release), and an AGENTS.md entry point; spoke mode writes the two-line pointer. Idempotent — existing files are kept and reported. | +| `codecrew init [--hub owner/repo]` | Scaffolds a new repo: hub mode writes `.codecrew.yml` with the full `~`-routed roles table, the ROADMAP.md seed, the role contracts (embedded at the installed release), and an AGENTS.md entry point; spoke mode writes the two-line pointer. Idempotent — existing files are kept and reported. Scaffolded contracts carry a provenance stamp naming the release that wrote them. | | `codecrew milestone new` | Creates a milestone tracking issue in the hub from the template; updates ROADMAP.md. | | `codecrew task new --milestone --repo ` | Creates a task issue in the spoke from the template; attaches it to the milestone as a sub-issue. | | `codecrew task start ` | Assigns the caller's identity, verifies a plan is present (refuses to start a planless nontrivial task), creates the working branch — unless the caller's role routing resolves to a role whose contract forbids commits (`qa`, `reviewer`), which get no branch. | | `codecrew checkpoint --question "…"` | Raises a human gate: posts the question as a comment, applies `cc:needs-decision`. | | `codecrew identity new --name ` | Mints the role's App identity via the GitHub App manifest flow: generates a manifest with the role's minimal permission set, hands the operator a one-click loopback URL, stores the returned private key locally, writes the role's routing into the hub's `.codecrew.yml` (`--no-route` opts out; printed as an instruction when the table is not local), and prints the remaining manual steps (install — per-account — and optional display polish). Webhooks off by default; `--with-webhook` opts in to protocol-traffic event delivery for platform receivers (§9). | +| `codecrew roles diff ` / `codecrew roles show --latest` | Contract-drift tooling: `status` reports when a local `roles/` contract differs from the copy embedded in the installed CLI (scaffolded contracts carry a provenance stamp naming their release); `diff` shows the divergence, `show --latest` prints the embedded contract whole. Contracts are the project's own fork — reconciliation is a judgment routed through a task and PR, never an overwrite. | | `codecrew role ` | Prints the identity holding a role — an App slug or username, or `~` for the operator (§5). Script-consumable; resolves from the hub's routing table when run in a spoke. The implementer uses it to request review from the reviewer role's holder at PR creation when the holder is review-requestable — a username or team; App-held seats are dispatched instead, Apps not being requestable (CODEOWNERS-driven requests coexist — requested reviewers union). | | `codecrew task finish ` | The gatekeeper: verifies a PR exists, CI checks exist and are green (`refused[NO_CHECKS]` when a PR reports zero checks — the deterministic gate cannot be satisfied by absence, and there is no override), an approving review exists from a non-doer, and deviations referenced in the PR body have recorded comments — then merges (rebase) and closes. When GitHub's own required-review rule is still unmet at that point (`reviewDecision: REVIEW_REQUIRED` — App reviews and operator confirmations are never counted by rulesets), it refuses with `refused[REVIEW_NOT_COUNTED]` naming the supported paths; `--bypass` performs the ruleset's administrator merge instead, recorded as a PR comment, and only for a human operator the ruleset lists as a bypass actor. Refuses otherwise, with the specific unmet condition. In a solo-tier project (§5) where author and operator are the same principal, the non-doer approval degrades to an explicit operator confirmation, recorded as a PR comment; the confirming identity must be human — crew identities (`[bot]` suffix or routed role) are refused with `refused[SELF_CONFIRM]`. | | `codecrew milestone close ` | Verifies all tasks closed and every requirement's latest QA verdict is `satisfied` (`refused[VERDICT_MISSING]` / `refused[VERDICT_UNSATISFIED]` otherwise; only verdicts from the qa role's holder count — its routed identity, or the human operator when the role is unrouted (§5) — and a later verdict supersedes an earlier one); gathers every Decision/Deviation comment across the milestone's tasks into raw material for the doc-synthesizer; refuses to close until the milestone document PR is merged. | diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 0fdb4d7..54d7b3f 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -20,6 +20,8 @@ verbs: [--bypass] (recorded admin merge when GitHub won't count the approval) checkpoint --question "..." raise a human gate (cc:needs-decision) role who holds a role (identity, or ~ for the operator) + roles diff local contract vs the one embedded in the CLI + roles show --latest print the embedded contract identity new --name N mint the role's App identity via the manifest flow [--owner O] [--with-webhook --webhook-url U] version installed release tag (dev for source builds) @@ -69,6 +71,8 @@ func Run(args []string) error { return checkpoint(os.Stdout, rest) case "role": return roleHolder(os.Stdout, rest) + case "roles": + return rolesCmd(os.Stdout, rest) case "version", "--version", "-v": return versionCmd(os.Stdout) case "help", "-h", "--help": diff --git a/internal/cli/init.go b/internal/cli/init.go index 2015d32..7a62523 100644 --- a/internal/cli/init.go +++ b/internal/cli/init.go @@ -46,6 +46,13 @@ https://github.com/radiusred/gh-codecrew (SPEC.md). ` + "`refused[CODE]: detail`" + ` — act on the code, don't work around it. - Plans before commits, decisions recorded when made, and the verifier is never the doer. +- **Contract drift.** ` + "`codecrew status`" + ` reports when a ` + "`roles/`" + ` contract + differs from the one embedded in the installed CLI. When it does, the + coordination layer compares (` + "`codecrew roles diff `" + `, full upstream + text via ` + "`codecrew roles show --latest`" + `), decides what to adopt — + contracts are this project's own fork, and local conventions are + legitimate — and routes the reconciliation through a normal task and PR + with the decision recorded. Never overwrite blindly. - **Dispatch authorization.** If you are the operator's primary session — not dispatched as any specific role — then when a role is routed to a GitHub App and that role's action is needed (a review, a verdict), @@ -77,7 +84,10 @@ func scaffold(dir, hub string, contracts fs.FS) (written, skipped []string, err if err != nil { return nil, nil, err } - files[filepath.Join("roles", e.Name())] = string(data) + // Provenance stamp: names the release these contracts shipped + // with, so drift can be judged three-way later (the base is + // fetchable from the upstream repo at this version). + files[filepath.Join("roles", e.Name())] = contractStamp(e.Name()) + string(data) } } for rel, content := range files { diff --git a/internal/cli/roles.go b/internal/cli/roles.go new file mode 100644 index 0000000..a46e5c0 --- /dev/null +++ b/internal/cli/roles.go @@ -0,0 +1,173 @@ +package cli + +import ( + "flag" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + + codecrew "github.com/radiusred/gh-codecrew" + "github.com/radiusred/gh-codecrew/internal/config" +) + +// stampPrefix opens every provenance stamp contractStamp writes; stripStamp +// keys on it, so a reworded stamp still strips as long as this prefix opens +// the comment. +const stampPrefix = "\n\n", stampPrefix, version, name) +} + +// stripStamp removes the provenance stamp (and its trailing blank line) so +// comparisons see the contract alone. Content without a stamp — the hub's +// own roles/, or a hand-created file — passes through unchanged. +func stripStamp(content string) string { + if !strings.HasPrefix(content, stampPrefix) { + return content + } + if _, rest, ok := strings.Cut(content, "-->\n"); ok { + return strings.TrimPrefix(rest, "\n") + } + return content +} + +// contractDrift compares each local roles/ contract (stamp-stripped) +// against the copy embedded in this binary, returning the names that +// differ. Local files with no embedded counterpart, and embedded contracts +// with no local file (a pointer-only spoke), are not drift. +func contractDrift(dir string, contracts fs.FS) ([]string, error) { + entries, err := fs.ReadDir(contracts, "roles") + if err != nil { + return nil, err + } + var drifted []string + for _, e := range entries { + local, err := os.ReadFile(filepath.Join(dir, "roles", e.Name())) + if err != nil { + continue // no local copy — nothing to drift + } + embedded, err := fs.ReadFile(contracts, "roles/"+e.Name()) + if err != nil { + return nil, err + } + if stripStamp(string(local)) != string(embedded) { + drifted = append(drifted, strings.TrimSuffix(e.Name(), ".md")) + } + } + return drifted, nil +} + +// unifiedDiff is a minimal line diff (LCS) — enough to judge a contract +// change without shelling out to external tools. +func unifiedDiff(a, b string) string { + al := strings.Split(strings.TrimSuffix(a, "\n"), "\n") + bl := strings.Split(strings.TrimSuffix(b, "\n"), "\n") + // lcs[i][j] = length of LCS of al[i:], bl[j:] + lcs := make([][]int, len(al)+1) + for i := range lcs { + lcs[i] = make([]int, len(bl)+1) + } + for i := len(al) - 1; i >= 0; i-- { + for j := len(bl) - 1; j >= 0; j-- { + if al[i] == bl[j] { + lcs[i][j] = lcs[i+1][j+1] + 1 + } else { + lcs[i][j] = max(lcs[i+1][j], lcs[i][j+1]) + } + } + } + var out strings.Builder + i, j := 0, 0 + for i < len(al) && j < len(bl) { + switch { + case al[i] == bl[j]: + fmt.Fprintf(&out, " %s\n", al[i]) + i++ + j++ + case lcs[i+1][j] >= lcs[i][j+1]: + fmt.Fprintf(&out, "- %s\n", al[i]) + i++ + default: + fmt.Fprintf(&out, "+ %s\n", bl[j]) + j++ + } + } + for ; i < len(al); i++ { + fmt.Fprintf(&out, "- %s\n", al[i]) + } + for ; j < len(bl); j++ { + fmt.Fprintf(&out, "+ %s\n", bl[j]) + } + return out.String() +} + +// rolesDiff prints the local contract against the embedded one: "-" lines +// are local (this project's fork), "+" lines are the embedded contract at +// the installed release. +func rolesDiff(w io.Writer, dir string, contracts fs.FS, role string) error { + embedded, err := fs.ReadFile(contracts, "roles/"+role+".md") + if err != nil { + return fmt.Errorf("no embedded contract for role %q", role) + } + local, err := os.ReadFile(filepath.Join(dir, "roles", role+".md")) + if err != nil { + return fmt.Errorf("no local roles/%s.md — run from the hub (spokes hold no contracts)", role) + } + stripped := stripStamp(string(local)) + if stripped == string(embedded) { + fmt.Fprintf(w, "roles/%s.md matches the embedded %s contract\n", role, version) + return nil + } + fmt.Fprintf(w, "roles/%s.md (local, -) vs embedded %s contract (+):\n", role, version) + fmt.Fprint(w, unifiedDiff(stripped, string(embedded))) + fmt.Fprintf(w, "\ncontracts are this project's fork — reconcile through a task and PR, never a blind overwrite\n") + return nil +} + +// rolesShow prints the embedded contract whole: the virtual "latest", +// materialized on demand instead of shadow-copied into the repo. +func rolesShow(w io.Writer, contracts fs.FS, role string, latest bool) error { + if !latest { + return fmt.Errorf("usage: codecrew roles show --latest (the local file is readable directly)") + } + data, err := fs.ReadFile(contracts, "roles/"+role+".md") + if err != nil { + return fmt.Errorf("no embedded contract for role %q", role) + } + _, err = w.Write(data) + return err +} + +// rolesCmd dispatches the roles subverbs against the installed binary's +// embedded contracts and the local hub checkout. +func rolesCmd(w io.Writer, args []string) error { + if len(args) < 2 { + return fmt.Errorf("usage: codecrew roles diff | codecrew roles show --latest") + } + sub, role := args[0], args[1] + cfg, err := config.Load(".") + if err != nil { + return err + } + switch sub { + case "diff": + return rolesDiff(w, cfg.Dir, codecrew.Roles, role) + case "show": + fs := flag.NewFlagSet("roles show", flag.ContinueOnError) + latest := fs.Bool("latest", false, "print the contract embedded in the installed binary") + if err := fs.Parse(args[2:]); err != nil { + return err + } + return rolesShow(w, codecrew.Roles, role, *latest) + default: + return fmt.Errorf("unknown subcommand roles %s", sub) + } +} diff --git a/internal/cli/roles_test.go b/internal/cli/roles_test.go new file mode 100644 index 0000000..9ad2f1b --- /dev/null +++ b/internal/cli/roles_test.go @@ -0,0 +1,114 @@ +package cli + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestStampRoundTrip(t *testing.T) { + stamped := contractStamp("implementer.md") + "# Role: implementer\nBody.\n" + if got := stripStamp(stamped); got != "# Role: implementer\nBody.\n" { + t.Errorf("stripStamp = %q", got) + } + // Unstamped content — the hub's own roles/ — passes through whole. + if got := stripStamp("# Role: qa\n"); got != "# Role: qa\n" { + t.Errorf("unstamped content altered: %q", got) + } +} + +func TestFreshScaffoldShowsNoDrift(t *testing.T) { + dir := t.TempDir() + if _, _, err := scaffold(dir, "self", fakeContracts); err != nil { + t.Fatal(err) + } + drifted, err := contractDrift(dir, fakeContracts) + if err != nil { + t.Fatal(err) + } + if len(drifted) != 0 { + t.Errorf("fresh scaffold drifted: %v — the stamp must strip cleanly", drifted) + } + // The scaffolded file really is stamped. + data, _ := os.ReadFile(filepath.Join(dir, "roles", "implementer.md")) + if !strings.HasPrefix(string(data), stampPrefix) { + t.Error("scaffolded contract missing the provenance stamp") + } +} + +func TestLocalEditIsDrift(t *testing.T) { + dir := t.TempDir() + if _, _, err := scaffold(dir, "self", fakeContracts); err != nil { + t.Fatal(err) + } + p := filepath.Join(dir, "roles", "qa.md") + data, _ := os.ReadFile(p) + os.WriteFile(p, append(data, []byte("\n- Local convention: tests ride along.\n")...), 0o644) + drifted, err := contractDrift(dir, fakeContracts) + if err != nil { + t.Fatal(err) + } + if len(drifted) != 1 || drifted[0] != "qa" { + t.Errorf("drift = %v, want [qa]", drifted) + } +} + +func TestContractDriftSkipsSpokes(t *testing.T) { + drifted, err := contractDrift(t.TempDir(), fakeContracts) // no roles/ dir at all + if err != nil { + t.Fatal(err) + } + if len(drifted) != 0 { + t.Errorf("spoke (no roles/) reported drift: %v", drifted) + } +} + +func TestUnifiedDiff(t *testing.T) { + got := unifiedDiff("a\nb\nc\n", "a\nx\nc\n") + want := " a\n- b\n+ x\n c\n" + if got != want { + t.Errorf("unifiedDiff = %q, want %q", got, want) + } +} + +func TestRolesDiffAndShow(t *testing.T) { + dir := t.TempDir() + if _, _, err := scaffold(dir, "self", fakeContracts); err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + if err := rolesDiff(&buf, dir, fakeContracts, "implementer"); err != nil { + t.Fatal(err) + } + if !strings.Contains(buf.String(), "matches the embedded") { + t.Errorf("clean diff output: %q", buf.String()) + } + // Edit locally, expect the divergence and the reconciliation line. + p := filepath.Join(dir, "roles", "implementer.md") + data, _ := os.ReadFile(p) + os.WriteFile(p, append(data, []byte("local line\n")...), 0o644) + buf.Reset() + if err := rolesDiff(&buf, dir, fakeContracts, "implementer"); err != nil { + t.Fatal(err) + } + for _, want := range []string{"- local line", "reconcile through a task and PR"} { + if !strings.Contains(buf.String(), want) { + t.Errorf("diff output missing %q:\n%s", want, buf.String()) + } + } + buf.Reset() + if err := rolesShow(&buf, fakeContracts, "qa", true); err != nil { + t.Fatal(err) + } + if buf.String() != "# Role: qa\n" { + t.Errorf("show --latest = %q", buf.String()) + } + if err := rolesShow(&buf, fakeContracts, "qa", false); err == nil { + t.Error("show without --latest accepted") + } + if err := rolesDiff(&buf, dir, fakeContracts, "navigator"); err == nil { + t.Error("unknown role accepted") + } +} diff --git a/internal/cli/status.go b/internal/cli/status.go index 65cb610..d8700e7 100644 --- a/internal/cli/status.go +++ b/internal/cli/status.go @@ -4,6 +4,8 @@ import ( "fmt" "io" + codecrew "github.com/radiusred/gh-codecrew" + "github.com/radiusred/gh-codecrew/internal/config" "github.com/radiusred/gh-codecrew/internal/gh" "github.com/radiusred/gh-codecrew/internal/tracker" @@ -64,5 +66,16 @@ func status(w io.Writer) error { fmt.Fprintf(w, " %s — %s\n", task.Ref, task.Title) } } + + // Contract drift: purely local — the embedded contracts ride the + // binary, so status can say when a hub's roles/ fork has diverged + // from the installed release without touching the network. + if drifted, err := contractDrift(cfg.Dir, codecrew.Roles); err == nil && len(drifted) > 0 { + fmt.Fprintln(w) + for _, role := range drifted { + fmt.Fprintf(w, "contract drift: roles/%s.md differs from the embedded %s contract — codecrew roles diff %s\n", role, version, role) + } + } + return nil }