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

feat(cos): add perpetual (drain-until-done) scheduled-task mode

[._.]/ Adam Eivyca4285f94005
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7ec9979219..82b2dec857 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,6 +6,8 @@
## Chief of Staff
+- **New `perpetual` (drain-until-done) schedule mode: a task runs back-to-back until there's nothing left to do, then parks and rechecks on a cadence.** Most scheduled tasks fire on a timer (daily, weekly, cron). The new **Perpetual** interval type instead keeps re-queuing a task the moment the previous run finishes — for as long as a *programmatic* pre-run check (no LLM) reports there's still actionable work — and when the work runs out it PARKS itself and only re-probes on a configurable recheck cadence (a cron expression or interval, default daily). The motivating use is `claim-issue`/`claim-work`: set it to Perpetual and PortOS will claim and ship open GitHub issues one after another until the backlog of *claimable* issues is empty, then stop and recheck tomorrow — no wasted agent runs spinning on an empty queue. The pre-run check mirrors the claim prompt's own skip-list exactly (it excludes assigned issues, epics, in-flight `claim/issue-<num>` branches, and issues labeled `in-progress`/`blocked`/`needs-input`/`future`/`wontfix`/`question`/`discussion`), so the drain converges to the same empty state the agent would reach. To make it converge instead of re-picking an un-actionable issue forever, the `claim-issue` **and** `claim-issue-gitlab` agent prompts now **tag an ambiguous or too-large issue `needs-input`** (and comment what decision a human must make) before releasing it — that label is what the pre-run check uses to permanently exclude it. The detector is a pluggable registry (`server/services/perpetualWork.js`) shipping **GitHub-issue, GitLab-issue, and PLAN.md** detectors (the GitLab one mirrors the GitHub flow over `glab` — normalizing `iid`→number, reading MR source branches for the in-flight scan, and resolving the owner filter from the project namespace); a perpetual task whose tracker has no detector (e.g. JIRA) parks rather than draining blindly. Perpetual runs also skip the per-app review cooldown so the drain isn't throttled to one item per 30 minutes — the park is the throttle. Works for GitHub, GitLab, and PLAN.md-tracked apps (and the `claim-work` router, which resolves to the right detector per app). Configure it in **CoS → Schedule → Configure → Interval Type → Perpetual**. (`server/services/taskSchedule.js`, `server/services/perpetualWork.js`, `server/services/cosTaskGenerator.js`, `server/services/agentCompletion.js`, `server/routes/cosScheduleRoutes.js`, `server/services/taskPromptDefaults/`, `client/src/components/cos/tabs/schedule/`)
+
- **Feature Agents moved from Dev Tools to the Chief of Staff section.** The Feature Agents page (`/feature-agents`) now lives under the Chief of Staff sidebar group alongside the other agent-management pages, rather than buried in Dev Tools. The route is unchanged — only the sidebar grouping and the ⌘K / voice nav section label moved. (`client/src/components/Layout.jsx`, `server/lib/navManifest.js`)
- **The CoS → Schedule page is now a scannable card grid instead of a flat expandable list.** Each task type renders as a status card you can read at a glance — a colored status dot (active / on-demand / waiting-on-deps / disabled), a **next-run countdown** ("in 3h", "Mon 9:00") that was previously computed server-side but never shown, an app-coverage bar with the enabled/total count kept front-and-center, and last-run/run-count. Cards sort by status then soonest next run (so what's about to run rises to the top), the All/Enabled toggle is replaced by per-status filters (Active / On-Demand / Waiting / Disabled), and a name filter box jumps to a task quickly. A **Run** button sits on each card — for app-targeting tasks it opens an app picker so the on-demand run carries app context (just like the old per-task controls), and falls back to a plain global run for tasks with no managed apps; **Configure** opens a slide-over drawer with the full per-task settings (interval, provider/model, prompt, agent options, dependencies, pipeline stages, and per-app overrides) — the same controls as before, now in a focused panel that's deep-linkable via `?task=` and closes on Esc/backdrop. Mobile collapses the grid to a single column.
diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
index 42bcdf8a41..fab201acf5 100644
--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
@@ -31,6 +31,7 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
const activeApps = apps?.filter(app => !app.archived) || [];
const [cronEditing, setCronEditing] = useState(false);
+ const [recheckEditing, setRecheckEditing] = useState(false);
const handleTypeChange = async (newType) => {
if (newType === 'cron') {
@@ -38,6 +39,17 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
setSelectedType('cron');
return;
}
+ if (newType === 'perpetual') {
+ // Don't null recheckCron — switching to perpetual keeps any prior cadence.
+ setCronEditing(false);
+ setUpdating(true);
+ setSelectedType('perpetual');
+ await onUpdate(taskType, { type: 'perpetual' }).catch(() => {
+ setSelectedType(config.type);
+ });
+ setUpdating(false);
+ return;
+ }
setCronEditing(false);
setUpdating(true);
setSelectedType(newType);
@@ -56,6 +68,17 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
setUpdating(false);
};
+ const handleRecheckCronSave = async (expr) => {
+ setUpdating(true);
+ // Switching to perpetual together with its recheck cadence in one PUT so a
+ // freshly-picked perpetual type lands with the cadence already set.
+ await onUpdate(taskType, { type: 'perpetual', recheckCron: expr }).catch(() => {
+ setSelectedType(config.type);
+ });
+ setRecheckEditing(false);
+ setUpdating(false);
+ };
+
const isPaused = !config.enabled;
const handleToggleEnabled = async () => {
@@ -157,6 +180,7 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
<option value="once">Once (run once then stop)</option>
<option value="on-demand">On Demand (manual trigger only)</option>
<option value="cron">Cron (custom schedule)</option>
+ <option value="perpetual">Perpetual (drain until done, then recheck)</option>
</select>
{(selectedType === 'cron' && (cronEditing || config.type === 'cron')) ? (
<CronInput
@@ -170,6 +194,41 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
)}
</div>
+ {selectedType === 'perpetual' && (
+ <div>
+ <label className="text-sm text-gray-400 block mb-2">Recheck Cadence</label>
+ {(recheckEditing || config.recheckCron) ? (
+ <CronInput
+ value={config.recheckCron || '0 9 * * *'}
+ onSave={handleRecheckCronSave}
+ onCancel={() => setRecheckEditing(false)}
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={() => setRecheckEditing(true)}
+ disabled={updating}
+ className="w-full bg-port-card border border-port-border rounded px-3 py-2 text-left text-sm text-gray-300 hover:border-gray-500"
+ >
+ Daily (default) — click to set a custom recheck schedule
+ </button>
+ )}
+ <p className="text-xs text-gray-500 mt-1">
+ Runs back-to-back while actionable work remains, then parks and re-probes on this schedule.
+ The check is programmatic (no LLM) — e.g. claim-issue counts open, claimable issues; an issue
+ the agent tags <code>needs-input</code> is excluded so the drain converges.
+ </p>
+ {status.reason === 'perpetual-parked' && (
+ <p className="text-xs text-port-warning mt-1">
+ Parked{status.parkReason ? ` (${status.parkReason})` : ''}{status.nextRunAt ? ` — rechecks ${new Date(status.nextRunAt).toLocaleString()}` : ''}
+ </p>
+ )}
+ {(status.reason === 'perpetual-drain' || status.reason === 'perpetual-recheck') && (
+ <p className="text-xs text-port-success mt-1">Draining — actionable work available</p>
+ )}
+ </div>
+ )}
+
{!config.taskMetadata?.pipeline?.stages?.length && (
<>
<div>
diff --git a/client/src/components/cos/tabs/schedule/scheduleConstants.js b/client/src/components/cos/tabs/schedule/scheduleConstants.js
index 80e03cd48a..76509de407 100644
--- a/client/src/components/cos/tabs/schedule/scheduleConstants.js
+++ b/client/src/components/cos/tabs/schedule/scheduleConstants.js
@@ -8,7 +8,8 @@ export const INTERVAL_LABELS = {
once: 'Once',
'on-demand': 'On Demand',
custom: 'Custom',
- cron: 'Cron'
+ cron: 'Cron',
+ perpetual: 'Perpetual'
};
export const INTERVAL_DESCRIPTIONS = {
@@ -18,7 +19,8 @@ export const INTERVAL_DESCRIPTIONS = {
once: 'Runs once then stops',
'on-demand': 'Only runs when manually triggered',
custom: 'Custom interval',
- cron: 'Cron expression schedule'
+ cron: 'Cron expression schedule',
+ perpetual: 'Drains actionable work back-to-back until none remains, then rechecks on a cadence'
};
const BADGE_COLORS = {
@@ -44,6 +46,7 @@ export const INTERVAL_BADGE_VARIANT = {
once: 'warning',
'on-demand': 'gray',
cron: 'cyan',
+ perpetual: 'success',
};
// --- Status grouping -------------------------------------------------------
@@ -101,6 +104,18 @@ export function describeNextRun(config) {
};
}
if (group === 'on-demand') return { text: 'Manual trigger only', tone: 'text-gray-400' };
+ if (config.type === 'perpetual') {
+ const reason = config.status?.reason;
+ if (reason === 'perpetual-parked') {
+ const next = config.status?.nextRunAt;
+ return {
+ text: next ? `parked · rechecks ${timeUntil(next, 'soon')}` : 'parked — no work',
+ tone: 'text-gray-400',
+ title: config.status?.parkReason ? `Parked: ${config.status.parkReason}` : undefined,
+ };
+ }
+ return { text: 'draining — runs back-to-back until done', tone: 'text-port-success' };
+ }
const next = config.status?.nextRunAt;
return {
text: next ? timeUntil(next, 'soon') : `${INTERVAL_LABELS[config.type] || config.type} — pending`,
diff --git a/client/src/components/cos/tabs/schedule/scheduleConstants.test.js b/client/src/components/cos/tabs/schedule/scheduleConstants.test.js
index b04dba233c..b2fb7c9116 100644
--- a/client/src/components/cos/tabs/schedule/scheduleConstants.test.js
+++ b/client/src/components/cos/tabs/schedule/scheduleConstants.test.js
@@ -99,6 +99,22 @@ describe('describeNextRun', () => {
it('falls back to an interval-label pending string when no next run is known', () => {
expect(describeNextRun({ enabled: true, type: 'daily' }).text).toBe('Daily — pending');
});
+
+ it('reports a draining perpetual task', () => {
+ const out = describeNextRun({ enabled: true, type: 'perpetual', status: { reason: 'perpetual-drain' } });
+ expect(out.text).toMatch(/draining/i);
+ expect(out.tone).toBe('text-port-success');
+ });
+
+ it('reports a parked perpetual task with its recheck countdown and reason', () => {
+ const out = describeNextRun({
+ enabled: true,
+ type: 'perpetual',
+ status: { reason: 'perpetual-parked', nextRunAt: '2999-01-01T00:00:00Z', parkReason: 'no-actionable-issues' }
+ });
+ expect(out.text).toMatch(/parked · rechecks/);
+ expect(out.title).toContain('no-actionable-issues');
+ });
});
describe('coverageTone', () => {
diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.js
index a52a633027..a2728eba92 100644
--- a/server/routes/cosScheduleRoutes.js
+++ b/server/routes/cosScheduleRoutes.js
@@ -19,7 +19,11 @@ const templateTaskSchema = z.object({
const router = Router();
-const SCHEDULE_FIELDS = ['type', 'enabled', 'intervalMs', 'cronExpression', 'providerId', 'model', 'prompt', 'taskMetadata', 'runAfter'];
+const SCHEDULE_FIELDS = ['type', 'enabled', 'intervalMs', 'cronExpression', 'providerId', 'model', 'prompt', 'taskMetadata', 'runAfter',
+ // Perpetual (drain-until-done) recheck cadence: after a perpetual task drains
+ // its backlog and parks, it re-probes its work-detector on this cadence.
+ // `recheckCron` (5-field) takes precedence over `recheckIntervalMs`.
+ 'recheckCron', 'recheckIntervalMs'];
/**
* Pick only defined values from body for schedule settings updates
@@ -35,6 +39,23 @@ function pickScheduleSettings(body) {
if (settings.intervalMs !== undefined && settings.intervalMs !== null && (typeof settings.intervalMs !== 'number' || settings.intervalMs < 0)) {
throw new ServerError('intervalMs must be a non-negative number or null', { status: 400, code: 'VALIDATION_ERROR' });
}
+ if (settings.recheckIntervalMs !== undefined && settings.recheckIntervalMs !== null && (typeof settings.recheckIntervalMs !== 'number' || settings.recheckIntervalMs < 0)) {
+ throw new ServerError('recheckIntervalMs must be a non-negative number or null', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (settings.recheckCron !== undefined && settings.recheckCron !== null) {
+ if (typeof settings.recheckCron !== 'string') {
+ throw new ServerError('recheckCron must be a cron string or null', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const trimmed = settings.recheckCron.trim();
+ // Empty string clears it; otherwise require a 5-field cron expression.
+ if (trimmed === '') {
+ settings.recheckCron = null;
+ } else if (trimmed.split(/\s+/).length !== 5) {
+ throw new ServerError('recheckCron must be a 5-field cron expression (minute hour dayOfMonth month dayOfWeek)', { status: 400, code: 'VALIDATION_ERROR' });
+ } else {
+ settings.recheckCron = trimmed;
+ }
+ }
if (settings.taskMetadata !== undefined && settings.taskMetadata !== null) {
if (typeof settings.taskMetadata !== 'object' || Array.isArray(settings.taskMetadata)) {
throw new ServerError('taskMetadata must be an object or null', { status: 400, code: 'VALIDATION_ERROR' });
@@ -194,7 +215,8 @@ router.get('/schedule/interval-types', (req, res) => {
once: 'Runs once per app or globally, then stops',
'on-demand': 'Only runs when manually triggered',
custom: 'Custom interval in milliseconds',
- cron: 'Cron expression schedule (minute hour dayOfMonth month dayOfWeek)'
+ cron: 'Cron expression schedule (minute hour dayOfMonth month dayOfWeek)',
+ perpetual: 'Drains actionable work back-to-back until none remains, then rechecks on a cadence (recheckCron / recheckIntervalMs, default daily)'
}
});
});
diff --git a/server/services/agentCompletion.js b/server/services/agentCompletion.js
index 636266cc7e..903e103a29 100644
--- a/server/services/agentCompletion.js
+++ b/server/services/agentCompletion.js
@@ -55,6 +55,18 @@ export async function processAgentCompletion(agentId, task, success, outputBuffe
emitLog('warn', `Failed to mark app review completed: ${err.message}`, { appId });
});
+ // Perpetual (drain-until-done) tasks intentionally re-queue back-to-back
+ // until their work-detector idles and the task PARKS itself
+ // (taskSchedule.parkPerpetual). Bumping the per-app review cooldown here
+ // would throttle that drain to one item per cooldown window (default 30
+ // min), defeating the "keep going until done" contract — the drain's own
+ // park IS the throttle. Skip the cooldown bump for them (stats above still
+ // recorded). Same spirit as the recovery-task skip above.
+ if (task.metadata?.perpetual) {
+ emitLog('info', `Skipping cooldown bump for perpetual task on app ${appId}`, { appId, taskId: task.id });
+ return;
+ }
+
await startAppCooldown(appId, cooldownMs).catch(err => {
emitLog('warn', `Failed to start app cooldown: ${err.message}`, { appId });
});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 476f8fe955..8494b9c37d 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1424,6 +1424,35 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
if ('openPR' in delegatedMeta) metadata.openPR = delegatedMeta.openPR;
}
}
+ // Perpetual (drain-until-done) gate. When this task type runs on the
+ // 'perpetual' interval, a programmatic work-detector decides whether there's
+ // anything to claim BEFORE we build the (expensive) prompt or burn an agent:
+ // - actionable → clear any park so the back-to-back drain continues, and
+ // stamp metadata.perpetual so the post-completion cooldown is skipped
+ // (agentCompletion.js) and the next tick re-dispatches promptly.
+ // - idle (definitive) → PARK on the recheck cadence and skip this dispatch.
+ // - transient probe failure (gh down) → skip WITHOUT parking so the next
+ // tick retries instead of waiting out a full recheck cadence.
+ // The detector keys on the RESOLVED promptTaskType so a claim-work router run
+ // probes the concrete tracker (claim-issue → GitHub issues, plan-task → PLAN.md).
+ if (interval.type === taskSchedule.INTERVAL_TYPES.PERPETUAL) {
+ const { detectActionableWork } = await import('./perpetualWork.js');
+ const detection = await detectActionableWork(promptTaskType, app, {
+ issueAuthorFilter: metadata.issueAuthorFilter || 'owner'
+ });
+ if (detection.actionable) {
+ await taskSchedule.clearPerpetualPark(taskType, app.id);
+ metadata.perpetual = true;
+ } else if (detection.transient) {
+ emitLog('debug', `Perpetual ${taskType} skip for ${app.name} (transient: ${detection.reason})`, { appId: app.id });
+ return null;
+ } else {
+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: detection.reason, actionableCount: detection.count });
+ emitLog('info', `Perpetual ${taskType} parked for ${app.name}: ${detection.reason}`, { appId: app.id });
+ return null;
+ }
+ }
+
// Honor a direct claim-work prompt customization if the user set one;
// otherwise delegate to the resolved tracker's prompt body via
// getTaskPrompt(promptTaskType), which reads THAT type's interval.prompt
diff --git a/server/services/perpetualWork.js b/server/services/perpetualWork.js
new file mode 100644
index 0000000000..0cc618e6f8
--- /dev/null
+++ b/server/services/perpetualWork.js
@@ -0,0 +1,301 @@
+/**
+ * Perpetual Work Detectors
+ *
+ * Programmatic (no-LLM) "is there actionable work?" probes for perpetual
+ * scheduled tasks (INTERVAL_TYPES.PERPETUAL in taskSchedule.js). A perpetual
+ * task drains work back-to-back until its detector reports nothing actionable,
+ * then PARKS on a recheck cadence (see taskSchedule.parkPerpetual). The detector
+ * IS the "pre-run check": it must mirror the corresponding claim prompt's
+ * skip-list so the drain converges to the SAME empty state the agent would
+ * reach — otherwise the drain re-picks an issue the agent always skips and never
+ * parks.
+ *
+ * The registry is pluggable: `detectActionableWork(taskType, app, opts)`
+ * dispatches on the RESOLVED prompt task type (claim-issue, plan-task, …). A
+ * task type with no registered detector returns `{ actionable: false,
+ * reason: 'no-detector' }` so perpetual mode PARKS rather than drains blindly.
+ *
+ * Detector results carry a `transient` flag: a definitive "no work" (empty
+ * actionable set) parks; a transient probe failure (gh unauthenticated, list
+ * errored) is surfaced with `transient: true` so the caller skips THIS dispatch
+ * without parking — the next evaluation tick retries instead of waiting out a
+ * full recheck cadence on a blip.
+ */
+
+import { spawn } from 'child_process';
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { emitLog } from './cosEvents.js';
+import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, extractSlugFromRef } from '../lib/planIds.js';
+import { readOriginRemoteUrl, parseGitRemoteUrl } from '../lib/gitRemote.js';
+
+// Labels that make a GitHub issue non-actionable for autonomous claiming. MUST
+// stay in sync with the claim-issue prompt's Phase 1 skip-list
+// (server/services/taskPromptDefaults/prompts.js). `needs-input` is the park
+// label the agent applies when it decides an issue needs a human decision
+// (claim-issue prompt Phase 3) — excluding it here is what lets a perpetual
+// drain converge instead of re-picking the same ambiguous issue forever.
+export const NON_ACTIONABLE_ISSUE_LABELS = new Set([
+ 'in-progress', 'blocked', 'needs-input', 'future', 'wontfix', 'question', 'discussion'
+]);
+
+const CLI_TIMEOUT_MS = 15000;
+
+/**
+ * Best-effort CLI runner mirroring git.js#spawnCli (which isn't exported).
+ * Never rejects: a spawn error, non-zero exit, or timeout all resolve to a
+ * result object the detectors classify themselves.
+ */
+function runCli(cmd, args, cwd) {
+ return new Promise((resolve) => {
+ let stdout = '', stderr = '', settled = false;
+ const child = spawn(cmd, args, { cwd, shell: false, windowsHide: true });
+ const done = (result) => { if (!settled) { settled = true; clearTimeout(timer); resolve(result); } };
+ child.stdout.on('data', (d) => { stdout += d.toString(); });
+ child.stderr.on('data', (d) => { stderr += d.toString(); });
+ child.on('error', () => done({ code: -1, stdout: '', stderr: '' }));
+ child.on('close', (code) => done({ code, stdout, stderr }));
+ const timer = setTimeout(() => { try { child.kill(); } catch { /* noop */ } done({ code: -1, stdout: '', stderr: '' }); }, CLI_TIMEOUT_MS);
+ if (timer.unref) timer.unref();
+ });
+}
+
+/**
+ * Extract a GitHub issue number from a git ref ONLY when it matches a documented
+ * claim pattern (`claim/issue-<num>` or `cos/<task>/issue-<num>/<agent>`).
+ * Reuses extractSlugFromRef so the ref-matching rules stay in one place.
+ */
+export function issueNumberFromRef(ref) {
+ const slug = extractSlugFromRef(ref);
+ if (!slug) return null;
+ const m = /^issue-(\d+)$/.exec(slug);
+ return m ? Number(m[1]) : null;
+}
+
+/**
+ * Resolve the repo owner from the git origin remote (host-agnostic — works for
+ * GitHub and GitLab). For a personal repo the owner segment is the user; for an
+ * org/group it's the org/group name. The GitHub detector prefers the
+ * authoritative `gh repo view` owner instead; this is used for GitLab, whose
+ * claim prompt resolves the author filter from the project namespace.
+ */
+async function resolveRemoteOwner(repoPath) {
+ const url = await readOriginRemoteUrl(repoPath).catch(() => null);
+ const parsed = url ? parseGitRemoteUrl(url) : null;
+ return parsed?.owner || null;
+}
+
+/**
+ * Collect the set of issue numbers currently in flight, evidenced by an open
+ * `claim/issue-<num>` / `cos/.../issue-<num>/...` branch (local or remote) or an
+ * open PR/MR source ref. Best-effort — degrades to whatever evidence is reachable.
+ * `forge` selects how open changes are listed: GitHub PR head refs
+ * (`gh pr list`) vs GitLab MR source branches (`glab mr list`).
+ */
+async function inFlightIssueNumbers(repoPath, forge = 'github') {
+ const nums = new Set();
+ // The branch list and the PR/MR list are independent CLI calls — run concurrently.
+ const prListCall = forge === 'gitlab'
+ ? runCli('glab', ['mr', 'list', '--per-page', '100', '-F', 'json'], repoPath)
+ : runCli('gh', ['pr', 'list', '--state', 'open', '--json', 'headRefName', '-q', '.[].headRefName'], repoPath);
+ const [branchRes, prRes] = await Promise.all([
+ runCli('git', ['branch', '-a', '--no-color', '--format=%(refname:short)'], repoPath),
+ prListCall
+ ]);
+ const refs = (branchRes.stdout || '').split('\n').map((s) => s.trim()).filter(Boolean);
+ if (forge === 'gitlab') {
+ // glab returns MR objects as JSON; the in-flight ref is each MR's source_branch.
+ let mrs = [];
+ try { mrs = JSON.parse(prRes.stdout || '[]'); } catch { mrs = []; }
+ if (Array.isArray(mrs)) {
+ for (const mr of mrs) {
+ if (mr?.source_branch) refs.push(String(mr.source_branch).trim());
+ }
+ }
+ } else {
+ refs.push(...(prRes.stdout || '').split('\n').map((s) => s.trim()).filter(Boolean));
+ }
+ for (const ref of refs) {
+ const n = issueNumberFromRef(ref);
+ if (n != null) nums.add(n);
+ }
+ return nums;
+}
+
+/**
+ * Decide whether a single GitHub issue (as returned by `gh issue list --json`)
+ * is autonomously claimable. Mirrors the claim-issue prompt's Phase 1 step 4
+ * predicate: no in-flight claim ref, no assignees, no blocking label, not an
+ * epic. Exported for direct unit testing.
+ */
+export function isActionableIssue(issue, inFlight = new Set()) {
+ if (!issue || typeof issue.number !== 'number') return false;
+ if (inFlight.has(issue.number)) return false;
+ if (Array.isArray(issue.assignees) && issue.assignees.length > 0) return false;
+ const labels = (Array.isArray(issue.labels) ? issue.labels : [])
+ .map((l) => (typeof l === 'string' ? l : l?.name) || '')
+ .map((s) => s.toLowerCase());
+ if (labels.some((l) => NON_ACTIONABLE_ISSUE_LABELS.has(l))) return false;
+ if (labels.includes('epic')) return false;
+ if ((issue.title || '').trim().toLowerCase().endsWith('(epic)')) return false;
+ return true;
+}
+
+// Per-forge config for the shared issue detector. Each entry captures only what
+// differs between GitHub (`gh`) and GitLab (`glab`): the CLI + issue-list args,
+// how owner-mode resolves the author filter, the transient reason strings, and
+// how a raw issue maps to the forge-agnostic `{ number, title, labels, assignees }`
+// shape `isActionableIssue` expects. The control flow itself lives once in
+// `detectForgeIssues`. `inFlightForge` selects the in-flight scan dialect.
+const FORGE_ISSUE_CONFIG = {
+ 'claim-issue': {
+ cli: 'gh',
+ inFlightForge: 'github',
+ listArgs: ['issue', 'list', '--state', 'open', '--search', 'sort:created-asc', '--json', 'number,assignees,labels,title', '--limit', '100'],
+ listFail: 'gh-list-failed',
+ parseFail: 'gh-parse-failed',
+ // Authoritative repo owner (org or user) via gh; transient if gh is
+ // unauthenticated / not a GitHub remote.
+ resolveOwner: async (repoPath) => {
+ const r = await runCli('gh', ['repo', 'view', '--json', 'owner', '-q', '.owner.login'], repoPath);
+ const owner = (r.stdout || '').trim();
+ return (r.code !== 0 || !owner) ? { error: 'gh-unavailable' } : { owner };
+ },
+ normalize: (raw) => raw
+ },
+ 'claim-issue-gitlab': {
+ cli: 'glab',
+ inFlightForge: 'gitlab',
+ listArgs: ['issue', 'list', '--per-page', '100', '-F', 'json'],
+ listFail: 'glab-list-failed',
+ parseFail: 'glab-parse-failed',
+ // GitLab has no authoritative `gh repo view` equivalent here; resolve the
+ // author filter from the project namespace (git remote owner), matching the
+ // claim-issue-gitlab prompt. For a GROUP-owned project the namespace is the
+ // group (not an issue author), so owner-mode finds nothing and parks —
+ // switch the task to 'any' author mode for group projects.
+ resolveOwner: async (repoPath) => {
+ const owner = await resolveRemoteOwner(repoPath);
+ return owner ? { owner } : { error: 'glab-owner-unresolved' };
+ },
+ // GitLab keys the number on `iid` and returns labels as plain strings.
+ normalize: (raw) => raw.map((r) => ({ number: r.iid, title: r.title, labels: r.labels, assignees: r.assignees }))
+ }
+};
+
+/**
+ * Shared claim-issue detector for both forges (config in FORGE_ISSUE_CONFIG).
+ * Counts open issues that pass the same skip-list the claim agent applies,
+ * honoring the author filter ('owner' = only the repo owner's issues, default;
+ * 'any' = every author). The in-flight scan runs only when the list is
+ * non-empty, so an empty queue parks without a wasted branch/PR scan.
+ */
+async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'owner' } = {}) {
+ const cfg = FORGE_ISSUE_CONFIG[forgeKey];
+ const repoPath = app?.repoPath;
+ if (!repoPath) return { actionable: false, count: 0, reason: 'no-repo-path' };
+
+ const args = [...cfg.listArgs];
+ if (issueAuthorFilter !== 'any') {
+ const { owner, error } = await cfg.resolveOwner(repoPath);
+ // Transient: skip this dispatch and retry next tick rather than parking a full cadence.
+ if (error) return { actionable: false, count: 0, reason: error, transient: true };
+ args.push('--author', owner);
+ }
+
+ const res = await runCli(cfg.cli, args, repoPath);
+ if (res.code !== 0) return { actionable: false, count: 0, reason: cfg.listFail, transient: true };
+ let raw;
+ try {
+ raw = JSON.parse(res.stdout || '[]');
+ } catch {
+ return { actionable: false, count: 0, reason: cfg.parseFail, transient: true };
+ }
+ if (!Array.isArray(raw)) return { actionable: false, count: 0, reason: cfg.parseFail, transient: true };
+ if (raw.length === 0) return { actionable: false, count: 0, reason: 'no-open-issues' };
+
+ const inFlight = await inFlightIssueNumbers(repoPath, cfg.inFlightForge);
+ const issues = cfg.normalize(raw);
+ const actionable = issues.filter((issue) => isActionableIssue(issue, inFlight));
+ return {
+ actionable: actionable.length > 0,
+ count: actionable.length,
+ reason: actionable.length > 0 ? 'actionable-issues' : 'no-actionable-issues',
+ sample: actionable.slice(0, 5).map((i) => i.number)
+ };
+}
+
+// Forge-specific detector entry points (thin wrappers over the shared factory).
+export const detectGithubIssues = (app, opts) => detectForgeIssues('claim-issue', app, opts);
+export const detectGitlabIssues = (app, opts) => detectForgeIssues('claim-issue-gitlab', app, opts);
+
+/**
+ * plan-task detector. Mirrors applyPlanIdMetadata's pick gate: an item is
+ * actionable when it is unchecked, not blocked on human input (NEEDS_INPUT),
+ * not drift-flagged, carries an id, and isn't already in flight via a
+ * `claim/<slug>` branch/PR.
+ */
+export async function detectPlanTask(app) {
+ const repoPath = app?.repoPath;
+ if (!repoPath) return { actionable: false, count: 0, reason: 'no-repo-path' };
+ const planMd = await readFile(join(repoPath, 'PLAN.md'), 'utf-8').catch(() => '');
+ if (!planMd) return { actionable: false, count: 0, reason: 'no-plan' };
+
+ const items = parsePlanItems(planMd);
+ const knownIds = new Set(extractAllIds(planMd));
+ const inFlight = await findInProgressIds(repoPath, knownIds).catch(() => new Set());
+ const pick = pickFirstAvailable(items, inFlight);
+ const count = items.filter((it) =>
+ !it.checked && !it.needsInput && !it.drifted && it.id && !inFlight.has(it.id)
+ ).length;
+ return {
+ actionable: !!pick,
+ count,
+ reason: pick ? 'actionable-plan-items' : 'no-actionable-plan-items'
+ };
+}
+
+// ============================================================
+// Registry
+// ============================================================
+
+const DETECTORS = new Map();
+
+export function registerWorkDetector(taskType, fn) {
+ DETECTORS.set(taskType, fn);
+}
+
+export function getWorkDetector(taskType) {
+ return DETECTORS.get(taskType) || null;
+}
+
+export function hasWorkDetector(taskType) {
+ return DETECTORS.has(taskType);
+}
+
+// Built-in detectors. claim-work resolves to one of these RESOLVED prompt task
+// types before dispatch, so claim-work itself needs no detector. The JIRA claim
+// flow (claim-issue-jira) has no detector yet — perpetual mode on a JIRA-tracked
+// app parks with reason 'no-detector' until one is registered.
+registerWorkDetector('claim-issue', detectGithubIssues);
+registerWorkDetector('claim-issue-gitlab', detectGitlabIssues);
+registerWorkDetector('plan-task', detectPlanTask);
+
+/**
+ * Probe whether `taskType` has actionable work for `app`. Always resolves to a
+ * normalized shape: `{ actionable, count, reason, transient?, hasDetector }`.
+ * A detector throw is caught and reported as a transient failure so the caller
+ * skips (and retries) rather than parking on a broken probe.
+ */
+export async function detectActionableWork(taskType, app, opts = {}) {
+ const detector = DETECTORS.get(taskType);
+ if (!detector) {
+ return { actionable: false, count: 0, reason: 'no-detector', hasDetector: false };
+ }
+ const result = await detector(app, opts).catch((err) => {
+ emitLog('warn', `Perpetual work-detector for ${taskType} errored: ${err.message}`, { taskType, appId: app?.id }, '🔁 Perpetual');
+ return { actionable: false, count: 0, reason: `detector-error: ${err.message}`, transient: true };
+ });
+ // Every detector (and the catch above) returns `count`, so spread last.
+ return { ...result, hasDetector: true };
+}
diff --git a/server/services/perpetualWork.test.js b/server/services/perpetualWork.test.js
new file mode 100644
index 0000000000..7fabb1bf23
--- /dev/null
+++ b/server/services/perpetualWork.test.js
@@ -0,0 +1,199 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { EventEmitter } from 'events';
+
+vi.mock('./cosEvents.js', () => ({
+ cosEvents: { emit: vi.fn() },
+ emitLog: vi.fn()
+}));
+
+vi.mock('child_process', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, spawn: vi.fn() };
+});
+
+import { spawn } from 'child_process';
+import {
+ isActionableIssue,
+ issueNumberFromRef,
+ detectActionableWork,
+ detectGithubIssues,
+ detectGitlabIssues,
+ registerWorkDetector,
+ getWorkDetector,
+ hasWorkDetector,
+ NON_ACTIONABLE_ISSUE_LABELS
+} from './perpetualWork.js';
+
+// A fake child process that emits canned stdout then closes — enough for the
+// best-effort runCli() in perpetualWork.js (stdout/close/error + kill).
+function fakeChild(stdout, code = 0) {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = () => {};
+ setImmediate(() => {
+ if (stdout) child.stdout.emit('data', Buffer.from(stdout));
+ child.emit('close', code);
+ });
+ return child;
+}
+
+// Route spawn calls to canned output by command + first arg.
+function routeSpawn(routes) {
+ spawn.mockImplementation((cmd, args = []) => {
+ const key = `${cmd} ${args[0] || ''}`;
+ const r = routes[key];
+ return fakeChild(r?.stdout ?? '', r?.code ?? 0);
+ });
+}
+
+describe('perpetualWork', () => {
+ describe('isActionableIssue', () => {
+ const base = { number: 7, title: 'Fix the thing', assignees: [], labels: [] };
+
+ it('accepts a plain open unassigned issue', () => {
+ expect(isActionableIssue(base)).toBe(true);
+ });
+
+ it('rejects an assigned issue', () => {
+ expect(isActionableIssue({ ...base, assignees: [{ login: 'someone' }] })).toBe(false);
+ });
+
+ it('rejects an in-flight issue number', () => {
+ expect(isActionableIssue(base, new Set([7]))).toBe(false);
+ });
+
+ it.each([...NON_ACTIONABLE_ISSUE_LABELS])('rejects a %s-labelled issue', (label) => {
+ expect(isActionableIssue({ ...base, labels: [{ name: label }] })).toBe(false);
+ });
+
+ it('treats the needs-input park label as non-actionable (drain convergence)', () => {
+ expect(isActionableIssue({ ...base, labels: [{ name: 'needs-input' }] })).toBe(false);
+ });
+
+ it('rejects an epic by label or by "(epic)" title', () => {
+ expect(isActionableIssue({ ...base, labels: [{ name: 'epic' }] })).toBe(false);
+ expect(isActionableIssue({ ...base, title: 'Big rollup (epic)' })).toBe(false);
+ });
+
+ it('accepts a plan-labelled issue (plan is the claimable queue, not a skip)', () => {
+ expect(isActionableIssue({ ...base, labels: [{ name: 'plan' }] })).toBe(true);
+ });
+
+ it('handles string labels as well as objects', () => {
+ expect(isActionableIssue({ ...base, labels: ['blocked'] })).toBe(false);
+ });
+
+ it('rejects malformed issues', () => {
+ expect(isActionableIssue(null)).toBe(false);
+ expect(isActionableIssue({ title: 'no number' })).toBe(false);
+ });
+ });
+
+ describe('issueNumberFromRef', () => {
+ it('extracts from a claim/issue-<num> ref', () => {
+ expect(issueNumberFromRef('claim/issue-123')).toBe(123);
+ expect(issueNumberFromRef('origin/claim/issue-99')).toBe(99);
+ });
+
+ it('extracts from a cos/<task>/issue-<num>/<agent> ref', () => {
+ expect(issueNumberFromRef('cos/claim-issue/issue-45/agent-x')).toBe(45);
+ });
+
+ it('returns null for non-claim refs', () => {
+ expect(issueNumberFromRef('feature/foo')).toBe(null);
+ expect(issueNumberFromRef('main')).toBe(null);
+ expect(issueNumberFromRef('claim/some-slug')).toBe(null); // slug, not issue-<num>
+ });
+ });
+
+ describe('registry', () => {
+ it('claim-issue, claim-issue-gitlab and plan-task are registered by default', () => {
+ expect(hasWorkDetector('claim-issue')).toBe(true);
+ expect(hasWorkDetector('claim-issue-gitlab')).toBe(true);
+ expect(hasWorkDetector('plan-task')).toBe(true);
+ expect(typeof getWorkDetector('claim-issue')).toBe('function');
+ });
+
+ it('detectActionableWork reports no-detector for an unregistered type (e.g. JIRA)', async () => {
+ const out = await detectActionableWork('claim-issue-jira', { id: 'a' });
+ expect(out).toEqual({ actionable: false, count: 0, reason: 'no-detector', hasDetector: false });
+ });
+
+ it('detectActionableWork normalizes a registered detector result', async () => {
+ registerWorkDetector('__test-type__', async () => ({ actionable: true, count: 3, reason: 'actionable-issues' }));
+ const out = await detectActionableWork('__test-type__', { id: 'a' });
+ expect(out).toMatchObject({ actionable: true, count: 3, reason: 'actionable-issues', hasDetector: true });
+ });
+
+ it('detectActionableWork catches a detector throw as a transient failure', async () => {
+ registerWorkDetector('__throwing__', async () => { throw new Error('boom'); });
+ const out = await detectActionableWork('__throwing__', { id: 'a' });
+ expect(out.actionable).toBe(false);
+ expect(out.transient).toBe(true);
+ expect(out.reason).toContain('boom');
+ });
+ });
+
+ describe('detectGithubIssues (spawn-mocked)', () => {
+ beforeEach(() => { spawn.mockReset(); });
+ const app = { id: 'a', repoPath: '/repo' };
+
+ it('counts actionable issues, excluding labelled/assigned/in-flight', async () => {
+ routeSpawn({
+ 'gh issue': { stdout: JSON.stringify([
+ { number: 1, title: 'plain', assignees: [], labels: [] },
+ { number: 2, title: 'needs a decision', assignees: [], labels: [{ name: 'needs-input' }] },
+ { number: 3, title: 'taken', assignees: [{ login: 'x' }], labels: [] },
+ { number: 4, title: 'in flight', assignees: [], labels: [] },
+ { number: 5, title: 'also plain', assignees: [], labels: [{ name: 'plan' }] }
+ ]) },
+ 'git branch': { stdout: 'main\norigin/claim/issue-4\n' },
+ 'gh pr': { stdout: '' }
+ });
+ const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
+ expect(out.actionable).toBe(true);
+ expect(out.count).toBe(2); // #1 and #5 (plan is claimable); #2 #3 #4 excluded
+ expect(out.sample).toEqual([1, 5]);
+ });
+
+ it('parks (no-open-issues) on an empty list', async () => {
+ routeSpawn({ 'gh issue': { stdout: '[]' } });
+ const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
+ expect(out).toMatchObject({ actionable: false, reason: 'no-open-issues' });
+ });
+
+ it('reports a transient failure when gh exits non-zero', async () => {
+ routeSpawn({ 'gh issue': { stdout: '', code: 1 } });
+ const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
+ expect(out).toMatchObject({ actionable: false, reason: 'gh-list-failed', transient: true });
+ });
+ });
+
+ describe('detectGitlabIssues (spawn-mocked)', () => {
+ beforeEach(() => { spawn.mockReset(); });
+ const app = { id: 'a', repoPath: '/repo' };
+
+ it('normalizes iid + string labels and excludes MR-in-flight issues', async () => {
+ routeSpawn({
+ 'glab issue': { stdout: JSON.stringify([
+ { iid: 10, title: 'plain', assignees: [], labels: [] },
+ { iid: 11, title: 'blocked', assignees: [], labels: ['blocked'] },
+ { iid: 12, title: 'in flight via MR', assignees: [], labels: [] }
+ ]) },
+ 'git branch': { stdout: 'main\n' },
+ 'glab mr': { stdout: JSON.stringify([{ source_branch: 'claim/issue-12' }]) }
+ });
+ const out = await detectGitlabIssues(app, { issueAuthorFilter: 'any' });
+ expect(out.actionable).toBe(true);
+ expect(out.count).toBe(1); // only #10 (#11 blocked label, #12 in-flight MR)
+ expect(out.sample).toEqual([10]);
+ });
+
+ it('reports a transient failure when glab exits non-zero', async () => {
+ routeSpawn({ 'glab issue': { stdout: '', code: 1 } });
+ const out = await detectGitlabIssues(app, { issueAuthorFilter: 'any' });
+ expect(out).toMatchObject({ actionable: false, reason: 'glab-list-failed', transient: true });
+ });
+ });
+});
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index 58c96a350c..0c3a4ca60e 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -12,8 +12,8 @@
"mobile-responsive": "16d8e7f63a673a2de48994c0ac08ef3d",
"feature-ideas": "0741418bd275b8953131155f8bc89460",
"plan-task": "5425306bf082b15b6a17f972557d4dd9",
- "claim-issue": "28f09436566c281a6915d6ad4c1b80f8",
- "claim-issue-gitlab": "880dd7820ac90c689065e28cdca032fb",
+ "claim-issue": "89308f712f99ad8134224639cd99f135",
+ "claim-issue-gitlab": "271ad9c6efa9dce424103711292fd055",
"claim-issue-jira": "157cfc80c3d00bcbf3e97aae3998c372",
"code-reviewer-review": "1cd13ee5142d130f95cc390098d0f278",
"code-reviewer-implement": "ab2c3e16d54e195bdf856574b7702042",
@@ -34,8 +34,8 @@
"PROMPT_VERSIONS": {
"feature-ideas": 9,
"plan-task": 8,
- "claim-issue": 2,
- "claim-issue-gitlab": 1,
+ "claim-issue": 3,
+ "claim-issue-gitlab": 2,
"claim-issue-jira": 1,
"pr-reviewer": 3,
"code-reviewer-a": 1,
@@ -80,8 +80,12 @@
"f9322140bff7d3f603799c09ce468da9"
],
"pr-watcher": [],
+ "claim-issue-gitlab": [
+ "880dd7820ac90c689065e28cdca032fb"
+ ],
"claim-issue": [
- "06190b8089adf1cb2c84bddeb6596af7"
+ "06190b8089adf1cb2c84bddeb6596af7",
+ "28f09436566c281a6915d6ad4c1b80f8"
],
"security": [
"d0f54c1fbe62d067b1a23ee0a9f3528c"
diff --git a/server/services/taskPromptDefaults/previousDefaults.js b/server/services/taskPromptDefaults/previousDefaults.js
index 781c010c11..b07ab6d030 100644
--- a/server/services/taskPromptDefaults/previousDefaults.js
+++ b/server/services/taskPromptDefaults/previousDefaults.js
@@ -1250,6 +1250,127 @@ For each reference above:
// empty list so the auto-upgrade machinery has an entry to consult and the
// next prompt revision just appends the v1 body here.
'pr-watcher': [],
+ // claim-issue-gitlab v1 default — GitLab sibling of claim-issue v2; did NOT
+ // tag un-actionable issues `needs-input`, so a perpetual drain would re-pick
+ // an ambiguous issue forever. Superseded by v2 (adds needs-input tagging in
+ // Phase 3). Kept so a stored v1 prompt auto-upgrades.
+ 'claim-issue-gitlab': [
+ `[Claim Issue: {appName}] Claim and ship the next open GitLab issue
+
+Pick the next available unclaimed open GitLab issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the \`/claim --issues\` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is \`glab\` (not \`gh\`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.
+
+{issueAuthorFilter}
+
+**How claiming works.** An issue is "in flight" when its number appears as the issue-position segment in either a \`claim/issue-<num>\` ref (the human/TUI pattern) or a \`cos/<task>/issue-<num>/<agent>\` ref (the CoS sub-agent pattern) across local branches, remote branches, or open MR source-branch refs — OR the issue is already assigned to someone OR carries an \`in-progress\` label. The \`claim/issue-<num>\` branch + the assignee/\`in-progress\` markers you set ARE the claim, visible to every other agent (including parallel machines).
+
+## Phase 1 — Pick the target issue
+
+Run steps 1–5 in order.
+
+1. cd into the repo root ({repoPath}) and confirm GitLab is the forge and \`glab\` is authenticated: \`glab auth status\` and \`glab repo view\`. If \`glab\` is not authenticated or the remote is not GitLab, exit cleanly — this task only works against GitLab issue trackers.
+2. List candidate open issues, honoring the author filter described above. Fetch a JSON page and order **oldest-first** (GitLab returns newest-first by default; sort client-side by \`created_at\` since the page is bounded):
+ \`\`\`bash
+ git fetch --prune 2>/dev/null
+ # Owner-only mode (default): add --author <owner> (resolve <owner> from the project namespace).
+ glab issue list --per-page 100 -F json
+ # Any-author mode: run the SAME command WITHOUT --author.
+ \`\`\`
+3. Build the in-flight set. Collect every branch/MR source ref:
+ \`\`\`bash
+ git branch -a --no-color --format='%(refname:short)'
+ glab mr list --per-page 100 -F json # read each MR's source_branch
+ \`\`\`
+ For each ref (after stripping any leading \`origin/\` prefix), extract the issue number **only when the ref matches** \`claim/issue-<num>\` (number after \`claim/issue-\`) or \`cos/<task>/issue-<num>/<agent>\` (the \`issue-<num>\` third segment). Do NOT flag an issue just because its bare number appears elsewhere in a ref.
+4. **Pick the target issue:** walk the candidate list oldest-first and pick the FIRST issue where ALL of the following are true:
+ - Its number (\`iid\`) is NOT in the in-flight set.
+ - It has NO assignees (an assignee means another machine/human already claimed it).
+ - It does NOT carry any of these blocking labels: \`in-progress\`, \`blocked\`, \`needs-input\`, \`future\`, \`wontfix\`, \`question\`, \`discussion\`.
+ - It is NOT a tracking/umbrella **epic** — recognized by an \`epic\` label OR a title ending in "(epic)". Leave epics for a human to split. **The bare \`plan\` label is NOT a skip signal** — it marks the claimable queue, not a blocker.
+5. **If no eligible issue exists**, exit cleanly — an empty actionable queue is a healthy state, not a failure.
+
+Capture the issue number (GitLab \`iid\`) as \`NUM\`, its title, and its full description — you'll reuse them in the MR and the \`Closes #<num>\` line.
+
+## Phase 2 — Claim (worktree + markers)
+
+Detect the default branch first (forge-agnostic), then create the worktree on \`claim/issue-<num>\` and set the cross-machine claim markers. Do all editing inside the worktree, NEVER in the source repo's working tree.
+
+\`\`\`bash
+NUM=<picked-number>
+DEFAULT_BRANCH="$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's@^origin/@@')"
+DEFAULT_BRANCH="\${DEFAULT_BRANCH:-main}"
+WORKTREE="data/cos/worktrees/claim-issue-\${NUM}"
+mkdir -p data/cos/worktrees
+git fetch origin "\${DEFAULT_BRANCH}"
+git worktree add -b "claim/issue-\${NUM}" "\${WORKTREE}" "origin/\${DEFAULT_BRANCH}"
+# Cross-machine claim markers (best-effort — do not abort the run if these fail).
+# Resolve your own username first — glab's --assignee wants a username (the
+# \`@me\` gh-ism isn't universally supported), falling back to @me if the lookup fails:
+ME="$(glab api user 2>/dev/null | sed -n 's/.*"username":"\\([^"]*\\)".*/\\1/p')"
+glab issue update "\${NUM}" --assignee "\${ME:-@me}" 2>/dev/null
+glab issue update "\${NUM}" --label in-progress 2>/dev/null
+cd "\${WORKTREE}"
+\`\`\`
+
+**If \`git worktree add\` fails because the \`claim/issue-<num>\` branch already exists** (a concurrent run won the race), do NOT force or reuse it — that branch IS another run's claim. Treat the issue as in-flight, return to Phase 1, and pick the next eligible issue; if nothing else is eligible, exit cleanly. Stash \`WORKTREE\` — you'll need it for Phase 7 cleanup.
+
+## Phase 3 — Verify still valid
+
+Read the full issue (\`glab issue view "\${NUM}"\`) before writing any code. **If ANY of these are true, release the claim and re-pick** (remove the assignee with \`glab issue update "\${NUM}" --unassign\` + the \`in-progress\` label with \`--unlabel in-progress\`, remove the worktree, return to Phase 1):
+
+- A note indicates the issue was already fixed, superseded, or closed-then-reopened-for-tracking.
+- The request references a function, file, or component that no longer exists (\`grep -rn\` the named identifiers — if they're gone, the issue is stale).
+- The work would require touching files far outside the issue's scope (>5 unrelated files).
+- The requirements are too ambiguous to implement without user clarification.
+
+If too ambiguous or large, post a brief note (\`glab issue note "\${NUM}" -m "..."\`), release the markers (\`glab issue update "\${NUM}" --unassign --unlabel in-progress\`), remove the worktree, and exit cleanly so a human can refine it. Do NOT leave a half-claimed issue.
+
+## Phase 4 — Implement
+
+Write the code, tests, and any docs the issue requires. Follow the repo conventions in CLAUDE.md. Run the relevant test suite as you go.
+
+**Roll discovered backbone work INTO this MR** — small supporting helpers, refactors, and tests that the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work; when you do, file a NEW issue (\`glab issue create\`) tagged \`plan\` that references this one (\`Related to #<num>\`).
+
+Commit with a conventional message referencing the issue:
+
+\`\`\`
+<type>: <one-line description> (#<num>)
+\`\`\`
+
+## Phase 5 — Open the merge request
+
+This flow ships GitLab issues — it does NOT touch PLAN.md. The audit trail is the merged MR + \`git log\`.
+
+1. If the repo maintains a changelog (\`.changelog/NEXT.md\`, or a \`## Unreleased\` section in \`CHANGELOG.md\`), append a one-line entry mirroring the repo's existing prose style. If no changelog convention exists, skip this.
+2. Push the branch: \`git push -u origin "claim/issue-\${NUM}"\`
+3. Open the MR with \`glab mr create --fill --source-branch "claim/issue-\${NUM}" --target-branch "\${DEFAULT_BRANCH}" --yes\`. The MR description MUST contain \`Closes #\${NUM}\` so the merge auto-closes the issue. Summarize what shipped + a short test plan (pass \`--description\` if \`--fill\` didn't capture it).
+
+## Phase 6 — Review and ship
+
+The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\` / \`codex\` / \`antigravity\` invoke a local-CLI critique. (\`copilot\` is GitHub-only — skip it on GitLab.) When more than one is configured, run each in the listed order before merging.
+
+1. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix findings in the same diff BEFORE the reviewers run. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.
+2. **Wait for each configured CLI reviewer's findings BEFORE merging.** For \`claude\` / \`codex\` / \`antigravity\`, invoke that CLI headless against the MR diff, apply fixes, run tests, re-push — capped at 3 rounds — then advance to the next reviewer.
+
+ **Review-stuck cleanup** (after 3 unresolved rounds): post one summarizing MR note (\`glab mr note\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open MR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.
+3. **Merge via \`glab mr merge\`** — NEVER a local \`git merge\`. \`glab mr merge\` takes the **MR IID**, which is NOT the issue number — resolve it from the source branch first, then merge by that IID:
+ \`\`\`bash
+ MR_IID="$(glab mr list --source-branch "claim/issue-\${NUM}" -F json | sed -n 's/.*"iid":\\([0-9]\\{1,\\}\\).*/\\1/p' | head -1)"
+ glab mr merge "\${MR_IID}" --yes --remove-source-branch \\
+ || glab mr merge "\${MR_IID}" --yes --squash --remove-source-branch
+ \`\`\`
+
+## Phase 7 — Clean up (post-merge ONLY)
+
+This phase runs only after the MR merged via Phase 6. From the **source repo** (cd back to {repoPath} first):
+
+\`\`\`bash
+cd {repoPath}
+git worktree remove "\${WORKTREE}"
+git branch -d "claim/issue-\${NUM}"
+\`\`\`
+
+If \`git branch -d\` refuses, use \`-D\` — the MR is confirmed merged, so the local branch is redundant. Verify the issue closed (the \`Closes #\${NUM}\` line auto-closes it on merge to the default branch); if it's still open, close it manually (\`glab issue close "\${NUM}"\`) and remove the \`in-progress\` label (\`glab issue update "\${NUM}" --unlabel in-progress\`). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitLab via \`glab mr merge\`; leave the user's working tree alone.`
+ ],
// claim-issue v1 default — excluded every `plan`-labelled issue (the entire
// migrated backlog), so auto-pick always reported an empty queue. Superseded
// by v2, which skips only true epics. Kept so a stored v1 prompt auto-upgrades.
@@ -1371,6 +1492,127 @@ git branch -d "claim/issue-\${NUM}"
\`\`\`
If \`git branch -d\` refuses (the PR squash-merged on GitHub but local doesn't know yet), use \`-D\` — the PR is confirmed merged, so the local branch is redundant. Verify the issue closed (the \`Closes #\${NUM}\` trailer auto-closes it on merge); if it's still open, close it manually (\`gh issue close "\${NUM}"\`) and remove the \`in-progress\` label (\`gh issue edit "\${NUM}" --remove-label in-progress\`). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitHub via \`gh pr merge\`; leave the user's working tree alone.`,
+ // claim-issue v2 default — skipped only true epics but did NOT tag
+ // un-actionable issues, so an autonomous drain would re-pick an ambiguous
+ // issue forever. Superseded by v3, which adds `needs-input` tagging in
+ // Phase 3. Kept so a stored v2 prompt auto-upgrades.
+ `[Claim Issue: {appName}] Claim and ship the next open GitHub issue
+
+Pick the next available unclaimed open GitHub issue, **create your own worktree at \`claim/issue-<num>\`**, implement the fix, ship a PR that closes the issue, and clean up. This is the \`/claim --issues\` flow — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's GitHub issue tracker instead of PLAN.md. **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.
+
+{issueAuthorFilter}
+
+**How claiming works.** An issue is "in flight" when its number appears as the issue-position segment in either a \`claim/issue-<num>\` ref (the human/TUI pattern) or a \`cos/<task>/issue-<num>/<agent>\` ref (the CoS sub-agent pattern) across local branches, remote branches, or open PR head refs — OR the issue is already assigned to someone OR carries an \`in-progress\` label. The \`claim/issue-<num>\` branch + the assignee/\`in-progress\` markers you set ARE the claim, visible to every other agent (including parallel machines) and to the human running \`/claim --issues\` in a TUI.
+
+## Phase 1 — Pick the target issue
+
+Run steps 1–5 in order.
+
+1. cd into the repo root ({repoPath}) and confirm GitHub is the forge: \`gh repo view --json nameWithOwner -q .nameWithOwner\`. If \`gh\` is not authenticated or the remote is not GitHub, exit cleanly — this task only works against GitHub issue trackers.
+2. List candidate open issues **oldest-first**, honoring the author filter described above. \`gh issue list\` defaults to newest-first, so order on the SERVER with \`--search "sort:created-asc"\` — a client-side \`jq\` sort would only reorder the already-truncated newest page, dropping the true oldest issues on repos with more than \`--limit\` open issues:
+ \`\`\`bash
+ git fetch --prune 2>/dev/null
+ # Author filter (see the block above). Pass --author as a QUOTED single token —
+ # do NOT pack flag+value into one variable: a bare \`$VAR\` holding "--author x"
+ # is a single argv token in zsh (no word-splitting) and gh rejects it.
+ # Owner-only mode (default): resolve the owner, then add --author "$OWNER"
+ OWNER="$(gh repo view --json owner -q .owner.login)"
+ gh issue list --state open --author "$OWNER" --search "sort:created-asc" --json number,title,author,assignees,labels,createdAt --limit 100
+ # Any-author mode: run the SAME command WITHOUT the --author "$OWNER" flag.
+ \`\`\`
+3. Build the in-flight set. Collect every branch/PR ref:
+ \`\`\`bash
+ git branch -a --no-color --format='%(refname:short)'
+ gh pr list --state open --json headRefName -q '.[].headRefName' 2>/dev/null
+ \`\`\`
+ For each ref (after stripping any leading \`origin/\` / \`upstream/\` prefix), extract the issue number **only when the ref matches** \`claim/issue-<num>\` (number after \`claim/issue-\`) or \`cos/<task>/issue-<num>/<agent>\` (the \`issue-<num>\` third segment). Do NOT flag an issue just because its bare number appears elsewhere in a ref.
+4. **Pick the target issue:** walk the candidate list oldest-first and pick the FIRST issue where ALL of the following are true:
+ - Its number is NOT in the in-flight set.
+ - It has NO assignees (an assignee means another machine/human already claimed it).
+ - It does NOT carry any of these blocking labels: \`in-progress\`, \`blocked\`, \`needs-input\`, \`future\`, \`wontfix\`, \`question\`, \`discussion\`.
+ - It is NOT a tracking/umbrella **epic** — recognized by an \`epic\` label OR a title ending in "(epic)". An epic needs per-slice partial-ship (each slice its own PR, \`Refs\` not \`Closes\`), so leave it for a human or \`/claim --issues\` to split — don't claim it wholesale here. **The bare \`plan\` label is NOT a skip signal.** \`do-replan --issues\` (and \`/do:replan --issues\`) labels EVERY migrated backlog item \`plan\` — atomic bug-fixes included — so \`plan\` marks the *claimable* queue exactly as \`/do:next --issues\` treats it (it is that flow's required candidate label). Skipping all \`plan\` issues would discard the entire actionable backlog and falsely report an empty queue.
+5. **If no eligible issue exists**, exit cleanly — an empty actionable queue is a healthy state, not a failure.
+
+Capture the issue number as \`NUM\`, its title, and its full body — you'll reuse them in the PR and the \`Closes #<num>\` trailer.
+
+## Phase 2 — Claim (worktree + markers)
+
+Create the worktree on a branch named \`claim/issue-<num>\`, then set the cross-machine claim markers. Do all editing inside the worktree, NEVER in the source repo's working tree.
+
+\`\`\`bash
+NUM=<picked-number>
+WORKTREE="data/cos/worktrees/claim-issue-\${NUM}"
+mkdir -p data/cos/worktrees
+git fetch origin main
+git worktree add -b "claim/issue-\${NUM}" "\${WORKTREE}" origin/main
+# Cross-machine claim markers (best-effort — do not abort the run if these fail):
+gh issue edit "\${NUM}" --add-assignee @me 2>/dev/null
+gh issue edit "\${NUM}" --add-label in-progress 2>/dev/null
+cd "\${WORKTREE}"
+\`\`\`
+
+(If the repo's default branch is not \`main\`, detect it with \`gh repo view --json defaultBranchRef -q .defaultBranchRef.name\` and substitute it for \`main\` above.)
+
+**If \`git worktree add\` fails because the \`claim/issue-<num>\` branch already exists** (a concurrent run won the race, or a remote claim branch is now visible), do NOT force or reuse it — that branch IS another run's claim. Treat the issue as in-flight, return to Phase 1, and pick the next eligible issue; if nothing else is eligible, exit cleanly. Stash \`WORKTREE\` — you'll need it for Phase 7 cleanup.
+
+## Phase 3 — Verify still valid
+
+Read the full issue (\`gh issue view "\${NUM}" --comments\`) before writing any code. **If ANY of these are true, release the claim and re-pick** (remove the assignee + \`in-progress\` label you set, remove the worktree, return to Phase 1):
+
+- A comment indicates the issue was already fixed, superseded, or closed-then-reopened-for-tracking.
+- The request references a function, file, or component that no longer exists (\`grep -rn\` the named identifiers — if they're gone, the issue is stale).
+- The work would require touching files far outside the issue's scope (>5 unrelated files), suggesting it's bigger than a single claim.
+- The requirements are too ambiguous to implement without user clarification.
+
+If the issue is too ambiguous or large, post a brief comment on the issue explaining what's blocking (\`gh issue comment "\${NUM}" --body "..."\`), release the markers (\`gh issue edit "\${NUM}" --remove-assignee @me --remove-label in-progress\`), remove the worktree, and exit cleanly so a human can refine it. Do NOT leave a half-claimed issue.
+
+## Phase 4 — Implement
+
+Write the code, tests, and any docs the issue requires. Follow the repo conventions in CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates). Run the relevant test suite as you go.
+
+**Roll discovered backbone work INTO this PR** — small supporting helpers, refactors, and tests that the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work; when you do, file a NEW issue (\`gh issue create\`) tagged \`plan\` that references this one (\`Related to #<num>\`) rather than appending to PLAN.md.
+
+Commit with a conventional message referencing the issue so the trail is grep-able:
+
+\`\`\`
+<type>: <one-line description> (#<num>)
+\`\`\`
+
+## Phase 5 — Open the PR
+
+This flow ships GitHub issues — it does NOT touch PLAN.md. The audit trail is the merged PR + \`git log\`.
+
+1. If the repo maintains a changelog (\`.changelog/NEXT.md\`, or a \`## Unreleased\` section in \`CHANGELOG.md\`), append a one-line entry mirroring the repo's existing prose style. If no changelog convention exists, skip this — the PR + commit history is the record.
+2. Push the branch: \`git push -u origin "claim/issue-\${NUM}"\`
+3. Open the PR with \`gh pr create\`. The body MUST contain \`Closes #\${NUM}\` so the merge auto-closes the issue. Summarize what shipped + a short test plan.
+
+## Phase 6 — Review and ship
+
+The configured reviewers for this task, in order, are \`{reviewers}\`. \`copilot\` waits for GitHub's auto-review; \`claude\` / \`codex\` / \`antigravity\` invoke a local-CLI critique. When more than one is configured, run each in the listed order before merging — this mirrors slashdo's \`/do:pr --review-with <list>\`.
+
+1. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix findings in the same diff BEFORE the reviewers run. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.
+2. **Wait for each configured reviewer's findings BEFORE merging.** \`gh pr merge --auto\` only waits for required status checks; it does NOT wait for code-review feedback. Run the reviewers in the listed order (\`{reviewers}\`); for \`copilot\`, poll up to 10 minutes for its review and address \`COMMENTED\` / \`CHANGES_REQUESTED\` findings (commit + push inside the worktree, re-poll), capped at 3 rounds. For \`claude\` / \`codex\` / \`antigravity\`, invoke that CLI headless against the PR diff, apply fixes, run tests, re-push — capped at 3 rounds — then advance to the next reviewer.
+
+ **Review-stuck cleanup** (after 3 unresolved rounds): post one summarizing PR comment (\`gh pr comment\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open PR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.
+3. **Merge via \`gh pr merge\`** — NEVER a local \`git merge\`. The repo may allow only one method, so try in order and use the first that succeeds:
+ \`\`\`bash
+ gh pr merge <pr-num> --auto --delete-branch \\
+ || gh pr merge <pr-num> --merge --delete-branch \\
+ || gh pr merge <pr-num> --squash --delete-branch \\
+ || gh pr merge <pr-num> --rebase --delete-branch
+ \`\`\`
+
+## Phase 7 — Clean up (post-merge ONLY)
+
+This phase runs only after the PR merged via Phase 6. From the **source repo** (cd back to {repoPath} first):
+
+\`\`\`bash
+cd {repoPath}
+git worktree remove "\${WORKTREE}"
+git branch -d "claim/issue-\${NUM}"
+\`\`\`
+
+If \`git branch -d\` refuses (the PR squash-merged on GitHub but local doesn't know yet), use \`-D\` — the PR is confirmed merged, so the local branch is redundant. Verify the issue closed (the \`Closes #\${NUM}\` trailer auto-closes it on merge); if it's still open, close it manually (\`gh issue close "\${NUM}"\`) and remove the \`in-progress\` label (\`gh issue edit "\${NUM}" --remove-label in-progress\`). **Do NOT \`git pull\`** from inside this phase — the work is already integrated on GitHub via \`gh pr merge\`; leave the user's working tree alone.`
],
// Basic self-improvement tasks: prior defaults that hardcoded the target app as
// "PortOS" (and, for some, http://localhost:5555) plus a couple of intermediate
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index 51e9869ca0..4f37a4753c 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -555,7 +555,7 @@ Read the full issue (\`gh issue view "\${NUM}" --comments\`) before writing any
- The work would require touching files far outside the issue's scope (>5 unrelated files), suggesting it's bigger than a single claim.
- The requirements are too ambiguous to implement without user clarification.
-If the issue is too ambiguous or large, post a brief comment on the issue explaining what's blocking (\`gh issue comment "\${NUM}" --body "..."\`), release the markers (\`gh issue edit "\${NUM}" --remove-assignee @me --remove-label in-progress\`), remove the worktree, and exit cleanly so a human can refine it. Do NOT leave a half-claimed issue.
+If the issue is too ambiguous or large, post a brief comment on the issue explaining exactly what decision or clarification a human must provide (\`gh issue comment "\${NUM}" --body "..."\`), then **tag it \`needs-input\` so it's excluded from future autonomous claims** (\`gh issue edit "\${NUM}" --add-label needs-input\`), release the claim markers (\`gh issue edit "\${NUM}" --remove-assignee @me --remove-label in-progress\`), remove the worktree, and exit cleanly so a human can refine it. **The \`needs-input\` label is what lets an autonomous drain converge** — Phase 1 step 4 skips \`needs-input\` issues, so without the tag this same un-actionable issue would be re-picked on the next pass forever. Do NOT leave a half-claimed issue.
## Phase 4 — Implement
@@ -679,7 +679,7 @@ Read the full issue (\`glab issue view "\${NUM}"\`) before writing any code. **I
- The work would require touching files far outside the issue's scope (>5 unrelated files).
- The requirements are too ambiguous to implement without user clarification.
-If too ambiguous or large, post a brief note (\`glab issue note "\${NUM}" -m "..."\`), release the markers (\`glab issue update "\${NUM}" --unassign --unlabel in-progress\`), remove the worktree, and exit cleanly so a human can refine it. Do NOT leave a half-claimed issue.
+If too ambiguous or large, post a brief note explaining exactly what decision or clarification a human must provide (\`glab issue note "\${NUM}" -m "..."\`), then **tag it \`needs-input\` so it's excluded from future autonomous claims** (\`glab issue update "\${NUM}" --label needs-input\`), release the claim markers (\`glab issue update "\${NUM}" --unassign --unlabel in-progress\`), remove the worktree, and exit cleanly so a human can refine it. **The \`needs-input\` label is what lets an autonomous drain converge** — Phase 1 step 4 skips \`needs-input\` issues, so without the tag this same un-actionable issue would be re-picked on the next pass forever. Do NOT leave a half-claimed issue.
## Phase 4 — Implement
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index ad34c8b00c..5553017bae 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -9,8 +9,8 @@
export const PROMPT_VERSIONS = {
'feature-ideas': 9, // v9: drop DONE.md reads — use `.changelog/` + `git log` (last 50) as the completed-work signal
'plan-task': 8, // v8: Phase-6 merge fallback prefers --merge over --squash (after --auto), matching the /do:pr + review-loop default and PortOS's merge-only policy
- 'claim-issue': 2, // v2: stop treating the bare `plan` label as a skip — `plan` is the claimable-queue label (do-replan --issues labels every migrated backlog item `plan`), so v1's exclusion emptied the whole actionable queue; now skip only true epics (`epic` label or "(epic)" title)
- 'claim-issue-gitlab': 1, // v1: GitLab sibling of claim-issue — same 7-phase /claim --issues flow over `glab` issues + merge requests. Reached via the claim-work router when an app's resolved workTracker is 'gitlab'.
+ 'claim-issue': 3, // v3: Phase 3 tags an ambiguous/too-large issue `needs-input` (not just a comment) so it's excluded from future autonomous claims — required for `perpetual` (drain-until-done) mode to converge instead of re-picking the same un-actionable issue. v2: stop treating the bare `plan` label as a skip — `plan` is the claimable-queue label (do-replan --issues labels every migrated backlog item `plan`), so v1's exclusion emptied the whole actionable queue; now skip only true epics (`epic` label or "(epic)" title)
+ 'claim-issue-gitlab': 2, // v2: Phase 3 tags an ambiguous/too-large issue `needs-input` (mirrors claim-issue v3) so it's excluded from future autonomous claims — required for `perpetual` (drain-until-done) mode to converge. v1: GitLab sibling of claim-issue — same 7-phase /claim --issues flow over `glab` issues + merge requests. Reached via the claim-work router when an app's resolved workTracker is 'gitlab'.
'claim-issue-jira': 1, // v1: JIRA sibling of claim-issue — claim ONE ready sprint ticket, move it To Do→In Progress→In Review around a self-managed worktree + MR/PR. Reached via the claim-work router when an app's resolved workTracker is 'jira' (replaces the prior jira→jira-sprint-manager route).
'pr-reviewer': 3, // v3: multi-stage pipeline (security scan → code review + merge)
'code-reviewer-a': 1, // v1: 2-stage pipeline (codebase review → triage & implement)
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index b384017884..3929d44c3f 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -11,6 +11,12 @@
* - 'once': Run once per app/globally then stop
* - 'on-demand': Only run when manually triggered
* - 'custom': Custom interval in milliseconds
+ * - 'cron': Cron expression schedule
+ * - 'perpetual': Drain actionable work back-to-back (re-queue on completion)
+ * until a programmatic work-detector reports nothing actionable, then PARK
+ * on a recheck cadence (`recheckCron` / `recheckIntervalMs`, default daily).
+ * See server/services/perpetualWork.js for the detector registry and the
+ * perpetual gate in cosTaskGenerator.generateManagedAppImprovementTaskForType.
*/
import { writeFile } from 'fs/promises';
@@ -61,11 +67,16 @@ export const INTERVAL_TYPES = {
ONCE: 'once', // Runs once per app or globally
ON_DEMAND: 'on-demand', // Only runs when manually triggered
CUSTOM: 'custom', // Custom interval in milliseconds
- CRON: 'cron' // Cron expression schedule
+ CRON: 'cron', // Cron expression schedule
+ PERPETUAL: 'perpetual' // Drain back-to-back until a work-detector idles, then park on a recheck cadence
};
const WEEK = 7 * DAY;
+// Default cadence a parked perpetual task waits before re-probing its
+// work-detector, when neither `recheckCron` nor `recheckIntervalMs` is set.
+const DEFAULT_PERPETUAL_RECHECK_MS = DAY;
+
/**
* Get learning-adjusted interval for a task type
*/
@@ -645,6 +656,88 @@ export async function getExecutionHistory(taskType) {
return schedule.executions[key] || { lastRun: null, count: 0, perApp: {} };
}
+// ============================================================
+// Perpetual (drain-until-done) park state
+// ============================================================
+
+/**
+ * Compute when a parked perpetual task should next re-probe its work-detector.
+ * Prefers `recheckCron` (a 5-field cron string, evaluated in the user's
+ * timezone) over `recheckIntervalMs`; falls back to DEFAULT_PERPETUAL_RECHECK_MS.
+ * Returns an ISO timestamp string.
+ */
+export async function computePerpetualRecheckAt(interval, fromMs = Date.now()) {
+ const cron = interval?.recheckCron;
+ if (typeof cron === 'string' && cron.trim().split(/\s+/).length === 5) {
+ const timezone = await getUserTimezone();
+ const next = parseCronToNextRun(cron, new Date(fromMs), timezone);
+ if (next) return next.toISOString();
+ }
+ const ms = Number(interval?.recheckIntervalMs) > 0
+ ? Number(interval.recheckIntervalMs)
+ : DEFAULT_PERPETUAL_RECHECK_MS;
+ return new Date(fromMs + ms).toISOString();
+}
+
+/**
+ * The park record lives ALONGSIDE the execution record (global or per-app), so a
+ * perpetual task's "parked until" survives restarts the same way `lastRun` does.
+ * Returns the execution sub-record that holds the park fields, creating the
+ * skeleton if absent.
+ */
+function ensureExecutionRecord(schedule, taskType, appId) {
+ const key = taskType.startsWith('task:') ? taskType : `task:${taskType}`;
+ if (!schedule.executions[key]) {
+ schedule.executions[key] = { lastRun: null, count: 0, perApp: {} };
+ }
+ const top = schedule.executions[key];
+ if (appId) {
+ if (!top.perApp) top.perApp = {};
+ if (!top.perApp[appId]) top.perApp[appId] = { lastRun: null, count: 0 };
+ return top.perApp[appId];
+ }
+ return top;
+}
+
+/**
+ * Park a perpetual task: its work-detector reported nothing actionable, so stop
+ * draining and wait until `parkedUntil` before re-probing. Stamps the park
+ * fields on the (per-app or global) execution record.
+ */
+export async function parkPerpetual(taskType, appId = null, { reason = null, actionableCount = 0 } = {}) {
+ const schedule = await loadSchedule();
+ const interval = schedule.tasks[taskType] || {};
+ const parkedUntil = await computePerpetualRecheckAt(interval);
+ const record = ensureExecutionRecord(schedule, taskType, appId);
+ record.parkedUntil = parkedUntil;
+ record.parkReason = reason;
+ record.parkActionableCount = actionableCount;
+ record.parkedAt = new Date().toISOString();
+ await saveSchedule(schedule);
+ emitLog('info', `Perpetual ${taskType} parked until ${parkedUntil} (${reason || 'idle'})`, { taskType, appId, parkedUntil }, '📅 TaskSchedule');
+ cosEvents.emit('schedule:perpetual-parked', { taskType, appId, parkedUntil, reason });
+ return record;
+}
+
+/**
+ * Clear a perpetual task's park so the drain resumes (its work-detector found
+ * actionable work). No-op (and no write) when there's nothing parked.
+ */
+export async function clearPerpetualPark(taskType, appId = null) {
+ const schedule = await loadSchedule();
+ const key = taskType.startsWith('task:') ? taskType : `task:${taskType}`;
+ const top = schedule.executions[key];
+ if (!top) return false;
+ const record = appId ? top.perApp?.[appId] : top;
+ if (!record || record.parkedUntil == null) return false;
+ delete record.parkedUntil;
+ delete record.parkReason;
+ delete record.parkActionableCount;
+ delete record.parkedAt;
+ await saveSchedule(schedule);
+ return true;
+}
+
/**
* Check if all runAfter dependencies have completed since this task's last run.
* Returns { satisfied, pending } where pending lists unfinished dependency task types.
@@ -858,6 +951,32 @@ export async function shouldRunTask(taskType, appId = null) {
break;
}
+ case INTERVAL_TYPES.PERPETUAL: {
+ // Drain-until-done: a perpetual task is "due" whenever it isn't parked.
+ // The actual programmatic work-detector runs at DISPATCH time (the gate in
+ // generateManagedAppImprovementTaskForType) and PARKS the task — writing
+ // `parkedUntil` onto the execution record — when nothing is actionable.
+ // shouldRunTask only reads that persisted park, so it never does network
+ // I/O even though it's called several times per evaluation cycle. While
+ // parked, the recheck cadence (parkedUntil) gates re-probing; once it
+ // elapses the task becomes due again and the gate re-runs the detector.
+ const parkedUntilMs = appExecution.parkedUntil
+ ? new Date(appExecution.parkedUntil).getTime()
+ : 0;
+ if (parkedUntilMs && now < parkedUntilMs) {
+ result = {
+ shouldRun: false,
+ reason: 'perpetual-parked',
+ nextRunAt: new Date(parkedUntilMs).toISOString(),
+ parkReason: appExecution.parkReason || null,
+ parkActionableCount: appExecution.parkActionableCount ?? null
+ };
+ } else {
+ result = { shouldRun: true, reason: parkedUntilMs ? 'perpetual-recheck' : 'perpetual-drain' };
+ }
+ break;
+ }
+
default:
result = { shouldRun: true, reason: 'unknown-default-rotation' };
}
@@ -910,6 +1029,17 @@ export async function getNextTaskType(appId = null, lastType = '') {
return { taskType: cronDue[0].taskType, reason: `${cronDue[0].interval.type}-due` };
}
+ // Perpetual tasks actively draining a backlog outrank the loose interval
+ // tasks (daily/weekly/once/rotation) so the drain keeps the app's single
+ // improvement slot until its work-detector idles and it parks — at which
+ // point the loose tasks below get their turn. (Explicit time-pinned cron/
+ // custom schedules above still win, so a perpetual drain can't starve a
+ // user-pinned 9 AM job.)
+ const perpetualDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.PERPETUAL);
+ if (perpetualDue.length > 0) {
+ return { taskType: perpetualDue[0].taskType, reason: 'perpetual-drain' };
+ }
+
const dailyDue = dueTasks.filter(t => t.interval.type === INTERVAL_TYPES.DAILY);
if (dailyDue.length > 0) {
return { taskType: dailyDue[0].taskType, reason: 'daily-priority' };
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 69cbe98495..6b20a5ddaf 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -92,6 +92,9 @@ import {
resetExecutionHistory,
triggerOnDemandTask,
getScheduleStatus,
+ computePerpetualRecheckAt,
+ parkPerpetual,
+ clearPerpetualPark,
PROMPT_VERSIONS,
DEFAULT_TASK_INTERVALS,
MANAGED_AGENT_OPTIONS,
@@ -149,6 +152,7 @@ describe('taskSchedule', () => {
expect(INTERVAL_TYPES.ON_DEMAND).toBe('on-demand')
expect(INTERVAL_TYPES.CUSTOM).toBe('custom')
expect(INTERVAL_TYPES.CRON).toBe('cron')
+ expect(INTERVAL_TYPES.PERPETUAL).toBe('perpetual')
})
})
@@ -1110,4 +1114,130 @@ describe('taskSchedule', () => {
expect(status.improvementEnabled).toBe(false)
})
})
+
+ describe('perpetual (drain-until-done)', () => {
+ describe('computePerpetualRecheckAt', () => {
+ it('uses recheckIntervalMs when no cron is set', async () => {
+ const at = await computePerpetualRecheckAt({ recheckIntervalMs: 3600000 }, 0)
+ expect(at).toBe(new Date(3600000).toISOString())
+ })
+
+ it('defaults to a daily (24h) recheck when nothing is configured', async () => {
+ const at = await computePerpetualRecheckAt({}, 0)
+ expect(at).toBe(new Date(24 * 60 * 60 * 1000).toISOString())
+ })
+
+ it('prefers a 5-field recheckCron over the interval', async () => {
+ const cronNext = new Date('2999-01-02T09:00:00.000Z')
+ parseCronToNextRun.mockReturnValue(cronNext)
+ const at = await computePerpetualRecheckAt({ recheckCron: '0 9 * * *', recheckIntervalMs: 1000 }, 0)
+ expect(at).toBe(cronNext.toISOString())
+ expect(parseCronToNextRun).toHaveBeenCalled()
+ })
+
+ it('falls back to the interval when recheckCron is not a 5-field expression', async () => {
+ const at = await computePerpetualRecheckAt({ recheckCron: 'not-a-cron', recheckIntervalMs: 5000 }, 0)
+ expect(at).toBe(new Date(5000).toISOString())
+ })
+ })
+
+ describe('shouldRunTask', () => {
+ it('is due (drain) when enabled and not parked', async () => {
+ mockSchedule({ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } } })
+ const result = await shouldRunTask('claim-issue')
+ expect(result.shouldRun).toBe(true)
+ expect(result.reason).toBe('perpetual-drain')
+ })
+
+ it('is NOT due while parked in the future', async () => {
+ const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
+ mockSchedule({
+ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: future, parkReason: 'no-actionable-issues', parkActionableCount: 0 } }
+ })
+ const result = await shouldRunTask('claim-issue')
+ expect(result.shouldRun).toBe(false)
+ expect(result.reason).toBe('perpetual-parked')
+ expect(result.nextRunAt).toBe(future)
+ expect(result.parkReason).toBe('no-actionable-issues')
+ })
+
+ it('becomes due again (recheck) once the park elapses', async () => {
+ const past = new Date(Date.now() - 60 * 1000).toISOString()
+ mockSchedule({
+ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: past } }
+ })
+ const result = await shouldRunTask('claim-issue')
+ expect(result.shouldRun).toBe(true)
+ expect(result.reason).toBe('perpetual-recheck')
+ })
+
+ it('reads per-app park state', async () => {
+ isTaskTypeEnabledForApp.mockResolvedValue(true)
+ const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
+ mockSchedule({
+ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, parkedUntil: future } } } }
+ })
+ const result = await shouldRunTask('claim-issue', 'app-1')
+ expect(result.shouldRun).toBe(false)
+ expect(result.reason).toBe('perpetual-parked')
+ })
+ })
+
+ describe('getNextTaskType', () => {
+ it('prioritizes a draining perpetual task over a due daily task', async () => {
+ mockSchedule({
+ tasks: {
+ 'claim-issue': { type: 'perpetual', enabled: true },
+ 'security': { type: 'daily', enabled: true }
+ }
+ })
+ const next = await getNextTaskType()
+ expect(next.taskType).toBe('claim-issue')
+ expect(next.reason).toBe('perpetual-drain')
+ })
+
+ it('does not pick a parked perpetual task — yields to the daily', async () => {
+ const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
+ mockSchedule({
+ tasks: {
+ 'claim-issue': { type: 'perpetual', enabled: true },
+ 'security': { type: 'daily', enabled: true }
+ },
+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {}, parkedUntil: future } }
+ })
+ const next = await getNextTaskType()
+ expect(next.taskType).toBe('security')
+ })
+ })
+
+ describe('parkPerpetual / clearPerpetualPark', () => {
+ it('parkPerpetual stamps parkedUntil + reason on the per-app record', async () => {
+ mockSchedule({ tasks: { 'claim-issue': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } } })
+ const record = await parkPerpetual('claim-issue', 'app-1', { reason: 'no-actionable-issues', actionableCount: 0 })
+ expect(record.parkedUntil).toBeTruthy()
+ expect(record.parkReason).toBe('no-actionable-issues')
+ expect(record.parkActionableCount).toBe(0)
+ })
+
+ it('clearPerpetualPark returns true when a park existed', async () => {
+ const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
+ mockSchedule({
+ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, parkedUntil: future } } } }
+ })
+ expect(await clearPerpetualPark('claim-issue', 'app-1')).toBe(true)
+ })
+
+ it('clearPerpetualPark is a no-op (false) when nothing is parked', async () => {
+ mockSchedule({
+ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {} } }
+ })
+ expect(await clearPerpetualPark('claim-issue', 'app-1')).toBe(false)
+ })
+ })
+ })
})