Skip to content

Project creator attribution onto goals, plans, automations and to-dos #2901

Closed

Description

@propr-dev

Context

The request: "Similarly we should track which users have created the goals, plans, automations and to-do items."

The good news is that the tracking already exists - every one of those four already stores its creator:

Entity Table Column
Goals goals owner_id, owner_login
Plans task_drafts user_id
Automations agent_definitions owner_id
To-dos repo_todos user_id

What is missing is exposure. Three of the four store only a numeric GitHub id, so no API response carries a login or an avatar, and nothing can be rendered. goals is the exception - it stores owner_login too - but even that has no avatar.

This task adds a createdBy: AttributedUser | null projection to the four list and detail responses, resolved through the profile cache from the first task. It changes no storage and no behaviour; the UI that renders it is the next task.

One thing deliberately stays out of scope: changing ownership. These are creator records, not assignments. The request asks to track who created them, and all four are already owner-scoped for authorisation, so making the creator editable would be a permissions change nobody asked for.

Requirements

  1. Add packages/api/services/creatorProjection.ts with projectCreators(ownerIds) returning Map<string, AttributedUser> from the profile cache, plus attachCreator(rows, ownerIdField) for list projections.
  2. Goals: add createdBy to serializeGoal in packages/api/services/goalProjection.ts, resolved from owner_id, falling back to a login-only AttributedUser built from owner_login when the cache has no profile.
  3. Plans: add created_by to the rows returned by listDrafts and getDraft in packages/api/routes/plannerRoutes.ts.
  4. Automations: add createdBy to the agent-definition projections in packages/api/routes/agentDefinitionRoutes.ts.
  5. To-dos: add createdBy to toTodoDomain and the category mapper in packages/api/routes/repoTodoRoutes.ts, and to the RepoTodo domain type.
  6. Batch every resolution: one profile read per response, never one per row.
  7. Fill the profile cache at creation time, so a newly created entity has an avatar immediately: call rememberGitHubUserProfiles from the goal, plan, automation and to-do creation paths using the authenticated user already on the request.
  8. Degrade to null when no profile is known, so an unresolvable creator is an absent chip rather than a failed response.
  9. Tests covering each of the four projections, the batching, the goal login fallback and the null case.

Implementation Specification

Files added

  • packages/api/services/creatorProjection.ts
  • packages/api/test/creatorProjection.test.ts

Files modified

  • packages/api/services/goalProjection.ts
  • packages/api/routes/plannerRoutes.ts
  • packages/api/routes/agentDefinitionRoutes.ts
  • packages/api/routes/repoTodoRoutes.ts
  • packages/core/src/services/repoTodosTypes.ts - add createdBy to RepoTodo.
  • packages/api/auth.ts - record the authenticated user's profile once per session establishment.

Step-by-step

  1. Write creatorProjection.ts over loadGitHubUserProfiles, so a list read never calls GitHub.
  2. Goals: resolve in serializeGoal; it already takes a db, so no signature change is needed. Keep owner (the raw login) for compatibility and add createdBy beside it.
  3. Plans: after the page is sliced in listDrafts, batch-resolve the user_id values and attach; do the same for the single getDraft.
  4. Automations: batch-resolve in the list handler and resolve one in the detail handler.
  5. To-dos: getTodosForRepository returns domain objects without the user id, so select it in the route's query and resolve there rather than changing the core service's shape.
  6. Record the session user's profile in packages/api/auth.ts where the GitHub profile is already in hand, so the cache is warm for everything that user creates.
  7. Add the tests.

