Skip to content

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

Go

MUL-6846: feat(cli): expose active and cross-issue agent runs on `issue runs` (#7922)

Bohan Jiang9fce92f42769
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 30999597b0..8df361e2be 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -701,6 +701,23 @@ multica issue runs <issue-id>
multica issue runs <issue-id> --full-id
multica issue runs <issue-id> --output json
+# Only work in flight (queued / dispatched / running / waiting_local_directory)
+multica issue runs <issue-id> --active --output json
+
+# ...and across the sub-issue family: the issue's parent (or itself, when it has
+# no parent) plus every child of that parent, each row labelled with its issue.
+# Answers "is another agent already working next to me?" before you start
+# overlapping code or PR work. Advisory only — it reserves nothing.
+#
+# Returns a compact per-run row — task_id, issue_id, issue_identifier,
+# issue_title, agent_id, status, created_at, started_at — not the full
+# execution-log record. Follow a task_id with `issue run-messages` for detail.
+#
+# Ordered running-first, newest-first within a status, capped at 20 rows. When
+# the cap truncates the answer the server sets X-Active-Runs-Truncated and the
+# CLI warns on stderr, so a short list is never mistaken for a complete one.
+multica issue runs <issue-id> --siblings --output json
+
# View messages for a specific execution run
multica issue run-messages <task-id>
multica issue run-messages <short-task-id> --issue <issue-id>
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index a9daa9d3b7..0dc5b28346 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -318,11 +318,22 @@ var issueSubscriberRemoveCmd = &cobra.Command{
// Execution history subcommands.
+// headerActiveRunsTruncated mirrors handler.HeaderActiveRunsTruncated. Declared
+// as a literal rather than imported because the CLI does not depend on the
+// handler package (same convention as headerTimelineTruncated in
+// `issue timeline`).
+const headerActiveRunsTruncated = "X-Active-Runs-Truncated"
+
var issueRunsCmd = &cobra.Command{
Use: "runs <issue-id>",
Short: "List execution history for an issue",
- Args: exactArgs(1),
- RunE: runIssueRuns,
+ Long: "List agent task runs for an issue.\n\n" +
+ "Defaults to this issue's full execution history, newest first. Narrow it to " +
+ "work in flight with --active, or widen it across the sub-issue family with " +
+ "--siblings when you need to know whether another agent is already working " +
+ "next to you.",
+ Args: exactArgs(1),
+ RunE: runIssueRuns,
}
var issueRunMessagesCmd = &cobra.Command{
@@ -566,6 +577,8 @@ func init() {
// issue runs
issueRunsCmd.Flags().String("output", "table", "Output format: table or json")
issueRunsCmd.Flags().Bool("full-id", false, "Show full task UUIDs in table output")
+ issueRunsCmd.Flags().Bool("active", false, "Only in-flight runs (queued, dispatched, running, waiting_local_directory) instead of the full execution history. Answers \"is an agent working on this right now\" without pulling every past run.")
+ issueRunsCmd.Flags().Bool("siblings", false, "Widen to this issue's sub-issue family — its parent (or itself, when it has no parent) plus every child of that parent — so you can see whether another run is already working alongside you before starting overlapping code or PR work. Implies --active. Returns a compact per-run row (task, issue, agent, status, started) rather than the full execution-log record. Ordered running-first, newest-first within a status, and capped at 20 rows; when the cap truncates the answer the CLI says so on stderr, so a short list is never mistaken for a complete one. Advisory only: it reports work in flight, it does not reserve or serialise anything.")
// issue usage
issueUsageCmd.Flags().String("output", "table", "Output format: table or json")
@@ -2146,10 +2159,38 @@ func runIssueRuns(cmd *cobra.Command, args []string) error {
return fmt.Errorf("resolve issue: %w", err)
}
+ activeOnly, _ := cmd.Flags().GetBool("active")
+ siblings, _ := cmd.Flags().GetBool("siblings")
+
+ params := url.Values{}
+ if siblings {
+ // The server implies active for a family read, so --siblings alone is
+ // enough; sending both keeps the request self-describing.
+ params.Set("scope", "family")
+ params.Set("active", "true")
+ } else if activeOnly {
+ params.Set("active", "true")
+ }
+
+ path := "/api/issues/" + issueRef.ID + "/task-runs"
+ if len(params) > 0 {
+ path += "?" + params.Encode()
+ }
+
var runs []map[string]any
- if err := client.GetJSON(ctx, "/api/issues/"+issueRef.ID+"/task-runs", &runs); err != nil {
+ respHeaders, err := client.GetJSONWithHeaders(ctx, path, &runs)
+ if err != nil {
return fmt.Errorf("list runs: %w", err)
}
+ // A truncated coordination read and a complete one look identical in the
+ // body, and reading the first as the second is exactly the wrong
+ // conclusion: "no run on that sibling" when the answer was simply cut off.
+ // Same stderr convention as the comment-list paging cursors.
+ if respHeaders.Get(headerActiveRunsTruncated) == "true" {
+ fmt.Fprintln(os.Stderr,
+ "warning: active runs truncated by the server cap: more runs are in flight than this read returns. "+
+ "\"No run on that issue\" cannot be concluded from this read.")
+ }
output, _ := cmd.Flags().GetString("output")
if output == "json" {
@@ -2158,6 +2199,32 @@ func runIssueRuns(cmd *cobra.Command, args []string) error {
actors := loadActorDisplayLookup(ctx, client)
fullID, _ := cmd.Flags().GetBool("full-id")
+
+ // The family read returns a different, deliberately smaller row than the
+ // execution log — no completed_at or error, because every row in it is
+ // still in flight — and it spans issues, so it needs a column saying which.
+ // On a single-issue read that column would repeat the argument on every
+ // line, so it stays off there.
+ if siblings {
+ headers := []string{"TASK", "ISSUE", "AGENT", "STATUS", "STARTED"}
+ rows := make([][]string, 0, len(runs))
+ for _, r := range runs {
+ started := strVal(r, "started_at")
+ if len(started) >= 16 {
+ started = started[:16]
+ }
+ rows = append(rows, []string{
+ displayID(strVal(r, "task_id"), fullID),
+ strVal(r, "issue_identifier"),
+ actors.agent(strVal(r, "agent_id")),
+ strVal(r, "status"),
+ started,
+ })
+ }
+ cli.PrintTable(os.Stdout, headers, rows)
+ return nil
+ }
+
headers := []string{"ID", "AGENT", "STATUS", "STARTED", "COMPLETED", "ERROR"}
rows := make([][]string, 0, len(runs))
for _, r := range runs {
diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.go
index 9b9726ebcb..8f8bad44bb 100644
--- a/server/cmd/multica/cmd_issue_test.go
+++ b/server/cmd/multica/cmd_issue_test.go
@@ -4011,3 +4011,206 @@ func TestIsTerminalChildIssue(t *testing.T) {
})
}
}
+
+// `issue runs` answers three different questions off one endpoint, and the only
+// thing telling them apart is the query string the CLI builds (#7768). These
+// tests pin that translation: a plain read must stay a plain read — the
+// short-task-ID resolver and the execution log both depend on the unfiltered
+// history — while --active and --siblings must actually reach the server.
+
+// newIssueRunsTestCmd mirrors the real flag set registered on issueRunsCmd.
+func newIssueRunsTestCmd(t *testing.T, output string) *cobra.Command {
+ t.Helper()
+ cmd := &cobra.Command{Use: "runs"}
+ cmd.Flags().String("output", output, "")
+ cmd.Flags().Bool("full-id", false, "")
+ cmd.Flags().Bool("active", false, "")
+ cmd.Flags().Bool("siblings", false, "")
+ return cmd
+}
+
+func TestRunIssueRunsScopeFlagsBuildQuery(t *testing.T) {
+ issueID := "1881a167-4bb6-4602-944b-f40ce4192fe6"
+
+ for _, tc := range []struct {
+ name string
+ flags []string
+ want url.Values
+ }{
+ // No flags means no params: the resolver and the sidebar read the same
+ // full history they always have.
+ {"default reads full history", nil, url.Values{}},
+ {"active narrows to in-flight", []string{"active"}, url.Values{"active": {"true"}}},
+ // --siblings implies active. The CLI sends both so the request says what
+ // it means without the reader having to know the server's default.
+ {"siblings widens to the family", []string{"siblings"},
+ url.Values{"scope": {"family"}, "active": {"true"}}},
+ {"siblings wins over a redundant active", []string{"siblings", "active"},
+ url.Values{"scope": {"family"}, "active": {"true"}}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var gotQuery url.Values
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/issues/" + issueID + "/task-runs":
+ gotQuery = r.URL.Query()
+ _ = json.NewEncoder(w).Encode([]map[string]any{})
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueRunsTestCmd(t, "json")
+ for _, flag := range tc.flags {
+ if err := cmd.Flags().Set(flag, "true"); err != nil {
+ t.Fatalf("set --%s: %v", flag, err)
+ }
+ }
+ if _, err := captureStdout(t, func() error { return runIssueRuns(cmd, []string{issueID}) }); err != nil {
+ t.Fatalf("issue runs: %v", err)
+ }
+
+ if len(gotQuery) != len(tc.want) {
+ t.Fatalf("query = %v, want %v", gotQuery, tc.want)
+ }
+ for key, want := range tc.want {
+ if got := gotQuery.Get(key); got != want[0] {
+ t.Fatalf("query %s = %q, want %q (full query %v)", key, got, want[0], gotQuery)
+ }
+ }
+ })
+ }
+}
+
+// The two modes return different payloads, so they render through different
+// column sets. The family row names its issue — without that the table is a
+// list of task ids the reader cannot attribute, which is the whole question
+// --siblings answers — and it drops COMPLETED / ERROR, which are empty on
+// every row of a read that only returns work still in flight.
+func TestRunIssueRunsSiblingsTableRendersFamilyColumns(t *testing.T) {
+ issueID := "1881a167-4bb6-4602-944b-f40ce4192fe6"
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/issues/" + issueID + "/task-runs":
+ if r.URL.Query().Get("scope") == "family" {
+ _ = json.NewEncoder(w).Encode([]map[string]any{{
+ "task_id": "abcd1234-0000-0000-0000-000000000000",
+ "issue_id": "5678abcd-0000-0000-0000-000000000000",
+ "issue_identifier": "MUL-7001",
+ "issue_title": "sibling work",
+ "agent_id": "agent-1",
+ "status": "running",
+ "created_at": "2026-09-02T07:00:00Z",
+ "started_at": "2026-09-02T07:00:01Z",
+ }})
+ return
+ }
+ _ = json.NewEncoder(w).Encode([]map[string]any{{
+ "id": "abcd1234-0000-0000-0000-000000000000", "agent_id": "agent-1",
+ "status": "completed", "error": "boom",
+ }})
+ default:
+ // Actor lookups for the AGENT column are best-effort; 404 is fine.
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueRunsTestCmd(t, "table")
+ if err := cmd.Flags().Set("siblings", "true"); err != nil {
+ t.Fatalf("set --siblings: %v", err)
+ }
+ out, err := captureStdout(t, func() error { return runIssueRuns(cmd, []string{issueID}) })
+ if err != nil {
+ t.Fatalf("issue runs: %v", err)
+ }
+ // The task id has to survive the new payload's task_id key — reading `id`
+ // here would render a column of blanks and lose the run-messages target.
+ for _, want := range []string{"TASK", "ISSUE", "MUL-7001", "abcd1234"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("family table missing %q:\n%s", want, out)
+ }
+ }
+ for _, unwanted := range []string{"COMPLETED", "ERROR"} {
+ if strings.Contains(out, unwanted) {
+ t.Fatalf("family table carries %q, which is empty on every in-flight row:\n%s", unwanted, out)
+ }
+ }
+
+ // The execution log keeps its own columns: same command, different question.
+ plain := newIssueRunsTestCmd(t, "table")
+ out, err = captureStdout(t, func() error { return runIssueRuns(plain, []string{issueID}) })
+ if err != nil {
+ t.Fatalf("issue runs: %v", err)
+ }
+ if strings.Contains(out, "ISSUE") {
+ t.Fatalf("single-issue table should not carry an issue column:\n%s", out)
+ }
+ if !strings.Contains(out, "ERROR") || !strings.Contains(out, "boom") {
+ t.Fatalf("execution log lost its error column:\n%s", out)
+ }
+}
+
+// A capped family read and a complete one are identical in the body. If the CLI
+// swallows the server's truncation header, an agent reads "no run on that
+// sibling" off a list that was simply cut off — the one wrong conclusion this
+// command exists to prevent.
+func TestRunIssueRunsWarnsOnTruncatedFamilyRead(t *testing.T) {
+ issueID := "1881a167-4bb6-4602-944b-f40ce4192fe6"
+
+ for _, tc := range []struct {
+ name string
+ truncated bool
+ }{
+ {"truncated read warns", true},
+ {"complete read stays quiet", false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/issues/" + issueID + "/task-runs":
+ if tc.truncated {
+ w.Header().Set(headerActiveRunsTruncated, "true")
+ }
+ _ = json.NewEncoder(w).Encode([]map[string]any{{
+ "id": "abcd1234-0000-0000-0000-000000000000", "status": "running",
+ }})
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueRunsTestCmd(t, "json")
+ if err := cmd.Flags().Set("siblings", "true"); err != nil {
+ t.Fatalf("set --siblings: %v", err)
+ }
+
+ capture := captureStderr(t)
+ _, err := captureStdout(t, func() error { return runIssueRuns(cmd, []string{issueID}) })
+ stderr := capture.read()
+ if err != nil {
+ t.Fatalf("issue runs: %v", err)
+ }
+
+ warned := strings.Contains(stderr, "truncated")
+ if warned != tc.truncated {
+ t.Fatalf("warned = %v, want %v; stderr was %q", warned, tc.truncated, stderr)
+ }
+ })
+ }
+}
diff --git a/server/cmd/server/cors_headers_test.go b/server/cmd/server/cors_headers_test.go
index dcc4a647fd..414bd3d6e2 100644
--- a/server/cmd/server/cors_headers_test.go
+++ b/server/cmd/server/cors_headers_test.go
@@ -32,8 +32,8 @@ func TestCORSAllowedHeaders_IncludeIdempotencyKey(t *testing.T) {
}
}
-// Timeline and comment-list endpoints report defensive hard-cap clamps with
-// custom response headers.
+// Timeline, comment-list and active-run reads report defensive hard-cap clamps
+// with custom response headers.
// Custom response headers are not readable from browser JS unless the server
// exposes them, and only the CORS-safelisted headers are exposed by default — so
// an entry missing here is not a degraded signal, it is no signal at all: the
@@ -42,6 +42,7 @@ func TestCORSExposedHeaders_IncludeTruncationSignals(t *testing.T) {
for _, want := range []string{
handler.HeaderCommentsTruncated,
handler.HeaderTimelineTruncated,
+ handler.HeaderActiveRunsTruncated,
} {
if !slices.Contains(corsExposedHeaders, want) {
t.Errorf("%s missing from CORS exposed headers: %v", want, corsExposedHeaders)
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 9e6ce3d7f9..57999739be 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -96,6 +96,7 @@ var corsExposedHeaders = []string{
"X-Request-ID",
handler.HeaderCommentsTruncated,
handler.HeaderTimelineTruncated,
+ handler.HeaderActiveRunsTruncated,
}
func registerPluginActionRoutes(r chi.Router, h *handler.Handler) {
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 6c3df1603c..c8b36be247 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -4880,7 +4880,76 @@ func (h *Handler) CancelTask(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
-// ListTasksByIssue returns all tasks (any status) for an issue — used for execution history.
+// familyActiveRunCap bounds a scope=family read.
+//
+// It is a response-size budget set to the shape of the normal case — a handful
+// of runs in flight at once (maintainer call, MUL-6846) — NOT a bound derived
+// from how much work can really be in flight. A family can legitimately exceed
+// it by a lot: a single agent may be configured up to
+// agentconfig.MaxMaxConcurrentTasks (50) on its own, this feature exists
+// precisely for the case where SEVERAL agents work a family at once, and the
+// returned set includes queued / dispatched / waiting_local_directory rows,
+// which no execution-slot limit bounds at all — a parent that fans out 200
+// children can have 200 of them enqueued.
+//
+// So truncation here is an ordinary outcome, not a pathological one, and that
+// is exactly why it must be reported. A cap that truncated silently would be
+// worse than no cap: "I saw no run on that sibling" and "the answer was cut
+// off" would look identical, and an agent would read the second as the first.
+// The handler asks for one row more than it will return and sets
+// HeaderActiveRunsTruncated when that extra row comes back. The query orders
+// running-first, so what the budget drops is the least decision-relevant.
+const familyActiveRunCap = 20
+
+// HeaderActiveRunsTruncated tells a caller its coordination read hit
+// familyActiveRunCap and is therefore an incomplete picture of who is working
+// in this family. Same shape and convention as HeaderTimelineTruncated: the
+// signal rides a header because the response body is a bare array that existing
+// callers parse positionally.
+const HeaderActiveRunsTruncated = "X-Active-Runs-Truncated"
+
+// ActiveRunSummary is one in-flight run as the coordination read reports it:
+// which issue, which agent, what state, since when, and the task id to follow
+// up with `multica issue run-messages`.
+//
+// Deliberately NOT AgentTaskResponse. That type is the execution log's row —
+// result, work_dir, attribution, coalesced comment ids — and it costs roughly
+// 5x the bytes of this one. A caller asking "is anyone working next to me?"
+// reads none of those fields, and it is an agent spending its own context on
+// the answer, so the payload is cut to what the question needs.
+//
+// It is also not ActiveSiblingRunData, which the daemon claim payload uses.
+// That one describes the claiming agent's OWN other runs, so it has no agent
+// field; this read spans agents, and which agent is on a sibling is the answer.
+// Sharing one struct across both would put an optional field on it that only
+// one caller ever sets — the exact shape this change removed from
+// AgentTaskResponse.
+type ActiveRunSummary struct {
+ TaskID string `json:"task_id"`
+ IssueID string `json:"issue_id"`
+ IssueIdentifier string `json:"issue_identifier"`
+ IssueTitle string `json:"issue_title"`
+ AgentID string `json:"agent_id"`
+ Status string `json:"status"`
+ CreatedAt string `json:"created_at"`
+ StartedAt *string `json:"started_at,omitempty"`
+}
+
+// ListTasksByIssue returns tasks for an issue — the execution history behind
+// the issue-detail sidebar, and the coordination reads behind
+// `multica issue runs --active` / `--siblings`.
+//
+// Two optional query params narrow or widen it; with neither, the response is
+// byte-identical to what it has always been (full history, newest first), which
+// is what the UI and the CLI's short-task-ID resolver both depend on:
+//
+// - active=true — restrict to in-flight statuses, the same set the
+// issue-detail "agent live" banner calls active.
+// - scope=family — widen from this issue to its sub-issue family: the
+// issue's parent (or the issue itself, when it has no parent) plus every
+// child of that parent. Implies active=true, because a full execution
+// history across a whole family is unbounded and answers no question anyone
+// asked.
func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {
issueID := chi.URLParam(r, "id")
issue, ok := h.loadIssueForUser(w, r, issueID)
@@ -4888,13 +4957,88 @@ func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {
return
}
- tasks, err := h.Queries.ListTasksByIssue(r.Context(), issue.ID)
+ scope := r.URL.Query().Get("scope")
+ if scope != "" && scope != "issue" && scope != "family" {
+ writeError(w, http.StatusBadRequest, "scope must be 'issue' or 'family'")
+ return
+ }
+ // Parse rather than compare. `active=tru` answering with the full history
+ // under a 200 is the same silent-downgrade failure the unknown-scope check
+ // above rejects: the caller asked who is here NOW and would be handed every
+ // run that ever finished, which reads as "nobody is here" only after it has
+ // paid for the whole log. Same shape as the comment-list boolean params.
+ activeOnly := false
+ if activeStr := r.URL.Query().Get("active"); activeStr != "" {
+ switch activeStr {
+ case "true":
+ activeOnly = true
+ case "false":
+ default:
+ writeError(w, http.StatusBadRequest, "invalid active parameter; expected boolean")
+ return
+ }
+ }
+
+ workspaceID := uuidToString(issue.WorkspaceID)
+
+ if scope == "family" {
+ // Root the family at the parent when there is one, so a child sees its
+ // siblings; at the issue itself otherwise, so a parent sees its children
+ // and a standalone issue degenerates to its own active runs. One rule,
+ // both directions.
+ root := issue.ID
+ if issue.ParentIssueID.Valid {
+ root = issue.ParentIssueID
+ }
+ // One row beyond the cap, so a full page can be told apart from a
+ // truncated one without a second count query.
+ rows, err := h.Queries.ListActiveTasksByIssueFamily(r.Context(), db.ListActiveTasksByIssueFamilyParams{
+ WorkspaceID: issue.WorkspaceID,
+ RootIssueID: root,
+ RowLimit: familyActiveRunCap + 1,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list tasks")
+ return
+ }
+ if len(rows) > familyActiveRunCap {
+ rows = rows[:familyActiveRunCap]
+ w.Header().Set(HeaderActiveRunsTruncated, "true")
+ }
+ summaries := make([]ActiveRunSummary, len(rows))
+ for i, row := range rows {
+ summaries[i] = ActiveRunSummary{
+ TaskID: uuidToString(row.TaskID),
+ IssueID: uuidToString(row.IssueID),
+ // Rows span several issues here, so each one has to carry the
+ // issue it belongs to — a caller cannot label it from the task.
+ IssueIdentifier: service.IssueIdentifier(row.IssuePrefix, row.IssueNumber),
+ IssueTitle: row.IssueTitle,
+ AgentID: uuidToString(row.AgentID),
+ Status: row.Status,
+ CreatedAt: timestampToString(row.CreatedAt),
+ StartedAt: timestampToPtr(row.StartedAt),
+ }
+ }
+ // No attribution hydration either: it was the single largest field on
+ // the old payload and needed its own query, and "on behalf of whom" is
+ // an execution-log question, not a coordination one.
+ writeJSON(w, http.StatusOK, summaries)
+ return
+ }
+
+ var tasks []db.AgentTaskQueue
+ var err error
+ if activeOnly {
+ tasks, err = h.Queries.ListActiveTasksByIssue(r.Context(), issue.ID)
+ } else {
+ tasks, err = h.Queries.ListTasksByIssue(r.Context(), issue.ID)
+ }
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list tasks")
return
}
- workspaceID := uuidToString(issue.WorkspaceID)
resp := make([]AgentTaskResponse, len(tasks))
for i, t := range tasks {
resp[i] = taskToResponse(t, workspaceID)
@@ -4903,7 +5047,14 @@ func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {
// issue-facing surface must resolve initiator/originator names (departed-safe,
// one batch) — otherwise the badge falls back to "someone" on issue detail.
h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))
- h.hydrateTaskUsage(r.Context(), issue.ID, resp)
+ // Usage belongs to the execution log, not to a coordination read.
+ // ListIssueTaskUsage returns a row per (task, provider, model) for EVERY
+ // task the issue ever ran, so hydrating it on the active path would keep
+ // paying the full-history cost this filter exists to remove — and pay it
+ // for a column that is near-empty on runs that have not finished.
+ if !activeOnly {
+ h.hydrateTaskUsage(r.Context(), issue.ID, resp)
+ }
writeJSON(w, http.StatusOK, resp)
}
diff --git a/server/internal/handler/task_runs_scope_test.go b/server/internal/handler/task_runs_scope_test.go
new file mode 100644
index 0000000000..eac49e54be
--- /dev/null
+++ b/server/internal/handler/task_runs_scope_test.go
@@ -0,0 +1,367 @@
+package handler
+
+import (
+ "net/http"
+ "sort"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// GET /api/issues/{id}/task-runs answers three different questions depending on
+// its query params (#7768): the execution history the issue sidebar renders,
+// "is anyone working on THIS issue right now", and "is anyone working anywhere
+// in this sub-issue family right now". These tests pin the boundaries between
+// them, because the only thing separating a cheap coordination read from a full
+// history dump is a query param the caller may forget.
+
+// familyFixture builds the shape the family read exists for: one parent, two
+// children, and an unrelated issue in the same workspace that must never appear.
+type familyFixture struct {
+ agentID string
+ parentID string
+ childA string
+ childB string
+ unrelated string
+}
+
+func newFamilyFixture(t *testing.T) familyFixture {
+ t.Helper()
+ f := familyFixture{
+ agentID: createHandlerTestAgent(t, "FamilyRunsAgent", []byte("[]")),
+ parentID: dbfx.Issue(t, "family-parent"),
+ }
+ f.childA = dbfx.Issue(t, "family-child-a", testutil.Cols{"parent_issue_id": f.parentID})
+ f.childB = dbfx.Issue(t, "family-child-b", testutil.Cols{"parent_issue_id": f.parentID})
+ f.unrelated = dbfx.Issue(t, "family-unrelated")
+ return f
+}
+
+func (f familyFixture) task(t *testing.T, issueID, status string) string {
+ t.Helper()
+ return dbfx.Task(t, f.agentID, testutil.Cols{
+ "issue_id": issueID,
+ "status": status,
+ "runtime_id": handlerTestRuntimeID(t),
+ })
+}
+
+// runsResponse drives the handler the way the router does: path params carry
+// the issue, the raw query string carries the scope. Headers come back too —
+// the truncation signal rides one.
+func runsResponse(t *testing.T, issueID, query string) *testutil.Response {
+ t.Helper()
+ path := "/api/issues/" + issueID + "/task-runs"
+ if query != "" {
+ path += "?" + query
+ }
+ return testutil.Call(t, testHandler.ListTasksByIssue,
+ withURLParam(newRequest(http.MethodGet, path, nil), "id", issueID),
+ )
+}
+
+func runsRequest(t *testing.T, issueID, query string) []AgentTaskResponse {
+ t.Helper()
+ var out []AgentTaskResponse
+ runsResponse(t, issueID, query).Want(http.StatusOK).JSON(&out)
+ return out
+}
+
+// familyRequest decodes the family read's own payload. It is a different,
+// deliberately smaller type than the execution log's row, so the tests decode
+// it as one rather than through AgentTaskResponse — a struct that silently
+// accepted both would stop noticing if the two shapes merged again.
+func familyRequest(t *testing.T, issueID, query string) []ActiveRunSummary {
+ t.Helper()
+ var out []ActiveRunSummary
+ runsResponse(t, issueID, query).Want(http.StatusOK).JSON(&out)
+ return out
+}
+
+func taskIDs(runs []AgentTaskResponse) []string {
+ ids := make([]string, len(runs))
+ for i, r := range runs {
+ ids[i] = r.ID
+ }
+ sort.Strings(ids)
+ return ids
+}
+
+func summaryIDs(runs []ActiveRunSummary) []string {
+ ids := make([]string, len(runs))
+ for i, r := range runs {
+ ids[i] = r.TaskID
+ }
+ sort.Strings(ids)
+ return ids
+}
+
+func sortedCopy(ids ...string) []string {
+ out := append([]string(nil), ids...)
+ sort.Strings(out)
+ return out
+}
+
+func sameIDs(got, want []string) bool {
+ if len(got) != len(want) {
+ return false
+ }
+ for i := range got {
+ if got[i] != want[i] {
+ return false
+ }
+ }
+ return true
+}
+
+// The no-param response is what the issue-detail execution log and the CLI's
+// short-task-ID resolver both read. Adding the coordination params must not
+// have narrowed it: a completed run still comes back.
+func TestListTasksByIssueDefaultsToFullHistory(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newFamilyFixture(t)
+ done := f.task(t, f.childA, "completed")
+ live := f.task(t, f.childA, "running")
+
+ got := taskIDs(runsRequest(t, f.childA, ""))
+ if want := sortedCopy(done, live); !sameIDs(got, want) {
+ t.Fatalf("history runs = %v, want %v (a completed run must survive)", got, want)
+ }
+}
+
+// active=true is the cheap "is an agent on this right now" read. It must drop
+// terminal runs and keep the whole in-flight set — including queued, which is
+// about to touch the same code even though it cannot answer you yet.
+func TestListTasksByIssueActiveDropsTerminalRuns(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newFamilyFixture(t)
+ f.task(t, f.childA, "completed")
+ f.task(t, f.childA, "failed")
+ queued := f.task(t, f.childA, "queued")
+ running := f.task(t, f.childA, "running")
+
+ got := taskIDs(runsRequest(t, f.childA, "active=true"))
+ if want := sortedCopy(queued, running); !sameIDs(got, want) {
+ t.Fatalf("active runs = %v, want %v", got, want)
+ }
+}
+
+// The point of #7768: a child asks the question and learns about its siblings.
+// The parent's own run counts (it is the same coordination family), an
+// unrelated issue's does not, and every row says which issue it belongs to —
+// without that, a caller cannot tell one sibling's run from another's.
+func TestListTasksByIssueFamilyScopeSpansSiblings(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newFamilyFixture(t)
+ onSelf := f.task(t, f.childA, "running")
+ onSibling := f.task(t, f.childB, "dispatched")
+ onParent := f.task(t, f.parentID, "running")
+ f.task(t, f.childB, "completed")
+ f.task(t, f.unrelated, "running")
+
+ runs := familyRequest(t, f.childA, "scope=family&active=true")
+ if want := sortedCopy(onSelf, onSibling, onParent); !sameIDs(summaryIDs(runs), want) {
+ t.Fatalf("family runs = %v, want %v (self + sibling + parent, no terminal, no unrelated issue)",
+ summaryIDs(runs), want)
+ }
+
+ for _, run := range runs {
+ // Issue identity labels the row; agent identity IS the answer, since
+ // this read exists to find the agent working next to you.
+ if run.IssueIdentifier == "" || run.IssueTitle == "" || run.AgentID == "" {
+ t.Fatalf("run %s carries no issue/agent identity (%q / %q / %q); a family row cannot be attributed from the task alone",
+ run.TaskID, run.IssueIdentifier, run.IssueTitle, run.AgentID)
+ }
+ }
+}
+
+// Asked from the parent instead of a child, the same flag has to answer the
+// mirror-image question — "who is running on my children?" — rather than
+// returning nothing because the parent has no parent of its own.
+func TestListTasksByIssueFamilyScopeFromParentSeesChildren(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newFamilyFixture(t)
+ onChild := f.task(t, f.childB, "running")
+ onParent := f.task(t, f.parentID, "queued")
+ f.task(t, f.unrelated, "running")
+
+ got := summaryIDs(familyRequest(t, f.parentID, "scope=family"))
+ if want := sortedCopy(onChild, onParent); !sameIDs(got, want) {
+ t.Fatalf("family runs from parent = %v, want %v", got, want)
+ }
+}
+
+// An issue with no parent and no children still has to answer, degenerating to
+// its own active runs — otherwise a caller has to know the issue's shape before
+// it can choose a flag.
+func TestListTasksByIssueFamilyScopeOnStandaloneIssue(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newFamilyFixture(t)
+ own := f.task(t, f.unrelated, "running")
+ f.task(t, f.unrelated, "completed")
+ f.task(t, f.childA, "running")
+
+ got := summaryIDs(familyRequest(t, f.unrelated, "scope=family"))
+ if want := sortedCopy(own); !sameIDs(got, want) {
+ t.Fatalf("family runs from standalone issue = %v, want %v", got, want)
+ }
+}
+
+// A misspelled scope must fail loudly. Silently falling back to full history
+// would hand an agent every past run when it asked for the live ones, which
+// reads as "nobody else is here" only after the caller has paid for the whole
+// log.
+func TestListTasksByIssueRejectsUnknownScope(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newFamilyFixture(t)
+
+ testutil.Call(t, testHandler.ListTasksByIssue,
+ withURLParam(newRequest(http.MethodGet,
+ "/api/issues/"+f.childA+"/task-runs?scope=sibling", nil), "id", f.childA),
+ ).Want(http.StatusBadRequest)
+}
+
+// The whole point of --active is a cheap read. ListIssueTaskUsage returns a row
+// per (task, provider, model) for EVERY task the issue ever ran, so hydrating
+// it here would keep paying the full-history cost the filter exists to remove.
+// Usage is an execution-log concern; a coordination read must not carry it even
+// when the active task happens to have some recorded.
+func TestListTasksByIssueActiveOmitsUsage(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newFamilyFixture(t)
+ running := f.task(t, f.childA, "running")
+ dbfx.Exec(t, `
+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_usd_ticks)
+ VALUES ($1, 'anthropic', 'claude-opus-5', 1000, 500, 0, 0, NULL)
+ `, running)
+
+ active := runsRequest(t, f.childA, "active=true")
+ if len(active) != 1 {
+ t.Fatalf("active runs = %d, want 1", len(active))
+ }
+ if len(active[0].Usage) != 0 {
+ t.Fatalf("active read carried usage %+v; the coordination path must not query it", active[0].Usage)
+ }
+
+ // The execution log still gets it — this is a per-path decision, not a
+ // removal of the feature.
+ history := runsRequest(t, f.childA, "")
+ if len(history) != 1 || len(history[0].Usage) != 1 {
+ t.Fatalf("history read lost its usage: %+v", history)
+ }
+}
+
+// A boolean param that only recognises the exact string "true" turns every
+// typo into a silent downgrade: `active=tru` would answer "who is here now?"
+// with the whole execution history under a 200, and the caller reads a pile of
+// finished runs as the live ones. Same reason the unknown-scope check exists.
+func TestListTasksByIssueRejectsInvalidActive(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newFamilyFixture(t)
+ f.task(t, f.childA, "completed")
+
+ for _, bad := range []string{"tru", "TRUE", "1", "yes", ""} {
+ query := "active=" + bad
+ if bad == "" {
+ // The empty value is the one non-rejection in the set: it means the
+ // caller did not ask, so the read stays the full history.
+ runsRequest(t, f.childA, query)
+ continue
+ }
+ runsResponse(t, f.childA, query).Want(http.StatusBadRequest)
+ }
+
+ // false is a real value and must not 400.
+ runsRequest(t, f.childA, "active=false")
+}
+
+// A truncated coordination read and a complete one are indistinguishable in the
+// body, and reading the first as the second produces exactly the wrong
+// conclusion — "no run on that sibling" when the answer was cut off. The cap
+// therefore has to announce itself.
+func TestListTasksByIssueFamilyScopeReportsTruncation(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newFamilyFixture(t)
+
+ // Exactly at the cap: a full page is not a truncated one.
+ for i := 0; i < familyActiveRunCap; i++ {
+ f.task(t, f.childA, "running")
+ }
+ full := runsResponse(t, f.childA, "scope=family").Want(http.StatusOK)
+ if got := full.Header().Get(HeaderActiveRunsTruncated); got != "" {
+ t.Fatalf("truncation header = %q on an exactly-full page, want empty", got)
+ }
+ var atCap []ActiveRunSummary
+ full.JSON(&atCap)
+ if len(atCap) != familyActiveRunCap {
+ t.Fatalf("rows at cap = %d, want %d", len(atCap), familyActiveRunCap)
+ }
+
+ // One past it: the response is capped AND says so.
+ f.task(t, f.childB, "running")
+ over := runsResponse(t, f.childA, "scope=family").Want(http.StatusOK)
+ if got := over.Header().Get(HeaderActiveRunsTruncated); got != "true" {
+ t.Fatalf("truncation header = %q past the cap, want \"true\"", got)
+ }
+ var truncated []ActiveRunSummary
+ over.JSON(&truncated)
+ if len(truncated) != familyActiveRunCap {
+ t.Fatalf("rows past cap = %d, want them trimmed to %d", len(truncated), familyActiveRunCap)
+ }
+}
+
+// The family read's payload is its product, not an implementation detail: it is
+// an agent spending its own context on the answer. The execution-log row costs
+// roughly 5x the bytes — attribution alone was the largest field on it and
+// needed a second query — and a caller asking "who else is here?" reads none of
+// it. Pinning the exact key set is what stops the two shapes from quietly
+// merging back together the next time someone reuses taskToResponse here.
+func TestListTasksByIssueFamilyScopePayloadStaysLean(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newFamilyFixture(t)
+ f.task(t, f.childB, "running")
+
+ var raw []map[string]any
+ runsResponse(t, f.childA, "scope=family").Want(http.StatusOK).JSON(&raw)
+ if len(raw) != 1 {
+ t.Fatalf("family rows = %d, want 1", len(raw))
+ }
+
+ want := map[string]bool{
+ "task_id": true, "issue_id": true, "issue_identifier": true,
+ "issue_title": true, "agent_id": true, "status": true,
+ "created_at": true, "started_at": true,
+ }
+ for key := range raw[0] {
+ if !want[key] {
+ t.Errorf("family row carries execution-log field %q; this read is a coordination payload", key)
+ }
+ }
+ // started_at is omitempty (a queued run has none), so only the rest are
+ // guaranteed present on a running row.
+ for key := range want {
+ if _, ok := raw[0][key]; !ok && key != "started_at" {
+ t.Errorf("family row missing %q", key)
+ }
+ }
+}
diff --git a/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md b/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md
index b3d10ac6eb..ae6d886f08 100644
--- a/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md
@@ -248,6 +248,39 @@ exact target `(issue, agent)` pair already has a non-terminal task, but it
deliberately keeps same-agent handoffs to a fresh issue starting runs: cross-issue
serial chains and triage batches rely on that.
+## Who else is running right now
+
+The `## Active sibling runs` block covers only YOUR OWN other in-flight tasks.
+It says nothing about another agent working next to you, and it is a claim-time
+snapshot that does not refresh mid-turn. Ask the server when you need the
+current answer:
+
+```bash
+multica issue runs <issue-id> --active --output json # in-flight runs on this issue
+multica issue runs <issue-id> --siblings --output json # ...and across the sub-issue family
+```
+
+`--active` drops the execution history and returns only `queued` / `dispatched`
+/ `running` / `waiting_local_directory` runs. `--siblings` widens the same read
+to the issue's family — its parent (or itself, when it has no parent) plus every
+child of that parent — and labels each row with the issue it belongs to, which
+is how you find another agent already working on a sibling sub-issue before you
+open a second PR against the same code.
+
+The family read returns a compact row — task, issue, agent, status, started —
+not the full execution-log record. If you need a run's detail, follow the task
+id with `multica issue run-messages`.
+
+Rows come back running-first, newest-first within a status, and the family read
+is capped at 20. When the cap truncates the answer the CLI prints a warning on
+stderr — read it. Without that warning a short list means "nobody else is
+there"; with it, the list proves nothing about the runs it did not return.
+
+Both are advisory reads. Nothing here reserves an issue or serialises anything:
+a run you see may finish a second later, and one you don't see may start a
+second later. Coordinate through the issue's comments — the reads tell you whom
+to coordinate with.
+
## Sub-issues: `todo` starts work now, `backlog` parks it
On an agent-assigned issue, create status decides whether the assignee fires
diff --git a/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md b/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md
index c2e060aa77..0d96769ad0 100644
--- a/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md
+++ b/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md
@@ -157,6 +157,12 @@ away, so no task is left orphaned.
| Trusted direct self-assignment suppresses enqueue only when the target `(issue, agent)` already has a non-terminal task | `server/internal/service/issue_trigger.go` (`WillEnqueueRun`), `server/internal/handler/issue_trigger.go` (`shouldSuppressActiveSelfAssignment`) |
| Claim responses expose a bounded, workspace-scoped snapshot of the same agent's other dispatched/running/waiting issue tasks; queued tasks are excluded | `server/pkg/db/queries/agent.sql` (`ListActiveSiblingIssueTasks`), `server/internal/handler/daemon.go` (`buildClaimedTaskResponse`) |
| Daemon prompts point to the target's comment history and concrete sibling `run-messages` commands | `server/internal/daemon/prompt.go` (`buildActiveSiblingRunsBlock`) |
+| `issue runs --active` / `--siblings` send `active=true` / `scope=family` to the task-runs endpoint | `server/cmd/multica/cmd_issue.go` (`runIssueRuns`) |
+| `scope=family` roots at the issue's parent, or the issue itself when it has none, and returns in-flight runs on that root plus all of its children | `server/internal/handler/daemon.go` (`ListTasksByIssue`), `server/pkg/db/queries/agent.sql` (`ListActiveTasksByIssueFamily`) |
+| Invalid `active` / `scope` values are rejected rather than silently answering with the full history | `server/internal/handler/daemon.go` (`ListTasksByIssue`) |
+| The family cap fetches one row past `familyActiveRunCap` and reports truncation on `X-Active-Runs-Truncated`, which the CLI surfaces on stderr | `server/internal/handler/daemon.go` (`familyActiveRunCap`, `HeaderActiveRunsTruncated`), `server/cmd/multica/cmd_issue.go` (`runIssueRuns`) |
+| The active path skips usage hydration, which is keyed by issue and spans the full history | `server/internal/handler/daemon.go` (`ListTasksByIssue`), `server/pkg/db/queries/task_usage.sql` (`ListIssueTaskUsage`) |
+| The family read returns its own compact row rather than the execution-log record, and skips usage and attribution hydration | `server/internal/handler/daemon.go` (`ActiveRunSummary`), `server/pkg/db/queries/agent.sql` (`ListActiveTasksByIssueFamily`) |
The self-assignment guard is intentionally pair-scoped. It does not treat
"this agent is busy on some other issue" as a reason to suppress a fresh
diff --git a/server/internal/service/builtin_skills_test.go b/server/internal/service/builtin_skills_test.go
index 21145d727b..49722ac5d4 100644
--- a/server/internal/service/builtin_skills_test.go
+++ b/server/internal/service/builtin_skills_test.go
@@ -261,6 +261,18 @@ func TestWorkingOnIssuesSkillCoversIssueLoopContracts(t *testing.T) {
// Owner ruling: metadata is deliberately free-form custom state;
// the platform curates no key vocabulary.
"the platform curates no vocabulary",
+ // #7768: the claim-time block and the on-demand reads answer different
+ // questions, and conflating them is what left cross-agent overlap
+ // invisible in the first place. All four anchors are load-bearing —
+ // the same-agent scoping is the correction, the command is the
+ // remedy, the cap disclosure is what stops a truncated answer from
+ // reading as an empty one, and the advisory line is a negative safety
+ // boundary: an agent that reads these as a lock will skip the
+ // coordination they exist to prompt.
+ "covers only YOUR OWN other in-flight tasks",
+ "multica issue runs <issue-id> --siblings --output json",
+ "capped at 20",
+ "Nothing here reserves an issue or serialises anything",
}
for _, want := range mustContain {
if !strings.Contains(body, want) {
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index a6b8c9bcd0..4f41fa9ce3 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -5338,6 +5338,109 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
return items, nil
}
+const listActiveTasksByIssueFamily = `-- name: ListActiveTasksByIssueFamily :many
+SELECT
+ atq.id AS task_id,
+ atq.agent_id,
+ atq.issue_id,
+ atq.status,
+ atq.created_at,
+ atq.started_at,
+ w.issue_prefix,
+ i.number AS issue_number,
+ i.title AS issue_title
+FROM agent_task_queue atq
+JOIN issue i ON i.id = atq.issue_id
+JOIN workspace w ON w.id = i.workspace_id
+WHERE i.workspace_id = $1
+ AND (i.id = $2::uuid OR i.parent_issue_id = $2::uuid)
+ AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ORDER BY
+ CASE atq.status
+ WHEN 'running' THEN 0
+ WHEN 'dispatched' THEN 1
+ WHEN 'waiting_local_directory' THEN 2
+ ELSE 3
+ END,
+ atq.created_at DESC
+LIMIT $3
+`
+
+type ListActiveTasksByIssueFamilyParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RootIssueID pgtype.UUID `json:"root_issue_id"`
+ RowLimit int32 `json:"row_limit"`
+}
+
+type ListActiveTasksByIssueFamilyRow struct {
+ TaskID pgtype.UUID `json:"task_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Status string `json:"status"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ StartedAt pgtype.Timestamptz `json:"started_at"`
+ IssuePrefix string `json:"issue_prefix"`
+ IssueNumber int32 `json:"issue_number"`
+ IssueTitle string `json:"issue_title"`
+}
+
+// Cross-issue coordination read for parallel sub-issue work (#7768). Given a
+// family root — the target issue's parent, or the target itself when it has
+// none — return every in-flight task on the root and on all of its children,
+// so a run can see who else is already working in the family before it starts
+// overlapping work. Advisory only: nothing here gates, queues, or serialises
+// anything.
+//
+// Same active set as ListActiveTasksByIssue, including 'queued': a queued
+// sibling cannot answer you yet, but it is about to touch the same code, which
+// is exactly what the caller is trying to find out. The status column tells the
+// two apart.
+//
+// Issue identity is joined in because the caller renders runs from several
+// issues in one list and cannot label a row from the task alone. agent_id is
+// here for the same reason: unlike ListActiveSiblingIssueTasks, whose rows all
+// belong to the claiming agent by construction, this read spans agents — which
+// one is on a sibling is the answer, not a detail.
+//
+// Columns are named rather than embedded. This is the coordination question,
+// not the execution log: result and context are JSONB blobs, and work_dir /
+// trigger_summary / the attribution ids are all execution-log fields that a
+// caller asking "who else is here?" never reads. Selecting them would make
+// Postgres detoast and ship roughly 5x the bytes per row for nothing.
+//
+// Ordered running-first so the truncation the LIMIT may impose drops the least
+// interesting rows, and bounded because a parent with hundreds of children must
+// not turn one coordination read into an unbounded scan.
+func (q *Queries) ListActiveTasksByIssueFamily(ctx context.Context, arg ListActiveTasksByIssueFamilyParams) ([]ListActiveTasksByIssueFamilyRow, error) {
+ rows, err := q.db.Query(ctx, listActiveTasksByIssueFamily, arg.WorkspaceID, arg.RootIssueID, arg.RowLimit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListActiveTasksByIssueFamilyRow{}
+ for rows.Next() {
+ var i ListActiveTasksByIssueFamilyRow
+ if err := rows.Scan(
+ &i.TaskID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.CreatedAt,
+ &i.StartedAt,
+ &i.IssuePrefix,
+ &i.IssueNumber,
+ &i.IssueTitle,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listAgentTasks = `-- name: ListAgentTasks :many
SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision FROM agent_task_queue
WHERE agent_id = $1
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index fdfb50a491..dea3e36ee2 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -2417,6 +2417,60 @@ SELECT * FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC;
+-- name: ListActiveTasksByIssueFamily :many
+-- Cross-issue coordination read for parallel sub-issue work (#7768). Given a
+-- family root — the target issue's parent, or the target itself when it has
+-- none — return every in-flight task on the root and on all of its children,
+-- so a run can see who else is already working in the family before it starts
+-- overlapping work. Advisory only: nothing here gates, queues, or serialises
+-- anything.
+--
+-- Same active set as ListActiveTasksByIssue, including 'queued': a queued
+-- sibling cannot answer you yet, but it is about to touch the same code, which
+-- is exactly what the caller is trying to find out. The status column tells the
+-- two apart.
+--
+-- Issue identity is joined in because the caller renders runs from several
+-- issues in one list and cannot label a row from the task alone. agent_id is
+-- here for the same reason: unlike ListActiveSiblingIssueTasks, whose rows all
+-- belong to the claiming agent by construction, this read spans agents — which
+-- one is on a sibling is the answer, not a detail.
+--
+-- Columns are named rather than embedded. This is the coordination question,
+-- not the execution log: result and context are JSONB blobs, and work_dir /
+-- trigger_summary / the attribution ids are all execution-log fields that a
+-- caller asking "who else is here?" never reads. Selecting them would make
+-- Postgres detoast and ship roughly 5x the bytes per row for nothing.
+--
+-- Ordered running-first so the truncation the LIMIT may impose drops the least
+-- interesting rows, and bounded because a parent with hundreds of children must
+-- not turn one coordination read into an unbounded scan.
+SELECT
+ atq.id AS task_id,
+ atq.agent_id,
+ atq.issue_id,
+ atq.status,
+ atq.created_at,
+ atq.started_at,
+ w.issue_prefix,
+ i.number AS issue_number,
+ i.title AS issue_title
+FROM agent_task_queue atq
+JOIN issue i ON i.id = atq.issue_id
+JOIN workspace w ON w.id = i.workspace_id
+WHERE i.workspace_id = @workspace_id
+ AND (i.id = @root_issue_id::uuid OR i.parent_issue_id = @root_issue_id::uuid)
+ AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ORDER BY
+ CASE atq.status
+ WHEN 'running' THEN 0
+ WHEN 'dispatched' THEN 1
+ WHEN 'waiting_local_directory' THEN 2
+ ELSE 3
+ END,
+ atq.created_at DESC
+LIMIT @row_limit;
+
-- name: GetWorkspaceAgentRunCounts :many
-- Total task runs per agent over the trailing 30 days, used by the Agents
-- list RUNS column. 30-day window keeps the count meaningful (a long-dormant