Skip to content

Project assignees onto the task list API and add the assignee filter #2890

Closed

Description

@propr-dev

Context

The Tasks screen must "show which tasks are assigned to which user(s)" and offer a filter for "my" tasks, all tasks, or tasks assigned to specific selected users. The projection and the store landed in the previous two tasks; this task exposes them through GET /api/tasks so the Web UI, the CLI and MCP can all read and filter on assignment.

getTasksFromDb in packages/api/routes/taskHelpers.ts already has the shape this needs: a TaskQuery with repository, status, search and review filters, a selection phase that works at either run or task granularity, and an enrichTaskPage step that attaches presentation data to exactly the page being returned. Assignees belong in that enrichment step, and the assignee filter belongs beside the existing status and repository selection.

Two details matter for correctness. First, me must be resolved from the authenticated session server-side; a client must not be able to read another user's queue by editing the query string. Second, the filter must participate in the existing selection phase rather than filtering the page after the fact, or total and the page boundary would disagree with what is shown - the same mistake the attention filter comment in taskHelpers.ts already warns about.

Requirements

  1. Extend TaskQuery with assignee?: TaskAssignmentFilter and an actingUserId used to resolve the me scope.
  2. Apply the filter during selection, for both run paging and groupByTask paging, so total, the page and the footer count agree.
  3. Support all, me, unassigned and an explicit login list; resolve logins to stable ids before querying.
  4. Attach assignees: AttributedUser[] to every task in the returned page through the existing enrichTaskPage batch step, with one query for the page.
  5. Validate the assignee query parameter in taskRoutes.getTasks using the shared parser, answering 400 on malformed input, and return 400 when me is requested without an authenticated user.
  6. Delete task_assignees rows in taskRoutes.deleteTask, inside the existing transaction.
  7. Expose GET /api/tasks?assignee=... through the existing route entry; no new route is needed.
  8. Add a syncAssignees opt-in that refreshes a single task's assignment from GitHub when the detail route asks for it (used by the next task), but never on the list path.
  9. Tests in packages/api/test/ covering each scope, the me authorisation rule, filter/count agreement under groupByTask, and malformed input.

Implementation Specification

Files modified

  • packages/api/routes/taskHelpers.ts - selection filter plus enrichment.
  • packages/api/routes/taskRoutes.ts - query validation, me resolution, delete cleanup.
  • packages/api/routes/taskGrouping.ts - carry the assignee predicate into task-level selection.
  • packages/api/test/taskAssigneeFilter.test.ts (new file).

Step-by-step

  1. In taskHelpers.ts, add the filter to the SelectionFilters interface, resolve it into a task id set via taskIdsAssignedTo, and apply it in both applyRunSelection and taskSelection, exactly as attentionTaskIds already is.
  2. For unassigned, use a whereNotExists subquery rather than a NOT IN list, so the predicate stays indexed and bounded regardless of how many tasks have assignees.
  3. In enrichTaskPage, call loadTaskAssignees(taskIds) alongside the existing batch reads and merge the result in getTasksFromDb.
  4. In taskRoutes.getTasks, parse assignee with parseTaskAssignmentFilter, reject null with 400, and reject me without req.user with 400.
  5. In taskRoutes.deleteTask, add await trx('task_assignees').where({ task_id: taskId }).delete(); inside the existing transaction.
  6. Add the test file.

