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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: move the manual claim/JIRA/replan prompt builders out of the CoS scheduling engine
Adam Eivy57c4114b8855
diff --git a/server/routes/apps/taskTypes.js b/server/routes/apps/taskTypes.jsindex 52366a8e62..2bcee8387f 100644--- a/server/routes/apps/taskTypes.js+++ b/server/routes/apps/taskTypes.js@@ -26,7 +26,7 @@ import { PORTOS_APP_ID } from '../../services/apps.js';import { sanitizeTaskMetadata, ISSUE_AUTHOR_FILTERS, validateRequest, qualitySchedulePlanSchema, appTaskTypeToggleBodySchema, appTaskTypeOverrideBodySchema } from '../../lib/validation.js';import { buildQualitySchedulePlan, applyQualitySchedulePlan } from '../../services/appQualitySchedule.js';import { listWorkItems } from '../../services/workItems.js';-import { resolveClaimWorkMetadata, resolveClaimAuthorFilter, resolveAppClaimReviewers } from '../../services/cosTaskGenerator.js';+import { resolveClaimWorkMetadata, resolveClaimAuthorFilter, resolveAppClaimReviewers } from '../../services/cosTaskClaimWork.js';import { INTERVAL_TYPES, decodeIntervalType, isCronExpression, isKnownIntervalType } from '../../services/taskScheduleConstants.js';import { findCronExpressionError } from '../../lib/cronValidation.js';import { asyncHandler, ServerError } from '../../lib/errorHandler.js';diff --git a/server/routes/apps/taskTypes.test.js b/server/routes/apps/taskTypes.test.jsindex 602902e316..b29197f129 100644--- a/server/routes/apps/taskTypes.test.js+++ b/server/routes/apps/taskTypes.test.js@@ -40,7 +40,7 @@ vi.mock('../../services/appQualitySchedule.js', () => ({buildQualitySchedulePlan: vi.fn(),applyQualitySchedulePlan: vi.fn()}));-vi.mock('../../services/cosTaskGenerator.js', async (importActual) => ({+vi.mock('../../services/cosTaskClaimWork.js', async (importActual) => ({...(await importActual()),resolveClaimWorkMetadata: vi.fn(),resolveAppClaimReviewers: vi.fn()@@ -50,7 +50,7 @@ import * as appsService from '../../services/apps.js';import { listOutcomesResult } from '../../services/layeredIntelligenceOutcomes.js';import { listWorkItems } from '../../services/workItems.js';import { buildQualitySchedulePlan, applyQualitySchedulePlan } from '../../services/appQualitySchedule.js';-import { resolveClaimWorkMetadata, resolveAppClaimReviewers } from '../../services/cosTaskGenerator.js';+import { resolveClaimWorkMetadata, resolveAppClaimReviewers } from '../../services/cosTaskClaimWork.js';describe('Apps Task-Type Routes', () => {let app;@@ -129,7 +129,7 @@ describe('Apps Task-Type Routes', () => {// `source` label the UI acts on, and publish only the fields a claim flow can// honor. The reviewer RESOLUTION it previews (layer precedence, copilot guard,// emitted CSV) belongs to `resolveAppClaimReviewers`, which the claim builder- // shares — covered in cosTaskGenerator.test.js and reviewerConfig.test.js.+ // shares — covered in cosTaskClaimWork.test.js and reviewerConfig.test.js.describe('GET /api/apps/:id/claim-reviewers', () => {const RESOLVED = {reviewers: ['codex', 'claude'], usernames: [], optionalReviewers: [],diff --git a/server/routes/cos.test.js b/server/routes/cos.test.jsindex e2cc41f968..6b829b2a96 100644--- a/server/routes/cos.test.js+++ b/server/routes/cos.test.js@@ -121,7 +121,7 @@ vi.mock('../services/subAgentSpawner.js', () => ({// real buildJiraTicketTask runs so the `/tasks/jira-ticket` route still exercises// the extracted prompt assembly — it resolves getTaskPrompt/getCodeReviewDefaults,// which are mocked below, so the route-level assertions stay verbatim.-vi.mock('../services/cosTaskGenerator.js', async (importActual) => ({+vi.mock('../services/cosTaskClaimWork.js', async (importActual) => ({...(await importActual()),buildClaimWorkTask: vi.fn(),buildIssueReplanTask: vi.fn()@@ -153,7 +153,7 @@ import * as appActivity from '../services/appActivity.js';import * as claudeChangelog from '../services/claudeChangelog.js';import { enhanceTaskPrompt } from '../services/taskEnhancer.js';import { loadSlashdoCommand } from '../services/subAgentSpawner.js';-import { buildClaimWorkTask, buildIssueReplanTask } from '../services/cosTaskGenerator.js';+import { buildClaimWorkTask, buildIssueReplanTask } from '../services/cosTaskClaimWork.js';import { getAppById, getAppWorkTracker } from '../services/apps.js';import { getTaskPrompt } from '../services/taskPromptService.js';import { getCodeReviewDefaults } from '../services/codeReview.js';diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.jsindex f7b3580383..7446a14ffa 100644--- a/server/routes/cosTaskRoutes.js+++ b/server/routes/cosTaskRoutes.js@@ -7,7 +7,7 @@ import { z } from 'zod';import * as cos from '../services/cos.js';import * as taskWatcher from '../services/taskWatcher.js';import { enhanceTaskPrompt } from '../services/taskEnhancer.js';-import { buildClaimWorkTask, buildIssueReplanTask, buildJiraTicketTask } from '../services/cosTaskGenerator.js';+import { buildClaimWorkTask, buildIssueReplanTask, buildJiraTicketTask } from '../services/cosTaskClaimWork.js';import { getAppById, getAppWorkTracker, PORTOS_APP_ID } from '../services/apps.js';import { prepareAppIssueClaim } from '../services/appIssues.js';import { getAssignableInstances } from '../services/instances.js';diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.jsindex 3be388efa7..1cb158425b 100644--- a/server/routes/cosTaskRoutes.test.js+++ b/server/routes/cosTaskRoutes.test.js@@ -60,7 +60,7 @@ vi.mock('../services/cos.js', () => ({}));vi.mock('../services/taskWatcher.js', () => ({ refreshTasks: vi.fn() }));vi.mock('../services/taskEnhancer.js', () => ({ enhanceTaskPrompt: vi.fn() }));-vi.mock('../services/cosTaskGenerator.js', () => ({+vi.mock('../services/cosTaskClaimWork.js', () => ({buildClaimWorkTask: vi.fn(),buildJiraTicketTask: vi.fn(),}));diff --git a/server/services/cosTaskClaimWork.js b/server/services/cosTaskClaimWork.jsnew file mode 100644index 0000000000..7929b17520--- /dev/null+++ b/server/services/cosTaskClaimWork.js@@ -0,0 +1,406 @@+/**+ * CoS Claim-Work Task Builders+ *+ * The one-off, user-triggered prompt builders behind the managed-app buttons:+ * - `buildClaimWorkTask` — the Issues-tab / `/do:next` "claim the next work item"+ * button, routed by the app's configured work tracker.+ * - `buildJiraTicketTask` — the sprint-board per-card "play" button.+ * - `buildIssueReplanTask` — the Issues-tab Replan button.+ * - `resolveClaimWorkMetadata` / `resolveClaimAuthorFilter` /+ * `resolveAppClaimReviewers` — the configured-claim resolution those builders+ * share, also read by the work-item picker route, the claim-reviewer lookup+ * route, and the development watchdog so each previews exactly what a claim+ * run will use.+ *+ * Split out of `cosTaskGenerator.js` (the periodic scheduling engine) because+ * none of these run inside `evaluateTasks`, yet the routes and the watchdog had+ * to import the whole scheduler graph to reach them. Nothing here imports the+ * generator back; `taskSchedule.js` is imported lazily, as the generator does.+ */++import { sanitizeTaskMetadata, resolveClaimReviewerConfig, reviewerConfigMetadata, hasReviewerOverride } from '../lib/validation.js';+import { applyAppPlaceholders } from '../lib/appPromptPlaceholders.js';+import { PR_COMPLETIONS } from '../lib/prDisposition.js';+import { ServerError } from '../lib/errorHandler.js';+import { getAppTaskTypeOverrides } from './apps.js';+import { getCodeReviewDefaults } from './codeReview.js';+import {+ appendClaimOverrideContext,+ appendPrefetchedIssueContext,+ appendReviewerEffortBlock,+ appendTargetWorkItemBlock,+ buildLocalReviewerInstructions,+ buildIssueReplanPrompt,+ normalizeWorkItemRef,+} from './cosTaskPrompts.js';+import {+ resolveIssueAuthorFilterBlock,+ resolveIssueCandidateListBlock,+ resolveIssueExcludeLabelsBlock,+ resolveSwarmBlock,+} from './cosTaskPreStepBlocks.js';++// `normalizeClaimReviewers` moved to server/lib/reviewerConfig.js (#4770, #5702): the+// prompt builder needs the same copilot guard when it re-resolves reviewers off+// a persisted claim task, and a service-level definition would have meant a+// second copy there.++/**+ * Resolve an app's configured claim metadata the same way the scheduled+ * router does: global schedule metadata, then per-app overrides on top (managed+ * agent fields stripped, both passes sanitized/value-constrained). This is what+ * carries the user's `issueAuthorFilter`, reviewer, and swarm choices into the+ * prompt. Shared by `buildClaimWorkTask` and the work-item picker route, so the+ * items offered are scanned with the SAME author filter the claim agent will use.+ *+ * @returns {Promise<{ metadata: object, interval: object }>}+ */+export async function resolveClaimWorkMetadata(app, taskType = 'claim-work') {+ const taskSchedule = await import('./taskSchedule.js');+ // Independent reads (schedule config + per-app overrides) — the merge below+ // needs both, but neither depends on the other.+ const [interval, appOverrides] = await Promise.all([+ taskSchedule.getTaskInterval(taskType),+ getAppTaskTypeOverrides(app.id)+ ]);+ const metadata = {};+ const sanitizedGlobalMeta = sanitizeTaskMetadata(interval.taskMetadata);+ if (sanitizedGlobalMeta) Object.assign(metadata, sanitizedGlobalMeta);+ const strippedAppOverride = taskSchedule.stripManagedAgentOptionsFromOverride(+ taskType, appOverrides[taskType]?.taskMetadata+ );+ const sanitizedAppMeta = sanitizeTaskMetadata(strippedAppOverride);+ if (sanitizedAppMeta) Object.assign(metadata, sanitizedAppMeta);+ return { metadata, interval };+}++/**+ * The author filter a claim run will actually apply: explicit option >+ * configured `claim-work` metadata > `'self'` (the slashdo `/do:next --self`+ * security boundary — only claim issues you filed).+ */+export function resolveClaimAuthorFilter(explicit, metadata) {+ return explicit ?? metadata?.issueAuthorFilter ?? 'self';+}++/**+ * The reviewer bundle a claim will run: an explicit option wins per field, then+ * the app's configured `claim-work` metadata, then the Code Review Defaults. One+ * resolver for the whole bundle (list + usernames + `~opt` set + the three keyed+ * pins), so the CSV the prompt names and the `reviewers` the task PERSISTS cannot+ * disagree. Local-LLM reviewers stay in the operative list; the claim prompt's+ * appended Local Reviewer Procedure tells the agent how to invoke PortOS's review+ * service rather than silently replacing the user's configured reviewer.+ *+ * Shared with `resolveAppClaimReviewers` (and through it the claim-reviewer+ * lookup route) precisely so a change to this precedence reaches the preview the+ * UI shows and the run it previews at the same time — the two drifting apart is+ * the whole defect that lookup exists to close.+ */+function claimReviewersFrom(metadata, codeReviewDefaults, explicit = {}) {+ const { reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, prCompletion } = explicit;+ return resolveClaimReviewerConfig({+ ...metadata,+ ...(prCompletion !== undefined ? { prCompletion } : {}),+ reviewers: reviewers !== undefined ? (Array.isArray(reviewers) ? reviewers : [reviewers]) : metadata?.reviewers,+ usernames: usernames ?? metadata?.usernames,+ optionalReviewers: optionalReviewers ?? metadata?.optionalReviewers,+ reviewerMaxRounds: reviewerMaxRounds ?? metadata?.reviewerMaxRounds,+ reviewerModels: reviewerModels ?? metadata?.reviewerModels,+ reviewerEfforts: reviewerEfforts ?? metadata?.reviewerEfforts+ }, codeReviewDefaults, codeReviewDefaults?.reviewers);+}++/**+ * What a `/do:next` claim would resolve for `app` right now, without queuing one:+ * the reviewer bundle plus `overridden`, which says whether the claim-work task+ * metadata supplied any of the list (so the UI can send the user to the override+ * rather than to the Code Reviewers panel that isn't in play).+ *+ * Reads the same two layers `buildClaimWorkTask` does and hands them to the same+ * `claimReviewersFrom`, so the preview cannot report a chain the run won't use.+ */+export async function resolveAppClaimReviewers(app) {+ // Independent reads — the resolver needs both, but neither depends on the other.+ const [{ metadata }, codeReviewDefaults] = await Promise.all([+ resolveClaimWorkMetadata(app),+ // A settings read failure means "no configured defaults", never a failed+ // lookup: the task metadata layer wins over them anyway.+ getCodeReviewDefaults().catch(() => null)+ ]);+ const prCompletion = metadata?.prCompletion || app?.defaultPrCompletion || PR_COMPLETIONS.REVIEW_THEN_MERGE;+ return {+ ...claimReviewersFrom(metadata, codeReviewDefaults, { prCompletion }),+ prCompletion,+ overridden: hasReviewerOverride(metadata) || !!metadata?.prCompletion+ };+}++/**+ * Build a one-off "claim the next work item" task for `app`, routed by the app's+ * configured workTracker — the manual (Slashdo `/do:next` button) counterpart to+ * the scheduled `claim-work` router in cosTaskGenerator.js. Resolves the tracker, delegates to the+ * matching claim prompt body (plan-task / claim-issue / claim-issue-gitlab /+ * claim-issue-jira), substitutes the standard placeholders, and surfaces the+ * delegated flow's worktree/PR posture. `claimFlow` separately marks that the+ * prompt owns its worktree + MR/PR lifecycle; false/false remains the correct+ * CoS provisioning posture because a nested CoS worktree would conflict with+ * the claim branch.+ *+ * `issueAuthorFilter` and the reviewer options default to the app's *configured*+ * `claim-work` behavior (global schedule metadata → per-app override → Code+ * Review Defaults), exactly as the scheduled `claim-work` router resolves them —+ * so clicking the button honors `issueAuthorFilter: 'any'` and non-Copilot+ * reviewers instead of silently forcing owner-only + Copilot. A direct+ * `claim-work` prompt customization likewise overrides the tracker-specific body+ * (matching the scheduled router's `promptKeyForBody` selection). Explicit+ * options still win when a caller passes them.+ *+ * `target` pins the run to ONE work item (the drawer's "pick a specific item"+ * mode) by appending the tracker-appropriate constraint block, overriding the+ * prompt's own Phase 1 pick while keeping every claim safety check. A matching+ * `issueContext` from the managed-app Issues tab is appended for forge targets+ * so the agent can use the already-fetched title/body without retrieving it a+ * second time.+ *+ * @returns {Promise<{ tracker, source, promptTaskType, prompt, taskMetadata, target }>}+ */+export async function buildClaimWorkTask(app, {+ issueAuthorFilter,+ reviewers,+ usernames,+ optionalReviewers,+ reviewerMaxRounds,+ reviewerModels,+ reviewerEfforts,+ prCompletion,+ target,+ issueContext,+ overrideContext+} = {}) {+ const { resolveAppWorkTracker, trackerToClaimTaskType } = await import('../lib/workTracker.js');+ const { getTaskPrompt } = await import('./taskPromptService.js');+ const taskSchedule = await import('./taskSchedule.js');++ // The tracker probe (a `git` shell-out), the configured claim-work metadata,+ // and the Code Review Defaults are mutually independent — only the prompt-body+ // read below depends on them, so overlap the three.+ const [wt, { metadata, interval }, codeReviewDefaults] = await Promise.all([+ resolveAppWorkTracker(app),+ resolveClaimWorkMetadata(app),+ getCodeReviewDefaults().catch(() => null)+ ]);+ const promptTaskType = trackerToClaimTaskType(wt.resolved) || 'plan-task';++ // Honor a direct claim-work prompt customization if the user set one;+ // otherwise delegate to the resolved tracker's prompt body. Mirrors the+ // scheduled router's `promptKeyForBody` selection — a custom claim-work prompt+ // overrides the tracker-specific body for both paths.+ const template = await getTaskPrompt(+ interval.prompt ? 'claim-work' : promptTaskType,+ { claimFlow: true }+ );++ const resolvedAuthorFilter = resolveClaimAuthorFilter(issueAuthorFilter, metadata);+ const effectivePrCompletion = prCompletion ?? metadata?.prCompletion ?? app?.defaultPrCompletion;++ const claimReviewers = claimReviewersFrom(metadata, codeReviewDefaults, {+ reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts,+ ...(effectivePrCompletion !== undefined ? { prCompletion: effectivePrCompletion } : {})+ });+ const {+ reviewers: reviewersList,+ reviewerModels: promptReviewerModels,+ reviewerEfforts: promptReviewerEfforts,+ csv: reviewersCsv+ } = claimReviewers;+ const issueAuthorFilterBlock = resolveIssueAuthorFilterBlock(promptTaskType, resolvedAuthorFilter);+ const issueExcludeLabelsBlock = resolveIssueExcludeLabelsBlock(metadata.issueExcludeLabels);+ // Swarm mode (`/do:next --swarm`) is prepended (not an in-template+ // placeholder) so it stays an opt-in orchestration wrapper that needs no+ // prompt-default version bump; empty when swarmCount is off or the tracker+ // isn't a forge issue tracker. {reviewers} inside the block is substituted by+ // the same replacer below. A pinned target claims exactly one item, so the+ // swarm wrapper (claim N in parallel) is suppressed — the two are exclusive.+ const targetRef = normalizeWorkItemRef(target);+ const swarmBlock = targetRef ? '' : resolveSwarmBlock(promptTaskType, metadata.swarmCount);++ const prompt = applyAppPlaceholders(`${swarmBlock}${template}`, app)+ // Function-form replacers so literal `$`/`$1` in the substituted text isn't+ // interpreted as a backreference (see the scheduler's same-pattern note).+ .replace(/\{reviewers\}/g, () => reviewersCsv || 'none')+ .replace(/\{issueAuthorFilter\}/g, () => issueAuthorFilterBlock)+ .replace(/\{issueCandidateList\}/g, () => resolveIssueCandidateListBlock(promptTaskType, resolvedAuthorFilter))+ .replace(/\{issueExcludeLabels\}/g, () => issueExcludeLabelsBlock)+ + appendTargetWorkItemBlock(promptTaskType, targetRef, issueExcludeLabelsBlock)+ + appendPrefetchedIssueContext(promptTaskType, targetRef, issueContext)+ + appendClaimOverrideContext(overrideContext)+ + appendReviewerEffortBlock(reviewersList, promptReviewerEfforts, promptReviewerModels)+ + buildLocalReviewerInstructions(reviewersList, promptReviewerModels, promptReviewerEfforts, {+ claimCommentGate: promptTaskType === 'claim-issue',+ enforceIsolation: promptTaskType.startsWith('claim-issue'),+ });++ // Mirror the scheduler: inherit the delegated flow's isolation posture so the+ // JIRA route runs in a CoS-managed worktree rather than the live checkout.+ // The resolved reviewer bundle rides along so the prompt builder's+ // `resolveReviewerConfig(task.metadata, …)` reads back the list this prompt+ // names — the reviewer pin is emitted once from there (#4770).+ const delegatedMeta = taskSchedule.DEFAULT_TASK_INTERVALS[promptTaskType]?.taskMetadata || {};+ const taskMetadata = { ...reviewerConfigMetadata(claimReviewers), claimFlow: true };+ if (effectivePrCompletion) taskMetadata.prCompletion = effectivePrCompletion;+ // The manual `/do:next` path persists this non-raw task through addTask's+ // metadata allowlist before agentLifecycle sees it. Carry the same count that+ // rendered the swarm block so Codex can size its session to root + workers.+ // A pinned target suppresses swarmBlock above and therefore must not retain a+ // stale configured count.+ if (swarmBlock) taskMetadata.swarmCount = metadata.swarmCount;+ if ('useWorktree' in delegatedMeta) taskMetadata.useWorktree = delegatedMeta.useWorktree;+ if ('openPR' in delegatedMeta) taskMetadata.openPR = delegatedMeta.openPR;++ return { tracker: wt.resolved, source: wt.source, promptTaskType, prompt, taskMetadata, target: targetRef };+}++/**+ * Resolve the reviewer prompt pieces for the claim flow as buildClaimWorkTask+ * does on its default (no-explicit-option) path (including local-LLM+ * reviewers). Mirrors the scheduled claim-work resolution so the JIRA play+ * button honors the user's reviewer choice.+ *+ * Returns each piece separately because they travel differently: `csv` fills the+ * template's `{reviewers}` placeholder, `effortBlock` is appended prose (the+ * claim agent spawns each reviewer CLI itself, so no `--review-with` parser ever+ * reads the CSV's `~effort=` suffix), and `taskMetadata` is PERSISTED so the+ * prompt builder resolves the same list back off the task record (#4770).+ */+async function resolveClaimReviewerPrompt(app) {+ const [{ metadata }, codeReviewDefaults] = await Promise.all([+ resolveClaimWorkMetadata(app),+ getCodeReviewDefaults().catch(() => null)+ ]);+ // The app's configured claim-work metadata layers over the Code Review+ // Defaults through the same claimReviewersFrom the scheduled path uses —+ // resolving from the defaults alone would silently drop a pinned override.+ const effectivePrCompletion = metadata?.prCompletion ?? app?.defaultPrCompletion;+ const config = effectivePrCompletion !== undefined+ ? claimReviewersFrom(metadata, codeReviewDefaults, { prCompletion: effectivePrCompletion })+ : claimReviewersFrom(metadata, codeReviewDefaults);+ const { reviewers: list, reviewerModels, reviewerEfforts, csv } = config;+ return {+ csv,+ taskMetadata: reviewerConfigMetadata(config),+ effortBlock: appendReviewerEffortBlock(list, reviewerEfforts, reviewerModels),+ localReviewerBlock: buildLocalReviewerInstructions(list, reviewerModels, reviewerEfforts, { enforceIsolation: true }),+ };+}++/**+ * 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. `claimFlow` records that+ * lifecycle ownership while `useWorktree/openPR` stay `false/false` so CoS does+ * not provision a nested worktree.+ *+ * @returns {Promise<{ ticketKey: string, prompt: string, taskMetadata: { useWorktree: boolean, openPR: boolean, claimFlow: boolean } }>} —+ * `taskMetadata` also carries the resolved reviewer bundle so the prompt+ * builder's reviewer pin names this prompt's list (#4770).+ */+export async function buildJiraTicketTask(app, ticketKey) {+ const { getTaskPrompt } = await import('./taskPromptService.js');+ // Same normalizer the `/do:next` target uses — one definition of "a valid work+ // item ref". The route's Zod key regex has already rejected junk by here, so a+ // null (unnormalizable) key can only come from a direct service caller.+ const key = normalizeWorkItemRef(ticketKey);++ // Independent reads (prompt body + claim reviewers) — fetch concurrently.+ const [template, { csv: reviewersCsv, taskMetadata: reviewerMetadata, effortBlock, localReviewerBlock }] = await Promise.all([+ getTaskPrompt('claim-issue-jira'),+ resolveClaimReviewerPrompt(app),+ ]);+ const prompt = applyAppPlaceholders(template, app)+ // Function-form replacer so a literal `$` in the reviewers CSV isn't read as+ // a backreference.+ .replace(/\{reviewers\}/g, () => reviewersCsv || 'none')+ + appendTargetWorkItemBlock('claim-issue-jira', key)+ + effortBlock+ + localReviewerBlock;++ return { ticketKey: key, prompt, taskMetadata: { ...reviewerMetadata, useWorktree: false, openPR: false, claimFlow: true } };+}+++/**+ * Build a one-off "re-plan THIS issue" task — the Replan button beside Claim on+ * an app's Issues tab. A second model re-derives the plan from today's code and+ * leaves refinements, redirections, or adjustments on the tracker.+ *+ * Scoped to the forge the Issues tab actually listed (`resolveAppForgeTarget`,+ * the same resolver `listAppIssues` uses), so the comment lands on the repo the+ * user was reading rather than on whatever the checkout's origin happens to be.+ *+ * Not a claim and not `/do:replan`: nothing is implemented, nothing is assigned,+ * and the whole backlog is not audited. The deliverable is a tracker comment, so+ * the run is read-only and its clean worktree is the success shape — see+ * `buildIssueReplanPrompt` for the review contract itself.+ *+ * Throws a 400 ServerError when the app's tracker is not a forge issue tracker+ * (PLAN.md / JIRA have no issue to comment on) or when `target` is not a forge+ * issue number.+ *+ * @returns {Promise<{ tracker, prompt, taskMetadata, target }>}+ */+export async function buildIssueReplanTask(app, { target, issueContext, overrideContext } = {}) {+ const {+ resolveAppForgeTarget, forgeCliForTracker, workTrackerLabel: trackerLabel, trackerToClaimTaskType,+ } = await import('../lib/workTracker.js');++ const targetRef = normalizeWorkItemRef(target);+ if (!targetRef || !/^\d+$/.test(targetRef)) {+ throw new ServerError('Replan needs the number of the issue to review', { status: 400, code: 'REPLAN_TARGET_REQUIRED' });+ }++ const { tracker, target: forgeTarget } = await resolveAppForgeTarget(app);+ if (tracker !== 'github' && tracker !== 'gitlab') {+ throw new ServerError(+ `Replan needs a GitHub or GitLab issue tracker (${app.name} resolved to ${trackerLabel(tracker)})`,+ { status: 400, code: 'UNSUPPORTED_REPLAN_TRACKER' }+ );+ }+ const cli = forgeCliForTracker(tracker) || 'gh';++ const prompt = buildIssueReplanPrompt({+ appName: app.name,+ repoPath: app.repoPath,+ target: targetRef,+ cli,+ trackerName: trackerLabel(tracker),+ // gh takes a host-qualified spec; glab resolves the project from the+ // checkout, so it gets the plain path and no --repo flag it can't parse.+ repoFlag: (tracker === 'github' && forgeTarget?.repoSpec) ? forgeTarget.repoSpec : '',+ })+ // Reuses the claim flow's prefetched-issue block verbatim: the Issues tab has+ // already fetched this title/body, and the block's untrusted-data framing is+ // exactly what a prompt embedding someone else's issue text needs. Keyed on+ // the tracker's claim task type so its forge gate matches this run's forge.+ + appendPrefetchedIssueContext(trackerToClaimTaskType(tracker), targetRef, issueContext)+ + appendClaimOverrideContext(overrideContext);++ return {+ tracker,+ prompt,+ target: targetRef,+ // No worktree, no PR, and `noCodeOutput` because the deliverable is a forge+ // comment — that flag is what suppresses the commit/push/PR completion+ // contract, so the agent is never told to `/do:push` a run that changed+ // nothing. `worktreeChangesExpected: false` keeps its clean tree from being+ // scored as a missed deliverable (#3636).+ taskMetadata: { useWorktree: false, openPR: false, noCodeOutput: true, worktreeChangesExpected: false },+ };+}diff --git a/server/services/cosTaskGenerator.replan.test.js b/server/services/cosTaskClaimWork.replan.test.jssimilarity index 98%rename from server/services/cosTaskGenerator.replan.test.jsrename to server/services/cosTaskClaimWork.replan.test.jsindex bae7d9758b..06e4c5056d 100644--- a/server/services/cosTaskGenerator.replan.test.js+++ b/server/services/cosTaskClaimWork.replan.test.js@@ -19,7 +19,7 @@ vi.mock('../lib/workTracker.js', async (importActual) => ({resolveAppForgeTarget: (...args) => resolveAppForgeTarget(...args),}));-import { buildIssueReplanTask } from './cosTaskGenerator.js';+import { buildIssueReplanTask } from './cosTaskClaimWork.js';const APP = { id: 'my-app', name: 'MyApp', repoPath: '/repo' };diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 752f7f1737..0760b1cae6 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -28,9 +28,8 @@ import { isPrivateSecurityTask, PRIVATE_SECURITY_DELIVERY } from '../lib/privateimport { readFile } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';-import { sanitizeTaskMetadata, PIPELINE_STAGE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, resolveClaimReviewerConfig, reviewerConfigMetadata, hasReviewerOverride } from '../lib/validation.js';+import { sanitizeTaskMetadata, PIPELINE_STAGE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, resolveClaimReviewerConfig, reviewerConfigMetadata } from '../lib/validation.js';import { PATHS } from '../lib/fileUtils.js';-import { applyAppPlaceholders } from '../lib/appPromptPlaceholders.js';import { renderOrPrependSection } from '../lib/promptSectionRenderer.js';import { currentTaskTypeName } from '../lib/scheduledTaskTypes.js';import { isPlainObject } from '../lib/objects.js';@@ -60,7 +59,7 @@ import { isRecoveryTask } from './recoveryTasks.js';import { getCodeReviewDefaults } from './codeReview.js';import { getSkipReason } from './cosTaskClaim.js';import { ensureInstanceId } from './instanceIdentity.js';-import { PR_COMPLETIONS, PR_COMPLETION_VALUES } from '../lib/prDisposition.js';+import { PR_COMPLETION_VALUES } from '../lib/prDisposition.js';import { resolveTrackerFilingBlock } from '../lib/workTracker.js';import {isAuditTaskType,@@ -75,19 +74,11 @@ import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js// CoS provisioning posture that prevents a nested worktree. agentPromptBuilder.js// reads the same set back via isClaimFlowTask().import { CLAIM_FLOW_TASK_TYPES } from '../lib/claimFlowTaskTypes.js';-import { ServerError } from '../lib/errorHandler.js';import { isReconcileDrainTaskType } from './taskScheduleConstants.js';import { isProgrammaticScheduledTaskType, requiresInstallWideTarget } from './taskScheduleRegistry.js';import {- appendClaimOverrideContext,- appendPrefetchedIssueContext,appendReviewerEffortBlock,- appendTargetWorkItemBlock,- buildClaimOverrideContextBlock,buildLocalReviewerInstructions,- buildIssueReplanPrompt,- buildPrefetchedIssueContextBlock,- normalizeWorkItemRef,} from './cosTaskPrompts.js';import { appendTaskDataInputs, resolveTaskDataInputs } from './taskDataInputs.js';import { ensurePrReviewerPipeline, runPrReviewerSecurityPreflight, scopeDescriptionToPullRequest } from './prReviewerPipeline.js';@@ -97,14 +88,10 @@ import {buildImprovementTaskDescription,buildPlanConstraintBlock,resolveBranchReconcileBlock,- resolveIssueAuthorFilterBlock,- resolveIssueCandidateListBlock,- resolveIssueExcludeLabelsBlock,resolveIssueReconcileBlock,resolvePrWatcherBlock,resolveReferenceWatchBlock,resolveRepoSyncBlock,- resolveSwarmBlock,} from './cosTaskPreStepBlocks.js';import { detectIdleLeftoverBranches, formatUserActionDetectorBlock } from './userActionDetectors.js';@@ -376,296 +363,6 @@ const PLAN_SELF_CLAIM_TASK_TYPES = new Set(['plan-task']);// cleanly — burning an LLM round for nothing.const PLAN_GATE_TASK_TYPES = new Set(['plan-task']);-/**- * Resolve an app's configured claim metadata the same way the scheduled- * router does: global schedule metadata, then per-app overrides on top (managed- * agent fields stripped, both passes sanitized/value-constrained). This is what- * carries the user's `issueAuthorFilter`, reviewer, and swarm choices into the- * prompt. Shared by `buildClaimWorkTask` and the work-item picker route, so the- * items offered are scanned with the SAME author filter the claim agent will use.- *- * @returns {Promise<{ metadata: object, interval: object }>}- */-export async function resolveClaimWorkMetadata(app, taskType = 'claim-work') {- const taskSchedule = await import('./taskSchedule.js');- // Independent reads (schedule config + per-app overrides) — the merge below- // needs both, but neither depends on the other.- const [interval, appOverrides] = await Promise.all([- taskSchedule.getTaskInterval(taskType),- getAppTaskTypeOverrides(app.id)- ]);- const metadata = {};- const sanitizedGlobalMeta = sanitizeTaskMetadata(interval.taskMetadata);- if (sanitizedGlobalMeta) Object.assign(metadata, sanitizedGlobalMeta);- const strippedAppOverride = taskSchedule.stripManagedAgentOptionsFromOverride(- taskType, appOverrides[taskType]?.taskMetadata- );- const sanitizedAppMeta = sanitizeTaskMetadata(strippedAppOverride);- if (sanitizedAppMeta) Object.assign(metadata, sanitizedAppMeta);- return { metadata, interval };-}--/**- * The author filter a claim run will actually apply: explicit option >- * configured `claim-work` metadata > `'self'` (the slashdo `/do:next --self`- * security boundary — only claim issues you filed).- */-export function resolveClaimAuthorFilter(explicit, metadata) {- return explicit ?? metadata?.issueAuthorFilter ?? 'self';-}--/**- * The reviewer bundle a claim will run: an explicit option wins per field, then- * the app's configured `claim-work` metadata, then the Code Review Defaults. One- * resolver for the whole bundle (list + usernames + `~opt` set + the three keyed- * pins), so the CSV the prompt names and the `reviewers` the task PERSISTS cannot- * disagree. Local-LLM reviewers stay in the operative list; the claim prompt's- * appended Local Reviewer Procedure tells the agent how to invoke PortOS's review- * service rather than silently replacing the user's configured reviewer.- *- * Shared with `resolveAppClaimReviewers` (and through it the claim-reviewer- * lookup route) precisely so a change to this precedence reaches the preview the- * UI shows and the run it previews at the same time — the two drifting apart is- * the whole defect that lookup exists to close.- */-function claimReviewersFrom(metadata, codeReviewDefaults, explicit = {}) {- const { reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, prCompletion } = explicit;- return resolveClaimReviewerConfig({- ...metadata,- ...(prCompletion !== undefined ? { prCompletion } : {}),- reviewers: reviewers !== undefined ? (Array.isArray(reviewers) ? reviewers : [reviewers]) : metadata?.reviewers,- usernames: usernames ?? metadata?.usernames,- optionalReviewers: optionalReviewers ?? metadata?.optionalReviewers,- reviewerMaxRounds: reviewerMaxRounds ?? metadata?.reviewerMaxRounds,- reviewerModels: reviewerModels ?? metadata?.reviewerModels,- reviewerEfforts: reviewerEfforts ?? metadata?.reviewerEfforts- }, codeReviewDefaults, codeReviewDefaults?.reviewers);-}--/**- * What a `/do:next` claim would resolve for `app` right now, without queuing one:- * the reviewer bundle plus `overridden`, which says whether the claim-work task- * metadata supplied any of the list (so the UI can send the user to the override- * rather than to the Code Reviewers panel that isn't in play).- *- * Reads the same two layers `buildClaimWorkTask` does and hands them to the same- * `claimReviewersFrom`, so the preview cannot report a chain the run won't use.- */-export async function resolveAppClaimReviewers(app) {- // Independent reads — the resolver needs both, but neither depends on the other.- const [{ metadata }, codeReviewDefaults] = await Promise.all([- resolveClaimWorkMetadata(app),- // A settings read failure means "no configured defaults", never a failed- // lookup: the task metadata layer wins over them anyway.- getCodeReviewDefaults().catch(() => null)- ]);- const prCompletion = metadata?.prCompletion || app?.defaultPrCompletion || PR_COMPLETIONS.REVIEW_THEN_MERGE;- return {- ...claimReviewersFrom(metadata, codeReviewDefaults, { prCompletion }),- prCompletion,- overridden: hasReviewerOverride(metadata) || !!metadata?.prCompletion- };-}--/**- * Build a one-off "claim the next work item" task for `app`, routed by the app's- * configured workTracker — the manual (Slashdo `/do:next` button) counterpart to- * the scheduled `claim-work` router below. Resolves the tracker, delegates to the- * matching claim prompt body (plan-task / claim-issue / claim-issue-gitlab /- * claim-issue-jira), substitutes the standard placeholders, and surfaces the- * delegated flow's worktree/PR posture. `claimFlow` separately marks that the- * prompt owns its worktree + MR/PR lifecycle; false/false remains the correct- * CoS provisioning posture because a nested CoS worktree would conflict with- * the claim branch.- *- * `issueAuthorFilter` and the reviewer options default to the app's *configured*- * `claim-work` behavior (global schedule metadata → per-app override → Code- * Review Defaults), exactly as the scheduled `claim-work` router resolves them —- * so clicking the button honors `issueAuthorFilter: 'any'` and non-Copilot- * reviewers instead of silently forcing owner-only + Copilot. A direct- * `claim-work` prompt customization likewise overrides the tracker-specific body- * (matching the scheduled router's `promptKeyForBody` selection). Explicit- * options still win when a caller passes them.- *- * `target` pins the run to ONE work item (the drawer's "pick a specific item"- * mode) by appending the tracker-appropriate constraint block, overriding the- * prompt's own Phase 1 pick while keeping every claim safety check. A matching- * `issueContext` from the managed-app Issues tab is appended for forge targets- * so the agent can use the already-fetched title/body without retrieving it a- * second time.- *- * @returns {Promise<{ tracker, source, promptTaskType, prompt, taskMetadata, target }>}- */-export async function buildClaimWorkTask(app, {- issueAuthorFilter,- reviewers,- usernames,- optionalReviewers,- reviewerMaxRounds,- reviewerModels,- reviewerEfforts,- prCompletion,- target,- issueContext,- overrideContext-} = {}) {- const { resolveAppWorkTracker, trackerToClaimTaskType } = await import('../lib/workTracker.js');- const { getTaskPrompt } = await import('./taskPromptService.js');- const taskSchedule = await import('./taskSchedule.js');-- // The tracker probe (a `git` shell-out), the configured claim-work metadata,- // and the Code Review Defaults are mutually independent — only the prompt-body- // read below depends on them, so overlap the three.- const [wt, { metadata, interval }, codeReviewDefaults] = await Promise.all([- resolveAppWorkTracker(app),- resolveClaimWorkMetadata(app),- getCodeReviewDefaults().catch(() => null)- ]);- const promptTaskType = trackerToClaimTaskType(wt.resolved) || 'plan-task';-- // Honor a direct claim-work prompt customization if the user set one;- // otherwise delegate to the resolved tracker's prompt body. Mirrors the- // scheduled router's `promptKeyForBody` selection — a custom claim-work prompt- // overrides the tracker-specific body for both paths.- const template = await getTaskPrompt(- interval.prompt ? 'claim-work' : promptTaskType,- { claimFlow: true }- );-- const resolvedAuthorFilter = resolveClaimAuthorFilter(issueAuthorFilter, metadata);- const effectivePrCompletion = prCompletion ?? metadata?.prCompletion ?? app?.defaultPrCompletion;-- const claimReviewers = claimReviewersFrom(metadata, codeReviewDefaults, {- reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts,- ...(effectivePrCompletion !== undefined ? { prCompletion: effectivePrCompletion } : {})- });- const {- reviewers: reviewersList,- reviewerModels: promptReviewerModels,- reviewerEfforts: promptReviewerEfforts,- csv: reviewersCsv- } = claimReviewers;- const issueAuthorFilterBlock = resolveIssueAuthorFilterBlock(promptTaskType, resolvedAuthorFilter);- const issueExcludeLabelsBlock = resolveIssueExcludeLabelsBlock(metadata.issueExcludeLabels);- // Swarm mode (`/do:next --swarm`) is prepended (not an in-template- // placeholder) so it stays an opt-in orchestration wrapper that needs no- // prompt-default version bump; empty when swarmCount is off or the tracker- // isn't a forge issue tracker. {reviewers} inside the block is substituted by- // the same replacer below. A pinned target claims exactly one item, so the- // swarm wrapper (claim N in parallel) is suppressed — the two are exclusive.- const targetRef = normalizeWorkItemRef(target);- const swarmBlock = targetRef ? '' : resolveSwarmBlock(promptTaskType, metadata.swarmCount);-- const prompt = applyAppPlaceholders(`${swarmBlock}${template}`, app)- // Function-form replacers so literal `$`/`$1` in the substituted text isn't- // interpreted as a backreference (see the scheduler's same-pattern note).- .replace(/\{reviewers\}/g, () => reviewersCsv || 'none')- .replace(/\{issueAuthorFilter\}/g, () => issueAuthorFilterBlock)- .replace(/\{issueCandidateList\}/g, () => resolveIssueCandidateListBlock(promptTaskType, resolvedAuthorFilter))- .replace(/\{issueExcludeLabels\}/g, () => issueExcludeLabelsBlock)- + appendTargetWorkItemBlock(promptTaskType, targetRef, issueExcludeLabelsBlock)- + appendPrefetchedIssueContext(promptTaskType, targetRef, issueContext)- + appendClaimOverrideContext(overrideContext)- + appendReviewerEffortBlock(reviewersList, promptReviewerEfforts, promptReviewerModels)- + buildLocalReviewerInstructions(reviewersList, promptReviewerModels, promptReviewerEfforts, {- claimCommentGate: promptTaskType === 'claim-issue',- enforceIsolation: promptTaskType.startsWith('claim-issue'),- });-- // Mirror the scheduler: inherit the delegated flow's isolation posture so the- // JIRA route runs in a CoS-managed worktree rather than the live checkout.- // The resolved reviewer bundle rides along so the prompt builder's- // `resolveReviewerConfig(task.metadata, …)` reads back the list this prompt- // names — the reviewer pin is emitted once from there (#4770).- const delegatedMeta = taskSchedule.DEFAULT_TASK_INTERVALS[promptTaskType]?.taskMetadata || {};- const taskMetadata = { ...reviewerConfigMetadata(claimReviewers), claimFlow: true };- if (effectivePrCompletion) taskMetadata.prCompletion = effectivePrCompletion;- // The manual `/do:next` path persists this non-raw task through addTask's- // metadata allowlist before agentLifecycle sees it. Carry the same count that- // rendered the swarm block so Codex can size its session to root + workers.- // A pinned target suppresses swarmBlock above and therefore must not retain a- // stale configured count.- if (swarmBlock) taskMetadata.swarmCount = metadata.swarmCount;- if ('useWorktree' in delegatedMeta) taskMetadata.useWorktree = delegatedMeta.useWorktree;- if ('openPR' in delegatedMeta) taskMetadata.openPR = delegatedMeta.openPR;-- return { tracker: wt.resolved, source: wt.source, promptTaskType, prompt, taskMetadata, target: targetRef };-}--/**- * Resolve the reviewer prompt pieces for the claim flow as buildClaimWorkTask- * does on its default (no-explicit-option) path (including local-LLM- * reviewers). Mirrors the scheduled claim-work resolution so the JIRA play- * button honors the user's reviewer choice.- *- * Returns each piece separately because they travel differently: `csv` fills the- * template's `{reviewers}` placeholder, `effortBlock` is appended prose (the- * claim agent spawns each reviewer CLI itself, so no `--review-with` parser ever- * reads the CSV's `~effort=` suffix), and `taskMetadata` is PERSISTED so the- * prompt builder resolves the same list back off the task record (#4770).- */-async function resolveClaimReviewerPrompt(app) {- const [{ metadata }, codeReviewDefaults] = await Promise.all([- resolveClaimWorkMetadata(app),- getCodeReviewDefaults().catch(() => null)- ]);- // The app's configured claim-work metadata layers over the Code Review- // Defaults through the same claimReviewersFrom the scheduled path uses —- // resolving from the defaults alone would silently drop a pinned override.- const effectivePrCompletion = metadata?.prCompletion ?? app?.defaultPrCompletion;- const config = effectivePrCompletion !== undefined- ? claimReviewersFrom(metadata, codeReviewDefaults, { prCompletion: effectivePrCompletion })- : claimReviewersFrom(metadata, codeReviewDefaults);- const { reviewers: list, reviewerModels, reviewerEfforts, csv } = config;- return {- csv,- taskMetadata: reviewerConfigMetadata(config),- effortBlock: appendReviewerEffortBlock(list, reviewerEfforts, reviewerModels),- localReviewerBlock: buildLocalReviewerInstructions(list, reviewerModels, reviewerEfforts, { enforceIsolation: true }),- };-}--/**- * 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. `claimFlow` records that- * lifecycle ownership while `useWorktree/openPR` stay `false/false` so CoS does- * not provision a nested worktree.- *- * @returns {Promise<{ ticketKey: string, prompt: string, taskMetadata: { useWorktree: boolean, openPR: boolean, claimFlow: boolean } }>} —- * `taskMetadata` also carries the resolved reviewer bundle so the prompt- * builder's reviewer pin names this prompt's list (#4770).- */-export async function buildJiraTicketTask(app, ticketKey) {- const { getTaskPrompt } = await import('./taskPromptService.js');- // Same normalizer the `/do:next` target uses — one definition of "a valid work- // item ref". The route's Zod key regex has already rejected junk by here, so a- // null (unnormalizable) key can only come from a direct service caller.- const key = normalizeWorkItemRef(ticketKey);-- // Independent reads (prompt body + claim reviewers) — fetch concurrently.- const [template, { csv: reviewersCsv, taskMetadata: reviewerMetadata, effortBlock, localReviewerBlock }] = await Promise.all([- getTaskPrompt('claim-issue-jira'),- resolveClaimReviewerPrompt(app),- ]);- const prompt = applyAppPlaceholders(template, app)- // Function-form replacer so a literal `$` in the reviewers CSV isn't read as- // a backreference.- .replace(/\{reviewers\}/g, () => reviewersCsv || 'none')- + appendTargetWorkItemBlock('claim-issue-jira', key)- + effortBlock- + localReviewerBlock;-- return { ticketKey: key, prompt, taskMetadata: { ...reviewerMetadata, useWorktree: false, openPR: false, claimFlow: true } };-}-/*** 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@@ -3107,76 +2804,3 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stawait recordDeferredPerpetualDispatch(prepared.pendingPerpetualDispatch, taskSchedule);return prepared.task;}-// `normalizeClaimReviewers` moved to server/lib/reviewerConfig.js (#4770, #5702): the-// prompt builder needs the same copilot guard when it re-resolves reviewers off-// a persisted claim task, and a service-level definition would have meant a-// second copy there.--/**- * Build a one-off "re-plan THIS issue" task — the Replan button beside Claim on- * an app's Issues tab. A second model re-derives the plan from today's code and- * leaves refinements, redirections, or adjustments on the tracker.- *- * Scoped to the forge the Issues tab actually listed (`resolveAppForgeTarget`,- * the same resolver `listAppIssues` uses), so the comment lands on the repo the- * user was reading rather than on whatever the checkout's origin happens to be.- *- * Not a claim and not `/do:replan`: nothing is implemented, nothing is assigned,- * and the whole backlog is not audited. The deliverable is a tracker comment, so- * the run is read-only and its clean worktree is the success shape — see- * `buildIssueReplanPrompt` for the review contract itself.- *- * Throws a 400 ServerError when the app's tracker is not a forge issue tracker- * (PLAN.md / JIRA have no issue to comment on) or when `target` is not a forge- * issue number.- *- * @returns {Promise<{ tracker, prompt, taskMetadata, target }>}- */-export async function buildIssueReplanTask(app, { target, issueContext, overrideContext } = {}) {- const {- resolveAppForgeTarget, forgeCliForTracker, workTrackerLabel: trackerLabel, trackerToClaimTaskType,- } = await import('../lib/workTracker.js');-- const targetRef = normalizeWorkItemRef(target);- if (!targetRef || !/^\d+$/.test(targetRef)) {- throw new ServerError('Replan needs the number of the issue to review', { status: 400, code: 'REPLAN_TARGET_REQUIRED' });- }-- const { tracker, target: forgeTarget } = await resolveAppForgeTarget(app);- if (tracker !== 'github' && tracker !== 'gitlab') {- throw new ServerError(- `Replan needs a GitHub or GitLab issue tracker (${app.name} resolved to ${trackerLabel(tracker)})`,- { status: 400, code: 'UNSUPPORTED_REPLAN_TRACKER' }- );- }- const cli = forgeCliForTracker(tracker) || 'gh';-- const prompt = buildIssueReplanPrompt({- appName: app.name,- repoPath: app.repoPath,- target: targetRef,- cli,- trackerName: trackerLabel(tracker),- // gh takes a host-qualified spec; glab resolves the project from the- // checkout, so it gets the plain path and no --repo flag it can't parse.- repoFlag: (tracker === 'github' && forgeTarget?.repoSpec) ? forgeTarget.repoSpec : '',- })- // Reuses the claim flow's prefetched-issue block verbatim: the Issues tab has- // already fetched this title/body, and the block's untrusted-data framing is- // exactly what a prompt embedding someone else's issue text needs. Keyed on- // the tracker's claim task type so its forge gate matches this run's forge.- + appendPrefetchedIssueContext(trackerToClaimTaskType(tracker), targetRef, issueContext)- + appendClaimOverrideContext(overrideContext);-- return {- tracker,- prompt,- target: targetRef,- // No worktree, no PR, and `noCodeOutput` because the deliverable is a forge- // comment — that flag is what suppresses the commit/push/PR completion- // contract, so the agent is never told to `/do:push` a run that changed- // nothing. `worktreeChangesExpected: false` keeps its clean tree from being- // scored as a missed deliverable (#3636).- taskMetadata: { useWorktree: false, openPR: false, noCodeOutput: true, worktreeChangesExpected: false },- };-}diff --git a/server/services/cosTaskGenerator.providerPin.test.js b/server/services/cosTaskGenerator.providerPin.test.jsindex 7955e9d08c..c06dbc6999 100644--- a/server/services/cosTaskGenerator.providerPin.test.js+++ b/server/services/cosTaskGenerator.providerPin.test.js@@ -67,7 +67,8 @@ vi.mock('./perpetualWork.js', async importOriginal => ({import { detectActionableWork } from './perpetualWork.js';import { recordPerpetualStall } from './taskSchedule.js';-import { generateManagedAppImprovementTaskForType, prepareManagedAppImprovementTask, resolveClaimWorkMetadata } from './cosTaskGenerator.js';+import { generateManagedAppImprovementTaskForType, prepareManagedAppImprovementTask } from './cosTaskGenerator.js';+import { resolveClaimWorkMetadata } from './cosTaskClaimWork.js';const APP = { id: 'app-1', name: 'Example App', repoPath: '/tmp/example-repo' };const STATE = { config: { confidenceAutoApproval: { enabled: false }, idleReviewPriority: 'MEDIUM' } };diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex df945f507b..12ff08e5eb 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -79,9 +79,6 @@ import {applyOnDemandConsent,isConfiguredApprovalRequired,PERPETUAL_TRANSIENT_ESCALATION_THRESHOLD,- buildJiraTicketTask,- buildClaimWorkTask,- resolveAppClaimReviewers,buildImprovementDedupSets,queueDueInstallWideImprovementTasks,generateManagedAppImprovementTaskForType,@@ -96,6 +93,7 @@ import {applyUserActionDeliveryMode,applyUserActionDetectorSection} from './cosTaskGenerator.js';+import { buildJiraTicketTask, buildClaimWorkTask, resolveAppClaimReviewers } from './cosTaskClaimWork.js';import * as cosTaskGenerator from './cosTaskGenerator.js';import * as cosTaskPreStepBlocks from './cosTaskPreStepBlocks.js';import * as prReviewerPipeline from './prReviewerPipeline.js';@@ -106,11 +104,16 @@ import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';const __dirname = dirname(fileURLToPath(import.meta.url));const GEN_SRC = readFileSync(join(__dirname, 'cosTaskGenerator.js'), 'utf-8');const PRESTEP_SRC = readFileSync(join(__dirname, 'cosTaskPreStepBlocks.js'), 'utf-8');-// The CoS task-generation layer spans the selection engine (cosTaskGenerator.js)-// and the prompt pre-step module it composes (cosTaskPreStepBlocks.js). A guard-// about WHERE a call sits reads one file; a guard about the call's SHAPE reads-// both, so moving code between them can neither break it nor silently disarm it.-const LAYER_SRC = `${GEN_SRC}\n${PRESTEP_SRC}`;+// The manual claim / JIRA / replan prompt builders (cosTaskClaimWork.js) share+// their reviewer + claim-metadata resolution with the scheduled claim-work router+// that stays in cosTaskGenerator.js.+const CLAIM_SRC = readFileSync(join(__dirname, 'cosTaskClaimWork.js'), 'utf-8');+// The CoS task-generation layer spans the selection engine (cosTaskGenerator.js),+// the manual claim builders (cosTaskClaimWork.js), and the prompt pre-step module+// they compose (cosTaskPreStepBlocks.js). A guard about WHERE a call sits reads+// one file; a guard about the call's SHAPE reads the layer, so moving code between+// them can neither break it nor silently disarm it.+const LAYER_SRC = `${GEN_SRC}\n${CLAIM_SRC}\n${PRESTEP_SRC}`;const COS_SRC = readFileSync(join(__dirname, 'cos.js'), 'utf-8');// The ONE Priority-0 on-demand loop body both engines delegate to (#6618).const DRAIN_SRC = readFileSync(join(__dirname, 'onDemandDrain.js'), 'utf-8');@@ -452,8 +455,8 @@ describe('{reviewers} interpolation honors Code Review Defaults', () => {// Every claim path layers the app's claim-work metadata over the defaults// through claimReviewersFrom — no path may resolve the defaults alone with// a bare `{}` (that silently drops a pinned override; #6210).- expect(GEN_SRC).not.toContain('resolveClaimReviewerConfig({}, codeReviewDefaults, codeReviewDefaults?.reviewers)');- expect(GEN_SRC).not.toMatch(/normalizeReviewers\(metadata\)(?!,)/);+ expect(LAYER_SRC).not.toContain('resolveClaimReviewerConfig({}, codeReviewDefaults, codeReviewDefaults?.reviewers)');+ expect(LAYER_SRC).not.toMatch(/normalizeReviewers\(metadata\)(?!,)/);});it('keeps local-LLM reviewers and appends their fail-closed invocation procedure', () => {@@ -471,8 +474,8 @@ describe('{reviewers} interpolation honors Code Review Defaults', () => {// The models ride along because cursor's effort is a variant of its model id// rather than a flag — without them a cursor pin would have no invocation to// name (see `reviewerModelArg`).- expect(GEN_SRC).toContain('appendReviewerEffortBlock(reviewersList, promptReviewerEfforts, promptReviewerModels)');- expect(GEN_SRC).toContain('appendReviewerEffortBlock(list, reviewerEfforts, reviewerModels)');+ expect(CLAIM_SRC).toContain('appendReviewerEffortBlock(reviewersList, promptReviewerEfforts, promptReviewerModels)');+ expect(CLAIM_SRC).toContain('appendReviewerEffortBlock(list, reviewerEfforts, reviewerModels)');expect(PRESTEP_SRC).toContain('appendReviewerEffortBlock(promptReviewers, promptReviewerEfforts, promptReviewerModels)');expect(LAYER_SRC).not.toMatch(/buildReviewerEffortNote\([^)]*reviewWith/);});@@ -495,9 +498,9 @@ describe('{reviewers} interpolation honors Code Review Defaults', () => {// run if the CSV carries it. Both the scheduled path and buildClaimWorkTask// feed the cap into the shared claim resolver, which applies task-over-default// precedence (unit-tested in reviewerConfig.test.js).- expect(GEN_SRC).toContain('reviewerMaxRounds: reviewerMaxRounds ?? metadata?.reviewerMaxRounds');+ expect(CLAIM_SRC).toContain('reviewerMaxRounds: reviewerMaxRounds ?? metadata?.reviewerMaxRounds');expect(GEN_SRC).toContain('resolveClaimReviewerConfig(metadata, codeReviewDefaults, codeReviewDefaults?.reviewers)');- expect(GEN_SRC).not.toContain('resolveReviewerMaxRounds(');+ expect(LAYER_SRC).not.toContain('resolveReviewerMaxRounds(');});it('threads per-reviewer model pins into the prompt CSV on both claim paths (#3133)', () => {@@ -511,18 +514,18 @@ describe('{reviewers} interpolation honors Code Review Defaults', () => {// agy model id can carry its effort as a suffix, so a path that resolved the// models alone would emit `--model <suffixed> --effort <tier>`, a pair agy// rejects, while the other paths emitted the split form.- expect(GEN_SRC).toContain('reviewerModels: reviewerModels ?? metadata?.reviewerModels');- expect(GEN_SRC).toContain('reviewerEfforts: reviewerEfforts ?? metadata?.reviewerEfforts');+ expect(CLAIM_SRC).toContain('reviewerModels: reviewerModels ?? metadata?.reviewerModels');+ expect(CLAIM_SRC).toContain('reviewerEfforts: reviewerEfforts ?? metadata?.reviewerEfforts');// All three claim paths layer claim-work metadata over the defaults via// claimReviewersFrom — including the JIRA play button (#6210). No path may// resolve the defaults alone with a bare `{}`.- expect(GEN_SRC).toContain('claimReviewersFrom(metadata, codeReviewDefaults)');- expect(GEN_SRC).not.toContain('resolveClaimReviewerConfig({}, codeReviewDefaults, codeReviewDefaults?.reviewers)');+ expect(CLAIM_SRC).toContain('claimReviewersFrom(metadata, codeReviewDefaults)');+ expect(LAYER_SRC).not.toContain('resolveClaimReviewerConfig({}, codeReviewDefaults, codeReviewDefaults?.reviewers)');// No path may resolve one map without the other — or reach past the shared// claim resolver, which wraps `resolveReviewerPins` for all three sites.- expect(GEN_SRC).not.toContain('resolveReviewerModels(');- expect(GEN_SRC).not.toContain('resolveReviewerEfforts(');- expect(GEN_SRC).not.toContain('resolveReviewerPins(');+ expect(LAYER_SRC).not.toContain('resolveReviewerModels(');+ expect(LAYER_SRC).not.toContain('resolveReviewerEfforts(');+ expect(LAYER_SRC).not.toContain('resolveReviewerPins(');});});@@ -566,18 +569,18 @@ describe('claim-work single-source routing', () => {// selecting the generic commit-only handoff. The hook stays so a future// delegated type that DOES need CoS-managed isolation would have its// DEFAULT_TASK_INTERVALS metadata applied here.- expect(GEN_SRC).toContain('taskSchedule.DEFAULT_TASK_INTERVALS[promptTaskType]?.taskMetadata');- expect(GEN_SRC).toContain("'useWorktree' in delegatedMeta");- expect(GEN_SRC).toContain("'openPR' in delegatedMeta");- expect(GEN_SRC).toContain('const taskMetadata = { ...reviewerConfigMetadata(claimReviewers), claimFlow: true }');+ expect(CLAIM_SRC).toContain('taskSchedule.DEFAULT_TASK_INTERVALS[promptTaskType]?.taskMetadata');+ expect(CLAIM_SRC).toContain("'useWorktree' in delegatedMeta");+ expect(CLAIM_SRC).toContain("'openPR' in delegatedMeta");+ expect(CLAIM_SRC).toContain('const taskMetadata = { ...reviewerConfigMetadata(claimReviewers), claimFlow: true }');expect(GEN_SRC).toContain('metadata.claimFlow = true');});it('exposes buildClaimWorkTask so the manual /do:next button reuses the same router', () => {- expect(GEN_SRC).toContain('export async function buildClaimWorkTask(');+ expect(CLAIM_SRC).toContain('export async function buildClaimWorkTask(');// Same tracker resolution + delegated isolation posture as the scheduler.- expect(GEN_SRC).toMatch(/buildClaimWorkTask[\s\S]*resolveAppWorkTracker, trackerToClaimTaskType/);- expect(GEN_SRC).toMatch(/buildClaimWorkTask[\s\S]*resolveIssueAuthorFilterBlock\(promptTaskType/);+ expect(CLAIM_SRC).toMatch(/buildClaimWorkTask[\s\S]*resolveAppWorkTracker, trackerToClaimTaskType/);+ expect(CLAIM_SRC).toMatch(/buildClaimWorkTask[\s\S]*resolveIssueAuthorFilterBlock\(promptTaskType/);});it('buildClaimWorkTask resolves issueAuthorFilter + reviewers from configured claim-work metadata (parity with scheduler)', () => {@@ -585,15 +588,15 @@ describe('claim-work single-source routing', () => {// (issueAuthorFilter:'any', non-Copilot reviewers), not force owner+copilot.// The metadata merge itself lives in resolveClaimWorkMetadata, shared with the// work-item picker route so both scan under the SAME author filter.- const resolver = GEN_SRC.slice(GEN_SRC.indexOf('export async function resolveClaimWorkMetadata('));+ const resolver = CLAIM_SRC.slice(CLAIM_SRC.indexOf('export async function resolveClaimWorkMetadata('));expect(resolver).toContain("taskType = 'claim-work'");expect(resolver).toMatch(/getTaskInterval\(taskType\)/);expect(resolver).toMatch(/getAppTaskTypeOverrides\(app\.id\)/);expect(resolver).toMatch(/stripManagedAgentOptionsFromOverride\(\s*taskType/);// issueAuthorFilter: explicit option > configured metadata > 'self'// (the slashdo /do:next --self security boundary).- expect(GEN_SRC).toMatch(/return explicit \?\? metadata\?\.issueAuthorFilter \?\? 'self'/);- const fn = GEN_SRC.slice(GEN_SRC.indexOf('export async function buildClaimWorkTask('));+ expect(CLAIM_SRC).toMatch(/return explicit \?\? metadata\?\.issueAuthorFilter \?\? 'self'/);+ const fn = CLAIM_SRC.slice(CLAIM_SRC.indexOf('export async function buildClaimWorkTask('));expect(fn).toMatch(/resolveClaimWorkMetadata\(app\)/);expect(fn).toMatch(/resolveClaimAuthorFilter\(issueAuthorFilter, metadata\)/);// Reviewers layer an explicit per-field option over the configured claim-work@@ -603,7 +606,7 @@ describe('claim-work single-source routing', () => {// claim-reviewer lookup route, so the preview the UI shows and the run it// previews can't resolve differently.expect(fn).toMatch(/claimReviewersFrom\(metadata, codeReviewDefaults, \{/);- const layering = GEN_SRC.slice(GEN_SRC.indexOf('function claimReviewersFrom('));+ const layering = CLAIM_SRC.slice(CLAIM_SRC.indexOf('function claimReviewersFrom('));expect(layering).toMatch(/resolveClaimReviewerConfig\(\{\s*\.\.\.metadata,/);expect(layering).toMatch(/reviewers: reviewers !== undefined/);expect(fn).toMatch(/buildLocalReviewerInstructions\(reviewersList/);@@ -741,7 +744,7 @@ describe('work-item target', () => {});it('wires the prefetch block into the manual claim prompt assembly', () => {- const claimBuilder = GEN_SRC.slice(GEN_SRC.indexOf('export async function buildClaimWorkTask('));+ const claimBuilder = CLAIM_SRC.slice(CLAIM_SRC.indexOf('export async function buildClaimWorkTask('));expect(claimBuilder).toContain('appendPrefetchedIssueContext(promptTaskType, targetRef, issueContext)');expect(claimBuilder).toContain('appendClaimOverrideContext(overrideContext)');});@@ -800,14 +803,14 @@ describe('buildJiraTicketTask', () => {});it('is exported so the /tasks/jira-ticket route reuses the shared assembly', () => {- expect(GEN_SRC).toContain('export async function buildJiraTicketTask(');+ expect(CLAIM_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]*appendTargetWorkItemBlock\('claim-issue-jira', key\)/);+ expect(CLAIM_SRC).toMatch(/buildJiraTicketTask[\s\S]*getTaskPrompt\('claim-issue-jira'\)/);+ expect(CLAIM_SRC).toMatch(/buildJiraTicketTask[\s\S]*appendTargetWorkItemBlock\('claim-issue-jira', key\)/);// The play button layers the app's claim-work metadata, not the defaults// alone (#6210) — the app travels into the reviewer resolution.- expect(GEN_SRC).toMatch(/buildJiraTicketTask[\s\S]*resolveClaimReviewerPrompt\(app\)/);- expect(GEN_SRC).toMatch(/async function resolveClaimReviewerPrompt\(app\)/);+ expect(CLAIM_SRC).toMatch(/buildJiraTicketTask[\s\S]*resolveClaimReviewerPrompt\(app\)/);+ expect(CLAIM_SRC).toMatch(/async function resolveClaimReviewerPrompt\(app\)/);});});diff --git a/server/services/cosTaskPreStepBlocks.test.js b/server/services/cosTaskPreStepBlocks.test.jsindex d5fcfdf56f..728be27d07 100644--- a/server/services/cosTaskPreStepBlocks.test.js+++ b/server/services/cosTaskPreStepBlocks.test.js@@ -26,12 +26,13 @@ import { DISPATCH_HINT_FANOUT_GUIDANCE } from '../lib/dispatchLabels.js';const __dirname = dirname(fileURLToPath(import.meta.url));const GEN_SRC = readFileSync(join(__dirname, 'cosTaskGenerator.js'), 'utf-8');+const CLAIM_SRC = readFileSync(join(__dirname, 'cosTaskClaimWork.js'), 'utf-8');const PRESTEP_SRC = readFileSync(join(__dirname, 'cosTaskPreStepBlocks.js'), 'utf-8');-// The CoS task-generation layer spans the selection engine and the pre-step-// module it composes. A guard about WHERE a call sits reads one file; a guard-// about the call's shape reads both, so moving code between them can neither-// break it nor silently disarm it.-const LAYER_SRC = `${GEN_SRC}\n${PRESTEP_SRC}`;+// The CoS task-generation layer spans the selection engine, the manual claim+// builders, and the pre-step module they compose. A guard about WHERE a call sits+// reads one file; a guard about the call's shape reads the layer, so moving code+// between them can neither break it nor silently disarm it.+const LAYER_SRC = `${GEN_SRC}\n${CLAIM_SRC}\n${PRESTEP_SRC}`;// #6112 — an abandoned volunteer claim is released deterministically, and the// release must happen BEFORE the "no zombies → park" early return. A repo whose@@ -133,7 +134,7 @@ describe('resolveIssueExcludeLabelsBlock', () => {});it('buildClaimWorkTask threads the resolved block into the pinned-target constraint, not just the {issueExcludeLabels} placeholder', () => {- expect(GEN_SRC).toContain('appendTargetWorkItemBlock(promptTaskType, targetRef, issueExcludeLabelsBlock)');+ expect(CLAIM_SRC).toContain('appendTargetWorkItemBlock(promptTaskType, targetRef, issueExcludeLabelsBlock)');});});@@ -262,7 +263,7 @@ describe('swarm block wiring', () => {it('prepends resolveSwarmBlock(...) to the rendered prompt at both render sites', () => {const occurrences = LAYER_SRC.match(/resolveSwarmBlock\(promptTaskType, metadata\.swarmCount\)/g) || [];expect(occurrences.length).toBe(2);- expect(GEN_SRC).toContain('`${swarmBlock}${template}`');+ expect(CLAIM_SRC).toContain('`${swarmBlock}${template}`');expect(PRESTEP_SRC).toContain('`${swarmBlock}${promptTemplate}`');});});diff --git a/server/services/developmentWatchdog.js b/server/services/developmentWatchdog.jsindex dc30bfc964..604cc3bb7a 100644--- a/server/services/developmentWatchdog.js+++ b/server/services/developmentWatchdog.js@@ -86,7 +86,7 @@ async function inspectApp(app, tasks, localReviewTasks = [], activeAgentTaskIdsconst { resolveAppForgeTarget } = await import('../lib/workTracker.js');const { listAppPullRequests } = await import('./appPullRequests.js');const { detectActionableWork, listConfiguredForgeIssues, issueNumberFromRef } = await import('./perpetualWork.js');- const { resolveClaimWorkMetadata } = await import('./cosTaskGenerator.js');+ const { resolveClaimWorkMetadata } = await import('./cosTaskClaimWork.js');const { execGh } = await import('./github.js');const { resolveForgeExecOptions } = await import('./forgeExecOptions.js');const { createGithubActorTrust } = await import('./forgeActorTrust.js');diff --git a/server/services/developmentWatchdog.test.js b/server/services/developmentWatchdog.test.jsindex bedc7408fb..380a2cdc3b 100644--- a/server/services/developmentWatchdog.test.js+++ b/server/services/developmentWatchdog.test.js@@ -14,8 +14,10 @@ vi.mock('./instances.js', () => ({ getPeers: async () => m.peers }));vi.mock('../lib/workTracker.js', () => ({ resolveAppForgeTarget: async () => ({ tracker: 'github', target: { fullName: 'atomantic/example', repoSpec: 'github.com/atomantic/example', apiHost: 'github.com' } }) }));vi.mock('./appPullRequests.js', () => ({ listAppPullRequests: async () => ({ pullRequests: ++m.prReads > 1 && m.nextPrs ? m.nextPrs : m.prs, transient: false }) }));vi.mock('./perpetualWork.js', async importOriginal => ({ ...(await importOriginal()), detectActionableWork: async () => ({ count: m.backlog.length, items: m.backlog }), listConfiguredForgeIssues: async () => ({ ok: true, truncated: m.issueTruncated, issues: m.backlog.map(i => ({ number: Number(i.ref), labels: [], assignees: [] })) }) }));-vi.mock('./cosTaskGenerator.js', () => ({+vi.mock('./cosTaskClaimWork.js', () => ({resolveClaimWorkMetadata: (...args) => m.metadata(...args),+}));+vi.mock('./cosTaskGenerator.js', () => ({resolveAutonomyBudget: async () => ({ cosAutonomyMode: 'execute', autonomousActionsRemaining: 10 }),prepareManagedAppImprovementTask: (...args) => m.prepare(...args),recordDeferredPerpetualDispatch: (...args) => m.record(...args),