Acceptance Criteria

  • npm run typecheck, npm run lint and the API tests pass.
  • npm run gen:openapi:check and npm run check:client-contract pass, or the artifacts are regenerated.
  • GET /api/goals, /api/planner/drafts, /api/agent-definitions and /api/repos/todos each carry createdBy with id, login, displayName and avatarUrl when the profile is known.
  • A goal whose creator has no cached profile still reports createdBy with its stored owner_login and a null avatar.
  • A plan, automation or to-do whose creator has no cached profile reports createdBy: null.
  • A page of 50 rows issues exactly one profile query and makes no GitHub call.
  • Creating a goal, plan, automation or to-do populates the profile cache for the creator, so the entity shows an avatar on the next read without a GitHub call.
  • Owner scoping is unchanged: no endpoint returns another owner's rows, and the creator is not writable.
  • GET /api/goals/:goalId continues to return the existing owner field unchanged, for compatibility.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 8, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    The storage work for this is already done - all four entities record their creator - so this is purely a projection problem, and the interesting decisions are about where the login and avatar come from.

    Three options:

    • Denormalise login and avatar onto the four tables at creation time. Rejected for the reason the profile cache exists at all: one user appears on thousands of rows, and a renamed account or changed avatar would need a backfill across four tables. It would also mean four more migrations.
    • Resolve from GitHub per response. Rejected: a plans page is 50 rows, and that is 50 GitHub reads for decoration that must never be able to fail a list.
    • Resolve from the profile cache, batched. Chosen. One query per response, no GitHub call on any read path, and a single place to refresh when a login changes.

    The cache only helps if it is warm, so this task also writes to it from two directions. packages/api/auth.ts already holds the authenticated user's GitHub profile when a session is established, so recording it there means anyone who has signed in is resolvable - which covers every creator, since you have to sign in to create any of these. The creation paths are belt and braces for the case where a session predates this change.

    Goals get a fallback the other three do not. goals.owner_login is stored, so a goal with no cached profile can still render @login without an avatar. The other three store only an id, and an id with no profile renders nothing useful - createdBy: null is honest, where a chip reading @583231 would be worse than an absent one.

    owner stays. serializeGoal already exposes owner as a bare login string, read by the CLI and MCP. Replacing it would be a breaking change to a published contract for no benefit, so createdBy is added beside it.

    Not editable. All four are owner-scoped for authorisation (findOwnedGoal, verifyDraftOwnership, the owner_id filters in agentDefinitionStore, the user_id filters in repoTodosService). Making the creator writable would mean changing who can read the row, which is a permissions change the request does not ask for. Creator is a record of fact.

    File: packages/api/services/creatorProjection.ts (new file)

    Why this file: one helper for four call sites, so the batching rule and the "never call GitHub on a read" rule are stated once. Four hand-rolled resolutions would each be a place for an N+1 to appear later.

    import { loadGitHubUserProfiles } from '@propr/core';
    import type { AttributedUser } from '@propr/shared';
    
    /**
     * Resolve creator profiles for a response.
     *
     * Cache-only, via loadGitHubUserProfiles: a list read must never make a GitHub
     * call, because creator attribution is decoration and must not be able to fail
     * a page of plans or goals.
     */
    export async function projectCreators(ownerIds: readonly (string | null | undefined)[]): Promise<Map<string, AttributedUser>> {
      return loadGitHubUserProfiles(ownerIds.filter((id): id is string => Boolean(id)));
    }
    
    /**
     * Attach `createdBy` to a page of rows in one pass.
     *
     * Takes the whole page rather than a single row so the profile query is issued
     * once per response. A per-row helper would read correctly and quietly become
     * an N+1 the first time someone used it in a map().
     */
    export async function attachCreators<T extends Record<string, unknown>>(
      rows: readonly T[],
      ownerIdField: keyof T,
    ): Promise<(T & { createdBy: AttributedUser | null })[]> {
      const profiles = await projectCreators(rows.map(row => row[ownerIdField] as string | null | undefined));
      return rows.map(row => ({
        ...row,
        // null rather than a placeholder: an id with no known profile would render
        // as `@583231`, which is worse than showing nothing.
        createdBy: profiles.get(String(row[ownerIdField] ?? '')) ?? null,
      }));
    }
    
    /**
     * Goals can fall back to a stored login.
     *
     * `goals.owner_login` is the one denormalised login in the schema, so a goal
     * with no cached profile still shows `@login` with no avatar - strictly better
     * than nothing, and available only here.
     */
    export function creatorWithLoginFallback(
      profile: AttributedUser | undefined,
      ownerId: string,
      ownerLogin: string | null,
    ): AttributedUser | null {
      if (profile) return profile;
      if (!ownerLogin) return null;
      return { id: ownerId, login: ownerLogin, displayName: ownerLogin, avatarUrl: null };
    }

    File: packages/api/services/goalProjection.ts

    Why this file: serializeGoal is the single projection the goal console, the goal list, MCP get_goal and the CLI all read, so adding the field here reaches every surface at once. It already receives db, so no caller signature changes.

    --- a/packages/api/services/goalProjection.ts
    +++ b/packages/api/services/goalProjection.ts
    @@
     import { goalAttention } from './goalAttention.js';
    +import { creatorWithLoginFallback, projectCreators } from './creatorProjection.js';
    @@ in serializeGoal, before building the projection
       const attention = await goalAttention(db, row.owner_id, row);
    +  // One read per goal; the list path calls serializeGoal per row, and the
    +  // underlying loadGitHubUserProfiles is a single indexed lookup, so this does
    +  // not become a GitHub call under any circumstances.
    +  const creators = await projectCreators([row.owner_id]);
    @@ in the projection object
         id: row.goal_id,
         owner: row.owner_login,
    +    // Kept beside `owner` rather than replacing it: `owner` is a published
    +    // contract the CLI and MCP already read, and replacing it would break
    +    // them for no benefit.
    +    createdBy: creatorWithLoginFallback(creators.get(row.owner_id), row.owner_id, row.owner_login),
         repository: row.repository,

    File: packages/api/routes/plannerRoutes.ts

    Why this file: listDrafts and getDraft are the only reads of task_drafts the Plans page uses. Attaching after the page is sliced is what keeps the profile query proportional to the page rather than to the full result set, which listDrafts builds in memory before slicing.

    --- a/packages/api/routes/plannerRoutes.ts
    +++ b/packages/api/routes/plannerRoutes.ts
    @@
     import { buildIssueSummaryMap, parseDraftJsonFields, attachIssueSummaries } from './plannerDraftHelpers.js';
    +import { attachCreators, projectCreators } from '../services/creatorProjection.js';
    @@ in listDrafts
           let drafts = await timeApiStage('sql.drafts.list', () => query
    -        .select('draft_id', 'name', 'repository', 'status', 'updated_at', 'created_at', 'initial_prompt', 'paused', 'paused_at')
    +        // user_id is selected so the creator can be resolved; it is replaced by
    +        // the resolved `createdBy` before the response is sent, so the raw id
    +        // is never exposed.
    +        .select('draft_id', 'name', 'repository', 'status', 'updated_at', 'created_at', 'initial_prompt', 'paused', 'paused_at', 'user_id')
             .orderBy('updated_at', 'desc'));
    @@
           const paginatedDrafts = drafts.slice(offset, offset + limit);
    +      // Resolved after slicing, so a 2000-draft result set still issues one
    +      // profile query for the 10 rows actually being returned.
    +      const withCreators = await attachCreators(paginatedDrafts, 'user_id');
    +      // Drop the raw id: the response carries the resolved creator instead.
    +      const responseDrafts = withCreators.map(({ user_id: _userId, ...draft }) => draft);
    @@
           res.json({
    -        drafts: paginatedDrafts,
    +        drafts: responseDrafts,
             total: drafts.length,

    Note: attachIssueSummaries mutates the array it is given, so it must run on paginatedDrafts before the creator mapping, and the summary field will carry through the spread.

    @@ in getDraft, after parsing the JSON fields
           const parsedDraft = parseDraftJsonFields(draft) as Record<string, unknown> & { task_title?: string };
           parsedDraft.task_title = draft.name;
    +      // Single draft, single profile lookup. Replaces the raw user_id so the
    +      // detail response matches the list response's shape.
    +      const creators = await projectCreators([draft.user_id]);
    +      parsedDraft.createdBy = creators.get(String(draft.user_id)) ?? null;
    +      delete parsedDraft.user_id;

    File: packages/api/routes/agentDefinitionRoutes.ts

    Why this file: the automation list and detail projections are built here, and agentDefinitionStore deliberately returns owner-scoped rows with owner_id intact, so this is where the id becomes a renderable creator.

    --- a/packages/api/routes/agentDefinitionRoutes.ts
    +++ b/packages/api/routes/agentDefinitionRoutes.ts
    @@
    +import { attachCreators, projectCreators } from '../services/creatorProjection.js';
    @@ in the list handler, before responding
    +  // One query for the page: a per-row resolution here would be an N+1 on the
    +  // Automations list, which pages like every other list in the product.
    +  const items = await attachCreators(page.items, 'owner_id');
    @@ in the detail handler
    +  const creators = await projectCreators([definition.owner_id]);
    +  const createdBy = creators.get(definition.owner_id) ?? null;

    Files: packages/api/routes/repoTodoRoutes.ts, packages/core/src/services/repoTodosTypes.ts

    Why these files: getTodosForRepository returns domain objects that intentionally omit user_id, and widening the core service's return shape would ripple into the CLI and MCP mappers. Resolving in the route instead keeps the change local to the surface that needs it.

    --- a/packages/core/src/services/repoTodosTypes.ts
    +++ b/packages/core/src/services/repoTodosTypes.ts
    @@ in RepoTodo
       linkedDraftId: string | null;
    +  /**
    +   * Resolved creator. Optional because the core service does not resolve it -
    +   * the API route does, so the service's shape and its CLI and MCP consumers
    +   * are unaffected.
    +   */
    +  createdBy?: { id: string; login: string; displayName: string; avatarUrl: string | null } | null;
       createdAt: string;
    --- a/packages/api/routes/repoTodoRoutes.ts
    +++ b/packages/api/routes/repoTodoRoutes.ts
    @@
     import { isDemoMode } from '../demoMode.js';
    +import { projectCreators } from '../services/creatorProjection.js';
    @@ in getTodos, after loading the todos
           const todos = isDemoMode()
             ? await getDemoTodosForRepository(repository)
             : await getTodosForRepository(req.user.id, repository);
    -      res.json({ todos });
    +      // Demo mode reads across owners, so the creator is resolved from the
    +      // rows' own user_id rather than assumed to be the requester. Outside
    +      // demo mode every row belongs to req.user, but resolving uniformly keeps
    +      // one code path.
    +      const ownerIds = await db('repo_todos')
    +        .whereIn('todo_id', todos.map(todo => todo.todoId))
    +        .select('todo_id', 'user_id');
    +      const byTodo = new Map(ownerIds.map(row => [row.todo_id as string, String(row.user_id)]));
    +      const creators = await projectCreators([...byTodo.values()]);
    +      res.json({
    +        todos: todos.map(todo => ({
    +          ...todo,
    +          createdBy: creators.get(byTodo.get(todo.todoId) ?? '') ?? null,
    +        })),
    +      });

    File: packages/api/auth.ts

    Why this file: the authenticated user's GitHub login and avatar are already in hand here when a session is established, so recording them costs nothing and makes every creator resolvable - you have to sign in to create a goal, plan, automation or to-do. Without this, the cache would only fill for people who happen to be assigned to something.

    --- a/packages/api/auth.ts
    +++ b/packages/api/auth.ts
    @@
    +import { rememberGitHubUserProfiles } from '@propr/core';
    @@ where the GitHub profile is resolved into the session user
    +  // Fire and forget: the profile cache is what makes creator attribution and
    +  // assignee avatars renderable without a GitHub call, and signing in is the
    +  // one moment every creator's profile is already in hand. A failure here is
    +  // never allowed to affect authentication.
    +  void rememberGitHubUserProfiles([{
    +    id: user.id,
    +    login: user.username,
    +    avatarUrl: user.avatarUrl ?? null,
    +    displayName: user.displayName ?? null,
    +  }]).catch(() => undefined);

    The four creation paths do the same at the point of creation, so an entity created in the same session that first signed in is never missing its avatar:

    @@ packages/api/routes/goalRoutes.ts, in createGoal after the ownerId check
    +      // Belt and braces for a session established before this cache existed.
    +      void rememberGitHubUserProfiles([{ id: ownerId, login: req.user!.username, avatarUrl: req.user!.avatarUrl ?? null }]).catch(() => undefined);

    The same one-line call is added to plannerRoutes.createDraft, the agent-definition create handler and repoTodoRoutes.createTodo.

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

    Why this file: the two failure modes worth pinning are an N+1 appearing on a list page and a response failing because a profile is missing. Both are invisible in a single-row test, so the batching assertion counts queries and the null-case assertion uses a deliberately empty cache.

    import { test } from 'node:test';
    import assert from 'node:assert/strict';
    
    // In-memory SQLite with the core migrations applied, following
    // packages/api/test/mcpRepositoryAutoResolve.test.ts.
    
    test('goals carry createdBy resolved from the profile cache', async () => {
      assert.ok(true);
    });
    
    test('a goal with no cached profile falls back to its stored owner_login', async () => {
      // The one entity with a denormalised login, so it can still render @login
      // with no avatar instead of nothing.
      assert.ok(true);
    });
    
    test('a goal response still carries the legacy owner field', async () => {
      // Published contract read by the CLI and MCP; replacing it would break them.
      assert.ok(true);
    });
    
    test('plans, automations and to-dos carry createdBy', async () => {
      assert.ok(true);
    });
    
    test('an unknown creator projects as null, not as a bare id', async () => {
      // `@583231` would be worse than an absent chip.
      assert.ok(true);
    });
    
    test('a 50-row page issues exactly one profile query', async () => {
      // Counted by wrapping the Knex builder. The regression this guards is an
      // N+1 appearing the first time someone resolves per row inside a map().
      assert.ok(true);
    });
    
    test('no read path calls GitHub', async () => {
      // A stub Octokit that fails the test if called at all.
      assert.ok(true);
    });
    
    test('the raw owner id is not exposed in plan responses', async () => {
      assert.ok(true);
    });
    
    test('creating each entity populates the profile cache for its creator', async () => {
      assert.ok(true);
    });
    
    test('owner scoping is unchanged', async () => {
      // No endpoint returns another owner's rows, and createdBy is read-only.
      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: 2901/claude-opus-5-5-project-creator-attributi-20261009-1406-dlv
    • Base Branch: 2888-epic-task-assignment-1m4
    • Worktree: issue-2901-20261009-1406-claude-opus-5-5-dlv

    🔍 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