carlos / platform Public

devbox mode (#474): link names and the durable link store

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 9739e9b2a4b085c0cfe13979518f9413ae271f5e parent 5deb672
4 files changed, +441 −0
  • internal/devbox/links.go +193 −0
  • internal/devbox/links_test.go +129 −0
  • internal/devbox/names.go +61 −0
  • internal/devbox/names_test.go +58 −0

Intent

Human

<task-notification> <task-id>ac566491bcc233331</task-id> <tool-use-id>toolu_01PmUJdqN2krYS2UvB59TAPp</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/9b370a04-693c-4bda-b2eb-9a4b08f7626d/tasks/ac566491bcc233331.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3: ServeDevbox front door" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE. Not pushed. Commits: 3a8a59f6 (ServeDevbox) and 5deb672a (your three rulings). Tests: `go test ./internal/edge -run 'TestDevbox|TestWildcard'` passes. That includes all 7 TestDevbox* tests, with the new TestDevboxRefusesExtraParents covering both variables. gofmt and vet are clean. Rulings applied: 1. The `go w.run()` line now has a comment saying the loop outlives ServeDevbox and that this is fine because the process exits. 2. ServeDevbox returns an error naming `PLATFORM_APPS_DOMAIN` or `CARLOS_STEERING_ZONE_ID` when either is set. The check runs before anything is built or bound. 3. This needed only a small seam: the unexported `serveDevbox(ctx, cfg, bound func(net.Addr))`, which ServeDevbox calls with nil. The end-to-end test now binds 127.0.0.1:0 and gets the real address from it, so the port-reuse race is gone. Concerns: the new test was written together with the change, so it has no separate RED run. The TLS handshake-error log line for refused names is still not rate-limited. Report (fix section appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/devbox-mode/.superpowers/sdd/2026-10-30-devbox-mode/task-3-report.md</result> <usage><subagent_tokens>122136</subagent_tokens><tool_uses>32</tool_uses><duration_ms>417948</duration_ms></usage> </task-notification>

Attributed to this commit: 13.3 g CO₂e (1,612,103 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-devbox-mode, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/devbox/links.go b/internal/devbox/links.go
new file mode 100644
index 000000000..5fa64aa84
--- /dev/null
+++ b/internal/devbox/links.go
@@ -0,0 +1,193 @@
+package devbox
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "sort"
+ "sync"
+ "time"
+)
+
+// Kind says what a link serves.
+type Kind string
+
+const (
+ KindLive Kind = "live"
+ KindFolder Kind = "folder"
+)
+
+// Link is the record of one published name.
+type Link struct {
+ Name string `json:"name"`
+ OwnerName string `json:"ownerName"`
+ OwnerUID uint32 `json:"ownerUID"`
+ Kind Kind `json:"kind"`
+ Port int `json:"port,omitempty"` // live only
+ Snapshot string `json:"snapshot,omitempty"` // folder only: current snapshot dir name
+ Created time.Time `json:"created"`
+ Updated time.Time `json:"updated"`
+}
+
+// Links is the durable record of who owns each name. One process writes the
+// file; the mutex serialises that process's callers.
+type Links struct {
+ path string
+ mu sync.Mutex
+ links map[string]Link
+}
+
+type linksFile struct {
+ Links []Link `json:"links"`
+}
+
+// OpenLinks loads the store at path. A missing file is an empty store and is
+// created with mode 0600. A file that does not parse is an error and is left
+// untouched.
+func OpenLinks(path string) (*Links, error) {
+ l := &Links{path: path, links: map[string]Link{}}
+ data, err := os.ReadFile(path)
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ if err := l.write(l.links); err != nil {
+ return nil, err
+ }
+ return l, nil
+ case err != nil:
+ return nil, err
+ }
+ var f linksFile
+ if err := json.Unmarshal(data, &f); err != nil {
+ return nil, fmt.Errorf("devbox: read %s: %w", path, err)
+ }
+ for _, k := range f.Links {
+ l.links[k.Name] = k
+ }
+ return l, nil
+}
+
+// Get returns the link called name.
+func (l *Links) Get(name string) (Link, bool) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ k, ok := l.links[name]
+ return k, ok
+}
+
+// Put stores link, replacing any link of the same name, and writes the file
+// durably before returning. If the write fails the store is unchanged.
+func (l *Links) Put(link Link) error {
+ if err := ValidName(link.Name); err != nil {
+ return err
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ next := l.copyLocked()
+ next[link.Name] = link
+ if err := l.write(next); err != nil {
+ return err
+ }
+ l.links = next
+ return nil
+}
+
+// Delete removes the link called name. A name that is not there is not an error.
+func (l *Links) Delete(name string) error {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ if _, ok := l.links[name]; !ok {
+ return nil
+ }
+ next := l.copyLocked()
+ delete(next, name)
+ if err := l.write(next); err != nil {
+ return err
+ }
+ l.links = next
+ return nil
+}
+
+// All returns every link, sorted by name.
+func (l *Links) All() []Link {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ out := make([]Link, 0, len(l.links))
+ for _, k := range l.links {
+ out = append(out, k)
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
+ return out
+}
+
+func (l *Links) copyLocked() map[string]Link {
+ next := make(map[string]Link, len(l.links)+1)
+ for n, k := range l.links {
+ next[n] = k
+ }
+ return next
+}
+
+// write replaces the file with links: temp file in the same directory, fsync,
+// rename, then fsync the directory so the rename itself survives a crash.
+func (l *Links) write(links map[string]Link) error {
+ f := linksFile{Links: make([]Link, 0, len(links))}
+ for _, k := range links {
+ f.Links = append(f.Links, k)
+ }
+ sort.Slice(f.Links, func(i, j int) bool { return f.Links[i].Name < f.Links[j].Name })
+ data, err := json.MarshalIndent(f, "", " ")
+ if err != nil {
+ return err
+ }
+ data = append(data, '\n')
+
+ dir := filepath.Dir(l.path)
+ tmp, err := os.CreateTemp(dir, filepath.Base(l.path)+".tmp-*") // created 0600
+ if err != nil {
+ return err
+ }
+ tmpName := tmp.Name()
+ fail := func(err error) error {
+ tmp.Close()
+ os.Remove(tmpName)
+ return err
+ }
+ if err := tmp.Chmod(0o600); err != nil && runtime.GOOS != "windows" {
+ return fail(err)
+ }
+ if _, err := tmp.Write(data); err != nil {
+ return fail(err)
+ }
+ if err := tmp.Sync(); err != nil {
+ return fail(err)
+ }
+ if err := tmp.Close(); err != nil {
+ os.Remove(tmpName)
+ return err
+ }
+ if err := os.Rename(tmpName, l.path); err != nil {
+ os.Remove(tmpName)
+ return err
+ }
+ return syncDir(dir)
+}
+
+// syncDir fsyncs a directory. Windows cannot fsync a directory handle, so the
+// error is tolerated there.
+func syncDir(dir string) error {
+ d, err := os.Open(dir)
+ if err != nil {
+ if runtime.GOOS == "windows" {
+ return nil
+ }
+ return err
+ }
+ defer d.Close()
+ if err := d.Sync(); err != nil && runtime.GOOS != "windows" {
+ return err
+ }
+ return nil
+}
diff --git a/internal/devbox/links_test.go b/internal/devbox/links_test.go
new file mode 100644
index 000000000..8636cfb07
--- /dev/null
+++ b/internal/devbox/links_test.go
@@ -0,0 +1,129 @@
+package devbox
+
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+ "time"
+)
+
+func sample(name string) Link {
+ t := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)
+ return Link{Name: name, OwnerName: "paul", OwnerUID: 1001, Kind: "live", Port: 3000, Created: t, Updated: t.Add(time.Minute)}
+}
+
+func TestLinksRoundTrip(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "links.json")
+ l, err := OpenLinks(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fi, err := os.Stat(path); err != nil || fi.Mode().Perm() != 0o600 {
+ t.Fatalf("new store: %v, %v", fi, err)
+ }
+ want := sample("shop")
+ if err := l.Put(want); err != nil {
+ t.Fatal(err)
+ }
+ folder := Link{Name: "docs", OwnerName: "ann", OwnerUID: 1002, Kind: "folder", Snapshot: "s-1", Created: want.Created, Updated: want.Updated}
+ if err := l.Put(folder); err != nil {
+ t.Fatal(err)
+ }
+ fi, err := os.Stat(path)
+ if err != nil || fi.Mode().Perm() != 0o600 {
+ t.Fatalf("mode after put: %v, %v", fi, err)
+ }
+ l2, err := OpenLinks(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, w := range []Link{want, folder} {
+ got, ok := l2.Get(w.Name)
+ if !ok || !reflect.DeepEqual(got, w) {
+ t.Errorf("Get(%q) = %+v, %v; want %+v", w.Name, got, ok, w)
+ }
+ }
+ if _, ok := l2.Get("nope"); ok {
+ t.Error("Get of missing name found something")
+ }
+ // Put replaces.
+ want.Port = 4000
+ if err := l2.Put(want); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := l2.Get("shop"); got.Port != 4000 {
+ t.Errorf("replace: port %d", got.Port)
+ }
+ // No temp files left behind.
+ ents, _ := os.ReadDir(filepath.Dir(path))
+ if len(ents) != 1 {
+ t.Errorf("directory has %d entries, want 1", len(ents))
+ }
+}
+
+func TestLinksPutRejectsInvalidName(t *testing.T) {
+ l, err := OpenLinks(filepath.Join(t.TempDir(), "links.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := l.Put(sample("A.b")); err == nil {
+ t.Error("Put accepted an invalid name")
+ }
+}
+
+func TestLinksAllSorted(t *testing.T) {
+ l, err := OpenLinks(filepath.Join(t.TempDir(), "links.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, n := range []string{"zed", "alpha", "mid"} {
+ if err := l.Put(sample(n)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var got []string
+ for _, k := range l.All() {
+ got = append(got, k.Name)
+ }
+ if !reflect.DeepEqual(got, []string{"alpha", "mid", "zed"}) {
+ t.Errorf("All = %v", got)
+ }
+}
+
+func TestLinksDeleteMissingIsNoError(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "links.json")
+ l, err := OpenLinks(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := l.Delete("ghost"); err != nil {
+ t.Fatal(err)
+ }
+ if err := l.Put(sample("shop")); err != nil {
+ t.Fatal(err)
+ }
+ if err := l.Delete("shop"); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := l.Get("shop"); ok {
+ t.Error("deleted link still present")
+ }
+ l2, _ := OpenLinks(path)
+ if len(l2.All()) != 0 {
+ t.Error("delete not persisted")
+ }
+}
+
+func TestLinksCorruptFileIsError(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "links.json")
+ if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := OpenLinks(path); err == nil {
+ t.Fatal("corrupt file opened")
+ }
+ if b, _ := os.ReadFile(path); string(b) != "{not json" {
+ t.Error("corrupt file was modified")
+ }
+}
diff --git a/internal/devbox/names.go b/internal/devbox/names.go
new file mode 100644
index 000000000..a81ffa73e
--- /dev/null
+++ b/internal/devbox/names.go
@@ -0,0 +1,61 @@
+// Package devbox holds the pieces of devbox mode that do not touch the
+// network: link names and the durable record of who owns each one.
+package devbox
+
+import (
+ "errors"
+ "strings"
+)
+
+// maxLabel is the longest a single DNS label may be.
+const maxLabel = 63
+
+var (
+ // ErrInvalidName means a name is not a single valid DNS label.
+ ErrInvalidName = errors.New("devbox: invalid name")
+ // ErrNoNameInBranch means a branch has no letters or digits to name a link.
+ ErrNoNameInBranch = errors.New("devbox: no name in branch")
+)
+
+// ValidName reports whether name is a usable link name: one lower-case DNS
+// label of 1 to 63 characters, letters, digits and hyphens, with no hyphen at
+// either end. The wildcard certificate covers exactly one label, so dots are
+// refused. Explicit names are checked as typed, never folded.
+func ValidName(name string) error {
+ if len(name) == 0 || len(name) > maxLabel {
+ return ErrInvalidName
+ }
+ if name[0] == '-' || name[len(name)-1] == '-' {
+ return ErrInvalidName
+ }
+ for i := 0; i < len(name); i++ {
+ c := name[i]
+ if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
+ return ErrInvalidName
+ }
+ }
+ return nil
+}
+
+// NameFromBranch turns a git branch into a link name. It lower-cases the
+// branch, turns each run of characters outside [a-z0-9] into one hyphen, trims
+// hyphens from both ends, cuts to 63 characters and trims again. It returns
+// ErrNoNameInBranch when nothing is left.
+func NameFromBranch(branch string) (string, error) {
+ var b strings.Builder
+ for _, r := range strings.ToLower(branch) {
+ if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' {
+ b.WriteRune(r)
+ } else if s := b.String(); s != "" && s[len(s)-1] != '-' {
+ b.WriteByte('-')
+ }
+ }
+ name := strings.Trim(b.String(), "-")
+ if len(name) > maxLabel {
+ name = strings.TrimRight(name[:maxLabel], "-")
+ }
+ if name == "" {
+ return "", ErrNoNameInBranch
+ }
+ return name, nil
+}
diff --git a/internal/devbox/names_test.go b/internal/devbox/names_test.go
new file mode 100644
index 000000000..4ba7ee092
--- /dev/null
+++ b/internal/devbox/names_test.go
@@ -0,0 +1,58 @@
+package devbox
+
+import (
+ "errors"
+ "strings"
+ "testing"
+)
+
+func TestValidName(t *testing.T) {
+ for _, ok := range []string{"shop", "a", "x-1", strings.Repeat("a", 63)} {
+ if err := ValidName(ok); err != nil {
+ t.Errorf("ValidName(%q) = %v, want nil", ok, err)
+ }
+ }
+ for _, bad := range []string{"", "-a", "a-", "A", "a_b", "a.b", strings.Repeat("a", 64)} {
+ err := ValidName(bad)
+ if !errors.Is(err, ErrInvalidName) {
+ t.Errorf("ValidName(%q) = %v, want ErrInvalidName", bad, err)
+ }
+ }
+}
+
+func TestNameFromBranch(t *testing.T) {
+ long := strings.Repeat("a", 62) + "/" + strings.Repeat("b", 17) // 80 chars
+ cases := []struct{ in, want string }{
+ {"Feature/Widget_GTM", "feature-widget-gtm"},
+ {"a///b___c...d", "a-b-c-d"},
+ {"--main--", "main"},
+ {long, strings.Repeat("a", 62)},
+ {strings.Repeat("a", 62) + "-" + strings.Repeat("b", 17), strings.Repeat("a", 62)},
+ }
+ for _, c := range cases {
+ got, err := NameFromBranch(c.in)
+ if err != nil || got != c.want {
+ t.Errorf("NameFromBranch(%q) = %q, %v; want %q", c.in, got, err, c.want)
+ }
+ if err == nil && ValidName(got) != nil {
+ t.Errorf("NameFromBranch(%q) = %q is not a valid name", c.in, got)
+ }
+ }
+ // 80 characters, cut lands on a hyphen: no trailing hyphen.
+ b := strings.Repeat("a", 63) + "-" + strings.Repeat("b", 16)
+ if len(b) != 80 {
+ t.Fatalf("setup: len %d", len(b))
+ }
+ if got, err := NameFromBranch(b); err != nil || got != strings.Repeat("a", 63) {
+ t.Errorf("long branch = %q, %v", got, err)
+ }
+ b = strings.Repeat("a", 62) + "-" + strings.Repeat("b", 17)
+ if got, err := NameFromBranch(b); err != nil || len(got) != 62 || strings.HasSuffix(got, "-") {
+ t.Errorf("hyphen at cut = %q, %v", got, err)
+ }
+ for _, none := range []string{"///", "", "___", "éü"} {
+ if _, err := NameFromBranch(none); !errors.Is(err, ErrNoNameInBranch) {
+ t.Errorf("NameFromBranch(%q) err = %v, want ErrNoNameInBranch", none, err)
+ }
+ }
+}