Compare commits
No commits in common. "main" and "release/tailscale-v2.1.0" have entirely different histories.
main
...
release/ta
43 changed files with 61 additions and 2796 deletions
13
.github/workflows/release.yml
vendored
13
.github/workflows/release.yml
vendored
|
|
@ -25,7 +25,7 @@ jobs:
|
|||
- name: De-version asset names (match install.sh)
|
||||
run: |
|
||||
cd dist
|
||||
for f in devbox_*_* devbox-hub_*_* devbox-mcpd-plugin_*_*; do
|
||||
for f in devbox_*_* devbox-hub_*_*; do
|
||||
[ -f "$f" ] || continue
|
||||
ext=""; case "$f" in *.exe) ext=".exe"; f="${f%.exe}";; esac
|
||||
arch="${f##*_}"; rest="${f%_*}"; os="${rest##*_}"; bin="${rest%_*}"; bin="${bin%_*}"
|
||||
|
|
@ -33,17 +33,12 @@ jobs:
|
|||
done
|
||||
cp ../install.sh ../install.ps1 .
|
||||
rm SHA256SUMS
|
||||
sha256sum devbox_* devbox-hub_* devbox-mcpd-plugin_* install.sh install.ps1 > SHA256SUMS
|
||||
sha256sum devbox_* devbox-hub_* install.sh install.ps1 > SHA256SUMS
|
||||
ls -la
|
||||
- name: Publish GitHub release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
if [ -f "docs/releases/${{ github.ref_name }}.md" ]; then
|
||||
notes=(--notes-file "docs/releases/${{ github.ref_name }}.md")
|
||||
else
|
||||
notes=(--generate-notes)
|
||||
fi
|
||||
gh release create "${{ github.ref_name }}" dist/devbox_* dist/devbox-hub_* dist/devbox-mcpd-plugin_* dist/install.sh dist/install.ps1 dist/SHA256SUMS \
|
||||
gh release create "${{ github.ref_name }}" dist/devbox_* dist/devbox-hub_* dist/install.sh dist/install.ps1 dist/SHA256SUMS \
|
||||
--title "${{ github.ref_name }}" \
|
||||
"${notes[@]}"
|
||||
--generate-notes
|
||||
|
|
|
|||
99
README.md
99
README.md
|
|
@ -2,24 +2,19 @@
|
|||
|
||||
# 📦 devbox
|
||||
|
||||
### Your working tree, everywhere. Built-in Tailscale. Built-in MCP. 🔒
|
||||
### Your working tree, everywhere. Now with built-in Tailscale. 🔒
|
||||
|
||||
Continuous file sync for developers: private networking, selective mounts,
|
||||
conflict copies, snapshot history, and structured tools for your AI coding agent.
|
||||
conflict copies, snapshot history, and a secret guard that keeps credentials home.
|
||||
|
||||
**Linux · macOS · Windows · Raspberry Pi**
|
||||
|
||||
[Install](#-install) · [Tailscale quick start](#-tailscale-quick-start) · [Agent MCP](#-built-in-mcp-for-agents) · [Commands](#-commands) · [Configuration](#-configuration) · [Build](#-build-and-release)
|
||||
[Install](#-install) · [Tailscale quick start](#-tailscale-quick-start) · [Commands](#-commands) · [Configuration](#-configuration) · [Build](#-build-and-release)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
> 🛠️ **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
|
||||
|
|
@ -31,10 +26,6 @@ router port forwarding, or reverse proxy is required for this mode.
|
|||
devbox-hub serve --data ./hub-data --tailscale --tailscale-hostname devbox-hub
|
||||
```
|
||||
|
||||

|
||||
|
||||
*Actual CLI help, rendered for readability. The hub joins the tailnet itself.*
|
||||
|
||||
On first launch, open the authentication URL printed in the terminal. Once
|
||||
connected, the hub prints its private endpoint:
|
||||
|
||||
|
|
@ -53,58 +44,6 @@ uses the private URL through that connection. Embedded client networking is not
|
|||
included in this release. The embedded hub is a separate Tailscale device, even
|
||||
if its host machine already runs Tailscale.
|
||||
|
||||
## 🤖 Built-in MCP for agents
|
||||
|
||||
**New in v2.2.0:** connect your coding agent directly to devbox with the built-in
|
||||
Model Context Protocol server. It ships in the same client binary:
|
||||
|
||||
```bash
|
||||
codex mcp add devbox -- /absolute/path/to/devbox mcp
|
||||
```
|
||||
|
||||
Or configure any agent that accepts `mcpServers` JSON:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"devbox": {
|
||||
"command": "/absolute/path/to/devbox",
|
||||
"args": ["mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||

|
||||
|
||||
*Captured from the built-in stdio server using an isolated enrolled device.*
|
||||
|
||||
Ask your agent to check sync status, diagnose a failing mount, inspect history,
|
||||
or list conflicts. Default tools inspect the existing enrolled device.
|
||||
`--allow-writes` enables pause/resume, publish, and mount;
|
||||
`--allow-writes --allow-destructive` additionally enables restore, deploy, and
|
||||
unmount. Tools use the CLI's authentication and conflict behavior.
|
||||
|
||||
**Tailscale connects your machines; MCP connects your agent.** The hub embeds
|
||||
Tailscale, client machines use their regular Tailscale connection, and the MCP
|
||||
server talks locally over stdio. No extra MCP service or Node runtime is needed.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Agent["AI coding agent"] -->|"local stdio"| MCP["devbox mcp"]
|
||||
MCP --> Client["Enrolled devbox client"]
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
## ✨ Why devbox?
|
||||
|
||||
Git records the work you choose to commit. devbox continuously mirrors the
|
||||
|
|
@ -142,10 +81,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.
|
||||
|
||||
|
|
@ -155,21 +90,11 @@ hub separately, or configure its own service with the `serve` arguments below.
|
|||
irm https://git.shoemoney.ai/shoemoney/devbox-dist/releases/download/latest/install.ps1 | iex
|
||||
```
|
||||
|
||||
Download from [GitHub Releases](https://github.com/shoemoney/devbox/releases) or
|
||||
the [Forgejo distribution mirror](https://git.shoemoney.ai/shoemoney/devbox-dist/releases).
|
||||
Both are public. Release downloads include `devbox` and `devbox-hub` for Linux amd64/arm64/arm,
|
||||
Release downloads include both `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
|
||||
|
|
@ -273,7 +198,6 @@ probes the host-network API, so it must be replaced for tailnet-only mode.
|
|||
|
||||
| Client command | Purpose |
|
||||
|---|---|
|
||||
| `devbox mcp` | Serve structured agent tools over local stdio |
|
||||
| `devbox setup` | Interactive first-run setup |
|
||||
| `devbox join <hub> <token>` | Enroll this device |
|
||||
| `devbox publish <localdir> <share>` | Create a share and push its files |
|
||||
|
|
@ -300,10 +224,7 @@ planned, so use a hub for a trusted group rather than mutually untrusted tenants
|
|||
|
||||
## 📊 Built-in dashboard
|
||||
|
||||
<p align="center"><img src="docs/images/dashboard.png" alt="Live devbox dashboard showing three devices and three demo shares" width="1000"></p>
|
||||
|
||||
*Live hub dashboard with isolated demo data. The capture uses a local hub; it is
|
||||
not evidence of production Tailscale enrollment.*
|
||||
<p align="center"><img src="docs/images/dashboard.png" alt="devbox live sync dashboard" width="860"></p>
|
||||
|
||||
```bash
|
||||
devbox-hub serve --data ./hub-data --tailscale --dashboard
|
||||
|
|
@ -365,14 +286,12 @@ 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.1.0 ./scripts/build-release.sh
|
||||
```
|
||||
|
||||
The release script cross-compiles the client, hub, and optional mcpd plugin 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
|
||||
installer uses Forgejo; `--release-url` can select either host.
|
||||
The release script cross-compiles both binaries for six platform/architecture
|
||||
combinations and generates checksums. Public binary distribution lives in
|
||||
[`devbox-dist`](https://git.shoemoney.ai/shoemoney/devbox-dist).
|
||||
|
||||
Design documents: [original sync design](docs/superpowers/specs/2026-06-22-devbox-design.md)
|
||||
and [v2 roadmap](docs/V2-SPEC.md). Future work includes embedded client networking,
|
||||
|
|
|
|||
|
|
@ -1,141 +0,0 @@
|
|||
// devbox-mcpd-plugin is metadata-only request audit middleware for Mozilla mcpd.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
mcpdpluginsv1 "github.com/mozilla-ai/mcpd-plugins-sdk-go/pkg/plugins/v1"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
)
|
||||
|
||||
var version = "dev"
|
||||
|
||||
// Only canonical, bounded tool identifiers may enter the audit stream.
|
||||
var toolName = regexp.MustCompile(`^devbox_[a-z][a-z0-9_]{0,63}$`)
|
||||
|
||||
type auditPlugin struct {
|
||||
mcpdpluginsv1.BasePlugin
|
||||
version string
|
||||
output io.Writer
|
||||
mu sync.Mutex
|
||||
stop context.CancelFunc
|
||||
}
|
||||
|
||||
func (p *auditPlugin) GetMetadata(context.Context, *emptypb.Empty) (*mcpdpluginsv1.Metadata, error) {
|
||||
return &mcpdpluginsv1.Metadata{Name: "devbox-mcpd-plugin", Version: p.version, Description: "Metadata-only audit telemetry for devbox tool requests"}, nil
|
||||
}
|
||||
func (p *auditPlugin) GetCapabilities(context.Context, *emptypb.Empty) (*mcpdpluginsv1.Capabilities, error) {
|
||||
return &mcpdpluginsv1.Capabilities{Flows: []mcpdpluginsv1.Flow{mcpdpluginsv1.FlowRequest}}, nil
|
||||
}
|
||||
func (p *auditPlugin) Stop(context.Context, *emptypb.Empty) (*emptypb.Empty, error) {
|
||||
if p.stop != nil {
|
||||
p.stop()
|
||||
}
|
||||
return &emptypb.Empty{}, nil
|
||||
}
|
||||
|
||||
func requestTool(req *mcpdpluginsv1.HTTPRequest) string {
|
||||
if req.GetMethod() != "POST" {
|
||||
return ""
|
||||
}
|
||||
const prefix = "/api/v1/servers/devbox/tools/"
|
||||
path := req.GetPath()
|
||||
if !strings.HasPrefix(path, prefix) {
|
||||
return ""
|
||||
}
|
||||
tool := strings.TrimPrefix(path, prefix)
|
||||
if !toolName.MatchString(tool) {
|
||||
return ""
|
||||
}
|
||||
// Path is decoded by HTTP servers. Check the wire representations too, so
|
||||
// percent-encoded separators or identifiers cannot masquerade as canonical paths.
|
||||
for _, raw := range []string{req.GetUrl(), req.GetRequestUri()} {
|
||||
if raw == "" {
|
||||
continue
|
||||
}
|
||||
u, err := url.ParseRequestURI(raw)
|
||||
if err != nil || u.EscapedPath() != path || u.Fragment != "" {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return tool
|
||||
}
|
||||
|
||||
func (p *auditPlugin) HandleRequest(ctx context.Context, req *mcpdpluginsv1.HTTPRequest) (*mcpdpluginsv1.HTTPResponse, error) {
|
||||
if tool := requestTool(req); tool != "" {
|
||||
event := struct {
|
||||
Event string `json:"event"`
|
||||
Version string `json:"version"`
|
||||
Method string `json:"method"`
|
||||
Tool string `json:"tool"`
|
||||
}{"devbox.tool.request", p.version, "POST", tool}
|
||||
p.mu.Lock()
|
||||
// Telemetry failures must never block or change a tool request's policy.
|
||||
_ = json.NewEncoder(p.output).Encode(event)
|
||||
p.mu.Unlock()
|
||||
}
|
||||
return p.BasePlugin.HandleRequest(ctx, req)
|
||||
}
|
||||
|
||||
func run(args []string, stdout, stderr io.Writer) error {
|
||||
flags := flag.NewFlagSet("devbox-mcpd-plugin", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
address := flags.String("address", "", "gRPC address (socket path for unix, host:port for tcp)")
|
||||
network := flags.String("network", "unix", "Network type (unix or tcp)")
|
||||
showVersion := flags.Bool("version", false, "Print version and exit")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if *showVersion {
|
||||
_, err := fmt.Fprintln(stdout, "devbox-mcpd-plugin", version)
|
||||
return err
|
||||
}
|
||||
if flags.NArg() != 0 || *address == "" || (*network != "unix" && *network != "tcp") {
|
||||
return fmt.Errorf("--address and --network unix|tcp are required")
|
||||
}
|
||||
lis, err := net.Listen(*network, *address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("plugin listener failed")
|
||||
}
|
||||
defer lis.Close()
|
||||
if *network == "unix" {
|
||||
defer os.Remove(*address)
|
||||
}
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
server := grpc.NewServer()
|
||||
mcpdpluginsv1.RegisterPluginServer(server, &auditPlugin{version: version, output: stderr, stop: cancel})
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
server.GracefulStop()
|
||||
case <-done:
|
||||
}
|
||||
}()
|
||||
err = server.Serve(lis)
|
||||
close(done)
|
||||
if err != nil {
|
||||
return fmt.Errorf("plugin server failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func main() {
|
||||
if err := run(os.Args[1:], os.Stdout, os.Stderr); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,205 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
mcpdpluginsv1 "github.com/mozilla-ai/mcpd-plugins-sdk-go/pkg/plugins/v1"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
)
|
||||
|
||||
func clientFor(t *testing.T, p *auditPlugin) mcpdpluginsv1.PluginClient {
|
||||
t.Helper()
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
mcpdpluginsv1.RegisterPluginServer(server, p)
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
conn, err := grpc.NewClient("passthrough:///plugin", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) { return listener.Dial() }))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { conn.Close(); server.Stop(); listener.Close() })
|
||||
return mcpdpluginsv1.NewPluginClient(conn)
|
||||
}
|
||||
|
||||
func TestSDKLifecycleAndTelemetry(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
stopped := false
|
||||
p := &auditPlugin{version: "v2.3.0", output: &logs, stop: func() { stopped = true }}
|
||||
client := clientFor(t, p)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
empty := &emptypb.Empty{}
|
||||
metadata, err := client.GetMetadata(ctx, empty)
|
||||
if err != nil || metadata.GetName() != "devbox-mcpd-plugin" || metadata.GetVersion() != "v2.3.0" || !strings.Contains(metadata.GetDescription(), "audit") {
|
||||
t.Fatalf("metadata: %v %v", metadata, err)
|
||||
}
|
||||
caps, err := client.GetCapabilities(ctx, empty)
|
||||
if err != nil || len(caps.GetFlows()) != 1 || caps.Flows[0] != mcpdpluginsv1.FlowRequest {
|
||||
t.Fatalf("capabilities: %v %v", caps, err)
|
||||
}
|
||||
if _, err := client.CheckHealth(ctx, empty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.CheckReady(ctx, empty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.Configure(ctx, &mcpdpluginsv1.PluginConfig{CustomConfig: map[string]string{"secret": "CONFIG_PII"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := "/api/v1/servers/devbox/tools/devbox_status"
|
||||
req := &mcpdpluginsv1.HTTPRequest{Method: "POST", Path: path, Url: "http://localhost" + path + "?token=QUERY_SECRET", RequestUri: path + "?token=QUERY_SECRET", Headers: map[string]string{"Authorization": "HEADER_SECRET", "X-User": "USER_PII"}, Body: []byte("ARGS_SECRET /home/private/FILE_SECRET\x00\xff"), RemoteAddr: "IP_PII"}
|
||||
before := proto.Clone(req)
|
||||
resp, err := client.HandleRequest(ctx, req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := &mcpdpluginsv1.HTTPResponse{Continue: true, Headers: req.Headers, Body: req.Body}
|
||||
if !proto.Equal(resp, want) || !proto.Equal(req, before) {
|
||||
t.Fatal("request changed")
|
||||
}
|
||||
original := &mcpdpluginsv1.HTTPResponse{StatusCode: 207, Headers: req.Headers, Body: req.Body, Continue: true}
|
||||
after, err := client.HandleResponse(ctx, original)
|
||||
if err != nil || !proto.Equal(after, original) {
|
||||
t.Fatalf("response changed: %v", err)
|
||||
}
|
||||
var event map[string]string
|
||||
if err := json.Unmarshal(logs.Bytes(), &event); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(event) != 4 || event["event"] != "devbox.tool.request" || event["version"] != "v2.3.0" || event["method"] != "POST" || event["tool"] != "devbox_status" {
|
||||
t.Fatalf("unexpected audit fields: %v", event)
|
||||
}
|
||||
for _, secret := range []string{"CONFIG_PII", "QUERY_SECRET", "HEADER_SECRET", "USER_PII", "ARGS_SECRET", "FILE_SECRET", "IP_PII", path, "localhost"} {
|
||||
if strings.Contains(logs.String(), secret) {
|
||||
t.Fatalf("audit leaked %s", secret)
|
||||
}
|
||||
}
|
||||
if _, err := client.Stop(ctx, empty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !stopped {
|
||||
t.Fatal("Stop did not cancel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIgnoredRoutes(t *testing.T) {
|
||||
const valid = "/api/v1/servers/devbox/tools/devbox_status"
|
||||
cases := []struct{ method, path, raw string }{
|
||||
{"GET", valid, ""}, {"post", valid, ""}, {"POST\n", valid, ""},
|
||||
{"POST", "/api/v1/servers/other/tools/devbox_status", ""},
|
||||
{"POST", "/api/v1/servers/devbox/tools/other", ""},
|
||||
{"POST", valid + "/", ""}, {"POST", valid + "/extra", ""},
|
||||
{"POST", valid + "?x=y", ""}, {"POST", valid + "\nFORGED", ""},
|
||||
{"POST", valid + ".txt", ""}, {"POST", valid + "%0a", ""},
|
||||
{"POST", strings.Replace(valid, "devbox_status", "devbox_..", 1), ""},
|
||||
{"POST", strings.Replace(valid, "/tools/", "//tools/", 1), ""},
|
||||
{"POST", valid + strings.Repeat("a", 65), ""},
|
||||
{"POST", valid, strings.Replace(valid, "status", "%73tatus", 1)},
|
||||
{"POST", valid, strings.Replace(valid, "/tools/", "%2ftools/", 1)},
|
||||
{"POST", valid, valid + "%0aFORGED"}, {"POST", valid, "/different"},
|
||||
{"POST", valid, "http://[invalid"},
|
||||
}
|
||||
var logs bytes.Buffer
|
||||
client := clientFor(t, &auditPlugin{version: "v2.3.0", output: &logs})
|
||||
for i, tc := range cases {
|
||||
req := &mcpdpluginsv1.HTTPRequest{Method: tc.method, Path: tc.path, RequestUri: tc.raw, Headers: map[string]string{"secret": "sentinel"}, Body: []byte{0, 255, 1}}
|
||||
resp, err := client.HandleRequest(context.Background(), req)
|
||||
if err != nil || !resp.GetContinue() || !bytes.Equal(resp.GetBody(), req.Body) || resp.Headers["secret"] != "sentinel" {
|
||||
t.Fatalf("case %d changed request: %v", i, err)
|
||||
}
|
||||
}
|
||||
if logs.Len() != 0 {
|
||||
t.Fatalf("ignored paths logged: %s", &logs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentRequests(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
client := clientFor(t, &auditPlugin{version: "v2.3.0", output: &logs})
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 64; i++ {
|
||||
wg.Go(func() {
|
||||
resp, err := client.HandleRequest(context.Background(), &mcpdpluginsv1.HTTPRequest{Method: "POST", Path: "/api/v1/servers/devbox/tools/devbox_status"})
|
||||
if err != nil || !resp.GetContinue() {
|
||||
t.Errorf("request: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
dec := json.NewDecoder(&logs)
|
||||
for i := 0; i < 64; i++ {
|
||||
var v map[string]string
|
||||
if err := dec.Decode(&v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var extra any
|
||||
if err := dec.Decode(&extra); err != io.EOF {
|
||||
t.Fatalf("extra log data: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type brokenWriter struct{}
|
||||
|
||||
func (brokenWriter) Write([]byte) (int, error) { return 0, fmt.Errorf("sink unavailable") }
|
||||
func TestAuditFailureIsPassThrough(t *testing.T) {
|
||||
p := &auditPlugin{output: brokenWriter{}}
|
||||
resp, err := p.HandleRequest(context.Background(), &mcpdpluginsv1.HTTPRequest{Method: "POST", Path: "/api/v1/servers/devbox/tools/devbox_status"})
|
||||
if err != nil || !resp.Continue {
|
||||
t.Fatalf("telemetry blocked request: %v", err)
|
||||
}
|
||||
}
|
||||
func TestVersion(t *testing.T) {
|
||||
for _, flag := range []string{"-version", "--version"} {
|
||||
var out, logs bytes.Buffer
|
||||
if err := run([]string{flag}, &out, &logs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.String() != "devbox-mcpd-plugin "+version+"\n" || logs.Len() != 0 {
|
||||
t.Fatal("invalid version output")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeServerStop(t *testing.T) {
|
||||
socket := t.TempDir() + "/plugin.sock"
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- run([]string{"--network", "unix", "--address", socket}, io.Discard, io.Discard) }()
|
||||
conn, err := grpc.NewClient("passthrough:///native", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, "unix", socket)
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
client := mcpdpluginsv1.NewPluginClient(conn)
|
||||
if _, err := client.CheckHealth(ctx, &emptypb.Empty{}, grpc.WaitForReady(true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.Stop(ctx, &emptypb.Empty{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Stop did not exit server promptly")
|
||||
}
|
||||
}
|
||||
|
|
@ -64,7 +64,6 @@ func main() {
|
|||
doctorCmd(),
|
||||
setupCmd(),
|
||||
versionCmd(),
|
||||
mcpCmd(),
|
||||
)
|
||||
// First run: on a bare `devbox` (no subcommand) on a terminal, offer the setup
|
||||
// wizard if this machine isn't joined yet and the user hasn't opted out.
|
||||
|
|
@ -314,15 +313,11 @@ func writeJSON(w io.Writer, v any) error {
|
|||
|
||||
func logCmd() *cobra.Command {
|
||||
var asJSON bool
|
||||
var limit int
|
||||
cmd := &cobra.Command{
|
||||
Use: "log <share>",
|
||||
Short: "🕓 show a share's snapshot history",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if limit < 1 || limit > 100 {
|
||||
return fmt.Errorf("limit must be between 1 and 100")
|
||||
}
|
||||
share := args[0]
|
||||
dir, err := config.Dir()
|
||||
if err != nil {
|
||||
|
|
@ -341,9 +336,6 @@ func logCmd() *cobra.Command {
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(snaps) > limit {
|
||||
snaps = snaps[:limit]
|
||||
}
|
||||
out := cmd.OutOrStdout()
|
||||
if asJSON {
|
||||
return writeJSON(out, snaps)
|
||||
|
|
@ -356,7 +348,6 @@ func logCmd() *cobra.Command {
|
|||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&asJSON, "json", false, "emit machine-readable JSON")
|
||||
cmd.Flags().IntVar(&limit, "limit", 100, "maximum snapshots (1-100)")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
|
@ -1077,10 +1068,8 @@ func doctorCmd() *cobra.Command {
|
|||
}
|
||||
|
||||
// fsnotify watcher (catches inotify exhaustion on Linux).
|
||||
probe, probeErr := os.MkdirTemp("", "devbox-doctor-watch-")
|
||||
if probeErr != nil {
|
||||
check(false, false, "file watcher", probeErr.Error())
|
||||
} else {
|
||||
probe := filepath.Join(os.TempDir(), "devbox-doctor-watch")
|
||||
_ = os.MkdirAll(probe, 0o755)
|
||||
if w, err := watch.New(probe, 100*time.Millisecond); err != nil {
|
||||
check(false, false, "file watcher", err.Error())
|
||||
} else {
|
||||
|
|
@ -1088,7 +1077,6 @@ func doctorCmd() *cobra.Command {
|
|||
check(true, false, "file watcher", "fsnotify ok")
|
||||
}
|
||||
_ = os.RemoveAll(probe)
|
||||
}
|
||||
|
||||
// macOS Full Disk Access — needed to sync TCC-protected folders
|
||||
// (~/Desktop, ~/Documents, ~/Downloads, iCloud). A background daemon
|
||||
|
|
|
|||
|
|
@ -1,337 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const mcpOutputLimit = 1 << 20
|
||||
const mcpStderrLimit = 64 << 10
|
||||
|
||||
func mcpCmd() *cobra.Command {
|
||||
var writes, destructive bool
|
||||
var timeout time.Duration
|
||||
cmd := &cobra.Command{
|
||||
Use: "mcp", Short: "serve MCP tools over stdin/stdout (inspection only by default)", Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
if destructive && !writes {
|
||||
return fmt.Errorf("--allow-destructive requires --allow-writes")
|
||||
}
|
||||
if timeout <= 0 {
|
||||
return fmt.Errorf("--command-timeout must be positive")
|
||||
}
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return newMCPServer(executable, writes, destructive, timeout).Run(cmd.Context(), &mcp.StdioTransport{})
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&writes, "allow-writes", false, "expose pause, resume, publish, and mount")
|
||||
cmd.Flags().BoolVar(&destructive, "allow-destructive", false, "also expose restore, deploy, and unmount (requires --allow-writes)")
|
||||
cmd.Flags().DurationVar(&timeout, "command-timeout", 2*time.Minute, "positive timeout for each tool command, including queue time")
|
||||
return cmd
|
||||
}
|
||||
|
||||
type mcpArguments struct {
|
||||
Share string `json:"share"`
|
||||
LocalDir string `json:"local_dir"`
|
||||
Snapshot string `json:"snapshot"`
|
||||
Path string `json:"path"`
|
||||
ReadOnly bool `json:"read_only"`
|
||||
Exclude []string `json:"exclude"`
|
||||
Duration string `json:"duration"`
|
||||
Limit *int `json:"limit"`
|
||||
}
|
||||
|
||||
type mcpCommandResult struct {
|
||||
Stdout string `json:"stdout"`
|
||||
Stderr string `json:"stderr"`
|
||||
ExitCode int `json:"exit_code"`
|
||||
Truncated bool `json:"truncated"`
|
||||
Data any `json:"data,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type mcpToolSpec struct {
|
||||
name, description string
|
||||
fields, required []string
|
||||
write, destructive, idempotent, openWorld bool
|
||||
}
|
||||
|
||||
func newMCPServer(executable string, writes, destructive bool, timeout time.Duration) *mcp.Server {
|
||||
server := mcp.NewServer(&mcp.Implementation{Name: "devbox", Version: version}, nil)
|
||||
// CLI config/state updates are atomic files, but not multi-process transactions.
|
||||
// Serialize calls in this server to avoid two mutating children losing updates.
|
||||
gate := make(chan struct{}, 1)
|
||||
specs := []mcpToolSpec{
|
||||
{name: "status", description: "Inspect enrollment, mounts, and running daemon state. Does not test hub connectivity.", idempotent: true},
|
||||
{name: "doctor", description: "Diagnose enrollment, hub connectivity, mounts, and watcher. Failed checks remain in data with isError=true.", idempotent: true, openWorld: true},
|
||||
{name: "conflicts", description: "List conflict copies across configured mounts; never deletes files.", idempotent: true},
|
||||
{name: "history", description: "Get the newest share snapshots, bounded by limit (default 20; maximum 100).", fields: []string{"share", "limit"}, required: []string{"share"}, idempotent: true, openWorld: true},
|
||||
{name: "members", description: "List share members and roles using the enrolled device's access.", fields: []string{"share"}, required: []string{"share"}, idempotent: true, openWorld: true},
|
||||
{name: "pause", description: "Pause the running sync daemon. Optional positive duration auto-resumes it; omitted means until resume.", fields: []string{"duration"}, write: true, idempotent: false},
|
||||
{name: "resume", description: "Resume the running sync daemon and catch up configured mounts.", write: true, idempotent: true, openWorld: true},
|
||||
{name: "publish", description: "Create a hub share and upload a local directory with the existing secret guard. Does not configure a mount.", fields: []string{"share", "local_dir"}, required: []string{"share", "local_dir"}, write: true, openWorld: true},
|
||||
{name: "mount", description: "Clone and sync a share or share/subpath into a local directory; may merge local files and push changes unless read_only=true. Replaces that mount's configuration and clears its pin. Review conflicts after mounting.", fields: []string{"share", "local_dir", "read_only", "exclude"}, required: []string{"share", "local_dir"}, write: true, destructive: true, openWorld: true},
|
||||
{name: "restore", description: "Restore a mounted share or relative path from a snapshot, modifying local files and publishing a new head.", fields: []string{"share", "snapshot", "path"}, required: []string{"share", "snapshot"}, write: true, destructive: true, openWorld: true},
|
||||
{name: "deploy", description: "Rewrite a mount to a snapshot without pushing, then pin it against live advancement.", fields: []string{"share", "snapshot"}, required: []string{"share", "snapshot"}, write: true, destructive: true, idempotent: true, openWorld: true},
|
||||
{name: "unmount", description: "Remove a share's mount configuration and sync state. Files remain on disk.", fields: []string{"share"}, required: []string{"share"}, write: true, destructive: true},
|
||||
}
|
||||
for _, spec := range specs {
|
||||
if spec.write && !writes {
|
||||
continue
|
||||
}
|
||||
// mount is available with writes as planned, but accurately advertises its
|
||||
// existing merge/config-replacement behavior as potentially destructive.
|
||||
if (spec.name == "restore" || spec.name == "deploy" || spec.name == "unmount") && !destructive {
|
||||
continue
|
||||
}
|
||||
props := map[string]any{}
|
||||
for _, field := range spec.fields {
|
||||
props[field] = mcpFieldSchema(field, spec.name)
|
||||
}
|
||||
schema := map[string]any{"type": "object", "properties": props, "additionalProperties": false}
|
||||
if len(spec.required) > 0 {
|
||||
schema["required"] = spec.required
|
||||
}
|
||||
server.AddTool(&mcp.Tool{
|
||||
Name: "devbox_" + spec.name, Description: spec.description, InputSchema: schema,
|
||||
OutputSchema: map[string]any{"type": "object", "properties": map[string]any{
|
||||
"stdout": map[string]any{"type": "string"}, "stderr": map[string]any{"type": "string"},
|
||||
"exit_code": map[string]any{"type": "integer"}, "truncated": map[string]any{"type": "boolean"},
|
||||
"data": map[string]any{"description": "Parsed CLI JSON, when complete and valid (object or array)."}, "error": map[string]any{"type": "string"},
|
||||
}, "required": []string{"stdout", "stderr", "exit_code", "truncated"}, "additionalProperties": false},
|
||||
Annotations: &mcp.ToolAnnotations{ReadOnlyHint: !spec.write, DestructiveHint: &spec.destructive, IdempotentHint: spec.idempotent, OpenWorldHint: &spec.openWorld},
|
||||
}, func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
args, err := mcpCommandArgs(spec, req.Params.Arguments)
|
||||
if err != nil {
|
||||
return mcpResult(mcpCommandResult{ExitCode: -1, Error: err.Error()}), nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
select {
|
||||
case gate <- struct{}{}:
|
||||
defer func() { <-gate }()
|
||||
case <-ctx.Done():
|
||||
return mcpResult(mcpCommandResult{ExitCode: -1, Error: ctx.Err().Error()}), nil
|
||||
}
|
||||
return mcpResult(runMCPCommand(ctx, executable, args)), nil
|
||||
})
|
||||
}
|
||||
return server
|
||||
}
|
||||
|
||||
func mcpFieldSchema(field, tool string) map[string]any {
|
||||
switch field {
|
||||
case "limit":
|
||||
return map[string]any{"type": "integer", "minimum": 1, "maximum": 100, "default": 20, "description": "Maximum newest snapshots to return."}
|
||||
case "read_only":
|
||||
return map[string]any{"type": "boolean", "default": false, "description": "Pull only; never push local files."}
|
||||
case "exclude":
|
||||
return map[string]any{"type": "array", "maxItems": 100, "items": map[string]any{"type": "string", "minLength": 1, "maxLength": 4096}, "description": "Device-local gitignore patterns layered over .devignore."}
|
||||
case "local_dir":
|
||||
return map[string]any{"type": "string", "minLength": 1, "maxLength": 4096, "description": "Absolute local directory path. Shell characters are literal; no expansion."}
|
||||
case "snapshot":
|
||||
return map[string]any{"type": "string", "pattern": "^[a-f0-9]{64}$", "description": "Full 64-character snapshot ID from devbox_history."}
|
||||
case "duration":
|
||||
return map[string]any{"type": "string", "minLength": 1, "maxLength": 128, "description": "Positive Go duration, e.g. 30m or 2h; omitted pauses until resume."}
|
||||
case "path":
|
||||
return map[string]any{"type": "string", "minLength": 1, "maxLength": 4096, "description": "Relative forward-slash file path within the share; no dot or parent components."}
|
||||
default:
|
||||
desc := "Share name (letters, digits, dots, underscores, hyphens; no leading dot or hyphen)."
|
||||
if tool == "mount" {
|
||||
desc += " Optionally append /relative/subpath."
|
||||
}
|
||||
return map[string]any{"type": "string", "minLength": 1, "maxLength": 4096, "description": desc}
|
||||
}
|
||||
}
|
||||
|
||||
var mcpSharePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
|
||||
var mcpSnapshotPattern = regexp.MustCompile(`^[a-f0-9]{64}$`)
|
||||
|
||||
func mcpCommandArgs(spec mcpToolSpec, raw json.RawMessage) ([]string, error) {
|
||||
if len(raw) == 0 {
|
||||
raw = []byte("{}")
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &fields); err != nil || fields == nil {
|
||||
return nil, fmt.Errorf("arguments must be an object")
|
||||
}
|
||||
allowed := map[string]bool{}
|
||||
for _, k := range spec.fields {
|
||||
allowed[k] = true
|
||||
}
|
||||
for k, v := range fields {
|
||||
if !allowed[k] {
|
||||
return nil, fmt.Errorf("unknown argument %q", k)
|
||||
}
|
||||
if bytes.Equal(bytes.TrimSpace(v), []byte("null")) {
|
||||
return nil, fmt.Errorf("%s must not be null", k)
|
||||
}
|
||||
}
|
||||
for _, k := range spec.required {
|
||||
if _, ok := fields[k]; !ok {
|
||||
return nil, fmt.Errorf("%s is required", k)
|
||||
}
|
||||
}
|
||||
var a mcpArguments
|
||||
if err := json.Unmarshal(raw, &a); err != nil {
|
||||
return nil, fmt.Errorf("invalid arguments: %w", err)
|
||||
}
|
||||
for k, v := range map[string]string{"share": a.Share, "local_dir": a.LocalDir, "snapshot": a.Snapshot, "path": a.Path, "duration": a.Duration} {
|
||||
if _, ok := fields[k]; ok && (v == "" || len(v) > 4096 || strings.IndexFunc(v, unicode.IsControl) >= 0) {
|
||||
return nil, fmt.Errorf("%s must be nonempty, at most 4096 bytes, and contain no control characters", k)
|
||||
}
|
||||
}
|
||||
if a.Share != "" {
|
||||
share, sub := splitShare(a.Share)
|
||||
if !mcpSharePattern.MatchString(share) || strings.HasSuffix(share, ".") {
|
||||
return nil, fmt.Errorf("invalid share name")
|
||||
}
|
||||
if strings.Contains(a.Share, "/") && (spec.name != "mount" || !mcpRelativePath(sub)) {
|
||||
return nil, fmt.Errorf("only mount accepts share/subpath; subpath must be a safe relative path")
|
||||
}
|
||||
}
|
||||
if a.LocalDir != "" && !filepath.IsAbs(a.LocalDir) {
|
||||
return nil, fmt.Errorf("local_dir must be an absolute path")
|
||||
}
|
||||
if a.Snapshot != "" && !mcpSnapshotPattern.MatchString(a.Snapshot) {
|
||||
return nil, fmt.Errorf("snapshot must be a full lowercase 64-character hex ID")
|
||||
}
|
||||
if a.Path != "" && !mcpRelativePath(a.Path) {
|
||||
return nil, fmt.Errorf("path must be relative without dot or parent components")
|
||||
}
|
||||
if a.Duration != "" {
|
||||
d, err := time.ParseDuration(a.Duration)
|
||||
if err != nil || d <= 0 || len(a.Duration) > 128 {
|
||||
return nil, fmt.Errorf("duration must be a positive Go duration, e.g. 30m")
|
||||
}
|
||||
}
|
||||
if len(a.Exclude) > 100 {
|
||||
return nil, fmt.Errorf("exclude supports at most 100 patterns")
|
||||
}
|
||||
for _, p := range a.Exclude {
|
||||
if p == "" || len(p) > 4096 || strings.IndexFunc(p, unicode.IsControl) >= 0 {
|
||||
return nil, fmt.Errorf("invalid exclude pattern")
|
||||
}
|
||||
}
|
||||
command := spec.name
|
||||
if command == "history" {
|
||||
command = "log"
|
||||
}
|
||||
args := []string{command}
|
||||
switch spec.name {
|
||||
case "status", "doctor", "conflicts":
|
||||
args = append(args, "--json")
|
||||
case "history":
|
||||
limit := 20
|
||||
if a.Limit != nil {
|
||||
limit = *a.Limit
|
||||
}
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, fmt.Errorf("limit must be between 1 and 100")
|
||||
}
|
||||
args = append(args, "--json", fmt.Sprintf("--limit=%d", limit))
|
||||
case "pause":
|
||||
if a.Duration != "" {
|
||||
args = append(args, "--for="+a.Duration)
|
||||
}
|
||||
case "mount":
|
||||
if a.ReadOnly {
|
||||
args = append(args, "--ro")
|
||||
}
|
||||
for _, p := range a.Exclude {
|
||||
args = append(args, "--exclude="+p)
|
||||
}
|
||||
}
|
||||
args = append(args, "--")
|
||||
switch spec.name {
|
||||
case "history", "members", "unmount":
|
||||
args = append(args, a.Share)
|
||||
case "publish":
|
||||
args = append(args, a.LocalDir, a.Share)
|
||||
case "mount":
|
||||
args = append(args, a.Share, a.LocalDir)
|
||||
case "restore", "deploy":
|
||||
args = append(args, a.Share, a.Snapshot)
|
||||
if a.Path != "" {
|
||||
args = append(args, a.Path)
|
||||
}
|
||||
}
|
||||
return args, nil
|
||||
}
|
||||
|
||||
func mcpRelativePath(p string) bool {
|
||||
if p == "" || strings.HasPrefix(p, "-") || strings.ContainsAny(p, `\:`) || strings.IndexFunc(p, unicode.IsControl) >= 0 {
|
||||
return false
|
||||
}
|
||||
for _, part := range strings.Split(p, "/") {
|
||||
if part == "" || part == "." || part == ".." {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Keep draining after the cap so a noisy child cannot deadlock on a full pipe.
|
||||
type mcpCapture struct {
|
||||
buffer bytes.Buffer
|
||||
limit int
|
||||
truncated bool
|
||||
}
|
||||
|
||||
func (b *mcpCapture) Write(p []byte) (int, error) {
|
||||
n := len(p)
|
||||
if len(p) > b.limit-b.buffer.Len() {
|
||||
p = p[:b.limit-b.buffer.Len()]
|
||||
b.truncated = true
|
||||
}
|
||||
_, _ = b.buffer.Write(p)
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func runMCPCommand(ctx context.Context, executable string, args []string) mcpCommandResult {
|
||||
out, stderr := &mcpCapture{limit: mcpOutputLimit}, &mcpCapture{limit: mcpStderrLimit}
|
||||
cmd := exec.CommandContext(ctx, executable, args...)
|
||||
cmd.Stdout, cmd.Stderr = out, stderr
|
||||
cmd.Stdin = nil // Commands must never prompt or consume MCP protocol input.
|
||||
cmd.WaitDelay = time.Second
|
||||
err := cmd.Run()
|
||||
result := mcpCommandResult{Stdout: strings.ToValidUTF8(out.buffer.String(), ""), Stderr: strings.ToValidUTF8(stderr.buffer.String(), ""), Truncated: out.truncated || stderr.truncated}
|
||||
if err != nil {
|
||||
result.ExitCode = -1
|
||||
if cmd.ProcessState != nil {
|
||||
result.ExitCode = cmd.ProcessState.ExitCode()
|
||||
}
|
||||
result.Error = err.Error()
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
result.Error = ctx.Err().Error() + "; completed side effects are not rolled back; inspect state before retrying"
|
||||
}
|
||||
if !out.truncated {
|
||||
var data any
|
||||
if json.Unmarshal(out.buffer.Bytes(), &data) == nil {
|
||||
result.Data = data
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func mcpResult(result mcpCommandResult) *mcp.CallToolResult {
|
||||
// Emit the same envelope as text for clients without structured-content support.
|
||||
data, _ := json.Marshal(result)
|
||||
return &mcp.CallToolResult{IsError: result.Error != "", StructuredContent: result, Content: []mcp.Content{&mcp.TextContent{Text: string(data)}}}
|
||||
}
|
||||
|
|
@ -1,545 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/shoemoney/devbox/internal/config"
|
||||
"github.com/shoemoney/devbox/internal/control"
|
||||
"github.com/shoemoney/devbox/internal/daemon"
|
||||
"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/identity"
|
||||
"github.com/shoemoney/devbox/internal/ignore"
|
||||
"github.com/shoemoney/devbox/internal/secret"
|
||||
"github.com/shoemoney/devbox/internal/syncer"
|
||||
"github.com/shoemoney/devbox/internal/transport"
|
||||
"github.com/shoemoney/devbox/pkg/proto"
|
||||
)
|
||||
|
||||
// DEVBOX_MCP_TEST_BINARY reruns these protocol checks against a packaged binary.
|
||||
// Otherwise build the actual command with the race detector, not a test shim.
|
||||
func TestMCPStdio(t *testing.T) {
|
||||
binary := os.Getenv("DEVBOX_MCP_TEST_BINARY")
|
||||
if binary == "" {
|
||||
binary = filepath.Join(t.TempDir(), "devbox")
|
||||
if runtime.GOOS == "windows" {
|
||||
binary += ".exe"
|
||||
}
|
||||
build := exec.Command("go", "build", "-race", "-o", binary, ".")
|
||||
if out, err := build.CombinedOutput(); err != nil {
|
||||
t.Fatalf("build actual binary: %v\n%s", err, out)
|
||||
}
|
||||
}
|
||||
t.Run("permissions-and-errors", func(t *testing.T) {
|
||||
for _, mode := range []struct {
|
||||
flags []string
|
||||
count int
|
||||
}{{nil, 5}, {[]string{"--allow-writes"}, 9}, {[]string{"--allow-writes", "--allow-destructive"}, 12}} {
|
||||
t.Run(fmt.Sprint(mode.count), func(t *testing.T) {
|
||||
cfg := t.TempDir()
|
||||
cs := mcpTestClient(t, binary, cfg, mode.flags...)
|
||||
listed, err := cs.ListTools(t.Context(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(listed.Tools) != mode.count {
|
||||
t.Fatalf("tool count %d, want %d", len(listed.Tools), mode.count)
|
||||
}
|
||||
names := map[string]bool{}
|
||||
for _, tool := range listed.Tools {
|
||||
names[tool.Name] = true
|
||||
if tool.InputSchema == nil || tool.OutputSchema == nil || tool.Annotations == nil {
|
||||
t.Fatalf("missing schema/annotations: %s", tool.Name)
|
||||
}
|
||||
read := tool.Name == "devbox_status" || tool.Name == "devbox_doctor" || tool.Name == "devbox_conflicts" || tool.Name == "devbox_history" || tool.Name == "devbox_members"
|
||||
if tool.Annotations.ReadOnlyHint != read {
|
||||
t.Fatalf("wrong read annotation: %s", tool.Name)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"devbox_status", "devbox_doctor", "devbox_conflicts", "devbox_history", "devbox_members"} {
|
||||
if !names[name] {
|
||||
t.Fatalf("missing %s", name)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"devbox_pause", "devbox_resume", "devbox_publish", "devbox_mount"} {
|
||||
if names[name] != (mode.count >= 9) {
|
||||
t.Fatalf("bad gating %s", name)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"devbox_restore", "devbox_deploy", "devbox_unmount"} {
|
||||
if names[name] != (mode.count == 12) {
|
||||
t.Fatalf("bad gating %s", name)
|
||||
}
|
||||
}
|
||||
got := mcpCall(t, cs, "status", nil, false)
|
||||
var status statusJSON
|
||||
mcpData(t, got, &status)
|
||||
if status.Joined {
|
||||
t.Fatal("fabricated enrollment")
|
||||
}
|
||||
doctor := mcpCall(t, cs, "doctor", nil, true)
|
||||
var checks []struct{ Name, Status, Detail string }
|
||||
mcpData(t, doctor, &checks)
|
||||
if doctor.ExitCode == 0 || len(checks) != 1 || checks[0].Name != "identity" || checks[0].Status != "fail" {
|
||||
t.Fatalf("lost failed diagnostics: %+v", doctor)
|
||||
}
|
||||
mcpCall(t, cs, "conflicts", nil, false)
|
||||
mcpCall(t, cs, "history", map[string]any{"share": "demo"}, true)
|
||||
if mode.count == 5 {
|
||||
for _, name := range []string{"pause", "resume", "publish", "mount", "restore", "deploy", "unmount"} {
|
||||
_, err := cs.CallTool(t.Context(), &mcp.CallToolParams{Name: "devbox_" + name, Arguments: map[string]any{}})
|
||||
if err == nil {
|
||||
t.Fatalf("disabled tool callable: %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
// A command error must leave stdout readable as protocol traffic.
|
||||
mcpCall(t, cs, "status", nil, false)
|
||||
})
|
||||
}
|
||||
for _, flags := range [][]string{{"--allow-destructive"}, {"--command-timeout=0s"}, {"--command-timeout=-1s"}} {
|
||||
cmd := exec.Command(binary, append([]string{"mcp"}, flags...)...)
|
||||
cmd.Env = mcpTestEnv(t.TempDir())
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err == nil || stdout.Len() != 0 || stderr.Len() == 0 {
|
||||
t.Fatalf("invalid flags accepted or stdout polluted: %v", flags)
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("input-validation", func(t *testing.T) {
|
||||
cs := mcpTestClient(t, binary, t.TempDir(), "--allow-writes", "--allow-destructive")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
args any
|
||||
}{
|
||||
{"status", map[string]any{"command": "whoami"}},
|
||||
{"conflicts", map[string]any{"rm": true}},
|
||||
{"history", map[string]any{"share": "--help"}},
|
||||
{"history", map[string]any{"share": "demo; touch /tmp/unwanted"}},
|
||||
{"history", map[string]any{"share": "demo", "limit": 0}},
|
||||
{"history", map[string]any{"share": "demo", "limit": 101}},
|
||||
{"history", map[string]any{"share": "demo", "limit": 1.5}},
|
||||
{"history", map[string]any{"share": "demo", "limit": nil}},
|
||||
{"history", map[string]any{}},
|
||||
{"history", map[string]any{"share": "demo/sub"}},
|
||||
{"mount", map[string]any{"share": "demo/../escape", "local_dir": t.TempDir()}},
|
||||
{"mount", map[string]any{"share": "demo", "local_dir": "--help"}},
|
||||
{"mount", map[string]any{"share": "demo", "local_dir": t.TempDir(), "read_only": "true"}},
|
||||
{"mount", map[string]any{"share": "demo", "local_dir": t.TempDir(), "exclude": []string{"x\n--help"}}},
|
||||
{"publish", map[string]any{"share": "demo", "local_dir": "relative"}},
|
||||
{"pause", map[string]any{"duration": "-1s"}},
|
||||
{"pause", map[string]any{"duration": "1s --help"}},
|
||||
{"restore", map[string]any{"share": "demo", "snapshot": "--help"}},
|
||||
{"restore", map[string]any{"share": "demo", "snapshot": strings.Repeat("a", 64), "path": "../escape"}},
|
||||
{"deploy", map[string]any{"share": "demo", "snapshot": strings.Repeat("a", 64), "path": "file"}},
|
||||
{"unmount", map[string]any{"share": "demo\x00evil"}},
|
||||
} {
|
||||
r := mcpCall(t, cs, tc.name, tc.args, true)
|
||||
if r.ExitCode != -1 || r.Stdout != "" || r.Stderr != "" {
|
||||
t.Fatalf("invalid input reached child: %s %+v", tc.name, r)
|
||||
}
|
||||
}
|
||||
mcpCall(t, cs, "status", nil, false)
|
||||
})
|
||||
t.Run("actual-isolated-hub", func(t *testing.T) { mcpTestHub(t, binary) })
|
||||
t.Run("cancellation-and-timeout", func(t *testing.T) { mcpTestCancellation(t, binary) })
|
||||
t.Run("output-cap", func(t *testing.T) {
|
||||
cfg := t.TempDir()
|
||||
dir := filepath.Join(cfg, "devbox")
|
||||
if _, err := identity.LoadOrCreate(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := config.Daemon{Hub: "http://127.0.0.1:1", Bearer: "fixture-secret-must-not-appear"}
|
||||
for i := 0; i < 10000; i++ {
|
||||
d.Mounts = append(d.Mounts, config.Mount{Share: fmt.Sprintf("share%d", i), Local: "/unused/" + strings.Repeat("x", 128)})
|
||||
}
|
||||
if err := config.SaveDaemon(dir, d); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cs := mcpTestClient(t, binary, cfg)
|
||||
r := mcpCall(t, cs, "status", nil, false)
|
||||
if !r.Truncated || len(r.Stdout) != mcpOutputLimit || r.Data != nil {
|
||||
t.Fatalf("cap not enforced: bytes=%d, truncated=%v", len(r.Stdout), r.Truncated)
|
||||
}
|
||||
if strings.Contains(r.Stdout, d.Bearer) {
|
||||
t.Fatal("bearer leaked")
|
||||
}
|
||||
mcpCall(t, cs, "history", map[string]any{"share": "demo", "limit": 0}, true)
|
||||
})
|
||||
}
|
||||
|
||||
func mcpTestEnv(cfg string) []string {
|
||||
env := []string{}
|
||||
for _, v := range os.Environ() {
|
||||
if !strings.HasPrefix(v, "XDG_CONFIG_HOME=") && !strings.HasPrefix(v, "GORACE=") {
|
||||
env = append(env, v)
|
||||
}
|
||||
}
|
||||
return append(env, "XDG_CONFIG_HOME="+cfg, "GORACE=atexit_sleep_ms=0")
|
||||
}
|
||||
|
||||
func mcpTestClient(t *testing.T, binary, cfg string, flags ...string) *mcp.ClientSession {
|
||||
t.Helper()
|
||||
cmd := exec.Command(binary, append([]string{"mcp"}, flags...)...)
|
||||
cmd.Env = mcpTestEnv(cfg)
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
client := mcp.NewClient(&mcp.Implementation{Name: "devbox-mcp-test", Version: "1"}, nil)
|
||||
cs, err := client.Connect(t.Context(), &mcp.CommandTransport{Command: cmd}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("stdio initialize: %v; stderr: %s", err, stderr.String())
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := cs.Close(); err != nil {
|
||||
t.Errorf("stdio close: %v", err)
|
||||
}
|
||||
if stderr.Len() != 0 {
|
||||
t.Errorf("unexpected server stderr: %s", stderr.String())
|
||||
}
|
||||
})
|
||||
return cs
|
||||
}
|
||||
|
||||
func mcpCall(t *testing.T, cs *mcp.ClientSession, name string, args any, wantError bool) mcpCommandResult {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second)
|
||||
defer cancel()
|
||||
r, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "devbox_" + name, Arguments: args})
|
||||
if err != nil {
|
||||
t.Fatalf("%s protocol call: %v", name, err)
|
||||
}
|
||||
if r.IsError != wantError {
|
||||
t.Fatalf("%s isError=%v, want %v: %+v", name, r.IsError, wantError, r.Content)
|
||||
}
|
||||
raw, err := json.Marshal(r.StructuredContent)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var result mcpCommandResult
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(r.Content) != 1 || r.Content[0].(*mcp.TextContent).Text == "" {
|
||||
t.Fatalf("missing readable result: %s", name)
|
||||
}
|
||||
var text mcpCommandResult
|
||||
if err := json.Unmarshal([]byte(r.Content[0].(*mcp.TextContent).Text), &text); err != nil || text.Stdout != result.Stdout || text.Error != result.Error {
|
||||
t.Fatalf("text/structured mismatch: %s", name)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func mcpData(t *testing.T, r mcpCommandResult, dst any) {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(r.Data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := json.Unmarshal(b, dst); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func mcpTestHub(t *testing.T, binary string) {
|
||||
db, err := meta.Open(filepath.Join(t.TempDir(), "hub.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
store, err := blobstore.NewDisk(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := httptest.NewServer(hub.NewServer(db, store).Handler())
|
||||
defer server.Close()
|
||||
cfg := t.TempDir()
|
||||
dir := filepath.Join(cfg, "devbox")
|
||||
if err := db.CreateToken(hub.HashToken("isolated-mcp-fixture"), time.Now().Add(time.Hour).Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
joined, err := joinHub(dir, server.URL, "isolated-mcp-fixture")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cs := mcpTestClient(t, binary, cfg, "--allow-writes", "--allow-destructive")
|
||||
inspection := mcpTestClient(t, binary, cfg)
|
||||
src := t.TempDir()
|
||||
content := "MCP fixture first version\n"
|
||||
if err := os.WriteFile(filepath.Join(src, "hello.txt"), []byte(content), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mcpCall(t, cs, "publish", map[string]any{"share": "fixture", "local_dir": src}, false)
|
||||
client := transport.New(server.URL)
|
||||
client.SetBearer(joined.Bearer)
|
||||
initial, err := client.Log("fixture")
|
||||
if err != nil || len(initial) != 1 {
|
||||
t.Fatalf("initial snapshot: %v", err)
|
||||
}
|
||||
// A second enrolled device exercises actual two-way mount and creates history
|
||||
// without racing any daemon or touching the worker's own configuration.
|
||||
cfg2 := t.TempDir()
|
||||
dir2 := filepath.Join(cfg2, "devbox")
|
||||
if err := db.CreateToken(hub.HashToken("second-mcp-fixture"), time.Now().Add(time.Hour).Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := joinHub(dir2, server.URL, "second-mcp-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cs2 := mcpTestClient(t, binary, cfg2, "--allow-writes")
|
||||
// Shell syntax is a literal directory name; never interpreted or expanded.
|
||||
dst := filepath.Join(t.TempDir(), "literal $(echo injected); --help")
|
||||
mcpCall(t, cs2, "mount", map[string]any{"share": "fixture", "local_dir": dst, "exclude": []string{"--ro"}}, false)
|
||||
got, err := os.ReadFile(filepath.Join(dst, "hello.txt"))
|
||||
if err != nil || string(got) != content {
|
||||
t.Fatal("mount did not download fixture")
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dst, "hello.txt"), []byte("second version\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mcpCall(t, cs2, "mount", map[string]any{"share": "fixture", "local_dir": dst}, false)
|
||||
// Multiple distinct versions prove default and explicit history limits.
|
||||
ig, err := syncer.LoadIgnoreWith(dst, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 22; i++ {
|
||||
if err := os.WriteFile(filepath.Join(dst, "hello.txt"), []byte(fmt.Sprintf("version %d\n", i)), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head, err := client.Head("fixture")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := pushFixture(client, dst, ig, head); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
history := mcpCall(t, inspection, "history", map[string]any{"share": "fixture"}, false)
|
||||
var snaps []proto.SnapshotInfo
|
||||
mcpData(t, history, &snaps)
|
||||
if len(snaps) != 20 {
|
||||
t.Fatalf("default limit=%d", len(snaps))
|
||||
}
|
||||
latest := snaps[0].ID
|
||||
history = mcpCall(t, inspection, "history", map[string]any{"share": "fixture", "limit": 1}, false)
|
||||
mcpData(t, history, &snaps)
|
||||
if len(snaps) != 1 || snaps[0].ID != latest {
|
||||
t.Fatal("limit/order mismatch")
|
||||
}
|
||||
mcpCall(t, inspection, "members", map[string]any{"share": "fixture"}, false)
|
||||
mcpCall(t, cs, "mount", map[string]any{"share": "fixture", "local_dir": src, "read_only": true}, false)
|
||||
mcpCall(t, cs, "deploy", map[string]any{"share": "fixture", "snapshot": initial[0].ID}, false)
|
||||
got, err = os.ReadFile(filepath.Join(src, "hello.txt"))
|
||||
if err != nil || string(got) != content {
|
||||
t.Fatal("deploy did not restore original file")
|
||||
}
|
||||
d, err := config.LoadDaemon(dir)
|
||||
if err != nil || len(d.Mounts) != 1 || !d.Mounts[0].Pinned {
|
||||
t.Fatal("deploy pin missing")
|
||||
}
|
||||
head, err := client.Head("fixture")
|
||||
if err != nil || head != latest {
|
||||
t.Fatal("deploy changed hub head")
|
||||
}
|
||||
// Restore requires a read-write mount, so re-mount the second device to pick
|
||||
// up the latest head, then opt that MCP process into destructive operations.
|
||||
cs2destructive := mcpTestClient(t, binary, cfg2, "--allow-writes", "--allow-destructive")
|
||||
mcpCall(t, cs2, "mount", map[string]any{"share": "fixture", "local_dir": dst}, false)
|
||||
mcpCall(t, cs2destructive, "restore", map[string]any{"share": "fixture", "snapshot": initial[0].ID, "path": "hello.txt"}, false)
|
||||
got, err = os.ReadFile(filepath.Join(dst, "hello.txt"))
|
||||
if err != nil || string(got) != content {
|
||||
t.Fatal("restore did not restore original file")
|
||||
}
|
||||
head, err = client.Head("fixture")
|
||||
if err != nil || head == latest {
|
||||
t.Fatal("restore did not publish new head")
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(src, "hello.conflict-fixture-1.txt"), []byte("conflict"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conflicts := mcpCall(t, inspection, "conflicts", nil, false)
|
||||
var copies []struct{ Share, Path string }
|
||||
mcpData(t, conflicts, &copies)
|
||||
if len(copies) != 1 || copies[0].Share != "fixture" {
|
||||
t.Fatal("conflict missing")
|
||||
}
|
||||
// A real control server and daemon instance prove pause/resume IPC without
|
||||
// starting a watcher or syncing background data on the shared host.
|
||||
if runtime.GOOS != "windows" {
|
||||
dmn, err := daemon.New(dir, d, "mcp-fixture", func(string, ...any) {})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
controlCtx, stop := context.WithCancel(t.Context())
|
||||
defer stop()
|
||||
if _, err := control.Serve(controlCtx, dir, dmn, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mcpCall(t, cs, "pause", map[string]any{"duration": "1h"}, false)
|
||||
status := mcpCall(t, inspection, "status", nil, false)
|
||||
var st statusJSON
|
||||
mcpData(t, status, &st)
|
||||
if !st.Live || !st.Paused {
|
||||
t.Fatal("pause not reflected in live status")
|
||||
}
|
||||
mcpCall(t, cs, "resume", nil, false)
|
||||
if dmn.StateSnapshot().Paused {
|
||||
t.Fatal("resume did not clear pause")
|
||||
}
|
||||
}
|
||||
mcpCall(t, cs, "unmount", map[string]any{"share": "fixture"}, false)
|
||||
if _, err := os.Stat(filepath.Join(src, "hello.txt")); err != nil {
|
||||
t.Fatal("unmount removed files")
|
||||
}
|
||||
d, err = config.LoadDaemon(dir)
|
||||
if err != nil || len(d.Mounts) != 0 {
|
||||
t.Fatal("unmount retained mount")
|
||||
}
|
||||
// Inspect result envelopes, including failed commands, for private material.
|
||||
for _, result := range []mcpCommandResult{history, conflicts, mcpCall(t, inspection, "doctor", nil, false)} {
|
||||
b, _ := json.Marshal(result)
|
||||
if strings.Contains(string(b), joined.Bearer) || strings.Contains(string(b), "DEVBOX PRIVATE KEY") {
|
||||
t.Fatal("private material in MCP result")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func pushFixture(c *transport.Client, dir string, ig *ignore.Matcher, head string) error {
|
||||
guard, err := secret.New(nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := syncer.Push(c, dir, "fixture", "", ig, guard, head, nil)
|
||||
if err == nil && result.Conflict {
|
||||
return fmt.Errorf("fixture push unexpectedly conflicted")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func mcpTestCancellation(t *testing.T, binary string) {
|
||||
for _, kind := range []string{"cancel", "timeout"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
started, ended := make(chan struct{}), make(chan struct{})
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != proto.PathLog {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
close(started)
|
||||
<-r.Context().Done()
|
||||
close(ended)
|
||||
}))
|
||||
defer func() { server.CloseClientConnections(); server.Close() }()
|
||||
cfg := t.TempDir()
|
||||
dir := filepath.Join(cfg, "devbox")
|
||||
if _, err := identity.LoadOrCreate(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := config.SaveDaemon(dir, config.Daemon{Hub: server.URL, Bearer: "isolated-fake-bearer"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
flags := []string{}
|
||||
if kind == "timeout" {
|
||||
flags = append(flags, "--command-timeout=750ms")
|
||||
}
|
||||
cs := mcpTestClient(t, binary, cfg, flags...)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
type response struct {
|
||||
r *mcp.CallToolResult
|
||||
err error
|
||||
}
|
||||
done := make(chan response, 1)
|
||||
go func() {
|
||||
r, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "devbox_history", Arguments: map[string]any{"share": "demo"}})
|
||||
done <- response{r, err}
|
||||
}()
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("child did not reach HTTP request")
|
||||
}
|
||||
if kind == "cancel" {
|
||||
cancel()
|
||||
}
|
||||
select {
|
||||
case <-ended:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("cancellation did not terminate child HTTP connection")
|
||||
}
|
||||
select {
|
||||
case got := <-done:
|
||||
if kind == "timeout" {
|
||||
if got.err != nil || got.r == nil || !got.r.IsError {
|
||||
t.Fatalf("timeout lost tool error: %v", got.err)
|
||||
}
|
||||
b, _ := json.Marshal(got.r.StructuredContent)
|
||||
if !strings.Contains(string(b), "context deadline exceeded") || !strings.Contains(string(b), "not rolled back") {
|
||||
t.Fatal("missing timeout/retry explanation")
|
||||
}
|
||||
} else if got.err == nil && (got.r == nil || !got.r.IsError) {
|
||||
t.Fatal("cancelled command reported success")
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("call did not finish after cancellation")
|
||||
}
|
||||
// Completion and a subsequent call prove the gate/stdio session survives.
|
||||
mcpCall(t, cs, "status", nil, false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPCapture(t *testing.T) {
|
||||
for _, limit := range []int{0, 1, 10} {
|
||||
b := &mcpCapture{limit: limit}
|
||||
for i := 0; i < 3; i++ {
|
||||
if n, err := b.Write([]byte("0123456789")); err != nil || n != 10 {
|
||||
t.Fatal("writer must drain all bytes")
|
||||
}
|
||||
}
|
||||
if b.buffer.Len() != limit || !b.truncated {
|
||||
t.Fatal("capture exceeded bound")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This subprocess exercises both pipe-draining paths and nonzero exit handling;
|
||||
// the stdio suite separately exercises the stdout cap on the actual CLI binary.
|
||||
func TestMCPCommandCapture(t *testing.T) {
|
||||
t.Setenv("DEVBOX_MCP_COMMAND_FIXTURE", "1")
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
got := runMCPCommand(ctx, executable, []string{"-test.run=^TestMCPCommandFixture$", "--"})
|
||||
if got.ExitCode != 7 || got.Error == "" || !got.Truncated || len(got.Stdout) != mcpOutputLimit || len(got.Stderr) != mcpStderrLimit || got.Data != nil {
|
||||
t.Fatalf("capture failed: exit=%d, error=%q, trunc=%v, stdout=%d, stderr=%d", got.ExitCode, got.Error, got.Truncated, len(got.Stdout), len(got.Stderr))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPCommandFixture(t *testing.T) {
|
||||
if os.Getenv("DEVBOX_MCP_COMMAND_FIXTURE") != "1" {
|
||||
return
|
||||
}
|
||||
_, _ = os.Stdout.Write(bytes.Repeat([]byte("x"), mcpOutputLimit+4096))
|
||||
_, _ = os.Stderr.Write(bytes.Repeat([]byte("y"), mcpStderrLimit+4096))
|
||||
os.Exit(7)
|
||||
}
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
# Built-in MCP for devbox
|
||||
|
||||
## Goal
|
||||
|
||||
Ship `devbox mcp`: an MCP server over stdin/stdout, inside the existing client
|
||||
binary. Agents can inspect an enrolled device and opt into sync operations.
|
||||
The existing hub, authentication, Tailscale networking, and conflict handling
|
||||
remain the source of behavior. No additional network listener is needed.
|
||||
|
||||
## Tool surface
|
||||
|
||||
| Access | Tools | CLI behavior reused |
|
||||
|---|---|---|
|
||||
| Default | `devbox_status`, `devbox_doctor`, `devbox_conflicts`, `devbox_history`, `devbox_members` | status, doctor, conflicts, log, members |
|
||||
| `--allow-writes` | `devbox_pause`, `devbox_resume`, `devbox_publish`, `devbox_mount` | pause, resume, publish, mount |
|
||||
| `--allow-writes --allow-destructive` | `devbox_restore`, `devbox_deploy`, `devbox_unmount` | restore, deploy, unmount |
|
||||
|
||||
Default operation is inspection only. Tool annotations describe read-only,
|
||||
destructive, idempotent, and open-world behavior accurately. Tools unavailable
|
||||
in the selected mode are not advertised and cannot be invoked.
|
||||
|
||||
## Implementation
|
||||
|
||||
Use the official Go MCP SDK with its stdio transport. Reuse the existing CLI
|
||||
commands through the current executable with explicit argument arrays, never a
|
||||
shell or an arbitrary command tool. This shares behavior and avoids coupling MCP
|
||||
handlers to private command implementations. Pass user arguments after an
|
||||
explicit option terminator where appropriate; validate inputs before execution.
|
||||
|
||||
Only MCP protocol messages go to stdout. Tool results contain structured data
|
||||
where existing commands provide JSON, plus a readable representation. Command
|
||||
errors remain tool errors and preserve useful diagnostic data. Never return the
|
||||
stored bearer token, device private key, or full config files.
|
||||
|
||||
Bound command duration and captured output. History responses support a limit.
|
||||
Cancellation terminates the child operation. Side effects already completed by
|
||||
a cancelled command are not automatically retried.
|
||||
|
||||
## Agent configuration
|
||||
|
||||
Document a portable `mcpServers.devbox` entry using an absolute executable path
|
||||
and `args: ["mcp"]`, plus opt-in write and destructive configurations. The MCP
|
||||
process uses the same user/config directory as `devbox setup` or `devbox join`.
|
||||
Start the sync daemon separately with `devbox start`.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. A real SDK client initializes the server, lists tools, and calls status over
|
||||
stdio. Stdout stays valid MCP traffic, including on errors.
|
||||
2. Inspection works with an empty/unjoined isolated config and reports that
|
||||
state without fabricating a connection.
|
||||
3. Default mode excludes mutating tools; explicit flags expose the documented
|
||||
sets. Invalid arguments cannot inject options or shell commands.
|
||||
4. An isolated actual hub verifies history and authenticated operations through
|
||||
MCP. Failed diagnostics return structured details and an error signal.
|
||||
5. Command cancellation and output bounds are exercised with meaningful tests.
|
||||
6. Vet, the race suite, platform builds, and packaged-binary MCP smoke checks pass
|
||||
on a build worker. Public installation from the new release works.
|
||||
7. README and release notes lead with built-in Tailscale and MCP, include real
|
||||
screenshots, explain hub/client scope, and distinguish demo captures from
|
||||
production enrollment evidence.
|
||||
151
docs/MCP.md
151
docs/MCP.md
|
|
@ -1,151 +0,0 @@
|
|||
# Use devbox from an AI agent
|
||||
|
||||
`devbox mcp` runs a Model Context Protocol server over stdin/stdout, built into
|
||||
the devbox client binary. It gives local agents structured access to the same
|
||||
device, mounts, and hub that the CLI uses. No separate MCP package, Node runtime,
|
||||
or additional network listener is required.
|
||||
|
||||

|
||||
|
||||
## Connect your device first
|
||||
|
||||
Enroll with `devbox setup` or `devbox join`, and configure mounts through the
|
||||
CLI. Start the sync daemon separately with `devbox start`. The MCP process
|
||||
inherits the launching user's config directory; `XDG_CONFIG_HOME` can select a
|
||||
different one. It does not ask for a join token through a tool.
|
||||
|
||||
For a Tailscale hub, connect the client machine's regular Tailscale app. Your
|
||||
hub runs embedded Tailscale with `devbox-hub serve --tailscale`; MCP tools use the
|
||||
private hub URL already stored by `devbox join`. MCP itself remains local stdio.
|
||||
|
||||
## Add it to an agent
|
||||
|
||||
Use the absolute path to the installed **file-sync devbox executable**. If you
|
||||
also have a fleet administration command named `devbox`, do not point the agent
|
||||
at that script.
|
||||
|
||||
### Codex
|
||||
|
||||
```bash
|
||||
codex mcp add devbox -- /absolute/path/to/devbox mcp
|
||||
```
|
||||
|
||||
For a separate devbox configuration:
|
||||
|
||||
```bash
|
||||
codex mcp add devbox --env XDG_CONFIG_HOME=/absolute/path/to/config-base -- /absolute/path/to/devbox mcp
|
||||
```
|
||||
|
||||
Equivalent TOML:
|
||||
|
||||
```toml
|
||||
[mcp_servers.devbox]
|
||||
command = "/absolute/path/to/devbox"
|
||||
args = ["mcp"]
|
||||
```
|
||||
|
||||
### Clients using `mcpServers` JSON
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"devbox": {
|
||||
"command": "/absolute/path/to/devbox",
|
||||
"args": ["mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Use the MCP configuration location supported by your agent. On Windows, select
|
||||
the absolute path to `devbox.exe`. Restart or reconnect the agent after adding
|
||||
the server.
|
||||
|
||||
## Use Mozilla AI mcpd
|
||||
|
||||
Mozilla AI's Go-based **mcpd** can manage `devbox mcp` and expose its tools through
|
||||
its HTTP API. The [tested mcpd example](../examples/mcpd/README.md) includes a
|
||||
Docker-runtime configuration, read-only enrollment mounts, explicit tool
|
||||
allowlisting, timeout settings, and a PHP HTTP example. It was verified with
|
||||
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.
|
||||
|
||||
## Available tools
|
||||
|
||||
The default server exposes inspection tools only:
|
||||
|
||||
| Tool | Purpose |
|
||||
|---|---|
|
||||
| `devbox_status` | Joined state, hub, configured mounts, and live daemon state when available |
|
||||
| `devbox_doctor` | Structured configuration, hub, filesystem, and watcher diagnostics |
|
||||
| `devbox_conflicts` | List conflict copies without deleting them |
|
||||
| `devbox_history` | Bounded snapshot history for a share |
|
||||
| `devbox_members` | Membership information for a share |
|
||||
|
||||
To allow sync operations, set `args` to `["mcp", "--allow-writes"]`:
|
||||
|
||||
| Additional tool | Purpose |
|
||||
|---|---|
|
||||
| `devbox_pause` | Pause the running sync daemon |
|
||||
| `devbox_resume` | Resume the running sync daemon |
|
||||
| `devbox_publish` | Create a share from a local directory and push its files |
|
||||
| `devbox_mount` | Mount a share or subdirectory, optionally read-only |
|
||||
|
||||
To also allow restore, deployment, and unmounting, use
|
||||
`["mcp", "--allow-writes", "--allow-destructive"]`:
|
||||
|
||||
| Additional tool | Purpose |
|
||||
|---|---|
|
||||
| `devbox_restore` | Restore a snapshot or selected path |
|
||||
| `devbox_deploy` | Apply a snapshot and pin the local mount |
|
||||
| `devbox_unmount` | Remove a mount from configuration |
|
||||
|
||||
`devbox_mount` may merge local files, push changes, replace its mount config,
|
||||
and clear a deployment pin. It is available with `--allow-writes` and advertises
|
||||
`destructiveHint: true`; set `read_only: true` for a pull-only mount. Publish and
|
||||
mount require an absolute `local_dir`; shell expansions such as `~` are not
|
||||
performed. Snapshot IDs must be the full lowercase 64-character value from
|
||||
history.
|
||||
|
||||
Unavailable tools are omitted from discovery. `--allow-destructive` requires
|
||||
`--allow-writes`. Tool descriptions and schemas specify the exact parameters.
|
||||
Use tool discovery rather than guessing arguments.
|
||||
|
||||
## Results and failures
|
||||
|
||||
Tools return structured results with the underlying command's output. A failed
|
||||
operation is marked as an MCP tool error, including failed doctor checks; an
|
||||
agent should inspect the diagnostic result before taking another action.
|
||||
|
||||
The command timeout defaults to `2m` and includes time waiting for another tool
|
||||
call in this server. Set a positive `--command-timeout`, for example
|
||||
`["mcp", "--command-timeout", "5m"]`, for large transfers. Captured stdout is
|
||||
limited to 1 MiB and stderr to 64 KiB; `truncated` reports clipping. Results have
|
||||
`stdout`, `stderr`, `exit_code`, `truncated`, optional parsed `data`, and optional
|
||||
`error` fields. History accepts `limit` from 1 to 100 (default 20).
|
||||
|
||||
Calls are serialized within one MCP server. Coordinate mount/config changes
|
||||
across multiple agents or CLI processes. Cancellation stops
|
||||
the child command. An interrupted write may have completed some work already;
|
||||
inspect status and history before retrying. Existing lifecycle hooks and
|
||||
conflict-preservation behavior apply exactly as they do through the CLI.
|
||||
|
||||
MCP stdout contains protocol traffic only. Logs and startup errors go to stderr.
|
||||
The server does not expose the stored bearer token, device private key, arbitrary
|
||||
shell commands, or conflict-copy deletion as tools.
|
||||
|
||||
## Useful agent requests
|
||||
|
||||
- “Check whether this device is joined and whether its sync daemon is running.”
|
||||
- “List conflicts and the latest snapshots for this share; don't change files.”
|
||||
- “Diagnose why this mount isn't syncing and explain the failing checks.”
|
||||
- With writes enabled: “Pause sync while I change dependencies, then resume it.”
|
||||
|
||||
See the [implementation plan](MCP-PLAN.md) for the scope and acceptance checks.
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
# Documentation screenshots
|
||||
|
||||
These images show released CLI output and a running isolated demo. They do not
|
||||
show production data, credentials, or production-tailnet enrollment.
|
||||
|
||||
- `tailscale-help.png`: screenshot of an HTML terminal-style presentation of the
|
||||
actual `devbox-hub serve --help | grep -- --tailscale` output. The presentation
|
||||
adds a title/caption; the flag descriptions are captured from the binary.
|
||||
- `mcp-tools.png`: screenshot of a terminal-style presentation of actual MCP
|
||||
tool discovery and a `devbox_status` result from the built-in stdio server.
|
||||
The server uses an isolated enrolled demo config.
|
||||
- `dashboard.png`: browser screenshot of the live dashboard from a local hub
|
||||
with three demo device identities and shares (`web-app`, `api-service`, and
|
||||
`shared-tools`). Changes are sent through actual sync daemons. The dashboard
|
||||
is separate from the API and is not itself published by `--tailscale`.
|
||||
|
||||
The Tailscale client/server distinction remains the same in every capture:
|
||||
the hub embeds tsnet, client machines use regular Tailscale, and MCP runs over
|
||||
local stdin/stdout in the client binary.
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 2.6 MiB After Width: | Height: | Size: 946 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 62 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 62 KiB |
|
|
@ -1,45 +0,0 @@
|
|||
<evaluation>
|
||||
<!-- Read-only agent evaluation prompts. Launch the documented modes and use
|
||||
tool discovery/schemas, the setup guide, and an isolated enrolled fixture.
|
||||
These prompts are not a claim that an LLM benchmark has been run. -->
|
||||
<qa_pair>
|
||||
<question>Discover the tools in default mode, inspect their annotations, and compare them with the guide. How many tools are available?</question>
|
||||
<answer>5</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Discover tools in default mode and with --allow-writes. How many additional tools does the write flag enable?</question>
|
||||
<answer>4</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Compare discovery in all three documented access modes. How many tools are available when both write and destructive flags are enabled?</question>
|
||||
<answer>12</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Inspect the tools available with --allow-writes and the schemas described in the guide. Can an agent restore a snapshot in this mode without the destructive flag?</question>
|
||||
<answer>no</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Use status on a fresh unjoined configuration, then inspect the setup guide. What CLI command can enroll the device interactively before MCP uses its hub connection?</question>
|
||||
<answer>devbox setup</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Discover tools and inspect the schema for conflict inspection. Which tool lists conflict copies without deleting them?</question>
|
||||
<answer>devbox_conflicts</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Compare the restore and deployment tool descriptions without calling either. Which one applies a snapshot and pins the local mount?</question>
|
||||
<answer>devbox_deploy</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Use status on an enrolled fixture and compare it with the tool-discovery list. Which history tool can inspect the snapshots for one of its mounted shares without changing files?</question>
|
||||
<answer>devbox_history</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Inspect the agent launch configuration and the Tailscale setup guide. Does devbox mcp require a remote HTTP MCP listener or communicate through local stdio?</question>
|
||||
<answer>local stdio</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Compare the Tailscale client setup and MCP launch configuration. Which command starts the embedded Tailscale hub rather than the local agent MCP server?</question>
|
||||
<answer>devbox-hub serve --tailscale</answer>
|
||||
</qa_pair>
|
||||
</evaluation>
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
# v2.2.0 — Built-in MCP + Tailscale
|
||||
|
||||
Your working tree on every machine. Structured sync tools for your coding agent.
|
||||
|
||||
## Tailscale is built into the hub
|
||||
|
||||
```bash
|
||||
devbox-hub serve --data ./hub-data --tailscale --tailscale-hostname devbox-hub
|
||||
```
|
||||
|
||||
The hub joins your tailnet itself, without a separate Tailscale installation,
|
||||
root privileges, TUN device, router port forwarding, or reverse proxy. Enroll
|
||||
using the first-run login URL or a securely supplied `TS_AUTHKEY`; preserve
|
||||
`<data>/tailscale` across upgrades. Clients use the regular Tailscale app and
|
||||
the private endpoint printed by the hub. Devbox join tokens remain required.
|
||||
|
||||

|
||||
|
||||
## MCP is built into the client
|
||||
|
||||
```bash
|
||||
codex mcp add devbox -- /absolute/path/to/devbox mcp
|
||||
```
|
||||
|
||||
The new `devbox mcp` command serves tools over local stdio. Inspect status,
|
||||
diagnostics, conflicts, history, and memberships by default. Enable pause,
|
||||
resume, publish, and mount with `--allow-writes`. Restore, deploy, and unmount
|
||||
also require `--allow-destructive`. The server uses the enrolled device's
|
||||
existing config and connection, including access to Tailscale hubs.
|
||||
|
||||

|
||||
|
||||
See the [MCP guide](https://github.com/shoemoney/devbox/blob/main/docs/MCP.md)
|
||||
for configuration examples and tool details. No separate MCP package or Node
|
||||
runtime is needed. Start the sync daemon separately with `devbox start`.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
curl -fsSL https://git.shoemoney.ai/shoemoney/devbox-dist/releases/download/latest/install.sh | sh
|
||||
```
|
||||
|
||||
For the hub too, download the installer and run `sh install.sh --hub --no-service`.
|
||||
Both binaries ship for Linux amd64/arm64/arm, macOS amd64/arm64, and Windows amd64.
|
||||
`SHA256SUMS` covers the 12 binaries and both installers. Public downloads are
|
||||
available on GitHub and Forgejo. Source builds require Go 1.27.4+.
|
||||
|
||||
## Validation
|
||||
|
||||
Passed vet, 189 race tests across 19 packages, and real SDK stdio tests for
|
||||
initialization, discovery, calls, permissions, authenticated hub operations,
|
||||
input validation, cancellation, timeouts, and output caps. The embedded Tailscale
|
||||
regression uses real nodes against an isolated local control/DERP plane; no
|
||||
production-tailnet enrollment is claimed.
|
||||
|
||||

|
||||
|
||||
The dashboard capture uses a local demo hub and real sync daemons. It is not a
|
||||
production-tailnet capture.
|
||||
|
|
@ -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.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
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.
|
||||
|
|
@ -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.
|
||||
1
examples/mcpd/.gitignore
vendored
1
examples/mcpd/.gitignore
vendored
|
|
@ -1 +0,0 @@
|
|||
runtime.local.toml
|
||||
|
|
@ -1,183 +0,0 @@
|
|||
# Mozilla AI mcpd + devbox
|
||||
|
||||
Use Mozilla AI's **Go daemon** to manage the Go `devbox mcp` server. This
|
||||
example was exercised with **mcpd v0.7.0** and **devbox v2.2.0** on Linux.
|
||||
It discovered all five inspection tools and called status and authenticated
|
||||
snapshot history through mcpd's HTTP API.
|
||||
|
||||
## How the pieces fit
|
||||
|
||||
- `devbox mcp` implements the sync tools and speaks MCP over stdio.
|
||||
- [mcpd](https://github.com/mozilla-ai/mcpd) starts and manages the server and
|
||||
exposes its tools through REST endpoints.
|
||||
- Mozilla's [Go plugin SDK](https://github.com/mozilla-ai/mcpd-plugins-sdk-go)
|
||||
extends mcpd with middleware: authentication, observability, rate limiting,
|
||||
and request/response processing.
|
||||
- The community [PHP plugin SDK](https://github.com/shoemoney/mcpd-plugins-sdk-php)
|
||||
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.**
|
||||
|
||||
## 1. Install the prerequisites
|
||||
|
||||
Install mcpd from [Mozilla's releases](https://github.com/mozilla-ai/mcpd/releases)
|
||||
and Docker. Download a **Linux** devbox binary matching Docker's architecture
|
||||
from the [devbox release](https://github.com/shoemoney/devbox/releases/tag/v2.2.0),
|
||||
check its SHA256SUMS entry, and make it executable. A macOS/Windows binary
|
||||
cannot run inside the Linux Alpine container.
|
||||
|
||||
mcpd v0.7.0 supports `uvx`, `npx`, and Docker runtimes; it has no general native
|
||||
binary launcher. This example uses its Docker runtime, which starts the released
|
||||
static Go binary in Alpine. No Node.js or Python server runtime is involved.
|
||||
|
||||
## 2. Select the devbox configuration
|
||||
|
||||
Copy `runtime.example.toml` to an untracked local runtime file and replace:
|
||||
|
||||
- `binary`: absolute path to the Linux devbox binary.
|
||||
- `config`: absolute path to the **devbox config directory itself**, such as
|
||||
`/home/alice/.config/devbox`, containing the existing enrollment.
|
||||
- `certificates`: the Linux host's CA certificate directory, usually
|
||||
`/etc/ssl/certs`.
|
||||
|
||||
For a fresh configuration, create the config directory first. Enroll using the
|
||||
normal CLI before expecting authenticated tools to work. The config directory
|
||||
and binary are mounted read-only. No tokens belong in `mcpd.toml` or the example
|
||||
runtime file. Keep the actual enrollment directory private.
|
||||
|
||||
mcpd's Docker runtime uses host networking in v0.7.0. On Linux this gives the
|
||||
client the host's network routes, including its regular Tailscale connection.
|
||||
The hub can continue using embedded Tailscale. This is a Linux host example;
|
||||
Docker Desktop networking, certificate paths, and filesystem mounts need their
|
||||
own configuration on macOS and Windows.
|
||||
|
||||
## 3. Start mcpd
|
||||
|
||||
Run from this directory, substituting your local runtime file:
|
||||
|
||||
```bash
|
||||
mcpd daemon \
|
||||
--config-file ./mcpd.toml \
|
||||
--runtime-file /absolute/path/to/runtime.local.toml \
|
||||
--addr 127.0.0.1:8090 \
|
||||
--timeout-mcp-request 150s
|
||||
```
|
||||
|
||||
The daemon request timeout is longer than devbox's default two-minute command
|
||||
timeout. The tool allowlist is explicit: status, doctor, conflicts, history, and
|
||||
memberships. Only inspection tools are enabled.
|
||||
|
||||
## 4. Call devbox through the daemon
|
||||
|
||||
```bash
|
||||
curl -fsS http://127.0.0.1:8090/api/v1/servers/devbox/tools
|
||||
|
||||
curl -fsS -X POST \
|
||||
http://127.0.0.1:8090/api/v1/servers/devbox/tools/devbox_status \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{}'
|
||||
|
||||
curl -fsS -X POST \
|
||||
http://127.0.0.1:8090/api/v1/servers/devbox/tools/devbox_history \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"share":"projects","limit":5}'
|
||||
```
|
||||
|
||||
mcpd v0.7.0 returns devbox's JSON text result as a JSON string. Decode the HTTP
|
||||
JSON, then decode that string to get devbox's result envelope. `status.php`
|
||||
handles this and also accepts an already-decoded envelope:
|
||||
|
||||
```bash
|
||||
MCPD_URL=http://127.0.0.1:8090 php status.php
|
||||
```
|
||||
|
||||
**These are REST endpoints.** They are not Streamable HTTP MCP endpoints. For
|
||||
an MCP-only agent, use Mozilla's
|
||||
[mcpd-proxy](https://github.com/mozilla-ai/mcpd-client#manual-integration) adapter,
|
||||
or connect the agent directly to `devbox mcp` as in the
|
||||
[built-in MCP guide](../../docs/MCP.md). The proxy configuration is documented
|
||||
upstream; the REST path above is the integration exercised here.
|
||||
|
||||
## Workspace paths and tool visibility
|
||||
|
||||
If the enrolled configuration contains mounts, add matching workspace volumes
|
||||
to both files before using conflict/doctor tools. Each workspace must appear
|
||||
inside the container at the **same absolute path** used by `daemon.toml`.
|
||||
For example, if the real mount lives at `/home/alice/Projects`:
|
||||
|
||||
```toml
|
||||
# Add to mcpd.toml
|
||||
[servers.volumes.workspace]
|
||||
path = "/home/alice/Projects:ro"
|
||||
required = true
|
||||
```
|
||||
|
||||
```toml
|
||||
# Add under [servers.devbox.volumes] in the local runtime file
|
||||
workspace = "/home/alice/Projects"
|
||||
```
|
||||
|
||||
Without workspace mounts, status/history/membership queries can still use the
|
||||
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.
|
||||
|
|
@ -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
|
||||
|
|
@ -1,13 +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
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
# Local execution context: replace these paths before starting mcpd.
|
||||
# The binary must be a Linux binary matching Docker's architecture.
|
||||
[servers.devbox]
|
||||
args = ["/opt/devbox/devbox", "mcp"]
|
||||
[servers.devbox.env]
|
||||
XDG_CONFIG_HOME = "/config"
|
||||
[servers.devbox.volumes]
|
||||
binary = "/absolute/path/to/linux/devbox"
|
||||
config = "/absolute/path/to/config-base/devbox"
|
||||
certificates = "/etc/ssl/certs"
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
// Plain HTTP example for mcpd's REST API. Plugin SDKs are a separate layer.
|
||||
$base = rtrim(getenv('MCPD_URL') ?: 'http://127.0.0.1:8090', '/');
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'POST',
|
||||
'header' => "Content-Type: application/json\r\nAccept: application/json\r\n",
|
||||
'content' => '{}',
|
||||
'timeout' => 10,
|
||||
'ignore_errors' => true,
|
||||
],
|
||||
]);
|
||||
|
||||
try {
|
||||
$response = file_get_contents($base . '/api/v1/servers/devbox/tools/devbox_status', false, $context);
|
||||
if ($response === false) {
|
||||
throw new RuntimeException('Could not reach mcpd; check MCPD_URL and daemon status.');
|
||||
}
|
||||
$headers = $http_response_header ?? [];
|
||||
$status = 0;
|
||||
foreach ($headers as $header) {
|
||||
if (preg_match('~^HTTP/\S+\s+(\d{3})~', $header, $matches)) {
|
||||
$status = (int) $matches[1];
|
||||
}
|
||||
}
|
||||
if ($status < 200 || $status >= 300) {
|
||||
throw new RuntimeException('mcpd returned HTTP ' . $status . ': ' . $response);
|
||||
}
|
||||
$result = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
|
||||
// mcpd v0.7.0 returns a JSON string containing devbox's text envelope.
|
||||
if (is_string($result)) {
|
||||
$result = json_decode($result, true, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
if (!is_array($result) || !array_key_exists('exit_code', $result)) {
|
||||
throw new RuntimeException('Unexpected mcpd response shape.');
|
||||
}
|
||||
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), PHP_EOL;
|
||||
exit($result['exit_code'] === 0 && empty($result['error']) ? 0 : 1);
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, $error->getMessage() . PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
9
go.mod
9
go.mod
|
|
@ -6,13 +6,9 @@ require (
|
|||
github.com/BurntSushi/toml v1.6.0
|
||||
github.com/fsnotify/fsnotify v1.10.1
|
||||
github.com/jotfs/fastcdc-go v0.2.0
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0
|
||||
github.com/mozilla-ai/mcpd-plugins-sdk-go v0.1.1
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/zeebo/blake3 v0.2.4
|
||||
golang.org/x/time v0.16.0
|
||||
google.golang.org/grpc v1.83.2
|
||||
google.golang.org/protobuf v1.36.12
|
||||
modernc.org/sqlite v1.53.0
|
||||
tailscale.com v1.106.1
|
||||
)
|
||||
|
|
@ -61,7 +57,6 @@ require (
|
|||
github.com/google/btree v1.1.3 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/go-tpm v0.9.8 // indirect
|
||||
github.com/google/jsonschema-go v0.4.3 // indirect
|
||||
github.com/google/nftables v0.3.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/hdevalence/ed25519consensus v0.2.0 // indirect
|
||||
|
|
@ -87,8 +82,6 @@ require (
|
|||
github.com/pkg/sftp v1.13.11 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/safchain/ethtool v0.7.0 // indirect
|
||||
github.com/segmentio/asm v1.1.3 // indirect
|
||||
github.com/segmentio/encoding v0.5.4 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d // indirect
|
||||
github.com/tailscale/gliderssh v0.3.4-0.20261026144310-31f7cf365d3a // indirect
|
||||
|
|
@ -104,7 +97,6 @@ require (
|
|||
github.com/u-root/uio v0.0.0-20240224005618-d2acac8f3701 // indirect
|
||||
github.com/vishvananda/netns v0.0.5 // indirect
|
||||
github.com/x448/float16 v0.8.4 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
go4.org/mem v0.0.0-20240501181205-ae6ca9944745 // indirect
|
||||
go4.org/netipx v0.0.0-20260823151212-3075585bcbeb // indirect
|
||||
golang.org/x/crypto v0.59.0 // indirect
|
||||
|
|
@ -120,7 +112,6 @@ require (
|
|||
golang.org/x/tools v0.52.0 // indirect
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect
|
||||
golang.zx2c4.com/wireguard/windows v1.0.1 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
|
||||
gvisor.dev/gvisor v0.0.0-20261117040555-0303b2605d5e // indirect
|
||||
honnef.co/go/tools v0.8.1 // indirect
|
||||
modernc.org/libc v1.73.4 // indirect
|
||||
|
|
|
|||
40
go.sum
40
go.sum
|
|
@ -50,8 +50,6 @@ github.com/bradfitz/reco v0.0.0-20260929154613-b883fbd17e3f h1:jdXGSp5Ge5/kzikux
|
|||
github.com/bradfitz/reco v0.0.0-20260929154613-b883fbd17e3f/go.mod h1:oiCPXxBoDKSkb/RGEZwAZk8y/fwDlQ1vYlBbNRxPysw=
|
||||
github.com/bramvdbogaerde/go-scp v1.6.1 h1:HE63uMkmMEB62JwqdRrVqRTBi7H/L/rkTp8TPC7uffY=
|
||||
github.com/bramvdbogaerde/go-scp v1.6.1/go.mod h1:Lqx75BOgAvQoeBbPuPN/MfU3jf5tlfZVmUqpPbSZkZc=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cilium/ebpf v0.22.0 h1:v2ktp0roffpMOj2MMf3idtCQZOsAoC4BJbAJN+ke2bY=
|
||||
github.com/cilium/ebpf v0.22.0/go.mod h1:CDzZbe2hC5JjlDC+CY3KFCzlYwN4gbxppYM+Z10bQt4=
|
||||
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
|
||||
|
|
@ -91,10 +89,6 @@ github.com/github/fakeca v0.1.0 h1:Km/MVOFvclqxPM9dZBC4+QE564nU4gz4iZ0D9pMw28I=
|
|||
github.com/github/fakeca v0.1.0/go.mod h1:+bormgoGMMuamOscx7N91aOuUST7wdaJ2rNjeohylyo=
|
||||
github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 h1:UADEEmDKgfXbtnGJZ97beY5XLo9ZechG1nlU4KnRrkE=
|
||||
github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg=
|
||||
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
|
||||
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/go4org/hashtriemap v0.0.0-20260925222741-44e5305f85d9 h1:J8S+Ms89nvHX1F9Ma2m3KhdTl41ZhbFKMyAJqvDA+iE=
|
||||
|
|
@ -103,12 +97,8 @@ github.com/go4org/plan9netshell v0.0.0-20250324183649-788daa080737 h1:cf60tHxREO
|
|||
github.com/go4org/plan9netshell v0.0.0-20250324183649-788daa080737/go.mod h1:MIS0jDzbU/vuM9MC4YnBITCv+RYuTRq8dJzmCrFsK9g=
|
||||
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
|
||||
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
|
||||
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=
|
||||
github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
|
|
@ -117,8 +107,6 @@ github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
|
|||
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
|
||||
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba h1:qJEJcuLzH5KDR0gKc0zcktin6KSAwL7+jWKBYceddTc=
|
||||
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
|
||||
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
|
||||
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/nftables v0.3.0 h1:bkyZ0cbpVeMHXOrtlFc8ISmfVqq5gPJukoYieyVmITg=
|
||||
github.com/google/nftables v0.3.0/go.mod h1:BCp9FsrbF1Fn/Yu6CLUc9GGZFw/+hsxfluNXXmxBfRM=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
|
|
@ -174,10 +162,6 @@ github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
|
|||
github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
|
||||
github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc=
|
||||
github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
|
||||
github.com/mozilla-ai/mcpd-plugins-sdk-go v0.1.1 h1:I8zb8vn/PNxiuYZV3f5dBOx12M/IhxzpgHm+c5KNQJI=
|
||||
github.com/mozilla-ai/mcpd-plugins-sdk-go v0.1.1/go.mod h1:mcdV4ULyHd8wVtBeDgZj4M9Ouis+dGEJPc7DM8BHUQE=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
|
|
@ -201,10 +185,6 @@ github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52Z
|
|||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/safchain/ethtool v0.7.0 h1:rlJzfDetsVvT61uz8x1YIcFn12akMfuPulHtZjtb7Is=
|
||||
github.com/safchain/ethtool v0.7.0/go.mod h1:MenQKEjXdfkjD3mp2QdCk8B/hwvkrlOTm/FD4gTpFxQ=
|
||||
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
|
||||
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
|
||||
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
|
||||
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
|
||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
|
|
@ -249,26 +229,12 @@ github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zd
|
|||
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY=
|
||||
github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
|
||||
github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI=
|
||||
github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE=
|
||||
github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo=
|
||||
github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU=
|
||||
go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ=
|
||||
go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M=
|
||||
go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
|
||||
go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag=
|
||||
go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
|
|
@ -317,12 +283,6 @@ golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 h1:cqHQ3AycTHvM2R7
|
|||
golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw=
|
||||
golang.zx2c4.com/wireguard/windows v1.0.1 h1:eOxiDVbywPC+ZQqvdCK7x+ZwWXKbYv50TtH8ysFIbw8=
|
||||
golang.zx2c4.com/wireguard/windows v1.0.1/go.mod h1:+fbT3FFdX4zzYDLwJh5+HPEcNN/3HyNdzhNSVsQM+zs=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
|
||||
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
|
||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@
|
|||
param(
|
||||
[string]$BinDir = $env:DEVBOX_BIN_DIR,
|
||||
[switch]$Hub,
|
||||
[switch]$McpdPlugin,
|
||||
[switch]$Service,
|
||||
[switch]$NoService,
|
||||
[string]$ReleaseUrl = $(if ($env:DEVBOX_RELEASE_URL) { $env:DEVBOX_RELEASE_URL } else { "https://git.shoemoney.ai/shoemoney/devbox-dist/releases/download/latest" })
|
||||
|
|
@ -74,7 +73,6 @@ function Install-One($name) {
|
|||
}
|
||||
Install-One "devbox"
|
||||
if ($Hub) { Install-One "devbox-hub" }
|
||||
if ($McpdPlugin) { Install-One "devbox-mcpd-plugin" }
|
||||
|
||||
# Add to the user PATH (persisted) if missing.
|
||||
$userPath = [Environment]::GetEnvironmentVariable("Path", "User")
|
||||
|
|
|
|||
11
install.sh
11
install.sh
|
|
@ -9,12 +9,10 @@
|
|||
# DEVBOX_BIN_DIR=~/.local/bin DEVBOX_SERVICE=1 sh install.sh # non-interactive
|
||||
#
|
||||
# Knobs (flags or env): --bin-dir DIR (DEVBOX_BIN_DIR) · --hub (DEVBOX_INSTALL_HUB=1)
|
||||
# · --mcpd-plugin (DEVBOX_INSTALL_MCPD_PLUGIN=1)
|
||||
# · --service / --no-service (DEVBOX_SERVICE=1/0) · --release-url URL (DEVBOX_RELEASE_URL).
|
||||
set -eu
|
||||
|
||||
INSTALL_HUB="${DEVBOX_INSTALL_HUB:-0}"
|
||||
INSTALL_MCPD_PLUGIN="${DEVBOX_INSTALL_MCPD_PLUGIN:-0}"
|
||||
BIN_DIR="${DEVBOX_BIN_DIR:-}"
|
||||
WANT_SERVICE="${DEVBOX_SERVICE:-ask}"
|
||||
RELEASE_URL="${DEVBOX_RELEASE_URL:-https://git.shoemoney.ai/shoemoney/devbox-dist/releases/download/latest}"
|
||||
|
|
@ -22,7 +20,6 @@ RELEASE_URL="${DEVBOX_RELEASE_URL:-https://git.shoemoney.ai/shoemoney/devbox-dis
|
|||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--hub) INSTALL_HUB=1 ;;
|
||||
--mcpd-plugin) INSTALL_MCPD_PLUGIN=1 ;;
|
||||
--bin-dir) BIN_DIR="$2"; shift ;;
|
||||
--service) WANT_SERVICE=1 ;;
|
||||
--no-service) WANT_SERVICE=0 ;;
|
||||
|
|
@ -100,10 +97,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
|
||||
|
|
@ -123,7 +117,6 @@ install_one() {
|
|||
say "🚚 installing to $BIN_DIR"
|
||||
install_one devbox
|
||||
[ "$INSTALL_HUB" = 1 ] && install_one devbox-hub
|
||||
[ "$INSTALL_MCPD_PLUGIN" = 1 ] && install_one devbox-mcpd-plugin
|
||||
|
||||
case ":$PATH:" in *":$BIN_DIR:"*) ;; *)
|
||||
say "⚠️ $BIN_DIR is not on your PATH. Add to your shell rc:"
|
||||
|
|
@ -223,5 +216,3 @@ fi
|
|||
say ""
|
||||
say "🎉 done. Next: run 'devbox setup' to join a hub and start syncing."
|
||||
[ "$INSTALL_HUB" = 1 ] && say " hub: 'devbox-hub serve --dashboard' — or use the Dockerfile for a NAS (see README)."
|
||||
|
||||
exit 0
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1324,7 +1324,7 @@
|
|||
===================================================================== */
|
||||
function applyState(s){
|
||||
const prev={...state.totals};
|
||||
if(s.hub){ state.hub=s.hub; $("m-version").textContent=(s.hub.version||"—").replace(/^v/, "");
|
||||
if(s.hub){ state.hub=s.hub; $("m-version").textContent=s.hub.version||"—";
|
||||
state.baseUptime=s.hub.uptime_s||0; state.baseUptimeAt=Date.now(); }
|
||||
if(s.totals){ state.totals={...state.totals, ...s.totals}; }
|
||||
if(Array.isArray(s.devices)){ state.devices=s.devices;
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -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
21
plan.md
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Cross-compile all three devbox binaries for all release targets.
|
||||
# Cross-compile both devbox binaries for all release targets.
|
||||
# Override version: VERSION=v1.2.3 ./scripts/build-release.sh
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
|
@ -9,7 +9,7 @@ cd "$(dirname "$0")/.."
|
|||
VERSION="${VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo dev)}"
|
||||
LDFLAGS="-s -w -X main.version=$VERSION"
|
||||
|
||||
BINS=(devbox devbox-hub devbox-mcpd-plugin)
|
||||
BINS=(devbox devbox-hub)
|
||||
# linux/arm64 = Raspberry Pi 5/4/3 (64-bit) + arm Macs' Linux VMs; linux/arm = 32-bit Pi OS.
|
||||
TARGETS=(linux/amd64 linux/arm64 linux/arm darwin/arm64 darwin/amd64 windows/amd64)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,18 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# Run the real SDK stdio integration checks against a native packaged binary.
|
||||
# Requires the repository's Go toolchain; never uses the caller's devbox config.
|
||||
set -euo pipefail
|
||||
if [[ $# -ne 1 ]]; then
|
||||
echo "usage: $0 /absolute/path/to/devbox" >&2
|
||||
exit 2
|
||||
fi
|
||||
case "$1" in
|
||||
/*) ;;
|
||||
*) echo "binary path must be absolute" >&2; exit 2 ;;
|
||||
esac
|
||||
if [[ ! -x "$1" ]]; then
|
||||
echo "binary is not executable: $1" >&2
|
||||
exit 2
|
||||
fi
|
||||
cd "$(dirname "$0")/.."
|
||||
DEVBOX_MCP_TEST_BINARY="$1" go test ./cmd/devbox -run '^TestMCPStdio$' -count=1 -v
|
||||
|
|
@ -32,7 +32,7 @@ BUILD_VERSION=$(sed -n '2p' dist/BUILD_INFO)
|
|||
STAGE=dist/release-assets
|
||||
rm -rf "$STAGE"
|
||||
mkdir -p "$STAGE"
|
||||
for bin in devbox devbox-hub devbox-mcpd-plugin; do
|
||||
for bin in devbox devbox-hub; do
|
||||
for target in linux/amd64 linux/arm64 linux/arm darwin/arm64 darwin/amd64 windows/amd64; do
|
||||
os="${target%/*}"; arch="${target#*/}"; ext=""
|
||||
[ "$os" != windows ] || ext=.exe
|
||||
|
|
@ -40,7 +40,7 @@ for bin in devbox devbox-hub devbox-mcpd-plugin; do
|
|||
done
|
||||
done
|
||||
cp install.sh install.ps1 "$STAGE/"
|
||||
(cd "$STAGE" && hashes devbox_* devbox-hub_* devbox-mcpd-plugin_* install.sh install.ps1 > SHA256SUMS)
|
||||
(cd "$STAGE" && hashes devbox_* devbox-hub_* install.sh install.ps1 > SHA256SUMS)
|
||||
|
||||
# Read errors fail the release; a 404 alone means the tag has no release.
|
||||
old_json=$(mktemp)
|
||||
|
|
@ -57,12 +57,7 @@ if [ -n "$old_id" ] && [ "$TAG" != latest ]; then
|
|||
fi
|
||||
upload_tag="$TAG"
|
||||
[ "$TAG" != latest ] || upload_tag="latest-staging-${COMMIT:0:12}-$(date +%s)"
|
||||
body=$(printf 'devbox %s — built from source `%s`, binary version `%s`.\n\nBuilt-in Tailscale in the hub: `devbox-hub serve --data ./hub-data --tailscale`. No separate Tailscale installation is required on the hub. Authenticate using the logged login URL or TS_AUTHKEY; identity persists under <data>/tailscale. Clients use the regular Tailscale app. Existing HTTP/HTTPS deployments remain supported.\n\nInstall: `curl -fsSL https://git.shoemoney.ai/%s/releases/download/%s/install.sh -o install.sh && sh install.sh --release-url https://git.shoemoney.ai/%s/releases/download/%s`\n\nAssets include 18 binaries, both installers, and SHA256SUMS. Building from source requires Go 1.27.4+.' "$TAG" "$COMMIT" "$BUILD_VERSION" "$REPO" "$TAG" "$REPO" "$TAG")
|
||||
if [ -f "docs/releases/$BUILD_VERSION.md" ]; then
|
||||
body="$(cat "docs/releases/$BUILD_VERSION.md")
|
||||
|
||||
Built from source \`$COMMIT\`; binary version \`$BUILD_VERSION\`."
|
||||
fi
|
||||
body=$(printf 'devbox %s — built from source `%s`, binary version `%s`.\n\nBuilt-in Tailscale in the hub: `devbox-hub serve --data ./hub-data --tailscale`. No separate Tailscale installation is required on the hub. Authenticate using the logged login URL or TS_AUTHKEY; identity persists under <data>/tailscale. Clients use the regular Tailscale app. Existing HTTP/HTTPS deployments remain supported.\n\nInstall: `curl -fsSL https://git.shoemoney.ai/%s/releases/download/%s/install.sh -o install.sh && sh install.sh --release-url https://git.shoemoney.ai/%s/releases/download/%s`\n\nAssets include 12 binaries, both installers, and SHA256SUMS. Building from source requires Go 1.27.4+.' "$TAG" "$COMMIT" "$BUILD_VERSION" "$REPO" "$TAG" "$REPO" "$TAG")
|
||||
rel_id=$(api -X POST "$API/repos/$REPO/releases" -H 'Content-Type: application/json' \
|
||||
-d "$(python3 -c 'import json,sys;print(json.dumps(dict(tag_name=sys.argv[1],target_commitish=sys.argv[2],name=sys.argv[3],body=sys.argv[4],draft=True,prerelease=False)))' "$upload_tag" "$DIST_BRANCH" "$TAG" "$body")" \
|
||||
| python3 -c 'import json,sys;print(json.load(sys.stdin)["id"])')
|
||||
|
|
@ -74,15 +69,9 @@ for f in "$STAGE"/*; do
|
|||
curl -fsSL "${auth[@]}" -X POST "$API/repos/$REPO/releases/$rel_id/assets?name=$name" -F "attachment=@$f" >/dev/null
|
||||
done
|
||||
count=$(api "$API/repos/$REPO/releases/$rel_id" | python3 -c 'import json,sys;print(len(json.load(sys.stdin)["assets"]))')
|
||||
[ "$count" = 21 ] || { echo "Expected 21 assets, got $count; leaving draft unpublished" >&2; exit 1; }
|
||||
[ "$count" = 15 ] || { echo "Expected 15 assets, got $count; leaving draft unpublished" >&2; exit 1; }
|
||||
# Keep the existing moving release until the replacement is fully uploaded.
|
||||
if [ -n "$old_id" ]; then api -X DELETE "$API/repos/$REPO/releases/$old_id" >/dev/null; fi
|
||||
# Forgejo cannot publish a renamed draft onto an existing tag (it returns 500).
|
||||
# Remove only the moving distribution tag after uploads; version tags stay fixed.
|
||||
if [ "$TAG" = latest ]; then
|
||||
code=$(curl -sSL "${auth[@]}" -X DELETE -o "$old_json" -w '%{http_code}' "$API/repos/$REPO/tags/latest")
|
||||
case "$code" in 200|204|404) ;; *) echo "Moving tag removal failed: HTTP $code" >&2; exit 1;; esac
|
||||
fi
|
||||
api -X PATCH "$API/repos/$REPO/releases/$rel_id" -H 'Content-Type: application/json' \
|
||||
-d "$(python3 -c 'import json,sys;print(json.dumps(dict(tag_name=sys.argv[1],draft=False)))' "$TAG")" >/dev/null
|
||||
echo "https://git.shoemoney.ai/$REPO/releases/tag/$TAG"
|
||||
|
|
|
|||
|
|
@ -1,80 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Installer smoke using explicit temporary binaries; never installs services."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
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:
|
||||
root = Path(tmp)
|
||||
env = dict(os.environ)
|
||||
env.pop('DEVBOX_INSTALL_HUB', None)
|
||||
env.pop('DEVBOX_INSTALL_MCPD_PLUGIN', None)
|
||||
for binary in ('devbox', 'devbox-hub', 'devbox-mcpd-plugin'):
|
||||
source = root / binary
|
||||
source.write_text(f'#!/bin/sh\necho {binary}-fixture\n')
|
||||
source.chmod(0o755)
|
||||
env[binary.upper().replace('-', '_') + '_BIN'] = str(source)
|
||||
dest = root / 'installed'
|
||||
args = ['sh', str(INSTALLER), '--no-service', '--bin-dir', str(dest)]
|
||||
if mode == 'flag':
|
||||
args += ['--mcpd-plugin', '--hub']
|
||||
if mode == 'env':
|
||||
env['DEVBOX_INSTALL_MCPD_PLUGIN'] = '1'
|
||||
result = subprocess.run(args, env=env, capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
expected = {'devbox'}
|
||||
if mode != 'default':
|
||||
expected.add('devbox-mcpd-plugin')
|
||||
if mode == 'flag':
|
||||
expected.add('devbox-hub')
|
||||
self.assertEqual({p.name for p in dest.iterdir()}, expected)
|
||||
for binary in expected:
|
||||
self.assertEqual(subprocess.check_output([str(dest / binary)], text=True), f'{binary}-fixture\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
|
@ -9,7 +9,6 @@ import shutil
|
|||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import textwrap
|
||||
import unittest
|
||||
|
||||
SCRIPT = Path(__file__).with_name('release.sh').resolve()
|
||||
|
|
@ -30,14 +29,14 @@ class ReleaseTest(unittest.TestCase):
|
|||
dist = self.root / 'dist'
|
||||
dist.mkdir()
|
||||
lines = []
|
||||
for binary in ('devbox', 'devbox-hub', 'devbox-mcpd-plugin'):
|
||||
for binary in ('devbox', 'devbox-hub'):
|
||||
for target in ('linux_amd64', 'linux_arm64', 'linux_arm', 'darwin_arm64', 'darwin_amd64', 'windows_amd64.exe'):
|
||||
name = f'{binary}_v2.3.0_{target}'
|
||||
name = f'{binary}_v2.1.0_{target}'
|
||||
data = name.encode()
|
||||
(dist / name).write_bytes(data)
|
||||
lines.append(f'{hashlib.sha256(data).hexdigest()} {name}\n')
|
||||
(dist / 'SHA256SUMS').write_text(''.join(lines))
|
||||
(dist / 'BUILD_INFO').write_text(f'{self.sha}\nv2.3.0\n')
|
||||
(dist / 'BUILD_INFO').write_text(f'{self.sha}\nv2.1.0\n')
|
||||
self.calls = []
|
||||
self.assets = []
|
||||
self.existing = False
|
||||
|
|
@ -84,11 +83,10 @@ class ReleaseTest(unittest.TestCase):
|
|||
env=env, capture_output=True, text=True, timeout=20)
|
||||
|
||||
def test_complete_versioned_release(self):
|
||||
result = self.run_release('v2.3.0')
|
||||
result = self.run_release('v2.1.0')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(len(self.assets), 21)
|
||||
self.assertEqual(len(self.assets), 15)
|
||||
self.assertIn('devbox-hub_windows_amd64.exe', self.assets)
|
||||
self.assertIn('devbox-mcpd-plugin_windows_amd64.exe', self.assets)
|
||||
self.assertIn('install.ps1', self.assets)
|
||||
creates = [json.loads(body) for method, _, body in self.calls if method == 'POST' and body.startswith(b'{')]
|
||||
self.assertTrue(creates[0]['draft'])
|
||||
|
|
@ -98,24 +96,7 @@ class ReleaseTest(unittest.TestCase):
|
|||
for line in (stage / 'SHA256SUMS').read_text().splitlines():
|
||||
digest, name = line.split()
|
||||
self.assertEqual(hashlib.sha256((stage / name).read_bytes()).hexdigest(), digest)
|
||||
self.assertEqual(len((stage / 'SHA256SUMS').read_text().splitlines()), 20)
|
||||
|
||||
def test_github_asset_rename_and_checksums(self):
|
||||
workflow = SCRIPT.parents[1] / '.github/workflows/release.yml'
|
||||
text = workflow.read_text()
|
||||
shell = text.split(' - name: De-version asset names (match install.sh)\n run: |\n', 1)[1].split(' - name: Publish GitHub release', 1)[0]
|
||||
result = subprocess.run(['bash', '-euc', textwrap.dedent(shell)], cwd=self.root,
|
||||
capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
dist = self.root / 'dist'
|
||||
checksums = (dist / 'SHA256SUMS').read_text().splitlines()
|
||||
self.assertEqual(len(checksums), 20)
|
||||
self.assertIn('devbox-mcpd-plugin_windows_amd64.exe', {line.split()[1] for line in checksums})
|
||||
for line in checksums:
|
||||
digest, name = line.split()
|
||||
self.assertEqual(hashlib.sha256((dist / name).read_bytes()).hexdigest(), digest)
|
||||
# BUILD_INFO is provenance only and is deliberately excluded from upload.
|
||||
self.assertIn('dist/devbox-mcpd-plugin_*', text.split('gh release create', 1)[1])
|
||||
self.assertEqual(len((stage / 'SHA256SUMS').read_text().splitlines()), 14)
|
||||
|
||||
def test_latest_keeps_old_release_until_uploads_complete(self):
|
||||
self.existing = True
|
||||
|
|
@ -124,7 +105,6 @@ class ReleaseTest(unittest.TestCase):
|
|||
methods = [method for method, _, _ in self.calls]
|
||||
delete_index = methods.index('DELETE')
|
||||
self.assertGreater(delete_index, max(i for i, (_, path, _) in enumerate(self.calls) if '/assets?' in path))
|
||||
self.assertTrue(any(method == 'DELETE' and path.endswith('/tags/latest') for method, path, _ in self.calls))
|
||||
self.assertEqual(json.loads(self.calls[-1][2])['tag_name'], 'latest')
|
||||
|
||||
def test_upload_failure_keeps_existing_latest(self):
|
||||
|
|
@ -135,32 +115,22 @@ class ReleaseTest(unittest.TestCase):
|
|||
|
||||
def test_existing_version_is_immutable(self):
|
||||
self.existing = True
|
||||
self.assertNotEqual(self.run_release('v2.3.0').returncode, 0)
|
||||
self.assertNotEqual(self.run_release('v2.1.0').returncode, 0)
|
||||
self.assertEqual([method for method, _, _ in self.calls], ['GET'])
|
||||
|
||||
def test_checked_in_release_notes_are_published(self):
|
||||
notes = self.root / 'docs/releases'
|
||||
notes.mkdir(parents=True)
|
||||
(notes / 'v2.3.0.md').write_text('# Custom release\n\n\n')
|
||||
result = self.run_release('v2.3.0')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
create = next(json.loads(body) for method, _, body in self.calls if method == 'POST' and body.startswith(b'{'))
|
||||
self.assertIn('![Screenshot]', create['body'])
|
||||
self.assertIn(self.sha, create['body'])
|
||||
|
||||
def test_lookup_failure_does_not_publish(self):
|
||||
self.lookup_code = 403
|
||||
self.assertNotEqual(self.run_release('latest').returncode, 0)
|
||||
self.assertEqual([method for method, _, _ in self.calls], ['GET'])
|
||||
|
||||
def test_corrupt_artifact_never_reaches_api(self):
|
||||
(self.root / 'dist/devbox_v2.3.0_linux_amd64').write_bytes(b'corrupt')
|
||||
self.assertNotEqual(self.run_release('v2.3.0').returncode, 0)
|
||||
(self.root / 'dist/devbox_v2.1.0_linux_amd64').write_bytes(b'corrupt')
|
||||
self.assertNotEqual(self.run_release('v2.1.0').returncode, 0)
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_wrong_source_never_reaches_api(self):
|
||||
(self.root / 'dist/BUILD_INFO').write_text('wrong\nv2.3.0\n')
|
||||
self.assertNotEqual(self.run_release('v2.3.0').returncode, 0)
|
||||
(self.root / 'dist/BUILD_INFO').write_text('wrong\nv2.1.0\n')
|
||||
self.assertNotEqual(self.run_release('v2.1.0').returncode, 0)
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue