Compare commits

..

No commits in common. "main" and "feat/mozilla-plugin-v2.3.0" have entirely different histories.

18 changed files with 31 additions and 773 deletions

View file

@ -15,11 +15,6 @@ conflict copies, snapshot history, and structured tools for your AI coding agent
---
> 🛠️ **Source-only reliability fixes (unreleased):** push-conflict retries preserve
> peer edits, hub push acceptance is atomic, and the shell installer preserves literal
> destination paths. Published binaries remain **v2.3.0**. See the
> [fixes and verification scope](docs/reliability-fixes.md).
## 🔒 Built-in Tailscale, one hub binary
Run your own sync hub on a NAS, Pi, server, or spare computer. **The hub can join
@ -96,11 +91,8 @@ flowchart LR
Client -->|"regular Tailscale app"| Hub["Hub with embedded Tailscale"]
```
**Mozilla AI integration, native Go:** v2.3.0 ships an optional
`devbox-mcpd-plugin` built with Mozilla's official Go plugin SDK. It records
tool-request metadata without logging arguments or file contents. Use the
[tested mcpd setup](examples/mcpd/README.md) to enable it alongside devbox's
built-in MCP server; Go and PHP plugins share mcpd's middleware protocol.
**Mozilla AI mcpd supported:** use the [tested daemon configuration](examples/mcpd/README.md)
to manage devbox through mcpd, with optional Go or PHP middleware plugins.
Read the [MCP setup guide](docs/MCP.md) for tool names, configuration, execution
limits, and errors, or the [implementation plan](docs/MCP-PLAN.md) for scope.
@ -142,10 +134,6 @@ curl -fsSL https://git.shoemoney.ai/shoemoney/devbox-dist/releases/download/late
sh install.sh --hub --no-service
```
For the optional native Mozilla mcpd plugin (v2.3.0+), run
`sh install.sh --mcpd-plugin --no-service`; see the
[mcpd guide](examples/mcpd/README.md) for registration.
`--service` installs a keep-alive service for the **client sync daemon**. Run the
hub separately, or configure its own service with the `serve` arguments below.
@ -160,16 +148,8 @@ the [Forgejo distribution mirror](https://git.shoemoney.ai/shoemoney/devbox-dist
Both are public. Release downloads include `devbox` and `devbox-hub` for Linux amd64/arm64/arm,
macOS amd64/arm64, and Windows amd64, plus `SHA256SUMS`. The shell installer
supports amd64 and arm64; download the Linux arm binaries directly for 32-bit Pi OS.
The optional `devbox-mcpd-plugin` has matching platform binaries.
Use `--release-url` / `DEVBOX_RELEASE_URL` to select a versioned release.
🛠️ **Unreleased shell installer behavior:** in the source checkout, `--bin-dir DIR`
or `DEVBOX_BIN_DIR` treats the destination literally, expanding only a leading
`~/` to the home directory. Quote the value so your calling shell preserves spaces,
`$` signs, and backticks; the installer does not evaluate them. For example:
`sh ./install.sh --bin-dir '~/tools with spaces/bin' --no-service`.
This fix is not yet in the release-hosted installer linked above.
## 🚀 Tailscale quick start
### 1. Start your private hub
@ -365,10 +345,10 @@ pinned Tailscale dependency. Downloading prebuilt binaries needs no Go toolchain
go build ./cmd/devbox ./cmd/devbox-hub
go vet ./...
go test -race ./...
VERSION=v2.3.0 ./scripts/build-release.sh
VERSION=v2.2.0 ./scripts/build-release.sh
```
The release script cross-compiles the client, hub, and optional mcpd plugin for six platform/architecture
The release script cross-compiles both binaries for six platform/architecture
combinations and generates checksums. Public binaries are available through
[GitHub Releases](https://github.com/shoemoney/devbox/releases) and the Forgejo
[`devbox-dist`](https://git.shoemoney.ai/shoemoney/devbox-dist) mirror. The default

View file

@ -71,11 +71,8 @@ mcpd v0.7.0 and devbox v2.2.0 on Linux, including authenticated snapshot history
Mozilla's [Go plugin SDK](https://github.com/mozilla-ai/mcpd-plugins-sdk-go) and
the community [PHP plugin SDK](https://github.com/shoemoney/mcpd-plugins-sdk-php)
provide middleware around daemon requests/responses. In v2.3.0, the optional
`devbox-mcpd-plugin` uses Mozilla's Go SDK to record metadata for devbox tool
requests without logging payloads. Install it with `--mcpd-plugin` and follow
the [native plugin setup](../examples/mcpd/README.md#use-the-native-mozilla-go-sdk-plugin-v230).
The daemon can also manage the tool server without enabling this plugin.
provide optional middleware around daemon requests/responses. Devbox's native
MCP tools work through mcpd without adding a plugin dependency.
## Available tools

View file

@ -1,60 +0,0 @@
# v2.3.0 — Native Mozilla AI Go SDK integration
Devbox now ships an optional **native mcpd middleware plugin**, built with
Mozilla AI's official [`mcpd-plugins-sdk-go`](https://github.com/mozilla-ai/mcpd-plugins-sdk-go).
## Install the plugin
```bash
curl -fsSL https://git.shoemoney.ai/shoemoney/devbox-dist/releases/download/latest/install.sh -o install.sh
sh install.sh --mcpd-plugin --no-service
```
The PowerShell installer supports `-McpdPlugin`. Releases include the plugin
alongside the client and hub for Linux amd64/arm64/arm, macOS amd64/arm64,
and Windows amd64.
Register `devbox-mcpd-plugin` in mcpd's plugin directory and enable its optional
request observability flow. The [tested setup guide](https://github.com/shoemoney/devbox/tree/main/examples/mcpd)
includes complete configuration and a PHP HTTP example.
The plugin records the tool name, HTTP method, event, and plugin version for
recognized devbox tool requests. It leaves the request unchanged and excludes
arguments, bodies, headers, queries, identities, addresses, filenames, and file
contents from audit records. It is request telemetry, not a durable transaction
history or proof an operation completed. Existing tool permissions still apply.
## Built-in MCP and Tailscale remain available
```bash
codex mcp add devbox -- /absolute/path/to/devbox mcp
devbox-hub serve --data ./hub-data --tailscale
```
The client serves structured agent tools over local stdio. The hub embeds
Tailscale, while client machines use their regular Tailscale connection. mcpd
can manage the tool server with or without the optional plugin.
![Actual Tailscale CLI help](https://raw.githubusercontent.com/shoemoney/devbox/main/docs/images/tailscale-help.png)
![MCP discovery and selected status fields](https://raw.githubusercontent.com/shoemoney/devbox/main/docs/images/mcp-tools.png)
The CLI/MCP screenshots were captured from v2.2.0; that tool surface remains in
v2.3.0. The live dashboard capture uses an isolated local demo, not production
Tailscale enrollment.
## Downloads
Each release provides **18 binaries**, both installers, and `SHA256SUMS`:
21 assets, with hashes for all 20 payloads. Public downloads are on GitHub and
Forgejo. Prebuilt binaries require no Go toolchain; source builds require Go
1.27.4 or newer. Mozilla's Go plugin SDK is pinned to v0.1.1.
## Verification
Passed vet and the full race suite, SDK gRPC lifecycle and request tests,
concurrent audit tests, payload-exclusion checks, installer smoke, and nine
publication tests. A real mcpd v0.7.0 instance loaded the native plugin, served
devbox tool calls, emitted metadata records without header/query/body sentinels,
kept the write allowlist enforced, and stopped the plugin without a forced kill.
PowerShell installer execution was not available in the validation environment.

View file

@ -1,67 +0,0 @@
# 🛠️ Reliability fixes — unreleased source
> 📌 **2026-11-28:** these four accepted changes are integrated in source.
> Published binaries remain **v2.3.0**. This cycle has not released or deployed
> them, and release-hosted installers do not yet contain the path fix.
## 🔧 What changed
| Fix | Result |
|---|---|
| 🔄 Sync retry base | A rejected push retains the last locally applied base. The next pull merges the advanced hub head, preserving disjoint peer changes and same-path edits through conflict copies. |
| 🔒 Atomic hub acceptance | `meta.AcceptSnapshot` takes SQLite's write lock before reading the head. Parent validation, snapshot metadata, chunk refcounts, and head update share one transaction; a stale push is rejected with the winning head. |
| 🧪 Daemon test shutdown | Both live-sync fixtures cancel and join their daemon `Run` calls before closing the hub/database or returning from the test. Assertions and timeouts are unchanged. |
| 📂 Literal installer destination | The shell installer no longer evaluates `--bin-dir` / `DEVBOX_BIN_DIR`. Only a leading `~/` expands to the home directory; spaces, quotes, dollar signs, backticks, and shell metacharacters otherwise stay literal. Quote values in the calling shell. |
Replaying the current snapshot does not double-count chunk references or announce
a head advance. Reverting to an existing snapshot requires the current parent.
`DeleteSnapshot` rechecks head protection when deleting a candidate, preserving
metadata and refcounts if the candidate became the head in the meantime.
This metadata protection does not establish safe concurrent live blob sweeping.
For the installer behavior, use the script from the source checkout:
```sh
sh ./install.sh --bin-dir '~/tools with spaces/bin' --no-service
```
The same literal-path rule applies to `DEVBOX_BIN_DIR`; it does not expand `$HOME`
written inside the value or interpret command substitutions. These changes apply
to `install.sh`; this cycle makes no PowerShell runtime-verification claim.
## 🧪 Verification scope
Independent scoped verification and review accepted all four changes. The three product regressions failed against the original v2.3.0 source
(`36690ee`) and passed with their fixes. A delayed shutdown probe reproduced the
daemon fixtures logging after test completion before their cleanup fix; the same
probe passes afterward, with shutdown logs preceding test completion. Counts below describe those scoped checks, not a full-suite
total.
| Scope | Accepted evidence |
|---|---|
| 🔄 Syncer | Race checks: 23 tests in one package; deterministic advanced-head retry covers disjoint additions, same-path edits, conflict-copy propagation, hooks, and convergence. |
| 🔒 Hub | Race checks: 50 tests across four packages, including subtests; concurrent stale-parent rejection, replay/revert, candidate head protection, pruned-snapshot restoration, and independent database connections. |
| 🧪 Daemon fixtures | `go test -race ./internal/daemon -count=3` passed; independent delayed-shutdown probes fail both original fixtures and pass both fixed fixtures. `Run` joins mount workers; this does not establish that every child goroutine is joined. |
| 📂 Shell installer | Two top-level tests: ten literal-path subcases across flag/env inputs, plus existing optional-plugin cases. |
✅ **Combined validation passed on dev3 at source `8e06d83`:** `go vet ./...`,
`go build ./...`, and `go test -race -json ./... -count=1` all exited 0. The race
run passed 171 top-level tests and 30 subtests across 19 packages; one additional
package has no tests. Nine release fixtures and two installer tests also passed.
The final docs-only update does not change the tested code.
The first combined run exposed an overlong temporary Unix socket path and the
daemon test shutdown bug. Short temporary paths address the environment limit;
the fixture cleanup fix passed the final complete rerun. This cycle does not
establish production-tailnet behavior, ARM runtime verification, or safe
concurrent live blob GC. Earlier dated ARM verification in
[the project plan](../plan.md) remains historical evidence.
## 🔎 Source and regression references
- 🔄 [Retry-base handling](../internal/syncer/pull.go) and [regression](../internal/syncer/conflict_retry_test.go).
- 🔒 [Hub acceptance](../internal/hub/server.go), [metadata transactions](../internal/hub/meta/meta.go), [HTTP race regression](../internal/hub/atomic_push_test.go), and [metadata regressions](../internal/hub/meta/atomic_push_test.go).
- 🧪 [Daemon lifecycle helper](../internal/daemon/daemon_test.go) and [pause fixture](../internal/daemon/pause_test.go).
- 📂 [Shell installer](../install.sh) and [installer tests](../scripts/test-install.py).
📦 Source fixes today; published release status stays explicit.

View file

@ -17,9 +17,8 @@ snapshot history through mcpd's HTTP API.
serves that same middleware role. `status.php` here is a plain HTTP consumer;
it does not require a plugin SDK.
The plugin SDK and the MCP tool server are separate integration points. Basic
mcpd management works without a plugin. **v2.3.0 also ships an optional native
`devbox-mcpd-plugin` built with Mozilla's official Go plugin SDK.**
The plugin SDK and the MCP tool server are separate integration points. No new
Go dependency is required in devbox for mcpd to manage it.
## 1. Install the prerequisites
@ -125,59 +124,3 @@ config and hub, but filesystem diagnostics cannot inspect the actual files.
This example does not enable mutation tools. Enabling them also requires writable
mounts, appropriate container ownership, and an updated mcpd tool allowlist.
Use the [native MCP guide](../../docs/MCP.md) for the tool permission model.
## Use the native Mozilla Go SDK plugin (v2.3.0)
Install the optional plugin along with the client:
```bash
curl -fsSL https://git.shoemoney.ai/shoemoney/devbox-dist/releases/download/latest/install.sh -o install.sh
sh install.sh --mcpd-plugin --no-service
```
On Windows the PowerShell installer supports `-McpdPlugin`. Select the plugin
binary matching the machine running **mcpd**, which may be different from
Docker's Linux architecture. The Linux binary requirement above applies to the
MCP server inside the container, not the native middleware process.
Create a dedicated plugin directory and place the executable inside it:
```bash
mkdir -p ./plugins
cp /absolute/path/to/devbox-mcpd-plugin ./plugins/devbox-mcpd-plugin
chmod 755 ./plugins/devbox-mcpd-plugin
```
Copy `mcpd-with-plugin.toml` and set `[plugins].dir` to that directory's absolute
path. The configured plugin name must match the executable filename. Start the
daemon with that configuration and your existing runtime file:
```bash
mcpd daemon --config-file ./mcpd-with-plugin.toml --runtime-file /absolute/path/to/runtime.local.toml --addr 127.0.0.1:8090 --timeout-mcp-request 150s --log-level INFO --log-path ./mcpd.log
```
mcpd launches the native plugin over its standard gRPC socket protocol. The
plugin is written against `mozilla-ai/mcpd-plugins-sdk-go`; it is a separate
native executable included in devbox releases, not a replacement for
`devbox mcp`.
The plugin records **request metadata only** for recognized devbox tool-call
routes: the event, plugin version, HTTP method, and tool name. It leaves the
request unchanged. Audit records exclude arguments, request/response bodies,
headers, query strings, user identities, network addresses, filenames, and file
contents. It does not change tool permissions or authorize a write. The
observability category is optional; these records are operational telemetry,
not a durable transaction history or proof an operation completed.
Only the request flow is advertised. Other daemon routes pass through without
a devbox audit event. mcpd captures the plugin's stderr and forwards it into its
logs. Its normal startup/lifecycle logs are separate from the audit records.
### Verified behavior
The v2.3.0 plugin was exercised in a real mcpd v0.7.0 process. It registered,
received tool requests, emitted `devbox.tool.request` records, and left
header/query/body sentinels out of those records. An unlisted write tool still
received HTTP 403. On daemon shutdown the native plugin exited without a
forced-kill warning. Unit tests also exercise the official SDK's metadata,
capability, health, readiness, request, and Stop RPCs over real gRPC.

View file

@ -1,22 +0,0 @@
[[servers]]
name = "devbox"
package = "docker::alpine@3.22"
tools = ["devbox_status", "devbox_doctor", "devbox_conflicts", "devbox_history", "devbox_members"]
[servers.volumes.binary]
path = "/opt/devbox/devbox:ro"
required = true
[servers.volumes.config]
path = "/config/devbox:ro"
required = true
[servers.volumes.certificates]
path = "/etc/ssl/certs:ro"
required = true
# Install the v2.3.0 native plugin into this directory, then set its absolute path.
[plugins]
dir = "/absolute/path/to/mcpd/plugins"
[[plugins.observability]]
name = "devbox-mcpd-plugin"
flows = ["request"]
required = false

View file

@ -100,10 +100,7 @@ if [ -z "$BIN_DIR" ]; then
BIN_DIR=$def
fi
fi
# Expand only a leading ~/; keep the rest of the path literal.
case "$BIN_DIR" in
'~/'*) BIN_DIR="$HOME/${BIN_DIR#\~/}" ;;
esac
BIN_DIR=$(eval echo "$BIN_DIR") # expand a leading ~
SUDO=""
if ! mkdir -p "$BIN_DIR" 2>/dev/null || ! [ -w "$BIN_DIR" ]; then

View file

@ -8,7 +8,6 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"sync"
"testing"
"time"
@ -19,27 +18,6 @@ import (
"github.com/shoemoney/devbox/internal/transport"
)
// startDaemons returns a shutdown function that must be deferred after the hub
// and database close defers, so Run finishes before its dependencies or t expire.
func startDaemons(t *testing.T, daemons ...*Daemon) func() {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
for _, d := range daemons {
wg.Add(1)
go func() {
defer wg.Done()
if err := d.Run(ctx); err != nil {
t.Errorf("daemon Run: %v", err)
}
}()
}
return func() {
cancel()
wg.Wait()
}
}
func join(t *testing.T, db *meta.DB, url, name string) string {
t.Helper()
tok := name + "-tok"
@ -162,8 +140,10 @@ func TestLiveTwoWaySyncViaSSE(t *testing.T) {
if err != nil {
t.Fatal(err)
}
stop := startDaemons(t, dA, dB)
defer stop()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go dA.Run(ctx)
go dB.Run(ctx)
time.Sleep(200 * time.Millisecond) // let both subscribe before the first edit
// Alice creates a file -> it should reach Bob automatically.

View file

@ -1,6 +1,7 @@
package daemon
import (
"context"
"net/http/httptest"
"os"
"path/filepath"
@ -97,8 +98,10 @@ func TestPauseGatesSyncing(t *testing.T) {
if err != nil {
t.Fatal(err)
}
stop := startDaemons(t, dA, dB)
defer stop()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go dA.Run(ctx)
go dB.Run(ctx)
time.Sleep(300 * time.Millisecond) // let both subscribe + do initial sync
// Pause Alice, then make a local edit. It must NOT reach Bob while paused.

View file

@ -1,108 +0,0 @@
package hub
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/shoemoney/devbox/internal/chunk"
"github.com/shoemoney/devbox/internal/hub/blobstore"
"github.com/shoemoney/devbox/internal/hub/meta"
"github.com/shoemoney/devbox/internal/manifest"
"github.com/shoemoney/devbox/pkg/proto"
)
// Pause each manifest read after the handler's preliminary head check. Channels
// let both requests observe the same parent, then commit A before releasing B.
// There is no scheduler timing or repeated-attempt assumption in this proof.
type pushBarrierStore struct {
blobstore.Store
gates map[string]chan struct{}
arrived chan string
}
func (s *pushBarrierStore) Get(hash string) ([]byte, error) {
if gate, ok := s.gates[hash]; ok {
s.arrived <- hash
<-gate
}
return s.Store.Get(hash)
}
func TestConcurrentPushRejectsStaleParent(t *testing.T) {
db, err := meta.Open(":memory:")
if err != nil {
t.Fatal(err)
}
defer db.Close()
if err := db.AddDevice("device", "test", []byte("pub"), 1); err != nil {
t.Fatal(err)
}
if err := db.CreateShare("proj", "device", 1); err != nil {
t.Fatal(err)
}
disk, err := blobstore.NewDisk(t.TempDir())
if err != nil {
t.Fatal(err)
}
store := &pushBarrierStore{Store: disk, gates: make(map[string]chan struct{}), arrived: make(chan string, 2)}
var hashes, chunks [2]string
for i, name := range []string{"a", "b"} {
data := []byte(name)
chunks[i] = chunk.Hash(data)
if err := disk.Put(chunks[i], data); err != nil {
t.Fatal(err)
}
mf := manifest.Manifest{Entries: []manifest.Entry{{Path: name, Mode: 0644, Size: 1, Chunks: []string{chunks[i]}}}}
body, err := mf.Marshal()
if err != nil {
t.Fatal(err)
}
hashes[i] = chunk.Hash(body)
if err := disk.Put(hashes[i], body); err != nil {
t.Fatal(err)
}
store.gates[hashes[i]] = make(chan struct{})
}
srv := NewServer(db, store)
done := [2]chan *httptest.ResponseRecorder{make(chan *httptest.ResponseRecorder, 1), make(chan *httptest.ResponseRecorder, 1)}
for i := range hashes {
body := mustJSON(t, proto.PushRequest{Share: "proj", ManifestHash: hashes[i]})
go func(i int) {
w := httptest.NewRecorder()
srv.handlePush(w, httptest.NewRequest("POST", proto.PathPush, bytes.NewReader(body)), "device")
done[i] <- w
}(i)
}
<-store.arrived
<-store.arrived
close(store.gates[hashes[0]])
first := <-done[0]
close(store.gates[hashes[1]])
second := <-done[1]
for i, w := range []*httptest.ResponseRecorder{first, second} {
var got proto.PushResponse
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &got) != nil {
t.Fatalf("push %d: %d %s", i, w.Code, w.Body)
}
if got.Conflict != (i == 1) || got.Head != hashes[0] {
t.Errorf("push %d: %+v, want conflict=%v head=%s", i, got, i == 1, hashes[0])
}
}
head, _, err := db.ShareHead("proj")
if err != nil || head != hashes[0] {
t.Errorf("head=%s err=%v, want %s", head, err, hashes[0])
}
snaps, err := db.SnapshotIDs("proj")
if err != nil || len(snaps) != 1 || snaps[0] != hashes[0] {
t.Errorf("snapshots=%v err=%v, want only winner", snaps, err)
}
for i, hash := range chunks {
want := 1 - i
if rc, err := db.ChunkRefcount(hash); err != nil || rc != want {
t.Errorf("chunk %d refcount=%d err=%v, want %d", i, rc, err, want)
}
}
}

View file

@ -1,100 +0,0 @@
package meta
import (
"path/filepath"
"testing"
)
func TestAcceptSnapshotReplayRevertAndGC(t *testing.T) {
db := open(t)
if err := db.CreateShare("proj", "device", 1); err != nil {
t.Fatal(err)
}
accept := func(id, parent string, conflict, advanced bool, head string) {
t.Helper()
got, err := db.AcceptSnapshot(Snapshot{ID: id, ManifestHash: id, Share: "proj", ParentID: parent}, []ChunkRef{{Hash: id}, {Hash: id}})
if err != nil || got != (SnapshotAcceptance{Head: head, Conflict: conflict, Advanced: advanced}) {
t.Fatalf("accept(%s,%s)=%+v, %v", id, parent, got, err)
}
}
accept("a", "", false, true, "a")
accept("a", "old-parent", false, false, "a") // replay is independent of its original parent
accept("b", "a", false, true, "b")
candidates, err := db.DeletableSnapshots("proj", 0)
if err != nil || len(candidates) != 1 || candidates[0] != "a" {
t.Fatalf("GC candidates=%v, %v", candidates, err)
}
accept("a", "", true, false, "b") // existing snapshot cannot bypass the parent check
accept("a", "b", false, true, "a") // valid revert preserves original row and refs
// GC's previously selected candidate is now head; deletion must recheck.
if err := db.DeleteSnapshot("proj", "a", []string{"a"}); err != nil {
t.Fatal(err)
}
for _, hash := range []string{"a", "b"} {
if rc, err := db.ChunkRefcount(hash); err != nil || rc != 1 {
t.Fatalf("%s refcount=%d, %v; want 1", hash, rc, err)
}
}
snaps, err := db.SnapshotIDs("proj")
if err != nil || len(snaps) != 2 {
t.Fatalf("snapshots=%v, %v", snaps, err)
}
// If GC prunes an old snapshot before a revert, accepting it must restore refs.
if err := db.DeleteSnapshot("proj", "b", []string{"b"}); err != nil {
t.Fatal(err)
}
accept("b", "a", false, true, "b")
if rc, err := db.ChunkRefcount("b"); err != nil || rc != 1 {
t.Fatalf("restored b refcount=%d, %v", rc, err)
}
}
func TestAcceptSnapshotAcrossConnections(t *testing.T) {
path := filepath.Join(t.TempDir(), "meta.db")
a, err := Open(path)
if err != nil {
t.Fatal(err)
}
defer a.Close()
b, err := Open(path)
if err != nil {
t.Fatal(err)
}
defer b.Close()
if err := a.CreateShare("proj", "device", 1); err != nil {
t.Fatal(err)
}
type outcome struct {
id string
result SnapshotAcceptance
err error
}
start := make(chan struct{})
done := make(chan outcome, 2)
for i, db := range []*DB{a, b} {
id := []string{"a", "b"}[i]
go func() {
<-start
got, err := db.AcceptSnapshot(Snapshot{ID: id, Share: "proj"}, []ChunkRef{{Hash: id}})
done <- outcome{id, got, err}
}()
}
close(start)
first, second := <-done, <-done
if first.err != nil || second.err != nil {
t.Fatalf("errors: %v, %v", first.err, second.err)
}
if first.result.Conflict {
first, second = second, first
}
if first.result.Conflict || !first.result.Advanced || !second.result.Conflict || second.result.Advanced || second.result.Head != first.id {
t.Fatalf("outcomes: %+v, %+v", first, second)
}
ids, err := a.SnapshotIDs("proj")
if err != nil || len(ids) != 1 || ids[0] != first.id {
t.Fatalf("snapshots=%v, %v", ids, err)
}
if rc, err := a.ChunkRefcount(second.id); err != nil || rc != 0 {
t.Fatalf("loser refcount=%d, %v", rc, err)
}
}

View file

@ -660,53 +660,6 @@ func (d *DB) AddSnapshot(s Snapshot, chunks []ChunkRef) error {
}
defer tx.Rollback()
if err := recordSnapshot(tx, s, chunks); err != nil {
return err
}
return tx.Commit()
}
// SnapshotAcceptance is the result at the transaction's head check. A conflict
// records nothing; Advanced distinguishes a replay from a genuine head change.
type SnapshotAcceptance struct {
Head string
Conflict bool
Advanced bool
}
// AcceptSnapshot accepts only a push extending the current head, or a replay of
// that head. The check, snapshot/refcount writes and head advance share one
// transaction. Acquire SQLite's write lock BEFORE reading so independent DB
// handles cannot both read an old head or fail upgrading a stale read transaction.
func (d *DB) AcceptSnapshot(s Snapshot, chunks []ChunkRef) (SnapshotAcceptance, error) {
var result SnapshotAcceptance
tx, err := d.sql.Begin()
if err != nil {
return result, err
}
defer tx.Rollback()
if _, err := tx.Exec(`UPDATE shares SET head_snapshot=head_snapshot WHERE name=?`, s.Share); err != nil {
return result, err
}
if err := tx.QueryRow(`SELECT COALESCE(head_snapshot,'') FROM shares WHERE name=?`, s.Share).Scan(&result.Head); err != nil {
return result, err
}
if s.ID != result.Head && s.ParentID != result.Head {
result.Conflict = true
return result, nil
}
result.Advanced = s.ID != result.Head
if err := recordSnapshot(tx, s, chunks); err != nil {
return SnapshotAcceptance{}, err
}
if err := tx.Commit(); err != nil {
return SnapshotAcceptance{}, err
}
result.Head = s.ID
return result, nil
}
func recordSnapshot(tx *sql.Tx, s Snapshot, chunks []ChunkRef) error {
// Snapshots are content-addressed, so re-pushing an unchanged tree (or
// reverting to a prior state) replays an existing id within THIS share. That's
// idempotent: advance the head to it, but never re-insert or double-count chunk
@ -718,7 +671,7 @@ func recordSnapshot(tx *sql.Tx, s Snapshot, chunks []ChunkRef) error {
if _, err := tx.Exec(`UPDATE shares SET head_snapshot=? WHERE name=?`, s.ID, s.Share); err != nil {
return err
}
return nil
return tx.Commit()
case !errors.Is(err, sql.ErrNoRows):
return err
}
@ -745,7 +698,7 @@ func recordSnapshot(tx *sql.Tx, s Snapshot, chunks []ChunkRef) error {
if _, err := tx.Exec(`UPDATE shares SET head_snapshot=? WHERE name=?`, s.ID, s.Share); err != nil {
return err
}
return nil
return tx.Commit()
}
// ChunkRefcount returns a chunk's refcount (0 if unknown). Used by tests and GC.
@ -839,16 +792,14 @@ func (d *DB) DeletableSnapshots(share string, keep int) ([]string, error) {
// each distinct chunk hash it referenced, all in one transaction. The caller
// derives chunkHashes from the snapshot's manifest (distinct, as AddSnapshot
// counted them). Keyed by (share, id): pruning one share's copy of shared content
// leaves another share's snapshot (and its refcounts) intact. Recheck the live
// head in the DELETE: a GC candidate can become head after selection via revert.
// leaves another share's snapshot (and its refcounts) intact.
func (d *DB) DeleteSnapshot(share, id string, chunkHashes []string) error {
tx, err := d.sql.Begin()
if err != nil {
return err
}
defer tx.Rollback()
res, err := tx.Exec(`DELETE FROM snapshots WHERE share=? AND id=?
AND NOT EXISTS (SELECT 1 FROM shares WHERE name=? AND head_snapshot=?)`, share, id, share, id)
res, err := tx.Exec(`DELETE FROM snapshots WHERE share=? AND id=?`, share, id)
if err != nil {
return err
}

View file

@ -306,11 +306,6 @@ func TestCrossShareRefcount(t *testing.T) {
t.Fatalf("share %s ids = %v, want [shared]", s, ids)
}
}
// Advance share a so its shared snapshot is eligible for pruning; live heads
// are protected even if a caller passes one to DeleteSnapshot.
if err := db.AddSnapshot(Snapshot{ID: "new-a", Share: "a", ParentID: "shared"}, nil); err != nil {
t.Fatal(err)
}
// Pruning one share's copy leaves the other's refcount intact (rc 2 -> 1).
if err := db.DeleteSnapshot("a", "shared", []string{"c1"}); err != nil {
t.Fatal(err)

View file

@ -3,8 +3,8 @@
package hub
import (
"compress/gzip"
"context"
"compress/gzip"
"crypto/ed25519"
"crypto/rand"
"crypto/sha256"
@ -505,8 +505,7 @@ func (s *Server) handlePush(w http.ResponseWriter, r *http.Request, deviceID str
return
}
// Preliminary conflict check: a push must extend the current head (or replay
// it). AcceptSnapshot repeats this check atomically with the writes below.
// Conflict detection: a push must extend the current head (or replay it).
// Re-pushing the existing head is idempotent; a push whose parent IS the
// current head fast-forwards; anything else means the device is behind and
// must pull + reconcile (M3) before pushing again — we never clobber head.
@ -581,21 +580,14 @@ func (s *Server) handlePush(w http.ResponseWriter, r *http.Request, deviceID str
ManifestHash: req.ManifestHash,
CreatedAt: time.Now().Unix(),
}
accepted, err := s.db.AcceptSnapshot(snap, chunks)
if err != nil {
if err := s.db.AddSnapshot(snap, chunks); err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
if accepted.Conflict {
s.conflicts.Add(1)
s.dash.Emit(dashboard.Event{Type: "conflict", Device: deviceID, Share: req.Share})
writeJSON(w, http.StatusOK, proto.PushResponse{Head: accepted.Head, Conflict: true})
return
}
// Only announce a genuine head advance. An idempotent re-push (manifest ==
// current head) must NOT broadcast, or daemons would storm: pull -> re-push
// the same state -> broadcast -> pull -> ... forever.
advanced := accepted.Advanced
advanced := req.ManifestHash != head
if advanced {
s.broker.publish(proto.Event{Share: req.Share, Snapshot: snapshotID})
}

View file

@ -1,173 +0,0 @@
package syncer
import (
"bytes"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"github.com/shoemoney/devbox/internal/hooks"
"github.com/shoemoney/devbox/internal/hub"
"github.com/shoemoney/devbox/internal/hub/blobstore"
"github.com/shoemoney/devbox/internal/hub/meta"
"github.com/shoemoney/devbox/internal/secret"
)
func TestSyncConflictRetryMergesAdvancedHead(t *testing.T) {
for _, samePath := range []bool{false, true} {
name := "disjoint-files"
if samePath {
name = "same-path-conflicting-edits"
}
t.Run(name, func(t *testing.T) {
db, err := meta.Open(":memory:")
if err != nil {
t.Fatal(err)
}
defer db.Close()
store, err := blobstore.NewDisk(t.TempDir())
if err != nil {
t.Fatal(err)
}
handler := hub.NewServer(db, store).Handler()
clean := httptest.NewServer(handler)
defer clean.Close()
bob := joinDevice(t, db, clean.URL, "bob")
rootA, rootB := t.TempDir(), t.TempDir()
ig, err := LoadIgnore(rootA)
if err != nil {
t.Fatal(err)
}
guard, err := secret.New(nil)
if err != nil {
t.Fatal(err)
}
// Advance the hub immediately before Alice's push reaches it. Setup
// uses the clean server, so exactly the first raced push is intercepted.
var armed atomic.Bool
var pushes atomic.Int32
var interleave func() error
interleaved := make(chan error, 1)
wrapped := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/v1/push" {
pushes.Add(1)
if armed.CompareAndSwap(true, false) {
interleaved <- interleave()
}
}
handler.ServeHTTP(w, r)
}))
defer wrapped.Close()
alice := joinDevice(t, db, wrapped.URL, "alice")
if err := bob.Publish("s"); err != nil {
t.Fatal(err)
}
writeFile(t, rootB, "shared.txt", "baseline\n")
initial, _, err := Sync(bob, rootB, "s", "", "", "bob", 1, ig, guard, nil)
if err != nil {
t.Fatal(err)
}
pr, err := Pull(alice, rootA, "s", "", "", "alice", 2, ig, guard, nil)
if err != nil || pr.Base != initial {
t.Fatalf("initial pull: base=%s err=%v", pr.Base, err)
}
writeFile(t, rootA, "a.txt", "Alice addition\n")
writeFile(t, rootB, "b.txt", "Bob addition\n")
if samePath {
writeFile(t, rootA, "shared.txt", "Alice edit\n")
writeFile(t, rootB, "shared.txt", "Bob edit\n")
}
var advanced string
interleave = func() error {
result, err := Push(bob, rootB, "s", "", ig, guard, initial, nil)
advanced = result.Snapshot
return err
}
// Hook output must identify the head actually merged on the retry.
var hookOutput bytes.Buffer
hk := hooks.New(rootA, "s", "alice", wrapped.URL)
hk.Stdout = &hookOutput
for _, event := range []string{hooks.PrePull, hooks.PostPull, hooks.OnConflict} {
path := filepath.Join(hooks.Dir(rootA), event)
writeFile(t, rootA, filepath.ToSlash(filepath.Join(".devbox", "hooks", event)), "#!/usr/bin/env bash\necho \"$DEVBOX_EVENT $DEVBOX_SNAPSHOT\"\ncat \"$DEVBOX_CHANGED_FILES\"\n")
if err := os.Chmod(path, 0o755); err != nil {
t.Fatal(err)
}
}
armed.Store(true)
base, result, err := Sync(alice, rootA, "s", "", initial, "alice", 3, ig, guard, hk)
if err != nil {
t.Fatal(err)
}
select {
case err := <-interleaved:
if err != nil {
t.Fatal(err)
}
default:
t.Fatal("concurrent push was not exercised")
}
if pushes.Load() != 2 {
t.Errorf("push attempts = %d, want rejected push then retry", pushes.Load())
}
if advanced == "" || advanced == initial || result.Base != advanced {
t.Errorf("pull base = %s, want advanced head %s (initial %s)", result.Base, advanced, initial)
}
head, err := alice.Head("s")
if err != nil || base != head || base == advanced {
t.Errorf("final base=%s head=%s advanced=%s err=%v", base, head, advanced, err)
}
for _, event := range []string{hooks.PrePull, hooks.PostPull} {
if !strings.Contains(hookOutput.String(), event+" "+advanced+"\n") {
t.Errorf("missing retry %s hook for merged head; output=%q", event, hookOutput.String())
}
}
if !exists(rootA, "b.txt") {
t.Error("retry failed to apply Bob's committed file to Alice")
}
if samePath {
if got := read(t, rootA, "shared.txt"); got != "Bob edit\n" {
t.Errorf("canonical content = %q, want Bob edit", got)
}
if len(result.Conflicts) != 1 {
t.Errorf("conflicts = %v, want Alice's preserved edit", result.Conflicts)
} else if got := read(t, rootA, result.Conflicts[0]); got != "Alice edit\n" {
t.Errorf("conflict content = %q, want Alice edit", got)
}
if !strings.Contains(hookOutput.String(), hooks.OnConflict+" "+advanced+"\n") {
t.Error("missing conflict hook for merged head")
}
} else if len(result.Conflicts) != 0 {
t.Errorf("disjoint edits produced conflicts: %v", result.Conflicts)
}
// Bob's next sync must retain his committed files and receive Alice's
// addition and conflict copy, proving the final hub snapshot is safe.
baseB, resultB, err := Sync(bob, rootB, "s", "", advanced, "bob", 4, ig, guard, nil)
if err != nil {
t.Fatal(err)
}
if baseB != base || len(resultB.Deleted) != 0 {
t.Errorf("Bob convergence: base=%s want=%s deleted=%v", baseB, base, resultB.Deleted)
}
for _, file := range []string{"a.txt", "b.txt", "shared.txt"} {
if !exists(rootB, file) {
t.Errorf("Bob lost %s after retry", file)
} else if exists(rootA, file) && read(t, rootA, file) != read(t, rootB, file) {
t.Errorf("devices disagree on %s", file)
}
}
for _, file := range result.Conflicts {
if got := read(t, rootB, file); got != "Alice edit\n" {
t.Errorf("propagated conflict = %q, want Alice edit", got)
}
}
})
}
}

View file

@ -303,8 +303,7 @@ func Sync(c *transport.Client, root, share, subpath, base, host string, now int6
return base, pr, nil // pre-push vetoed
}
if push.Conflict {
// The remote head has not been applied locally. Keep the last
// merged base so the next Pull three-way merges the advanced head.
base = push.Head // hub advanced; re-pull against the new head
continue
}
return push.Snapshot, pr, nil

21
plan.md
View file

@ -14,19 +14,6 @@
> know it's done. M9–M11 stay **demand-driven** — captured, not committed.
## 🎯 Where we are
> 🛠️ **Current status — 2026-11-28:** published binaries remain **v2.3.0**.
> Forgejo and GitHub source repositories are public. Four accepted reliability
> changes are integrated in source and **unreleased**; see
> [behavior and scoped regression evidence](docs/reliability-fixes.md).
> ✅ **Combined validation passed on dev3:** vet/build/race, 171 top-level Go tests
> plus 30 subtests, nine release fixtures, and two installer tests.
> 🔨 **Next:** prepare a release containing these source fixes when requested.
> No release or deployment has been performed for this cycle.
>
> 📜 The shipped milestones and fleet checks below are historical records; they
> do not establish fleet verification for these new fixes.
v1 is complete + audited + hardened. **M8 (v2 foundations) shipped & fleet-verified**: schema migration runner,
per-`(share,id)` snapshots, daemon control socket + `pause`/`resume`, **M8a teams** (principals · roles · invites
with attenuation · members), and `restore` byte-safety. Plus an **embedded live dashboard**, **cross-platform
@ -61,10 +48,10 @@ download a prebuilt binary — **had nothing to download** (no published release
the v2 codebase the **regression safety** it lacked.
**Shipped**
- [x] `scripts/release.sh` — cross-build (**6 targets incl. `linux/arm64` + `linux/arm`** for Pi) → upload **de-versioned** assets (`devbox_<os>_<arch>`, `+.exe`) plus `SHA256SUMS`. **Current behavior:** versioned releases are immutable (an existing version is rejected); moving `latest` is replaced only after all replacement assets upload. v2.3.0 packaging includes 18 binaries, both installers, and the checksum manifest.
- [x] `scripts/release.sh` — one-shot: cross-build (now **6 targets incl. `linux/arm64` + `linux/arm`** for Pi) → create/update the release → upload **de-versioned** assets (`devbox_<os>_<arch>`, `+.exe`) the installer downloads directly, plus a de-versioned `SHA256SUMS` so `shasum -c` matches. Idempotent.
- [x] CI on **Forgejo Actions** (`.forgejo/workflows/`) **+ GitHub Actions** mirror: `go vet` · `go build ./...` · `go test ./... -race` on push/PR; release-on-tag workflow ready. **GitHub CI is green on every push** (Forgejo waits on a self-hosted runner — per the gotcha, the local `release.sh` is the real path).
- [x] Hub image published to the Forgejo registry: `git.shoemoney.ai/shoemoney/devbox-hub:latest`; compose now `image:` by default (`--build` for local source).
- [x] **Original distribution deviation (approved):** ~~the source repo stays private~~ — superseded: both Forgejo and GitHub source repositories are now public, as is **`shoemoney/devbox-dist`**, which carries installers + binaries → `curl|sh` works **with no token**. The **GitHub mirror was made public** (AGPLv3 — matching the open-core moat, module path `github.com/shoemoney/devbox` so `go install …/cmd/devbox@latest` works) after a clean two-method git-history secret scan.
- [x] **Deviation (approved):** the source repo stays private, so a public **`shoemoney/devbox-dist`** repo carries the installers + binaries as release assets → `curl|sh` works **with no token**. Separately, the **GitHub mirror was made public** (AGPLv3 — matching the open-core moat, module path `github.com/shoemoney/devbox` so `go install …/cmd/devbox@latest` works) after a clean two-method git-history secret scan.
**Acceptance — all met ✅**
- ✅ Clean **no-Go** box, `curl -fsSL …/install.sh | sh` installs a working `devbox` from the real release — verified end-to-end on **amd64** and **fleet-verified on a real clean no-Go arm64 Raspberry Pi** (`192.168.1.13`): anon `curl|sh` → `devbox 0346995`, `devbox doctor` reports `linux/arm64`.
@ -134,7 +121,7 @@ Do **not** pre-build these — there's no user who needs them yet, and the spec
<div align="center">
**Next:** prepare a release containing the validated, unreleased reliability fixes when requested.
P1–P3 are shipped; M9–M11 remain demand-driven. 🛠️
**Recommendation:** start at **P1**. It finishes the adoption story you just set and hardens the build —
highest leverage, lowest risk. 🚀
</div>

View file

@ -10,42 +10,6 @@ INSTALLER = Path(__file__).resolve().parents[1] / 'install.sh'
class InstallTest(unittest.TestCase):
def test_bin_dir_is_literal(self):
for mode in ('flag', 'env'):
for case in ('spaces', 'tilde', 'substitution', 'backticks', 'special'):
with self.subTest(mode=mode, case=case), tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
home = root / 'home directory'
home.mkdir()
source = root / 'devbox-fixture'
source.write_text('#!/bin/sh\necho devbox-fixture\n')
source.chmod(0o755)
marker = root / 'executed'
paths = {
'spaces': str(root / ' two spaces '),
'tilde': '~/two spaces/bin',
'substitution': str(root / f'$(touch {marker})'),
'backticks': str(root / f'`touch {marker}`'),
'special': str(root / 'literal \'single\' "double" ; & $HOME * ? [abc] \\ ~'),
}
requested = paths[case]
dest = home / requested[2:] if requested.startswith('~/') else Path(requested)
env = dict(os.environ)
for key in ('DEVBOX_INSTALL_HUB', 'DEVBOX_INSTALL_MCPD_PLUGIN', 'DEVBOX_BIN_DIR'):
env.pop(key, None)
env.update(HOME=str(home), TMPDIR=str(root), DEVBOX_BIN=str(source))
args = ['sh', str(INSTALLER), '--no-service']
if mode == 'flag':
args += ['--bin-dir', requested]
else:
env['DEVBOX_BIN_DIR'] = requested
result = subprocess.run(args, cwd=root, env=env, capture_output=True, text=True, timeout=10)
self.assertFalse(marker.exists(), 'bin directory input executed a command')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertTrue((dest / 'devbox').is_file(), f'missing literal destination: {dest!s}\n{result.stdout}')
self.assertEqual({p.name for p in dest.iterdir()}, {'devbox'})
self.assertEqual(subprocess.check_output([str(dest / 'devbox')], text=True), 'devbox-fixture\n')
def test_optional_plugin(self):
for mode in ('default', 'flag', 'env'):
with self.subTest(mode=mode), tempfile.TemporaryDirectory() as tmp: