Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6921 fix(daemon): honor the Co-authored-by toggle in existing checkouts (#7868)

Bohan Jiang11bd18a50794
diff --git a/server/internal/daemon/coauthor_enabled_test.go b/server/internal/daemon/coauthor_enabled_test.go
index 175858f77d..18f9849e09 100644
--- a/server/internal/daemon/coauthor_enabled_test.go
+++ b/server/internal/daemon/coauthor_enabled_test.go
@@ -3,11 +3,18 @@ package daemon
import (
"context"
"encoding/json"
+ "fmt"
"log/slog"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
+ "sync"
"sync/atomic"
"testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/daemon/repocache"
)
// workspaceCoAuthoredByEnabled gates the prepare-commit-msg hook installed in
@@ -125,3 +132,487 @@ func TestSyncWorkspacesSkipsReposRefreshOnExistingWorkspace(t *testing.T) {
t.Fatal("workspace sync unexpectedly replaced cached settings")
}
}
+
+// coAuthoredByStateCache is a repoCacheBackend that records what the daemon
+// publishes for installed prepare-commit-msg hooks to read.
+type coAuthoredByStateCache struct {
+ mu sync.Mutex
+ writes []bool
+ reconciles []bool
+ checkouts []reconciledCheckout
+}
+
+// reconciledCheckout records one isolated checkout the daemon asked to bring in
+// line with the workspace setting.
+type reconciledCheckout struct {
+ path string
+ enabled bool
+}
+
+func (c *coAuthoredByStateCache) Lookup(string, string) string { return "" }
+func (c *coAuthoredByStateCache) BarePath(string, string) string { return "" }
+func (c *coAuthoredByStateCache) Sync(string, []repocache.RepoInfo) error {
+ return nil
+}
+func (c *coAuthoredByStateCache) WithRepoLock(_ string, fn func() error) error { return fn() }
+func (c *coAuthoredByStateCache) CreateWorktree(repocache.WorktreeParams) (*repocache.WorktreeResult, error) {
+ return nil, nil
+}
+
+func (c *coAuthoredByStateCache) WriteCoAuthoredByState(_ string, enabled bool) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.writes = append(c.writes, enabled)
+ return nil
+}
+
+func (c *coAuthoredByStateCache) ReconcileCoAuthoredByHooks(_ string, enabled bool) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.reconciles = append(c.reconciles, enabled)
+ return nil
+}
+
+func (c *coAuthoredByStateCache) ReconcileCoAuthoredByHookInCheckout(checkoutPath, _ string, enabled bool) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.checkouts = append(c.checkouts, reconciledCheckout{path: checkoutPath, enabled: enabled})
+ return nil
+}
+
+func (c *coAuthoredByStateCache) reconciledCheckouts() []reconciledCheckout {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return append([]reconciledCheckout(nil), c.checkouts...)
+}
+
+func (c *coAuthoredByStateCache) lastReconcile(t *testing.T) bool {
+ t.Helper()
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if len(c.reconciles) == 0 {
+ t.Fatal("hooks were never reconciled")
+ }
+ return c.reconciles[len(c.reconciles)-1]
+}
+
+func (c *coAuthoredByStateCache) lastWrite(t *testing.T) bool {
+ t.Helper()
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if len(c.writes) == 0 {
+ t.Fatal("no Co-authored-by state was published")
+ }
+ return c.writes[len(c.writes)-1]
+}
+
+// newCoAuthoredByStateDaemon returns a daemon tracking one workspace whose
+// settings the fake server serves from settings, plus the cache recording
+// published state.
+func newCoAuthoredByStateDaemon(t *testing.T, workspaceID string, settings *string) (*Daemon, *coAuthoredByStateCache) {
+ t.Helper()
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/daemon/workspaces/"+workspaceID+"/repos" {
+ http.NotFound(w, r)
+ return
+ }
+ resp := WorkspaceReposResponse{WorkspaceID: workspaceID, ReposVersion: "v1"}
+ if settings != nil {
+ resp.Settings = json.RawMessage(*settings)
+ }
+ json.NewEncoder(w).Encode(resp)
+ }))
+ t.Cleanup(srv.Close)
+
+ cache := &coAuthoredByStateCache{}
+ d := &Daemon{
+ cfg: Config{CLIVersion: "v1.0.0"},
+ client: NewClient(srv.URL),
+ repoCache: cache,
+ workspaces: map[string]*workspaceState{workspaceID: newWorkspaceState(workspaceID, nil, "", nil, nil)},
+ logger: slog.Default(),
+ }
+ return d, cache
+}
+
+// A settings refresh must publish the current verdict to the repo cache, not
+// just to the daemon's in-memory copy: prepare-commit-msg hooks installed by
+// earlier checkouts read that file on every commit, and it is the only way a
+// toggle-off reaches a checkout that already exists (MUL-6921).
+func TestRefreshWorkspaceReposPublishesCoAuthoredByState(t *testing.T) {
+ t.Parallel()
+
+ const workspaceID = "ws-1"
+ settings := `{"co_authored_by_enabled":false}`
+ d, cache := newCoAuthoredByStateDaemon(t, workspaceID, &settings)
+
+ if _, err := d.refreshWorkspaceRepos(context.Background(), workspaceID); err != nil {
+ t.Fatalf("refreshWorkspaceRepos failed: %v", err)
+ }
+ if cache.lastWrite(t) {
+ t.Error("published state = enabled, want disabled after the toggle was turned off")
+ }
+
+ settings = `{"co_authored_by_enabled":true}`
+ if _, err := d.refreshWorkspaceRepos(context.Background(), workspaceID); err != nil {
+ t.Fatalf("refreshWorkspaceRepos failed: %v", err)
+ }
+ if !cache.lastWrite(t) {
+ t.Error("published state = disabled, want enabled after the toggle was turned back on")
+ }
+}
+
+// The server's workspaces-changed hint is the only signal a running daemon
+// gets for a settings edit — the periodic sync makes no repos/settings request
+// for a workspace it already tracks. refreshTrackedWorkspaceSettings is what
+// turns that hint into a new verdict without waiting for the next checkout.
+func TestRefreshTrackedWorkspaceSettingsAppliesToggle(t *testing.T) {
+ t.Parallel()
+
+ const workspaceID = "ws-1"
+ settings := `{"co_authored_by_enabled":false}`
+ d, cache := newCoAuthoredByStateDaemon(t, workspaceID, &settings)
+
+ if !d.workspaceCoAuthoredByEnabled(workspaceID) {
+ t.Fatal("precondition: workspace should start with the default (enabled) verdict")
+ }
+
+ d.refreshTrackedWorkspaceSettings(context.Background())
+
+ if d.workspaceCoAuthoredByEnabled(workspaceID) {
+ t.Error("daemon still reports the trailer as enabled after the workspace disabled it")
+ }
+ if cache.lastWrite(t) {
+ t.Error("published state = enabled, want disabled")
+ }
+}
+
+// A daemon that starts (or restarts) after the toggle was flipped learns the
+// new value from its register response, and nothing else would ever carry it
+// to the hooks already on disk. The workspace sync republishes it locally —
+// without touching the repos endpoint, which the sibling test above pins.
+func TestSyncWorkspacesPublishesCoAuthoredByState(t *testing.T) {
+ t.Parallel()
+
+ const workspaceID = "ws-1"
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/daemon/workspaces" {
+ http.NotFound(w, r)
+ return
+ }
+ json.NewEncoder(w).Encode([]WorkspaceInfo{{ID: workspaceID, Name: "ws"}})
+ }))
+ t.Cleanup(srv.Close)
+
+ cache := &coAuthoredByStateCache{}
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.Default(),
+ repoCache: cache,
+ workspaces: make(map[string]*workspaceState),
+ runtimeIndex: make(map[string]Runtime),
+ runtimeSet: newRuntimeSetWatcher(),
+ }
+ d.workspaces[workspaceID] = newWorkspaceState(
+ workspaceID,
+ []string{"rt-1"},
+ "v1",
+ nil,
+ json.RawMessage(`{"co_authored_by_enabled":false}`),
+ )
+
+ if err := d.syncWorkspacesFromAPI(context.Background(), false); err != nil {
+ t.Fatalf("syncWorkspacesFromAPI: %v", err)
+ }
+
+ if cache.lastWrite(t) {
+ t.Error("published state = enabled, want disabled for a workspace whose settings say so")
+ }
+}
+
+// Publishing has to carry hooks written by earlier daemon releases too: they
+// read no state file, so a new value alone never reaches them.
+func TestPersistCoAuthoredByStateReconcilesHooks(t *testing.T) {
+ t.Parallel()
+
+ const workspaceID = "ws-1"
+ settings := `{"co_authored_by_enabled":false}`
+ d, cache := newCoAuthoredByStateDaemon(t, workspaceID, &settings)
+ d.workspaces[workspaceID] = newWorkspaceState(workspaceID, nil, "", nil, json.RawMessage(settings))
+
+ d.persistCoAuthoredByState(workspaceID)
+
+ if cache.lastWrite(t) {
+ t.Error("published state = enabled, want disabled")
+ }
+ if cache.lastReconcile(t) {
+ t.Error("reconciled hooks as enabled, want disabled")
+ }
+}
+
+// A publisher that started before a settings update must not overwrite the
+// value that update produced. The lock is what rules that out: the verdict is
+// read INSIDE it, so a publisher parked before its read is holding the lock and
+// no fresher publisher can slip past and be overwritten afterwards.
+//
+// The ordering is driven by channels, not sleeps: A parks inside its verdict
+// read, B is started afterwards, and B reaching the cache while A is parked is
+// itself the failure — it can only happen if A read before taking the lock.
+func TestPersistCoAuthoredByStateReadsVerdictUnderPublishLock(t *testing.T) {
+ t.Parallel()
+
+ const workspaceID = "ws-1"
+ d, cache := newCoAuthoredByStateDaemon(t, workspaceID, nil)
+ ws := newWorkspaceState(workspaceID, nil, "", nil, json.RawMessage(`{"co_authored_by_enabled":true}`))
+ d.workspaces[workspaceID] = ws
+
+ parked := make(chan struct{})
+ resume := make(chan struct{})
+ staleDone := make(chan struct{})
+ go func() {
+ defer close(staleDone)
+ d.publishCoAuthoredByState(workspaceID, func(id string) bool {
+ enabled := d.workspaceCoAuthoredByEnabled(id)
+ close(parked)
+ <-resume
+ return enabled
+ })
+ }()
+
+ // A has read "enabled" and is parked. Under the contract it holds the
+ // publish lock while parked.
+ <-parked
+
+ d.mu.Lock()
+ ws.settings = json.RawMessage(`{"co_authored_by_enabled":false}`)
+ d.mu.Unlock()
+
+ freshDone := make(chan struct{})
+ go func() {
+ defer close(freshDone)
+ d.persistCoAuthoredByState(workspaceID)
+ }()
+
+ // The fresh publisher must not be able to publish while A is parked. This
+ // wait is the assertion: it is expected to expire, and any write arriving
+ // inside it means the verdict was read outside the lock.
+ select {
+ case <-freshDone:
+ close(resume)
+ <-staleDone
+ t.Fatal("a publisher completed while another was parked mid-publish: the verdict is being read outside the lock")
+ case <-time.After(300 * time.Millisecond):
+ }
+
+ close(resume)
+ <-staleDone
+ select {
+ case <-freshDone:
+ case <-time.After(5 * time.Second):
+ t.Fatal("publication never completed")
+ }
+
+ if cache.lastWrite(t) {
+ t.Error("last published state = enabled: a stale publisher overwrote the value the settings update produced")
+ }
+}
+
+// A settings edit made while the daemon's websocket was down produces a hint
+// nobody receives. Reconnect reconcile must re-read settings for tracked
+// workspaces, or the daemon keeps republishing the stale verdict and existing
+// checkouts stay wrong until their next checkout.
+func TestWorkspaceSyncLoop_ReconcilePicksUpSettingsChangedWhileOffline(t *testing.T) {
+ t.Parallel()
+
+ const workspaceID = "ws-1"
+ var repoCalls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/daemon/workspaces":
+ json.NewEncoder(w).Encode([]WorkspaceInfo{{ID: workspaceID, Name: "ws"}})
+ case "/api/daemon/workspaces/" + workspaceID + "/repos":
+ repoCalls.Add(1)
+ // What the server has believed since the user flipped the toggle
+ // during the websocket outage.
+ json.NewEncoder(w).Encode(WorkspaceReposResponse{
+ WorkspaceID: workspaceID,
+ ReposVersion: "v2",
+ Settings: json.RawMessage(`{"co_authored_by_enabled":false}`),
+ })
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(srv.Close)
+
+ cache := &coAuthoredByStateCache{}
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.Default(),
+ repoCache: cache,
+ workspaces: make(map[string]*workspaceState),
+ runtimeIndex: make(map[string]Runtime),
+ runtimeSet: newRuntimeSetWatcher(),
+ reconcile: newReconcileBroadcaster(),
+ }
+ // Cached from before the outage: a live runtime ID keeps the sync from
+ // short-circuiting into a re-register.
+ d.workspaces[workspaceID] = newWorkspaceState(
+ workspaceID,
+ []string{"rt-1"},
+ "v1",
+ nil,
+ json.RawMessage(`{"co_authored_by_enabled":true}`),
+ )
+
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ loopDone := make(chan struct{})
+ go func() {
+ defer close(loopDone)
+ d.workspaceSyncLoop(ctx)
+ }()
+
+ d.reconcile.broadcast()
+
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) && d.workspaceCoAuthoredByEnabled(workspaceID) {
+ time.Sleep(10 * time.Millisecond)
+ }
+ cancel()
+ <-loopDone
+
+ if repoCalls.Load() == 0 {
+ t.Fatal("reconnect reconcile never re-read workspace settings")
+ }
+ if d.workspaceCoAuthoredByEnabled(workspaceID) {
+ t.Fatal("daemon still reports the trailer as enabled after reconnecting")
+ }
+ if cache.lastWrite(t) {
+ t.Error("published state = enabled, want the value the server held during the outage")
+ }
+}
+
+// Isolated checkouts (Codex on Linux, the Windows sandbox) keep their hook
+// inside the task workdir, so publishing a value cannot reach a workdir
+// prepared by an earlier release. The daemon walks its env roots to find them —
+// and must reconcile only the ones the workspace owns.
+func TestPersistCoAuthoredByStateReconcilesIsolatedCheckouts(t *testing.T) {
+ t.Parallel()
+
+ const workspaceID = "ws-1"
+ settings := `{"co_authored_by_enabled":false}`
+ d, cache := newCoAuthoredByStateDaemon(t, workspaceID, &settings)
+ d.workspaces[workspaceID] = newWorkspaceState(workspaceID, nil, "", nil, json.RawMessage(settings))
+
+ root := t.TempDir()
+ d.cfg.WorkspacesRoot = root
+
+ // Two env roots that look identical on disk and differ only in the
+ // workspace that owns them, plus a daemon-internal cache directory the walk
+ // must not treat as a workspace.
+ ours := seedEnvRootCheckout(t, root, "multica-ws-1", "env-a", workspaceAwareOwner(workspaceID))
+ theirs := seedEnvRootCheckout(t, root, "other-ws", "env-b", workspaceAwareOwner("ws-2"))
+ if err := os.MkdirAll(filepath.Join(root, ".repos", "ws-1"), 0o755); err != nil {
+ t.Fatalf("seed cache dir: %v", err)
+ }
+
+ d.persistCoAuthoredByState(workspaceID)
+
+ got := cache.reconciledCheckouts()
+ if len(got) != 1 {
+ t.Fatalf("reconciled %d checkouts, want exactly the one this workspace owns: %+v", len(got), got)
+ }
+ if got[0].path != ours {
+ t.Errorf("reconciled %q, want %q", got[0].path, ours)
+ }
+ if got[0].enabled {
+ t.Error("reconciled the isolated checkout as enabled, want disabled")
+ }
+ for _, checkout := range got {
+ if checkout.path == theirs {
+ t.Error("reconciled a checkout owned by another workspace")
+ }
+ }
+}
+
+// seedEnvRootCheckout builds <root>/<wsDir>/<envRoot> with a checkout that owns
+// its git metadata, plus the owner marker the release that created it would
+// have written. marker == "" seeds no marker at all, which is what releases
+// before .task_owner left behind.
+func seedEnvRootCheckout(t *testing.T, root, wsDir, envRootName, marker string) string {
+ t.Helper()
+ envRoot := filepath.Join(root, wsDir, envRootName)
+ checkout := filepath.Join(envRoot, "workdir", "repo")
+ if err := os.MkdirAll(filepath.Join(checkout, ".git", "hooks"), 0o755); err != nil {
+ t.Fatalf("seed checkout: %v", err)
+ }
+ if marker != "" {
+ if err := os.WriteFile(filepath.Join(envRoot, ".task_owner"), []byte(marker), 0o644); err != nil {
+ t.Fatalf("seed env root owner: %v", err)
+ }
+ }
+ return checkout
+}
+
+// workspaceAwareOwner is the marker written since v0.4.35: JSON carrying the
+// workspace the env root belongs to.
+func workspaceAwareOwner(workspaceID string) string {
+ return fmt.Sprintf(`{"workspace_id":%q,"task_id":"task-1"}`, workspaceID)
+}
+
+// legacyTaskOnlyOwner is the marker v0.4.32–v0.4.34 wrote: the bare task ID,
+// with nothing that names a workspace.
+const legacyTaskOnlyOwner = "01a05b87-32d9-741c-b7ce-fb90fbd8c451"
+
+// Env roots prepared before v0.4.35 name no workspace: v0.4.32–v0.4.34 wrote a
+// bare task ID into .task_owner, and older releases wrote no marker at all.
+// Both live under that era's layout — <workspaces root>/<workspace ID>/<task
+// key> — and both survive upgrades untouched, so the sweep has to attribute
+// them by directory name or the trailer never stops in the very workdirs this
+// issue was reported from (Linux Codex, Windows sandbox).
+func TestPersistCoAuthoredByStateReconcilesLegacyEnvRoots(t *testing.T) {
+ t.Parallel()
+
+ // The legacy layout used the raw workspace UUID as the directory name.
+ const workspaceID = "01a05b87-a8f3-7eea-8c17-61070ea7e840"
+ const otherWorkspaceID = "01a05b87-0000-7000-8000-000000000002"
+ settings := `{"co_authored_by_enabled":false}`
+ d, cache := newCoAuthoredByStateDaemon(t, workspaceID, &settings)
+ d.workspaces[workspaceID] = newWorkspaceState(workspaceID, nil, "", nil, json.RawMessage(settings))
+
+ root := t.TempDir()
+ d.cfg.WorkspacesRoot = root
+
+ noMarker := seedEnvRootCheckout(t, root, workspaceID, "v0431-style", "")
+ taskOnlyMarker := seedEnvRootCheckout(t, root, workspaceID, "v0434-style", legacyTaskOnlyOwner)
+ // Same two shapes under another workspace's legacy directory, plus a
+ // modern readable directory whose marker names no workspace: neither can
+ // be attributed to this workspace, so neither may be touched.
+ otherNoMarker := seedEnvRootCheckout(t, root, otherWorkspaceID, "v0431-style", "")
+ otherTaskOnly := seedEnvRootCheckout(t, root, otherWorkspaceID, "v0434-style", legacyTaskOnlyOwner)
+ readableUnattributed := seedEnvRootCheckout(t, root, "multica-61070eA_", "env-x", legacyTaskOnlyOwner)
+
+ d.persistCoAuthoredByState(workspaceID)
+
+ reconciled := make(map[string]bool)
+ for _, checkout := range cache.reconciledCheckouts() {
+ reconciled[checkout.path] = checkout.enabled
+ }
+ for _, want := range []string{noMarker, taskOnlyMarker} {
+ enabled, ok := reconciled[want]
+ if !ok {
+ t.Errorf("legacy env root was skipped: %s", want)
+ continue
+ }
+ if enabled {
+ t.Errorf("reconciled %s as enabled, want disabled", want)
+ }
+ }
+ for _, forbidden := range []string{otherNoMarker, otherTaskOnly, readableUnattributed} {
+ if _, ok := reconciled[forbidden]; ok {
+ t.Errorf("reconciled a checkout this workspace cannot claim: %s", forbidden)
+ }
+ }
+}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 20eddfddcb..296d5d5a39 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -301,6 +301,11 @@ type workspaceState struct {
settings json.RawMessage // workspace settings (JSONB)
lastRepoSyncErr string
repoRefreshMu contextLock
+ // coAuthorPublishMu serializes publication of the Co-authored-by verdict
+ // for this workspace. Unlike the fields above it is NOT guarded by
+ // Daemon.mu: it exists precisely so the verdict can be read and written as
+ // one step without holding the daemon's central lock across file I/O.
+ coAuthorPublishMu sync.Mutex
// profileSetSig is a content hash of the workspace's custom runtime
// profile list (MUL-3332) as last seen from the server. An on-demand
// refresh compares the live signature with this cached value; any drift
@@ -3204,9 +3209,243 @@ func (d *Daemon) refreshWorkspaceRepos(ctx context.Context, workspaceID string)
}
d.mu.Unlock()
+ // Publish the refreshed Co-authored-by verdict to the repo cache. Hooks
+ // installed by earlier checkouts read that file at commit time, so this is
+ // what makes a toggled-off setting apply to checkouts that already exist
+ // instead of only to the next one (MUL-6921).
+ d.persistCoAuthoredByState(workspaceID)
+
return resp, nil
}
+// coAuthoredByPublisher is the repo cache's half of the Co-authored-by wiring:
+// the state file every installed hook reads at commit time, and the hooks
+// themselves in the workspace's bare caches. Optional so test daemons can run
+// with a minimal repoCacheBackend.
+type coAuthoredByPublisher interface {
+ WriteCoAuthoredByState(workspaceID string, enabled bool) error
+ ReconcileCoAuthoredByHooks(workspaceID string, enabled bool) error
+ ReconcileCoAuthoredByHookInCheckout(checkoutPath, workspaceID string, enabled bool) error
+}
+
+// persistCoAuthoredByState records the workspace's current Co-authored-by
+// verdict where the installed prepare-commit-msg hooks can see it, and brings
+// hooks written by earlier daemon releases — which read no state at all — in
+// line with it. Called after every settings refresh and on every workspace
+// sync; best-effort, since a failed write only leaves the previous value in
+// place.
+//
+// The daemon is the only writer of this state, and publishes under a
+// per-workspace lock with the verdict read INSIDE that lock. Two publishers
+// racing (a settings refresh and a sync tick, say) therefore serialize, and the
+// one that writes last is the one that read last — a publisher that started
+// before a settings update can never overwrite the value that update produced.
+func (d *Daemon) persistCoAuthoredByState(workspaceID string) {
+ d.publishCoAuthoredByState(workspaceID, d.workspaceCoAuthoredByEnabled)
+}
+
+// publishCoAuthoredByState is persistCoAuthoredByState with the verdict read
+// injected. Production always passes workspaceCoAuthoredByEnabled; tests pass a
+// wrapper that parks a publisher between taking the lock and reading, which is
+// the one ordering the lock exists to guarantee and cannot be observed
+// otherwise.
+func (d *Daemon) publishCoAuthoredByState(workspaceID string, verdict func(string) bool) {
+ if d.repoCache == nil || workspaceID == "" {
+ return
+ }
+ cache, ok := d.repoCache.(coAuthoredByPublisher)
+ if !ok {
+ return
+ }
+
+ d.mu.Lock()
+ ws := d.workspaces[workspaceID]
+ d.mu.Unlock()
+ if ws == nil {
+ return
+ }
+
+ ws.coAuthorPublishMu.Lock()
+ defer ws.coAuthorPublishMu.Unlock()
+
+ enabled := verdict(workspaceID)
+ if err := cache.WriteCoAuthoredByState(workspaceID, enabled); err != nil {
+ d.logger.Warn("record co-authored-by state failed", "workspace_id", workspaceID, "error", err)
+ }
+ if err := cache.ReconcileCoAuthoredByHooks(workspaceID, enabled); err != nil {
+ d.logger.Warn("reconcile co-authored-by hooks failed", "workspace_id", workspaceID, "error", err)
+ }
+ d.reconcileIsolatedCoAuthoredByHooks(cache, workspaceID, enabled)
+}
+
+// isolatedCheckoutScanDepth bounds how far below an env root the sweep looks
+// for a checkout. Repos land at <env root>/<workdir>/<repo>, so two levels
+// covers the layout with one to spare and keeps the walk from wandering into
+// the checked-out source tree.
+const isolatedCheckoutScanDepth = 2
+
+// reconcileIsolatedCoAuthoredByHooks applies the workspace setting to hooks
+// that live inside task workdirs rather than in the shared bare cache.
+//
+// Codex on Linux and the Windows sandbox check out with isolated git metadata,
+// so their hook sits in <checkout>/.git/hooks and the repo cache cannot see it.
+// Left alone, a workdir prepared by an earlier release keeps its unconditional
+// hook — and its next commit keeps adding the trailer — until that repo happens
+// to be checked out again. Env roots are attributed by their owner record, so a
+// workspace never rewrites hooks belonging to another one.
+func (d *Daemon) reconcileIsolatedCoAuthoredByHooks(cache coAuthoredByPublisher, workspaceID string, enabled bool) {
+ root := d.cfg.WorkspacesRoot
+ if root == "" || workspaceID == "" {
+ return
+ }
+ wsEntries, err := os.ReadDir(root)
+ if err != nil {
+ if !os.IsNotExist(err) {
+ d.logger.Debug("co-authored-by sweep: read workspaces root failed", "error", err)
+ }
+ return
+ }
+
+ for _, wsEntry := range wsEntries {
+ // Dot directories are daemon-internal caches (.repos, .skill-cache),
+ // never workspace directories — the same rule runGC walks by.
+ if !wsEntry.IsDir() || strings.HasPrefix(wsEntry.Name(), ".") {
+ continue
+ }
+ wsDir := filepath.Join(root, wsEntry.Name())
+ envRoots, err := os.ReadDir(wsDir)
+ if err != nil {
+ continue
+ }
+ for _, envEntry := range envRoots {
+ if !envEntry.IsDir() || strings.HasPrefix(envEntry.Name(), ".") {
+ continue
+ }
+ envRoot := filepath.Join(wsDir, envEntry.Name())
+ if !d.envRootBelongsToWorkspace(wsEntry.Name(), envRoot, workspaceID) {
+ continue
+ }
+ for _, checkout := range isolatedCheckoutCandidates(envRoot, isolatedCheckoutScanDepth) {
+ if err := cache.ReconcileCoAuthoredByHookInCheckout(checkout, workspaceID, enabled); err != nil {
+ d.logger.Warn("reconcile co-authored-by hook in checkout failed",
+ "workspace_id", workspaceID, "path", checkout, "error", err)
+ }
+ }
+ }
+ }
+}
+
+// envRootBelongsToWorkspace reports whether an env root is this workspace's, by
+// the strongest evidence the release that created it left behind.
+//
+// Since v0.4.35 the owner record carries the workspace ID, and an exact match
+// is required. Env roots prepared before that recorded only a task ID — or, on
+// older releases still, no marker at all — and they live under the layout that
+// release used: <workspaces root>/<workspace ID>/<task key>. So for an owner
+// record that names no workspace, the directory name is the evidence, and it
+// has to BE the workspace ID. The readable layout that replaced it always
+// appends a suffix (`<slug>-<id tail>`), so a bare workspace UUID can only be
+// one of those older roots and this can never alias a modern one.
+//
+// An unreadable marker attributes nothing: skipping costs a stale hook in one
+// workdir, guessing would rewrite hooks in another workspace's.
+func (d *Daemon) envRootBelongsToWorkspace(wsDirName, envRoot, workspaceID string) bool {
+ owner, err := execenv.ReadEnvRootOwner(envRoot)
+ if err != nil || owner == nil {
+ return false
+ }
+ if owner.WorkspaceID != "" {
+ return owner.WorkspaceID == workspaceID
+ }
+ return wsDirName == workspaceID
+}
+
+// isolatedCheckoutCandidates returns directories at or below dir that hold
+// their own git metadata. A linked worktree's .git is a file, so only isolated
+// checkouts match, and matching stops descending: nothing nested inside a
+// checkout is one.
+func isolatedCheckoutCandidates(dir string, depth int) []string {
+ if depth <= 0 {
+ return nil
+ }
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return nil
+ }
+ var found []string
+ for _, entry := range entries {
+ if !entry.IsDir() || strings.HasPrefix(entry.Name(), ".") {
+ continue
+ }
+ child := filepath.Join(dir, entry.Name())
+ if info, err := os.Stat(filepath.Join(child, ".git")); err == nil && info.IsDir() {
+ found = append(found, child)
+ continue
+ }
+ found = append(found, isolatedCheckoutCandidates(child, depth-1)...)
+ }
+ return found
+}
+
+// publishTrackedCoAuthoredByState writes the current verdict for every tracked
+// workspace and reconciles the hooks in their bare caches. Purely local — no
+// request — and both halves skip the write when what is on disk already
+// matches, so a sync tick on a converged host costs a handful of small reads.
+func (d *Daemon) publishTrackedCoAuthoredByState() {
+ d.mu.Lock()
+ ids := make([]string, 0, len(d.workspaces))
+ for id := range d.workspaces {
+ ids = append(ids, id)
+ }
+ d.mu.Unlock()
+
+ for _, id := range ids {
+ d.persistCoAuthoredByState(id)
+ }
+}
+
+// trackedSettingsRefreshTimeout bounds one refreshTrackedWorkspaceSettings
+// pass. A workspace it does not reach keeps its cached settings and picks the
+// change up on its next repo checkout.
+const trackedSettingsRefreshTimeout = 30 * time.Second
+
+// refreshTrackedWorkspaceSettings re-reads repos and settings for workspaces
+// this daemon already tracks. Only the server's workspaces-changed hint calls
+// it: the periodic sync deliberately makes no repos request for a tracked
+// workspace (see syncWorkspacesFromAPI), so without this a settings edit —
+// the GitHub master switch, the Co-authored-by toggle — would sit unseen
+// until the workspace's next repo checkout.
+func (d *Daemon) refreshTrackedWorkspaceSettings(ctx context.Context) {
+ // The sync loop is single-threaded and still owes the hint its membership
+ // reconcile, so bound the whole pass rather than letting one slow
+ // workspace hold every other signal behind it.
+ ctx, cancel := context.WithTimeout(ctx, trackedSettingsRefreshTimeout)
+ defer cancel()
+
+ d.mu.Lock()
+ tracked := make(map[string]*workspaceState, len(d.workspaces))
+ for id, ws := range d.workspaces {
+ tracked[id] = ws
+ }
+ d.mu.Unlock()
+
+ for id, ws := range tracked {
+ if ctx.Err() != nil {
+ return
+ }
+ // Share ensureRepoReady's lock so a checkout in flight and this
+ // refresh cannot interleave their writes to the same workspace.
+ if err := ws.repoRefreshMu.Lock(ctx); err != nil {
+ return
+ }
+ _, err := d.refreshWorkspaceRepos(ctx, id)
+ ws.repoRefreshMu.Unlock()
+ if err != nil {
+ d.logger.Debug("workspace settings refresh failed", "workspace_id", id, "error", err)
+ }
+ }
+}
+
// refreshWorkspaceRuntimeProfiles fetches the workspace's enabled custom
// runtime profile list (MUL-3332), compares its content signature against
// the value cached on the workspaceState, and triggers a re-register when
@@ -3592,8 +3831,17 @@ func (d *Daemon) workspaceSyncLoop(ctx context.Context) {
if d.reconcile != nil {
reconcileCh = d.reconcile.notify()
}
+ // A settings edit made while the websocket was down produced a
+ // workspaces-changed hint nobody received. Reconnecting is the
+ // daemon's chance to catch up on it: without this the stale
+ // verdict would just get republished by the sync below.
+ d.refreshTrackedWorkspaceSettings(ctx)
syncNow(true)
case <-workspaceChangesCh:
+ // The hint fires for membership changes AND for workspace edits,
+ // including settings. Refresh cached settings for the workspaces
+ // we already track before reconciling the membership set.
+ d.refreshTrackedWorkspaceSettings(ctx)
syncNow(false)
case <-timer.C:
syncNow(false)
@@ -3812,6 +4060,14 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context, reconcileProfiles bo
d.notifyRuntimeSetChanged()
}
+ // Republish each tracked workspace's Co-authored-by verdict. This costs no
+ // request — it writes the daemon's cached verdict where prepare-commit-msg
+ // hooks read it, and migrates hooks left by earlier releases — and is what
+ // covers the cases no refresh reaches: a toggle flipped while the daemon
+ // was down (settings arrive with the register response above), a host that
+ // just upgraded, and a state file removed by repo cache GC.
+ d.publishTrackedCoAuthoredByState()
+
if len(d.allRuntimeIDs()) == 0 && registered == 0 && len(workspaces) > 0 {
return fmt.Errorf("failed to register runtimes for any of the %d workspace(s)", len(workspaces))
}
diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.go
index 09827f401d..ff86b411a7 100644
--- a/server/internal/daemon/repocache/cache.go
+++ b/server/internal/daemon/repocache/cache.go
@@ -862,15 +862,7 @@ func (c *Cache) CreateWorktreeContext(ctx context.Context, params WorktreeParams
for _, pattern := range agentGitExcludePatterns {
_ = excludeFromGitContext(ctx, worktreePath, pattern)
}
- if params.CoAuthoredByEnabled {
- if err := installCoAuthoredByHookContext(ctx, worktreePath); err != nil {
- c.logger.Warn("repo checkout: install co-authored-by hook failed (non-fatal)", "error", err)
- }
- } else {
- if err := removeCoAuthoredByHookContext(ctx, worktreePath); err != nil {
- c.logger.Warn("repo checkout: remove co-authored-by hook failed (non-fatal)", "error", err)
- }
- }
+ c.applyCoAuthoredBySettingContext(ctx, worktreePath, params)
if err := ctx.Err(); err != nil {
return nil, context.Cause(ctx)
}
@@ -896,20 +888,12 @@ func (c *Cache) CreateWorktreeContext(ctx context.Context, params WorktreeParams
_ = excludeFromGitContext(ctx, worktreePath, pattern)
}
- // Install or remove the Co-authored-by hook based on the workspace
+ // Reconcile the Co-authored-by hook and the workspace's recorded
// setting. The hook lives in the bare repo's shared hooks dir, so we
// must actively remove it when disabled — otherwise a previously
// installed hook keeps appending the trailer to every commit even
// after the user toggles the setting off.
- if params.CoAuthoredByEnabled {
- if err := installCoAuthoredByHookContext(ctx, worktreePath); err != nil {
- c.logger.Warn("repo checkout: install co-authored-by hook failed (non-fatal)", "error", err)
- }
- } else {
- if err := removeCoAuthoredByHookContext(ctx, worktreePath); err != nil {
- c.logger.Warn("repo checkout: remove co-authored-by hook failed (non-fatal)", "error", err)
- }
- }
+ c.applyCoAuthoredBySettingContext(ctx, worktreePath, params)
if err := ctx.Err(); err != nil {
return nil, context.Cause(ctx)
}
@@ -939,18 +923,10 @@ func (c *Cache) CreateWorktreeContext(ctx context.Context, params WorktreeParams
_ = excludeFromGitContext(ctx, worktreePath, pattern)
}
- // Install or remove the Co-authored-by hook based on the workspace
- // setting. See the existing-worktree branch above for why removal is
- // required when the setting is disabled.
- if params.CoAuthoredByEnabled {
- if err := installCoAuthoredByHookContext(ctx, worktreePath); err != nil {
- c.logger.Warn("repo checkout: install co-authored-by hook failed (non-fatal)", "error", err)
- }
- } else {
- if err := removeCoAuthoredByHookContext(ctx, worktreePath); err != nil {
- c.logger.Warn("repo checkout: remove co-authored-by hook failed (non-fatal)", "error", err)
- }
- }
+ // Reconcile the Co-authored-by hook and the workspace's recorded setting.
+ // See the existing-worktree branch above for why removal is required when
+ // the setting is disabled.
+ c.applyCoAuthoredBySettingContext(ctx, worktreePath, params)
if err := ctx.Err(); err != nil {
return nil, context.Cause(ctx)
}
@@ -1601,9 +1577,253 @@ var daemonInstalledHookSignatures = []string{
"# Installed by the Multica daemon.",
}
-// prepareCommitMsgHook is the prepare-commit-msg hook script that appends a
-// Co-authored-by trailer for the Multica Agent to every commit message.
-const prepareCommitMsgHook = `#!/bin/sh
+// coAuthoredByStateFile records the workspace's current Co-authored-by setting
+// for hooks that are already on disk. It lives beside the workspace's bare
+// caches (`<root>/<workspace-id>/`) and is rewritten every time the daemon
+// learns the setting, so a checkout made before the toggle was flipped still
+// commits under the current value. Without it the decision would be frozen
+// into the hook file at checkout time (MUL-6921).
+const (
+ coAuthoredByStateFile = ".multica_co_authored_by"
+ coAuthoredByStateEnabled = "1"
+ coAuthoredByStateDisabled = "0"
+)
+
+// CoAuthoredByStatePath returns the file the prepare-commit-msg hook consults
+// at commit time for a workspace. Empty when the workspace is unknown, which
+// installs a hook with no gate — the pre-MUL-6921 behavior.
+func (c *Cache) CoAuthoredByStatePath(workspaceID string) string {
+ if workspaceID == "" {
+ return ""
+ }
+ return filepath.Join(c.root, workspaceID, coAuthoredByStateFile)
+}
+
+// WriteCoAuthoredByState publishes the workspace's current setting to every
+// prepare-commit-msg hook the daemon has installed for it, including hooks in
+// checkouts this call knows nothing about. The daemon calls it whenever it
+// refreshes workspace settings, which is what makes the toggle apply without
+// waiting for the repo to be checked out again.
+//
+// The write is atomic (temp file + rename) so a hook running concurrently
+// reads either the old value or the new one, never a half-written file.
+func (c *Cache) WriteCoAuthoredByState(workspaceID string, enabled bool) error {
+ path := c.CoAuthoredByStatePath(workspaceID)
+ if path == "" {
+ return nil
+ }
+ value := coAuthoredByStateDisabled
+ if enabled {
+ value = coAuthoredByStateEnabled
+ }
+ if current, err := os.ReadFile(path); err == nil && strings.TrimSpace(string(current)) == value {
+ // Already published. The daemon republishes on every workspace sync so
+ // the file survives cache GC and daemon restarts; skipping the rewrite
+ // keeps that cheap.
+ return nil
+ }
+ dir := filepath.Dir(path)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return fmt.Errorf("create workspace cache dir: %w", err)
+ }
+ tmp, err := os.CreateTemp(dir, coAuthoredByStateFile+".*")
+ if err != nil {
+ return fmt.Errorf("create co-authored-by state temp file: %w", err)
+ }
+ tmpName := tmp.Name()
+ if _, err := tmp.WriteString(value + "\n"); err != nil {
+ tmp.Close()
+ os.Remove(tmpName)
+ return fmt.Errorf("write co-authored-by state: %w", err)
+ }
+ if err := tmp.Close(); err != nil {
+ os.Remove(tmpName)
+ return fmt.Errorf("write co-authored-by state: %w", err)
+ }
+ if err := os.Rename(tmpName, path); err != nil {
+ os.Remove(tmpName)
+ return fmt.Errorf("publish co-authored-by state: %w", err)
+ }
+ return nil
+}
+
+// applyCoAuthoredBySettingContext reconciles this checkout's hook file with the
+// workspace setting.
+//
+// It deliberately does NOT publish the state file. params.CoAuthoredByEnabled
+// is a snapshot the handler took before fetch and lock waits, so a checkout can
+// finish long after the value it captured stopped being true; writing that
+// snapshot to the workspace-wide state file would let a slow checkout resurrect
+// a trailer the user has since turned off. The daemon is the only publisher —
+// it holds the ordering between settings updates — and this reads what the
+// daemon published, falling back to the snapshot only when nothing has been
+// published yet (a cache driven without a daemon, or a state file removed under
+// us).
+func (c *Cache) applyCoAuthoredBySettingContext(ctx context.Context, worktreePath string, params WorktreeParams) {
+ enabled := params.CoAuthoredByEnabled
+ if published, ok := c.readCoAuthoredByState(params.WorkspaceID); ok {
+ enabled = published
+ }
+ if enabled {
+ if err := installCoAuthoredByHookContext(ctx, worktreePath, c.CoAuthoredByStatePath(params.WorkspaceID)); err != nil {
+ c.logger.Warn("repo checkout: install co-authored-by hook failed (non-fatal)", "error", err)
+ }
+ return
+ }
+ if err := removeCoAuthoredByHookContext(ctx, worktreePath); err != nil {
+ c.logger.Warn("repo checkout: remove co-authored-by hook failed (non-fatal)", "error", err)
+ }
+}
+
+// readCoAuthoredByState reports the setting the daemon last published for a
+// workspace. ok is false when nothing has been published — the caller decides
+// what "unknown" means for it.
+func (c *Cache) readCoAuthoredByState(workspaceID string) (enabled, ok bool) {
+ path := c.CoAuthoredByStatePath(workspaceID)
+ if path == "" {
+ return false, false
+ }
+ contents, err := os.ReadFile(path)
+ if err != nil {
+ return false, false
+ }
+ switch strings.TrimSpace(string(contents)) {
+ case coAuthoredByStateEnabled:
+ return true, true
+ case coAuthoredByStateDisabled:
+ return false, true
+ default:
+ return false, false
+ }
+}
+
+// ReconcileCoAuthoredByHooks brings the hooks in a workspace's bare caches in
+// line with enabled, without waiting for those repos to be checked out again.
+//
+// This is the migration path for hooks installed by earlier daemon versions:
+// they predate the state file and read nothing at commit time, so publishing a
+// new value cannot reach them. Enabled rewrites them to the current gated
+// script (a later toggle-off then applies at commit time); disabled deletes
+// them. Hooks the daemon does not own are never touched.
+//
+// Only bare caches are enumerable here — the cache root is all this type
+// knows. Isolated checkouts keep their hook inside a task workdir; the daemon
+// finds those and reconciles them one at a time through
+// ReconcileCoAuthoredByHookInCheckout.
+func (c *Cache) ReconcileCoAuthoredByHooks(workspaceID string, enabled bool) error {
+ if workspaceID == "" {
+ return nil
+ }
+ wsDir := filepath.Join(c.root, workspaceID)
+ entries, err := os.ReadDir(wsDir)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return fmt.Errorf("read workspace cache dir: %w", err)
+ }
+
+ var firstErr error
+ for _, entry := range entries {
+ if !entry.IsDir() {
+ continue
+ }
+ barePath := filepath.Join(wsDir, entry.Name())
+ if !isBareRepo(barePath) {
+ continue
+ }
+ if err := c.reconcileHookAt(filepath.Join(barePath, "hooks"), workspaceID, enabled); err != nil && firstErr == nil {
+ firstErr = err
+ }
+ }
+ return firstErr
+}
+
+// ReconcileCoAuthoredByHookInCheckout applies the workspace setting to a single
+// checkout that owns its git metadata — an isolated checkout, whose .git lives
+// in the task workdir instead of the shared bare cache and is therefore
+// invisible to ReconcileCoAuthoredByHooks. The daemon knows where those
+// workdirs are and calls this for each one it finds.
+//
+// A linked worktree has a .git FILE pointing at the bare cache; it is skipped
+// here because its hook is reconciled through the bare cache instead.
+func (c *Cache) ReconcileCoAuthoredByHookInCheckout(checkoutPath, workspaceID string, enabled bool) error {
+ if checkoutPath == "" || workspaceID == "" {
+ return nil
+ }
+ gitDir := filepath.Join(checkoutPath, ".git")
+ info, err := os.Stat(gitDir)
+ if err != nil || !info.IsDir() {
+ return nil
+ }
+ return c.reconcileHookAt(filepath.Join(gitDir, "hooks"), workspaceID, enabled)
+}
+
+// reconcileHookAt applies the workspace setting to one hooks directory. It
+// leaves a hook the daemon did not install alone, and never creates a hooks
+// directory it did not find.
+func (c *Cache) reconcileHookAt(hooksDir, workspaceID string, enabled bool) error {
+ hookPath := filepath.Join(hooksDir, "prepare-commit-msg")
+ current, err := os.ReadFile(hookPath)
+ switch {
+ case err == nil && !isDaemonInstalledHook(current):
+ return nil // user or third-party hook: not ours to reconcile
+ case err != nil && !os.IsNotExist(err):
+ return fmt.Errorf("read prepare-commit-msg hook: %w", err)
+ }
+ exists := err == nil
+
+ if !enabled {
+ if !exists {
+ return nil
+ }
+ if err := os.Remove(hookPath); err != nil && !os.IsNotExist(err) {
+ return fmt.Errorf("remove prepare-commit-msg hook: %w", err)
+ }
+ return nil
+ }
+
+ want := prepareCommitMsgHook(c.CoAuthoredByStatePath(workspaceID))
+ if exists && string(current) == want {
+ return nil
+ }
+ if err := os.MkdirAll(hooksDir, 0o755); err != nil {
+ return fmt.Errorf("create hooks dir: %w", err)
+ }
+ if err := writeHookFile(hookPath, want); err != nil {
+ return fmt.Errorf("write prepare-commit-msg hook: %w", err)
+ }
+ return nil
+}
+
+// prepareCommitMsgHook builds the prepare-commit-msg hook script that appends
+// a Co-authored-by trailer for the Multica Agent to every commit message.
+//
+// The script re-reads statePath on every commit instead of trusting its own
+// presence on disk: the hook is installed in the git common directory and
+// outlives the checkout that created it, so a workspace toggled off after the
+// checkout must still stop the trailer at the very next commit — including
+// commits the daemon never sees, and `git commit --no-verify`, which bypasses
+// pre-commit and commit-msg but not prepare-commit-msg.
+//
+// A missing or unreadable state file keeps the trailer: the hook only exists
+// because a checkout ran with the setting enabled, so "no state recorded" must
+// mean the same thing it meant before the state file existed.
+func prepareCommitMsgHook(statePath string) string {
+ var gate string
+ if statePath != "" {
+ gate = fmt.Sprintf(`# Current workspace setting, refreshed by the daemon. "0" means the
+# Co-authored-by toggle is off — leave the message alone.
+STATE_FILE=%s
+if [ -f "$STATE_FILE" ]; then
+ case "$(cat "$STATE_FILE" 2>/dev/null)" in
+ 0) exit 0 ;;
+ esac
+fi
+
+`, shellSingleQuoted(filepath.ToSlash(statePath)))
+ }
+ return `#!/bin/sh
# multica:prepare-commit-msg:co-authored-by
# Multica: add Co-authored-by trailer for the Multica Agent.
# Installed by the Multica daemon. Do not edit — it will be overwritten.
@@ -1616,7 +1836,7 @@ case "$COMMIT_SOURCE" in
merge|squash) exit 0 ;;
esac
-TRAILER="Co-authored-by: multica-agent <[email protected]>"
+` + gate + `TRAILER="Co-authored-by: multica-agent <[email protected]>"
# Don't add if already present.
if grep -qF "$TRAILER" "$COMMIT_MSG_FILE"; then
@@ -1626,16 +1846,26 @@ fi
# Use git interpret-trailers for proper formatting.
git interpret-trailers --in-place --trailer "$TRAILER" "$COMMIT_MSG_FILE"
`
+}
+
+// shellSingleQuoted renders s as a POSIX shell single-quoted literal so a path
+// with spaces or shell metacharacters survives being embedded in the hook.
+func shellSingleQuoted(s string) string {
+ return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
+}
// installCoAuthoredByHook installs a prepare-commit-msg git hook that appends
// a Co-authored-by trailer for the Multica Agent. The hook is installed in the
// git common directory (the bare repo for worktrees) so it applies to all
// worktrees created from this cache.
-func installCoAuthoredByHook(worktreePath string) error {
- return installCoAuthoredByHookContext(context.Background(), worktreePath)
+//
+// statePath is the file the hook re-reads on every commit to decide whether
+// the trailer is still wanted; pass "" to install an ungated hook.
+func installCoAuthoredByHook(worktreePath, statePath string) error {
+ return installCoAuthoredByHookContext(context.Background(), worktreePath, statePath)
}
-func installCoAuthoredByHookContext(ctx context.Context, worktreePath string) error {
+func installCoAuthoredByHookContext(ctx context.Context, worktreePath, statePath string) error {
out, err := runGitOutputContext(ctx, "-C", worktreePath, "rev-parse", "--git-common-dir")
if err != nil {
return fmt.Errorf("resolve git common dir: %w", err)
@@ -1651,12 +1881,42 @@ func installCoAuthoredByHookContext(ctx context.Context, worktreePath string) er
}
hookPath := filepath.Join(hooksDir, "prepare-commit-msg")
- if err := os.WriteFile(hookPath, []byte(prepareCommitMsgHook), 0o755); err != nil {
+ if err := writeHookFile(hookPath, prepareCommitMsgHook(statePath)); err != nil {
return fmt.Errorf("write prepare-commit-msg hook: %w", err)
}
return nil
}
+// writeHookFile publishes a hook script by rename. A plain truncate-and-write
+// would be visible to a commit running at that moment as a half-written
+// script, and this path rewrites hooks in repos with checkouts live on them.
+func writeHookFile(hookPath, contents string) error {
+ dir := filepath.Dir(hookPath)
+ tmp, err := os.CreateTemp(dir, ".multica-hook-*")
+ if err != nil {
+ return err
+ }
+ tmpName := tmp.Name()
+ if _, err := tmp.WriteString(contents); err != nil {
+ tmp.Close()
+ os.Remove(tmpName)
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ os.Remove(tmpName)
+ return err
+ }
+ if err := os.Chmod(tmpName, 0o755); err != nil {
+ os.Remove(tmpName)
+ return err
+ }
+ if err := os.Rename(tmpName, hookPath); err != nil {
+ os.Remove(tmpName)
+ return err
+ }
+ return nil
+}
+
// isDaemonInstalledHook reports whether a prepare-commit-msg hook on disk was
// installed by the Multica daemon (current or any previously released
// version). It returns false for hooks that don't carry any known daemon
diff --git a/server/internal/daemon/repocache/cache_test.go b/server/internal/daemon/repocache/cache_test.go
index 9541048570..95e4e72bd8 100644
--- a/server/internal/daemon/repocache/cache_test.go
+++ b/server/internal/daemon/repocache/cache_test.go
@@ -2250,3 +2250,449 @@ func TestBranchNameDistinctForSharedUUIDv7Prefix(t *testing.T) {
t.Fatalf("both tasks resolved to branch %q", a)
}
}
+
+// TestCoAuthoredByStateStopsTrailerInExistingCheckout is the MUL-6921
+// regression: disabling the workspace toggle used to apply only to checkouts
+// created afterwards, because the decision was frozen into the hook file at
+// checkout time. A checkout that already exists must honor the new value on
+// its very next commit — including `git commit --no-verify`, which bypasses
+// pre-commit and commit-msg but not prepare-commit-msg.
+func TestCoAuthoredByStateStopsTrailerInExistingCheckout(t *testing.T) {
+ t.Parallel()
+ sourceRepo := createTestRepo(t)
+ cacheRoot := t.TempDir()
+
+ cache := New(cacheRoot, testLogger())
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {
+ t.Fatalf("sync failed: %v", err)
+ }
+
+ workDir := t.TempDir()
+ result, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: workDir,
+ AgentName: "Test Agent",
+ TaskID: "33333333-0000-0000-0000-000000000000",
+ CoAuthoredByEnabled: true,
+ })
+ if err != nil {
+ t.Fatalf("CreateWorktree failed: %v", err)
+ }
+
+ commit := func(name, message string, args ...string) string {
+ t.Helper()
+ if err := os.WriteFile(filepath.Join(result.Path, name), []byte("hello\n"), 0o644); err != nil {
+ t.Fatalf("write test file: %v", err)
+ }
+ runGitAuthored(t, result.Path, "add", ".")
+ runGitAuthored(t, result.Path, append(append([]string{"commit"}, args...), "-m", message)...)
+ out, err := exec.Command("git", "-C", result.Path, "log", "-1", "--format=%B").Output()
+ if err != nil {
+ t.Fatalf("git log failed: %v", err)
+ }
+ return string(out)
+ }
+
+ if msg := commit("a.txt", "enabled commit"); !strings.Contains(msg, "Co-authored-by: multica-agent") {
+ t.Fatalf("precondition: commit made with the setting on lacks the trailer.\ngot:\n%s", msg)
+ }
+
+ // The user flips the toggle off. No new checkout happens — the daemon
+ // only republishes the workspace's setting.
+ if err := cache.WriteCoAuthoredByState("ws-1", false); err != nil {
+ t.Fatalf("WriteCoAuthoredByState(false) failed: %v", err)
+ }
+
+ if msg := commit("b.txt", "disabled commit"); strings.Contains(msg, "Co-authored-by: multica-agent") {
+ t.Errorf("commit in the existing checkout still carries the trailer after the toggle was turned off.\ngot:\n%s", msg)
+ }
+ if msg := commit("c.txt", "disabled commit, no-verify", "--no-verify"); strings.Contains(msg, "Co-authored-by: multica-agent") {
+ t.Errorf("--no-verify commit still carries the trailer after the toggle was turned off.\ngot:\n%s", msg)
+ }
+
+ // Turning it back on restores the trailer without a new checkout either.
+ if err := cache.WriteCoAuthoredByState("ws-1", true); err != nil {
+ t.Fatalf("WriteCoAuthoredByState(true) failed: %v", err)
+ }
+ if msg := commit("d.txt", "re-enabled commit"); !strings.Contains(msg, "Co-authored-by: multica-agent") {
+ t.Errorf("commit missing the trailer after the toggle was turned back on.\ngot:\n%s", msg)
+ }
+}
+
+// TestCreateWorktreeInstallsGatedHook pins the fact the hook gate depends on:
+// the hook a checkout installs reads the workspace state file the daemon
+// publishes, and stays recognizable as daemon-owned so the disable path can
+// still clean it up.
+func TestCreateWorktreeInstallsGatedHook(t *testing.T) {
+ t.Parallel()
+ sourceRepo := createTestRepo(t)
+ cacheRoot := t.TempDir()
+
+ cache := New(cacheRoot, testLogger())
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {
+ t.Fatalf("sync failed: %v", err)
+ }
+
+ workDir := t.TempDir()
+ if _, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: workDir,
+ AgentName: "Test Agent",
+ TaskID: "44444444-0000-0000-0000-000000000000",
+ CoAuthoredByEnabled: true,
+ }); err != nil {
+ t.Fatalf("CreateWorktree failed: %v", err)
+ }
+
+ statePath := cache.CoAuthoredByStatePath("ws-1")
+ hook, err := os.ReadFile(filepath.Join(cache.Lookup("ws-1", sourceRepo), "hooks", "prepare-commit-msg"))
+ if err != nil {
+ t.Fatalf("read hook: %v", err)
+ }
+ if !strings.Contains(string(hook), filepath.ToSlash(statePath)) {
+ t.Errorf("installed hook does not read the state file at %s.\ngot:\n%s", statePath, hook)
+ }
+ if !isDaemonInstalledHook(hook) {
+ t.Error("gated hook is no longer recognized as daemon-installed; disabling the toggle would stop cleaning it up")
+ }
+}
+
+// TestWriteCoAuthoredByStateIsAtomic guards the hook's read: the state file is
+// published by rename, so a commit racing a settings refresh reads either the
+// old value or the new one, never an empty or half-written file.
+func TestWriteCoAuthoredByStateIsAtomic(t *testing.T) {
+ t.Parallel()
+ cacheRoot := t.TempDir()
+ cache := New(cacheRoot, testLogger())
+
+ for i := 0; i < 20; i++ {
+ enabled := i%2 == 0
+ if err := cache.WriteCoAuthoredByState("ws-1", enabled); err != nil {
+ t.Fatalf("WriteCoAuthoredByState failed: %v", err)
+ }
+ state, err := os.ReadFile(cache.CoAuthoredByStatePath("ws-1"))
+ if err != nil {
+ t.Fatalf("read state: %v", err)
+ }
+ want := "0"
+ if enabled {
+ want = "1"
+ }
+ if got := strings.TrimSpace(string(state)); got != want {
+ t.Fatalf("state = %q, want %q", got, want)
+ }
+ }
+
+ entries, err := os.ReadDir(filepath.Dir(cache.CoAuthoredByStatePath("ws-1")))
+ if err != nil {
+ t.Fatalf("read workspace cache dir: %v", err)
+ }
+ for _, entry := range entries {
+ if entry.Name() != coAuthoredByStateFile {
+ t.Errorf("temp file %q left behind in the workspace cache dir", entry.Name())
+ }
+ }
+}
+
+// releasedUngatedHook is the exact prepare-commit-msg script shipped before
+// MUL-6921: it carries the marker, so the daemon still recognizes it as its
+// own, but it reads no state and appends the trailer unconditionally. Hosts
+// that upgrade have this file sitting in every bare cache they checked out
+// under the old release, so the migration path has to be tested against the
+// real bytes rather than against a hook this PR's code produced.
+const releasedUngatedHook = `#!/bin/sh
+# multica:prepare-commit-msg:co-authored-by
+# Multica: add Co-authored-by trailer for the Multica Agent.
+# Installed by the Multica daemon. Do not edit — it will be overwritten.
+
+COMMIT_MSG_FILE="$1"
+COMMIT_SOURCE="$2"
+
+# Skip merge and squash commits.
+case "$COMMIT_SOURCE" in
+ merge|squash) exit 0 ;;
+esac
+
+TRAILER="Co-authored-by: multica-agent <[email protected]>"
+
+# Don't add if already present.
+if grep -qF "$TRAILER" "$COMMIT_MSG_FILE"; then
+ exit 0
+fi
+
+# Use git interpret-trailers for proper formatting.
+git interpret-trailers --in-place --trailer "$TRAILER" "$COMMIT_MSG_FILE"
+`
+
+// seedUpgradedHost returns a cache, a worktree created under the previous
+// release, and the path of the hook that release installed: the state of a
+// machine at the moment it upgrades to a daemon carrying this change.
+func seedUpgradedHost(t *testing.T, taskID string) (cache *Cache, worktreePath, hookPath string) {
+ t.Helper()
+ sourceRepo := createTestRepo(t)
+ cache = New(t.TempDir(), testLogger())
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {
+ t.Fatalf("sync failed: %v", err)
+ }
+ result, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: t.TempDir(),
+ AgentName: "Test Agent",
+ TaskID: taskID,
+ CoAuthoredByEnabled: true,
+ })
+ if err != nil {
+ t.Fatalf("CreateWorktree failed: %v", err)
+ }
+
+ hookPath = filepath.Join(cache.Lookup("ws-1", sourceRepo), "hooks", "prepare-commit-msg")
+ if err := os.WriteFile(hookPath, []byte(releasedUngatedHook), 0o755); err != nil {
+ t.Fatalf("seed previous-release hook: %v", err)
+ }
+ return cache, result.Path, hookPath
+}
+
+// commitInWorktree makes a real commit and returns the resulting message.
+func commitInWorktree(t *testing.T, worktreePath, name, message string, args ...string) string {
+ t.Helper()
+ if err := os.WriteFile(filepath.Join(worktreePath, name), []byte("hello\n"), 0o644); err != nil {
+ t.Fatalf("write test file: %v", err)
+ }
+ runGitAuthored(t, worktreePath, "add", ".")
+ runGitAuthored(t, worktreePath, append(append([]string{"commit"}, args...), "-m", message)...)
+ out, err := exec.Command("git", "-C", worktreePath, "log", "-1", "--format=%B").Output()
+ if err != nil {
+ t.Fatalf("git log failed: %v", err)
+ }
+ return string(out)
+}
+
+// A host that upgrades carries hooks from the previous release, and those read
+// no state file — publishing a new value cannot reach them. Turning the setting
+// off must still take effect on the existing checkout, with no CreateWorktree
+// call in between.
+func TestReconcileCoAuthoredByHooksMigratesReleasedHook(t *testing.T) {
+ t.Parallel()
+ cache, worktreePath, hookPath := seedUpgradedHost(t, "55555555-0000-0000-0000-000000000000")
+
+ if msg := commitInWorktree(t, worktreePath, "a.txt", "before the toggle"); !strings.Contains(msg, "Co-authored-by: multica-agent") {
+ t.Fatalf("precondition: the previous release's hook should still add the trailer.\ngot:\n%s", msg)
+ }
+
+ // The daemon learns the setting is off: it publishes the new value and
+ // reconciles the hooks it owns. No checkout happens.
+ if err := cache.WriteCoAuthoredByState("ws-1", false); err != nil {
+ t.Fatalf("WriteCoAuthoredByState failed: %v", err)
+ }
+ if err := cache.ReconcileCoAuthoredByHooks("ws-1", false); err != nil {
+ t.Fatalf("ReconcileCoAuthoredByHooks failed: %v", err)
+ }
+
+ if _, err := os.Stat(hookPath); !os.IsNotExist(err) {
+ t.Errorf("expected the previous release's hook to be removed at %s, stat err=%v", hookPath, err)
+ }
+ if msg := commitInWorktree(t, worktreePath, "b.txt", "after the toggle"); strings.Contains(msg, "Co-authored-by: multica-agent") {
+ t.Errorf("upgraded host still adds the trailer after the toggle was turned off.\ngot:\n%s", msg)
+ }
+}
+
+// With the setting on there is nothing to remove, but the previous release's
+// hook still has to be replaced by the gated one — otherwise the NEXT toggle-off
+// is stuck waiting for a checkout all over again.
+func TestReconcileCoAuthoredByHooksUpgradesReleasedHookInPlace(t *testing.T) {
+ t.Parallel()
+ cache, worktreePath, hookPath := seedUpgradedHost(t, "66666666-0000-0000-0000-000000000000")
+
+ if err := cache.WriteCoAuthoredByState("ws-1", true); err != nil {
+ t.Fatalf("WriteCoAuthoredByState failed: %v", err)
+ }
+ if err := cache.ReconcileCoAuthoredByHooks("ws-1", true); err != nil {
+ t.Fatalf("ReconcileCoAuthoredByHooks failed: %v", err)
+ }
+
+ hook, err := os.ReadFile(hookPath)
+ if err != nil {
+ t.Fatalf("read hook: %v", err)
+ }
+ if !strings.Contains(string(hook), filepath.ToSlash(cache.CoAuthoredByStatePath("ws-1"))) {
+ t.Fatalf("hook was not upgraded to read the state file.\ngot:\n%s", hook)
+ }
+ if msg := commitInWorktree(t, worktreePath, "a.txt", "still enabled"); !strings.Contains(msg, "Co-authored-by: multica-agent") {
+ t.Errorf("upgraded hook dropped the trailer while the setting is on.\ngot:\n%s", msg)
+ }
+
+ // The point of the upgrade: from here a publish alone is enough.
+ if err := cache.WriteCoAuthoredByState("ws-1", false); err != nil {
+ t.Fatalf("WriteCoAuthoredByState failed: %v", err)
+ }
+ if msg := commitInWorktree(t, worktreePath, "b.txt", "toggled off"); strings.Contains(msg, "Co-authored-by: multica-agent") {
+ t.Errorf("upgraded hook ignored the published state.\ngot:\n%s", msg)
+ }
+}
+
+// The sweep runs across every bare cache in a workspace, so it must be as
+// conservative as the checkout path about hooks it does not own.
+func TestReconcileCoAuthoredByHooksPreservesUserHook(t *testing.T) {
+ t.Parallel()
+ sourceRepo := createTestRepo(t)
+ cache := New(t.TempDir(), testLogger())
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {
+ t.Fatalf("sync failed: %v", err)
+ }
+
+ const userHook = "#!/bin/sh\n# my own hook\nexit 0\n"
+ hooksDir := filepath.Join(cache.Lookup("ws-1", sourceRepo), "hooks")
+ if err := os.MkdirAll(hooksDir, 0o755); err != nil {
+ t.Fatalf("create hooks dir: %v", err)
+ }
+ hookPath := filepath.Join(hooksDir, "prepare-commit-msg")
+ if err := os.WriteFile(hookPath, []byte(userHook), 0o755); err != nil {
+ t.Fatalf("seed user hook: %v", err)
+ }
+
+ for _, enabled := range []bool{false, true} {
+ if err := cache.ReconcileCoAuthoredByHooks("ws-1", enabled); err != nil {
+ t.Fatalf("ReconcileCoAuthoredByHooks(%v) failed: %v", enabled, err)
+ }
+ got, err := os.ReadFile(hookPath)
+ if err != nil {
+ t.Fatalf("user hook disappeared after reconcile(%v): %v", enabled, err)
+ }
+ if string(got) != userHook {
+ t.Fatalf("reconcile(%v) rewrote a hook the daemon does not own.\ngot:\n%s", enabled, got)
+ }
+ }
+}
+
+// A checkout captures the setting before its fetch and lock waits, so it can
+// finish long after that value stopped being true. It must not write that stale
+// snapshot back over the value the daemon published in the meantime — doing so
+// resurrects a trailer the user already turned off, on every checkout in the
+// workspace.
+func TestCreateWorktreeDoesNotResurrectDisabledState(t *testing.T) {
+ t.Parallel()
+ sourceRepo := createTestRepo(t)
+ cache := New(t.TempDir(), testLogger())
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {
+ t.Fatalf("sync failed: %v", err)
+ }
+
+ // The daemon published "off" while a checkout that snapshotted "on" was
+ // still waiting on its fetch.
+ if err := cache.WriteCoAuthoredByState("ws-1", false); err != nil {
+ t.Fatalf("WriteCoAuthoredByState failed: %v", err)
+ }
+
+ result, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: t.TempDir(),
+ AgentName: "Test Agent",
+ TaskID: "77777777-0000-0000-0000-000000000000",
+ CoAuthoredByEnabled: true, // stale snapshot
+ })
+ if err != nil {
+ t.Fatalf("CreateWorktree failed: %v", err)
+ }
+
+ state, err := os.ReadFile(cache.CoAuthoredByStatePath("ws-1"))
+ if err != nil {
+ t.Fatalf("read co-authored-by state: %v", err)
+ }
+ if strings.TrimSpace(string(state)) != "0" {
+ t.Errorf("state = %q, want it left at 0: a checkout must not republish its snapshot", state)
+ }
+ if msg := commitInWorktree(t, result.Path, "a.txt", "checked out with a stale snapshot"); strings.Contains(msg, "Co-authored-by: multica-agent") {
+ t.Errorf("commit carries the trailer although the workspace setting is off.\ngot:\n%s", msg)
+ }
+}
+
+// Codex on Linux and the Windows sandbox check out with isolated git metadata,
+// so the hook lives in the task workdir instead of the shared bare cache and no
+// sweep of the cache root can see it. The daemon finds those checkouts and
+// reconciles them one at a time; this is that path, end to end on a checkout
+// carrying the previous release's hook.
+func TestReconcileCoAuthoredByHookInCheckoutMigratesReleasedHook(t *testing.T) {
+ t.Parallel()
+ sourceRepo := createTestRepo(t)
+ cache := New(t.TempDir(), testLogger())
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {
+ t.Fatalf("sync failed: %v", err)
+ }
+
+ result, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: t.TempDir(),
+ AgentName: "Test Agent",
+ TaskID: "88888888-0000-0000-0000-000000000000",
+ CoAuthoredByEnabled: true,
+ IsolatedGitMetadata: true,
+ })
+ if err != nil {
+ t.Fatalf("CreateWorktree failed: %v", err)
+ }
+
+ hookPath := filepath.Join(result.Path, ".git", "hooks", "prepare-commit-msg")
+ if _, err := os.Stat(hookPath); err != nil {
+ t.Fatalf("precondition: isolated checkout should carry its own hook: %v", err)
+ }
+ // Roll it back to what the previous release installed.
+ if err := os.WriteFile(hookPath, []byte(releasedUngatedHook), 0o755); err != nil {
+ t.Fatalf("seed previous-release hook: %v", err)
+ }
+ if msg := commitInWorktree(t, result.Path, "a.txt", "before the toggle"); !strings.Contains(msg, "Co-authored-by: multica-agent") {
+ t.Fatalf("precondition: the previous release's hook should still add the trailer.\ngot:\n%s", msg)
+ }
+
+ if err := cache.WriteCoAuthoredByState("ws-1", false); err != nil {
+ t.Fatalf("WriteCoAuthoredByState failed: %v", err)
+ }
+ if err := cache.ReconcileCoAuthoredByHookInCheckout(result.Path, "ws-1", false); err != nil {
+ t.Fatalf("ReconcileCoAuthoredByHookInCheckout failed: %v", err)
+ }
+
+ if _, err := os.Stat(hookPath); !os.IsNotExist(err) {
+ t.Errorf("expected the hook to be removed at %s, stat err=%v", hookPath, err)
+ }
+ if msg := commitInWorktree(t, result.Path, "b.txt", "after the toggle"); strings.Contains(msg, "Co-authored-by: multica-agent") {
+ t.Errorf("isolated checkout still adds the trailer after the toggle was turned off.\ngot:\n%s", msg)
+ }
+}
+
+// A linked worktree keeps its hook in the bare cache, where the cache-root
+// sweep already reconciles it. Reaching into the worktree would be reaching
+// into someone else's git dir, so the per-checkout path must ignore it.
+func TestReconcileCoAuthoredByHookInCheckoutIgnoresLinkedWorktree(t *testing.T) {
+ t.Parallel()
+ sourceRepo := createTestRepo(t)
+ cache := New(t.TempDir(), testLogger())
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {
+ t.Fatalf("sync failed: %v", err)
+ }
+
+ result, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: t.TempDir(),
+ AgentName: "Test Agent",
+ TaskID: "99999999-0000-0000-0000-000000000000",
+ CoAuthoredByEnabled: true,
+ })
+ if err != nil {
+ t.Fatalf("CreateWorktree failed: %v", err)
+ }
+
+ if err := cache.ReconcileCoAuthoredByHookInCheckout(result.Path, "ws-1", false); err != nil {
+ t.Fatalf("ReconcileCoAuthoredByHookInCheckout failed: %v", err)
+ }
+
+ // The bare cache's hook — the one that actually governs this worktree — is
+ // untouched by the per-checkout path.
+ if _, err := os.Stat(filepath.Join(cache.Lookup("ws-1", sourceRepo), "hooks", "prepare-commit-msg")); err != nil {
+ t.Errorf("per-checkout reconcile disturbed the bare cache's hook: %v", err)
+ }
+}
diff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.go
index 041f4b3c9d..d6b803d7ee 100644
--- a/server/internal/daemon/wakeup.go
+++ b/server/internal/daemon/wakeup.go
@@ -148,9 +148,10 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strin
// the workspace sync loop park on coarse tickers (5s and 30s) that do not
// observe the wakeup channel, so anything the server changed during the
// WS gap — task cancellation or runtime updates — stays invisible to
- // them until the next tick. Repository bindings and workspace settings
- // refresh when a checkout needs them. The reconcile broadcaster nudges
- // those loops to re-check immediately. broadcast() debounces back-to-back
+ // them until the next tick. The reconcile broadcaster nudges those loops to
+ // re-check immediately — including workspace settings, which the sync loop
+ // re-reads for tracked workspaces on reconcile precisely because a settings
+ // edit made during the gap left no hint behind (MUL-6921). broadcast() debounces back-to-back
// calls so a flapping connection cannot fan out into a request stampede.
if d.reconcile != nil {
d.reconcile.broadcast()
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index e2e2b6af74..ffbef83f0d 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -447,7 +447,11 @@ func (h *Handler) UpdateWorkspace(w http.ResponseWriter, r *http.Request) {
slog.Info("workspace updated", append(logger.RequestAttrs(r), "workspace_id", id)...)
userID := requestUserID(r)
h.publish(protocol.EventWorkspaceUpdated, uuidToString(ws.ID), "member", userID, map[string]any{"workspace": h.workspaceToResponse(ws)})
- if req.Name != nil {
+ // A rename changes what daemons display; a settings edit changes how they
+ // behave — the GitHub master switch and the Co-authored-by toggle are read
+ // from this JSONB. Daemons cache settings and have no other way to learn
+ // they moved, so both edits have to wake every member's daemons.
+ if req.Name != nil || req.Settings != nil {
if members, err := h.Queries.ListMembers(r.Context(), ws.ID); err == nil {
userIDs := make([]string, 0, len(members))
for _, member := range members {
diff --git a/server/internal/handler/workspace_test.go b/server/internal/handler/workspace_test.go
index 96f474e1a0..b9874c5b20 100644
--- a/server/internal/handler/workspace_test.go
+++ b/server/internal/handler/workspace_test.go
@@ -680,6 +680,66 @@ VALUES ($1, $2, 'owner')
}
}
+// recordingWorkspaceRefreshNotifier captures the daemon wakeups a workspace
+// write fans out to its members.
+type recordingWorkspaceRefreshNotifier struct {
+ userIDs []string
+}
+
+func (n *recordingWorkspaceRefreshNotifier) NotifyWorkspacesChanged(userID string) {
+ n.userIDs = append(n.userIDs, userID)
+}
+
+// Daemons cache workspace settings and read the GitHub master switch and the
+// Co-authored-by toggle from them. A settings edit that does not wake them
+// leaves the old verdict live until the workspace's next repo checkout, which
+// is how a disabled Co-authored-by trailer kept landing in commits (MUL-6921).
+func TestUpdateWorkspace_NotifiesDaemonsOnSettingsChange(t *testing.T) {
+ ctx := context.Background()
+
+ const slug = "handler-tests-settings-notify"
+ _, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)
+
+ wsID := dbfx.Insert(t, "workspace", testutil.Cols{
+ "name": "Handler Test Settings Notify",
+ "slug": slug,
+ "description": "UpdateWorkspace settings notification test",
+ })
+
+ dbfx.Exec(t, `
+INSERT INTO member (workspace_id, user_id, role)
+VALUES ($1, $2, 'owner')
+`, wsID, testUserID)
+
+ notifier := &recordingWorkspaceRefreshNotifier{}
+ previous := testHandler.DaemonWorkspaceRefresh
+ testHandler.DaemonWorkspaceRefresh = notifier
+ t.Cleanup(func() { testHandler.DaemonWorkspaceRefresh = previous })
+
+ req := newRequest("PATCH", "/api/workspaces/"+wsID, map[string]any{
+ "settings": map[string]any{"co_authored_by_enabled": false},
+ })
+ req = withURLParam(req, "id", wsID)
+ testutil.Call(t, testHandler.UpdateWorkspace, req).Want(http.StatusOK)
+
+ if len(notifier.userIDs) != 1 || notifier.userIDs[0] != testUserID {
+ t.Fatalf("settings update notified %v, want exactly the workspace member %s", notifier.userIDs, testUserID)
+ }
+
+ // An edit that touches neither the name nor the settings has nothing for
+ // daemons to re-read.
+ notifier.userIDs = nil
+ req2 := newRequest("PATCH", "/api/workspaces/"+wsID, map[string]any{
+ "description": "new description",
+ })
+ req2 = withURLParam(req2, "id", wsID)
+ testutil.Call(t, testHandler.UpdateWorkspace, req2).Want(http.StatusOK)
+
+ if len(notifier.userIDs) != 0 {
+ t.Fatalf("description-only update notified %v, want no daemon wakeup", notifier.userIDs)
+ }
+}
+
func TestUpdateWorkspace_ReposValidation(t *testing.T) {
ctx := context.Background()