Skip to content

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

Go

fix(daemon): remove Co-authored-by hook when workspace setting is off (#2035)

Bohan Jiang3dc3e49a4751
diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.go
index ec3a918304..968a6a0208 100644
--- a/server/internal/daemon/repocache/cache.go
+++ b/server/internal/daemon/repocache/cache.go
@@ -439,11 +439,19 @@ func (c *Cache) CreateWorktree(params WorktreeParams) (*WorktreeResult, error) {
_ = excludeFromGit(worktreePath, pattern)
}
- // Install Co-authored-by hook for Multica Agent attribution (if enabled).
+ // Install or remove the Co-authored-by hook based on the workspace
+ // 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 := installCoAuthoredByHook(worktreePath); err != nil {
c.logger.Warn("repo checkout: install co-authored-by hook failed (non-fatal)", "error", err)
}
+ } else {
+ if err := removeCoAuthoredByHook(worktreePath); err != nil {
+ c.logger.Warn("repo checkout: remove co-authored-by hook failed (non-fatal)", "error", err)
+ }
}
c.logger.Info("repo checkout: existing worktree updated",
@@ -471,11 +479,17 @@ func (c *Cache) CreateWorktree(params WorktreeParams) (*WorktreeResult, error) {
_ = excludeFromGit(worktreePath, pattern)
}
- // Install Co-authored-by hook for Multica Agent attribution (if enabled).
+ // 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 := installCoAuthoredByHook(worktreePath); err != nil {
c.logger.Warn("repo checkout: install co-authored-by hook failed (non-fatal)", "error", err)
}
+ } else {
+ if err := removeCoAuthoredByHook(worktreePath); err != nil {
+ c.logger.Warn("repo checkout: remove co-authored-by hook failed (non-fatal)", "error", err)
+ }
}
c.logger.Info("repo checkout: worktree created",
@@ -728,9 +742,29 @@ func bareHeadBranch(barePath string) string {
return ref
}
+// multicaHookMarker is a sentinel comment embedded in every prepare-commit-msg
+// hook installed by the daemon. removeCoAuthoredByHook uses it to recognize
+// hooks it owns so it never deletes a hook installed by the user or another
+// tool. Do not change without bumping the recognition logic.
+const multicaHookMarker = "# multica:prepare-commit-msg:co-authored-by"
+
+// daemonInstalledHookSignatures lists substrings that identify a
+// prepare-commit-msg hook as one the daemon installed. removeCoAuthoredByHook
+// treats a hook as Multica-owned if its content contains ANY of these
+// substrings. The list deliberately includes the legacy comment that the
+// daemon used before multicaHookMarker existed, so disabling the toggle on
+// existing installations still cleans up old hooks seeded by previous daemon
+// versions. Add to this list — never remove from it — so future tweaks to
+// prepareCommitMsgHook keep recognizing every previously-shipped variant.
+var daemonInstalledHookSignatures = []string{
+ multicaHookMarker,
+ "# 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
+# 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.
@@ -780,6 +814,55 @@ func installCoAuthoredByHook(worktreePath string) error {
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
+// signature, so a user-installed hook at the same path is left alone.
+func isDaemonInstalledHook(contents []byte) bool {
+ body := string(contents)
+ for _, sig := range daemonInstalledHookSignatures {
+ if strings.Contains(body, sig) {
+ return true
+ }
+ }
+ return false
+}
+
+// removeCoAuthoredByHook removes the prepare-commit-msg hook installed by
+// installCoAuthoredByHook. It only deletes the file when the content matches
+// a known daemon signature (current marker or any previously released hook
+// content), so a user-installed prepare-commit-msg hook is never touched.
+// Returns nil when no hook is present or when an unrelated hook occupies
+// the path.
+func removeCoAuthoredByHook(worktreePath string) error {
+ cmd := exec.Command("git", "-C", worktreePath, "rev-parse", "--git-common-dir")
+ out, err := cmd.Output()
+ if err != nil {
+ return fmt.Errorf("resolve git common dir: %w", err)
+ }
+ commonDir := strings.TrimSpace(string(out))
+ if !filepath.IsAbs(commonDir) {
+ commonDir = filepath.Join(worktreePath, commonDir)
+ }
+
+ hookPath := filepath.Join(commonDir, "hooks", "prepare-commit-msg")
+ contents, err := os.ReadFile(hookPath)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return fmt.Errorf("read prepare-commit-msg hook: %w", err)
+ }
+ if !isDaemonInstalledHook(contents) {
+ // Unrelated hook (user or third-party): leave it alone.
+ return nil
+ }
+ if err := os.Remove(hookPath); err != nil && !os.IsNotExist(err) {
+ return fmt.Errorf("remove prepare-commit-msg hook: %w", err)
+ }
+ return nil
+}
+
// excludeFromGit adds a pattern to the worktree's .git/info/exclude file.
func excludeFromGit(worktreePath, pattern string) error {
cmd := exec.Command("git", "-C", worktreePath, "rev-parse", "--git-dir")
diff --git a/server/internal/daemon/repocache/cache_test.go b/server/internal/daemon/repocache/cache_test.go
index 971ef8b305..f41b141ac0 100644
--- a/server/internal/daemon/repocache/cache_test.go
+++ b/server/internal/daemon/repocache/cache_test.go
@@ -1158,6 +1158,210 @@ func TestCoAuthoredByHookIdempotent(t *testing.T) {
}
}
+// TestCreateWorktreeRemovesCoAuthoredByHookWhenDisabled verifies the toggle-off
+// path: a bare cache that already carries the Multica prepare-commit-msg hook
+// (e.g. from a prior worktree created with the setting on) must drop the hook
+// when the next CreateWorktree call passes CoAuthoredByEnabled=false.
+// Otherwise commits keep getting the trailer even after the user disables the
+// workspace setting.
+func TestCreateWorktreeRemovesCoAuthoredByHookWhenDisabled(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)
+ }
+
+ // First worktree: setting enabled → hook installed in the bare cache's
+ // shared hooks dir.
+ workDir1 := t.TempDir()
+ if _, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: workDir1,
+ AgentName: "Test Agent",
+ TaskID: "11111111-0000-0000-0000-000000000000",
+ CoAuthoredByEnabled: true,
+ }); err != nil {
+ t.Fatalf("CreateWorktree (enabled) failed: %v", err)
+ }
+
+ barePath := cache.Lookup("ws-1", sourceRepo)
+ hookPath := filepath.Join(barePath, "hooks", "prepare-commit-msg")
+ if _, err := os.Stat(hookPath); err != nil {
+ t.Fatalf("precondition: expected hook to be installed at %s: %v", hookPath, err)
+ }
+
+ // Second worktree on the same bare cache: setting disabled → hook must
+ // be removed and a commit in the new worktree must NOT carry the
+ // trailer.
+ workDir2 := t.TempDir()
+ result, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: workDir2,
+ AgentName: "Test Agent",
+ TaskID: "22222222-0000-0000-0000-000000000000",
+ CoAuthoredByEnabled: false,
+ })
+ if err != nil {
+ t.Fatalf("CreateWorktree (disabled) failed: %v", err)
+ }
+
+ if _, err := os.Stat(hookPath); !os.IsNotExist(err) {
+ t.Errorf("expected hook to be removed at %s, stat err=%v", hookPath, err)
+ }
+
+ if err := os.WriteFile(filepath.Join(result.Path, "test.txt"), []byte("hello\n"), 0o644); err != nil {
+ t.Fatalf("write test file: %v", err)
+ }
+ runGitAuthored(t, result.Path, "add", ".")
+ runGitAuthored(t, result.Path, "commit", "-m", "test commit")
+
+ out, err := exec.Command("git", "-C", result.Path, "log", "-1", "--format=%B").Output()
+ if err != nil {
+ t.Fatalf("git log failed: %v", err)
+ }
+ commitMsg := string(out)
+ if strings.Contains(commitMsg, "Co-authored-by: multica-agent") {
+ t.Errorf("commit unexpectedly carries the Co-authored-by trailer with setting disabled.\ngot:\n%s", commitMsg)
+ }
+}
+
+// TestCreateWorktreeRemovesLegacyCoAuthoredByHook verifies the migration
+// path: bare clones already on disk from previous daemon versions carry a
+// prepare-commit-msg hook that does NOT include the multicaHookMarker
+// sentinel — only the older `# Installed by the Multica daemon.` comment.
+// Toggling the workspace setting off must still remove those legacy hooks,
+// otherwise users who flip the toggle in production keep seeing the trailer
+// indefinitely (the exact bug reported in MUL-1704).
+func TestCreateWorktreeRemovesLegacyCoAuthoredByHook(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)
+ }
+
+ // Seed the bare cache with the exact hook content shipped by the
+ // previous daemon release (no multicaHookMarker line). Keeping a
+ // verbatim copy here means the test fails if recognition logic ever
+ // drifts away from what production hosts actually have on disk.
+ const legacyHook = `#!/bin/sh
+# 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"
+`
+
+ barePath := cache.Lookup("ws-1", sourceRepo)
+ hooksDir := filepath.Join(barePath, "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(legacyHook), 0o755); err != nil {
+ t.Fatalf("seed legacy hook: %v", err)
+ }
+
+ workDir := t.TempDir()
+ result, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: workDir,
+ AgentName: "Test Agent",
+ TaskID: "44444444-0000-0000-0000-000000000000",
+ CoAuthoredByEnabled: false,
+ })
+ if err != nil {
+ t.Fatalf("CreateWorktree (disabled) failed: %v", err)
+ }
+
+ if _, err := os.Stat(hookPath); !os.IsNotExist(err) {
+ t.Errorf("expected legacy hook to be removed at %s, stat err=%v", hookPath, err)
+ }
+
+ if err := os.WriteFile(filepath.Join(result.Path, "test.txt"), []byte("hello\n"), 0o644); err != nil {
+ t.Fatalf("write test file: %v", err)
+ }
+ runGitAuthored(t, result.Path, "add", ".")
+ runGitAuthored(t, result.Path, "commit", "-m", "test commit")
+
+ out, err := exec.Command("git", "-C", result.Path, "log", "-1", "--format=%B").Output()
+ if err != nil {
+ t.Fatalf("git log failed: %v", err)
+ }
+ if commitMsg := string(out); strings.Contains(commitMsg, "Co-authored-by: multica-agent") {
+ t.Errorf("commit unexpectedly carries the Co-authored-by trailer after legacy hook removal.\ngot:\n%s", commitMsg)
+ }
+}
+
+// TestRemoveCoAuthoredByHookPreservesUserHook verifies that the disable path
+// only deletes hooks installed by the daemon. A prepare-commit-msg hook
+// without the Multica marker (e.g. one a user added manually) must be left
+// untouched even when CoAuthoredByEnabled=false.
+func TestRemoveCoAuthoredByHookPreservesUserHook(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)
+ }
+
+ barePath := cache.Lookup("ws-1", sourceRepo)
+ hooksDir := filepath.Join(barePath, "hooks")
+ if err := os.MkdirAll(hooksDir, 0o755); err != nil {
+ t.Fatalf("create hooks dir: %v", err)
+ }
+ hookPath := filepath.Join(hooksDir, "prepare-commit-msg")
+ userHook := "#!/bin/sh\n# user hook, not Multica\nexit 0\n"
+ if err := os.WriteFile(hookPath, []byte(userHook), 0o755); err != nil {
+ t.Fatalf("seed user hook: %v", err)
+ }
+
+ workDir := t.TempDir()
+ if _, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: workDir,
+ AgentName: "Test Agent",
+ TaskID: "33333333-0000-0000-0000-000000000000",
+ CoAuthoredByEnabled: false,
+ }); err != nil {
+ t.Fatalf("CreateWorktree (disabled) failed: %v", err)
+ }
+
+ got, err := os.ReadFile(hookPath)
+ if err != nil {
+ t.Fatalf("user hook unexpectedly removed: %v", err)
+ }
+ if string(got) != userHook {
+ t.Errorf("user hook contents changed.\nwant:\n%s\ngot:\n%s", userHook, string(got))
+ }
+}
+
// TestGetRemoteDefaultBranchAmbiguousOriginReturnsEmpty verifies step 4's
// safe-scan gating: when the cache has multiple refs/remotes/origin/*
// entries, none match the common defaults, and none match the bare HEAD