diff --git a/README.md b/README.md index 474d9c5..b3b0994 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,8 @@ All commands output JSON envelopes (`{"ok": true, "data": ...}`), making them co | Command | Description | |---------|-------------| | `gm init` | Initialize event graph database | +| `gm update check` | Check GitHub Releases for a newer CLI version | +| `gm update apply` | Download and install a newer CLI version | ### Proposal-First Writes @@ -219,6 +221,20 @@ Download a pre-built binary from [Releases](https://github.com/GuoMonth/graphmin go install github.com/senguoyun-guosheng/graphmind/cmd/gm@latest ``` +## Updates + +GraphMind can check for newer releases published on GitHub: + +```bash +gm update check +gm update apply +gm update apply --version v0.3.1 +``` + +Normal `gm` commands may trigger a **non-blocking** background update check at +most once every 24 hours. If a newer release is already known, `gm` prints a +short notice to **stderr** while keeping stdout JSON unchanged. + --- ## License diff --git a/docs/cli-spec.md b/docs/cli-spec.md index 9a0e8fc..e2cc42a 100644 --- a/docs/cli-spec.md +++ b/docs/cli-spec.md @@ -106,6 +106,8 @@ One JSON object per line. Every object includes `id` and `entity` for downstream | Command | Purpose | |---|---| | `gm init` | Initialize graph database | +| `gm update check` | Check GitHub Releases for a newer CLI version | +| `gm update apply` | Download and install a release archive | | `gm schema` | Machine-readable command/type schema (JSON) | --- @@ -172,6 +174,45 @@ Creates the database file and runs all migrations. Safe to run on existing datab --- +### gm update check + +Check GitHub Releases for a newer `gm` binary. + +``` +gm update check +``` + +This command performs a blocking network request and refreshes the local update +cache immediately. + +Regular `gm` commands may also trigger a **non-blocking** background update +check at most once every 24 hours. Any update hint is written to **stderr** so +stdout remains valid JSON. + +--- + +### gm update apply + +Download and install the latest matching release asset for the current +platform. + +``` +gm update apply [--version ] +``` + +| Flag | Description | +|---|---| +| `--version ` | Install a specific release tag instead of the latest one | + +Examples: + +```bash +gm update apply +gm update apply --version v0.3.1 +``` + +--- + ### gm schema Output machine-readable schema as JSON. AI agents call this once at session start for self-discovery. diff --git a/go.mod b/go.mod index 200733e..140e72d 100644 --- a/go.mod +++ b/go.mod @@ -4,17 +4,20 @@ go 1.26.2 require ( github.com/google/uuid v1.6.0 + github.com/minio/selfupdate v0.6.0 github.com/spf13/cobra v1.10.2 modernc.org/sqlite v1.48.2 ) require ( + aead.dev/minisign v0.2.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/ncruces/go-strftime v1.0.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/spf13/pflag v1.0.9 // indirect + golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b // indirect golang.org/x/sys v0.42.0 // indirect modernc.org/libc v1.70.0 // indirect modernc.org/mathutil v1.7.1 // indirect diff --git a/go.sum b/go.sum index a12e346..0c821d6 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +aead.dev/minisign v0.2.0 h1:kAWrq/hBRu4AARY6AlciO83xhNnW9UaC8YipS2uhLPk= +aead.dev/minisign v0.2.0/go.mod h1:zdq6LdSd9TbuSxchxwhpA9zEb9YXcVGoE8JakuiGaIQ= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= @@ -11,6 +13,8 @@ github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2 github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/minio/selfupdate v0.6.0 h1:i76PgT0K5xO9+hjzKcacQtO7+MjJ4JKA8Ak8XQ9DDwU= +github.com/minio/selfupdate v0.6.0/go.mod h1:bO02GTIPCMQFTEvE5h4DjYB58bCoZ35XLeBf0buTDdM= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= @@ -21,13 +25,30 @@ github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiT github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= +golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b h1:QAqMVf3pSa6eeTsuklijukjXBlj7Es2QQplab+/RbQ4= +golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8= golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210228012217-479acdf4ea46/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/cli/root.go b/internal/cli/root.go index 4fc821e..99d5e14 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -15,6 +15,7 @@ import ( "github.com/senguoyun-guosheng/graphmind/internal/model" "github.com/senguoyun-guosheng/graphmind/internal/proposal" "github.com/senguoyun-guosheng/graphmind/internal/tag" + "github.com/senguoyun-guosheng/graphmind/internal/update" "github.com/spf13/cobra" ) @@ -31,6 +32,7 @@ type services struct { graph *graph.Service tag *tag.Service proposal *proposal.Service + updater *update.Manager } var svc services @@ -107,6 +109,7 @@ COMMANDS Setup: init Initialize graph database gm init + update Check/apply CLI updates gm update check GLOBAL FLAGS @@ -138,8 +141,10 @@ Use "gm --help" for detailed usage, examples, and output samples.`, func init() { rootCmd.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error { - // init handles its own DB setup; skip for root-only (help/version) - if cmd.Name() == "init" || cmd.Parent() == nil { + if shouldAutoCheckForUpdates(cmd) && svc.updater != nil { + svc.updater.MaybeNotifyAndCheck() + } + if shouldSkipServiceWire(cmd) { return nil } return wireAndMigrate(cmd.Context()) @@ -162,11 +167,13 @@ func init() { rootCmd.AddCommand(grepCmd) rootCmd.AddCommand(logCmd) rootCmd.AddCommand(batchCmd) + rootCmd.AddCommand(updateCmd) } // Execute runs the root command and handles exit codes. func Execute(version string) { rootCmd.Version = version + svc.updater = update.NewManager(version) if err := rootCmd.Execute(); err != nil { code := outputError(err) os.Exit(code) @@ -283,3 +290,29 @@ func newJSONEncoder(w io.Writer) *json.Encoder { enc.SetEscapeHTML(false) return enc } + +func shouldSkipServiceWire(cmd *cobra.Command) bool { + if cmd == nil || cmd.Parent() == nil { + return true + } + return commandInTree(cmd, "init") || commandInTree(cmd, "update") +} + +func shouldAutoCheckForUpdates(cmd *cobra.Command) bool { + if quiet || cmd == nil { + return false + } + if cmd.Parent() == nil { + return false + } + return !commandInTree(cmd, "init") && !commandInTree(cmd, "update") +} + +func commandInTree(cmd *cobra.Command, name string) bool { + for current := cmd; current != nil; current = current.Parent() { + if current.Name() == name { + return true + } + } + return false +} diff --git a/internal/cli/update.go b/internal/cli/update.go new file mode 100644 index 0000000..632ae44 --- /dev/null +++ b/internal/cli/update.go @@ -0,0 +1,90 @@ +package cli + +import ( + "fmt" + + "github.com/senguoyun-guosheng/graphmind/internal/update" + "github.com/spf13/cobra" +) + +var ( + updateApplyVersion string + updateCheckBackground bool +) + +var updateCmd = &cobra.Command{ + Use: "update", + Short: "Check for or apply gm updates", + Long: `Manage GraphMind CLI updates published through GitHub Releases. + +Use "gm update check" to perform a blocking version check now. +Use "gm update apply" to download and install a newer release. + +Regular gm commands may trigger a non-blocking background update check at most +once every 24 hours. If a newer release is already known, gm prints a short +notice to stderr without changing stdout JSON output.`, +} + +var updateCheckCmd = &cobra.Command{ + Use: "check", + Short: "Check for a newer release", + Long: `Check GitHub Releases for a newer GraphMind CLI build. + +This command performs a blocking network request and refreshes the local update +cache immediately. Normal gm commands use a separate non-blocking background +check path instead.`, + RunE: func(cmd *cobra.Command, _ []string) error { + result, err := svc.updater.Check(cmd.Context(), update.CheckOptions{ + Background: updateCheckBackground, + }) + if err != nil { + return err + } + if updateCheckBackground { + return nil + } + + summary := fmt.Sprintf("Checked for updates. Current: %s. Latest: %s.", result.CurrentVersion, result.LatestVersion) + next := []string{"gm update apply — download and install the latest release"} + if !result.UpdateAvailable { + summary = fmt.Sprintf("Already up to date at %s.", result.CurrentVersion) + next = []string{"gm --version — confirm the active version"} + } + outputSuccess(result, summary, next) + return nil + }, +} + +var updateApplyCmd = &cobra.Command{ + Use: "apply", + Short: "Download and install a release", + Long: `Download the matching GitHub Release archive for the current platform and +replace the current gm executable. + +By default this installs the latest release. Use --version to pin a specific +tag such as v0.3.1.`, + RunE: func(cmd *cobra.Command, _ []string) error { + result, err := svc.updater.Apply(cmd.Context(), updateApplyVersion) + if err != nil { + return err + } + + summary := fmt.Sprintf("Installed %s.", result.InstalledVersion) + next := []string{"gm --version — confirm the installed version"} + if !result.Updated { + summary = fmt.Sprintf("Already up to date at %s.", result.InstalledVersion) + } + outputSuccess(result, summary, next) + return nil + }, +} + +func init() { + updateCmd.AddCommand(updateCheckCmd) + updateCmd.AddCommand(updateApplyCmd) + + updateCheckCmd.Flags().BoolVar(&updateCheckBackground, "background", false, "Run as a silent background refresh") + _ = updateCheckCmd.Flags().MarkHidden("background") + + updateApplyCmd.Flags().StringVar(&updateApplyVersion, "version", "", "Install a specific release tag (for example v0.3.1)") +} diff --git a/internal/update/archive.go b/internal/update/archive.go new file mode 100644 index 0000000..16934cf --- /dev/null +++ b/internal/update/archive.go @@ -0,0 +1,97 @@ +package update + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "fmt" + "io" + "path" +) + +func archiveName(tag, goos, goarch string) string { + extension := ".tar.gz" + if goos == "windows" { + extension = ".zip" + } + return fmt.Sprintf("gm-%s-%s-%s%s", tag, goos, goarch, extension) +} + +func extractBinary(archive []byte, goos string) ([]byte, error) { + name := "gm" + if goos == "windows" { + name = "gm.exe" + return extractZipBinary(archive, name) + } + return extractTarGzBinary(archive, name) +} + +func extractTarGzBinary(archive []byte, binaryName string) ([]byte, error) { + gzr, err := gzip.NewReader(bytes.NewReader(archive)) + if err != nil { + return nil, fmt.Errorf("open tar.gz archive: %w", err) + } + defer func() { + _ = gzr.Close() + }() + + tr := tar.NewReader(gzr) + var matches [][]byte + for { + header, err := tr.Next() + switch { + case err == io.EOF: + if len(matches) == 0 { + return nil, fmt.Errorf("binary %q not found in archive", binaryName) + } + if len(matches) > 1 { + return nil, fmt.Errorf("binary %q appeared multiple times in archive", binaryName) + } + return matches[0], nil + case err != nil: + return nil, fmt.Errorf("read tar.gz archive: %w", err) + } + + if path.Base(header.Name) != binaryName { + continue + } + payload, err := io.ReadAll(tr) + if err != nil { + return nil, fmt.Errorf("read %q from archive: %w", binaryName, err) + } + matches = append(matches, payload) + } +} + +func extractZipBinary(archive []byte, binaryName string) ([]byte, error) { + zr, err := zip.NewReader(bytes.NewReader(archive), int64(len(archive))) + if err != nil { + return nil, fmt.Errorf("open zip archive: %w", err) + } + + var matches [][]byte + for _, file := range zr.File { + if path.Base(file.Name) != binaryName { + continue + } + rc, err := file.Open() + if err != nil { + return nil, fmt.Errorf("open %q in archive: %w", binaryName, err) + } + payload, err := io.ReadAll(rc) + rc.Close() + if err != nil { + return nil, fmt.Errorf("read %q from archive: %w", binaryName, err) + } + matches = append(matches, payload) + } + + if len(matches) == 0 { + return nil, fmt.Errorf("binary %q not found in archive", binaryName) + } + if len(matches) > 1 { + return nil, fmt.Errorf("binary %q appeared multiple times in archive", binaryName) + } + return matches[0], nil +} diff --git a/internal/update/manager.go b/internal/update/manager.go new file mode 100644 index 0000000..1231183 --- /dev/null +++ b/internal/update/manager.go @@ -0,0 +1,438 @@ +package update + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "runtime" + "strings" + "time" + + "github.com/minio/selfupdate" +) + +const ( + defaultOwner = "GuoMonth" + defaultRepo = "graphmind" + defaultCheckInterval = 24 * time.Hour + defaultLockTTL = 15 * time.Minute + backgroundCheckTimeout = 750 * time.Millisecond + maxArchiveBytes = 100 << 20 + defaultGitHubAPIBase = "https://api.github.com/repos/GuoMonth/graphmind" + defaultInstallCommand = "gm update apply" + backgroundCheckFlag = "--background" + backgroundCheckSubcmd = "check" + backgroundParentSubcmd = "update" +) + +// Manager handles release discovery, update cache state, and binary replacement. +type Manager struct { + currentVersion string + client *http.Client + apiBase string + cachePath string + lockPath string + stderr io.Writer + now func() time.Time + goos string + goarch string + + executablePath func() (string, error) + startProcess func(string, ...string) error + applyBinary func([]byte) error +} + +// NewManager constructs an updater configured for the current build and platform. +func NewManager(currentVersion string) *Manager { + cacheDir := defaultCacheDir() + return &Manager{ + currentVersion: currentVersion, + client: &http.Client{ + Timeout: 5 * time.Second, + }, + apiBase: defaultGitHubAPIBase, + cachePath: filepath.Join(cacheDir, "update.json"), + lockPath: filepath.Join(cacheDir, "update.lock"), + stderr: os.Stderr, + now: time.Now, + goos: runtime.GOOS, + goarch: runtime.GOARCH, + executablePath: os.Executable, + startProcess: startDetachedProcess, + applyBinary: defaultApplyBinary, + } +} + +// MaybeNotifyAndCheck prints a cached update hint to stderr and schedules a background +// refresh when the cached result is missing or older than the configured interval. +func (m *Manager) MaybeNotifyAndCheck() { + state, err := m.loadState() + if err == nil && state.UpdateAvailable && state.CheckedVersion == m.currentVersion && state.LatestVersion != "" { + _, _ = fmt.Fprintf( + m.stderr, + "gm update available: %s (current %s). Run %q to install.\n", + state.LatestVersion, + m.currentVersion, + defaultInstallCommand, + ) + } + if !shouldAutoCheck(&state, m.currentVersion, m.now()) { + return + } + _ = m.startBackgroundCheck() +} + +// Check queries GitHub Releases for the latest version and updates the local cache. +func (m *Manager) Check(ctx context.Context, options CheckOptions) (CheckResult, error) { + if options.Background { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(context.Background(), backgroundCheckTimeout) + defer cancel() + + unlock, ok, err := m.tryAcquireLock() + if err != nil || !ok { + return CheckResult{}, nil + } + defer unlock() + } + + release, err := m.fetchLatestRelease(ctx) + if err != nil { + _ = m.saveState(&State{ + CheckedAt: m.now().UTC(), + CheckedVersion: m.currentVersion, + LastError: err.Error(), + }) + if options.Background { + return CheckResult{}, nil + } + return CheckResult{}, err + } + + asset, err := m.findAsset(release) + if err != nil { + _ = m.saveState(&State{ + CheckedAt: m.now().UTC(), + CheckedVersion: m.currentVersion, + LatestVersion: release.TagName, + ReleaseURL: releaseURLFor(release), + LastError: err.Error(), + }) + if options.Background { + return CheckResult{}, nil + } + return CheckResult{}, err + } + + status, available := updateStatus(m.currentVersion, release.TagName) + result := CheckResult{ + Status: status, + CurrentVersion: m.currentVersion, + LatestVersion: release.TagName, + UpdateAvailable: available, + AssetName: asset.Name, + ReleaseURL: releaseURLFor(release), + InstallCommand: defaultInstallCommand, + CheckedAt: m.now().UTC(), + } + if err := m.saveState(&State{ + CheckedAt: result.CheckedAt, + CheckedVersion: m.currentVersion, + LatestVersion: result.LatestVersion, + UpdateAvailable: result.UpdateAvailable, + AssetName: result.AssetName, + DownloadURL: asset.BrowserDownloadURL, + ReleaseURL: result.ReleaseURL, + }); err != nil && !options.Background { + return CheckResult{}, err + } + return result, nil +} + +// Apply downloads the matching release asset and replaces the current binary. +func (m *Manager) Apply(ctx context.Context, targetVersion string) (ApplyResult, error) { + release, err := m.fetchRelease(ctx, targetVersion) + if err != nil { + return ApplyResult{}, err + } + status, available := updateStatus(m.currentVersion, release.TagName) + if strings.TrimSpace(targetVersion) == "" && !available && status == "up_to_date" { + executablePath, _ := m.executablePath() + return ApplyResult{ + Status: "up_to_date", + PreviousVersion: m.currentVersion, + InstalledVersion: release.TagName, + Updated: false, + TargetPath: executablePath, + ReleaseURL: releaseURLFor(release), + }, nil + } + + asset, err := m.findAsset(release) + if err != nil { + return ApplyResult{}, err + } + archive, err := m.downloadAsset(ctx, asset) + if err != nil { + return ApplyResult{}, err + } + if err := verifyAssetDigest(archive, asset.Digest); err != nil { + return ApplyResult{}, err + } + binary, err := extractBinary(archive, m.goos) + if err != nil { + return ApplyResult{}, err + } + if err := m.applyBinary(binary); err != nil { + return ApplyResult{}, err + } + + executablePath, _ := m.executablePath() + result := ApplyResult{ + Status: "updated", + PreviousVersion: m.currentVersion, + InstalledVersion: release.TagName, + Updated: true, + AssetName: asset.Name, + ReleaseURL: releaseURLFor(release), + TargetPath: executablePath, + } + _ = m.saveState(&State{ + CheckedAt: m.now().UTC(), + CheckedVersion: release.TagName, + LatestVersion: release.TagName, + UpdateAvailable: false, + AssetName: asset.Name, + DownloadURL: asset.BrowserDownloadURL, + ReleaseURL: result.ReleaseURL, + }) + return result, nil +} + +func (m *Manager) fetchRelease(ctx context.Context, targetVersion string) (Release, error) { + tag := canonicalVersionTag(targetVersion) + if tag == "" { + return m.fetchLatestRelease(ctx) + } + return m.fetchReleaseByTag(ctx, tag) +} + +func (m *Manager) fetchLatestRelease(ctx context.Context) (Release, error) { + return m.getRelease(ctx, m.apiBase+"/releases/latest") +} + +func (m *Manager) fetchReleaseByTag(ctx context.Context, tag string) (Release, error) { + return m.getRelease(ctx, m.apiBase+"/releases/tags/"+tag) +} + +func (m *Manager) getRelease(ctx context.Context, endpoint string) (Release, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, http.NoBody) + if err != nil { + return Release{}, fmt.Errorf("create update request: %w", err) + } + req.Header.Set("Accept", "application/vnd.github+json") + req.Header.Set("User-Agent", "graphmind/"+m.currentVersion) + + resp, err := m.client.Do(req) + if err != nil { + return Release{}, fmt.Errorf("fetch release metadata: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return Release{}, fmt.Errorf("fetch release metadata: unexpected status %d: %s", resp.StatusCode, strings.TrimSpace(string(body))) + } + + var release Release + if err := json.NewDecoder(resp.Body).Decode(&release); err != nil { + return Release{}, fmt.Errorf("decode release metadata: %w", err) + } + if release.TagName == "" { + return Release{}, fmt.Errorf("decode release metadata: missing tag_name") + } + return release, nil +} + +func (m *Manager) findAsset(release Release) (Asset, error) { + expected := archiveName(release.TagName, m.goos, m.goarch) + for _, asset := range release.Assets { + if asset.Name == expected { + return asset, nil + } + } + return Asset{}, fmt.Errorf("no release asset for %s/%s (expected %s)", m.goos, m.goarch, expected) +} + +func (m *Manager) downloadAsset(ctx context.Context, asset Asset) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, asset.BrowserDownloadURL, http.NoBody) + if err != nil { + return nil, fmt.Errorf("create asset request: %w", err) + } + req.Header.Set("User-Agent", "graphmind/"+m.currentVersion) + + resp, err := m.client.Do(req) + if err != nil { + return nil, fmt.Errorf("download update archive: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return nil, fmt.Errorf("download update archive: unexpected status %d: %s", resp.StatusCode, strings.TrimSpace(string(body))) + } + + if resp.ContentLength > maxArchiveBytes { + return nil, fmt.Errorf("download update archive: asset too large (%d bytes)", resp.ContentLength) + } + + data, err := io.ReadAll(io.LimitReader(resp.Body, maxArchiveBytes+1)) + if err != nil { + return nil, fmt.Errorf("read update archive: %w", err) + } + if int64(len(data)) > maxArchiveBytes { + return nil, fmt.Errorf("download update archive: asset exceeded %d bytes", maxArchiveBytes) + } + return data, nil +} + +func (m *Manager) loadState() (State, error) { + data, err := os.ReadFile(m.cachePath) + if err != nil { + if os.IsNotExist(err) { + return State{}, nil + } + return State{}, fmt.Errorf("read update cache: %w", err) + } + var state State + if err := json.Unmarshal(data, &state); err != nil { + return State{}, fmt.Errorf("decode update cache: %w", err) + } + return state, nil +} + +func (m *Manager) saveState(state *State) error { + if err := os.MkdirAll(filepath.Dir(m.cachePath), 0o755); err != nil { + return fmt.Errorf("create update cache directory: %w", err) + } + data, err := json.Marshal(state) + if err != nil { + return fmt.Errorf("encode update cache: %w", err) + } + tmpPath := m.cachePath + ".tmp" + if err := os.WriteFile(tmpPath, data, 0o644); err != nil { + return fmt.Errorf("write update cache: %w", err) + } + if err := os.Rename(tmpPath, m.cachePath); err != nil { + return fmt.Errorf("replace update cache: %w", err) + } + return nil +} + +func (m *Manager) tryAcquireLock() (unlock func(), ok bool, err error) { + if err := os.MkdirAll(filepath.Dir(m.lockPath), 0o755); err != nil { + return nil, false, fmt.Errorf("create update lock directory: %w", err) + } + + for attempt := 0; attempt < 2; attempt++ { + file, err := os.OpenFile(m.lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) + if err == nil { + _, _ = file.WriteString(m.now().UTC().Format(time.RFC3339)) + _ = file.Close() + return func() { + _ = os.Remove(m.lockPath) + }, true, nil + } + if !errors.Is(err, os.ErrExist) { + return nil, false, fmt.Errorf("create update lock: %w", err) + } + info, statErr := os.Stat(m.lockPath) + if statErr != nil { + if os.IsNotExist(statErr) { + continue + } + return nil, false, fmt.Errorf("stat update lock: %w", statErr) + } + if m.now().Sub(info.ModTime()) <= defaultLockTTL { + return nil, false, nil + } + if removeErr := os.Remove(m.lockPath); removeErr != nil && !os.IsNotExist(removeErr) { + return nil, false, fmt.Errorf("remove stale update lock: %w", removeErr) + } + } + return nil, false, nil +} + +func (m *Manager) startBackgroundCheck() error { + executablePath, err := m.executablePath() + if err != nil { + return err + } + return m.startProcess(executablePath, backgroundParentSubcmd, backgroundCheckSubcmd, backgroundCheckFlag) +} + +func shouldAutoCheck(state *State, currentVersion string, now time.Time) bool { + if state == nil { + return true + } + if state.CheckedAt.IsZero() { + return true + } + if state.CheckedVersion != currentVersion { + return true + } + return now.Sub(state.CheckedAt) >= defaultCheckInterval +} + +func verifyAssetDigest(payload []byte, digest string) error { + if strings.TrimSpace(digest) == "" { + return nil + } + const prefix = "sha256:" + if !strings.HasPrefix(digest, prefix) { + return fmt.Errorf("unsupported asset digest format %q", digest) + } + expected, err := hex.DecodeString(strings.TrimPrefix(digest, prefix)) + if err != nil { + return fmt.Errorf("decode asset digest: %w", err) + } + sum := sha256.Sum256(payload) + if !bytes.Equal(sum[:], expected) { + return fmt.Errorf("update archive checksum mismatch") + } + return nil +} + +func releaseURLFor(release Release) string { + if release.HTMLURL != "" { + return release.HTMLURL + } + return fmt.Sprintf("https://github.com/%s/%s/releases/tag/%s", defaultOwner, defaultRepo, release.TagName) +} + +func defaultCacheDir() string { + cacheDir, err := os.UserCacheDir() + if err != nil { + return filepath.Join(os.TempDir(), "graphmind") + } + return filepath.Join(cacheDir, "graphmind") +} + +func defaultApplyBinary(binary []byte) error { + err := selfupdate.Apply(bytes.NewReader(binary), selfupdate.Options{}) + if err == nil { + return nil + } + if rollbackErr := selfupdate.RollbackError(err); rollbackErr != nil { + return fmt.Errorf("apply update: %w (rollback failed: %v)", err, rollbackErr) + } + return fmt.Errorf("apply update: %w", err) +} diff --git a/internal/update/manager_test.go b/internal/update/manager_test.go new file mode 100644 index 0000000..0153384 --- /dev/null +++ b/internal/update/manager_test.go @@ -0,0 +1,315 @@ +package update + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestCheckWritesStateAndFindsPlatformAsset(t *testing.T) { + release := Release{ + TagName: "v1.2.0", + HTMLURL: "https://example.invalid/releases/v1.2.0", + Assets: []Asset{ + {Name: "gm-v1.2.0-darwin-arm64.tar.gz", BrowserDownloadURL: "https://example.invalid/darwin-arm64.tar.gz"}, + }, + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/releases/latest" { + t.Fatalf("unexpected path: %s", r.URL.Path) + } + if err := json.NewEncoder(w).Encode(release); err != nil { + t.Fatalf("encode response: %v", err) + } + })) + defer server.Close() + + manager := newTestManager(t) + manager.apiBase = server.URL + manager.goos = "darwin" + manager.goarch = "arm64" + manager.currentVersion = "v1.1.0" + manager.now = func() time.Time { return time.Date(2026, 4, 14, 8, 0, 0, 0, time.UTC) } + + result, err := manager.Check(context.Background(), CheckOptions{}) + if err != nil { + t.Fatalf("check updates: %v", err) + } + + if result.Status != "update_available" { + t.Fatalf("status = %q, want update_available", result.Status) + } + if !result.UpdateAvailable { + t.Fatalf("expected update available") + } + if result.AssetName != "gm-v1.2.0-darwin-arm64.tar.gz" { + t.Fatalf("asset name = %q", result.AssetName) + } + + state, err := manager.loadState() + if err != nil { + t.Fatalf("load state: %v", err) + } + if state.LatestVersion != "v1.2.0" { + t.Fatalf("latest version = %q", state.LatestVersion) + } + if !state.UpdateAvailable { + t.Fatalf("expected cached update availability") + } +} + +func TestMaybeNotifyAndCheckUsesCachedAvailability(t *testing.T) { + manager := newTestManager(t) + manager.currentVersion = "v1.0.0" + manager.now = func() time.Time { return time.Date(2026, 4, 14, 8, 0, 0, 0, time.UTC) } + + if err := manager.saveState(&State{ + CheckedAt: manager.now(), + CheckedVersion: "v1.0.0", + LatestVersion: "v1.1.0", + UpdateAvailable: true, + }); err != nil { + t.Fatalf("save state: %v", err) + } + + var spawned []string + manager.startProcess = func(name string, args ...string) error { + spawned = append([]string{name}, args...) + return nil + } + + manager.MaybeNotifyAndCheck() + + if got := manager.stderr.(*bytes.Buffer).String(); !strings.Contains(got, `gm update available: v1.1.0 (current v1.0.0). Run "gm update apply" to install.`) { + t.Fatalf("stderr = %q", got) + } + if len(spawned) != 0 { + t.Fatalf("expected no background spawn for fresh cache, got %v", spawned) + } +} + +func TestMaybeNotifyAndCheckStartsBackgroundWhenStale(t *testing.T) { + manager := newTestManager(t) + manager.currentVersion = "v1.0.0" + now := time.Date(2026, 4, 14, 8, 0, 0, 0, time.UTC) + manager.now = func() time.Time { return now } + + if err := manager.saveState(&State{ + CheckedAt: now.Add(-25 * time.Hour), + CheckedVersion: "v1.0.0", + LatestVersion: "v1.0.0", + }); err != nil { + t.Fatalf("save state: %v", err) + } + + var spawned []string + manager.executablePath = func() (string, error) { return "/tmp/gm", nil } + manager.startProcess = func(name string, args ...string) error { + spawned = append([]string{name}, args...) + return nil + } + + manager.MaybeNotifyAndCheck() + + want := []string{"/tmp/gm", "update", "check", "--background"} + if strings.Join(spawned, " ") != strings.Join(want, " ") { + t.Fatalf("spawned = %v, want %v", spawned, want) + } +} + +func TestApplyDownloadsArchiveVerifiesDigestAndPassesBinary(t *testing.T) { + archive := mustTarGzBinary(t, "gm", []byte("new-binary")) + sum := sha256.Sum256(archive) + digest := "sha256:" + hex.EncodeToString(sum[:]) + + var serverURL string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/releases/latest": + release := Release{ + TagName: "v1.2.0", + HTMLURL: "https://example.invalid/releases/v1.2.0", + Assets: []Asset{ + { + Name: "gm-v1.2.0-linux-amd64.tar.gz", + BrowserDownloadURL: serverURL + "/assets/linux-amd64.tar.gz", + Digest: digest, + }, + }, + } + if err := json.NewEncoder(w).Encode(release); err != nil { + t.Fatalf("encode release: %v", err) + } + case "/assets/linux-amd64.tar.gz": + _, _ = w.Write(archive) + default: + t.Fatalf("unexpected path: %s", r.URL.Path) + } + })) + defer server.Close() + serverURL = server.URL + + manager := newTestManager(t) + manager.apiBase = server.URL + manager.goos = "linux" + manager.goarch = "amd64" + manager.currentVersion = "v1.1.0" + manager.executablePath = func() (string, error) { return "/usr/local/bin/gm", nil } + + var applied []byte + manager.applyBinary = func(binary []byte) error { + applied = append([]byte(nil), binary...) + return nil + } + + result, err := manager.Apply(context.Background(), "") + if err != nil { + t.Fatalf("apply update: %v", err) + } + if !result.Updated { + t.Fatalf("expected update to be applied") + } + if string(applied) != "new-binary" { + t.Fatalf("applied payload = %q", string(applied)) + } +} + +func TestApplyReturnsUpToDateWithoutDownload(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + release := Release{ + TagName: "v1.2.0", + Assets: []Asset{ + {Name: "gm-v1.2.0-linux-amd64.tar.gz", BrowserDownloadURL: "https://example.invalid/linux-amd64.tar.gz"}, + }, + } + if err := json.NewEncoder(w).Encode(release); err != nil { + t.Fatalf("encode release: %v", err) + } + })) + defer server.Close() + + manager := newTestManager(t) + manager.apiBase = server.URL + manager.goos = "linux" + manager.goarch = "amd64" + manager.currentVersion = "v1.2.0" + manager.executablePath = func() (string, error) { return "/usr/local/bin/gm", nil } + manager.applyBinary = func(binary []byte) error { + t.Fatalf("applyBinary should not be called when already up to date") + return nil + } + + result, err := manager.Apply(context.Background(), "") + if err != nil { + t.Fatalf("apply update: %v", err) + } + if result.Status != "up_to_date" || result.Updated { + t.Fatalf("unexpected result: %+v", result) + } +} + +func TestDownloadAssetRejectsOversizedPayload(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "104857601") + _, _ = w.Write([]byte("x")) + })) + defer server.Close() + + manager := newTestManager(t) + _, err := manager.downloadAsset(context.Background(), Asset{ + Name: "gm-v1.2.0-linux-amd64.tar.gz", + BrowserDownloadURL: server.URL, + }) + if err == nil || !strings.Contains(err.Error(), "asset too large") { + t.Fatalf("err = %v, want asset too large", err) + } +} + +func TestExtractZipBinary(t *testing.T) { + archive := mustZipBinary(t, "gm.exe", []byte("windows-binary")) + got, err := extractBinary(archive, "windows") + if err != nil { + t.Fatalf("extract binary: %v", err) + } + if string(got) != "windows-binary" { + t.Fatalf("binary = %q", string(got)) + } +} + +func newTestManager(t *testing.T) *Manager { + t.Helper() + dir := t.TempDir() + return &Manager{ + currentVersion: "v0.0.0", + client: &http.Client{Timeout: 2 * time.Second}, + apiBase: "https://example.invalid", + cachePath: filepath.Join(dir, "update.json"), + lockPath: filepath.Join(dir, "update.lock"), + stderr: &bytes.Buffer{}, + now: time.Now, + goos: "linux", + goarch: "amd64", + executablePath: func() (string, error) { return "/tmp/gm", nil }, + startProcess: func(string, ...string) error { return nil }, + applyBinary: func([]byte) error { return nil }, + } +} + +func mustTarGzBinary(t *testing.T, name string, payload []byte) []byte { + t.Helper() + var archive bytes.Buffer + gzw := gzip.NewWriter(&archive) + tw := tar.NewWriter(gzw) + header := &tar.Header{ + Name: name, + Mode: 0o755, + Size: int64(len(payload)), + } + if err := tw.WriteHeader(header); err != nil { + t.Fatalf("write tar header: %v", err) + } + if _, err := tw.Write(payload); err != nil { + t.Fatalf("write tar payload: %v", err) + } + if err := tw.Close(); err != nil { + t.Fatalf("close tar writer: %v", err) + } + if err := gzw.Close(); err != nil { + t.Fatalf("close gzip writer: %v", err) + } + return archive.Bytes() +} + +func mustZipBinary(t *testing.T, name string, payload []byte) []byte { + t.Helper() + var archive bytes.Buffer + zw := zip.NewWriter(&archive) + file, err := zw.Create(name) + if err != nil { + t.Fatalf("create zip file: %v", err) + } + if _, err := io.Copy(file, bytes.NewReader(payload)); err != nil { + t.Fatalf("write zip payload: %v", err) + } + if err := zw.Close(); err != nil { + t.Fatalf("close zip writer: %v", err) + } + return archive.Bytes() +} + +func TestMain(m *testing.M) { + os.Exit(m.Run()) +} diff --git a/internal/update/process_unix.go b/internal/update/process_unix.go new file mode 100644 index 0000000..cd56845 --- /dev/null +++ b/internal/update/process_unix.go @@ -0,0 +1,24 @@ +//go:build !windows + +package update + +import ( + "context" + "io" + "os/exec" + "syscall" +) + +func startDetachedProcess(name string, args ...string) error { + cmd := exec.CommandContext(context.Background(), name, args...) + cmd.Stdin = nil + cmd.Stdout = io.Discard + cmd.Stderr = io.Discard + cmd.SysProcAttr = &syscall.SysProcAttr{ + Setsid: true, + } + if err := cmd.Start(); err != nil { + return err + } + return cmd.Process.Release() +} diff --git a/internal/update/process_windows.go b/internal/update/process_windows.go new file mode 100644 index 0000000..989bf53 --- /dev/null +++ b/internal/update/process_windows.go @@ -0,0 +1,26 @@ +//go:build windows + +package update + +import ( + "context" + "io" + "os/exec" + "syscall" +) + +const createNewProcessGroup = 0x00000200 + +func startDetachedProcess(name string, args ...string) error { + cmd := exec.CommandContext(context.Background(), name, args...) + cmd.Stdin = nil + cmd.Stdout = io.Discard + cmd.Stderr = io.Discard + cmd.SysProcAttr = &syscall.SysProcAttr{ + CreationFlags: createNewProcessGroup, + } + if err := cmd.Start(); err != nil { + return err + } + return cmd.Process.Release() +} diff --git a/internal/update/types.go b/internal/update/types.go new file mode 100644 index 0000000..a4faa46 --- /dev/null +++ b/internal/update/types.go @@ -0,0 +1,57 @@ +package update + +import "time" + +// Release is the subset of GitHub release metadata used by gm updates. +type Release struct { + TagName string `json:"tag_name"` + HTMLURL string `json:"html_url"` + Assets []Asset `json:"assets"` +} + +// Asset is one downloadable archive attached to a GitHub release. +type Asset struct { + Name string `json:"name"` + BrowserDownloadURL string `json:"browser_download_url"` + Digest string `json:"digest,omitempty"` +} + +// State caches the last update check result for non-blocking CLI startup checks. +type State struct { + CheckedAt time.Time `json:"checked_at"` + CheckedVersion string `json:"checked_version"` + LatestVersion string `json:"latest_version,omitempty"` + UpdateAvailable bool `json:"update_available"` + AssetName string `json:"asset_name,omitempty"` + DownloadURL string `json:"download_url,omitempty"` + ReleaseURL string `json:"release_url,omitempty"` + LastError string `json:"last_error,omitempty"` +} + +// CheckOptions controls how an update check runs. +type CheckOptions struct { + Background bool +} + +// CheckResult is the structured stdout payload for gm update check. +type CheckResult struct { + Status string `json:"status"` + CurrentVersion string `json:"current_version"` + LatestVersion string `json:"latest_version,omitempty"` + UpdateAvailable bool `json:"update_available"` + AssetName string `json:"asset_name,omitempty"` + ReleaseURL string `json:"release_url,omitempty"` + InstallCommand string `json:"install_command,omitempty"` + CheckedAt time.Time `json:"checked_at"` +} + +// ApplyResult is the structured stdout payload for gm update apply. +type ApplyResult struct { + Status string `json:"status"` + PreviousVersion string `json:"previous_version"` + InstalledVersion string `json:"installed_version"` + Updated bool `json:"updated"` + AssetName string `json:"asset_name,omitempty"` + ReleaseURL string `json:"release_url,omitempty"` + TargetPath string `json:"target_path,omitempty"` +} diff --git a/internal/update/version.go b/internal/update/version.go new file mode 100644 index 0000000..bd3673b --- /dev/null +++ b/internal/update/version.go @@ -0,0 +1,96 @@ +package update + +import ( + "strconv" + "strings" +) + +type semVersion struct { + major int + minor int + patch int +} + +func compareVersions(current, latest string) (int, bool) { + a, ok := parseSemVersion(current) + if !ok { + return 0, false + } + b, ok := parseSemVersion(latest) + if !ok { + return 0, false + } + switch { + case a.major != b.major: + if a.major < b.major { + return -1, true + } + return 1, true + case a.minor != b.minor: + if a.minor < b.minor { + return -1, true + } + return 1, true + case a.patch != b.patch: + if a.patch < b.patch { + return -1, true + } + return 1, true + default: + return 0, true + } +} + +func parseSemVersion(raw string) (semVersion, bool) { + value := strings.TrimSpace(raw) + value = strings.TrimPrefix(value, "v") + parts := strings.Split(value, ".") + if len(parts) != 3 { + return semVersion{}, false + } + major, err := strconv.Atoi(parts[0]) + if err != nil { + return semVersion{}, false + } + minor, err := strconv.Atoi(parts[1]) + if err != nil { + return semVersion{}, false + } + patch, err := strconv.Atoi(parts[2]) + if err != nil { + return semVersion{}, false + } + return semVersion{major: major, minor: minor, patch: patch}, true +} + +func canonicalVersionTag(raw string) string { + value := strings.TrimSpace(raw) + if value == "" { + return "" + } + if _, ok := parseSemVersion(value); ok && !strings.HasPrefix(value, "v") { + return "v" + value + } + return value +} + +func updateStatus(current, latest string) (string, bool) { + current = strings.TrimSpace(current) + latest = strings.TrimSpace(latest) + if latest == "" { + return "unknown", false + } + if current == latest { + return "up_to_date", false + } + if cmp, ok := compareVersions(current, latest); ok { + if cmp < 0 { + return "update_available", true + } + return "up_to_date", false + } + if current == "" { + return "update_available", true + } + return "update_available", true +}