Skip to content

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

Go

chore(server): remove 69 unreachable Go functions (MUL-9128) (#10453)

Jiayuan Zhang450792b9d78a
diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.go
index 7d11ffa660..0663abf04b 100644
--- a/server/cmd/server/notification_listeners.go
+++ b/server/cmd/server/notification_listeners.go
@@ -22,40 +22,6 @@ type mention struct {
ID string // user_id, agent_id, issue_id, or "all"
}
-// statusLabels maps DB status values to human-readable labels for notifications.
-var statusLabels = map[string]string{
- "backlog": "Backlog",
- "todo": "Todo",
- "in_progress": "In Progress",
- "in_review": "In Review",
- "done": "Done",
- "blocked": "Blocked",
- "cancelled": "Cancelled",
-}
-
-// priorityLabels maps DB priority values to human-readable labels for notifications.
-var priorityLabels = map[string]string{
- "urgent": "Urgent",
- "high": "High",
- "medium": "Medium",
- "low": "Low",
- "none": "No priority",
-}
-
-func statusLabel(s string) string {
- if l, ok := statusLabels[s]; ok {
- return l
- }
- return s
-}
-
-func priorityLabel(p string) string {
- if l, ok := priorityLabels[p]; ok {
- return l
- }
- return p
-}
-
var emptyDetails = []byte("{}")
// parseMentions extracts mentions from markdown content.
diff --git a/server/internal/cli/client.go b/server/internal/cli/client.go
index aa5030dc6b..e36a7e8d9a 100644
--- a/server/internal/cli/client.go
+++ b/server/internal/cli/client.go
@@ -817,29 +817,3 @@ func (c *APIClient) DownloadFile(ctx context.Context, downloadURL string) ([]byt
data, err := io.ReadAll(io.LimitReader(resp.Body, maxDownloadSize))
return data, wrapBodyRead(req, err)
}
-
-// HealthCheck hits the /health endpoint and returns the response body.
-func (c *APIClient) HealthCheck(ctx context.Context) (string, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"/health", nil)
- if err != nil {
- return "", err
- }
- resp, err := c.HTTPClient.Do(req)
- err = wrapTransport(req, err)
- if err != nil {
- return "", err
- }
- defer resp.Body.Close()
-
- data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
- if resp.StatusCode >= 400 {
- return "", &HTTPError{
- Method: http.MethodGet,
- Path: "/health",
- StatusCode: resp.StatusCode,
- Body: strings.TrimSpace(string(data)),
- TaskScoped: requestUsedTaskToken(resp),
- }
- }
- return strings.TrimSpace(string(data)), nil
-}
diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.go
index 76a3d648ae..3ab419d632 100644
--- a/server/internal/daemon/config_test.go
+++ b/server/internal/daemon/config_test.go
@@ -1631,18 +1631,6 @@ func pinNonCodexAgentsToMissingPaths(t *testing.T) {
// CLI config Backends.OpenClaw overrides (issue #3875)
// =============================================================================
-// writeCLIConfigForProfile is a minimal helper for the override tests:
-// stages a HOME, writes a config.json under the given profile (empty profile
-// = default), and returns the resolved path so tests can assert against it.
-func writeCLIConfigForProfile(t *testing.T, profile string, cfg cli.CLIConfig) {
- t.Helper()
- tmp := t.TempDir()
- redirectTestHome(t, tmp)
- if err := cli.SaveCLIConfigForProfile(cfg, profile); err != nil {
- t.Fatalf("write cli config: %v", err)
- }
-}
-
// TestApplyOpenclawOverride_DoesNothingWhenNil verifies the early-return
// path. A daemon started with no override should not Setenv anything; the
// existing probe / spawn flow remains undisturbed.
diff --git a/server/internal/daemon/execenv/git.go b/server/internal/daemon/execenv/git.go
index 227bb3de5f..ca4a85ba3a 100644
--- a/server/internal/daemon/execenv/git.go
+++ b/server/internal/daemon/execenv/git.go
@@ -1,162 +1,10 @@
package execenv
import (
- "fmt"
- "log/slog"
- "os"
- "os/exec"
- "path/filepath"
"regexp"
"strings"
- "time"
)
-// detectGitRepo checks if dir is inside a git repository (regular or bare).
-// Returns the git root path and true if found.
-func detectGitRepo(dir string) (string, bool) {
- // Try regular repo first.
- cmd := exec.Command("git", "-C", dir, "rev-parse", "--show-toplevel")
-
- if out, err := cmd.Output(); err == nil {
- return strings.TrimSpace(string(out)), true
- }
-
- // Try bare repo: git-dir is "." for bare repos when -C points at the repo.
- cmd = exec.Command("git", "-C", dir, "rev-parse", "--is-bare-repository")
-
- if out, err := cmd.Output(); err == nil && strings.TrimSpace(string(out)) == "true" {
- return dir, true
- }
-
- return "", false
-}
-
-// fetchOrigin runs `git fetch origin` to ensure the local repo has the latest remote refs.
-func fetchOrigin(gitRoot string) error {
- cmd := exec.Command("git", "-C", gitRoot, "fetch", "origin")
-
- if out, err := cmd.CombinedOutput(); err != nil {
- return fmt.Errorf("git fetch origin: %s: %w", strings.TrimSpace(string(out)), err)
- }
- return nil
-}
-
-// getRemoteDefaultBranch returns "origin/<branch>" for the remote's default branch.
-// Falls back to "origin/main", then "HEAD".
-func getRemoteDefaultBranch(gitRoot string) string {
- // Try symbolic-ref of origin/HEAD (set by `git clone` or `git remote set-head`).
- cmd := exec.Command("git", "-C", gitRoot, "symbolic-ref", "refs/remotes/origin/HEAD")
-
- if out, err := cmd.Output(); err == nil {
- ref := strings.TrimSpace(string(out))
- // ref looks like "refs/remotes/origin/main" — return "origin/main".
- if strings.HasPrefix(ref, "refs/remotes/") {
- return strings.TrimPrefix(ref, "refs/remotes/")
- }
- return ref
- }
-
- // Fallback: check if origin/main exists.
- cmd = exec.Command("git", "-C", gitRoot, "rev-parse", "--verify", "origin/main")
-
- if err := cmd.Run(); err == nil {
- return "origin/main"
- }
-
- // Fallback: check if origin/master exists.
- cmd = exec.Command("git", "-C", gitRoot, "rev-parse", "--verify", "origin/master")
-
- if err := cmd.Run(); err == nil {
- return "origin/master"
- }
-
- return "HEAD"
-}
-
-// setupGitWorktree creates a git worktree at worktreePath with a new branch.
-func setupGitWorktree(gitRoot, worktreePath, branchName, baseRef string) error {
- // Remove the workdir created by caller — git worktree add needs to create it.
- if err := os.Remove(worktreePath); err != nil && !os.IsNotExist(err) {
- return fmt.Errorf("remove placeholder workdir: %w", err)
- }
-
- err := runGitWorktreeAdd(gitRoot, worktreePath, branchName, baseRef)
- if err != nil && strings.Contains(err.Error(), "already exists") {
- // Branch name collision: append timestamp and retry once.
- branchName = fmt.Sprintf("%s-%d", branchName, time.Now().Unix())
- err = runGitWorktreeAdd(gitRoot, worktreePath, branchName, baseRef)
- }
- return err
-}
-
-func runGitWorktreeAdd(gitRoot, worktreePath, branchName, baseRef string) error {
- cmd := exec.Command("git", "-C", gitRoot, "worktree", "add", "-b", branchName, worktreePath, baseRef)
-
- if out, err := cmd.CombinedOutput(); err != nil {
- return fmt.Errorf("git worktree add: %s: %w", strings.TrimSpace(string(out)), err)
- }
- return nil
-}
-
-// removeGitWorktree removes a worktree and its branch. Best-effort: logs errors.
-func removeGitWorktree(gitRoot, worktreePath, branchName string, logger *slog.Logger) {
- // Remove the worktree.
- cmd := exec.Command("git", "-C", gitRoot, "worktree", "remove", "--force", worktreePath)
-
- if out, err := cmd.CombinedOutput(); err != nil {
- logger.Warn("execenv: git worktree remove failed", "output", strings.TrimSpace(string(out)), "error", err)
- }
-
- // Delete the branch (best-effort).
- if branchName != "" {
- cmd = exec.Command("git", "-C", gitRoot, "branch", "-D", branchName)
-
- if out, err := cmd.CombinedOutput(); err != nil {
- logger.Warn("execenv: git branch delete failed", "branch", branchName, "output", strings.TrimSpace(string(out)), "error", err)
- }
- }
-}
-
-// excludeFromGit adds a pattern to the worktree's .git/info/exclude file.
-func excludeFromGit(worktreePath, pattern string) error {
- // Resolve the actual git dir for this worktree.
- cmd := exec.Command("git", "-C", worktreePath, "rev-parse", "--git-dir")
-
- out, err := cmd.Output()
- if err != nil {
- return fmt.Errorf("resolve git dir: %w", err)
- }
-
- gitDir := strings.TrimSpace(string(out))
- if !filepath.IsAbs(gitDir) {
- gitDir = filepath.Join(worktreePath, gitDir)
- }
-
- excludePath := filepath.Join(gitDir, "info", "exclude")
-
- // Ensure the info directory exists.
- if err := os.MkdirAll(filepath.Dir(excludePath), 0o755); err != nil {
- return fmt.Errorf("create info dir: %w", err)
- }
-
- // Check if pattern is already present.
- existing, _ := os.ReadFile(excludePath)
- if strings.Contains(string(existing), pattern) {
- return nil
- }
-
- f, err := os.OpenFile(excludePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
- if err != nil {
- return fmt.Errorf("open exclude file: %w", err)
- }
- defer f.Close()
-
- if _, err := fmt.Fprintf(f, "\n%s\n", pattern); err != nil {
- return fmt.Errorf("write exclude pattern: %w", err)
- }
- return nil
-}
-
// repoNameFromURL extracts a short directory name from a git remote URL.
// e.g. "https://github.com/org/my-repo.git" → "my-repo"
func repoNameFromURL(url string) string {
diff --git a/server/internal/daemon/execenv/openclaw_config.go b/server/internal/daemon/execenv/openclaw_config.go
index 58b2269982..24690daed6 100644
--- a/server/internal/daemon/execenv/openclaw_config.go
+++ b/server/internal/daemon/execenv/openclaw_config.go
@@ -1218,19 +1218,6 @@ func openclawRegistryAgentsList(bin string, timeout time.Duration) ([]any, error
// to avoid spawning a real binary. Production code never reassigns it.
var openclawExec = execOpenclawCLI
-// openclawLastNonEmptyLine returns the last non-empty, trimmed line of out.
-// Used by openclawParseActiveConfigPath for the `config file` fallback, where the
-// path is the last line the CLI prints.
-func openclawLastNonEmptyLine(out string) string {
- lines := strings.Split(strings.TrimSpace(out), "\n")
- for i := len(lines) - 1; i >= 0; i-- {
- if trimmed := strings.TrimSpace(lines[i]); trimmed != "" {
- return trimmed
- }
- }
- return ""
-}
-
// openclawOutputComplete returns the rule that decides whether the bytes
// captured so far are a finished answer for this openclaw subcommand, for
// agent.RunCollectQuiet's early return.
diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.go
index 0b0e8d1045..46e919a7af 100644
--- a/server/internal/daemon/gc.go
+++ b/server/internal/daemon/gc.go
@@ -1666,14 +1666,6 @@ func (d *Daemon) pruneWorktreeLocked(ctx context.Context, barePath string) {
}
}
-func runGitGCCommand(barePath string, args ...string) (string, error) {
- return runGitGCCommandContext(context.Background(), barePath, args...)
-}
-
-func runGitCommand(barePath string, timeout time.Duration, args ...string) (string, error) {
- return runGitCommandContext(context.Background(), barePath, timeout, args...)
-}
-
func runGitGCCommandContext(ctx context.Context, barePath string, args ...string) (string, error) {
return runGitCommandContext(ctx, barePath, gitCmdTimeout, args...)
}
@@ -1754,10 +1746,6 @@ func (d *Daemon) cleanupNewRepoMaintenanceLocks(barePath string, before repoMain
}
}
-func agentWorktreeBranches(barePath string) (map[string]struct{}, error) {
- return agentWorktreeBranchesContext(context.Background(), barePath)
-}
-
func agentWorktreeBranchesContext(ctx context.Context, barePath string) (map[string]struct{}, error) {
out, err := runGitGCCommandContext(ctx, barePath, "worktree", "list", "--porcelain")
if err != nil {
@@ -1778,14 +1766,10 @@ func agentWorktreeBranchesContext(ctx context.Context, barePath string) (map[str
return branches, nil
}
-func listAgentBranches(barePath string) ([]string, error) {
- return listAgentBranchesContext(context.Background(), barePath)
-}
-
func listAgentBranchesContext(ctx context.Context, barePath string) ([]string, error) {
// Trailing slash narrows the pattern to the `agent/` namespace only. Without
// it, `for-each-ref` would also return a branch literally named `agent`,
- // which `agentWorktreeBranches` ignores — that branch would then be deleted.
+ // which `agentWorktreeBranchesContext` ignores — that branch would then be deleted.
out, err := runGitGCCommandContext(ctx, barePath, "for-each-ref", "--format=%(refname:short)", "refs/heads/agent/")
if err != nil {
return nil, err
diff --git a/server/internal/daemon/local_directory.go b/server/internal/daemon/local_directory.go
index 5880c14856..bdfbd68a20 100644
--- a/server/internal/daemon/local_directory.go
+++ b/server/internal/daemon/local_directory.go
@@ -6,7 +6,6 @@ import (
"errors"
"fmt"
"os"
- "os/exec"
"path/filepath"
"runtime"
"strings"
@@ -437,21 +436,6 @@ func checkDirReadWrite(dir string) error {
return nil
}
-// isGitWorkTree reports whether path is the working tree of a git repo. The
-// daemon uses this to skip branch / worktree machinery when the user has
-// already pointed the project at their own clone — the agent operates on
-// the current branch in place. Returns false on any error (git not on PATH,
-// path not in a repo, exec failure) so the caller can treat "not a git
-// tree" and "can't tell" the same way: skip the git-specific path.
-func isGitWorkTree(ctx context.Context, path string) bool {
- cmd := exec.CommandContext(ctx, "git", "-C", path, "rev-parse", "--is-inside-work-tree")
- out, err := cmd.Output()
- if err != nil {
- return false
- }
- return strings.TrimSpace(string(out)) == "true"
-}
-
// LocalPathLocker serialises agent tasks that share the same on-disk path.
// The lock is owned for the entire lifetime of a task (claim → context
// write → agent execution → result report), not just the agent execution
diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.go
index c391abe152..29031739a0 100644
--- a/server/internal/daemon/repocache/cache.go
+++ b/server/internal/daemon/repocache/cache.go
@@ -102,10 +102,6 @@ func runGitCombinedOutputContext(ctx context.Context, args ...string) ([]byte, e
return runGitCombinedOutputWithTimeoutContext(ctx, repoCacheGitTimeout, args...)
}
-func runGitCombinedOutputWithTimeout(timeout time.Duration, args ...string) ([]byte, error) {
- return runGitCombinedOutputWithTimeoutContext(context.Background(), timeout, args...)
-}
-
func runGitCombinedOutputWithTimeoutContext(parent context.Context, timeout time.Duration, args ...string) ([]byte, error) {
ctx, cancel := context.WithTimeout(parent, timeout)
defer cancel()
@@ -150,10 +146,6 @@ func runGitContext(ctx context.Context, args ...string) error {
return runGitWithTimeoutContext(ctx, repoCacheGitTimeout, args...)
}
-func runGitWithTimeout(timeout time.Duration, args ...string) error {
- return runGitWithTimeoutContext(context.Background(), timeout, args...)
-}
-
func runGitWithTimeoutContext(parent context.Context, timeout time.Duration, args ...string) error {
ctx, cancel := context.WithTimeout(parent, timeout)
defer cancel()
@@ -604,10 +596,6 @@ func isBareRepo(path string) bool {
// refs and abort the entire fetch.
const modernFetchRefspec = "+refs/heads/*:refs/remotes/origin/*"
-func gitCloneBare(url, dest string) error {
- return gitCloneBareContext(context.Background(), url, dest)
-}
-
func gitCloneBareContext(ctx context.Context, url, dest string) error {
args := append(caCloneArgs(), "clone", "--bare", url, dest)
if out, err := runGitCombinedOutputContext(ctx, args...); err != nil {
@@ -975,7 +963,7 @@ func (c *Cache) CreateWorktreeContext(ctx context.Context, params WorktreeParams
return result, nil
}
- // Create a new worktree. createWorktree may rename the branch to avoid
+ // Create a new worktree. createWorktreeContext may rename the branch to avoid
// collisions with stale per-task refs left over from previous runs.
actualBranch, err := createWorktreeContext(ctx, barePath, worktreePath, branchName, baseRef)
if err != nil {
@@ -1042,17 +1030,6 @@ const (
isolatedCacheRemoteName = "multica-cache"
)
-// createOrUpdateIsolatedCheckout keeps Git metadata inside the task workdir.
-// The fresh path uses a local clone, so immutable Git objects are hard-linked
-// (copied on Windows, see localCloneArgs) from the daemon's cache while refs,
-// index, logs, config, and new objects remain private to the task checkout.
-// The temporary cache remote is then replaced with the real repository URL so
-// an agent's normal fetch / push commands still target GitHub rather than the
-// daemon-owned bare cache.
-func (c *Cache) createOrUpdateIsolatedCheckout(barePath, repoURL, checkoutPath, branchName, baseRef string, fresh bool) (*WorktreeResult, error) {
- return c.createOrUpdateIsolatedCheckoutContext(context.Background(), barePath, repoURL, checkoutPath, branchName, baseRef, fresh)
-}
-
func (c *Cache) createOrUpdateIsolatedCheckoutContext(ctx context.Context, barePath, repoURL, checkoutPath, branchName, baseRef string, fresh bool) (*WorktreeResult, error) {
baseCommit, err := resolveCommitContext(ctx, barePath, baseRef)
if err != nil {
@@ -1130,10 +1107,6 @@ func (c *Cache) createOrUpdateIsolatedCheckoutContext(ctx context.Context, bareP
return &WorktreeResult{Path: checkoutPath, BranchName: actualBranch}, nil
}
-func removeLinkedWorktree(barePath, checkoutPath string) error {
- return removeLinkedWorktreeContext(context.Background(), barePath, checkoutPath)
-}
-
func removeLinkedWorktreeContext(ctx context.Context, barePath, checkoutPath string) error {
out, err := runGitOutputContext(ctx, "-C", checkoutPath, "rev-parse", "--git-common-dir")
if err != nil {
@@ -1271,10 +1244,6 @@ func createIsolatedCheckoutContext(ctx context.Context, barePath, repoURL, check
return actualBranch, nil
}
-func resolveCommit(repoPath, ref string) (string, error) {
- return resolveCommitContext(context.Background(), repoPath, ref)
-}
-
func resolveCommitContext(ctx context.Context, repoPath, ref string) (string, error) {
out, err := runGitOutputContext(ctx, "-C", repoPath, "rev-parse", "--verify", ref+"^{commit}")
if err != nil {
@@ -1319,15 +1288,6 @@ func isPartialCloneContext(ctx context.Context, repoPath string) bool {
return strings.TrimSpace(string(out)) == "true"
}
-// configurePromisorRemote marks origin as the promisor remote for a repository
-// whose object store is incomplete, so git lazily fetches missing blobs from
-// the real remote instead of failing. It mirrors the two config keys
-// `git clone --filter=blob:none` writes; `git clone --local` does not copy
-// them across, which is why they have to be restored by hand.
-func configurePromisorRemote(repoPath string) error {
- return configurePromisorRemoteContext(context.Background(), repoPath)
-}
-
func configurePromisorRemoteContext(ctx context.Context, repoPath string) error {
settings := [][2]string{
{"remote.origin.promisor", "true"},
@@ -1341,10 +1301,6 @@ func configurePromisorRemoteContext(ctx context.Context, repoPath string) error
return nil
}
-func setIsolatedCheckoutOrigin(path, repoURL string) error {
- return setIsolatedCheckoutOriginContext(context.Background(), path, repoURL)
-}
-
func setIsolatedCheckoutOriginContext(ctx context.Context, path, repoURL string) error {
out, err := runGitCombinedOutputContext(ctx, "-C", path, "remote", "set-url", "origin", repoURL)
if err != nil {
@@ -1353,14 +1309,6 @@ func setIsolatedCheckoutOriginContext(ctx context.Context, path, repoURL string)
return nil
}
-// syncIsolatedCheckoutRefs mirrors the cache's real origin/* and tag refs into
-// the task-local repository. It also fetches the selected base ref directly so
-// a reused checkout can move to a newly-fetched commit without depending on
-// the cache after this function returns.
-func syncIsolatedCheckoutRefs(barePath, checkoutPath, baseRef string) error {
- return syncIsolatedCheckoutRefsContext(context.Background(), barePath, checkoutPath, baseRef)
-}
-
func syncIsolatedCheckoutRefsContext(ctx context.Context, barePath, checkoutPath, baseRef string) error {
refspecs := []string{
"+refs/remotes/origin/*:refs/remotes/origin/*",
@@ -1377,26 +1325,10 @@ func syncIsolatedCheckoutRefsContext(ctx context.Context, barePath, checkoutPath
return nil
}
-// deleteAllLocalBranches removes the heads copied from the bare cache into a
-// fresh local clone. The clone is detached and has no task-created branches to
-// preserve yet.
-func deleteAllLocalBranches(repoPath string) error {
- return deleteAllLocalBranchesContext(context.Background(), repoPath)
-}
-
func deleteAllLocalBranchesContext(ctx context.Context, repoPath string) error {
return deleteLocalBranchesUnderContext(ctx, repoPath, "refs/heads/", nil)
}
-// deleteStaleAgentBranches prunes branches left by earlier Multica tasks while
-// preserving the current task branch, every user-created local branch, and
-// every agent branch holding commits no remote-tracking ref reaches. In an
-// isolated checkout that branch is the only copy of those commits; deleting it
-// would leave them to the reflog (MUL-7284).
-func deleteStaleAgentBranches(repoPath, keepBranch string) error {
- return deleteStaleAgentBranchesContext(context.Background(), repoPath, keepBranch)
-}
-
func deleteStaleAgentBranchesContext(ctx context.Context, repoPath, keepBranch string) error {
keepRef := "refs/heads/" + keepBranch
return deleteLocalBranchesUnderContext(ctx, repoPath, "refs/heads/agent/", func(ref string) (bool, error) {
@@ -1408,12 +1340,6 @@ func deleteStaleAgentBranchesContext(ctx context.Context, repoPath, keepBranch s
})
}
-// deleteLocalBranchesUnder deletes every branch under namespace that keep does
-// not claim. A nil keep deletes them all.
-func deleteLocalBranchesUnder(repoPath, namespace string, keep func(ref string) (bool, error)) error {
- return deleteLocalBranchesUnderContext(context.Background(), repoPath, namespace, keep)
-}
-
func deleteLocalBranchesUnderContext(ctx context.Context, repoPath, namespace string, keep func(ref string) (bool, error)) error {
out, err := runGitOutputContext(ctx, "-C", repoPath, "for-each-ref", "--format=%(refname)", namespace)
if err != nil {
@@ -1440,10 +1366,6 @@ func deleteLocalBranchesUnderContext(ctx context.Context, repoPath, namespace st
return nil
}
-func checkoutNewBranch(repoPath, branchName, baseRef string) (string, error) {
- return checkoutNewBranchContext(context.Background(), repoPath, branchName, baseRef)
-}
-
func checkoutNewBranchContext(ctx context.Context, repoPath, branchName, baseRef string) (string, error) {
out, err := runGitCombinedOutputContext(ctx, "-C", repoPath, "checkout", "-b", branchName, baseRef)
if err == nil {
@@ -1460,10 +1382,6 @@ func checkoutNewBranchContext(ctx context.Context, repoPath, branchName, baseRef
return branchName, nil
}
-func resolveBaseRef(barePath, requestedRef string) (string, error) {
- return resolveBaseRefContext(context.Background(), barePath, requestedRef)
-}
-
func resolveBaseRefContext(ctx context.Context, barePath, requestedRef string) (string, error) {
ref := strings.TrimSpace(requestedRef)
if ref == "" {
@@ -1485,27 +1403,16 @@ func resolveBaseRefContext(ctx context.Context, barePath, requestedRef string) (
return "", fmt.Errorf("cannot resolve requested ref %q in repo cache at %s", ref, barePath)
}
-func gitRefExists(repoPath, ref string) bool {
- return gitRefExistsContext(context.Background(), repoPath, ref)
-}
-
func gitRefExistsContext(ctx context.Context, repoPath, ref string) bool {
return runGitContext(ctx, "-C", repoPath, "rev-parse", "--verify", "--quiet", ref) == nil
}
-// createWorktree creates a git worktree at the given path with a new branch.
-// Returns the actual branch name used — which may differ from the requested
-// branchName if a collision was resolved by appending a timestamp suffix.
-func createWorktree(gitRoot, worktreePath, branchName, baseRef string) (string, error) {
- return createWorktreeContext(context.Background(), gitRoot, worktreePath, branchName, baseRef)
-}
-
func createWorktreeContext(ctx context.Context, gitRoot, worktreePath, branchName, baseRef string) (string, error) {
// Pre-check: if the worktree path already exists we would get a confusing
// "already exists" error from `git worktree add` — which used to be
// misclassified as a branch collision, causing the retry to leak branches
// into the bare repo. Fail cleanly here instead. The caller is expected
- // to route reused workdirs through updateExistingWorktree via isGitWorktree.
+ // to route reused workdirs through updateExistingWorktreeContext via isGitWorktree.
if _, err := os.Stat(worktreePath); err == nil {
return "", fmt.Errorf("worktree path already exists and is not a valid git worktree: %s", worktreePath)
}
@@ -1628,10 +1535,6 @@ func moveAside(path string) (string, error) {
return dest, nil
}
-func runWorktreeAdd(gitRoot, worktreePath, branchName, baseRef string) error {
- return runWorktreeAddContext(context.Background(), gitRoot, worktreePath, branchName, baseRef)
-}
-
func runWorktreeAddContext(ctx context.Context, gitRoot, worktreePath, branchName, baseRef string) error {
if out, err := runGitCombinedOutputContext(ctx, "-C", gitRoot, "worktree", "add", "-b", branchName, worktreePath, baseRef); err != nil {
return fmt.Errorf("git worktree add: %s: %w", strings.TrimSpace(string(out)), err)
@@ -1742,7 +1645,7 @@ func countUnpushedCommitsContext(ctx context.Context, repoPath, ref string) (int
// isTaskBranch reports whether branch is the one CreateWorktree gives the task
// that owns branchName: that name itself, or the timestamp-suffixed name a
-// branch collision retry picks (see updateExistingWorktree).
+// branch collision retry picks (see updateExistingWorktreeContext).
func isTaskBranch(branch, branchName string) bool {
if branch == branchName {
return true
@@ -1759,17 +1662,6 @@ func isTaskBranch(branch, branchName string) bool {
return true
}
-// updateExistingWorktree resets the worktree to a clean state and checks out a
-// new branch from the default branch, discarding uncommitted changes and
-// untracked files. Callers go through updateExistingCheckoutContext, which
-// reaches it only when that loses nothing or the caller asked for fresh. The
-// caller is responsible for fetching the bare cache beforehand (worktrees share
-// the same object store). Returns the actual branch name used (may differ from
-// input on collision).
-func updateExistingWorktree(worktreePath, branchName, baseRef string) (string, error) {
- return updateExistingWorktreeContext(context.Background(), worktreePath, branchName, baseRef)
-}
-
func updateExistingWorktreeContext(ctx context.Context, worktreePath, branchName, baseRef string) (string, error) {
// Discard any leftover uncommitted changes from the previous task.
if out, err := runGitCombinedOutputContext(ctx, "-C", worktreePath, "reset", "--hard"); err != nil {
@@ -1928,13 +1820,13 @@ func bareHeadBranchContext(ctx context.Context, barePath string) string {
}
// multicaHookMarker is a sentinel comment embedded in every prepare-commit-msg
-// hook installed by the daemon. removeCoAuthoredByHook uses it to recognize
+// hook installed by the daemon. removeCoAuthoredByHookContext 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
+// prepare-commit-msg hook as one the daemon installed. removeCoAuthoredByHookContext
// 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
@@ -2223,17 +2115,6 @@ 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.
-//
-// 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, statePath string) error {
out, err := runGitOutputContext(ctx, "-C", worktreePath, "rev-parse", "--git-common-dir")
if err != nil {
@@ -2300,16 +2181,6 @@ func isDaemonInstalledHook(contents []byte) bool {
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 {
- return removeCoAuthoredByHookContext(context.Background(), worktreePath)
-}
-
func removeCoAuthoredByHookContext(ctx context.Context, worktreePath string) error {
out, err := runGitOutputContext(ctx, "-C", worktreePath, "rev-parse", "--git-common-dir")
if err != nil {
@@ -2338,11 +2209,6 @@ func removeCoAuthoredByHookContext(ctx context.Context, worktreePath string) err
return nil
}
-// excludeFromGit adds a pattern to the worktree's .git/info/exclude file.
-func excludeFromGit(worktreePath, pattern string) error {
- return excludeFromGitContext(context.Background(), worktreePath, pattern)
-}
-
func excludeFromGitContext(ctx context.Context, worktreePath, pattern string) error {
out, err := runGitOutputContext(ctx, "-C", worktreePath, "rev-parse", "--git-dir")
if err != nil {
@@ -2434,13 +2300,3 @@ func taskKey(uuid string) string {
}
return s
}
-
-// shortID returns the first 8 characters of a UUID string (dashes stripped).
-// Display and logging only — see taskKey for anything that must be unique.
-func shortID(uuid string) string {
- s := strings.ReplaceAll(uuid, "-", "")
- if len(s) > 8 {
- return s[:8]
- }
- return s
-}
diff --git a/server/internal/daemon/repocache/cache_test.go b/server/internal/daemon/repocache/cache_test.go
index f48ce85eb8..a76c9db144 100644
--- a/server/internal/daemon/repocache/cache_test.go
+++ b/server/internal/daemon/repocache/cache_test.go
@@ -1756,7 +1756,7 @@ func TestEnsureRemoteTrackingLayoutMigratesLegacyCache(t *testing.T) {
// TestCreateWorktreePathCollisionDoesNotLeakBranch verifies the secondary bug
// fix: when the worktree path already exists as a non-worktree (e.g. a plain
-// directory), createWorktree must fail cleanly without leaking a branch into
+// directory), createWorktreeContext must fail cleanly without leaking a branch into
// the bare repo. Previously the "already exists" retry logic would
// misclassify path collisions as branch collisions and create a second
// timestamp-suffixed branch before hitting the same path error.
diff --git a/server/internal/handler/autopilot_webhook.go b/server/internal/handler/autopilot_webhook.go
index 25b7b3b045..015c64d1cb 100644
--- a/server/internal/handler/autopilot_webhook.go
+++ b/server/internal/handler/autopilot_webhook.go
@@ -882,34 +882,6 @@ func (h *Handler) finaliseDeliveryTerminal(
h.Metrics.RecordWebhookDelivery(h.deliveryProvider(r.Context(), id), status)
}
-// finaliseDeliveryWithRun records a delivery that produced (or was admission-
-// skipped to) an autopilot_run. Same response-capture as the terminal path.
-func (h *Handler) finaliseDeliveryWithRun(
- r *http.Request,
- id pgtype.UUID,
- status string,
- runID pgtype.UUID,
- httpStatus int,
- responseBody any,
-) {
- bodyJSON, _ := json.Marshal(responseBody)
- params := db.UpdateWebhookDeliveryDispatchedParams{
- ID: id,
- Status: status,
- AutopilotRunID: runID,
- ResponseStatus: pgtype.Int4{Int32: int32(httpStatus), Valid: true},
- ResponseBody: pgtype.Text{String: string(bodyJSON), Valid: true},
- }
- if _, err := h.Queries.UpdateWebhookDeliveryDispatched(r.Context(), params); err != nil {
- slog.Warn("webhook: finalise with run failed",
- "delivery_id", uuidToString(id),
- "run_id", uuidToString(runID),
- "error", err,
- )
- }
- h.Metrics.RecordWebhookDelivery(h.deliveryProvider(r.Context(), id), status)
-}
-
// deliveryProvider best-effort reads the provider for a delivery id so the
// webhook delivery metric carries useful provenance. On lookup failure we
// fall back to "generic" — the metric must always be incremented exactly
diff --git a/server/internal/handler/comment_list_test.go b/server/internal/handler/comment_list_test.go
index 120f2203c3..0890a0e19e 100644
--- a/server/internal/handler/comment_list_test.go
+++ b/server/internal/handler/comment_list_test.go
@@ -1401,19 +1401,6 @@ func TestListComments_ThreadTailNotFoundReturns404(t *testing.T) {
_ = fx
}
-// resolveCommentRow marks a comment resolved directly in the DB (test helper —
-// the public path goes through ResolveComment, but for list-filter tests we
-// just need the column set).
-func resolveCommentRow(t *testing.T, commentID string) {
- t.Helper()
- if _, err := testPool.Exec(context.Background(),
- `UPDATE comment SET resolved_at = now(), resolved_by_type = 'member', resolved_by_id = $2 WHERE id = $1`,
- commentID, testUserID,
- ); err != nil {
- t.Fatalf("resolve comment row: %v", err)
- }
-}
-
// TestCountNewCommentsSince_IssueWideExcludesAgentOwnAndTrigger pins the
// claim-side count query: it counts comments created after the given anchor
// ACROSS THE WHOLE ISSUE (every thread, not just the triggering one), excludes
diff --git a/server/internal/handler/comment_trigger_preview_test.go b/server/internal/handler/comment_trigger_preview_test.go
index 9e0fa71ce3..62ac22b6bd 100644
--- a/server/internal/handler/comment_trigger_preview_test.go
+++ b/server/internal/handler/comment_trigger_preview_test.go
@@ -126,19 +126,6 @@ func countQueuedCommentTriggerTasks(t *testing.T, issueID, agentID string) int {
return n
}
-func countCommentTriggerTasksWithStatus(t *testing.T, issueID, agentID, status string) int {
- t.Helper()
-
- var n int
- if err := testPool.QueryRow(context.Background(), `
- SELECT count(*) FROM agent_task_queue
- WHERE issue_id = $1 AND agent_id = $2 AND status = $3
- `, issueID, agentID, status).Scan(&n); err != nil {
- t.Fatalf("count %s tasks: %v", status, err)
- }
- return n
-}
-
func createCommentTriggerPreviewSquad(t *testing.T, name, leaderID string) string {
t.Helper()
diff --git a/server/internal/handler/daemon_runtime_access_test.go b/server/internal/handler/daemon_runtime_access_test.go
index 1a08a70a94..b4da6391bf 100644
--- a/server/internal/handler/daemon_runtime_access_test.go
+++ b/server/internal/handler/daemon_runtime_access_test.go
@@ -262,29 +262,6 @@ func TestBuildClaimedTaskResponseRejectsAgentReboundAfterClaim(t *testing.T) {
}
}
-// PUCK-89 blocker 1: the claim path reads the runtime BEFORE claiming, so a
-// concurrent re-registration can flip runtime.owner_id between that read and
-// final delivery. The final delivery gate must re-authorize against the
-// CURRENT owner inside the finalize transaction — the singular claim must not
-// return the task to the daemon, must settle it through the existing failure
-// path, and must keep the empty successful-poll response.
-// finalizeClaimDeliveryForTest drives the singular finalize+delivery path
-// (shared gate included) against a task already claimed out-of-band, so a test
-// can mutate the runtime between claim and finalize the way a concurrent
-// re-registration would in production.
-func (h *Handler) finalizeClaimDeliveryForTest(
- r *http.Request, task *db.AgentTaskQueue, runtimeID, runtimeWorkspaceID string,
-) (AgentTaskResponse, []pgtype.UUID, int, int, *claimBuildFailure, error) {
- runtime, err := h.Queries.GetAgentRuntimeForWorkspace(r.Context(), db.GetAgentRuntimeForWorkspaceParams{
- ID: parseUUID(runtimeID),
- WorkspaceID: parseUUID(runtimeWorkspaceID),
- })
- if err != nil {
- return AgentTaskResponse{}, nil, 0, 0, nil, fmt.Errorf("load runtime: %w", err)
- }
- return h.finalizeClaimDeliveryForTestWithRuntime(r, task, runtime, runtimeID, runtimeWorkspaceID)
-}
-
func (h *Handler) finalizeClaimDeliveryForTestWithRuntime(
r *http.Request, task *db.AgentTaskQueue, runtime db.AgentRuntime, runtimeID, runtimeWorkspaceID string,
) (AgentTaskResponse, []pgtype.UUID, int, int, *claimBuildFailure, error) {
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index 424dee27c4..1279f68b6f 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -1557,18 +1557,6 @@ func (h *Handler) DeleteAttachment(w http.ResponseWriter, r *http.Request) {
// Attachment linking
-// linkAttachmentsByIssueIDs links unbound attachments to an issue. A caller
-// that did not already advance the issue revision can ask this visible change
-// to advance it exactly once.
-func (h *Handler) linkAttachmentsByIssueIDs(ctx context.Context, issueID, workspaceID pgtype.UUID, ids []pgtype.UUID, bumpRevision bool) (db.LinkAttachmentsToIssueRow, error) {
- return h.Queries.LinkAttachmentsToIssue(ctx, db.LinkAttachmentsToIssueParams{
- IssueID: issueID,
- WorkspaceID: workspaceID,
- AttachmentIds: ids,
- BumpRevision: bumpRevision,
- })
-}
-
// attachmentOwnerLockAttempts bounds the re-read below. An attachment gains an
// owner once, when the issue or comment it was uploaded for links it, so one
// retry is enough in practice; the bound is what keeps a pathological
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 530f529cd4..60ebb5b588 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -827,19 +827,6 @@ func (h *Handler) NotifyRuntimeRecovered(_ context.Context, workspaceID string)
h.PublishRuntimeRefresh(workspaceID, "system", "", "heartbeat_recovery")
}
-// publishTask is publish() plus a TaskID hint so the realtime layer can route
-// the event to the per-task scope rather than the whole workspace.
-func (h *Handler) publishTask(eventType, workspaceID, actorType, actorID, taskID string, payload any) {
- h.Bus.Publish(events.Event{
- Type: eventType,
- WorkspaceID: workspaceID,
- ActorType: actorType,
- ActorID: actorID,
- TaskID: taskID,
- Payload: payload,
- })
-}
-
// publishChat is publish() plus the chat session routing hints. actorID must
// be the session's creator: every chat endpoint gates on creator ownership
// before publishing, and the realtime layer delivers the event to that user
diff --git a/server/internal/handler/inbox_issue_read_test.go b/server/internal/handler/inbox_issue_read_test.go
index 958629d63f..3a04bb5afc 100644
--- a/server/internal/handler/inbox_issue_read_test.go
+++ b/server/internal/handler/inbox_issue_read_test.go
@@ -160,21 +160,6 @@ func (f issueInboxFixture) openIssue() int64 {
return resp.Count
}
-// openInInbox is selecting the issue's row in the inbox: it renders the
-// group's newest row and marks that one read, which reads the whole issue.
-func (f issueInboxFixture) openInInbox() {
- f.t.Helper()
- var items []InboxItemResponse
- testutil.Call(f.t, inboxWorkspaceHandler(testHandler.ListInbox),
- inboxRequest(http.MethodGet, "/api/inbox", f.workspaceID)).
- Want(http.StatusOK).
- JSON(&items)
- if len(items) == 0 {
- f.t.Fatal("the inbox lists nothing for the issue")
- }
- f.markRead(items[0].ID)
-}
-
func (f issueInboxFixture) markRead(id string) {
f.t.Helper()
testutil.Call(f.t, inboxWorkspaceHandler(testHandler.MarkInboxRead),
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 4d8b366527..51ca0d85de 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -4533,21 +4533,6 @@ func (h *Handler) validateAssigneePair(ctx context.Context, r *http.Request, wor
}
}
-// shouldEnqueueAgentTask returns true when an issue creation or assignment
-// should trigger the assigned agent. Backlog issues are skipped — backlog
-// acts as a parking lot where issues can be pre-assigned without immediately
-// triggering execution. Moving out of backlog is handled separately in
-// UpdateIssue.
-func (h *Handler) shouldEnqueueAgentTask(ctx context.Context, issue db.Issue) bool {
- // Only the fixed backlog key parks work; custom unstarted statuses do not.
- // An issue in Triage is not parked but refused: it produces no run from any
- // entry point until it is accepted (MUL-7189 §2.3).
- if issue.TriageState.Valid || issuestatus.Effective(ctx, h.Queries, issue.WorkspaceID, issue.Status) == "backlog" {
- return false
- }
- return h.isAgentAssigneeReady(ctx, issue)
-}
-
// shouldEnqueueAssigneeFallback returns true when comment routing can fall back
// to the issue's assigned agent. Fires for any status — comments are
// conversational and can happen at any stage, including after completion
@@ -4620,34 +4605,6 @@ func (h *Handler) isAgentRunningOnIssue(r *http.Request, actorType string, issue
return uuidToString(task.IssueID) == uuidToString(issue.ID)
}
-// isAgentAssigneeReady checks if an issue is assigned to an active agent
-// with a valid runtime.
-func (h *Handler) isAgentAssigneeReady(ctx context.Context, issue db.Issue) bool {
- if !issue.AssigneeType.Valid || issue.AssigneeType.String != "agent" || !issue.AssigneeID.Valid {
- return false
- }
-
- agent, err := h.Queries.GetAgent(ctx, issue.AssigneeID)
- if err != nil {
- return false
- }
- // The shared verdict, not a local re-check (service.AgentReadiness). Only a
- // BLOCKED verdict stops the enqueue: an offline machine still queues,
- // because that work runs when the machine comes back.
- verdict, err := service.AgentReadiness(ctx, h.runtimeLookup(obsmetrics.RuntimeLookupSourceIssue), agent)
- if err != nil || !verdict.Blocked() {
- return err == nil
- }
- // Assignment has no response the assigner reads for this outcome, so a
- // refusal that needs human repair leaves the explanation on the issue
- // (MUL-6164). An unbound agent keeps its silent skip: the agent list
- // already shows it has no runtime, and nothing about it is new here.
- if service.RuntimeBlockedNeedsNotice(verdict.Reason) {
- h.noteRuntimeUnusable(ctx, issue, agent, verdict)
- }
- return false
-}
-
func (h *Handler) DeleteIssue(w http.ResponseWriter, r *http.Request) {
r = h.withWakeupActor(r)
id := chi.URLParam(r, "id")
diff --git a/server/internal/handler/issue_child_done_test.go b/server/internal/handler/issue_child_done_test.go
index f06030215e..b540a1324b 100644
--- a/server/internal/handler/issue_child_done_test.go
+++ b/server/internal/handler/issue_child_done_test.go
@@ -119,11 +119,6 @@ func countPendingTasksForAgent(t *testing.T, issueID, agentID string) int {
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running')`, issueID, agentID)
}
-func countInboxItems(t *testing.T, recipientUserID, issueID string) int {
- t.Helper()
- return dbfx.Count(t, `SELECT count(*) FROM inbox_item WHERE recipient_id = $1 AND issue_id = $2`, recipientUserID, issueID)
-}
-
// childDoneEntry is one timeline entry the rule wrote on the parent.
type childDoneEntry struct {
Stage *int32 `json:"stage"`
diff --git a/server/internal/handler/property.go b/server/internal/handler/property.go
index 6f3a563a42..db298682cb 100644
--- a/server/internal/handler/property.go
+++ b/server/internal/handler/property.go
@@ -291,14 +291,6 @@ func propertyOptionIDs(cfg PropertyConfig) map[string]int {
return ids
}
-func selectOptionsHint(cfg PropertyConfig) string {
- parts := make([]string, len(cfg.Options))
- for i, opt := range cfg.Options {
- parts[i] = fmt.Sprintf("%s (%s)", opt.ID, opt.Name)
- }
- return strings.Join(parts, ", ")
-}
-
// Actor values (MUL-6286)
// Compatibility aliases keep the focused handler tests on the same helper
@@ -306,7 +298,6 @@ func selectOptionsHint(cfg PropertyConfig) string {
type actorRef = issueproperty.ActorRef
func propertyTypeIsActor(t string) bool { return issueproperty.IsActor(t) }
-func actorKindsHint() string { return issueproperty.ActorKindsHint() }
func parseActorRef(s string) (actorRef, error) {
return issueproperty.ParseActorRef(s)
}
diff --git a/server/internal/handler/squad_comment_trigger_test.go b/server/internal/handler/squad_comment_trigger_test.go
index cc7bc4e465..0d74b1788c 100644
--- a/server/internal/handler/squad_comment_trigger_test.go
+++ b/server/internal/handler/squad_comment_trigger_test.go
@@ -50,11 +50,6 @@ func shouldEnqueueSquadLeaderOnCommentForTest(ctx context.Context, issue db.Issu
return triggersContainIssueAssigneeSquadLeader(triggers)
}
-func shouldEnqueueSquadLeaderOnReplyForTest(ctx context.Context, issue db.Issue, content string, parent *db.Comment, authorType, authorID string) bool {
- triggers, _ := testHandler.computeCommentAgentTriggers(ctx, issue, content, parent, authorType, authorID, commentTriggerComputeOptions{})
- return triggersContainIssueAssigneeSquadLeader(triggers)
-}
-
func triggersContainIssueAssigneeSquadLeader(triggers []commentAgentTrigger) bool {
for _, trigger := range triggers {
if trigger.Source == commentTriggerSourceIssueAssignee && trigger.Squad != nil {
diff --git a/server/internal/handler/trigger_test.go b/server/internal/handler/trigger_test.go
index 63c014c90e..751d1f4f19 100644
--- a/server/internal/handler/trigger_test.go
+++ b/server/internal/handler/trigger_test.go
@@ -34,10 +34,6 @@ func issueWithAgentAssignee() db.Issue {
}
}
-func issueNoAssignee() db.Issue {
- return db.Issue{}
-}
-
func TestHasAgentOrSquadMention(t *testing.T) {
tests := []struct {
name string
diff --git a/server/internal/handler/webhook_rate_limiter.go b/server/internal/handler/webhook_rate_limiter.go
index 5025b126c5..3fdac2cc83 100644
--- a/server/internal/handler/webhook_rate_limiter.go
+++ b/server/internal/handler/webhook_rate_limiter.go
@@ -279,12 +279,6 @@ return 1
var webhookLimiterCheckScript = redis.NewScript(webhookLimiterCheckSrc)
-// webhookLimiterAllowSource exposes the script body for tests that want to
-// assert structural invariants (e.g. trim before count before insert)
-// without spinning up a real Redis. Lower-cased "Source" makes the
-// test-only intent explicit.
-func webhookLimiterAllowSource() string { return webhookLimiterAllowSrc }
-
type redisWebhookRateLimiter struct {
cfg SlidingWindowRateLimit
rdb redis.UniversalClient
diff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.go
index a3750e9250..1e788eff59 100644
--- a/server/internal/integrations/channel/engine/router_test.go
+++ b/server/internal/integrations/channel/engine/router_test.go
@@ -258,12 +258,6 @@ func (f *fakeMedia) HasMedia(_ channel.InboundMessage) bool {
return !f.noMedia
}
-func (f *fakeMedia) resolvedMessageID() pgtype.UUID {
- f.mu.Lock()
- defer f.mu.Unlock()
- return f.lastMessageID
-}
-
func (f *fakeMedia) ResolveMedia(ctx context.Context, _ ResolvedInstallation, _ ResolvedIdentity, _ pgtype.UUID, chatMessageID pgtype.UUID, msg channel.InboundMessage) channel.InboundMessage {
f.mu.Lock()
f.count++
diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.go
index 5acc5f57e9..5326cfbc5f 100644
--- a/server/internal/integrations/channel/engine/session.go
+++ b/server/internal/integrations/channel/engine/session.go
@@ -224,17 +224,6 @@ type SessionTitles struct {
Fallback string
}
-func (t SessionTitles) forType(ct channel.ChatType) string {
- switch ct {
- case channel.ChatTypeGroup:
- return t.Group
- case channel.ChatTypeP2P:
- return t.Direct
- default:
- return t.Fallback
- }
-}
-
// ChatSession is the shared chat-session service. One instance is built per
// channel_type (so the binding rows carry the right discriminator); the logic
// is otherwise platform-neutral.
diff --git a/server/internal/integrations/lark/registration_service.go b/server/internal/integrations/lark/registration_service.go
index 56180e0402..e83e348e06 100644
--- a/server/internal/integrations/lark/registration_service.go
+++ b/server/internal/integrations/lark/registration_service.go
@@ -805,10 +805,6 @@ func (s *RegistrationService) liveOwnerConflictMessage(ctx context.Context, requ
}
}
-func (s *RegistrationService) gcDeadline() time.Time {
- return s.cfg.Now().Add(s.cfg.SessionTTL)
-}
-
// ErrRegistrationSessionNotFound is what the service returns for
// unknown / GC'd sessions. The handler maps it to 404.
var ErrRegistrationSessionNotFound = errors.New("lark registration: session not found")
diff --git a/server/internal/integrations/lark/registration_test.go b/server/internal/integrations/lark/registration_test.go
index 1b6a3136b9..68ff21fb21 100644
--- a/server/internal/integrations/lark/registration_test.go
+++ b/server/internal/integrations/lark/registration_test.go
@@ -60,15 +60,6 @@ func (f *registrationFake) stubBegin(resp map[string]any) {
})
}
-// rewriteHandler replaces /oauth/v1/app/registration with a fresh
-// handler — used to install a poll script after Begin has been
-// exercised.
-func (f *registrationFake) rewriteHandler(h http.HandlerFunc) {
- f.mux = http.NewServeMux()
- f.mux.HandleFunc(registrationEndpoint, h)
- f.srv.Config.Handler = f.mux
-}
-
func TestRegistrationClient_Begin_HappyPath(t *testing.T) {
fake := newRegistrationFake(t)
fake.stubBegin(map[string]any{
@@ -511,11 +502,11 @@ func TestRegistrationClient_Poll_DomainSwitchOnFeishuTenant(t *testing.T) {
// gate flips on only one side.
func TestRegistrationClient_Poll_NoSwitchWhenAlreadyOnMatchingHost(t *testing.T) {
cases := []struct {
- name string
- brand string
- begunOn string
- feishuHost string
- larkHost string
+ name string
+ brand string
+ begunOn string
+ feishuHost string
+ larkHost string
}{
{
name: "lark brand on lark host is a no-op",
diff --git a/server/internal/integrations/telegram/outbound.go b/server/internal/integrations/telegram/outbound.go
index 842a2ab3e3..1479688669 100644
--- a/server/internal/integrations/telegram/outbound.go
+++ b/server/internal/integrations/telegram/outbound.go
@@ -1704,31 +1704,6 @@ func (s *chatSchedule) backoffSnapshot() time.Time {
return time.Unix(0, nanos)
}
-// runScheduled waits for the chat's edit interval and any Telegram 429
-// retry_after window. Terminal delivery retries 429 responses until the event
-// context expires; other errors remain non-retriable to avoid duplicates.
-func (o *Outbound) runScheduled(ctx context.Context, schedule *chatSchedule, operation func() error) error {
- for {
- now := o.now()
- available := o.terminalAvailableAt(schedule, schedule.key.botKey, now)
- if delay := available.Sub(now); delay > 0 {
- if err := o.wait(ctx, delay); err != nil {
- return err
- }
- }
- err := operation()
- if retry, ok := retryAfter(err); ok {
- schedule.setBackoffTill(o.now().Add(retry))
- continue
- }
- if err == nil {
- schedule.lastEdit = o.now()
- schedule.setBackoffTill(time.Time{})
- }
- return err
- }
-}
-
func waitForOutbound(ctx context.Context, delay time.Duration) error {
if sleepCtx(ctx, delay) {
return nil
diff --git a/server/internal/issueguard/duplicate.go b/server/internal/issueguard/duplicate.go
index b5e10ab1f0..df35e6a50c 100644
--- a/server/internal/issueguard/duplicate.go
+++ b/server/internal/issueguard/duplicate.go
@@ -3,7 +3,6 @@ package issueguard
import (
"context"
"errors"
- "fmt"
"strings"
"time"
@@ -22,26 +21,6 @@ func DuplicateMessage(identifier, title, status string) string {
return "Active duplicate issue exists: " + identifier + " " + title + " (status: " + status + "). Set allow_duplicate=true or use --allow-duplicate to create another."
}
-type ActiveDuplicateError struct {
- ID string
- Identifier string
- Title string
- Status string
-}
-
-func (e *ActiveDuplicateError) Error() string {
- return DuplicateMessage(e.Identifier, e.Title, e.Status)
-}
-
-func NewActiveDuplicateError(issue db.Issue, issuePrefix string) *ActiveDuplicateError {
- return &ActiveDuplicateError{
- ID: util.UUIDToString(issue.ID),
- Identifier: fmt.Sprintf("%s-%d", issuePrefix, issue.Number),
- Title: issue.Title,
- Status: issue.Status,
- }
-}
-
// inactiveStatusKeys are the status keys the duplicate guards never count as an
// active duplicate: the terminal categories.
//
diff --git a/server/internal/issuestatus/issuestatus.go b/server/internal/issuestatus/issuestatus.go
index c808c1f056..4f0f34cfb0 100644
--- a/server/internal/issuestatus/issuestatus.go
+++ b/server/internal/issuestatus/issuestatus.go
@@ -396,30 +396,6 @@ func Effective(ctx context.Context, q Querier, workspaceID pgtype.UUID, status s
return customBehavior(status, entry.Category)
}
-// EffectiveAndName resolves a status to BOTH its behavior and its display name
-// in one catalog read, for payload builders that need the pair.
-//
-// Two separate calls would double the query on every background event carrying
-// a custom status. Same fail-safe direction as Effective: an unresolvable key
-// yields the key unchanged and an empty name.
-//
-// The name is empty for a built-in on purpose — clients localize those from the
-// key, so echoing the seeded English one would be the single string a
-// non-English workspace has to ignore. (MUL-6749)
-func EffectiveAndName(ctx context.Context, q Querier, workspaceID pgtype.UUID, status string) (string, string) {
- if IsBuiltIn(status) {
- return status, ""
- }
- entry, err := q.GetIssueStatusEntryByKey(ctx, db.GetIssueStatusEntryByKeyParams{
- WorkspaceID: workspaceID,
- Key: status,
- })
- if err != nil {
- return status, ""
- }
- return customBehavior(status, entry.Category), entry.Name
-}
-
// Category resolves a status to its four-value lifecycle category.
// Unknown keys return empty so callers never guess at lifecycle
// behavior when a catalog read fails.
@@ -436,9 +412,12 @@ func CategoryWithError(ctx context.Context, q Querier, workspaceID pgtype.UUID,
return category, err
}
-// CategoryAndName is the payload-oriented counterpart to EffectiveAndName.
-// It shares one catalog read while returning the public category rather than
-// the internal behavior projection.
+// CategoryAndName resolves a status to its public lifecycle category and its
+// display name in one catalog read.
+//
+// The name is empty for a built-in on purpose — clients localize those from the
+// key, so echoing the seeded English one would be the single string a
+// non-English workspace has to ignore. (MUL-6749)
func CategoryAndName(ctx context.Context, q Querier, workspaceID pgtype.UUID, status string) (string, string) {
category, name, _ := categoryAndName(ctx, q, workspaceID, status)
return category, name
diff --git a/server/internal/issueworkflow/issueworkflow.go b/server/internal/issueworkflow/issueworkflow.go
index 8fe6249617..f5c1a9b014 100644
--- a/server/internal/issueworkflow/issueworkflow.go
+++ b/server/internal/issueworkflow/issueworkflow.go
@@ -139,17 +139,6 @@ func keysOf(steps []Step) []string {
return keys
}
-// MiddleKeys returns the workflow's own steps, without the fixed statuses.
-func MiddleKeys(keys []string) []string {
- out := make([]string, 0, len(keys))
- for _, key := range keys {
- if !IsFixed(key) {
- out = append(out, key)
- }
- }
- return out
-}
-
// BuiltInDefaultKeys is Default before a workspace stores its own.
func BuiltInDefaultKeys() []string {
return ArrangeKeys([]string{issuestatus.Backlog, issuestatus.InProgress, issuestatus.InReview, issuestatus.Blocked})
diff --git a/server/internal/metrics/labels_pr3.go b/server/internal/metrics/labels_pr3.go
index 1e0772417e..f7b4fbd60c 100644
--- a/server/internal/metrics/labels_pr3.go
+++ b/server/internal/metrics/labels_pr3.go
@@ -407,21 +407,6 @@ func NormalizeCloudRuntimeStatus(value string) string {
return "error"
}
-// CloudRuntimeStatusForCode maps an HTTP status code to its bucket label.
-// Used by cloudruntime client instrumentation.
-func CloudRuntimeStatusForCode(code int) string {
- switch {
- case code >= 200 && code < 400:
- return "ok"
- case code >= 400 && code < 500:
- return "4xx"
- case code >= 500 && code < 600:
- return "5xx"
- default:
- return "error"
- }
-}
-
func NormalizeDaemonWSKind(value string) string {
return normalizeFromAllowList(value, knownDaemonWSKinds, "other")
}
diff --git a/server/internal/metrics/pricing_test.go b/server/internal/metrics/pricing_test.go
index 9cc281ce67..d87bea3529 100644
--- a/server/internal/metrics/pricing_test.go
+++ b/server/internal/metrics/pricing_test.go
@@ -295,7 +295,7 @@ func TestGrokPricingMatchesRecordedTurn(t *testing.T) {
// Captured payload: inputTokens 12929, cachedReadTokens 10880,
// outputTokens 29, totalTokens 12958, costUsdTicks 75360000. Grok counts
// the cached prefix inside inputTokens, so the uncached remainder is
- // 12929 - 10880 = 2049 (see excludeACPCachedInput in pkg/agent/hermes.go).
+ // 12929 - 10880 = 2049 (see normalizeACPTokenUsage in pkg/agent/acp_usage.go).
const (
uncachedInput = int64(2049)
cacheRead = int64(10880)
diff --git a/server/internal/middleware/owner_lookup_test.go b/server/internal/middleware/owner_lookup_test.go
index a971b76d77..e250ed8e3c 100644
--- a/server/internal/middleware/owner_lookup_test.go
+++ b/server/internal/middleware/owner_lookup_test.go
@@ -6,7 +6,6 @@ import (
"testing"
"time"
- "github.com/jackc/pgx/v5/pgtype"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -141,12 +140,3 @@ func TestOwnerLookupFor_DBError(t *testing.T) {
t.Fatalf("DB error must not look like ErrNoRows, got %v", err)
}
}
-
-// uuidToStringForOwnerLookup avoids depending on the existing
-// uuidToString helper here in case its signature changes; the
-// fixtures only need the canonical hyphenated form.
-//
-//nolint:unused // referenced via seedOwnerLookupUser indirectly.
-func uuidToStringForOwnerLookup(u pgtype.UUID) string {
- return uuidToString(u)
-}
diff --git a/server/internal/service/issue.go b/server/internal/service/issue.go
index f1424c3a29..88fd072a8c 100644
--- a/server/internal/service/issue.go
+++ b/server/internal/service/issue.go
@@ -981,9 +981,6 @@ func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue,
// path does the same test through agentAssigneeVerdict, which also tells it
// WHY a refusal happened; this one runs inside the create transaction, where
// there is nothing to tell anyone yet.
-//
-// Mirrors handler.shouldEnqueueAgentTask; kept here to make the service
-// self-contained, since both code paths must move together.
func (s *IssueService) shouldEnqueueAgentTaskWithQueries(ctx context.Context, q *db.Queries, issue db.Issue) bool {
// Resolved through q, not s.Queries: this runs inside the create
// transaction and must see the same snapshot as the rest of it. (MUL-6243)
diff --git a/server/internal/service/plugin_event_dispatch_test.go b/server/internal/service/plugin_event_dispatch_test.go
index 9720ecd2ac..613f4888ab 100644
--- a/server/internal/service/plugin_event_dispatch_test.go
+++ b/server/internal/service/plugin_event_dispatch_test.go
@@ -7,9 +7,7 @@ import (
"time"
"github.com/multica-ai/multica/server/internal/events"
- "github.com/multica-ai/multica/server/internal/featureflags"
db "github.com/multica-ai/multica/server/pkg/db/generated"
- "github.com/multica-ai/multica/server/pkg/featureflag"
"github.com/multica-ai/multica/server/pkg/plugincontract"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -246,12 +244,6 @@ func TestNewDispatcherDoesNotTouchTheDatabase(t *testing.T) {
dispatcher.sweepOnce()
}
-func testFlagService(enabled bool) *featureflag.Service {
- provider := featureflag.NewStaticProvider()
- provider.Set(featureflags.PluginsV1, featureflag.Rule{Default: enabled})
- return featureflag.NewService(provider)
-}
-
// Nil flags read as disabled. A deployment that never wired the flag service
// must not have outbound hooks enabled by that omission.
func TestEventDispatchTreatsMissingFlagsAsDisabled(t *testing.T) {
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 2d9643168d..31c725a989 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -4412,7 +4412,7 @@ func (s *TaskService) PromoteDueDeferredTasksForRuntime(ctx context.Context, run
// maybeLogClaimSlow emits one structured log per ClaimTask call when its total
// latency exceeds 300ms, so the prod tail can be diagnosed without flooding
// logs at normal poll rates. Called via defer so it captures the full path
-// including post-claim updateAgentStatus / broadcastTaskDispatch (both of
+// including post-claim ReconcileAgentStatus / broadcastTaskDispatch (both of
// which can hit the DB) and any error exit.
func (s *TaskService) maybeLogClaimSlow(agentID pgtype.UUID, outcome string, start time.Time, getAgentMs, countRunningMs, claimAgentMs, reanchorMs, updateStatusMs, dispatchMs int64) {
totalMs := time.Since(start).Milliseconds()
@@ -7145,17 +7145,6 @@ func (s *TaskService) ReconcileAgentStatus(ctx context.Context, agentID pgtype.U
s.publishAgentStatus(agent)
}
-func (s *TaskService) updateAgentStatus(ctx context.Context, agentID pgtype.UUID, status string) {
- agent, err := s.Queries.UpdateAgentStatus(ctx, db.UpdateAgentStatusParams{
- ID: agentID,
- Status: status,
- })
- if err != nil {
- return
- }
- s.publishAgentStatus(agent)
-}
-
func (s *TaskService) publishAgentStatus(agent db.Agent) {
s.Bus.Publish(events.Event{
Type: protocol.EventAgentStatus,
diff --git a/server/pkg/agent/acp_usage.go b/server/pkg/agent/acp_usage.go
index 92a619aff7..56f6d356aa 100644
--- a/server/pkg/agent/acp_usage.go
+++ b/server/pkg/agent/acp_usage.go
@@ -235,10 +235,6 @@ func parseACPTokenUsageSnapshotFromMeta(meta json.RawMessage) acpUsageSnapshot {
return preferred.withFallback(parseACPTokenUsageSnapshot(meta))
}
-func parseACPTokenUsageFromMeta(meta json.RawMessage) TokenUsage {
- return parseACPTokenUsageSnapshotFromMeta(meta).TokenUsage
-}
-
// normalizeACPTokenUsage re-buckets a usage record whose inputTokens already
// contains cachedReadTokens, so the persisted buckets stay mutually exclusive
// and dashboard cost math does not charge the cached prefix twice.
@@ -258,11 +254,6 @@ func normalizeACPTokenUsage(usage TokenUsage, totalTokens int64) (TokenUsage, bo
return usage, true
}
-func excludeACPCachedInput(usage TokenUsage, totalTokens int64) TokenUsage {
- normalized, _ := normalizeACPTokenUsage(usage, totalTokens)
- return normalized
-}
-
func acpUsageInt64(fields map[string]json.RawMessage, names ...string) (int64, bool) {
for _, name := range names {
raw, ok := fields[name]
diff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.go
index d162a979e6..a04f3a4714 100644
--- a/server/pkg/agent/kimi.go
+++ b/server/pkg/agent/kimi.go
@@ -621,7 +621,7 @@ const kimiUsageRecordType = "usage.record"
// fields sum exactly to the `used` figure kimi reports over ACP (22530 and
// 22566). So `inputOther` is uncached input only and maps straight onto
// TokenUsage.InputTokens with no cached-prefix subtraction — unlike the ACP
-// `inputTokens` case excludeACPCachedInput exists to correct.
+// `inputTokens` case normalizeACPTokenUsage exists to correct.
type kimiWireUsage struct {
Type string `json:"type"`
// Time is the record's epoch-millisecond write time. It is what keeps a