beads/cmd/bd/upgrade.go
Julian Knutsen 251ae6b6e0
fix(version): recognize brew --HEAD version stamps — never route HEAD witnesses into pre-v56 recovery (#5625 carry, #5603) (#6079)
* fix(version): never route a non-semver predecessor into the pre-0.56 .dolt recovery

CompareVersions scans each dot-separated part with %d and leaves whatever it
cannot read at 0, so every non-semver string writeLocalVersion has ever
recorded compares as "older than 0.56.0" and hands a live workspace to
RecoverPreV56DoltDir, which deletes .dolt when the .bd-dolt-ok marker is
absent. Two such stamps reach this call today:

  - "HEAD-<shortsha>", written by a Homebrew --HEAD install (#5603). Because
    CompareVersions also reads the stamp as 0.0.0 on the other side, such a
    workspace already registers an upgrade when the user installs a release,
    so the recovery fires on the very next command.
  - "v1.1.1-0.20260805093327-bf97b73749ac", the v-prefixed Go pseudo-version
    a `go install`-built bd stamps, which is the shape that bricked five
    production cities in #5650.

Gate the recovery on IsValidSemver before the comparison. It rejects exactly
the shapes CompareVersions misreads, so the gate can only remove predecessors
from the recovery set, never add one: every stamp that reaches the recovery
today and still parses keeps its recovery unchanged.

Extracting recoverPreV56IfNeeded makes the destructive edge testable against
the real fixture — a .dolt/ with no .bd-dolt-ok marker — instead of only
through a database open.

Carried from #5625 by @anisoptera and recomposed against release/1.3.0 after
#5650 rewrote the witness classifiers; see that PR for the original analysis.

Refs #5603, #5625, #5650

Co-authored-by: Isis Anisoptera <github@lotuswind.net>
Agent-Signature: claude-code-claude-opus-5[1m]-unknown-reasoning on behalf of Julian Knutsen

* feat(doctor): add IsBrewHeadVersion, the canonical brew --HEAD stamp recognizer

A Homebrew --HEAD install stamps HEAD-<shortsha> into main.Version, or a bare
HEAD when the head spec resolves no commit, either shape optionally carrying
Homebrew's _<revision> suffix. That string is not semver, so every consumer
that compares or validates a version stamp misreads it — but it is a healthy
current-era marker, not a malformed one: bd rewrites it identically on every
run, so nothing the user does can turn it into semver.

Put one recognizer in the doctor package rather than a predicate per consumer.
It is bounded to git's 7-40 character abbreviation range so arbitrary hex
cannot stand in for a commit, and the revision suffix is checked digits-only
so Atoi's tolerance of signed forms ("+1", "-0") cannot admit shapes brew
never emits. The dirty-suffix and signed-revision rejections are pinned by the
table.

Carried verbatim from #5625 by @anisoptera, including the test table; only the
doc comment is adapted, since the legacy upgrade guard's use of this
recognizer is deferred to main (#5650 gave the guard its own unknown-era
policy on this branch).

Refs #5603, #5625

Co-authored-by: Isis Anisoptera <github@lotuswind.net>
Agent-Signature: claude-code-claude-opus-5[1m]-unknown-reasoning on behalf of Julian Knutsen

* fix(doctor): stop nagging Homebrew --HEAD builds about a version they cannot change

Both version checks read a HEAD stamp as broken, and both offered a remedy
that does nothing:

  - CheckCLIVersion compares through CompareVersions, which reads the stamp as
    0.0.0, so every published release looks newer and the check warned "update:
    brew upgrade beads" on every run. Taking that advice would replace the
    --HEAD build with a release, i.e. undo what the user asked for.
  - CheckMetadataVersionTracking rejected the stamp as an "Invalid version
    format" and suggested running any bd command to reset tracking — which
    writes the identical stamp back. The warning was permanent by
    construction.

Report a --HEAD build as healthy in both, with no Fix line, and skip the
release fetch entirely when there is nothing to compare against. The staleness
heuristic below is untouched for semver stamps; hoisting its repeated OK
result into trackingActive is the /simplify cleanup from the original PR.

Carried from #5625 by @anisoptera.

Refs #5603, #5625

Co-authored-by: Isis Anisoptera <github@lotuswind.net>
Agent-Signature: claude-code-claude-opus-5[1m]-unknown-reasoning on behalf of Julian Knutsen

* fix(version): treat a changed brew --HEAD stamp as an upgrade

CompareVersions reads every HEAD stamp as 0.0.0, so the two directions a
--HEAD user actually travels were invisible: reinstalling onto a newer HEAD
compared equal, and moving a release workspace onto HEAD compared as a
downgrade. Both left versionUpgradeDetected false, so the one-shot
post-upgrade reconciliation in autoMigrateOnVersionBump never ran for them.

Treat a changed stamp with a HEAD build on either side as an upgrade: brew
reinstalls only move forward. The misfire is bounded if that is ever wrong —
the preceding commit stops a non-semver predecessor from reaching the pre-0.56
recovery, and the workspace's own version markers still refuse a genuine
downgrade. Those markers cannot arbitrate the direction here either; they
compare with the same dotted scan (workapi.compareDottedVersions) and read a
HEAD stamp as 0.0.0 too.

TestTrackBdVersion_HeadStampNeverReachesPreV56Recovery walks the whole #5603
shape end to end, because the two halves have to compose: widening detection
is exactly what puts a HEAD stamp into previousVersion, where the recovery
gate then has to refuse it.

Carried from #5625 by @anisoptera; the workspace setup shared by the two tests
is factored out here.

Refs #5603, #5625

Co-authored-by: Isis Anisoptera <github@lotuswind.net>
Agent-Signature: claude-code-claude-opus-5[1m]-unknown-reasoning on behalf of Julian Knutsen

* fix(upgrade): keep --HEAD stamps out of the changelog delta and out of banners

getVersionsSince matches its argument against the hardcoded changelog table
and falls back to "return everything" when it finds no entry — a sensible
default for a very old release, wrong for a stamp that can never appear there.
After a --HEAD reinstall, `bd upgrade status` and `bd upgrade review` dumped
the entire release history as new. A HEAD stamp now yields no delta.

The banners then labelled that stamp "vHEAD-f925f3f", which reads as a typo.
displayVersion adds the conventional "v" to semver and renders a HEAD stamp
verbatim, applied at the upgrade-path sites that prefixed a stamp with "v":
the ones #5625 changed, plus the three in `bd upgrade ack` and the pending-
migration notice. That last one is newly reachable for a --HEAD user because
of the preceding commit — detecting the upgrade is what lets
autoMigrateOnVersionBump run far enough to print it.

Left alone: the `bd doctor` headers, `bd info --whats-new`, and the hook
section markers in hooks.go, whose format is parsed back out of user files.

Carried from #5625 by @anisoptera.

Refs #5603, #5625

Co-authored-by: Isis Anisoptera <github@lotuswind.net>
Agent-Signature: claude-code-claude-opus-5[1m]-unknown-reasoning on behalf of Julian Knutsen

---------

Co-authored-by: Isis Anisoptera <github@lotuswind.net>
2026-08-30 16:28:45 -07:00

236 lines
6.4 KiB
Go

package main
import (
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/metrics"
)
var upgradeCmd = &cobra.Command{
Use: "upgrade",
GroupID: "maint",
Short: "Check and manage bd version upgrades",
Long: `Commands for checking bd version upgrades and reviewing changes.
The upgrade command helps you stay aware of bd version changes:
- bd upgrade status: Check if bd version changed since last use
- bd upgrade review: Show what's new since your last version
- bd upgrade ack: Acknowledge the current version
Version tracking is automatic - bd updates metadata.json on every run.`,
}
var upgradeStatusCmd = &cobra.Command{
Use: "status",
Short: "Check if bd version has changed",
Long: `Check if bd has been upgraded since you last used it.
This command uses the version tracking that happens automatically
at startup to detect if bd was upgraded.
Examples:
bd upgrade status
bd upgrade status --json`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("upgrade-status")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if jsonOutput {
result := map[string]interface{}{
"upgraded": versionUpgradeDetected,
"current_version": Version,
}
if versionUpgradeDetected {
result["previous_version"] = previousVersion
result["changes_available"] = len(getVersionsSince(previousVersion)) > 0
}
return outputJSON(result)
}
if versionUpgradeDetected {
fmt.Printf("✨ bd upgraded from %s to %s\n", displayVersion(previousVersion), displayVersion(Version))
newVersions := getVersionsSince(previousVersion)
if len(newVersions) > 0 {
fmt.Printf(" %d version%s with changes available\n",
len(newVersions),
pluralize(len(newVersions)))
fmt.Println()
fmt.Println("Run 'bd upgrade review' to see what changed")
}
} else if previousVersion == "" {
fmt.Printf("bd version: %s (first run or version tracking just enabled)\n", displayVersion(Version))
} else {
fmt.Printf("bd version: %s (no upgrade detected)\n", displayVersion(Version))
}
return nil
},
}
var upgradeReviewCmd = &cobra.Command{
Use: "review",
Short: "Review changes since last bd version",
Long: `Show what's new in bd since the last version you used.
Unlike 'bd info --whats-new' which shows the last 3 versions,
this command shows ALL changes since your specific last version.
If you're upgrading from an old version, you'll see the complete
changelog of everything that changed since then.
Examples:
bd upgrade review
bd upgrade review --json`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("upgrade-review")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
lastVersion := previousVersion
if lastVersion == "" {
fmt.Println("No previous version recorded")
fmt.Println("Run 'bd info --whats-new' to see recent changes")
return nil
}
if !versionUpgradeDetected {
fmt.Printf("You're already on %s (no upgrade detected)\n", displayVersion(Version))
fmt.Println("Run 'bd info --whats-new' to see recent changes")
return nil
}
newVersions := getVersionsSince(lastVersion)
if jsonOutput {
return outputJSON(map[string]interface{}{
"current_version": Version,
"previous_version": lastVersion,
"new_versions": newVersions,
})
}
fmt.Printf("\n🔄 Upgraded from %s to %s\n", displayVersion(lastVersion), displayVersion(Version))
fmt.Println(strings.Repeat("=", 60))
fmt.Println()
if len(newVersions) == 0 {
fmt.Printf("%s is newer than %s but not in changelog\n", displayVersion(Version), displayVersion(lastVersion))
fmt.Println("Run 'bd info --whats-new' to see recent documented changes")
return nil
}
for _, vc := range newVersions {
versionMarker := ""
if vc.Version == Version {
versionMarker = " ← current"
}
fmt.Printf("## v%s (%s)%s\n\n", vc.Version, vc.Date, versionMarker)
for _, change := range vc.Changes {
fmt.Printf(" • %s\n", change)
}
fmt.Println()
}
fmt.Println("💡 Run 'bd upgrade ack' to mark this version as seen")
fmt.Println()
return nil
},
}
var upgradeAckCmd = &cobra.Command{
Use: "ack",
Short: "Acknowledge the current bd version",
Long: `Mark the current bd version as acknowledged.
This updates metadata.json to record that you've seen the current
version. Mainly useful after reviewing upgrade changes to suppress
future upgrade notifications.
Note: Version tracking happens automatically, so you don't need to
run this command unless you want to explicitly mark acknowledgement.
Examples:
bd upgrade ack
bd upgrade ack --json`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("upgrade-ack")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return HandleErrorWithHint(activeWorkspaceNotFoundMessage(), diagHint())
}
cfg, err := configfile.Load(beadsDir)
if err != nil {
return HandleError("loading metadata.json: %v", err)
}
if cfg == nil {
cfg = configfile.DefaultConfig()
}
lastSeenVersion := cfg.LastBdVersion
cfg.LastBdVersion = Version
if err := cfg.Save(beadsDir); err != nil {
return HandleError("saving metadata.json: %v", err)
}
upgradeAcknowledged = true
versionUpgradeDetected = false
if jsonOutput {
return outputJSON(map[string]interface{}{
"acknowledged": true,
"current_version": Version,
"previous_version": lastSeenVersion,
})
}
if lastSeenVersion == Version {
fmt.Printf("✓ Already on %s\n", displayVersion(Version))
} else if lastSeenVersion == "" {
fmt.Printf("✓ Acknowledged bd %s\n", displayVersion(Version))
} else {
fmt.Printf("✓ Acknowledged upgrade from %s to %s\n", displayVersion(lastSeenVersion), displayVersion(Version))
}
return nil
},
}
func pluralize(count int) string {
if count == 1 {
return ""
}
return "s"
}
func init() {
upgradeCmd.AddCommand(upgradeStatusCmd)
upgradeCmd.AddCommand(upgradeReviewCmd)
upgradeCmd.AddCommand(upgradeAckCmd)
rootCmd.AddCommand(upgradeCmd)
}