fix(worktree): bind publication to dispatch grants

Worktree RPC used to accept repository coordinates from the sandbox. It now accepts only an opaque per-dispatch grant, and the daemon derives the repository path and branch from grant-owned state.

Repository worktree paths also move from an ambiguous flattened key to encoded owner/repo components. Origin-matched legacy clones migrate safely; mismatched legacy paths are preserved.
This commit is contained in:
sam committed 2026-08-22 22:06:54 +10:00
1 parent 7df2ae3626
commit dbb6550ab3
19 files changed
+494 -175

No files matched your search

+87 -3
View File
@@ -19,6 +19,7 @@ package worktree
import (
"context"
"encoding/base64"
"errors"
"fmt"
"os"
@@ -62,7 +63,17 @@ type Manager struct {
// Dir is the worktree path for a task.
func (m *Manager) Dir(owner, repo string, issue int) string {
return filepath.Join(m.WorkDir, owner+"-"+repo, fmt.Sprintf("issue-%d", issue))
ownerKey := base64.RawURLEncoding.EncodeToString([]byte(owner))
repoKey := base64.RawURLEncoding.EncodeToString([]byte(repo))
return filepath.Join(m.WorkDir, ownerKey, repoKey, fmt.Sprintf("issue-%d", issue))
}
// ValidCoordinates reports whether owner, repo, and issue can safely identify
// a task worktree without being interpreted as filesystem navigation.
func ValidCoordinates(owner, repo string, issue int) bool {
return owner != "" && repo != "" && issue > 0 &&
filepath.Base(owner) == owner && filepath.Base(repo) == repo &&
owner != "." && owner != ".." && repo != "." && repo != ".."
}
// auth builds the HTTP credential for clone, fetch and push.
@@ -100,6 +111,9 @@ func (m *Manager) Prepare(
issue int,
title, body, labels string,
) (dir, branch string, err error) {
if !ValidCoordinates(owner, repo, issue) {
return "", "", fmt.Errorf("invalid worktree coordinates")
}
dir = m.Dir(owner, repo, issue)
branch = archieBranch(issue, title, body, labels)
@@ -109,6 +123,14 @@ func (m *Manager) Prepare(
}
return dir, branch, nil
}
if migrated, migrateErr := m.migrateLegacy(owner, repo, issue, dir); migrateErr != nil {
return "", "", migrateErr
} else if migrated {
if err := m.refresh(ctx, dir, base, branch); err != nil {
return "", "", err
}
return dir, branch, nil
}
if err := os.RemoveAll(dir); err != nil {
return "", "", fmt.Errorf("clear stale worktree: %w", err)
@@ -146,6 +168,56 @@ func (m *Manager) Prepare(
return dir, branch, nil
}
func (m *Manager) legacyDir(owner, repo string, issue int) string {
return filepath.Join(m.WorkDir, owner+"-"+repo, fmt.Sprintf("issue-%d", issue))
}
// migrateLegacy preserves worktrees created before repository coordinates
// were encoded as separate path components. The old flattened key was
// ambiguous, so migration is allowed only when the clone's origin exactly
// matches the requested repository; an uncertain directory is left untouched.
func (m *Manager) migrateLegacy(owner, repo string, issue int, dir string) (bool, error) {
legacy := m.legacyDir(owner, repo, issue)
if _, err := os.Stat(filepath.Join(legacy, preparedSentinel)); err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, fmt.Errorf("inspect legacy worktree: %w", err)
}
if !repositoryUsesURL(legacy, m.cloneURL(owner, repo)) {
return false, nil
}
if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil {
return false, fmt.Errorf("create migrated worktree parent: %w", err)
}
if err := os.Rename(legacy, dir); err != nil {
return false, fmt.Errorf("migrate legacy worktree: %w", err)
}
_ = os.Remove(filepath.Dir(legacy))
return true, nil
}
func repositoryUsesURL(dir, want string) bool {
r, err := git.PlainOpen(dir)
if err != nil {
return false
}
cfg, err := r.Config()
if err != nil {
return false
}
remote, ok := cfg.Remotes[git.DefaultRemoteName]
if !ok {
return false
}
for _, got := range remote.URLs {
if got == want {
return true
}
}
return false
}
// refresh brings an already-prepared worktree back in line with the
// remote: fetch, move onto the task branch, and reset it to the base.
func (m *Manager) refresh(ctx context.Context, dir, base, branch string) error {
@@ -406,7 +478,20 @@ func (m *Manager) ChangedFiles(ctx context.Context, dir, base string) ([]string,
// Cleanup removes a task's worktree (merged/rejected); parked worktrees
// are kept for post-mortems.
func (m *Manager) Cleanup(owner, repo string, issue int) error {
return os.RemoveAll(m.Dir(owner, repo, issue))
if !ValidCoordinates(owner, repo, issue) {
return fmt.Errorf("invalid worktree coordinates")
}
if err := os.RemoveAll(m.Dir(owner, repo, issue)); err != nil {
return err
}
legacy := m.legacyDir(owner, repo, issue)
if repositoryUsesURL(legacy, m.cloneURL(owner, repo)) {
if err := os.RemoveAll(legacy); err != nil {
return err
}
_ = os.Remove(filepath.Dir(legacy))
}
return nil
}
func remoteBase(base string) string {
@@ -457,7 +542,6 @@ func archieBranch(issue int, title, body, labels string) string {
// branchPrefix derives a conventional-commit prefix from the issue
// labels, then falls back to "feat". Maps: bug→fix, feature→feat,
// enhancement→feat, docs→docs, chore→chore, test→test.
// FIXME - Unused parameters title and body where they should be used. - just a missing implementation by the looks of it.
func branchPrefix(title, body, labels string) string {
for l := range strings.SplitSeq(labels, ",") {
switch strings.TrimSpace(strings.ToLower(l)) {
+106
View File
@@ -541,6 +541,112 @@ func TestCleanupRemovesWorktree(t *testing.T) {
}
}
func TestDirDistinguishesRepositoryTuples(t *testing.T) {
m := &Manager{WorkDir: t.TempDir()}
first := m.Dir("a-b", "c", 1)
second := m.Dir("a", "b-c", 1)
if first == second {
t.Fatalf("distinct repositories share worktree path %q", first)
}
}
func TestPrepareMigratesMatchingLegacyWorktree(t *testing.T) {
ctx := context.Background()
host := newLocalRemote(t, "acme", "todo")
m := newManager(t, host)
legacy := filepath.Join(m.WorkDir, "acme-todo", "issue-44")
if _, err := git.PlainCloneContext(ctx, legacy, &git.CloneOptions{
URL: m.cloneURL("acme", "todo"),
ReferenceName: plumbing.NewBranchReferenceName(testBase),
}); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(legacy, preparedSentinel), nil, 0o644); err != nil {
t.Fatal(err)
}
marker := filepath.Join(legacy, "legacy-marker")
if err := os.WriteFile(marker, nil, 0o600); err != nil {
t.Fatal(err)
}
dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 44, "feat: migrate", "", "feature")
if err != nil {
t.Fatal(err)
}
if dir != m.Dir("acme", "todo", 44) {
t.Fatalf("Prepare dir = %q, want %q", dir, m.Dir("acme", "todo", 44))
}
if _, err := os.Stat(filepath.Join(dir, "legacy-marker")); err != nil {
t.Fatalf("legacy worktree was not migrated: %v", err)
}
if _, err := os.Stat(legacy); !os.IsNotExist(err) {
t.Fatalf("legacy path still exists after migration: %v", err)
}
}
func TestPreparePreservesMismatchedLegacyWorktree(t *testing.T) {
ctx := context.Background()
desiredHost := newLocalRemote(t, "acme", "todo")
otherHost := newLocalRemote(t, "other", "widget")
m := newManager(t, desiredHost)
legacy := filepath.Join(m.WorkDir, "acme-todo", "issue-45")
if _, err := git.PlainCloneContext(ctx, legacy, &git.CloneOptions{
URL: filepath.Join(otherHost, "other", "widget.git"),
ReferenceName: plumbing.NewBranchReferenceName(testBase),
}); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(legacy, preparedSentinel), nil, 0o644); err != nil {
t.Fatal(err)
}
marker := filepath.Join(legacy, "keep")
if err := os.WriteFile(marker, nil, 0o600); err != nil {
t.Fatal(err)
}
if _, _, err := m.Prepare(ctx, "acme", "todo", testBase, 45, "feat: safe migration", "", "feature"); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(marker); err != nil {
t.Fatalf("mismatched legacy worktree was altered: %v", err)
}
}
func TestCleanupHandlesLegacyWorktreesByOrigin(t *testing.T) {
for _, tc := range []struct {
name string
matching bool
wantExists bool
}{
{name: "matching origin is removed", matching: true},
{name: "mismatched origin is preserved", wantExists: true},
} {
t.Run(tc.name, func(t *testing.T) {
desiredHost := newLocalRemote(t, "acme", "todo")
m := newManager(t, desiredHost)
cloneURL := m.cloneURL("acme", "todo")
if !tc.matching {
otherHost := newLocalRemote(t, "other", "widget")
cloneURL = filepath.Join(otherHost, "other", "widget.git")
}
legacy := filepath.Join(m.WorkDir, "acme-todo", "issue-46")
if _, err := git.PlainClone(legacy, &git.CloneOptions{URL: cloneURL}); err != nil {
t.Fatal(err)
}
if err := m.Cleanup("acme", "todo", 46); err != nil {
t.Fatal(err)
}
_, err := os.Stat(legacy)
if tc.wantExists && err != nil {
t.Fatalf("legacy worktree should remain: %v", err)
}
if !tc.wantExists && !os.IsNotExist(err) {
t.Fatalf("legacy worktree still exists: %v", err)
}
})
}
}
// The prepared sentinel must never reach a commit. It previously lived in
// the working tree, hidden by .git/info/exclude -- which git honours and
// go-git does not, so it was committed and pushed onto every task branch.