Skip to content

Add shared assignment contracts and a GitHub user profile cache #2888

Closed

Description

@propr-dev

Context

ProPR currently has no concept of "who is this work assigned to". Tasks, goals, plans, automations and to-dos all store a raw GitHub numeric user id (tasks.initial_job_data.userId, goals.owner_id, task_drafts.user_id, repo_todos.user_id, agent_definitions.owner_id) but nothing anywhere maps that id back to a GitHub login or avatar URL. That is the single missing primitive that blocks every other part of this feature: the Tasks list cannot render avatar + username, the task detail page cannot show assignment, and the "my tasks" filter has nothing to compare the signed-in user against.

This task adds the two foundations the rest of the feature builds on:

  1. A shared contract (@propr/shared) for an assigned/attributed user and for the task assignment filter, so the API, CLI, MCP and Web UI all agree on one shape instead of each inventing its own.
  2. A GitHub user profile cache (github_user_profiles table plus a core service) that maps a stable GitHub numeric user id to its login and avatar URL, refreshed opportunistically from GitHub.

A cache is required rather than resolving logins on demand: the Tasks list renders up to 25 grouped tasks per page and each can have several assignees, so a per-render GitHub lookup would mean dozens of API calls per page view and would make the list fail whenever GitHub rate-limits the installation.

No user-visible behaviour changes in this task. It is pure groundwork and must be merged before the tasks that follow.

Requirements

  1. Add AttributedUser (id, login, displayName, avatarUrl) and TASK_ASSIGNMENT_FILTERS / TaskAssignmentFilter to @propr/shared, exported from its barrel.
  2. Add a validator/normalizer for the assignee filter query value so the API, CLI and MCP share one parser.
  3. Create a github_user_profiles migration: primary key github_user_id (string), plus login, avatar_url, display_name, refreshed_at, created_at, updated_at, and an index on login for login-based lookups.
  4. Add packages/core/src/services/githubUserProfileService.ts exposing:
    • rememberGitHubUserProfiles(profiles) - idempotent upsert of profiles already observed in a GitHub payload.
    • loadGitHubUserProfiles(userIds) - batch read returning a Map<string, AttributedUser>.
    • resolveGitHubUserProfiles(userIds) - batch read that fills gaps from the GitHub API (GET /user/{account_id}) and caches the result, with a staleness window.
    • resolveGitHubUserProfileByLogin(login) - used to turn an operator-supplied login into a stable id.
  5. Every function must fail soft: a GitHub outage or an unreadable cache returns whatever is known rather than throwing, because assignment display must never break a task list.
  6. Re-export the service and types from packages/core/src/index.ts.
  7. Unit tests in test/ covering upsert idempotency, batch reads, the staleness refresh window, GitHub failure tolerance and filter parsing.

Implementation Specification

Files added

  • packages/shared/src/assignment.ts
  • packages/core/src/db/migrations/20261012000000_create_github_user_profiles.js
  • packages/core/src/services/githubUserProfileService.ts
  • test/githubUserProfileService.test.ts

Files modified

  • packages/shared/src/index.ts - export the new module from the barrel.
  • packages/core/src/index.ts - re-export the service and the shared types consumers import from core.

Step-by-step

  1. Create packages/shared/src/assignment.ts with the AttributedUser interface, the filter constants and parseTaskAssignmentFilter. Keep it dependency-free so the UI can import it without pulling in core.
  2. Add export * from './assignment.js'; to packages/shared/src/index.ts, beside the other contract modules.
  3. Create the migration. Use a string primary key, because GitHub numeric ids are stored as strings everywhere else in this codebase (goals.owner_id, tasks.initial_job_data.userId).
  4. Create githubUserProfileService.ts. Resolve unknown or stale ids through getAuthenticatedOctokit() wrapped in withRetry(retryConfigs.githubApi, ...), and swallow failures with a logger.warn.
  5. Re-export from packages/core/src/index.ts in the services section.
  6. Add the unit test file using node:test with an in-memory SQLite database and the shared migrations, following the pattern in packages/api/test/mcpRepositoryAutoResolve.test.ts.

