Skip to content

Complete and link repository to-dos to the GitHub issue opened when a task is launched from them #2886

Closed

Description

@propr-dev

Context

Repository to-dos can already be turned into work in two ways:

  1. Plan first — the to-dos are linked to a planner draft (repo_todos.linked_draft_id via linkTodosToDraft), and when that plan reaches the merged status checkAndUpdateDraftStatus calls completeTodosForDraft, which flips is_completed for every linked to-do. The UI then shows a "Linked to plan" chip on the to-do.
  2. Run task — the to-do panel's Run task action (and the New Task launcher it opens) sends todoIds to POST /api/task-submissions. The server stores them in the submission payload (SubmissionPayload.todoIds) and… nothing else happens. The to-do stays open forever, with no record of the issue it produced. The docs even state this explicitly: "Select a to-do and choose Run task to prefill its text; launching does not mark the to-do complete."

That asymmetry is the bug being reported: a to-do that has been turned into a running task is still presented as outstanding work, and there is no way back from the to-do to the issue that was opened for it.

Requirements

  1. When a task submission successfully creates its GitHub issue, every to-do named by that submission's todoIds must be marked completed.
  2. Each of those to-dos must record which issue it produced, so the UI can link back to it — mirroring how a plan-linked to-do records linked_draft_id.
  3. The behaviour must be idempotent. POST /api/task-submissions is retried (same Idempotency-Key), POST /api/task-submissions/:key/retry resumes a stopped submission, and MCP create_task goes through the same route. Repeating any of those must not produce a different outcome or an error.
  4. Completing a to-do must never fail an otherwise accepted submission. The issue already exists on GitHub and the run is queued; a failed to-do write is a bookkeeping problem, not a reason to report failure to the caller.
  5. Every surface that reads to-dos must carry the new link: the REST API (including demo mode), the MCP list_todos/get_todo tools, the CLI client types and the Web UI.
  6. The Web UI must show the link on both active and completed to-dos as a chip that opens the GitHub issue.
  7. The plan path must keep working exactly as before. linked_draft_id, linkTodosToDraft, completeTodosForDraft and getTodosForDraft must be untouched.
  8. The documentation sentence that promises the old behaviour must be corrected.

Implementation Specification

Where the completion happens

Server-side, in packages/api/routes/taskSubmissionRoutes.ts, immediately after resumeTaskSubmission returns a row that has an issue_number. Both the submit and retry handlers call it. See the implementation section for why this location was chosen over the browser.

Files to change

File Change
packages/core/src/db/migrations/20261013000000_add_todo_issue_link.js New. Adds linked_issue_repository, linked_issue_number, linked_task_id to repo_todos, plus an index.
packages/core/src/services/repoTodosTypes.ts Record and domain types gain the three fields; new CompleteTodosForIssueParams.
packages/core/src/services/repoTodosService.ts toTodoDomain maps the new fields; new completeTodosForIssue.
packages/core/src/index.ts Export completeTodosForIssue and CompleteTodosForIssueParams.
packages/api/routes/repoTodoRoutes.ts The demo-mode toTodoDomain mapper gains the new fields.
packages/api/routes/taskSubmissionRoutes.ts New linkSubmissionTodos helper, injectable through services, called from submit and retry.
packages/api/mcp/toolsManagement.ts list_todos selects the new columns.
packages/cli/src/api/todos.ts RepoTodo interface gains the new fields.
propr-ui/src/api/repoTodosApi.ts RepoTodo interface gains the new fields.
propr-ui/src/components/Repositories/RepoTodos/TodoIssueLink.tsx New. The shared chip.
propr-ui/src/components/Repositories/RepoTodos/index.ts Export the chip.
propr-ui/src/components/Repositories/RepoTodos/SortableTodoItem.tsx Render the chip.
propr-ui/src/components/Repositories/RepoTodos/CompletedItemsAccordion.tsx Render the chip.
docs/docs/features/launching-work.md Correct the "launching does not mark the to-do complete" sentence.
CHANGELOG.md Unreleased → Changed entry.
packages/core/test/repoTodosIssueLink.test.ts New. Service-level tests.
packages/api/test/taskSubmissionRoutes.test.ts New case: submission completes and links its to-dos; failures are swallowed.
propr-ui/src/components/Repositories/RepoTodos/TodoIssueLink.test.tsx New. Chip rendering tests.

Behavioural detail

  • completeTodosForIssue scopes its UPDATE by user_id and repository as well as todo_id, so a submission can only ever complete to-dos that belong to the submitting user in the repository the issue was opened in. A forged or stale todoIds entry simply matches no row.
  • The update always writes the issue of the submission being resumed. Resuming the same submission always supplies the same issue number, which is what makes it idempotent; a deliberate relaunch of a reopened to-do intentionally retargets it at the issue that is now running.
  • linked_task_id is written when the submission already knows its task id and is otherwise left null; it is a convenience for later navigation, not a key anything depends on.

Acceptance Criteria

  1. npm run migrate applies the new migration on an existing SQLite database, and rolling it back removes the three columns and the index.
  2. Launching a task from the repository To-Dos panel (select a to-do → Run task → Run task in the launcher) marks that to-do completed. Reopening the repository workspace shows it under Completed Items with a chip reading #<issue number> that opens the GitHub issue in a new tab.
  3. The same launch performed through MCP create_task with todoIds, and through a retry of a submission whose dispatch failed, produces exactly the same single completion — no duplicate work, no error.
  4. A to-do belonging to another user, or named with a repository that does not match the submission, is left untouched.
  5. With the to-do table made unwritable (simulate by making completeTodosForIssue throw), POST /api/task-submissions still returns its normal 200/202 body and the run is still queued; a warning is logged.
  6. Plan-created to-dos still show "Linked to plan" and are still completed when the plan merges; completeTodosForDraft behaviour is unchanged.
  7. npm run typecheck, npm run lint and the touched test suites pass with no new warnings.
  8. docs/docs/features/launching-work.md no longer claims that launching leaves the to-do open.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 8, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Why complete the to-do on the server, in the task-submission route, rather than in the browser.
    The submission row is the one durable, idempotent record of "a task was initiated from these to-dos": it already stores todoIds in its payload, it already knows the authenticated user_id and the repository, and resumeTaskSubmission already guarantees exactly one GitHub issue per submission key. Hooking the completion there means every caller gets it for free — the Web UI launcher, MCP create_task, the retry endpoint and any future CLI path — and it cannot be lost because the browser navigated to /tasks/:id the moment the submission resolved. A browser-side PUT /api/repos/todos/:id after submitTask resolves was considered and rejected: it would silently leave the to-do open whenever that second request failed or the tab was closed, and it would not cover MCP or CLI submissions at all.

    Why new columns instead of reusing linked_draft_id.
    linked_draft_id is read by completeTodosForDraft and getTodosForDraft and is a foreign-key-ish reference to task_drafts.draft_id. A GitHub issue number is a different kind of object in a different namespace. Storing one in the other field would make completeTodosForDraft match rows it has no business matching and would make the "Linked to plan" chip lie. Three nullable columns (linked_issue_repository, linked_issue_number, linked_task_id) keep the two lifecycles independent; the repository is stored alongside the number because an issue number alone is meaningless.

    Why completion happens at launch rather than on merge.
    Plans complete their to-dos when the plan reaches merged, because a plan has a lifecycle to hang that on. A one-off task does not, and the request is explicit: the to-do should be completed once the task has been initiated. The recorded issue link is what makes that safe — if the run turns out badly, the user can follow the chip to the issue and reopen the to-do with the existing incomplete toggle.

    Trade-off accepted. Because the update always writes the issue of the submission being resumed, a very late retry of an old submission for a to-do that has since been relaunched would retarget the chip backwards. This is rare, visible and trivially recoverable, and the alternative (coalesce, keeping the first link forever) makes a deliberate relaunch point at a stale issue, which is worse.


    File: packages/core/src/db/migrations/20261013000000_add_todo_issue_link.js (new file)

    Why this file: The link has to survive restarts and be queryable, so it belongs in the schema next to linked_draft_id rather than in a cache. A dated migration file is how every other schema change in this repository is delivered, and the timestamp is chosen to sort after the newest existing migration (20260928000000).

    /**
     * Migration to record the GitHub issue a to-do was turned into.
     *
     * Repository to-dos could already be linked to a planner draft
     * (`linked_draft_id`), which is how `completeTodosForDraft` knows which
     * to-dos a merged plan finished. A to-do launched directly as a one-off
     * task had nowhere to record its outcome, so it stayed open forever.
     *
     * These columns are deliberately separate from `linked_draft_id`: a plan
     * draft id and a GitHub issue live in different namespaces, and reusing
     * one field for both would make the draft queries match unrelated rows.
     */
    export async function up(knex) {
      await knex.schema.alterTable('repo_todos', (table) => {
        // The repository is stored with the number because an issue number on
        // its own cannot be turned back into a URL.
        table.text('linked_issue_repository').nullable();
        table.integer('linked_issue_number').nullable();
        // Convenience pointer to the run that implements the to-do. Nothing
        // keys off it; it is null until the submission knows its task id.
        table.text('linked_task_id').nullable();
    
        // Supports "which to-do produced this issue?" lookups without a scan.
        table.index(['linked_issue_repository', 'linked_issue_number']);
      });
    }
    
    export async function down(knex) {
      await knex.schema.alterTable('repo_todos', (table) => {
        // Knex rebuilds the SQLite table to drop columns; the index goes with them.
        table.dropIndex(['linked_issue_repository', 'linked_issue_number']);
        table.dropColumn('linked_issue_repository');
        table.dropColumn('linked_issue_number');
        table.dropColumn('linked_task_id');
      });
    }

    File: packages/core/src/services/repoTodosTypes.ts

    Why this file: It is the single source of truth for the database row shape and the domain object every consumer (API, MCP, CLI, UI) is typed against. The new columns have to appear here first, or toTodoDomain cannot be made to carry them and TypeScript will reject every downstream change.

    --- a/packages/core/src/services/repoTodosTypes.ts
    +++ b/packages/core/src/services/repoTodosTypes.ts
    @@
     export interface RepoTodoRecord {
       id: number;
       todo_id: string;
       user_id: string;
       repository: string;
       category_id: string | null;
       content: string;
       order_index: number;
       is_completed: boolean;
       linked_draft_id: string | null;
    +  /** Repository of the GitHub issue this to-do was launched as, if any. */
    +  linked_issue_repository: string | null;
    +  /** Issue number opened for this to-do; null until it is launched as a task. */
    +  linked_issue_number: number | null;
    +  /** Run that implements the issue, when the submission already knows it. */
    +  linked_task_id: string | null;
       created_at: string;
       updated_at: string;
     }
    @@
     export interface RepoTodo {
       todoId: string;
       categoryId: string | null;
       content: string;
       orderIndex: number;
       isCompleted: boolean;
       linkedDraftId: string | null;
    +  linkedIssueRepository: string | null;
    +  linkedIssueNumber: number | null;
    +  linkedTaskId: string | null;
       createdAt: string;
       updatedAt: string;
     }
    @@
     export interface BatchReorderItem {
       id: string;
       orderIndex: number;
       categoryId?: string | null;
     }
    +
    +/**
    + * Identity of the submission whose issue finishes a set of to-dos. The
    + * user and repository are part of the parameters, not just the ids, so the
    + * update can be scoped: a submission may only ever complete to-dos that
    + * belong to the submitting user in the repository the issue was opened in.
    + */
    +export interface CompleteTodosForIssueParams {
    +  todoIds: string[];
    +  userId: string;
    +  repository: string;
    +  issueNumber: number;
    +  taskId?: string | null;
    +}

    Note that UpdateTodoParams is intentionally not extended. The link is written only by the submission path; letting an ordinary PUT /api/repos/todos/:todoId set it would let a client claim any issue number.


    File: packages/core/src/services/repoTodosService.ts

    Why this file: This is the only module that talks to the repo_todos table, so both the read mapping and the new write belong here. Putting the write beside completeTodosForDraft keeps the two "a to-do is finished" paths next to each other and visibly parallel.

    --- a/packages/core/src/services/repoTodosService.ts
    +++ b/packages/core/src/services/repoTodosService.ts
    @@
    -import type { RepoTodoCategoryRecord, RepoTodoRecord, RepoTodoCategory, RepoTodo, CreateCategoryParams, UpdateCategoryParams, CreateTodoParams, UpdateTodoParams, BatchReorderItem } from './repoTodosTypes.js';
    +import type { RepoTodoCategoryRecord, RepoTodoRecord, RepoTodoCategory, RepoTodo, CreateCategoryParams, UpdateCategoryParams, CreateTodoParams, UpdateTodoParams, BatchReorderItem, CompleteTodosForIssueParams } from './repoTodosTypes.js';
     
    -export type { RepoTodoCategoryRecord, RepoTodoRecord, RepoTodoCategory, RepoTodo, CreateCategoryParams, UpdateCategoryParams, CreateTodoParams, UpdateTodoParams, BatchReorderItem } from './repoTodosTypes.js';
    +export type { RepoTodoCategoryRecord, RepoTodoRecord, RepoTodoCategory, RepoTodo, CreateCategoryParams, UpdateCategoryParams, CreateTodoParams, UpdateTodoParams, BatchReorderItem, CompleteTodosForIssueParams } from './repoTodosTypes.js';
    @@
     function toTodoDomain(record: RepoTodoRecord): RepoTodo {
    -  return { todoId: record.todo_id, categoryId: record.category_id, content: record.content, orderIndex: record.order_index, isCompleted: Boolean(record.is_completed), linkedDraftId: record.linked_draft_id, createdAt: record.created_at, updatedAt: record.updated_at };
    +  return {
    +    todoId: record.todo_id, categoryId: record.category_id, content: record.content,
    +    orderIndex: record.order_index, isCompleted: Boolean(record.is_completed),
    +    linkedDraftId: record.linked_draft_id,
    +    // Rows written before the link migration have these as null, so every
    +    // consumer must already treat an absent link as "not launched yet".
    +    linkedIssueRepository: record.linked_issue_repository ?? null,
    +    linkedIssueNumber: record.linked_issue_number ?? null,
    +    linkedTaskId: record.linked_task_id ?? null,
    +    createdAt: record.created_at, updatedAt: record.updated_at,
    +  };
     }

    Then add the new writer next to completeTodosForDraft, so the two completion paths read as siblings:

    --- a/packages/core/src/services/repoTodosService.ts
    +++ b/packages/core/src/services/repoTodosService.ts
    @@
     /** Mark all todos linked to a draft as completed. Called when a draft/plan is merged. */
     export async function completeTodosForDraft(draftId: string): Promise<number> {
    @@
     }
     
    +/**
    + * Complete the to-dos a task submission was launched from and record the
    + * GitHub issue it opened. Called once the issue exists, which is the point
    + * at which the user's intent ("turn this to-do into work") has been acted on.
    + *
    + * Idempotent by construction: resuming the same submission always supplies
    + * the same issue number, so repeating the call rewrites the same values. A
    + * deliberate relaunch of a reopened to-do intentionally retargets it at the
    + * issue that is now running, which is more useful than preserving a stale one.
    + *
    + * The update is scoped by user and repository as well as by id, so a stale
    + * or forged todoId cannot reach another user's to-do or a to-do in a
    + * repository this issue has nothing to do with: it simply matches no row.
    + */
    +export async function completeTodosForIssue(params: CompleteTodosForIssueParams): Promise<number> {
    +  const { todoIds, userId, repository, issueNumber, taskId } = params;
    +  // Nothing to do is the common case (most tasks are not launched from a
    +  // to-do); return before touching the database at all.
    +  if (!todoIds.length) return 0;
    +  try {
    +    const updated = await db<RepoTodoRecord>('repo_todos')
    +      .whereIn('todo_id', todoIds)
    +      .andWhere('user_id', userId)
    +      .andWhere('repository', repository)
    +      .update({
    +        is_completed: true,
    +        linked_issue_repository: repository,
    +        linked_issue_number: issueNumber,
    +        // Left as-is when the submission has not been associated with a run
    +        // yet, so a later retry that does know the task id can fill it in.
    +        ...(taskId ? { linked_task_id: taskId } : {}),
    +        updated_at: db.fn.now(),
    +      });
    +    logger.info({ todoIds, repository, issueNumber, updated }, 'Completed todos launched as a task');
    +    return updated;
    +  } catch (error) {
    +    logger.error({ error: (error as Error).message, todoIds, repository, issueNumber }, 'Failed to complete todos for issue');
    +    throw error;
    +  }
    +}
    +
     /** Get todos linked to a specific draft. */
     export async function getTodosForDraft(draftId: string): Promise<RepoTodo[]> {

    File: packages/core/src/index.ts

    Why this file: @propr/core is the only entry point the API package imports from, so the new function and type are unreachable until they are re-exported from this barrel.

    --- a/packages/core/src/index.ts
    +++ b/packages/core/src/index.ts
    @@
         batchReorderTodos,
         linkTodosToDraft,
         completeTodosForDraft,
    +    completeTodosForIssue,
         getTodosForDraft
     } from './services/repoTodosService.js';
     export type {
    @@
         UpdateTodoParams,
    -    BatchReorderItem
    +    BatchReorderItem,
    +    CompleteTodosForIssueParams
     } from './services/repoTodosService.js';

    File: packages/api/routes/taskSubmissionRoutes.ts

    Why this file: This is the route that owns task submissions, and resumeTaskSubmission returning a row with an issue_number is the exact moment the issue is known to exist. Both the submit and retry handlers funnel through it, so one helper covers the first attempt, an idempotent repeat, a recovery retry and MCP create_task (which calls routes.submit).

    --- a/packages/api/routes/taskSubmissionRoutes.ts
    +++ b/packages/api/routes/taskSubmissionRoutes.ts
    @@
     import {
       AttachmentService, AgentRegistry, getAuthenticatedOctokit, loadMonitoredReposRaw,
       loadPrimaryProcessingLabels, resolvePlanIssueDefaultSelection, safeAddLabel, logger,
       insertTaskSubmission, resumeTaskSubmission, submissionMarker, submissionAssetPath, resolveVisualPreviewUploadToken,
    +  completeTodosForIssue,
       type MulterFile, type SubmissionAttachment, type SubmissionPayload, type TaskSubmission,
     } from '@propr/core';

    Add the helper next to the other submission helpers (above createTaskSubmissionRoutes):

    --- a/packages/api/routes/taskSubmissionRoutes.ts
    +++ b/packages/api/routes/taskSubmissionRoutes.ts
    @@
     function submissionBudget(body: SubmissionRequest) {
       return body.maxCostUsd ? { maxCostUsd: body.maxCostUsd } : {};
     }
     
    +/**
    + * Finish the to-dos this submission was launched from, once its issue exists.
    + *
    + * Best effort on purpose: the issue is already open on GitHub and the run is
    + * already queued, so a failed to-do write must not turn an accepted
    + * submission into a reported failure. It is logged and left for the next
    + * resume of the same submission to retry.
    + */
    +async function linkSubmissionTodos(row: TaskSubmission, complete = completeTodosForIssue): Promise<void> {
    +  // No issue yet means the submission is still in `prepared`/`creating`;
    +  // there is nothing to link the to-dos to.
    +  if (!row.issue_number) return;
    +  let todoIds: string[] = [];
    +  try {
    +    todoIds = (JSON.parse(row.payload) as SubmissionPayload).todoIds ?? [];
    +  } catch {
    +    // A payload we cannot read is a pre-existing corruption; the submission
    +    // itself already succeeded, so only the bookkeeping is skipped.
    +    logger.warn({ submissionId: row.id }, 'Could not read submission payload while completing todos');
    +    return;
    +  }
    +  if (!todoIds.length) return;
    +  try {
    +    await complete({
    +      todoIds, userId: row.user_id, repository: row.repository,
    +      issueNumber: row.issue_number, taskId: row.task_id,
    +    });
    +  } catch (error) {
    +    logger.warn({ error: (error as Error).message, submissionId: row.id, issueNumber: row.issue_number },
    +      'Task started, but its to-dos could not be marked complete');
    +  }
    +}
    +

    Make it injectable so tests can observe and fail it, then call it from both handlers:

    --- a/packages/api/routes/taskSubmissionRoutes.ts
    +++ b/packages/api/routes/taskSubmissionRoutes.ts
    @@
     export function createTaskSubmissionRoutes({ db, services = {} }: { db: Knex; services?: Partial<{
       authorize: typeof authorizeTaskSubmissionRepository;
       routing: typeof routing;
       getOctokit: typeof getAuthenticatedOctokit;
       processingLabels: typeof loadPrimaryProcessingLabels;
       enqueue: typeof enqueueIssueImplementationJob;
       images: SubmissionImageUploadServices;
    +  completeTodos: typeof completeTodosForIssue;
     }> }) {
       const checkAccess = services.authorize ?? authorizeTaskSubmissionRepository;
       const resolveRouting = services.routing ?? routing;
       const getOctokit = services.getOctokit ?? getAuthenticatedOctokit;
       const processingLabels = services.processingLabels ?? loadPrimaryProcessingLabels;
    +  const completeTodos = services.completeTodos ?? completeTodosForIssue;
    @@
           const result = await resumeTaskSubmission(db, row.id, submissionServices(await getOctokit(), services.enqueue, services.images));
    +      // The issue now exists, so the to-dos this task was launched from are done.
    +      await linkSubmissionTodos(result, completeTodos);
           res.status(result.state === 'queued' ? 200 : 202).json(publicSubmission(result));
         } catch (error) { await sendError(req, res, error); }
         finally { await removeTemporaryGoalUploads(files); }
       };
    @@
           const payload = JSON.parse(row.payload) as SubmissionPayload;
           await resolveRouting(payload);
    -      res.json(publicSubmission(await resumeTaskSubmission(db, row.id, submissionServices(await getOctokit(), services.enqueue, services.images))));
    +      const resumed = await resumeTaskSubmission(db, row.id, submissionServices(await getOctokit(), services.enqueue, services.images));
    +      // A retry may be the first attempt that got as far as creating the
    +      // issue, so the same completion runs here. It is idempotent.
    +      await linkSubmissionTodos(resumed, completeTodos);
    +      res.json(publicSubmission(resumed));
         } catch (error) { await sendError(req, res, error); }
       };

    File: packages/api/routes/repoTodoRoutes.ts

    Why this file: Demo mode reads repo_todos rows directly through this module's own toTodoDomain copy instead of going through the core service, so without this change a demo instance would silently drop the new fields and the UI chip would never appear there.

    --- a/packages/api/routes/repoTodoRoutes.ts
    +++ b/packages/api/routes/repoTodoRoutes.ts
    @@
     function toTodoDomain(record: RepoTodoRecord): RepoTodo {
       return {
         todoId: record.todo_id,
         categoryId: record.category_id,
         content: record.content,
         orderIndex: record.order_index,
         isCompleted: Boolean(record.is_completed),
         linkedDraftId: record.linked_draft_id,
    +    // Keep this mapper in step with the core service's: demo mode bypasses
    +    // the service, and a missing field here would hide the issue chip.
    +    linkedIssueRepository: record.linked_issue_repository ?? null,
    +    linkedIssueNumber: record.linked_issue_number ?? null,
    +    linkedTaskId: record.linked_task_id ?? null,
         createdAt: record.created_at,
         updatedAt: record.updated_at
       };
     }

    File: packages/api/mcp/toolsManagement.ts

    Why this file: list_todos hand-picks its columns, so MCP clients would otherwise see a to-do as completed with no explanation of why. Adding the columns makes the MCP view agree with the Web UI.

    --- a/packages/api/mcp/toolsManagement.ts
    +++ b/packages/api/mcp/toolsManagement.ts
    @@
           .select('todo.todo_id', 'todo.repository', 'todo.content', 'todo.is_completed', 'todo.category_id',
             'category.name as category_name', 'todo.linked_draft_id', 'plan.name as linked_plan_name',
    -        'plan.status as linked_plan_status', 'todo.order_index', 'todo.created_at', 'todo.updated_at')
    +        'plan.status as linked_plan_status',
    +        // Why a to-do is completed matters as much as that it is: these say
    +        // which issue the one-off task opened for it.
    +        'todo.linked_issue_repository', 'todo.linked_issue_number', 'todo.linked_task_id',
    +        'todo.order_index', 'todo.created_at', 'todo.updated_at')
           .orderBy('todo.order_index').orderBy('todo.id').offset(args.offset).limit(args.limit);

    Open packages/api/mcp/listSummaries.ts and check summarizeTodo. If it copies fields explicitly rather than spreading the row, add linkedIssueRepository, linkedIssueNumber and linkedTaskId to it from the selected columns; if it spreads, no change is needed.


    File: packages/cli/src/api/todos.ts

    Why this file: The CLI declares its own RepoTodo interface against the same endpoint. Leaving it behind would make propr's typed client disagree with the API it calls.

    --- a/packages/cli/src/api/todos.ts
    +++ b/packages/cli/src/api/todos.ts
    @@
     export interface RepoTodo {
       todoId: string;
       categoryId: string | null;
       content: string;
       orderIndex: number;
       isCompleted: boolean;
       linkedDraftId: string | null;
    +  /** Repository and issue opened when this to-do was launched as a task. */
    +  linkedIssueRepository: string | null;
    +  linkedIssueNumber: number | null;
    +  linkedTaskId: string | null;
       createdAt: string;
       updatedAt: string;
     }

    File: propr-ui/src/api/repoTodosApi.ts

    Why this file: The UI type drives the components. Without it, the chip's todo.linkedIssueNumber read is a TypeScript error.

    --- a/propr-ui/src/api/repoTodosApi.ts
    +++ b/propr-ui/src/api/repoTodosApi.ts
    @@
     export interface RepoTodo {
       todoId: string;
       categoryId: string | null;
       content: string;
       orderIndex: number;
       isCompleted: boolean;
       linkedDraftId: string | null;
    +  /** Set once the to-do was launched as a one-off task; null otherwise. */
    +  linkedIssueRepository: string | null;
    +  linkedIssueNumber: number | null;
    +  linkedTaskId: string | null;
       createdAt: string;
       updatedAt: string;
     }

    File: propr-ui/src/components/Repositories/RepoTodos/TodoIssueLink.tsx (new file)

    Why this file: The same chip is needed on active to-dos (SortableTodoItem) and completed ones (CompletedItemsAccordion). One shared component keeps the two in step and keeps the link-building logic in a single place.

    import React from 'react';
    import { CircleDot } from 'lucide-react';
    import { RepoTodo } from '../../../api/repoTodosApi';
    
    export interface TodoIssueLinkProps {
      todo: RepoTodo;
    }
    
    /**
     * Chip linking a to-do back to the GitHub issue a one-off task opened for it.
     * Mirrors the existing "Linked to plan" chip so the two ways a to-do can be
     * finished look like the same kind of fact.
     */
    const TodoIssueLink: React.FC<TodoIssueLinkProps> = ({ todo }) => {
      // Both halves are required: an issue number without its repository cannot
      // be turned into a URL, so the chip is shown only when the link is whole.
      if (!todo.linkedIssueNumber || !todo.linkedIssueRepository) return null;
    
      const href = `https://github.com/${todo.linkedIssueRepository}/issues/${todo.linkedIssueNumber}`;
      return (
        <a
          href={href}
          target="_blank"
          rel="noopener noreferrer"
          // The chip sits inside a row whose own click toggles selection, so the
          // click must not bubble.
          onClick={(e) => e.stopPropagation()}
          title={`Launched as issue #${todo.linkedIssueNumber} in ${todo.linkedIssueRepository}`}
          className="inline-flex items-center gap-1 mt-1 text-[10px] text-slate-600 bg-slate-100 hover:bg-slate-200 px-1.5 py-0.5 rounded transition-colors"
        >
          <CircleDot size={10} />
          #{todo.linkedIssueNumber}
        </a>
      );
    };
    
    export default TodoIssueLink;

    File: propr-ui/src/components/Repositories/RepoTodos/index.ts

    Why this file: It is the single entry point for the to-dos feature, so the chip must be re-exported for the panel and the tests to import it the same way as its siblings.

    --- a/propr-ui/src/components/Repositories/RepoTodos/index.ts
    +++ b/propr-ui/src/components/Repositories/RepoTodos/index.ts
    @@
     export { default as CompletedItemsAccordion } from './CompletedItemsAccordion';
     export { default as AddTodoInput } from './AddTodoInput';
    +export { default as TodoIssueLink } from './TodoIssueLink';
    +export type { TodoIssueLinkProps } from './TodoIssueLink';

    Match whatever export style the file already uses; the summary describes it as re-exporting the components and their prop types.


    File: propr-ui/src/components/Repositories/RepoTodos/SortableTodoItem.tsx

    Why this file: An active to-do can carry the link too — the user may have reopened it after the task finished — so the row has to be able to show where it came from.

    --- a/propr-ui/src/components/Repositories/RepoTodos/SortableTodoItem.tsx
    +++ b/propr-ui/src/components/Repositories/RepoTodos/SortableTodoItem.tsx
    @@
     import { GripVertical, Check, Trash2, Edit3, Sparkles } from 'lucide-react';
     import { RepoTodo } from '../../../api/repoTodosApi';
    +import TodoIssueLink from './TodoIssueLink';
    @@
    -        {todo.linkedDraftId && (
    -          <span className="inline-flex items-center gap-1 mt-1 text-[10px] text-teal-600 bg-teal-50 px-1.5 py-0.5 rounded">
    -            <Sparkles size={10} />
    -            Linked to plan
    -          </span>
    -        )}
    +        {/* The two ways a to-do becomes work sit side by side: a plan draft
    +            and a one-off task's issue. A to-do can carry both if it was
    +            planned first and then launched directly. */}
    +        <div className="flex flex-wrap items-center gap-1">
    +          {todo.linkedDraftId && (
    +            <span className="inline-flex items-center gap-1 mt-1 text-[10px] text-teal-600 bg-teal-50 px-1.5 py-0.5 rounded">
    +              <Sparkles size={10} />
    +              Linked to plan
    +            </span>
    +          )}
    +          <TodoIssueLink todo={todo} />
    +        </div>

    File: propr-ui/src/components/Repositories/RepoTodos/CompletedItemsAccordion.tsx

    Why this file: This is where a to-do completed by a launch now lands, so it is the most important place for the chip: without it the user sees a to-do that completed itself with no explanation.

    --- a/propr-ui/src/components/Repositories/RepoTodos/CompletedItemsAccordion.tsx
    +++ b/propr-ui/src/components/Repositories/RepoTodos/CompletedItemsAccordion.tsx
    @@
     import { Check, ChevronDown, ChevronRight, Trash2 } from 'lucide-react';
     import { RepoTodo } from '../../../api/repoTodosApi';
    +import TodoIssueLink from './TodoIssueLink';
    @@
    -              <p className="flex-1 text-sm text-slate-400 line-through break-words">
    -                {todo.content}
    -              </p>
    +              {/* The content and its provenance share one column so the
    +                  completion toggle and delete button keep their position. */}
    +              <div className="flex-1 min-w-0">
    +                <p className="text-sm text-slate-400 line-through break-words">
    +                  {todo.content}
    +                </p>
    +                {/* Explains an automatic completion: this to-do was launched
    +                    as a task, and here is the issue that was opened for it. */}
    +                <TodoIssueLink todo={todo} />
    +              </div>

    File: docs/docs/features/launching-work.md

    Why this file: It currently documents the old behaviour as a guarantee. Leaving it would make the shipped feature look like a bug.

    --- a/docs/docs/features/launching-work.md
    +++ b/docs/docs/features/launching-work.md
    @@
    -The repository workspace's **New task** action prefills the repository. Select a to-do and choose **Run task** to prefill its text; launching does not mark the to-do complete. Submission acceptance is not implementation completion. If submission reports a failure or uncertain issue creation, use the displayed recovery action instead of starting duplicate requests.
    +The repository workspace's **New task** action prefills the repository. Select a to-do and choose **Run task** to prefill its text. Once the task's GitHub issue is created, those to-dos are marked complete and record the issue they produced, so the repository workspace shows them under **Completed Items** with a link back to the issue. Reopen a to-do with its completion toggle if the run did not deliver what you wanted. Submission acceptance is not implementation completion. If submission reports a failure or uncertain issue creation, use the displayed recovery action instead of starting duplicate requests.

    File: CHANGELOG.md

    Why this file: Every user-visible behaviour change in this repository is recorded under Unreleased.

    --- a/CHANGELOG.md
    +++ b/CHANGELOG.md
    @@
     ### Changed
     
    +- **To-dos launched as a task are completed and linked to their issue**: a
    +  repository to-do turned into a one-off task through **Run task** (or MCP
    +  `create_task` with `todoIds`) is marked complete as soon as its GitHub
    +  issue is created, and records that issue so the to-do links back to it.
    +  Plan-linked to-dos are unchanged: they still complete when the plan merges.
    +  Reopen a to-do with its completion toggle if the run did not deliver.
    +

    Place the entry in the existing Unreleased → Changed section; create that heading if Unreleased does not have one yet.


    File: packages/core/test/repoTodosIssueLink.test.ts (new file)

    Why this file: The scoping rules (user_id and repository) and the idempotency are the parts most likely to be broken by a later refactor, and they are cheap to pin down against an in-memory SQLite database the way the other core service tests do.

    import assert from 'node:assert/strict';
    import { after, test } from 'node:test';
    import { closeConnection, db } from '../src/db/connection.js';
    import { up as createTodos } from '../src/db/migrations/20260317000000_create_repo_todos.js';
    import { up as addIssueLink } from '../src/db/migrations/20261013000000_add_todo_issue_link.js';
    import { completeTodosForIssue, getTodosForRepository } from '../src/services/repoTodosService.js';
    
    // The service writes through the shared `db` connection, so the suite runs
    // against that connection's schema rather than a separate Knex instance.
    async function fixture() {
      await db.schema.dropTableIfExists('repo_todos');
      await db.schema.dropTableIfExists('repo_todo_categories');
      await createTodos(db);
      await addIssueLink(db);
      await db('repo_todos').insert([
        { todo_id: 'mine', user_id: 'alice', repository: 'acme/billing', content: 'Fix invoice dates', order_index: 0, is_completed: false },
        { todo_id: 'other-user', user_id: 'bob', repository: 'acme/billing', content: 'Not mine', order_index: 1, is_completed: false },
        { todo_id: 'other-repo', user_id: 'alice', repository: 'acme/web', content: 'Other repository', order_index: 2, is_completed: false },
      ]);
    }
    
    after(closeConnection);
    
    test('completes only the submitter’s to-dos in the issue’s repository, and records the issue', async () => {
      await fixture();
      const updated = await completeTodosForIssue({
        todoIds: ['mine', 'other-user', 'other-repo', 'missing'],
        userId: 'alice', repository: 'acme/billing', issueNumber: 42, taskId: 'task-1',
      });
      assert.equal(updated, 1);
    
      const [mine] = await getTodosForRepository('alice', 'acme/billing');
      assert.equal(mine.isCompleted, true);
      assert.equal(mine.linkedIssueRepository, 'acme/billing');
      assert.equal(mine.linkedIssueNumber, 42);
      assert.equal(mine.linkedTaskId, 'task-1');
      // The plan link is a separate lifecycle and must not be touched.
      assert.equal(mine.linkedDraftId, null);
    
      const untouched = await db('repo_todos').whereIn('todo_id', ['other-user', 'other-repo']);
      for (const row of untouched) {
        assert.equal(Boolean(row.is_completed), false);
        assert.equal(row.linked_issue_number, null);
      }
    });
    
    test('repeating the same submission changes nothing further', async () => {
      await fixture();
      const params = { todoIds: ['mine'], userId: 'alice', repository: 'acme/billing', issueNumber: 42, taskId: null };
      await completeTodosForIssue(params);
      await completeTodosForIssue(params);
      const [mine] = await getTodosForRepository('alice', 'acme/billing');
      assert.equal(mine.linkedIssueNumber, 42);
      // A submission that has not been associated with a run yet leaves the
      // convenience pointer for a later retry to fill in.
      assert.equal(mine.linkedTaskId, null);
    });
    
    test('an empty selection never touches the database', async () => {
      await fixture();
      assert.equal(await completeTodosForIssue({ todoIds: [], userId: 'alice', repository: 'acme/billing', issueNumber: 42 }), 0);
      const [mine] = await getTodosForRepository('alice', 'acme/billing');
      assert.equal(mine.isCompleted, false);
    });

    If packages/core/test suites are listed individually in the root package.json scripts rather than globbed, add this file to the script that runs the other packages/core/test/*.test.ts suites.


    File: packages/api/test/taskSubmissionRoutes.test.ts

    Why this file: It already owns the submission route's contract, including its idempotency and failure handling, so the "a launch finishes its to-dos" and "a to-do failure never fails the submission" guarantees belong beside those cases.

    --- a/packages/api/test/taskSubmissionRoutes.test.ts
    +++ b/packages/api/test/taskSubmissionRoutes.test.ts
    @@
    +test('a submission completes the to-dos it was launched from, and a to-do failure never fails it', async () => {
    +  configureDemoMode(false);
    +  const db = await fixture();
    +  const completed: unknown[] = [];
    +  let failCompletion = true;
    +  const routes = createTaskSubmissionRoutes({ db, services: {
    +    authorize: async () => ({ id: 'repo', name: 'owner/repo', enabled: true }),
    +    routing: async () => ({ agentAlias: 'agent', model: 'model', routingLabel: 'llm-agent-model' }),
    +    processingLabels: async () => ['AI'],
    +    enqueue: async () => undefined,
    +    getOctokit: async () => ({ request: async (route: string) => {
    +      if (route.endsWith('/issues')) return { data: { number: 42, html_url: 'https://github.com/owner/repo/issues/42' } };
    +      if (route.endsWith('/timeline')) return { data: [] };
    +      return { data: {} };
    +    } }) as never,
    +    completeTodos: async params => {
    +      completed.push(params);
    +      // The issue exists and the run is queued; a to-do write that throws
    +      // must not change what the caller is told.
    +      if (failCompletion) throw new Error('todo table unavailable');
    +      return 1;
    +    },
    +  } });
    +  try {
    +    const first = response();
    +    await routes.submit(request({ repository: 'owner/repo', instruction: 'Fix invoice dates', todoIds: ['todo-1'] }), first.res);
    +    assert.equal(first.state.status, 200);
    +    assert.equal(first.state.body.state, 'queued');
    +    assert.deepEqual(completed, [{ todoIds: ['todo-1'], userId: 'alice', repository: 'owner/repo', issueNumber: 42, taskId: null }]);
    +
    +    // A retry resumes the same submission, so the same completion runs again
    +    // with the same issue: idempotent, not duplicated work.
    +    failCompletion = false;
    +    const retry = response();
    +    await routes.retry(request({}), retry.res);
    +    assert.equal(retry.state.status, 200);
    +    assert.equal(completed.length, 2);
    +
    +    // A submission with no to-dos must not reach the to-do layer at all.
    +    const plain = response();
    +    await routes.submit(request({ repository: 'owner/repo', instruction: 'Unrelated task' }, 'other-key'), plain.res);
    +    assert.equal(completed.length, 2);
    +  } finally { await db.destroy(); }
    +});
    +

    The suite's existing fixture() builds the task_submissions table from its migrations; completeTodos is stubbed, so no repo_todos table is needed here.


    File: propr-ui/src/components/Repositories/RepoTodos/TodoIssueLink.test.tsx (new file)

    Why this file: The chip's URL and its "only when the link is whole" rule are easy to get wrong and are what the user actually clicks.

    import { render, screen } from '@testing-library/react';
    import { describe, expect, it } from 'vitest';
    import TodoIssueLink from './TodoIssueLink';
    import type { RepoTodo } from '../../../api/repoTodosApi';
    
    const todo = (overrides: Partial<RepoTodo> = {}): RepoTodo => ({
      todoId: 'todo-1', categoryId: null, content: 'Fix invoice dates', orderIndex: 0,
      isCompleted: true, linkedDraftId: null, linkedIssueRepository: null,
      linkedIssueNumber: null, linkedTaskId: null,
      createdAt: '2026-10-08T09:00:00Z', updatedAt: '2026-10-08T09:00:00Z',
      ...overrides,
    });
    
    describe('TodoIssueLink', () => {
      it('links to the issue the to-do was launched as', () => {
        render(<TodoIssueLink todo={todo({ linkedIssueRepository: 'acme/billing', linkedIssueNumber: 42 })} />);
        const link = screen.getByRole('link', { name: '#42' });
        expect(link).toHaveAttribute('href', 'https://github.com/acme/billing/issues/42');
        expect(link).toHaveAttribute('target', '_blank');
        expect(link).toHaveAttribute('title', 'Launched as issue #42 in acme/billing');
      });
    
      it('renders nothing without a complete link', () => {
        // An issue number with no repository cannot be turned into a URL.
        const { container } = render(<TodoIssueLink todo={todo({ linkedIssueNumber: 42 })} />);
        expect(container).toBeEmptyDOMElement();
        expect(render(<TodoIssueLink todo={todo()} />).container).toBeEmptyDOMElement();
      });
    });

    Verification

    npm run migrate                   # applies 20261013000000_add_todo_issue_link
    npm run typecheck
    npm run lint
    node --test packages/core/test/repoTodosIssueLink.test.ts
    node --test packages/api/test/taskSubmissionRoutes.test.ts
    npx vitest run propr-ui/src/components/Repositories/RepoTodos

    Then exercise it by hand: open a repository workspace, add a to-do, select it, choose Run task, submit, and confirm the to-do moves to Completed Items with a #<number> chip that opens the new GitHub issue.

  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: 2886/claude-opus-5-5-complete-and-link-reposit-20261008-1428-1ry
    • Base Branch: main
    • Worktree: issue-2886-20261008-1428-claude-opus-5-5-1ry

    🔍 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