From 02a416cc73b2e39dfbad0091c874756727bd5f98 Mon Sep 17 00:00:00 2001 From: ecuthiell Date: Thu, 1 Oct 2026 08:46:37 -0600 Subject: [PATCH] fix: make release-version checks shell-free (#5614) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: make release-version checks shell-free (#5533) Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell * fix(release): preserve checker status and explain gate failures (saa-cgh.16) Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * docs: retain release-pinned CLI references (saa-cgh.16) Preserve corrected live preflight help while generated references continue to match docs/cli-docs.pin v1.2.2. Fix the exact two-line hosted docs-policy failure without changing pin authority. Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell * fix(versioncheck): carry base's release gates into the Go checker The base branch gained three release-metadata gates in scripts/check-versions.sh after this PR's merge point (release: prep v1.3.0, b3ef65c854): the Copilot plugin manifest, the four winres.json Windows PE version fields, and manifest.xml's assemblyIdentity version. This PR replaces that shell body with the Go authority, so adopting it as-written would have silently dropped all three — each one guards a file whose bump is a sed anchored on the old value, so a drifted copy no-ops and ships advertising the previous version. Port them into internal/versioncheck so the shell-free checker enforces the same set: - source gains an optional expected() so a surface can derive its required value; the Windows PE numeric fields must be purely numeric and so carry the prerelease-stripped form, and manifest.xml carries the four-part form. - readWinresVersionField reads the nested RT_VERSION resource path through the existing duplicate-key-checked JSON helpers. - readManifestAssemblyVersion anchors on line start, since the XML declaration also carries a version attribute. Also regenerate the Bazel BUILD files (make bazel-sync). cmd/bd/BUILD.bazel enumerates srcs explicitly, so the PR's new preflight_versions.go was missing from it and //cmd/bd:bd_lib failed to compile with `undefined: runBeadsVersionSyncCheck`; gazelle adds that src, the //internal/versioncheck dep edge, and BUILD files for the two new packages. Known follow-up for review: the PR's TestRepositoryReleaseVersionsMatch and TestPrePushHookOrdinaryPushWorksWithSystemBash read repository files directly, so they need `data` runfiles to pass under `bazel test` (advisory lane only). * fix(versioncheck): stop the release gate over-claiming docs coverage; distinguish --expect mismatch Maintainer review fixup for iteration 1 (both findings minor, non-gating; scorecard 915/850 approve with Required Changes: None). Contract & Interface Fidelity (claude + codex): the success line claimed "Version files and released-docs policy pass" while the checker reads no documentation surface, and it replaced the shell predecessor's explicit disclaimer that the docs release line and docs/cli-docs.pin are manual release steps. Restore the base wording ("Version files in sync at: ") plus the disclaimer, and update the three pins in main_test.go. This also repairs a consumer neither review lane censused: the tracked release runbook .beads/formulas/beads-release.formula.toml:475 instructs the operator that the gate "must print `✓ Version files in sync at: ` before you continue" — the renamed string had silently broken that acceptance check. Grepping the new spelling finds nothing; the breakage only shows up when grepping the old one. Error Handling & Resilience (codex): --expect mismatch reused exit 1, so .githooks/pre-push answered a tag/checkout mismatch with the version-drift remedy ("Fix with: scripts/update-versions.sh ") — advice that would rewrite every release surface to the wrong version. Give that case status 3 and add the matching hook branch pointing at CONTRIBUTING's actual rule. Only two --expect call sites exist: release.yml:45 (bare non-zero check, unaffected) and this hook. Verified at this head: check-versions.sh rc=0 (24 green rows, all three ported base gates); exit taxonomy 0/2/3 as documented; go test ./internal/versioncheck/ ./scripts/check-versions/ PASS=65 FAIL=0 SKIP=0; cmd/bd TestTrackedManagedHookSectionsMatchGenerator ok (hook edit sits above the generator-managed markers); gofmt/vet clean. Both fixes proven non-vacuous by mutating each back and requiring red. Declined as out of cleanup scope, recorded for follow-up: making TestRepositoryReleaseVersionsMatch fixture-based (redesigns the PR's own test architecture and interacts with the deliberate untracked-discovery pin at check_test.go:174; harm measured local-only) and declaring bazel data runfiles (gate impact none — no BAZEL key in either CI_GATE_REQUIRED map at this base; the remedy needs root filegroups that touch scripts/bazel_policy_test.go invariants). Co-Authored-By: Claude Opus 5 * test(versioncheck): declare the release-gate tests' repo inputs as Bazel data Base commit e1b2e79484 (#6941) promoted the seven BAZEL* lanes into pr.yml's CI_GATE_REQUIRED after this branch's merge point, so the two packages this PR adds are now graded by a required check. Both reach real repository files through a hand-rolled filepath.Join("..", ".."), which resolves outside the runfiles tree, and `bazel test //...` failed on them: TestRepositoryReleaseVersionsMatch open ../../cmd/bd/version.go: no such file or directory TestPrePushHookOrdinaryPushWorksWithSystemBash runfiles .githooks/pre-push: No such file or directory Resolve the root through internal/testutil/bazeltest.RepoRoot, the base's helper for exactly this, which reduces to the previous behavior under plain `go test`; and declare the inputs as data through a //:release_metadata_files filegroup aggregating the surfaces versioncheck.releaseSources gates, the canonical version it compares them against, the uv.lock pin and the tracked hooks, exported from the packages that own them. The filegroup is hand-listed because releaseSources is itself a closed list: a newly gated surface must be added there too, and until it is the test fails under Bazel. The shell entrypoint's exit-status subtests build the checker from source at the repository root, which cannot work against a runfiles tree that has no go.mod, so they skip under Bazel and keep running under `go test`. The guard sits inside each subtest, not above the loop, so the ordinary-push assertion still reports as run rather than hiding behind a skip. Validation: `go test ./internal/versioncheck/ ./scripts/check-versions/` is unchanged at 65 pass / 0 skip, with all three entrypoint subtests still executing; both targets pass `bazel test --config=ci`; //scripts:scripts_test (the tag-taxonomy and Bazel policy tests) passes; `bazel build //...` is clean across 321 targets; `make bazel-sync` reports no drift and is idempotent. * test(versioncheck): stop declaring the bazelignored npm manifest as Bazel data The required `Bazel / test` lane failed on the refreshed head in fork-PR CI: TestRepositoryReleaseVersionsMatch npm package.json: open .../versioncheck_test.runfiles/_main/ npm-package/package.json: no such file or directory (expected 1.3.0) npm-package/ is in .bazelignore (#6798), so Bazel never links it into the execroot, and a local sandbox cannot stage npm-package/package.json even though //:release_metadata_files named it and analysis accepted the label. It resolved only under remote execution, where the client uploads the file from the workspace. That is how the previous fixup's `bazel test --config=ci` passed on a host whose bazelrc defaults to remote execution. Fork PRs get no remote-execution secrets, so CI runs the test in processwrapper-sandbox, where it fails. Drop the entry from the filegroup. Under Bazel only, let TestRepositoryReleaseVersionsMatch tolerate exactly that surface's absence: the file must be missing, and every other gated surface, the uv.lock pin and the hook markers must pass. The test logs the gap. This mirrors the base's skipReleaseFormulaUnderBazel for the bazelignored .beads/. `go test`, which sees the real checkout, still checks the npm manifest. Validation: forcing local execution the way fork CI runs (`bazel test --config=ci --nocache_test_results --remote_executor= --strategy=TestRunner=processwrapper-sandbox`) reproduced the failure before the change. After it, //internal/versioncheck:versioncheck_test, //scripts/check-versions:check-versions_test and //scripts:scripts_test pass (3 of 3 executed), and both release-gate targets also pass under remote execution. Drifting a declared surface still fails the sandboxed run. The tolerance was probed through TEST_SRCDIR and BEADS_TEST_REPO_ROOT: each of these still fails: - another drifted surface - a present but mismatched npm manifest - an unreadable canonical version - plain `go test` with the manifest missing `go test ./internal/versioncheck/ ./scripts/check-versions/`, golangci-lint and `make bazel-sync-check` are clean. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Gas City Adopt-PR Co-authored-by: Claude Opus 5 --- .githooks/pre-push | 34 +- .github/workflows/main.yml | 6 + .github/workflows/pr.yml | 6 + .github/workflows/release.yml | 18 +- BUILD.bazel | 34 + CHANGELOG.md | 6 + CONTRIBUTING.md | 8 + cmd/bd/BUILD.bazel | 15 + cmd/bd/preflight.go | 99 +- cmd/bd/preflight_test.go | 208 ++++- cmd/bd/preflight_versions.go | 69 ++ internal/versioncheck/BUILD.bazel | 20 + internal/versioncheck/check.go | 923 +++++++++++++++++++ internal/versioncheck/check_test.go | 650 +++++++++++++ plugins/beads/BUILD.bazel | 11 + scripts/BUILD.bazel | 7 + scripts/check-versions.sh | 195 +--- scripts/check-versions/BUILD.bazel | 45 + scripts/check-versions/main.go | 158 ++++ scripts/check-versions/main_test.go | 228 +++++ scripts/check-versions/pre_push_hook_test.go | 83 ++ 21 files changed, 2532 insertions(+), 291 deletions(-) create mode 100644 cmd/bd/preflight_versions.go create mode 100644 internal/versioncheck/BUILD.bazel create mode 100644 internal/versioncheck/check.go create mode 100644 internal/versioncheck/check_test.go create mode 100644 scripts/check-versions/BUILD.bazel create mode 100644 scripts/check-versions/main.go create mode 100644 scripts/check-versions/main_test.go create mode 100644 scripts/check-versions/pre_push_hook_test.go diff --git a/.githooks/pre-push b/.githooks/pre-push index e454f0628..5c6acc315 100755 --- a/.githooks/pre-push +++ b/.githooks/pre-push @@ -26,14 +26,32 @@ if [ "$pushing_version_tag" -eq 1 ]; then repo_root="$(git rev-parse --show-toplevel)" # Skip on older checkouts without the consistency check; do not block. if [ -x "$repo_root/scripts/check-versions.sh" ]; then - echo "Release tag push detected — verifying version consistency..." - if ! (cd "$repo_root" && ./scripts/check-versions.sh); then - echo "" - echo "❌ Refusing to push release tag: versions are inconsistent." >&2 - echo " Fix with: scripts/update-versions.sh " >&2 - echo " Override with --no-verify only if you know what you are doing." >&2 - exit 1 - fi + while read -r local_ref _local_sha _remote_ref _remote_sha; do + case "$local_ref" in + refs/tags/v[0-9]*) + tag_version="${local_ref#refs/tags/v}" + echo "Release tag v$tag_version push detected — verifying version consistency..." + checker_status=0 + (cd "$repo_root" && ./scripts/check-versions.sh --expect "$tag_version") || checker_status=$? + if [ "$checker_status" -ne 0 ]; then + echo "" + if [ "$checker_status" -eq 1 ]; then + echo "❌ Refusing to push release tag v$tag_version: versions are inconsistent." >&2 + echo " Fix with: scripts/update-versions.sh " >&2 + elif [ "$checker_status" -eq 3 ]; then + echo "❌ Refusing to push release tag v$tag_version: the tag does not match this checkout's release version." >&2 + echo " The release surfaces agree with each other, so do NOT re-run update-versions.sh." >&2 + echo " Push only the tag matching this checkout (see CONTRIBUTING.md)." >&2 + else + echo "❌ Refusing to push release tag v$tag_version: version checker unavailable or failed (exit $checker_status)." >&2 + echo " Check the Go toolchain and checker diagnostics above." >&2 + fi + echo " Override with --no-verify only if you know what you are doing." >&2 + exit 1 + fi + ;; + esac + done <<< "$push_refs" fi fi diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 1045f28f3..588cead28 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -190,6 +190,12 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + - name: Set up Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: 'go.mod' + cache: false + - name: Check all versions match run: ./scripts/check-versions.sh diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 517176deb..e8d1389a1 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -478,6 +478,12 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + - name: Set up Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: 'go.mod' + cache: false + - name: Check all versions match run: ./scripts/check-versions.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e9fabb91e..80685e4d5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -35,18 +35,14 @@ jobs: with: fetch-depth: 0 - - name: Verify tag matches version.go - run: | - tag_version="${GITHUB_REF_NAME#v}" - code_version="$(grep 'Version = ' cmd/bd/version.go | sed 's/.*"\(.*\)".*/\1/')" - if [ "$tag_version" != "$code_version" ]; then - echo "ERROR: tag v$tag_version does not match cmd/bd/version.go ($code_version)" >&2 - exit 1 - fi - echo "OK: tag and version.go agree on $code_version" + - name: Set up Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: 'go.mod' + cache: false - - name: Check version consistency - run: ./scripts/check-versions.sh + - name: Verify tag and released versions + run: ./scripts/check-versions.sh --expect "${GITHUB_REF_NAME#v}" release-package-mcp: name: Release Package Gate (MCP) diff --git a/BUILD.bazel b/BUILD.bazel index 55b9cc7e1..b4ebcdbb6 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -120,6 +120,40 @@ filegroup( visibility = ["//scripts:__pkg__"], ) +# //internal/versioncheck and //scripts/check-versions release-gate tests: the +# metadata surfaces versioncheck.releaseSources gates, plus the canonical +# version it compares them against and the tracked git hooks whose version +# markers it checks. +# +# Hand-listed rather than globbed because releaseSources is itself a closed +# list: a newly gated surface must be added here too, and until it is the test +# fails under Bazel (it passes under `go test`, which sees the whole checkout). +# +# The exception is npm-package/package.json: npm-package/ is in .bazelignore, +# so no target can declare it. Listing it anyway passes under remote execution +# but fails in a local sandbox, which is how fork-PR CI runs. +# TestRepositoryReleaseVersionsMatch tolerates exactly its absence under +# Bazel; `go test` still checks it. +filegroup( + name = "release_metadata_files", + srcs = [ + ".claude-plugin/marketplace.json", + "integrations/beads-mcp/pyproject.toml", + "integrations/beads-mcp/src/beads_mcp/__init__.py", + "integrations/beads-mcp/uv.lock", + "//cmd/bd:version.go", + "//cmd/bd:winres/manifest.xml", + "//cmd/bd:winres/winres.json", + "//plugins/beads:.claude-plugin/plugin.json", + "//plugins/beads:.codex-plugin/plugin.json", + "//plugins/beads:.copilot-plugin/plugin.json", + ] + glob([".githooks/*"]), + visibility = [ + "//internal/versioncheck:__pkg__", + "//scripts/check-versions:__pkg__", + ], +) + # Inputs of the Bazel policy tests in //scripts (bazel_policy_test.go), so they # run under `bazel test` as well as `go test`. filegroup( diff --git a/CHANGELOG.md b/CHANGELOG.md index 947fc2325..89e60d86f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- `bd preflight --fix --json` no longer returns a `Version sync` fix result: + version updates must keep all release surfaces aligned via `scripts/update-versions.sh`. +- Release-tag pushes require Go and reject batches containing different release versions. + ### Fixed - **`bd list` no longer silently drops all but the last repeated filter flag.** diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ba3288a57..961a3664c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -315,6 +315,14 @@ dlv debug ./cmd/bd -- create "Test issue" 4. Push tag: `git push origin v0.x.0` 5. GitHub Actions will build and publish +The pre-push version gate requires Go and validates each `v*` release tag +against the checkout's canonical version. A batch containing different release +versions is refused; push only the tag matching this checkout. + +`bd preflight` finds the nearest Beads source module by walking ancestor +directories, checking both source markers and the module identity. Its version +check runs directly in Go; `scripts/check-versions.sh` remains a Bash entrypoint. + ## Questions? - Check existing [issues](https://github.com/gastownhall/beads/issues) diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index 886abb8b0..243834a47 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -243,6 +243,7 @@ go_library( "ping_proxied_server.go", "pour.go", "preflight.go", + "preflight_versions.go", "prime.go", "prime_divergence.go", "prime_proxied_server.go", @@ -430,6 +431,7 @@ go_library( "//internal/uimd", "//internal/utils", "//internal/validation", + "//internal/versioncheck", "//internal/workapi", "//internal/workspacegate", "//internal/worktreeremove", @@ -1290,6 +1292,7 @@ go_test( "//internal/uimd", "//internal/utils", "//internal/validation", + "//internal/versioncheck", "//internal/workapi", "//internal/workspacegate", "//internal/worktreeremove", @@ -1464,6 +1467,18 @@ exports_files( visibility = ["//test/docsync:__pkg__"], ) +# Release-metadata surfaces gated by //internal/versioncheck's releaseSources +# table: the canonical version and the Windows PE resource files. Aggregated +# into //:release_metadata_files, which is what the tests declare as data. +exports_files( + [ + "version.go", + "winres/manifest.xml", + "winres/winres.json", + ], + visibility = ["//:__pkg__"], +) + # --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) --- filegroup( diff --git a/cmd/bd/preflight.go b/cmd/bd/preflight.go index 719404ad9..848bf855c 100644 --- a/cmd/bd/preflight.go +++ b/cmd/bd/preflight.go @@ -78,7 +78,7 @@ const lintCancellationGrace = 10 * time.Second func init() { preflightCmd.Flags().Bool("check", false, "Run checks automatically") - preflightCmd.Flags().Bool("fix", false, "Auto-fix issues where possible (vendorHash, version sync)") + preflightCmd.Flags().Bool("fix", false, "Auto-fix issues where possible (vendorHash)") preflightCmd.Flags().Bool("skip-lint", false, "Skip lint check explicitly") rootCmd.AddCommand(preflightCmd) @@ -131,7 +131,7 @@ func fileExists(dir, name string) bool { // project's language stack, detected from standard marker files in dir. A // project with no recognized stack gets a generic reminder rather than a // misleading Go checklist, and the repo's own Go+Nix specific items -// (gms_pure_go build tags, nix vendorHash, version.go vs default.nix) only +// (gms_pure_go build tags, nix vendorHash, released metadata versions) only // appear where they apply (GH#4364). func buildPreflightChecklist(dir string) []string { // Preserve the exact rich checklist when run inside the beads repo itself @@ -144,7 +144,7 @@ func buildPreflightChecklist(dir string) []string { "Formatting: gofmt -l .", "No beads pollution: check .beads/issues.jsonl diff", "Nix hash current: go.sum unchanged or vendorHash updated", - "Version sync: version.go matches default.nix", + "Version sync: released metadata matches version.go", } } @@ -607,33 +607,19 @@ func runNixHashCheck() CheckResult { } } -// runVersionSyncCheck checks that all version files are in sync. -// Prefers scripts/check-versions.sh (matches CI) with fallback to inline logic. +// runVersionSyncCheck checks that all version files are in sync. Beads uses the +// shared Go authority; unrelated repositories retain the generic Go/Nix check. func runVersionSyncCheck() CheckResult { - command := "scripts/check-versions.sh" - - // Try using the script (matches CI's check-version-consistency job) - if _, err := os.Stat("scripts/check-versions.sh"); err == nil { - cmd := exec.Command("bash", "scripts/check-versions.sh") - output, err := cmd.CombinedOutput() - if err != nil { - return CheckResult{ - Name: "Version sync", - Passed: false, - Output: string(output), - Command: command, - } - } - return CheckResult{ - Name: "Version sync", - Passed: true, - Output: string(output), - Command: command, - } + root, found, rootFailure := resolveBeadsVersionRoot(".") + if rootFailure.Name != "" { + return rootFailure + } + if found { + return runBeadsVersionSyncCheck(root) } - // Fallback: inline comparison of version.go and default.nix - command = "Compare cmd/bd/version.go and default.nix" + // Generic fallback: inline comparison of version.go and default.nix. + command := "Compare cmd/bd/version.go and default.nix" // Read version.go versionGoContent, err := os.ReadFile("cmd/bd/version.go") @@ -773,19 +759,6 @@ func runFixes(jsonOutput bool) error { } results = append(results, nr) - versionFixed, versionOld, versionNew, versionErr := fixVersionSync() - vr := fixResult{Name: "Version sync"} - if versionErr != nil { - vr.Error = versionErr.Error() - hasError = true - } else if versionFixed { - vr.Fixed = true - vr.Detail = fmt.Sprintf("version.go: %s → %s", versionOld, versionNew) - } else { - vr.Skipped = true - } - results = append(results, vr) - if jsonOutput { enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") @@ -910,49 +883,3 @@ func fixNixHash() (bool, string, string, error) { restored = true return true, oldHash, newHash, nil } - -// fixVersionSync updates cmd/bd/version.go to match the version in default.nix. -// default.nix is the source of truth. Returns (fixed, oldVersion, newVersion, err). -func fixVersionSync() (bool, string, string, error) { - vgoPath := "cmd/bd/version.go" - vgoInfo, err := os.Stat(vgoPath) - if err != nil { - return false, "", "", fmt.Errorf("cannot read cmd/bd/version.go: %v", err) - } - vgoPerm := vgoInfo.Mode().Perm() - - vgoContent, err := os.ReadFile(vgoPath) - if err != nil { - return false, "", "", fmt.Errorf("cannot read cmd/bd/version.go: %v", err) - } - - vgoRe := regexp.MustCompile(`(Version\s*=\s*)"([^"]+)"`) - vgoLoc := vgoRe.FindSubmatchIndex(vgoContent) - if vgoLoc == nil { - return false, "", "", fmt.Errorf("cannot parse Version from cmd/bd/version.go") - } - oldVersion := string(vgoContent[vgoLoc[4]:vgoLoc[5]]) - - nixContent, err := os.ReadFile("default.nix") - if err != nil { - // No default.nix — nothing to sync against - return false, "", "", nil - } - - nixRe := regexp.MustCompile(`version\s*=\s*"([^"]+)"`) - nixM := nixRe.FindSubmatch(nixContent) - if nixM == nil { - return false, "", "", fmt.Errorf("cannot parse version from default.nix") - } - newVersion := string(nixM[1]) - - if oldVersion == newVersion { - return false, oldVersion, newVersion, nil - } - - updated := append(append([]byte{}, vgoContent[:vgoLoc[4]]...), append([]byte(newVersion), vgoContent[vgoLoc[5]:]...)...) - if err := os.WriteFile(vgoPath, updated, vgoPerm); err != nil { - return false, oldVersion, newVersion, fmt.Errorf("cannot update cmd/bd/version.go: %v", err) - } - return true, oldVersion, newVersion, nil -} diff --git a/cmd/bd/preflight_test.go b/cmd/bd/preflight_test.go index 5be1f4b59..4f7e54b3f 100644 --- a/cmd/bd/preflight_test.go +++ b/cmd/bd/preflight_test.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "errors" "os" "os/exec" "path/filepath" @@ -12,6 +13,7 @@ import ( "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/testutil/bazeltest" + "github.com/steveyegge/beads/internal/versioncheck" ) func TestCheckResult_Passed(t *testing.T) { @@ -419,31 +421,213 @@ func TestRunBeadsPollutionCheck_Clean(t *testing.T) { } } -func TestRunVersionSyncCheck_ScriptFallback(t *testing.T) { - // Run from a temp dir where scripts/check-versions.sh does not exist. - // The fallback inline logic should be used, resulting in a skipped result - // because version.go won't be found either. +func TestRunVersionSyncCheck_GenericFallback(t *testing.T) { + // An unrelated directory retains the generic inline Go/Nix behavior. origDir, err := os.Getwd() if err != nil { t.Fatal(err) } dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "cmd", "bd"), 0o755); err != nil { + t.Fatal(err) + } + for path, content := range map[string]string{ + "go.mod": "module example.com/unrelated\n\ngo 1.26.5\n", + "cmd/bd/version.go": "package main\n\nvar Version = \"2.3.4\"\n", + "default.nix": "{ version = \"2.3.4\"; }\n", + } { + if err := os.WriteFile( + filepath.Join(dir, filepath.FromSlash(path)), + []byte(content), + 0o644, + ); err != nil { + t.Fatal(err) + } + } if err := os.Chdir(dir); err != nil { t.Fatal(err) } defer os.Chdir(origDir) result := runVersionSyncCheck() - // Without version.go present, fallback should skip - if !result.Skipped { - // Could also pass if default.nix is also missing — both are acceptable fallback outcomes - if result.Passed && strings.Contains(result.Output, "not found") { - return // acceptable: nix not found skip + if !result.Passed || result.Skipped { + t.Fatalf("generic version fallback failed: %+v", result) + } + if result.Command != "Compare cmd/bd/version.go and default.nix" { + t.Fatalf("command = %q, want generic fallback", result.Command) + } + + if err := os.WriteFile( + filepath.Join(dir, "default.nix"), + []byte("{ version = \"9.9.9\"; }\n"), + 0o644, + ); err != nil { + t.Fatal(err) + } + result = runVersionSyncCheck() + if result.Passed || !strings.Contains(result.Output, "version.go=2.3.4, default.nix=9.9.9") { + t.Fatalf("generic mismatch was not preserved: %+v", result) + } +} + +func TestRunVersionSyncCheck_BeadsUsesBuiltInAuthority(t *testing.T) { + root := writeBeadsVersionFixture(t, "1.1.0") + // The historical entrypoint is intentionally hostile: production preflight + // must use the Go package directly, not execute this file or ambient bash. + if err := os.WriteFile( + filepath.Join(root, "scripts", "check-versions.sh"), + []byte("#!/bin/sh\nexit 86\n"), + 0o755, + ); err != nil { + t.Fatal(err) + } + + originalDirectory, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + if err := os.Chdir(root); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chdir(originalDirectory) }) + t.Setenv("PATH", "") + + result := runVersionSyncCheck() + if !result.Passed { + t.Fatalf("built-in Beads version check failed: %s", result.Output) + } + if result.Command != "built-in Beads release version check" { + t.Fatalf("command = %q, want built-in authority", result.Command) + } + + if err := os.WriteFile( + filepath.Join(root, "npm-package", "package.json"), + []byte(`{"version":"9.9.9"}`), + 0o644, + ); err != nil { + t.Fatal(err) + } + result = runVersionSyncCheck() + if result.Passed { + t.Fatal("mismatched released metadata unexpectedly passed") + } + if !strings.Contains(result.Output, "npm package.json: 9.9.9 (expected 1.1.0)") { + t.Fatalf("unexpected mismatch output: %q", result.Output) + } + + if err := os.WriteFile( + filepath.Join(root, "npm-package", "package.json"), + []byte(`{"version":"1.1.0"}`), + 0o644, + ); err != nil { + t.Fatal(err) + } + if err := os.WriteFile( + filepath.Join(root, ".githooks", "pre-push"), + []byte( + "# --- BEGIN BEADS INTEGRATION v9.9.9 ---\n"+ + "body\n# --- END BEADS INTEGRATION v1.1.0 ---\n", + ), + 0o755, + ); err != nil { + t.Fatal(err) + } + result = runVersionSyncCheck() + if result.Passed { + t.Fatal("mismatched tracked hook marker unexpectedly passed") + } + if !strings.Contains( + result.Output, + ".githooks/pre-push BEGIN marker: 9.9.9 (expected 1.1.0)", + ) { + t.Fatalf("unexpected tracked-hook mismatch output: %q", result.Output) + } +} + +func TestRunBeadsVersionSyncCheck_UVLockFreshness(t *testing.T) { + root := writeBeadsVersionFixture(t, "1.1.0") + tests := []struct { + name string + check versioncheck.UVLockChecker + wantPassed bool + wantContain string + wantAbsent string + }{ + { + name: "uv unavailable is a soft skip", + check: func(string) (bool, error) { return false, nil }, + wantPassed: true, + wantAbsent: "uv lock --check", + }, + { + name: "fresh lock passes", + check: func(string) (bool, error) { return true, nil }, + wantPassed: true, + wantContain: "MCP uv.lock: fresh (uv lock --check)", + }, + { + name: "stale lock fails", + check: func(string) (bool, error) { + return true, errors.New("lockfile needs regeneration") + }, + wantPassed: false, + wantContain: "MCP uv.lock: stale — run: uv lock --directory integrations/beads-mcp", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + result := runBeadsVersionSyncCheckWithUV(root, test.check) + if result.Passed != test.wantPassed { + t.Fatalf("Passed = %v, want %v; result: %+v", result.Passed, test.wantPassed, result) + } + if !strings.Contains(result.Output, test.wantContain) { + t.Fatalf("Output = %q, want substring %q", result.Output, test.wantContain) + } + if test.wantAbsent != "" && strings.Contains(result.Output, test.wantAbsent) { + t.Fatalf("Output = %q, want %q absent", result.Output, test.wantAbsent) + } + }) + } +} + +func writeBeadsVersionFixture(t *testing.T, version string) string { + t.Helper() + root := t.TempDir() + // The Windows PE numeric fields must be purely numeric, so they carry the + // prerelease-stripped form. + base, _, _ := strings.Cut(version, "-") + files := map[string]string{ + "go.mod": "module github.com/steveyegge/beads\n\ngo 1.26.5\n", + "cmd/bd/version.go": "package main\n\nvar Version = \"" + version + "\"\n", + "scripts/update-versions.sh": "#!/bin/sh\n", + "integrations/beads-mcp/pyproject.toml": "[project]\nversion = \"" + version + "\"\n", + "integrations/beads-mcp/src/beads_mcp/__init__.py": "__version__ = \"" + version + "\"\n", + "integrations/beads-mcp/uv.lock": "[[package]]\nname = \"beads-mcp\"\nversion = \"" + version + "\"\n", + "plugins/beads/.claude-plugin/plugin.json": `{"version":"` + version + `"}`, + "plugins/beads/.codex-plugin/plugin.json": `{"version":"` + version + `"}`, + ".claude-plugin/marketplace.json": `{"plugins":[{"version":"` + version + `"}]}`, + "npm-package/package.json": `{"version":"` + version + `"}`, + "plugins/beads/.copilot-plugin/plugin.json": `{"version":"` + version + `"}`, + "cmd/bd/winres/winres.json": `{"RT_VERSION":{"#1":{"0000":{` + + `"fixed":{"file_version":"` + base + `","product_version":"` + base + `"},` + + `"info":{"0409":{"FileVersion":"` + version + + `","ProductVersion":"` + version + `"}}}}}}`, + "cmd/bd/winres/manifest.xml": "\n" + + "\n \n\n", + ".githooks/pre-push": "# --- BEGIN BEADS INTEGRATION v" + version + " ---\n" + + "body\n# --- END BEADS INTEGRATION v" + version + " ---\n", + } + for relativePath, content := range files { + path := filepath.Join(root, filepath.FromSlash(relativePath)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatalf("create parent for %s: %v", relativePath, err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatalf("write %s: %v", relativePath, err) } } - if result.Command == "scripts/check-versions.sh" { - t.Fatal("expected fallback logic, not script invocation") - } + return root } // writeMarkerDir creates a temp dir containing the given marker files (each diff --git a/cmd/bd/preflight_versions.go b/cmd/bd/preflight_versions.go new file mode 100644 index 000000000..199c6bd86 --- /dev/null +++ b/cmd/bd/preflight_versions.go @@ -0,0 +1,69 @@ +package main + +import ( + "fmt" + + "github.com/steveyegge/beads/internal/versioncheck" +) + +func runBeadsVersionSyncCheck(root string) CheckResult { + return runBeadsVersionSyncCheckWithUV( + root, + versioncheck.CheckUVLockFreshness, + ) +} + +func runBeadsVersionSyncCheckWithUV( + root string, + checkUVLock versioncheck.UVLockChecker, +) CheckResult { + report, err := versioncheck.Check(root) + if err != nil { + output := err.Error() + if report.CanonicalVersion != "" { + output += "\nRun: scripts/update-versions.sh " + report.CanonicalVersion + } + return CheckResult{ + Name: "Version sync", + Passed: false, + Output: output, + Command: versioncheck.CommandDescription, + } + } + uvAvailable := false + if checkUVLock != nil { + var uvErr error + uvAvailable, uvErr = checkUVLock(root) + if uvAvailable && uvErr != nil { + return CheckResult{ + Name: "Version sync", + Passed: false, + Output: "MCP uv.lock: stale — run: uv lock --directory integrations/beads-mcp", + Command: versioncheck.CommandDescription, + } + } + } + output := report.SuccessMessage() + if uvAvailable { + output += "\nMCP uv.lock: fresh (uv lock --check)" + } + return CheckResult{ + Name: "Version sync", + Passed: true, + Output: output, + Command: versioncheck.CommandDescription, + } +} + +func resolveBeadsVersionRoot(start string) (string, bool, CheckResult) { + root, found, err := versioncheck.FindRoot(start) + if err == nil { + return root, found, CheckResult{} + } + return "", false, CheckResult{ + Name: "Version sync", + Passed: false, + Output: fmt.Sprintf("Cannot identify Beads release root: %v", err), + Command: versioncheck.CommandDescription, + } +} diff --git a/internal/versioncheck/BUILD.bazel b/internal/versioncheck/BUILD.bazel new file mode 100644 index 000000000..b439bcb54 --- /dev/null +++ b/internal/versioncheck/BUILD.bazel @@ -0,0 +1,20 @@ +load("@rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "versioncheck", + srcs = ["check.go"], + importpath = "github.com/steveyegge/beads/internal/versioncheck", + visibility = ["//:__subpackages__"], + deps = [ + "@com_github_burntsushi_toml//:toml", + "@org_golang_x_mod//modfile", + ], +) + +go_test( + name = "versioncheck_test", + srcs = ["check_test.go"], + data = ["//:release_metadata_files"], + embed = [":versioncheck"], + deps = ["//internal/testutil/bazeltest"], +) diff --git a/internal/versioncheck/check.go b/internal/versioncheck/check.go new file mode 100644 index 000000000..2d6f92f7f --- /dev/null +++ b/internal/versioncheck/check.go @@ -0,0 +1,923 @@ +package versioncheck + +import ( + "bytes" + "encoding/json" + "fmt" + "go/ast" + "go/parser" + "go/token" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "sort" + "strconv" + "strings" + + "github.com/BurntSushi/toml" + "golang.org/x/mod/modfile" +) + +const ( + // ModulePath identifies the Beads source module. + ModulePath = "github.com/steveyegge/beads" + + // CommandDescription is the stable preflight description for this checker. + CommandDescription = "built-in Beads release version check" +) + +type source struct { + path string + description string + read func(string) (string, error) + // expected derives the required value from the canonical version. A nil + // expected means the surface must carry the canonical version verbatim; + // the Windows PE numeric fields must be purely numeric, so they derive a + // prerelease-stripped form instead. + expected func(canonical string) string +} + +// SourceResult describes one metadata surface inspected by Check. +type SourceResult struct { + Description string + Version string + Expected string + Problem string +} + +// UVLockChecker runs the optional dependency-freshness check. The bool reports +// whether uv was available; an unavailable uv is a soft skip. +type UVLockChecker func(root string) (available bool, err error) + +var releaseSources = []source{ + { + path: "integrations/beads-mcp/pyproject.toml", + description: "MCP pyproject.toml", + read: readProjectTOMLVersion, + }, + { + path: "integrations/beads-mcp/src/beads_mcp/__init__.py", + description: "MCP __init__.py", + read: readPythonModuleVersion, + }, + { + path: "plugins/beads/.claude-plugin/plugin.json", + description: "Claude plugin.json", + read: readTopLevelJSONVersion, + }, + { + path: "plugins/beads/.codex-plugin/plugin.json", + description: "Codex plugin.json", + read: readTopLevelJSONVersion, + }, + { + path: ".claude-plugin/marketplace.json", + description: "Claude marketplace.json", + read: readMarketplaceJSONVersion, + }, + { + path: "npm-package/package.json", + description: "npm package.json", + read: readTopLevelJSONVersion, + }, + // update-versions.sh bumps this one too, but it was never gated before — + // so a drifted copilot manifest (the same drift class that carried stale + // .githooks markers through v1.2.0) would silently no-op the bump's + // old->new sed, pass this check, pass the pre-push hook and CI, and ship + // advertising the previous version. + { + path: "plugins/beads/.copilot-plugin/plugin.json", + description: "Copilot plugin.json", + read: readTopLevelJSONVersion, + }, + // Windows PE resource metadata. gen-winres.sh re-derives winres.json's + // numeric fields from version.go at build time, so those self-heal — but + // manifest.xml's version is embedded verbatim with no + // backstop, and update-versions.sh rewrites both with a sed anchored on + // the OLD value, so a drifted file is a silent no-op. Gate them. + { + path: "cmd/bd/winres/winres.json", + description: "winres.json file_version", + read: readWinresVersionField("RT_VERSION", "#1", "0000", "fixed", "file_version"), + expected: baseVersion, + }, + { + path: "cmd/bd/winres/winres.json", + description: "winres.json product_version", + read: readWinresVersionField("RT_VERSION", "#1", "0000", "fixed", "product_version"), + expected: baseVersion, + }, + { + path: "cmd/bd/winres/winres.json", + description: "winres.json FileVersion", + read: readWinresVersionField("RT_VERSION", "#1", "0000", "info", "0409", "FileVersion"), + }, + { + path: "cmd/bd/winres/winres.json", + description: "winres.json ProductVersion", + read: readWinresVersionField("RT_VERSION", "#1", "0000", "info", "0409", "ProductVersion"), + }, + { + path: "cmd/bd/winres/manifest.xml", + description: "manifest.xml assemblyIdentity version", + read: readManifestAssemblyVersion, + expected: assemblyIdentityVersion, + }, +} + +// manifestAssemblyVersionPattern anchors on line start: the XML declaration on +// line 1 also carries a version="1.0" attribute. +var manifestAssemblyVersionPattern = regexp.MustCompile(`(?m)^[ \t]*version="([0-9][^"]*)"`) + +var trackedHookMarkerPatterns = []struct { + name string + pattern *regexp.Regexp +}{ + { + name: "BEGIN", + pattern: regexp.MustCompile(`--- BEGIN BEADS INTEGRATION v([^ ]+) ---`), + }, + { + name: "END", + pattern: regexp.MustCompile(`--- END BEADS INTEGRATION v([^ ]+) ---`), + }, +} + +// Report describes a successful or failed release-version check. +type Report struct { + CanonicalVersion string + CheckedSources int + CheckedHookMarkers int + Sources []SourceResult +} + +// SuccessMessage formats the stable human-readable success result. +func (r Report) SuccessMessage() string { + return fmt.Sprintf( + "Versions match across %d release metadata checks, MCP uv.lock, and %d tracked hook markers: %s", + r.CheckedSources, + r.CheckedHookMarkers, + r.CanonicalVersion, + ) +} + +// Check compares every released metadata surface with cmd/bd/version.go. +func Check(root string) (Report, error) { + report := Report{CheckedSources: len(releaseSources)} + canonicalPath := filepath.Join(root, "cmd", "bd", "version.go") + canonical, err := readGoPackageVersion(canonicalPath) + if err != nil { + return report, fmt.Errorf( + "cannot read canonical version from cmd/bd/version.go: %w", + err, + ) + } + report.CanonicalVersion = canonical + + var problems []string + for _, item := range releaseSources { + expected := canonical + if item.expected != nil { + expected = item.expected(canonical) + } + version, readErr := item.read(filepath.Join(root, filepath.FromSlash(item.path))) + result := SourceResult{ + Description: item.description, + Version: version, + Expected: expected, + } + switch { + case readErr != nil: + result.Problem = readErr.Error() + problems = append( + problems, + fmt.Sprintf("%s: %v (expected %s)", item.description, readErr, expected), + ) + case version != expected: + result.Problem = fmt.Sprintf("version is %s", version) + problems = append( + problems, + fmt.Sprintf("%s: %s (expected %s)", item.description, version, expected), + ) + } + report.Sources = append(report.Sources, result) + } + + // uv.lock is not one of the six published metadata surfaces, but the + // existing release gate also requires its local beads-mcp package pin to + // match. Preserve that assertion without expanding the release inventory. + lockExpected := normalizePythonVersion(canonical) + lockVersion, lockErr := readUVLockPackageVersion( + filepath.Join(root, "integrations", "beads-mcp", "uv.lock"), + ) + lockResult := SourceResult{ + Description: "MCP uv.lock (beads-mcp pin)", + Version: lockVersion, + Expected: lockExpected, + } + switch { + case lockErr != nil: + lockResult.Problem = lockErr.Error() + problems = append( + problems, + fmt.Sprintf("%s: %v (expected %s)", lockResult.Description, lockErr, lockExpected), + ) + case lockVersion != lockExpected: + lockResult.Problem = fmt.Sprintf("version is %s", lockVersion) + problems = append( + problems, + fmt.Sprintf("%s: %s (expected %s)", lockResult.Description, lockVersion, lockExpected), + ) + } + report.Sources = append(report.Sources, lockResult) + + hookResults, hookProblems := checkTrackedHookMarkers(root, canonical) + report.CheckedHookMarkers = len(hookResults) + report.Sources = append(report.Sources, hookResults...) + problems = append(problems, hookProblems...) + + if len(problems) != 0 { + return report, fmt.Errorf( + "version mismatch detected:\n- %s", + strings.Join(problems, "\n- "), + ) + } + return report, nil +} + +func checkTrackedHookMarkers(root, canonical string) ([]SourceResult, []string) { + hooksDir := filepath.Join(root, ".githooks") + entries, err := os.ReadDir(hooksDir) + if err != nil { + if os.IsNotExist(err) { + return nil, nil + } + return nil, []string{fmt.Sprintf("enumerate tracked git hooks: %v", err)} + } + + var results []SourceResult + var problems []string + for _, entry := range entries { + // Match the shell's .githooks/* expansion: leading-dot artifacts are + // not tracked hooks and are not rewritten by update-versions.sh. + if strings.HasPrefix(entry.Name(), ".") { + continue + } + path := filepath.Join(hooksDir, entry.Name()) + info, statErr := os.Stat(path) + if statErr != nil || !info.Mode().IsRegular() { + continue + } + + relative, relErr := filepath.Rel(root, path) + if relErr != nil { + relative = path + } + relative = filepath.ToSlash(relative) + + content, readErr := os.ReadFile(path) //nolint:gosec // path comes from the bounded .githooks directory + + for _, marker := range trackedHookMarkerPatterns { + description := relative + " " + marker.name + " marker" + result := SourceResult{ + Description: description, + Expected: canonical, + } + switch { + case readErr != nil: + result.Problem = readErr.Error() + problems = append( + problems, + fmt.Sprintf("%s: %v (expected %s)", description, readErr, canonical), + ) + default: + version, found := firstHookMarkerVersion(content, marker.pattern) + result.Version = version + switch { + case !found: + result.Problem = fmt.Sprintf( + "no '%s BEADS INTEGRATION' marker found", + marker.name, + ) + problems = append( + problems, + fmt.Sprintf("%s: %s", description, result.Problem), + ) + case version != canonical: + result.Problem = fmt.Sprintf("version is %s", version) + problems = append( + problems, + fmt.Sprintf("%s: %s (expected %s)", description, version, canonical), + ) + } + } + results = append(results, result) + } + } + return results, problems +} + +func firstHookMarkerVersion(content []byte, pattern *regexp.Regexp) (string, bool) { + for _, line := range bytes.Split(content, []byte{'\n'}) { + match := pattern.FindSubmatch(line) + if len(match) == 2 { + return string(match[1]), true + } + } + return "", false +} + +func normalizePythonVersion(version string) string { + version = strings.Replace(version, "-rc.", "rc", 1) + return strings.Replace(version, "-rc", "rc", 1) +} + +// CheckUVLockFreshness runs uv directly, without selecting a shell. A missing +// uv executable is an intentional soft skip; an available uv returning an +// error means the checked-in lockfile is stale or otherwise invalid. +func CheckUVLockFreshness(root string) (bool, error) { + uv, err := exec.LookPath("uv") + if err != nil { + return false, nil + } + cmd := exec.Command( + uv, + "lock", + "--check", + "--directory", + filepath.Join(root, "integrations", "beads-mcp"), + ) + return true, cmd.Run() +} + +// FindRoot walks from start toward the filesystem root and identifies the +// nearest Beads source module. A Beads-shaped root with missing, malformed, or +// conflicting module identity is an error rather than an unrelated project. +func FindRoot(start string) (string, bool, error) { + current, err := filepath.Abs(start) + if err != nil { + return "", false, fmt.Errorf("resolve start directory: %w", err) + } + current, err = filepath.EvalSymlinks(current) + if err != nil { + return "", false, fmt.Errorf("resolve start directory symlinks: %w", err) + } + for { + signature, signatureErr := hasBeadsSourceSignature(current) + if signatureErr != nil { + return "", false, signatureErr + } + + goModPath := filepath.Join(current, "go.mod") + content, readErr := os.ReadFile(goModPath) //nolint:gosec // path is derived from the bounded ancestor walk + switch { + case readErr == nil: + modulePath, parseErr := readModulePath(content) + if parseErr != nil { + if signature { + return "", false, fmt.Errorf( + "Beads-shaped source root %s has malformed go.mod: %w", + current, + parseErr, + ) + } + return "", false, nil + } + if modulePath == ModulePath { + return current, true, nil + } + if signature { + return "", false, fmt.Errorf( + "Beads-shaped source root %s declares module %q, want %q", + current, + modulePath, + ModulePath, + ) + } + return "", false, nil + case !os.IsNotExist(readErr): + return "", false, fmt.Errorf("inspect %s: %w", goModPath, readErr) + case signature: + return "", false, fmt.Errorf( + "Beads-shaped source root %s is missing go.mod", + current, + ) + } + + parent := filepath.Dir(current) + if parent == current { + return "", false, nil + } + current = parent + } +} + +func hasBeadsSourceSignature(root string) (bool, error) { + paths := []string{ + filepath.Join(root, "cmd", "bd", "version.go"), + filepath.Join(root, "scripts", "update-versions.sh"), + filepath.Join(root, "integrations", "beads-mcp", "pyproject.toml"), + filepath.Join(root, "plugins", "beads", ".codex-plugin", "plugin.json"), + } + found := 0 + for _, path := range paths { + info, err := os.Stat(path) + switch { + case err == nil && info.Mode().IsRegular(): + found++ + case err == nil: + continue + case os.IsNotExist(err): + continue + default: + return false, fmt.Errorf("inspect Beads source marker %s: %w", path, err) + } + } + return found >= 2, nil +} + +func readModulePath(content []byte) (string, error) { + file, err := modfile.Parse("go.mod", content, nil) + if err != nil { + return "", fmt.Errorf("parse go.mod: %w", err) + } + if file.Module == nil { + return "", fmt.Errorf("module directive not found") + } + return file.Module.Mod.Path, nil +} + +func readGoPackageVersion(path string) (string, error) { + file, err := parser.ParseFile(token.NewFileSet(), path, nil, 0) + if err != nil { + return "", fmt.Errorf("parse Go: %w", err) + } + var versions []string + for _, declaration := range file.Decls { + general, ok := declaration.(*ast.GenDecl) + if !ok { + continue + } + for _, specification := range general.Specs { + values, ok := specification.(*ast.ValueSpec) + if !ok { + continue + } + for index, name := range values.Names { + if name.Name != "Version" { + continue + } + if index >= len(values.Values) { + return "", fmt.Errorf("package-level Version has no direct value") + } + literal, ok := values.Values[index].(*ast.BasicLit) + if !ok || literal.Kind != token.STRING { + return "", fmt.Errorf("package-level Version must be a string literal") + } + value, unquoteErr := strconv.Unquote(literal.Value) + if unquoteErr != nil { + return "", fmt.Errorf("parse package-level Version: %w", unquoteErr) + } + versions = append(versions, value) + } + } + } + if len(versions) != 1 { + return "", fmt.Errorf( + "found %d package-level Version string assignments, want exactly one", + len(versions), + ) + } + return versions[0], nil +} + +func readProjectTOMLVersion(path string) (string, error) { + var document map[string]any + if _, err := toml.DecodeFile(path, &document); err != nil { + return "", fmt.Errorf("parse TOML: %w", err) + } + + projectValue, found, err := readExactTOMLField(document, "project", "[project]") + if err != nil { + return "", err + } + if !found { + return "", fmt.Errorf("non-empty string field [project].version not found") + } + project, ok := projectValue.(map[string]any) + if !ok { + return "", fmt.Errorf("field [project] must be a table") + } + + versionValue, found, err := readExactTOMLField( + project, + "version", + "[project].version", + ) + if err != nil { + return "", err + } + if !found { + return "", fmt.Errorf("non-empty string field [project].version not found") + } + version, ok := versionValue.(string) + if !ok { + return "", fmt.Errorf("field [project].version must be a string") + } + if version == "" { + return "", fmt.Errorf("non-empty string field [project].version not found") + } + return version, nil +} + +func readUVLockPackageVersion(path string) (string, error) { + var document map[string]any + if _, err := toml.DecodeFile(path, &document); err != nil { + return "", fmt.Errorf("parse TOML: %w", err) + } + + packageValue, found, err := readExactTOMLField(document, "package", "[[package]]") + if err != nil { + return "", err + } + if !found { + return "", fmt.Errorf("package entries not found") + } + packages, ok := packageValue.([]map[string]any) + if !ok { + return "", fmt.Errorf("field [[package]] must be an array of tables") + } + + var versions []string + for index, item := range packages { + qualified := fmt.Sprintf("[[package]][%d]", index) + nameValue, nameFound, nameErr := readExactTOMLField(item, "name", qualified+".name") + if nameErr != nil { + return "", nameErr + } + if !nameFound { + return "", fmt.Errorf("non-empty string field %s.name not found", qualified) + } + name, ok := nameValue.(string) + if !ok || name == "" { + return "", fmt.Errorf("field %s.name must be a non-empty string", qualified) + } + if name != "beads-mcp" { + continue + } + + versionValue, versionFound, versionErr := readExactTOMLField( + item, + "version", + qualified+".version", + ) + if versionErr != nil { + return "", versionErr + } + if !versionFound { + return "", fmt.Errorf("non-empty string field %s.version not found", qualified) + } + version, ok := versionValue.(string) + if !ok || version == "" { + return "", fmt.Errorf("field %s.version must be a non-empty string", qualified) + } + versions = append(versions, version) + } + if len(versions) != 1 { + return "", fmt.Errorf( + "found %d beads-mcp package entries, want exactly one", + len(versions), + ) + } + return versions[0], nil +} + +func readExactTOMLField( + table map[string]any, + name string, + qualifiedName string, +) (any, bool, error) { + var aliases []string + for candidate := range table { + if strings.EqualFold(candidate, name) { + aliases = append(aliases, candidate) + } + } + if len(aliases) == 0 { + return nil, false, nil + } + sort.Strings(aliases) + if len(aliases) != 1 || aliases[0] != name { + quoted := make([]string, len(aliases)) + for index, alias := range aliases { + quoted[index] = strconv.Quote(alias) + } + return nil, false, fmt.Errorf( + "field %s is ambiguous or uses non-exact casing: %s", + qualifiedName, + strings.Join(quoted, ", "), + ) + } + return table[name], true, nil +} + +func readPythonModuleVersion(path string) (string, error) { + content, err := os.ReadFile(path) //nolint:gosec // callers supply fixed repository-relative paths + if err != nil { + return "", err + } + + var ( + tripleQuote string + versions []string + ) + for lineNumber, line := range strings.Split(string(content), "\n") { + if tripleQuote == "" && strings.HasPrefix(line, "__version__") { + version, matched, parseErr := parsePythonVersionAssignment(line) + if parseErr != nil { + return "", fmt.Errorf("line %d: %w", lineNumber+1, parseErr) + } + if matched { + versions = append(versions, version) + continue + } + } + tripleQuote = scanPythonTripleQuotedState(line, tripleQuote) + } + if len(versions) != 1 { + return "", fmt.Errorf( + "found %d module-level __version__ string assignments, want exactly one", + len(versions), + ) + } + return versions[0], nil +} + +func parsePythonVersionAssignment(line string) (string, bool, error) { + const name = "__version__" + if !strings.HasPrefix(line, name) { + return "", false, nil + } + rest := line[len(name):] + if rest != "" && !strings.ContainsRune(" \t=", rune(rest[0])) { + return "", false, nil + } + rest = strings.TrimLeft(rest, " \t") + if !strings.HasPrefix(rest, "=") || strings.HasPrefix(rest, "==") { + return "", true, fmt.Errorf("%s must use a direct assignment", name) + } + rest = strings.TrimLeft(rest[1:], " \t") + if len(rest) < 2 || (rest[0] != '"' && rest[0] != '\'') { + return "", true, fmt.Errorf("%s must be assigned a string literal", name) + } + quote := rest[0] + end := -1 + for index := 1; index < len(rest); index++ { + if rest[index] == '\\' { + index++ + continue + } + if rest[index] == quote { + end = index + break + } + } + if end < 0 { + return "", true, fmt.Errorf("%s has an unterminated string literal", name) + } + literal := rest[:end+1] + if strings.Contains(literal, `\`) { + return "", true, fmt.Errorf("%s must not use escape sequences", name) + } + value := literal[1 : len(literal)-1] + trailing := strings.TrimSpace(rest[end+1:]) + if trailing != "" && !strings.HasPrefix(trailing, "#") { + return "", true, fmt.Errorf("%s has unexpected trailing syntax", name) + } + if value == "" { + return "", true, fmt.Errorf("%s must be non-empty", name) + } + return value, true, nil +} + +func scanPythonTripleQuotedState(line, active string) string { + for index := 0; index < len(line); { + if active != "" { + end := findUnescaped(line, active, index) + if end < 0 { + return active + } + index = end + len(active) + active = "" + continue + } + if line[index] == '#' { + return "" + } + if line[index] != '\'' && line[index] != '"' { + index++ + continue + } + quote := line[index] + if index+2 < len(line) && line[index+1] == quote && line[index+2] == quote { + active = line[index : index+3] + index += 3 + continue + } + index++ + for index < len(line) { + if line[index] == '\\' { + index += 2 + continue + } + if index < len(line) && line[index] == quote { + index++ + break + } + index++ + } + } + return active +} + +func findUnescaped(value, needle string, start int) int { + for { + index := strings.Index(value[start:], needle) + if index < 0 { + return -1 + } + index += start + backslashes := 0 + for position := index - 1; position >= 0 && value[position] == '\\'; position-- { + backslashes++ + } + if backslashes%2 == 0 { + return index + } + start = index + 1 + } +} + +// baseVersion strips the prerelease suffix, so 1.1.0-rc.1 becomes 1.1.0. The +// Windows PE numeric fields must be purely numeric, so they carry this rather +// than the canonical version. +func baseVersion(canonical string) string { + base, _, _ := strings.Cut(canonical, "-") + return base +} + +// assemblyIdentityVersion renders the four-part form manifest.xml embeds. +func assemblyIdentityVersion(canonical string) string { + return baseVersion(canonical) + ".0" +} + +// readWinresVersionField reads one nested string field from winres.json, whose +// version values sit under a fixed RT_VERSION resource path. +func readWinresVersionField(keys ...string) func(string) (string, error) { + return func(path string) (string, error) { + content, err := os.ReadFile(path) //nolint:gosec // callers supply fixed repository-relative paths + if err != nil { + return "", err + } + return readNestedUniqueJSONString(content, keys...) + } +} + +func readNestedUniqueJSONString(document []byte, keys ...string) (string, error) { + current := json.RawMessage(document) + for _, key := range keys[:len(keys)-1] { + next, err := readUniqueJSONField(current, key) + if err != nil { + return "", err + } + current = next + } + field := keys[len(keys)-1] + version, err := readUniqueJSONStringField(current, field) + if err != nil { + return "", err + } + if version == "" { + return "", fmt.Errorf("non-empty string field .%s not found", strings.Join(keys, ".")) + } + return version, nil +} + +func readManifestAssemblyVersion(path string) (string, error) { + content, err := os.ReadFile(path) //nolint:gosec // callers supply fixed repository-relative paths + if err != nil { + return "", err + } + match := manifestAssemblyVersionPattern.FindSubmatch(content) + if match == nil { + return "", fmt.Errorf("no assemblyIdentity version attribute found") + } + return string(match[1]), nil +} + +func readTopLevelJSONVersion(path string) (string, error) { + content, err := os.ReadFile(path) //nolint:gosec // callers supply fixed repository-relative paths + if err != nil { + return "", err + } + version, err := readUniqueJSONStringField(content, "version") + if err != nil { + return "", err + } + if version == "" { + return "", fmt.Errorf("non-empty string field .version not found") + } + return version, nil +} + +func readMarketplaceJSONVersion(path string) (string, error) { + content, err := os.ReadFile(path) //nolint:gosec // callers supply fixed repository-relative paths + if err != nil { + return "", err + } + pluginsJSON, err := readUniqueJSONField(content, "plugins") + if err != nil { + return "", err + } + var plugins []json.RawMessage + if err := json.Unmarshal(pluginsJSON, &plugins); err != nil { + return "", fmt.Errorf("parse JSON field .plugins: %w", err) + } + if len(plugins) == 0 { + return "", fmt.Errorf("non-empty string field .plugins[0].version not found") + } + version, err := readUniqueJSONStringField(plugins[0], "version") + if err != nil { + return "", fmt.Errorf(".plugins[0]: %w", err) + } + if version == "" { + return "", fmt.Errorf("non-empty string field .plugins[0].version not found") + } + return version, nil +} + +func readUniqueJSONStringField(document []byte, field string) (string, error) { + raw, err := readUniqueJSONField(document, field) + if err != nil { + return "", err + } + var value string + if err := json.Unmarshal(raw, &value); err != nil { + return "", fmt.Errorf("field .%s must be a string: %w", field, err) + } + return value, nil +} + +func readUniqueJSONField(document []byte, field string) (json.RawMessage, error) { + decoder := json.NewDecoder(bytes.NewReader(document)) + start, err := decoder.Token() + if err != nil { + return nil, fmt.Errorf("parse JSON: %w", err) + } + if start != json.Delim('{') { + return nil, fmt.Errorf("parse JSON: top-level value must be an object") + } + + var ( + found bool + value json.RawMessage + ) + for decoder.More() { + keyToken, err := decoder.Token() + if err != nil { + return nil, fmt.Errorf("parse JSON: %w", err) + } + key, ok := keyToken.(string) + if !ok { + return nil, fmt.Errorf("parse JSON: object key must be a string") + } + var candidate json.RawMessage + if err := decoder.Decode(&candidate); err != nil { + return nil, fmt.Errorf("parse JSON: %w", err) + } + if key != field { + continue + } + if found { + return nil, fmt.Errorf("field .%s appears more than once", field) + } + found = true + value = candidate + } + if _, err := decoder.Token(); err != nil { + return nil, fmt.Errorf("parse JSON: %w", err) + } + var trailing json.RawMessage + if err := decoder.Decode(&trailing); err != io.EOF { + if err == nil { + return nil, fmt.Errorf("parse JSON: unexpected trailing value") + } + return nil, fmt.Errorf("parse JSON: %w", err) + } + if !found { + return nil, fmt.Errorf("field .%s not found", field) + } + return value, nil +} diff --git a/internal/versioncheck/check_test.go b/internal/versioncheck/check_test.go new file mode 100644 index 000000000..71c4564ba --- /dev/null +++ b/internal/versioncheck/check_test.go @@ -0,0 +1,650 @@ +package versioncheck + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/testutil/bazeltest" +) + +func TestRepositoryReleaseVersionsMatch(t *testing.T) { + root := bazeltest.RepoRoot(t) + report, err := Check(root) + if err != nil && !(bazeltest.IsBazel() && onlyNPMManifestUndeclared(t, root, report)) { + t.Fatalf("repository release metadata is inconsistent: %v", err) + } + if report.CheckedSources != 12 { + t.Fatalf("checked sources = %d, want 12", report.CheckedSources) + } + hookEntries, err := os.ReadDir(filepath.Join(root, ".githooks")) + if err != nil { + t.Fatal(err) + } + expectedHookMarkers := 0 + for _, entry := range hookEntries { + if strings.HasPrefix(entry.Name(), ".") { + continue + } + path := filepath.Join(root, ".githooks", entry.Name()) + info, statErr := os.Stat(path) + if statErr != nil { + t.Fatal(statErr) + } + if info.Mode().IsRegular() { + expectedHookMarkers += 2 + } + } + if report.CheckedHookMarkers != expectedHookMarkers { + t.Fatalf( + "checked hook markers = %d, want %d", + report.CheckedHookMarkers, + expectedHookMarkers, + ) + } + if len(report.Sources) != 13+expectedHookMarkers { + t.Fatalf( + "reported sources = %d, want %d (twelve release metadata checks, uv.lock, and tracked hook markers)", + len(report.Sources), + 13+expectedHookMarkers, + ) + } +} + +func TestCheckCoversEveryReleaseSource(t *testing.T) { + // Keyed by description: winres.json contributes several gated fields from + // a single path, so the path alone is no longer a unique key. + expected := map[string]string{ + "MCP pyproject.toml": "integrations/beads-mcp/pyproject.toml", + "MCP __init__.py": "integrations/beads-mcp/src/beads_mcp/__init__.py", + "Claude plugin.json": "plugins/beads/.claude-plugin/plugin.json", + "Codex plugin.json": "plugins/beads/.codex-plugin/plugin.json", + "Copilot plugin.json": "plugins/beads/.copilot-plugin/plugin.json", + "Claude marketplace.json": ".claude-plugin/marketplace.json", + "npm package.json": "npm-package/package.json", + "winres.json file_version": "cmd/bd/winres/winres.json", + "winres.json product_version": "cmd/bd/winres/winres.json", + "winres.json FileVersion": "cmd/bd/winres/winres.json", + "winres.json ProductVersion": "cmd/bd/winres/winres.json", + "manifest.xml assemblyIdentity version": "cmd/bd/winres/manifest.xml", + } + if len(releaseSources) != len(expected) { + t.Fatalf("release source count = %d, want %d", len(releaseSources), len(expected)) + } + + for _, item := range releaseSources { + path, ok := expected[item.description] + if !ok { + t.Fatalf("unexpected release source %q", item.description) + } + if item.path != path { + t.Fatalf( + "path for %q = %q, want %q", + item.description, + item.path, + path, + ) + } + delete(expected, item.description) + + t.Run(item.description, func(t *testing.T) { + root := writeFixture(t, "1.1.0") + path := filepath.Join(root, filepath.FromSlash(item.path)) + content, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + content = []byte(strings.ReplaceAll(string(content), "1.1.0", "9.9.9")) + if err := os.WriteFile(path, content, 0o644); err != nil { + t.Fatal(err) + } + + // The Windows surfaces derive a prerelease-stripped or four-part + // expectation, so the reported pair follows the source's own rule. + wantVersion := "1.1.0" + if item.expected != nil { + wantVersion = item.expected("1.1.0") + } + _, err = Check(root) + if err == nil { + t.Fatal("mismatch unexpectedly passed") + } + want := item.description + ": " + + strings.ReplaceAll(wantVersion, "1.1.0", "9.9.9") + + " (expected " + wantVersion + ")" + if !strings.Contains(err.Error(), want) { + t.Fatalf("error = %q, want %q", err, want) + } + }) + } + if len(expected) != 0 { + t.Fatalf("missing release sources: %v", expected) + } +} + +func TestCheckValidatesTrackedHookMarkerVersions(t *testing.T) { + tests := []struct { + name string + content string + want string + }{ + { + name: "begin mismatch", + content: "# --- BEGIN BEADS INTEGRATION v9.9.9 ---\n" + + "body\n# --- END BEADS INTEGRATION v1.1.0 ---\n", + want: ".githooks/pre-push BEGIN marker: 9.9.9 (expected 1.1.0)", + }, + { + name: "end mismatch", + content: "# --- BEGIN BEADS INTEGRATION v1.1.0 ---\n" + + "body\n# --- END BEADS INTEGRATION v9.9.9 ---\n", + want: ".githooks/pre-push END marker: 9.9.9 (expected 1.1.0)", + }, + { + name: "missing begin", + content: "body\n# --- END BEADS INTEGRATION v1.1.0 ---\n", + want: ".githooks/pre-push BEGIN marker: no 'BEGIN BEADS INTEGRATION' marker found", + }, + { + name: "missing end", + content: "# --- BEGIN BEADS INTEGRATION v1.1.0 ---\n" + + "body\n", + want: ".githooks/pre-push END marker: no 'END BEADS INTEGRATION' marker found", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + root := writeFixture(t, "1.1.0") + path := filepath.Join(root, ".githooks", "pre-push") + if err := os.WriteFile(path, []byte(test.content), 0o755); err != nil { + t.Fatal(err) + } + + _, err := Check(root) + if err == nil { + t.Fatal("invalid tracked hook marker unexpectedly passed") + } + if !strings.Contains(err.Error(), test.want) { + t.Fatalf("error = %q, want %q", err, test.want) + } + }) + } +} + +func TestCheckDiscoversAdditionalTrackedHookFiles(t *testing.T) { + root := writeFixture(t, "1.1.0") + path := filepath.Join(root, ".githooks", "post-merge") + if err := os.WriteFile( + path, + []byte( + "# --- BEGIN BEADS INTEGRATION v1.1.0 ---\n"+ + "body\n# --- END BEADS INTEGRATION v1.1.0 ---\n", + ), + 0o755, + ); err != nil { + t.Fatal(err) + } + + report, err := Check(root) + if err != nil { + t.Fatal(err) + } + if report.CheckedHookMarkers != 4 { + t.Fatalf("checked hook markers = %d, want 4", report.CheckedHookMarkers) + } + want := map[string]bool{ + ".githooks/post-merge BEGIN marker": false, + ".githooks/post-merge END marker": false, + } + for _, result := range report.Sources { + if _, ok := want[result.Description]; ok { + want[result.Description] = true + } + } + for description, found := range want { + if !found { + t.Fatalf("additional tracked hook result %q not reported", description) + } + } +} + +func TestCheckTreatsRepositoryRootAsLiteralPath(t *testing.T) { + root := filepath.Join(t.TempDir(), "[repo]") + writeFixtureAt(t, root, "1.1.0") + + report, err := Check(root) + if err != nil { + t.Fatal(err) + } + if report.CheckedHookMarkers != 2 { + t.Fatalf("checked hook markers = %d, want 2", report.CheckedHookMarkers) + } +} + +func TestCheckIgnoresDotfilesInTrackedHooks(t *testing.T) { + root := writeFixture(t, "1.1.0") + if err := os.WriteFile( + filepath.Join(root, ".githooks", ".DS_Store"), + []byte("not a managed hook\n"), + 0o644, + ); err != nil { + t.Fatal(err) + } + + report, err := Check(root) + if err != nil { + t.Fatal(err) + } + if report.CheckedHookMarkers != 2 { + t.Fatalf("checked hook markers = %d, want 2", report.CheckedHookMarkers) + } +} + +func TestCheckRejectsMissingMalformedOrAmbiguousMetadata(t *testing.T) { + tests := []struct { + name string + path string + data []byte + want string + }{ + { + name: "missing metadata", + path: "integrations/beads-mcp/src/beads_mcp/__init__.py", + data: nil, + want: "MCP __init__.py:", + }, + { + name: "duplicate project TOML field", + path: "integrations/beads-mcp/pyproject.toml", + data: []byte("[project]\nversion = \"1.1.0\"\nversion = \"1.1.0\"\n"), + want: "MCP pyproject.toml: parse TOML:", + }, + { + name: "version in wrong TOML table", + path: "integrations/beads-mcp/pyproject.toml", + data: []byte("[tool.example]\nversion = \"1.1.0\"\n"), + want: "MCP pyproject.toml: non-empty string field [project].version not found", + }, + { + name: "wrong-case TOML project table", + path: "integrations/beads-mcp/pyproject.toml", + data: []byte("[Project]\nversion = \"1.1.0\"\n"), + want: `MCP pyproject.toml: field [project] is ambiguous or uses non-exact casing: "Project"`, + }, + { + name: "wrong-case TOML version field", + path: "integrations/beads-mcp/pyproject.toml", + data: []byte("[project]\nVersion = \"1.1.0\"\n"), + want: `MCP pyproject.toml: field [project].version is ambiguous or uses non-exact casing: "Version"`, + }, + { + name: "case-alias TOML project tables", + path: "integrations/beads-mcp/pyproject.toml", + data: []byte( + "[project]\nversion = \"1.1.0\"\n" + + "[Project]\nversion = \"9.9.9\"\n", + ), + want: `MCP pyproject.toml: field [project] is ambiguous or uses non-exact casing: "Project", "project"`, + }, + { + name: "case-alias TOML version fields", + path: "integrations/beads-mcp/pyproject.toml", + data: []byte( + "[project]\nversion = \"1.1.0\"\nVersion = \"9.9.9\"\n", + ), + want: `MCP pyproject.toml: field [project].version is ambiguous or uses non-exact casing: "Version", "version"`, + }, + { + name: "nested Python assignment", + path: "integrations/beads-mcp/src/beads_mcp/__init__.py", + data: []byte("def f():\n __version__ = \"1.1.0\"\n"), + want: "MCP __init__.py: found 0 module-level __version__", + }, + { + name: "Python assignment inside multiline string", + path: "integrations/beads-mcp/src/beads_mcp/__init__.py", + data: []byte("payload = \"\"\"\n__version__ = \"1.1.0\"\n\"\"\"\n"), + want: "MCP __init__.py: found 0 module-level __version__", + }, + { + name: "malformed JSON", + path: "plugins/beads/.codex-plugin/plugin.json", + data: []byte("{"), + want: "Codex plugin.json: parse JSON:", + }, + { + name: "wrong-case JSON field", + path: "npm-package/package.json", + data: []byte(`{"Version":"1.1.0"}`), + want: "npm package.json: field .version not found", + }, + { + name: "duplicate JSON field", + path: "plugins/beads/.codex-plugin/plugin.json", + data: []byte(`{"version":"1.1.0","version":"1.1.0"}`), + want: "Codex plugin.json: field .version appears more than once", + }, + { + name: "trailing JSON document", + path: "npm-package/package.json", + data: []byte(`{"version":"1.1.0"} {}`), + want: "npm package.json: parse JSON: unexpected trailing value", + }, + { + name: "duplicate marketplace plugins field", + path: ".claude-plugin/marketplace.json", + data: []byte( + `{"plugins":[{"version":"1.1.0"}],"plugins":[{"version":"1.1.0"}]}`, + ), + want: "Claude marketplace.json: field .plugins appears more than once", + }, + { + name: "missing MCP lockfile", + path: "integrations/beads-mcp/uv.lock", + data: nil, + want: "MCP uv.lock (beads-mcp pin):", + }, + { + name: "duplicate MCP lock package", + path: "integrations/beads-mcp/uv.lock", + data: []byte( + "[[package]]\nname = \"beads-mcp\"\nversion = \"1.1.0\"\n" + + "[[package]]\nname = \"beads-mcp\"\nversion = \"1.1.0\"\n", + ), + want: "MCP uv.lock (beads-mcp pin): found 2 beads-mcp package entries, want exactly one", + }, + { + name: "wrong-case MCP lock name field", + path: "integrations/beads-mcp/uv.lock", + data: []byte("[[package]]\nName = \"beads-mcp\"\nversion = \"1.1.0\"\n"), + want: `MCP uv.lock (beads-mcp pin): field [[package]][0].name is ambiguous or uses non-exact casing: "Name"`, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + root := writeFixture(t, "1.1.0") + path := filepath.Join(root, filepath.FromSlash(test.path)) + var err error + if test.data == nil { + err = os.Remove(path) + } else { + err = os.WriteFile(path, test.data, 0o644) + } + if err != nil { + t.Fatal(err) + } + + _, err = Check(root) + if err == nil { + t.Fatal("invalid metadata unexpectedly passed") + } + if !strings.Contains(err.Error(), test.want) { + t.Fatalf("error = %q, want %q", err, test.want) + } + }) + } +} + +func TestCheckValidatesUVLockVersion(t *testing.T) { + root := writeFixture(t, "1.1.0") + lockPath := filepath.Join(root, "integrations", "beads-mcp", "uv.lock") + if err := os.WriteFile( + lockPath, + []byte("[[package]]\nname = \"beads-mcp\"\nversion = \"9.9.9\"\n"), + 0o644, + ); err != nil { + t.Fatal(err) + } + _, err := Check(root) + if err == nil { + t.Fatal("stale MCP lock version unexpectedly passed") + } + if want := "MCP uv.lock (beads-mcp pin): 9.9.9 (expected 1.1.0)"; !strings.Contains(err.Error(), want) { + t.Fatalf("error = %q, want %q", err, want) + } + + root = writeFixture(t, "1.1.0-rc.1") + if _, err := Check(root); err != nil { + t.Fatalf("PEP 440-normalized release-candidate lock version failed: %v", err) + } +} + +func TestCheckUsesSemanticGoAndPythonScopes(t *testing.T) { + root := writeFixture(t, "1.1.0") + if err := os.WriteFile( + filepath.Join(root, "cmd", "bd", "version.go"), + []byte( + "package main\n\n"+ + "const text = `Version = \"1.1.0\"`\n"+ + "func f() { Version := \"1.1.0\"; _ = Version }\n", + ), + 0o644, + ); err != nil { + t.Fatal(err) + } + _, err := Check(root) + if err == nil { + t.Fatal("declaration-shaped text and local Go variable unexpectedly passed") + } + if !strings.Contains(err.Error(), "found 0 package-level Version string assignments") { + t.Fatalf("unexpected Go scope error: %v", err) + } + + root = writeFixture(t, "1.1.0") + if err := os.WriteFile( + filepath.Join(root, "integrations", "beads-mcp", "src", "beads_mcp", "__init__.py"), + []byte("__version__ = '1.1.0' # release version\n"), + 0o644, + ); err != nil { + t.Fatal(err) + } + if _, err := Check(root); err != nil { + t.Fatalf("module-level Python assignment with trailing comment failed: %v", err) + } +} + +func TestFindRootFromSubdirectory(t *testing.T) { + root := writeFixture(t, "1.1.0") + subdirectory := filepath.Join(root, "cmd", "bd", "nested") + if err := os.MkdirAll(subdirectory, 0o755); err != nil { + t.Fatal(err) + } + + got, found, err := FindRoot(subdirectory) + if err != nil { + t.Fatal(err) + } + want, err := filepath.EvalSymlinks(root) + if err != nil { + t.Fatal(err) + } + if !found || filepath.Clean(got) != filepath.Clean(want) { + t.Fatalf("FindRoot = (%q, %v), want canonical root (%q, true)", got, found, want) + } +} + +func TestFindRootResolvesAliasedStart(t *testing.T) { + root := writeFixture(t, "1.1.0") + realStart := filepath.Join(root, "cmd", "bd") + alias := filepath.Join(t.TempDir(), "beads-command") + if err := os.Symlink(realStart, alias); err != nil { + t.Skipf("directory symlinks are unavailable: %v", err) + } + + got, found, err := FindRoot(alias) + if err != nil { + t.Fatal(err) + } + if !found { + t.Fatal("aliased Beads subdirectory was not identified") + } + gotInfo, err := os.Stat(got) + if err != nil { + t.Fatal(err) + } + rootInfo, err := os.Stat(root) + if err != nil { + t.Fatal(err) + } + if !os.SameFile(gotInfo, rootInfo) { + t.Fatalf("FindRoot = %q, want directory identity %q", got, root) + } +} + +func TestFindRootFailsClosedForAmbiguousBeadsIdentity(t *testing.T) { + tests := []struct { + name string + goMod *string + want string + }{ + { + name: "missing go.mod", + want: "is missing go.mod", + }, + { + name: "malformed go.mod", + goMod: stringPointer("go 1.26\n"), + want: "module directive not found", + }, + { + name: "module text inside malformed directive block", + goMod: stringPointer( + "require (\nmodule github.com/steveyegge/beads\n)\n", + ), + want: "parse go.mod", + }, + { + name: "conflicting module", + goMod: stringPointer("module example.com/not-beads\n"), + want: `declares module "example.com/not-beads"`, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + root := writeFixture(t, "1.1.0") + goModPath := filepath.Join(root, "go.mod") + var err error + if test.goMod == nil { + err = os.Remove(goModPath) + } else { + err = os.WriteFile(goModPath, []byte(*test.goMod), 0o644) + } + if err != nil { + t.Fatal(err) + } + + _, found, err := FindRoot(filepath.Join(root, "cmd", "bd")) + if err == nil { + t.Fatal("ambiguous Beads identity unexpectedly passed") + } + if found { + t.Fatal("ambiguous Beads identity was reported as found") + } + if !strings.Contains(err.Error(), test.want) { + t.Fatalf("error = %q, want %q", err, test.want) + } + }) + } +} + +func TestFindRootLeavesUnrelatedModuleUnclaimed(t *testing.T) { + root := t.TempDir() + if err := os.WriteFile( + filepath.Join(root, "go.mod"), + []byte("module example.com/other\n"), + 0o644, + ); err != nil { + t.Fatal(err) + } + _, found, err := FindRoot(root) + if err != nil { + t.Fatal(err) + } + if found { + t.Fatal("unrelated module was identified as Beads") + } +} + +func writeFixture(t *testing.T, version string) string { + t.Helper() + + root := t.TempDir() + writeFixtureAt(t, root, version) + return root +} + +func writeFixtureAt(t *testing.T, root, version string) { + t.Helper() + + files := map[string]string{ + "go.mod": "module " + ModulePath + "\n\ngo 1.26\n", + "cmd/bd/version.go": "package main\n\nvar Version = \"" + version + "\"\n", + "scripts/update-versions.sh": "#!/bin/sh\n", + "integrations/beads-mcp/pyproject.toml": "[project]\nversion = \"" + + version + "\"\n", + "integrations/beads-mcp/src/beads_mcp/__init__.py": "__version__ = \"" + + version + "\"\n", + "plugins/beads/.claude-plugin/plugin.json": `{"version":"` + version + `"}`, + "plugins/beads/.codex-plugin/plugin.json": `{"version":"` + version + `"}`, + ".claude-plugin/marketplace.json": `{"plugins":[{"version":"` + + version + `"}]}`, + "npm-package/package.json": `{"version":"` + version + `"}`, + "plugins/beads/.copilot-plugin/plugin.json": `{"version":"` + version + `"}`, + "cmd/bd/winres/winres.json": `{"RT_VERSION":{"#1":{"0000":{` + + `"fixed":{"file_version":"` + baseVersion(version) + + `","product_version":"` + baseVersion(version) + `"},` + + `"info":{"0409":{"FileVersion":"` + version + + `","ProductVersion":"` + version + `"}}}}}}`, + "cmd/bd/winres/manifest.xml": "\n" + + "\n" + + " \n\n", + "integrations/beads-mcp/uv.lock": "version = 1\nrevision = 3\n\n" + + "[[package]]\nname = \"beads-mcp\"\nversion = \"" + + normalizePythonVersion(version) + "\"\n", + ".githooks/pre-push": "# --- BEGIN BEADS INTEGRATION v" + version + " ---\n" + + "body\n# --- END BEADS INTEGRATION v" + version + " ---\n", + } + for relativePath, content := range files { + path := filepath.Join(root, filepath.FromSlash(relativePath)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatalf("create parent for %s: %v", relativePath, err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatalf("write %s: %v", relativePath, err) + } + } +} + +func stringPointer(value string) *string { + return &value +} + +// onlyNPMManifestUndeclared reports, and logs, whether the npm manifest is the +// one failing release surface and it failed because it is absent. npm-package/ +// is in .bazelignore, so no target can declare npm-package/package.json as data +// and a Bazel run never sees it; `go test` checks it against the real checkout. +func onlyNPMManifestUndeclared(t *testing.T, root string, report Report) bool { + t.Helper() + if _, err := os.Stat(filepath.Join(root, "npm-package", "package.json")); !os.IsNotExist(err) { + return false + } + npmMissing := false + for _, source := range report.Sources { + switch { + case source.Problem == "": + case source.Description == "npm package.json": + npmMissing = true + default: + return false + } + } + if npmMissing { + t.Log("npm-package/ is in .bazelignore, so npm-package/package.json cannot be declared as data; checked under go test") + } + return npmMissing +} diff --git a/plugins/beads/BUILD.bazel b/plugins/beads/BUILD.bazel index 8bb02bd03..152264079 100644 --- a/plugins/beads/BUILD.bazel +++ b/plugins/beads/BUILD.bazel @@ -20,3 +20,14 @@ filegroup( ), visibility = ["//cmd/bd/setup:__pkg__"], ) + +# Plugin manifests gated by //internal/versioncheck's releaseSources table, +# aggregated into //:release_metadata_files. +exports_files( + [ + ".claude-plugin/plugin.json", + ".codex-plugin/plugin.json", + ".copilot-plugin/plugin.json", + ], + visibility = ["//:__pkg__"], +) diff --git a/scripts/BUILD.bazel b/scripts/BUILD.bazel index 0b88fc188..8aff57276 100644 --- a/scripts/BUILD.bazel +++ b/scripts/BUILD.bazel @@ -98,3 +98,10 @@ exports_files( ["ci/gofmt-bin.sh"], visibility = ["//scripts/prlintmake:__pkg__"], ) + +# The compatibility entrypoint whose exit-status contract +# //scripts/check-versions:check-versions_test drives. +exports_files( + ["check-versions.sh"], + visibility = ["//scripts/check-versions:__pkg__"], +) diff --git a/scripts/check-versions.sh b/scripts/check-versions.sh index 90b515d7e..f9dc39b5a 100755 --- a/scripts/check-versions.sh +++ b/scripts/check-versions.sh @@ -1,182 +1,29 @@ #!/bin/bash -# Check that all version files are in sync -# Run this before committing version bumps +# Compatibility entrypoint for the authoritative Go release-version checker. +# Run this before committing version bumps. -set -e +set -euo pipefail -RED='\033[0;31m' -GREEN='\033[0;32m' -NC='\033[0m' - -# Get the canonical version from version.go -CANONICAL=$(grep 'Version = ' cmd/bd/version.go | sed 's/.*"\(.*\)".*/\1/') - -if [ -z "$CANONICAL" ]; then - echo -e "${RED}❌ Could not read version from cmd/bd/version.go${NC}" - exit 1 +if ! command -v go >/dev/null 2>&1; then + echo "Release version checker unavailable: install Go and add it to PATH." >&2 + exit 127 fi -echo "Canonical version (from version.go): $CANONICAL" -echo "" +script_dir="$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)" +repo_root="$(cd "$script_dir/.." && pwd)" -MISMATCH=0 - -# Base (prerelease-stripped) form. The Windows PE numeric fields must be purely -# numeric, so they carry this rather than $CANONICAL. -BASE_VERSION="${CANONICAL%%-*}" - -check_expected() { - local _file=$1 - local version=$2 - local expected=$3 - local description=$4 - - if [ "$version" != "$expected" ]; then - echo -e "${RED}❌ $description: ${version:-missing} (expected $expected)${NC}" - MISMATCH=1 - else - echo -e "${GREEN}✓ $description: $version${NC}" - fi -} - -check_version() { - check_expected "$1" "$2" "$CANONICAL" "$3" -} - -# Check all version files -check_version "integrations/beads-mcp/pyproject.toml" \ - "$(grep '^version = ' integrations/beads-mcp/pyproject.toml 2>/dev/null | sed 's/.*"\(.*\)".*/\1/')" \ - "MCP pyproject.toml" - -check_version "integrations/beads-mcp/src/beads_mcp/__init__.py" \ - "$(grep '__version__ = ' integrations/beads-mcp/src/beads_mcp/__init__.py 2>/dev/null | sed 's/.*"\(.*\)".*/\1/')" \ - "MCP __init__.py" - -check_version "plugins/beads/.claude-plugin/plugin.json" \ - "$(jq -r '.version' plugins/beads/.claude-plugin/plugin.json 2>/dev/null)" \ - "Claude plugin.json" - -check_version "plugins/beads/.codex-plugin/plugin.json" \ - "$(jq -r '.version' plugins/beads/.codex-plugin/plugin.json 2>/dev/null)" \ - "Codex plugin.json" - -# update-versions.sh bumps this one too, but it was never gated here — so a -# drifted copilot manifest (the same drift class that carried stale .githooks -# markers through v1.2.0) would silently no-op the bump's old->new sed, pass -# this script, pass the pre-push hook and CI, and ship advertising the previous -# version. -check_version "plugins/beads/.copilot-plugin/plugin.json" \ - "$(jq -r '.version' plugins/beads/.copilot-plugin/plugin.json 2>/dev/null)" \ - "Copilot plugin.json" - -check_version ".claude-plugin/marketplace.json" \ - "$(jq -r '.plugins[0].version' .claude-plugin/marketplace.json 2>/dev/null)" \ - "Claude marketplace.json" - -check_version "npm-package/package.json" \ - "$(jq -r '.version' npm-package/package.json 2>/dev/null)" \ - "npm package.json" - -# The release workflow's MCP package gate runs `uv sync --locked`, so a stale -# lockfile fails the release only in the tag-triggered run — after the tag -# exists and can no longer be rewritten (this burned the v1.1.1 tag; v1.1.0 -# lost its first run the same way). Gate it here so the release-tag pre-push -# hook and CI refuse the stale lock before a tag exists. The pinned-version -# check is dependency-free; the fuller `uv lock --check` runs when uv is -# available and also catches dependency edits made without a relock. -# -# uv.lock records the PEP 440-normalized version (1.1.0-rc.1 → 1.1.0rc1), so -# normalize the canonical form before comparing. -LOCK_EXPECTED=$(printf '%s' "$CANONICAL" | sed -E 's/-rc\.?/rc/') -LOCK_VERSION=$(awk -F '"' '/^name = "beads-mcp"$/ { found=1; next } found && /^version = / { print $2; exit }' integrations/beads-mcp/uv.lock 2>/dev/null) -if [ "$LOCK_VERSION" != "$LOCK_EXPECTED" ]; then - echo -e "${RED}❌ MCP uv.lock (beads-mcp pin): ${LOCK_VERSION:-missing} (expected $LOCK_EXPECTED) — run: uv lock --directory integrations/beads-mcp${NC}" - MISMATCH=1 -else - echo -e "${GREEN}✓ MCP uv.lock (beads-mcp pin): $LOCK_VERSION${NC}" +cd "$repo_root" +if ! checker_dir="$(mktemp -d "${TMPDIR:-/tmp}/beads-check-versions.XXXXXX")"; then + echo "Release version checker unavailable: cannot create a temporary directory." >&2 + exit 127 fi - -if command -v uv >/dev/null 2>&1; then - if uv lock --check --directory integrations/beads-mcp >/dev/null 2>&1; then - echo -e "${GREEN}✓ MCP uv.lock: fresh (uv lock --check)${NC}" - else - echo -e "${RED}❌ MCP uv.lock: stale — run: uv lock --directory integrations/beads-mcp${NC}" - MISMATCH=1 - fi -fi - -# Tracked managed git-hook sections (.githooks/*): the BEGIN/END markers embed -# the binary Version, and TestTrackedManagedHookSectionsMatchGenerator holds -# them equal to the cmd/bd/hooks.go generator output. A version bump that skips -# them reddens main only after the push (that was the v1.2.0 bump), so gate the -# markers here. Marker version only — full body equality stays the test's job. -for hook in .githooks/*; do - [ -f "$hook" ] || continue - for prefix in "BEGIN" "END"; do - marker=$(grep -oE -- "--- $prefix BEADS INTEGRATION v[^ ]+ ---" "$hook" | head -1) - if [ -z "$marker" ]; then - echo -e "${RED}❌ $hook: no '$prefix BEADS INTEGRATION' marker found${NC}" - MISMATCH=1 - continue - fi - check_version "$hook" \ - "$(printf '%s' "$marker" | sed -E 's/.* v([^ ]+) ---/\1/')" \ - "$hook $prefix marker" - done -done - -# Windows PE resource metadata. gen-winres.sh re-derives winres.json's numeric -# fields from version.go at build time, so those self-heal — but -# manifest.xml's version is embedded verbatim with no -# backstop, and update-versions.sh rewrites both with a sed anchored on the OLD -# value, so a drifted file is a silent no-op. Gate them. -# -# The numeric fields (file_version/product_version, and the manifest's -# four-part version) must be purely numeric, so they carry the base version: -# for 1.1.0-rc.1 they read 1.1.0 while FileVersion/ProductVersion read the full -# prerelease string. -WINRES_JSON="cmd/bd/winres/winres.json" -for field in file_version product_version; do - check_expected "$WINRES_JSON" \ - "$(jq -r ".RT_VERSION.\"#1\".\"0000\".fixed.$field" "$WINRES_JSON" 2>/dev/null)" \ - "$BASE_VERSION" "winres.json $field" -done -for field in FileVersion ProductVersion; do - check_expected "$WINRES_JSON" \ - "$(jq -r ".RT_VERSION.\"#1\".\"0000\".info.\"0409\".$field" "$WINRES_JSON" 2>/dev/null)" \ - "$CANONICAL" "winres.json $field" -done - -# Anchor on line start: the XML declaration on line 1 also carries a -# version="1.0" attribute. -check_expected "cmd/bd/winres/manifest.xml" \ - "$(grep -oE '^[[:space:]]*version="[0-9][^"]*"' cmd/bd/winres/manifest.xml 2>/dev/null | head -1 | sed -E 's/.*"(.*)"/\1/')" \ - "$BASE_VERSION.0" "manifest.xml assemblyIdentity version" - -echo "" - -if [ $MISMATCH -eq 1 ]; then - echo -e "${RED}❌ Version mismatch detected!${NC}" - echo "" - echo "Note: re-running 'scripts/update-versions.sh $CANONICAL' will NOT fix" - echo "most of these. It derives the OLD version from cmd/bd/version.go, which" - echo "already reads $CANONICAL, so its old->new substitutions rewrite" - echo "$CANONICAL -> $CANONICAL and no-op on a file that drifted. Only the" - echo ".githooks markers (rewritten wholesale) and uv.lock (regenerated) heal" - echo "on a re-run." - echo "" - echo "Fix whichever applies:" - echo " • cmd/bd/version.go itself is wrong (you meant another version):" - echo " scripts/update-versions.sh " - echo " • one gated file drifted: edit that file to $CANONICAL and re-run" - echo " this script." - echo " • several drifted: set cmd/bd/version.go back to the previous" - echo " version, then scripts/update-versions.sh $CANONICAL to replay the" - echo " whole bump." - exit 1 -else - echo -e "${GREEN}✓ Version files in sync at: $CANONICAL${NC}" - echo " (Version files only — this script does not check docs. The docs" - echo " release line and docs/cli-docs.pin are manual release steps; see" - echo " RELEASING.md.)" +trap 'rm -rf -- "$checker_dir"' EXIT +# An explicit .exe name works on Unix and native Windows alike. +checker="$checker_dir/check-versions.exe" +if ! go build -tags=gms_pure_go -o "$checker" ./scripts/check-versions; then + echo "Release version checker unavailable: Go could not build it." >&2 + exit 127 fi +# Running the binary preserves usage status 2, validation status 1 and --expect +# mismatch status 3; go run collapses them to 1 and adds its own diagnostic. +"$checker" "$@" diff --git a/scripts/check-versions/BUILD.bazel b/scripts/check-versions/BUILD.bazel new file mode 100644 index 000000000..88c87eee2 --- /dev/null +++ b/scripts/check-versions/BUILD.bazel @@ -0,0 +1,45 @@ +load("@rules_go//go:def.bzl", "go_binary", "go_library", "go_test") + +go_library( + name = "check-versions_lib", + srcs = ["main.go"], + importpath = "github.com/steveyegge/beads/scripts/check-versions", + visibility = ["//visibility:private"], + deps = ["//internal/versioncheck"], +) + +go_binary( + name = "check-versions", + embed = [":check-versions_lib"], + visibility = ["//visibility:public"], +) + +# Tags: +# host-tools: pre_push_hook_test.go runs the tracked pre-push hook and the +# shell entrypoint under the host's /bin/bash, and the hook shells out to +# the host's git and coreutils. +# no-remote-exec: so it runs where that inventory is known (the developer +# machine or the CI runner) rather than on a farm worker. +# no-remote-cache: the action key does not cover the host's bash or tools, so +# a result from one host is neither uploaded for nor served to another. +go_test( + name = "check-versions_test", + srcs = [ + "main_test.go", + "pre_push_hook_test.go", + ], + data = [ + "//:release_metadata_files", + "//scripts:check-versions.sh", + ], + embed = [":check-versions_lib"], + tags = [ + "host-tools", + "no-remote-cache", + "no-remote-exec", + ], + deps = [ + "//internal/testutil/bazeltest", + "//internal/versioncheck", + ], +) diff --git a/scripts/check-versions/main.go b/scripts/check-versions/main.go new file mode 100644 index 000000000..48224e948 --- /dev/null +++ b/scripts/check-versions/main.go @@ -0,0 +1,158 @@ +// check-versions validates every released Beads version surface through the +// same Go authority used by bd preflight. +package main + +import ( + "flag" + "fmt" + "io" + "os" + + "github.com/steveyegge/beads/internal/versioncheck" +) + +func main() { + os.Exit(run(os.Args[1:], ".", os.Stdout, os.Stderr, versioncheck.CheckUVLockFreshness)) +} + +const ( + red = "\033[0;31m" + green = "\033[0;32m" + reset = "\033[0m" +) + +type expectedVersionValue struct { + value string + specified bool +} + +func (value *expectedVersionValue) String() string { + return value.value +} + +func (value *expectedVersionValue) Set(candidate string) error { + if value.specified { + return fmt.Errorf("--expect may be specified only once") + } + value.specified = true + if candidate == "" { + return fmt.Errorf("--expect requires a non-empty VERSION") + } + value.value = candidate + return nil +} + +func run( + args []string, + start string, + stdout, stderr io.Writer, + checkUVLock versioncheck.UVLockChecker, +) int { + flags := flag.NewFlagSet("check-versions", flag.ContinueOnError) + flags.SetOutput(stderr) + var expected expectedVersionValue + flags.Var( + &expected, + "expect", + "require the canonical release version to equal this exact value", + ) + if err := flags.Parse(args); err != nil { + return 2 + } + if flags.NArg() != 0 { + fmt.Fprintln(stderr, "usage: scripts/check-versions.sh [--expect VERSION]") + return 2 + } + root, found, err := versioncheck.FindRoot(start) + if err != nil { + fmt.Fprintf(stderr, "Cannot identify Beads release root: %v\n", err) + return 1 + } + if !found { + fmt.Fprintln(stderr, "Cannot identify a Beads source repository from the current directory") + return 1 + } + report, err := versioncheck.Check(root) + printReport(stdout, report) + if err != nil { + fmt.Fprintf(stderr, "\n%s❌ %v%s\n", red, err, reset) + if report.CanonicalVersion != "" { + fmt.Fprintf( + stderr, + "Run: scripts/update-versions.sh %s\nOr manually update the mismatched files.\n", + report.CanonicalVersion, + ) + } + return 1 + } + if expected.specified && report.CanonicalVersion != expected.value { + fmt.Fprintf( + stderr, + "Canonical release version %s does not match required version %s\n", + report.CanonicalVersion, + expected.value, + ) + // Distinct from status 1: the release surfaces agree with each other, + // only the required version differs. Callers such as the release-tag + // pre-push hook must not answer this with the version-drift remedy. + return 3 + } + if checkUVLock != nil { + available, checkErr := checkUVLock(root) + if available && checkErr != nil { + fmt.Fprintln( + stderr, + red+"❌ MCP uv.lock: stale — run: uv lock --directory integrations/beads-mcp"+reset, + ) + return 1 + } + if available { + fmt.Fprintln(stdout, green+"✓ MCP uv.lock: fresh (uv lock --check)"+reset) + } + } + fmt.Fprintf( + stdout, + "\n%s✓ Version files in sync at: %s%s\n", + green, + report.CanonicalVersion, + reset, + ) + // The checker reads no documentation surface, so it must not imply one. + fmt.Fprintln(stdout, " (Version files only — this script does not check docs. The docs") + fmt.Fprintln(stdout, " release line and docs/cli-docs.pin are manual release steps; see") + fmt.Fprintln(stdout, " RELEASING.md.)") + return 0 +} + +func printReport(output io.Writer, report versioncheck.Report) { + if report.CanonicalVersion == "" { + return + } + fmt.Fprintf(output, "Canonical version (from version.go): %s\n\n", report.CanonicalVersion) + for _, item := range report.Sources { + switch { + case item.Problem == "": + fmt.Fprintf(output, "%s✓ %s: %s%s\n", green, item.Description, item.Version, reset) + case item.Version != "": + fmt.Fprintf( + output, + "%s❌ %s: %s (expected %s)%s\n", + red, + item.Description, + item.Version, + item.Expected, + reset, + ) + default: + fmt.Fprintf( + output, + "%s❌ %s: %s (expected %s)%s\n", + red, + item.Description, + item.Problem, + item.Expected, + reset, + ) + } + } +} diff --git a/scripts/check-versions/main_test.go b/scripts/check-versions/main_test.go new file mode 100644 index 000000000..0167b661f --- /dev/null +++ b/scripts/check-versions/main_test.go @@ -0,0 +1,228 @@ +package main + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/versioncheck" +) + +func TestRunExpectedVersionContract(t *testing.T) { + root := writeReleaseFixture(t, "1.1.0") + + tests := []struct { + name string + args []string + wantCode int + wantStdout string + wantStderr string + }{ + { + name: "aligned version", + args: []string{"--expect", "1.1.0"}, + wantCode: 0, + wantStdout: "✓ Version files in sync at: 1.1.0", + }, + { + name: "mismatched version", + args: []string{"--expect", "9.9.9"}, + wantCode: 3, + wantStdout: "Canonical version (from version.go): 1.1.0", + wantStderr: "Canonical release version 1.1.0 does not match required version 9.9.9", + }, + { + name: "empty version", + args: []string{"--expect="}, + wantCode: 2, + wantStderr: "--expect requires a non-empty VERSION", + }, + { + name: "duplicate version", + args: []string{"--expect", "1.1.0", "--expect", "1.1.0"}, + wantCode: 2, + wantStderr: "--expect may be specified only once", + }, + { + name: "unknown argument", + args: []string{"--unknown"}, + wantCode: 2, + wantStderr: "flag provided but not defined: -unknown", + }, + { + name: "positional argument", + args: []string{"1.1.0"}, + wantCode: 2, + wantStderr: "usage: scripts/check-versions.sh [--expect VERSION]", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var stdout bytes.Buffer + var stderr bytes.Buffer + code := run( + test.args, + root, + &stdout, + &stderr, + func(string) (bool, error) { return false, nil }, + ) + + if code != test.wantCode { + t.Fatalf( + "exit code = %d, want %d\nstdout:\n%s\nstderr:\n%s", + code, + test.wantCode, + stdout.String(), + stderr.String(), + ) + } + if test.wantStdout != "" && !strings.Contains(stdout.String(), test.wantStdout) { + t.Fatalf("stdout = %q, want substring %q", stdout.String(), test.wantStdout) + } + if test.wantStdout == "" && stdout.Len() != 0 { + t.Fatalf("stdout = %q, want empty", stdout.String()) + } + if !strings.Contains(stderr.String(), test.wantStderr) { + t.Fatalf("stderr = %q, want substring %q", stderr.String(), test.wantStderr) + } + if test.wantStderr == "" && stderr.Len() != 0 { + t.Fatalf("stderr = %q, want empty", stderr.String()) + } + }) + } +} + +func TestRunPreservesOptionalUVLockFreshnessCheck(t *testing.T) { + root := writeReleaseFixture(t, "1.1.0") + for _, test := range []struct { + name string + check versioncheck.UVLockChecker + wantCode int + wantStdout string + wantStderr string + }{ + { + name: "fresh", + check: func(string) (bool, error) { + return true, nil + }, + wantCode: 0, + wantStdout: "✓ MCP uv.lock: fresh (uv lock --check)", + }, + { + name: "stale", + check: func(string) (bool, error) { + return true, errors.New("stale") + }, + wantCode: 1, + wantStderr: "❌ MCP uv.lock: stale", + }, + } { + t.Run(test.name, func(t *testing.T) { + var stdout bytes.Buffer + var stderr bytes.Buffer + code := run(nil, root, &stdout, &stderr, test.check) + if code != test.wantCode { + t.Fatalf("exit code = %d, want %d", code, test.wantCode) + } + if !strings.Contains(stdout.String(), test.wantStdout) { + t.Fatalf("stdout = %q, want substring %q", stdout.String(), test.wantStdout) + } + if !strings.Contains(stderr.String(), test.wantStderr) { + t.Fatalf("stderr = %q, want substring %q", stderr.String(), test.wantStderr) + } + if test.wantCode != 0 && strings.Contains( + stdout.String(), + "Version files in sync at:", + ) { + t.Fatal("stale uv.lock emitted a success result") + } + }) + } +} + +func TestRunRejectsTrackedHookMarkerMismatch(t *testing.T) { + root := writeReleaseFixture(t, "1.1.0") + if err := os.WriteFile( + filepath.Join(root, ".githooks", "pre-push"), + []byte( + "# --- BEGIN BEADS INTEGRATION v1.1.0 ---\n"+ + "body\n# --- END BEADS INTEGRATION v9.9.9 ---\n", + ), + 0o755, + ); err != nil { + t.Fatal(err) + } + + var stdout bytes.Buffer + var stderr bytes.Buffer + code := run(nil, root, &stdout, &stderr, nil) + if code != 1 { + t.Fatalf("exit code = %d, want 1", code) + } + if !strings.Contains( + stdout.String(), + ".githooks/pre-push END marker: 9.9.9 (expected 1.1.0)", + ) { + t.Fatalf("stdout = %q, want tracked-hook mismatch", stdout.String()) + } + if !strings.Contains( + stderr.String(), + ".githooks/pre-push END marker: 9.9.9 (expected 1.1.0)", + ) { + t.Fatalf("stderr = %q, want tracked-hook mismatch summary", stderr.String()) + } + if strings.Contains(stdout.String(), "Version files in sync at:") { + t.Fatal("tracked-hook mismatch emitted a success result") + } +} + +func writeReleaseFixture(t *testing.T, version string) string { + t.Helper() + + root := t.TempDir() + // The Windows PE numeric fields must be purely numeric, so they carry the + // prerelease-stripped form. + base, _, _ := strings.Cut(version, "-") + files := map[string]string{ + "go.mod": "module github.com/steveyegge/beads\n\ngo 1.26\n", + "cmd/bd/version.go": "package main\n\nvar Version = \"" + version + "\"\n", + "scripts/update-versions.sh": "#!/bin/sh\n", + "integrations/beads-mcp/pyproject.toml": "[project]\nversion = \"" + + version + "\"\n", + "integrations/beads-mcp/src/beads_mcp/__init__.py": "__version__ = \"" + + version + "\"\n", + "plugins/beads/.claude-plugin/plugin.json": `{"version":"` + version + `"}`, + "plugins/beads/.codex-plugin/plugin.json": `{"version":"` + version + `"}`, + ".claude-plugin/marketplace.json": `{"plugins":[{"version":"` + + version + `"}]}`, + "npm-package/package.json": `{"version":"` + version + `"}`, + "plugins/beads/.copilot-plugin/plugin.json": `{"version":"` + version + `"}`, + "cmd/bd/winres/winres.json": `{"RT_VERSION":{"#1":{"0000":{` + + `"fixed":{"file_version":"` + base + `","product_version":"` + base + `"},` + + `"info":{"0409":{"FileVersion":"` + version + + `","ProductVersion":"` + version + `"}}}}}}`, + "cmd/bd/winres/manifest.xml": "\n" + + "\n \n\n", + "integrations/beads-mcp/uv.lock": "version = 1\nrevision = 3\n\n" + + "[[package]]\nname = \"beads-mcp\"\nversion = \"" + version + "\"\n", + ".githooks/pre-push": "# --- BEGIN BEADS INTEGRATION v" + version + " ---\n" + + "body\n# --- END BEADS INTEGRATION v" + version + " ---\n", + } + for relativePath, content := range files { + path := filepath.Join(root, filepath.FromSlash(relativePath)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatalf("create parent for %s: %v", relativePath, err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatalf("write %s: %v", relativePath, err) + } + } + return root +} diff --git a/scripts/check-versions/pre_push_hook_test.go b/scripts/check-versions/pre_push_hook_test.go new file mode 100644 index 000000000..a417fb0ed --- /dev/null +++ b/scripts/check-versions/pre_push_hook_test.go @@ -0,0 +1,83 @@ +package main + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/testutil/bazeltest" +) + +// The repository hook must keep ordinary pushes working under macOS's system +// Bash 3.2. In particular, nounset treats an empty array as unset there. +func TestPrePushHookOrdinaryPushWorksWithSystemBash(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows does not provide the oldest supported /bin/bash") + } + + const bash = "/bin/bash" + if _, err := os.Stat(bash); err != nil { + t.Skipf("system Bash unavailable: %v", err) + } + + repoRoot := bazeltest.RepoRoot(t) + hook := filepath.Join(repoRoot, ".githooks", "pre-push") + + command := exec.Command(bash, hook, "origin", "https://example.invalid/repo.git") + command.Dir = repoRoot + command.Env = append(os.Environ(), "PATH=/bin") + command.Stdin = strings.NewReader( + "refs/heads/main 1111111111111111111111111111111111111111 " + + "refs/heads/main 0000000000000000000000000000000000000000\n", + ) + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("ordinary pre-push hook under %s: %v\n%s", bash, err, output) + } + + // Keep the shell entrypoint's status contract covered on the oldest Bash, + // alongside the ordinary-push compatibility that brought us here. + // + // Unlike the ordinary push above, the entrypoint builds the Go checker from + // source at the repository root, so it needs a full module checkout there. + // Under Bazel the tree the test sees is its runfiles, which holds only the + // declared data and no go.mod, so the wrapper could only ever report its + // build failure (127); `go test` runs against the real checkout. The guard + // sits inside each subtest, not above the loop, so that the ordinary-push + // assertion above still reports as run rather than hiding behind a skip. + for _, tc := range []struct { + name string + args []string + code int + }{ + {"unknown option", []string{"--unknown"}, 2}, + {"positional argument", []string{"unexpected"}, 2}, + {"version mismatch", []string{"--expect", "0.0.0-checker-test"}, 3}, + } { + t.Run(tc.name, func(t *testing.T) { + if bazeltest.IsBazel() { + t.Skip("entrypoint builds from source: needs the real module checkout, not runfiles") + } + scratch := t.TempDir() + t.Setenv("TMPDIR", scratch) + checker := filepath.Join(repoRoot, "scripts", "check-versions.sh") + cmd := exec.Command(bash, append([]string{checker}, tc.args...)...) + cmd.Dir = repoRoot + output, err := cmd.CombinedOutput() + var exit *exec.ExitError + if !errors.As(err, &exit) || exit.ExitCode() != tc.code { + t.Fatalf("entrypoint status = %v, want %d: %s", err, tc.code, output) + } + if strings.Contains(string(output), "exit status ") { + t.Fatalf("launcher added its own exit diagnostic: %s", output) + } + entries, err := os.ReadDir(scratch) + if err != nil || len(entries) != 0 { + t.Fatalf("checker temporary files remain: %v, %v", entries, err) + } + }) + } +}