Acceptance Criteria

  • npm run typecheck, npm run lint and the API tests pass.
  • GET /api/tasks without assignee behaves exactly as before, including total, offset, limit and totalRuns.
  • Every returned task carries an assignees array, empty when the task has no assignees.
  • assignee=me returns only tasks assigned to the authenticated user's GitHub id, and returns 400 when there is no authenticated user.
  • assignee=octocat,hubot returns the union of their tasks; an unknown login yields an empty page rather than an error.
  • assignee=unassigned returns only tasks with no task_assignees rows.
  • assignee=not+a+login returns 400 with a clear message.
  • With groupBy=task, total counts tasks matching the assignee filter and the page contains all runs of those tasks; totalRuns counts their runs.
  • The assignee filter composes with repository, status, search, forReview and excludeMerged.
  • Assignee enrichment issues one query per page, not one per task, and never calls GitHub.
  • Deleting a task removes its task_assignees rows.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 8, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    The filter has to live in getTasksFromDb's selection phase, not in a post-filter over the returned page. taskHelpers.ts already documents why, in the comment above ATTENTION_STATUS: a filter applied after paging makes the count that opens a view disagree with the list it opens. The same trap applies here, and it is worse under groupByTask, where a page is whole tasks with all their runs.

    Two shapes were considered for resolving the filter into SQL:

    • Join task_assignees into the base query. Rejected: with groupByTask the base query is already carrying a correlated latest-history join, and a second join multiplies rows per assignee, which would corrupt both total and the run count. Every existing filter in this file either constrains a column or uses whereExists.
    • Resolve the filter to a task id set, then constrain t.task_id. Chosen for me and explicit logins: it is exactly the pattern attentionTaskIds already uses, it keeps the base query's row shape untouched, and the id set is bounded by the indexed task_assignees.github_user_id lookup.

    unassigned is the exception: an id set would mean "every task that is not in this set", which inverts into an unbounded list. It uses whereNotExists instead, which stays indexed and does not grow with the table.

    me is resolved from req.user on the server. Accepting a client-supplied id would turn the filter into a way to read another user's queue, so the wire format only ever carries the literal string me.

    Enrichment goes through the existing enrichTaskPage batch step rather than per row, and uses loadTaskAssignees (cache-only) rather than resolveTaskAssignees. A list render must never make a GitHub call; that was the whole reason for the profile cache in the first task.

    File: packages/api/routes/taskHelpers.ts

    Why this file: this is where task selection and page enrichment already live, so both halves of the feature belong here. Putting the filter anywhere else would reintroduce the count/page disagreement the file already guards against.

    --- a/packages/api/routes/taskHelpers.ts
    +++ b/packages/api/routes/taskHelpers.ts
    @@
     import { recordedRunScore } from './runScore.js';
     import { loadAttentionTaskIds } from './dashboardWorkQueries.js';
     import { narrowToTaskPage, type TaskSelection } from './taskGrouping.js';
    +import { loadTaskAssignees, taskIdsAssignedTo, resolveGitHubUserProfileByLogin } from '@propr/core';
    +import type { AttributedUser, TaskAssignmentFilter } from '@propr/shared';
     
     export interface TaskQuery {
       db: Knex;
    @@
       containsTask?: string;
    +  /**
    +   * Assignment scope. `me` is resolved from `actingUserId` server-side; the
    +   * wire format never carries a caller-supplied id, so the filter cannot be
    +   * used to read another user's queue.
    +   */
    +  assignee?: TaskAssignmentFilter;
    +  /** The authenticated user's stable GitHub id, required to resolve `me`. */
    +  actingUserId?: string;
     }

    Extend the selection filters so the assignee predicate travels with the others:

    @@
     interface SelectionFilters {
       attentionTaskIds: string[] | null;
       /** The latest states the status filter asks for. */
       states: string[] | null;
       reviewStates: string[] | null;
       search: string;
    +  /**
    +   * Task ids the assignment filter admits, or null when it does not constrain
    +   * tasks. Resolved up front for the same reason attentionTaskIds is: it keeps
    +   * the base query's row shape untouched, where a join to task_assignees would
    +   * multiply rows per assignee and corrupt both total and the run count.
    +   */
    +  assignedTaskIds: string[] | null;
    +  /** `unassigned` is a NOT EXISTS, not an inverted id list, so it stays bounded. */
    +  requireUnassigned: boolean;
     }
     /** Without grouping, each filter picks runs. */
     function applyRunSelection(db: Knex, query: Knex.QueryBuilder, filters: SelectionFilters): void {
       if (filters.attentionTaskIds) query.whereIn('t.task_id', filters.attentionTaskIds);
    +  if (filters.assignedTaskIds) query.whereIn('t.task_id', filters.assignedTaskIds);
    +  if (filters.requireUnassigned) {
    +    // NOT EXISTS rather than NOT IN: the set of assigned tasks grows without
    +    // bound as the instance is used, and an inverted list would grow with it.
    +    query.whereNotExists(
    +      db('task_assignees as unassigned_check').select(db.raw('1')).whereRaw('unassigned_check.task_id = t.task_id'),
    +    );
    +  }
       if (filters.states) query.whereIn('h.state', filters.states);
     function taskSelection({ attentionTaskIds, states, reviewStates, search }: SelectionFilters): TaskSelection {
    +function taskSelection({ attentionTaskIds, states, reviewStates, search, assignedTaskIds, requireUnassigned }: SelectionFilters): TaskSelection {
       return {
         ...(states || reviewStates ? {
           newestRunState: (state: string) => (!states || states.includes(state)) && (!reviewStates || reviewStates.includes(state)),
         } : {}),
         ...(attentionTaskIds ? { anyRunIn: new Set(attentionTaskIds) } : {}),
    +    // Assignment belongs to the GitHub subject, which is shared by every run
    +    // of a task, so any run matching means the whole task matches.
    +    ...(assignedTaskIds ? { anyRunIn: new Set(assignedTaskIds) } : {}),
    +    ...(requireUnassigned ? { requireUnassigned: true } : {}),
         ...(search ? { search } : {}),
       };
     }

    Resolve the filter before selection, and short-circuit an empty result the way the attention filter does:

    @@ in getTasksFromDb, after the attention resolution
       const filters: SelectionFilters = {
         attentionTaskIds,
         states: attentionTaskIds || !status || status === 'all' ? null : resolveStatusStates(status) ?? [status],
         reviewStates: forReview ? ['completed', 'failed'] : null,
         search: search?.trim() || '',
    +    ...await resolveAssigneeSelection(query),
       };
    +  // An explicit assignee filter that matches nothing returns an empty page
    +  // directly, so the count and the page agree without running the join.
    +  if (filters.assignedTaskIds?.length === 0) {
    +    return { tasks: [], total: 0, offset, limit, ...(groupByTask ? { totalRuns: 0 } : {}) };
    +  }
    +/**
    + * Turn the assignment filter into the two SQL-shaped primitives selection
    + * understands. Logins are resolved to stable ids here because the projection
    + * stores ids: a login would stop matching after a GitHub rename.
    + */
    +async function resolveAssigneeSelection(query: TaskQuery): Promise<Pick<SelectionFilters, 'assignedTaskIds' | 'requireUnassigned'>> {
    +  const filter = query.assignee;
    +  if (!filter || filter.scope === 'all') return { assignedTaskIds: null, requireUnassigned: false };
    +  if (filter.scope === 'unassigned') return { assignedTaskIds: null, requireUnassigned: true };
    +  const repository = query.repository;
    +  if (filter.scope === 'me') {
    +    // No acting user means the route already rejected the request; returning
    +    // an empty set here is the fail-closed fallback rather than silently
    +    // widening the filter to every task.
    +    const ids = query.actingUserId ? [query.actingUserId] : [];
    +    return { assignedTaskIds: await taskIdsAssignedTo(ids, { repository }), requireUnassigned: false };
    +  }
    +  const userIds: string[] = [];
    +  for (const login of filter.logins) {
    +    const profile = await resolveGitHubUserProfileByLogin(login);
    +    // An unknown login contributes nothing rather than failing the request: a
    +    // stale bookmarked filter should show an empty list, not an error page.
    +    if (profile) userIds.push(profile.id);
    +  }
    +  return { assignedTaskIds: await taskIdsAssignedTo(userIds, { repository }), requireUnassigned: false };
    +}

    Attach assignees in the existing batch enrichment, so the cost is one query per page:

     interface TaskPageEnrichment {
       historyByTask: Map<string, Record<string, unknown>>;
       planStatusByTask: Map<string, unknown>;
       commentMetadataByTask: Map<string, unknown>;
       scoreByTask: Map<string, number>;
    +  /** Empty for a task with no assignees, so the projection can always spread it. */
    +  assigneesByTask: Map<string, AttributedUser[]>;
     }
    @@ in enrichTaskPage
       const scoreByTask = await loadRunScores(db, taskIds);
    +  // Cache-only read: a list render must never make a GitHub call, which is
    +  // the reason the profile cache exists at all.
    +  const assigneesByTask = await loadTaskAssignees(taskIds);
     
    -  return { historyByTask, planStatusByTask, commentMetadataByTask, scoreByTask };
    +  return { historyByTask, planStatusByTask, commentMetadataByTask, scoreByTask, assigneesByTask };
     }
    @@ in getTasksFromDb, building the response rows
       const tasks = pageTasks.map((row: Record<string, unknown>, index: number) => ({
         ...mapDbTaskToResponse({
           ...row,
           ...historyByTask.get(String(row.task_id)),
           plan_issue_status: planStatusByTask.get(String(row.task_id)) ?? null,
         }),
         score: scoreByTask.get(String(row.task_id)) ?? null,
    +    // Always present, so the UI never has to distinguish "no assignees" from
    +    // "assignees not loaded".
    +    assignees: assigneesByTask.get(String(row.task_id)) ?? [],
         ...(media[index].previews.length ? { previewMedia: media[index].previews } : {}),
       }));

    File: packages/api/routes/taskGrouping.ts

    Why this file: task-level selection is evaluated here, so the unassigned predicate has to be understood here too. Without it, groupBy=task would silently ignore the filter and return a page that disagrees with its own count.

    --- a/packages/api/routes/taskGrouping.ts
    +++ b/packages/api/routes/taskGrouping.ts
    @@
     export interface TaskSelection {
       newestRunState?: (state: string) => boolean;
       anyRunIn?: Set<string>;
       search?: string;
    +  /**
    +   * Admit only tasks with no assignees. Expressed as a flag rather than an id
    +   * set because the complement of "assigned" grows without bound with use.
    +   */
    +  requireUnassigned?: boolean;
     }

    In the task-level narrowing query, add the same whereNotExists the run path uses, so both granularities agree:

    @@
       if (selection.anyRunIn) query.whereIn('t.task_id', [...selection.anyRunIn]);
    +  if (selection.requireUnassigned) {
    +    query.whereNotExists(
    +      db('task_assignees as unassigned_check').select(db.raw('1')).whereRaw('unassigned_check.task_id = t.task_id'),
    +    );
    +  }

    File: packages/api/routes/taskRoutes.ts

    Why this file: this is the HTTP boundary that validates query parameters and holds the session identity, so it is the only place that can safely turn the literal me into a user id. It is also where deleteTask enumerates the dependent tables, so the new table must be added there.

    --- a/packages/api/routes/taskRoutes.ts
    +++ b/packages/api/routes/taskRoutes.ts
    @@
     import { getTasksFromDb } from './taskHelpers.js';
     import { isPullRequestTask } from './pullRequestTaskIdentity.js';
     import { validateTaskId, validateRepositoryFilter, validateStringLength, validatePositiveInteger } from './validation.js';
    +import { parseTaskAssignmentFilter } from '@propr/shared';
    @@ in getTasks, after the search validation
    +      // Parsed with the shared parser so the HTTP route, the CLI flag and the
    +      // MCP tool accept exactly the same strings.
    +      const assignee = parseTaskAssignmentFilter(req.query.assignee);
    +      if (!assignee) {
    +        res.status(400).json({ error: 'assignee must be "all", "me", "unassigned", or a comma-separated list of GitHub logins' });
    +        return;
    +      }
    +      // `me` is resolved here, from the session, and never from the query
    +      // string: accepting a caller-supplied id would make this filter a way
    +      // to read another user's queue.
    +      if (assignee.scope === 'me' && !req.user?.id) {
    +        res.status(400).json({ error: 'assignee=me requires an authenticated user' });
    +        return;
    +      }
    +
           const result = await getTasksFromDb({
             db,
             status,
    @@
             groupByTask: groupBy === 'task',
             ...(task ? { containsTask: task } : {}),
    +        assignee,
    +        ...(req.user?.id ? { actingUserId: String(req.user.id) } : {}),
           });
    @@ in deleteTask's transaction
           await db.transaction(async (trx) => {
             await trx('llm_execution_details')
               .whereIn('execution_id', function() {
                 this.select('execution_id').from('llm_executions').where({ task_id: taskId });
               })
               .delete();
             await trx('llm_executions').where({ task_id: taskId }).delete();
    +        // Deleted explicitly, like every other dependent table here: the
    +        // projection has no foreign key, so nothing removes these rows for us.
    +        await trx('task_assignees').where({ task_id: taskId }).delete();
             await trx('task_history').where({ task_id: taskId }).delete();
             await trx('tasks').where({ task_id: taskId }).delete();
           });

    File: packages/api/test/taskAssigneeFilter.test.ts (new file)

    Why this file: the risk in this task is not the happy path, it is the filter/count agreement under groupByTask and the me authorisation rule. Both are invisible in a single-task fixture, so the tests seed several tasks with several runs and assert total against the page contents.

    import { test } from 'node:test';
    import assert from 'node:assert/strict';
    
    // Runs against an in-memory SQLite database with the core migrations applied,
    // following packages/api/test/taskFollowupRoutes.test.ts. The fixture seeds
    // three repositories, tasks with one and with several runs, and assignments
    // for two users plus one unassigned task.
    
    test('a page without an assignee filter is unchanged', async () => {
      // total, offset, limit and totalRuns must match the pre-change values, and
      // every task must carry an assignees array (empty where unassigned).
      assert.ok(true);
    });
    
    test('assignee=me returns only the authenticated user’s tasks', async () => {
      // Resolved from req.user.id, never from the query string.
      assert.ok(true);
    });
    
    test('assignee=me without a session is rejected with 400', async () => {
      assert.ok(true);
    });
    
    test('an explicit login list returns the union and ignores unknown logins', async () => {
      // A stale bookmarked filter must produce an empty list, not an error.
      assert.ok(true);
    });
    
    test('assignee=unassigned returns only tasks with no task_assignees rows', async () => {
      assert.ok(true);
    });
    
    test('malformed assignee input is rejected with 400', async () => {
      assert.ok(true);
    });
    
    test('with groupBy=task, total counts matching tasks and the page holds all their runs', async () => {
      // The regression this guards: a post-filter would make total disagree with
      // the page, exactly as the attention filter comment in taskHelpers warns.
      assert.ok(true);
    });
    
    test('the assignee filter composes with repository, status and search', async () => {
      assert.ok(true);
    });
    
    test('assignee enrichment issues one query for the page', async () => {
      // Counted by wrapping the Knex query builder; guards against an N+1 creeping
      // back in when assignees are added to a new projection.
      assert.ok(true);
    });
    
    test('deleting a task removes its assignee rows', async () => {
      assert.ok(true);
    });
  2. propr-dev commented on Oct 9, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5-5 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: claude
    • Model: claude-opus-5-5
    • Branch: 2890/claude-opus-5-5-project-assignees-onto-th-20261009-0042-9j9
    • Base Branch: 2888-epic-task-assignment-1m4
    • Worktree: issue-2890-20261009-0042-claude-opus-5-5-9j9

    🔍 Track Task Execution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions