Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: extract buildJiraTicketTask from cosTaskRoutes into cosTaskGenerator (#2533)

Adam Eivyedad02906818
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 548d87c91b..12b92d1b18 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -52,3 +52,4 @@
- **[issue-2522] Deep-link Tribe tabs and fix form label associations.** The Tribe page's active section (Circle / Map / Care Queue / Focus) lived in local `useState`, so a section couldn't be shared, bookmarked, or survive a reload. It now reads from a `?tab=` URL search param (default `circle` omitted for a clean `/tribe`) with a valid-tab fallback for stale/unknown values — matching the PromptManager convention. Separately, the `StylePresetPicker` style-preset `<label>` and the Loops "Interval" `<label>` had no `htmlFor`/`id` pairing; both now associate with their control via a `useId()`-generated id so click-to-focus and screen readers work.
- **[issue-2527] Route client localStorage and keyboard activation through the shared `safeStorage`/`a11yKeyboard` helpers.** Several client sites bypassed the guarded `safeStorage` helpers with raw `window.localStorage` + hand-rolled `try/catch` (or `typeof window` guards), and several non-`<button>` clickables reimplemented the Enter/Space `onKeyDown` handler inline. Storage reads/writes in `Security.jsx`, `PipelineManuscriptEditor.jsx`, `voiceVisibility.js`, `MortalLoomBanner.jsx`, `WhileAwayWidget.jsx`, and `ManuscriptReadAloud.jsx` now go through `safeReadStorage`/`safeReadJsonStorage`/`safeWriteStorage`/`safeRemoveStorage`; keyboard activation in `IngredientPicker.jsx`, `ManuscriptReadAloud.jsx`, `EditorialHealthPanel.jsx`, `TribeCircleMap.jsx`, and `GenomeTab.jsx` now spreads `clickableProps(handler)` (which supplies `role`/`tabIndex`/`onKeyDown` via the shared `onActivateKeyDown`). Behavior is preserved — same storage keys, same JSON-parse fallbacks and corrupt-entry cleanup, same Enter/Space activation.
- **[issue-2545] Add `aria-label`s to icon-only controls and fix Templates/MessageDetail form labels.** Several icon-only buttons exposed their purpose only via `title` (unreliable for screen readers): the MessageDetail toolbar (Reply, voice-mode toggle, AI Reply, Refresh, Archive, Delete), MusicVideo scene move-up/move-down/delete, MediaCard hide/delete, the MediaJobsQueue per-job cancel, Review's edit save/cancel, and DuplicateGroup rename now carry an `aria-label` matching their `title`. The MessageDetail reply `<textarea>` (previously placeholder-only) gains an `aria-label`, and the Templates "Target Directory" `<label>` is now wired to its input via `htmlFor`/`id` so click-to-focus and screen readers work. Accessibility attributes only — no behavior or styling change.
+- **[issue-2533] Extract JIRA-ticket claim assembly out of the route into `buildJiraTicketTask` (next to `buildClaimWorkTask`).** `POST /api/cos/tasks/jira-ticket` (the sprint-board per-card play button) inlined its reviewer-CSV resolution (`resolveClaimReviewersCsv`), the target-ticket constraint block (`buildTargetTicketBlock`), and the `claim-issue-jira` prompt assembly directly in `server/routes/cosTaskRoutes.js`. That logic now lives in `server/services/cosTaskGenerator.js` as an exported `buildJiraTicketTask(app, ticketKey)` that returns `{ ticketKey, prompt, taskMetadata }` — beside `buildClaimWorkTask`, sharing the same reviewer/isolation conventions. The route stays thin: validate → JIRA-enabled gate → assemble → queue. Pure refactor — the queued task's context, description, and `useWorktree/openPR` posture are byte-for-byte unchanged; new unit tests cover the extracted assembly.
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index a64f16e62d..03c23f958b 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -8,10 +8,8 @@ import * as cos from '../services/cos.js';
import * as taskWatcher from '../services/taskWatcher.js';
import { enhanceTaskPrompt } from '../services/taskEnhancer.js';
import { loadSlashdoCommand } from '../services/subAgentSpawner.js';
-import { buildClaimWorkTask } from '../services/cosTaskGenerator.js';
+import { buildClaimWorkTask, buildJiraTicketTask } from '../services/cosTaskGenerator.js';
import { getAppById } from '../services/apps.js';
-import { getTaskPrompt } from '../services/taskPromptService.js';
-import { getCodeReviewDefaults } from '../services/codeReview.js';
import { workTrackerLabel } from '../lib/workTracker.js';
import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
import {
@@ -20,9 +18,6 @@ import {
challengeTaskSchema,
resolveChallengeSchema,
validateRequest,
- normalizeReviewers,
- buildReviewersCsv,
- LOCAL_LLM_REVIEWERS,
isPaginationRequested,
parsePagination,
} from '../lib/validation.js';
@@ -39,33 +34,6 @@ const jiraTicketTaskSchema = z.object({
ticketKey: z.string().trim().regex(/^[A-Za-z][A-Za-z0-9]*-\d+$/, 'Invalid JIRA ticket key'),
});
-// Resolve the reviewers CSV for the claim flow exactly as buildClaimWorkTask
-// does (Code Review Defaults, minus local-LLM reviewers the claim prompt can't
-// drive, falling back to the hardcoded default). Mirrors the scheduled
-// claim-work resolution so the play button honors the user's reviewer choice.
-async function resolveClaimReviewersCsv() {
- const codeReviewDefaults = await getCodeReviewDefaults().catch(() => null);
- const list = normalizeReviewers({}, codeReviewDefaults?.reviewers)
- .filter((r) => !LOCAL_LLM_REVIEWERS.includes(r));
- // Arbitrary GitHub reviewer usernames from the Code Review Defaults, appended
- // as `@user` tokens so the play button's claim gates the merge on them too.
- // Optional-reviewer set rides along so a `~opt` reviewer stays non-blocking.
- return buildReviewersCsv(list, codeReviewDefaults?.usernames, codeReviewDefaults?.optionalReviewers);
-}
-
-// Append a "claim exactly this ticket" constraint to the claim-issue-jira body
-// — the JIRA analogue of buildPlanConstraintBlock. The base prompt's Phase 1
-// tells the agent to PICK the next-ready ticket; this overrides that to pin the
-// user's selection while keeping every safety check (already-claimed, stale,
-// too-ambiguous → exit cleanly).
-function buildTargetTicketBlock(ticketKey) {
- return `
-
-## Target Ticket Constraint
-
-The user explicitly selected JIRA ticket \`${ticketKey}\` from the board. Override Phase 1 ("Pick the target ticket"): do NOT pick a different ticket and do NOT scan for the next-ready one — claim exactly \`${ticketKey}\`. Still honor the safety checks: if \`${ticketKey}\` is already In Progress / In Review / Done / closed, is already on a \`claim/${ticketKey}\` (or \`cos/.../${ticketKey}/...\`) branch, or its requirements are too ambiguous or too large to implement in a single PR, exit cleanly (file a Review Hub todo for ambiguous requirements) rather than forcing it. Otherwise run Phases 2–7 against \`${ticketKey}\`.`;
-}
-
const SLASHDO_COMMANDS = {
push: { label: 'Push', description: 'Commit and push all work with changelog' },
review: { label: 'Review', description: 'Deep code review of changed files' },
@@ -209,7 +177,6 @@ router.post('/tasks/slashdo', asyncHandler(async (req, res) => {
// the 7-phase body. Queue-only: the daemon picks it up on the next evaluation.
router.post('/tasks/jira-ticket', asyncHandler(async (req, res) => {
const { app, ticketKey } = validateRequest(jiraTicketTaskSchema, req.body);
- const key = ticketKey.toUpperCase();
const appObj = await getAppById(app);
if (!appObj) {
@@ -219,31 +186,16 @@ router.post('/tasks/jira-ticket', asyncHandler(async (req, res) => {
throw new ServerError(`JIRA is not enabled for ${appObj.name}`, { status: 400, code: 'JIRA_NOT_ENABLED' });
}
- // Resolve the claim-issue-jira body directly (not via buildClaimWorkTask) —
- // an app can show a JIRA board while its general Work Tracker resolves to
- // GitHub/PLAN, so route the click to the JIRA flow regardless of that setting.
- // Independent reads (prompt body + Code Review Defaults) — fetch concurrently.
- const [template, reviewersCsv] = await Promise.all([
- getTaskPrompt('claim-issue-jira'),
- resolveClaimReviewersCsv(),
- ]);
- const context = template
- .replace(/\{appName\}/g, appObj.name)
- .replace(/\{repoPath\}/g, appObj.repoPath)
- .replace(/\{appId\}/g, appObj.id)
- // Function-form replacer so a literal `$` in the reviewers CSV isn't read as
- // a backreference.
- .replace(/\{reviewers\}/g, () => reviewersCsv)
- + buildTargetTicketBlock(key);
-
- // claim-issue-jira self-manages its worktree + MR/PR, so leave both false
- // (matching the /do:next slashdo default for the JIRA tracker).
+ // Assemble the claim-issue-jira prompt + target-ticket constraint in the
+ // generator service (shared with the scheduled JIRA claim flow). The route
+ // stays thin: validate → gate → assemble → queue.
+ const { ticketKey: key, prompt, taskMetadata } = await buildJiraTicketTask(appObj, ticketKey);
+
const taskData = {
description: `Claim JIRA ticket ${key} for ${appObj.name} — implement and ship a PR`,
app,
- context,
- useWorktree: false,
- openPR: false,
+ context: prompt,
+ ...taskMetadata,
simplify: false,
reviewLoop: false,
};
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 373021f561..15c64cde85 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -365,6 +365,73 @@ export async function buildClaimWorkTask(app, { issueAuthorFilter, reviewers } =
return { tracker: wt.resolved, source: wt.source, promptTaskType, prompt, taskMetadata };
}
+/**
+ * Resolve the reviewers CSV for the claim flow exactly as buildClaimWorkTask
+ * does (Code Review Defaults, minus local-LLM reviewers the claim prompt can't
+ * drive, falling back to the hardcoded default). Mirrors the scheduled
+ * claim-work resolution so the JIRA play button honors the user's reviewer choice.
+ */
+async function resolveClaimReviewersCsv() {
+ const codeReviewDefaults = await getCodeReviewDefaults().catch(() => null);
+ const list = normalizeReviewers({}, codeReviewDefaults?.reviewers)
+ .filter((r) => !LOCAL_LLM_REVIEWERS.includes(r));
+ // Arbitrary GitHub reviewer usernames from the Code Review Defaults, appended
+ // as `@user` tokens so the play button's claim gates the merge on them too.
+ // Optional-reviewer set rides along so a `~opt` reviewer stays non-blocking.
+ return buildReviewersCsv(list, codeReviewDefaults?.usernames, codeReviewDefaults?.optionalReviewers);
+}
+
+/**
+ * Append a "claim exactly this ticket" constraint to the claim-issue-jira body
+ * — the JIRA analogue of buildPlanConstraintBlock. The base prompt's Phase 1
+ * tells the agent to PICK the next-ready ticket; this overrides that to pin the
+ * user's selection while keeping every safety check (already-claimed, stale,
+ * too-ambiguous → exit cleanly).
+ */
+function buildTargetTicketBlock(ticketKey) {
+ return `
+
+## Target Ticket Constraint
+
+The user explicitly selected JIRA ticket \`${ticketKey}\` from the board. Override Phase 1 ("Pick the target ticket"): do NOT pick a different ticket and do NOT scan for the next-ready one — claim exactly \`${ticketKey}\`. Still honor the safety checks: if \`${ticketKey}\` is already In Progress / In Review / Done / closed, is already on a \`claim/${ticketKey}\` (or \`cos/.../${ticketKey}/...\`) branch, or its requirements are too ambiguous or too large to implement in a single PR, exit cleanly (file a Review Hub todo for ambiguous requirements) rather than forcing it. Otherwise run Phases 2–7 against \`${ticketKey}\`.`;
+}
+
+/**
+ * Build a one-off "implement THIS JIRA ticket" task for `app` — the per-card
+ * "play" button on the app overview's sprint board (the JIRA analogue of the
+ * `/do:next` claim button). Resolves the `claim-issue-jira` prompt body directly
+ * (NOT via buildClaimWorkTask — an app can show a JIRA board while its general
+ * Work Tracker resolves to GitHub/PLAN, so route the click to the JIRA flow
+ * regardless of that setting), substitutes the standard placeholders, and appends
+ * a target-ticket constraint that pins the agent to `ticketKey` while keeping
+ * every claim safety check. `ticketKey` is normalized to upper-case (`PROJ-1234`).
+ *
+ * claim-issue-jira self-manages its worktree + MR/PR, so `taskMetadata` stays
+ * `false/false` (matching the `/do:next` slashdo default for the JIRA tracker).
+ *
+ * @returns {Promise<{ ticketKey: string, prompt: string, taskMetadata: { useWorktree: boolean, openPR: boolean } }>}
+ */
+export async function buildJiraTicketTask(app, ticketKey) {
+ const { getTaskPrompt } = await import('./taskPromptService.js');
+ const key = String(ticketKey || '').toUpperCase();
+
+ // Independent reads (prompt body + Code Review Defaults) — fetch concurrently.
+ const [template, reviewersCsv] = await Promise.all([
+ getTaskPrompt('claim-issue-jira'),
+ resolveClaimReviewersCsv(),
+ ]);
+ const prompt = template
+ .replace(/\{appName\}/g, app.name)
+ .replace(/\{repoPath\}/g, app.repoPath)
+ .replace(/\{appId\}/g, app.id)
+ // Function-form replacer so a literal `$` in the reviewers CSV isn't read as
+ // a backreference.
+ .replace(/\{reviewers\}/g, () => reviewersCsv)
+ + buildTargetTicketBlock(key);
+
+ return { ticketKey: key, prompt, taskMetadata: { useWorktree: false, openPR: false } };
+}
+
/**
* For feature-ideas / plan-task, read the target repo's PLAN.md, find which
* item IDs are already in flight via branch/PR scan, and pick the first
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 1a6d7673fe..c345353b20 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -11,11 +11,24 @@
* (under-report). These tests pin both behaviors.
*/
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi } from 'vitest';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
-import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask, emitOnDemandEmpty } from './cosTaskGenerator.js';
+
+// buildJiraTicketTask resolves the claim-issue-jira prompt body (dynamic import)
+// and the Code Review Defaults (static import). Mock both leaf services so the
+// behavioral test below drives the assembly without touching disk/settings.
+vi.mock('./taskPromptService.js', async (importActual) => ({
+ ...(await importActual()),
+ getTaskPrompt: vi.fn(async (key) => `# ${key}\nApp {appName} at {repoPath} (id {appId})\nReviewers: {reviewers}`),
+}));
+vi.mock('./codeReview.js', async (importActual) => ({
+ ...(await importActual()),
+ getCodeReviewDefaults: vi.fn(async () => ({ reviewers: ['copilot'], usernames: ['alice'], optionalReviewers: [] })),
+}));
+
+import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask, emitOnDemandEmpty, buildJiraTicketTask } from './cosTaskGenerator.js';
import { cosEvents } from './cosEvents.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
@@ -227,6 +240,39 @@ describe('claim-work single-source routing', () => {
});
});
+// buildJiraTicketTask is the per-card "play" button's prompt assembly, extracted
+// out of cosTaskRoutes.js so the route stays thin (validate → gate → assemble →
+// queue) and the claim-reviewer + target-ticket logic lives next to
+// buildClaimWorkTask. Exercised directly with mocked leaf services.
+describe('buildJiraTicketTask', () => {
+ const app = { id: 'acme', name: 'Acme App', repoPath: '/repos/acme' };
+
+ it('substitutes app placeholders + reviewers and appends the target-ticket constraint', async () => {
+ const { ticketKey, prompt, taskMetadata } = await buildJiraTicketTask(app, 'proj-1234');
+ // Placeholders resolved from the app object.
+ expect(prompt).toContain('App Acme App at /repos/acme (id acme)');
+ // {reviewers} substituted (no literal placeholder left) with the Code Review
+ // Defaults reviewer + @username token.
+ expect(prompt).not.toContain('{reviewers}');
+ expect(prompt).toContain('copilot');
+ expect(prompt).toContain('@alice');
+ // Target-ticket constraint pins the uppercased key.
+ expect(prompt).toContain('## Target Ticket Constraint');
+ expect(prompt).toContain('PROJ-1234');
+ // Ticket key normalized to upper-case.
+ expect(ticketKey).toBe('PROJ-1234');
+ // claim-issue-jira self-manages worktree + PR.
+ expect(taskMetadata).toEqual({ useWorktree: false, openPR: false });
+ });
+
+ it('is exported so the /tasks/jira-ticket route reuses the shared assembly', () => {
+ expect(GEN_SRC).toContain('export async function buildJiraTicketTask(');
+ // Routes the JIRA flow directly, not via buildClaimWorkTask.
+ expect(GEN_SRC).toMatch(/buildJiraTicketTask[\s\S]*getTaskPrompt\('claim-issue-jira'\)/);
+ expect(GEN_SRC).toMatch(/buildJiraTicketTask[\s\S]*buildTargetTicketBlock\(key\)/);
+ });
+});
+
// The {issueAuthorFilter} directive is shared by the scheduled claim-work router
// AND the manual /do:next button (buildClaimWorkTask), so it is a standalone
// pure helper. These exercise it directly rather than via source string.