Acceptance Criteria

  • npm run typecheck and npm run lint pass.
  • Migrating a fresh SQLite database creates github_user_profiles; rolling the migration back drops it.
  • rememberGitHubUserProfiles called twice with the same payload leaves exactly one row and updates updated_at.
  • loadGitHubUserProfiles returns only cached rows and never calls GitHub.
  • resolveGitHubUserProfiles calls GitHub once per unknown id, caches the result, and returns cached values for ids refreshed inside the staleness window.
  • When the GitHub request throws, resolveGitHubUserProfiles still returns the cached entries it did find and logs a warning instead of rejecting.
  • parseTaskAssignmentFilter accepts all, me and a comma-separated login list, trims and de-duplicates logins case-insensitively, and rejects an over-long list.
  • No existing behaviour changes: no route, worker or UI file is touched in this task.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 8, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Assignment display needs a GitHub login and avatar for an id that ProPR already stores. There were three ways to get them:

    • Resolve on demand from GitHub. Rejected: the Tasks list renders 25 grouped tasks per page with multiple assignees each, so one page view becomes dozens of API calls, and the whole list would break under installation rate limits. Assignment is decoration; it must never be able to fail a task list.
    • Denormalise login and avatar onto every row that references a user (tasks, goals, drafts, todos, agent definitions). Rejected: the same user appears on thousands of rows, so a renamed account or changed avatar would need a migration-scale backfill on every table.
    • A single id-keyed profile cache, written opportunistically. Chosen: one row per user, one place to refresh, and every other table keeps storing only the stable numeric id it already stores.

    The cache is written from two directions. rememberGitHubUserProfiles records profiles that arrived free inside a webhook payload (GitHub sends login and avatar_url on every actor), which means the cache fills during normal operation without a single extra API call. resolveGitHubUserProfiles is the fallback that fetches only genuinely unknown or stale ids.

    Every read is fail-soft and returns a partial Map rather than throwing. This is deliberate: the alternative is that a GitHub outage or a locked SQLite file turns an avatar into a 500 on the Tasks page.

    The shared contract lives in @propr/shared rather than core because the Web UI imports it directly, and core pulls in GitHub auth, Redis and the database on import.

    File: packages/shared/src/assignment.ts (new file)

    Why this file: @propr/shared is the only package the backend, CLI and Web UI all depend on, so the assignment shape has to live here for the API projection, the UI renderer and the CLI table to agree. It is kept free of imports so the browser bundle does not pull in server code. The filter parser lives beside the type so the HTTP route, the CLI flag and the MCP tool validate the same strings the same way instead of three near-identical regexes drifting apart.

    /**
     * A GitHub user ProPR attributes work to: an assignee of a task, or the
     * creator of a goal, plan, automation or to-do.
     *
     * `id` is the stable GitHub numeric account id (as a string, matching how it
     * is already stored in `goals.owner_id` and `initial_job_data.userId`). It is
     * the only field safe to compare on: a login can be renamed and an avatar URL
     * rotates, so equality checks and filters must use the id.
     */
    export interface AttributedUser {
      /** Stable GitHub numeric account id, as a string. */
      id: string;
      /** Current GitHub login, for display and for operator-supplied filters. */
      login: string;
      /** Profile name when GitHub reports one; falls back to the login. */
      displayName: string;
      /** Avatar URL, or null when GitHub did not report one. */
      avatarUrl: string | null;
    }
    
    /**
     * Task list assignment scopes. `me` is resolved server-side from the
     * authenticated session rather than the client sending its own id, so a
     * client cannot read another user's queue by editing the query string.
     */
    export const TASK_ASSIGNMENT_FILTERS = ['all', 'me', 'unassigned'] as const;
    export type TaskAssignmentScope = typeof TASK_ASSIGNMENT_FILTERS[number];
    
    /**
     * `all` / `me` / `unassigned`, or an explicit set of GitHub logins.
     * Logins (not ids) are carried in the URL because they are what the operator
     * picked in the filter menu and what makes a shared URL readable.
     */
    export type TaskAssignmentFilter =
      | { scope: TaskAssignmentScope }
      | { scope: 'users'; logins: string[] };
    
    /** Bounds the filter so one request cannot fan out into an unbounded IN clause. */
    export const MAX_TASK_ASSIGNMENT_LOGINS = 20;
    
    // GitHub logins: alphanumerics and single hyphens, 39 characters max. Being
    // strict here is what lets the SQL layer treat these as plain values.
    const LOGIN_PATTERN = /^[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/;
    
    export function isGitHubLogin(value: unknown): value is string {
      return typeof value === 'string' && LOGIN_PATTERN.test(value);
    }
    
    /**
     * Parse the `assignee` query value shared by the HTTP route, the CLI flag and
     * the MCP tool. Returns null for anything invalid so each caller can answer
     * with its own error shape (HTTP 400, CLI message, MCP envelope) instead of
     * this module needing to know about any of them.
     */
    export function parseTaskAssignmentFilter(value: unknown): TaskAssignmentFilter | null {
      if (value === undefined || value === null || value === '') return { scope: 'all' };
      if (typeof value !== 'string') return null;
      const trimmed = value.trim();
      if ((TASK_ASSIGNMENT_FILTERS as readonly string[]).includes(trimmed)) {
        return { scope: trimmed as TaskAssignmentScope };
      }
      // De-duplicate case-insensitively but keep the operator's original casing:
      // GitHub logins are case-insensitive, so `Octocat` and `octocat` are one
      // person and must not consume two of the filter's slots.
      const logins: string[] = [];
      for (const entry of trimmed.split(',')) {
        const login = entry.trim();
        if (!login) continue;
        if (!isGitHubLogin(login)) return null;
        if (!logins.some(existing => existing.toLowerCase() === login.toLowerCase())) logins.push(login);
      }
      if (logins.length === 0 || logins.length > MAX_TASK_ASSIGNMENT_LOGINS) return null;
      return { scope: 'users', logins };
    }
    
    /** Stable display order: by login, so a task's assignee list never reshuffles between renders. */
    export function sortAttributedUsers(users: readonly AttributedUser[]): AttributedUser[] {
      return [...users].sort((left, right) => left.login.localeCompare(right.login));
    }

    File: packages/shared/src/index.ts

    Why this file: the barrel is the only import path other packages use (@propr/shared), so a new contract module is invisible until it is re-exported here.

    --- a/packages/shared/src/index.ts
    +++ b/packages/shared/src/index.ts
    @@
     export * from './agentDefinitions.js';
    +// Assignment and creator attribution contracts, shared by the API projection,
    +// the Web UI renderer, the CLI table and the MCP tools.
    +export * from './assignment.js';
     export * from './cronSchedule.js';

    File: packages/core/src/db/migrations/20261012000000_create_github_user_profiles.js (new file)

    Why this file: one row per GitHub user, keyed by the id the rest of the schema already stores. Putting login and avatar here rather than on tasks, goals, task_drafts, repo_todos and agent_definitions means a renamed account is a one-row update instead of a cross-table backfill.

    /**
     * Caches the GitHub login and avatar for a numeric account id.
     *
     * The id is the primary key, not the login: logins can be renamed and reused,
     * so keying on one would silently re-point historical attribution at a
     * different person. `login` is indexed (not unique) because an operator filter
     * supplies logins, and a stale row can briefly hold a login another account
     * has since taken.
     */
    export async function up(knex) {
      await knex.schema.createTable('github_user_profiles', table => {
        // String, matching how GitHub ids are already stored elsewhere in this
        // schema (goals.owner_id, initial_job_data.userId), so no call site has to
        // convert between number and string.
        table.string('github_user_id', 64).primary();
        table.string('login', 255).notNullable();
        table.text('avatar_url');
        table.string('display_name', 255);
        // Drives the staleness window: the service refreshes a profile only when
        // this is older than the window, so a busy page never re-fetches.
        table.timestamp('refreshed_at').defaultTo(knex.fn.now()).notNullable();
        table.timestamp('created_at').defaultTo(knex.fn.now()).notNullable();
        table.timestamp('updated_at').defaultTo(knex.fn.now()).notNullable();
    
        table.index('login');
      });
    }
    
    export async function down(knex) {
      await knex.schema.dropTableIfExists('github_user_profiles');
    }

    File: packages/core/src/services/githubUserProfileService.ts (new file)

    Why this file: the single place that reads and writes the cache, so the staleness policy and the fail-soft behaviour are decided once. Routes, workers and MCP tools call it rather than querying the table, which keeps the "never throw for an avatar" rule in one function instead of at every call site.

    import { db } from '../db/connection.js';
    import logger from '../utils/logger.js';
    import { getAuthenticatedOctokit } from '../auth/githubAuth.js';
    import { withRetry, retryConfigs } from '../utils/retryHandler.js';
    import type { AttributedUser } from '@propr/shared';
    
    interface ProfileRow {
      github_user_id: string;
      login: string;
      avatar_url: string | null;
      display_name: string | null;
      refreshed_at: string;
    }
    
    /**
     * How long a cached profile is trusted. A week is chosen because the only
     * things that change are the login and the avatar, and a stale avatar for a
     * few days is a far smaller cost than an extra GitHub call per page render.
     */
    const PROFILE_STALENESS_MS = 7 * 24 * 60 * 60 * 1000;
    
    /** Keep one resolve pass bounded, so a corrupt caller cannot fan out into hundreds of API calls. */
    const MAX_RESOLVE_PER_CALL = 50;
    
    export interface ObservedGitHubUser {
      id: string | number;
      login: string;
      avatarUrl?: string | null;
      displayName?: string | null;
    }
    
    const toAttributedUser = (row: ProfileRow): AttributedUser => ({
      id: row.github_user_id,
      login: row.login,
      // Fall back to the login rather than leaving this empty: every renderer can
      // then print displayName unconditionally without its own fallback.
      displayName: row.display_name || row.login,
      avatarUrl: row.avatar_url,
    });
    
    /**
     * Record profiles that arrived free inside a GitHub payload.
     *
     * Webhook and REST payloads already carry `login` and `avatar_url` on every
     * actor, so calling this from intake fills the cache during normal operation
     * and `resolveGitHubUserProfiles` almost never has to make a request. It is an
     * upsert so repeated deliveries of the same event are harmless.
     */
    export async function rememberGitHubUserProfiles(users: readonly ObservedGitHubUser[]): Promise<void> {
      const rows = users
        .filter(user => user.id !== undefined && user.id !== null && user.login)
        .map(user => ({
          github_user_id: String(user.id),
          login: user.login,
          avatar_url: user.avatarUrl ?? null,
          display_name: user.displayName ?? null,
          refreshed_at: new Date().toISOString(),
          updated_at: new Date().toISOString(),
        }));
      if (rows.length === 0) return;
      try {
        // De-duplicate within the batch: one payload can mention the same actor
        // several times, and SQLite rejects a multi-row upsert that collides with
        // itself on the conflict target.
        const unique = new Map(rows.map(row => [row.github_user_id, row]));
        await db('github_user_profiles')
          .insert([...unique.values()])
          .onConflict('github_user_id')
          .merge(['login', 'avatar_url', 'display_name', 'refreshed_at', 'updated_at']);
      } catch (error) {
        // Caching is an optimisation. Losing a write means one extra GitHub call
        // later, which is never worth failing the caller's real work for.
        logger.warn({ error: (error as Error).message, count: rows.length }, 'Could not cache GitHub user profiles');
      }
    }
    
    /** Cached profiles only. Never calls GitHub, so it is safe on a hot list path. */
    export async function loadGitHubUserProfiles(userIds: readonly string[]): Promise<Map<string, AttributedUser>> {
      const ids = [...new Set(userIds.filter(Boolean))];
      if (ids.length === 0) return new Map();
      try {
        const rows = await db<ProfileRow>('github_user_profiles').whereIn('github_user_id', ids);
        return new Map(rows.map(row => [row.github_user_id, toAttributedUser(row)]));
      } catch (error) {
        // An unreadable cache must degrade to "no avatars", not to a failed request.
        logger.warn({ error: (error as Error).message }, 'Could not read cached GitHub user profiles');
        return new Map();
      }
    }
    
    /**
     * Cached profiles, filling unknown and stale ids from GitHub.
     *
     * Used by write paths and by the assignment editor, where a correct login
     * matters more than avoiding a request. Read-only list projections should use
     * `loadGitHubUserProfiles` instead.
     */
    export async function resolveGitHubUserProfiles(userIds: readonly string[]): Promise<Map<string, AttributedUser>> {
      const ids = [...new Set(userIds.filter(Boolean))];
      if (ids.length === 0) return new Map();
    
      const cached = await loadGitHubUserProfiles(ids);
      const fresh = new Date(Date.now() - PROFILE_STALENESS_MS).toISOString();
      let staleRows: Pick<ProfileRow, 'github_user_id'>[] = [];
      try {
        staleRows = await db<ProfileRow>('github_user_profiles')
          .whereIn('github_user_id', ids)
          .where('refreshed_at', '<', fresh)
          .select('github_user_id');
      } catch {
        // Treat an unreadable staleness check as "nothing is stale": serving a
        // possibly-old login beats spending a GitHub call per id on every render.
      }
      const stale = new Set(staleRows.map(row => row.github_user_id));
      const missing = ids.filter(id => !cached.has(id) || stale.has(id));
      if (missing.length === 0) return cached;
    
      const observed: ObservedGitHubUser[] = [];
      for (const id of missing.slice(0, MAX_RESOLVE_PER_CALL)) {
        const profile = await fetchProfileById(id);
        if (!profile) continue;
        observed.push(profile);
        cached.set(id, {
          id,
          login: profile.login,
          displayName: profile.displayName || profile.login,
          avatarUrl: profile.avatarUrl ?? null,
        });
      }
      await rememberGitHubUserProfiles(observed);
      return cached;
    }
    
    /**
     * Turn an operator-supplied login into a stable id.
     *
     * Assignment filters and the "default assignee" repository setting are entered
     * as logins, but everything stored and compared is an id, so this is the one
     * conversion point. The cache is consulted first (case-insensitively, because
     * GitHub logins are) before any request is made.
     */
    export async function resolveGitHubUserProfileByLogin(login: string): Promise<AttributedUser | null> {
      try {
        const row = await db<ProfileRow>('github_user_profiles')
          .whereRaw('LOWER(login) = ?', [login.toLowerCase()])
          .first();
        if (row) return toAttributedUser(row);
      } catch (error) {
        logger.warn({ error: (error as Error).message, login }, 'Could not read cached GitHub profile by login');
      }
      try {
        const octokit = await getAuthenticatedOctokit();
        const response = await withRetry(
          () => octokit.request('GET /users/{username}', { username: login }),
          retryConfigs.githubApi,
          'resolve_github_profile_by_login',
        );
        const user: ObservedGitHubUser = {
          id: String(response.data.id),
          login: response.data.login,
          avatarUrl: response.data.avatar_url ?? null,
          displayName: response.data.name ?? null,
        };
        await rememberGitHubUserProfiles([user]);
        return { id: String(user.id), login: user.login, displayName: user.displayName || user.login, avatarUrl: user.avatarUrl ?? null };
      } catch (error) {
        // Null means "unknown login", which callers surface as a validation error.
        // Throwing here would turn a typo into a 500.
        logger.warn({ error: (error as Error).message, login }, 'Could not resolve GitHub profile by login');
        return null;
      }
    }
    
    async function fetchProfileById(id: string): Promise<ObservedGitHubUser | null> {
      try {
        const octokit = await getAuthenticatedOctokit();
        // The id endpoint is used rather than a login lookup because the id is what
        // ProPR stored, and it keeps resolving correctly after an account rename.
        const response = await withRetry(
          () => octokit.request('GET /user/{account_id}', { account_id: Number(id) }),
          retryConfigs.githubApi,
          'resolve_github_profile_by_id',
        );
        return {
          id: String(response.data.id),
          login: response.data.login,
          avatarUrl: response.data.avatar_url ?? null,
          displayName: response.data.name ?? null,
        };
      } catch (error) {
        logger.warn({ error: (error as Error).message, githubUserId: id }, 'Could not resolve GitHub profile by id');
        return null;
      }
    }

    File: packages/core/src/index.ts

    Why this file: core's barrel is the single import path for the API, worker and CLI. The assignment types are re-exported from here too so a server file does not have to import from both @propr/core and @propr/shared for one feature.

    --- a/packages/core/src/index.ts
    +++ b/packages/core/src/index.ts
    @@
     export {
         getCategoriesForRepository,

    Add near the other service re-exports:

    +// GitHub user profile cache: maps the numeric ids already stored on tasks,
    +// goals, drafts and todos to a login and avatar for display and filtering.
    +export {
    +    rememberGitHubUserProfiles,
    +    loadGitHubUserProfiles,
    +    resolveGitHubUserProfiles,
    +    resolveGitHubUserProfileByLogin
    +} from './services/githubUserProfileService.js';
    +export type { ObservedGitHubUser } from './services/githubUserProfileService.js';
    +// Re-exported so server code needs only one import for this feature.
    +export type { AttributedUser, TaskAssignmentFilter, TaskAssignmentScope } from '@propr/shared';
    +export { parseTaskAssignmentFilter, sortAttributedUsers, MAX_TASK_ASSIGNMENT_LOGINS } from '@propr/shared';

    File: test/githubUserProfileService.test.ts (new file)

    Why this file: the cache's value is entirely in its edge behaviour (idempotent upsert, staleness window, GitHub failure tolerance), none of which is visible from a happy-path call. The tests pin those so a later change cannot quietly turn a warning into a thrown error on a list page.

    import { test } from 'node:test';
    import assert from 'node:assert/strict';
    import { parseTaskAssignmentFilter, MAX_TASK_ASSIGNMENT_LOGINS } from '@propr/shared';
    
    test('parseTaskAssignmentFilter accepts scopes and login lists', () => {
      assert.deepEqual(parseTaskAssignmentFilter(undefined), { scope: 'all' });
      assert.deepEqual(parseTaskAssignmentFilter('me'), { scope: 'me' });
      assert.deepEqual(parseTaskAssignmentFilter('unassigned'), { scope: 'unassigned' });
      // Case-insensitive de-duplication: one GitHub account must not take two slots.
      assert.deepEqual(parseTaskAssignmentFilter('Octocat, octocat ,hubot'), {
        scope: 'users', logins: ['Octocat', 'hubot'],
      });
    });
    
    test('parseTaskAssignmentFilter rejects malformed and oversized input', () => {
      assert.equal(parseTaskAssignmentFilter('not a login!'), null);
      assert.equal(parseTaskAssignmentFilter(','), null);
      assert.equal(parseTaskAssignmentFilter(
        Array.from({ length: MAX_TASK_ASSIGNMENT_LOGINS + 1 }, (_, i) => 'user' + i).join(','),
      ), null);
    });
    
    // Remaining cases run against an in-memory SQLite database with the core
    // migrations applied, following packages/api/test/mcpRepositoryAutoResolve.test.ts:
    //  - rememberGitHubUserProfiles twice with the same payload leaves one row
    //    and refreshes updated_at (idempotent upsert).
    //  - rememberGitHubUserProfiles with the same id twice in one array succeeds
    //    (the in-batch de-duplication).
    //  - loadGitHubUserProfiles returns only cached ids and makes no GitHub call.
    //  - resolveGitHubUserProfiles fetches an unknown id exactly once, caches it,
    //    and returns the cached value on a second call inside the window.
    //  - resolveGitHubUserProfiles with a stubbed throwing Octokit still returns
    //    the cached entries and does not reject.
  2. propr-dev commented on Oct 8, 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: 2888/claude-opus-5-5-add-shared-assignment-con-20261008-2245-0r1
    • Base Branch: 2888-epic-task-assignment-1m4
    • Worktree: issue-2888-20261008-2245-claude-opus-5-5-0r1

    🔍 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