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
add per-app work tracker with claim-work single-source router
[._.]/ Adam Eivy0ef6303ab675
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5d66d8dc4a..727bbe673d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,8 @@- **[issue-1407] The LoRA-training form now exposes the per-run base-quant and low-RAM overrides.** The `baseQuant` (bf16 / 8-bit / 4-bit) and `lowRam` request params landed server-side under #1321 — schema, route threading, and the `LORA_TRAIN_MAX_QUANT_BITS` cap — but the training form had no controls for them, so opting a single run into a heavier or lighter frozen base than its memory-derived tier still meant a code change. The Train-LoRA panel now has two **Base quant** and **Low RAM spill** selects (both defaulting to **Auto**); an explicit pick overrides the tier — still clamped by the install's `LORA_TRAIN_MAX_QUANT_BITS` ceiling — while "Auto" sends an explicit `null` that forces the memory-derived tier. (The `null` is a deliberate clear, not an omitted key: the server re-merges `settings.loraTraining.defaults` into every run, so an omitted key would silently keep a *saved* default — `null` lets "Auto" actually beat one.) The controls only show when the mflux engine is the one that'll run; the torch/FLUX2 path trains the bf16 base and ignores them. (`client/src/components/loraTraining/TrainingPanel.jsx`, `server/lib/validation.js`, #1407)+- **Each managed app now declares where its autonomous work items live — PLAN.md, GitHub issues, GitLab issues, or JIRA.** Previously the CoS could only claim work from PLAN.md (`plan-task`) or GitHub issues (`claim-issue`) via separate per-app toggles. A new per-app **Work Tracker** setting (App settings → Edit) makes the work *source* a single explicit choice. It defaults to **Auto**, which resolves from the app's git `origin` host: a github.com remote → GitHub issues, a gitlab.* remote (incl. self-hosted) → GitLab issues, anything else → PLAN.md (JIRA is always an explicit opt-in). A new **`claim-work`** scheduled task is the single-source router: one toggle that, at dispatch, resolves the app's tracker and delegates to the matching claim flow — so the same agent still creates its own `claim/<slug>` worktree, opens its own PR/MR, and cleans up. **GitLab issue claiming is genuinely new**: a `claim-issue-gitlab` prompt drives the full 7-phase `/claim --issues` flow over `glab` issues + merge requests (the GitHub `claim-issue` flow is untouched). The legacy `plan-task` / `claim-issue` / `jira-sprint-manager` task types remain for backward compatibility. New `GET /api/apps/:id/work-tracker` resolves the effective tracker for the UI. (`server/lib/workTracker.js`, `server/services/{cosTaskGenerator,taskSchedule,apps}.js`, `server/services/taskPromptDefaults/prompts.js`, `server/routes/apps.js`, `client/src/components/apps/EditAppModal.jsx`)+- **CyberCity buildings now have real lit-room windows you can look into.** Online towers in the 3D city (CyberCity) render parallax interior-mapped window panes via the [three-fenestra](https://github.com/codedgar/three-fenestra) shader — a `MeshStandardMaterial` that fakes furnished 3D rooms behind flat glass, so as the camera moves you see *into* lit (and unlit) rooms rather than a flat emissive texture. Each building is a single instanced draw call: a deterministic per-pane seed drives the room-cell pick and per-window lit/unlit + warm/cool lighting entirely on the GPU, with the cool tone pulled toward the building's neon accent so windows stay in-family with the scene. The effect is night-only (by day a tower reads as a sunlit solid) and gated to the **high** quality preset and above, so medium/low machines keep the lighter flat-texture facade. (`client/src/components/city/BuildingWindows.jsx`, `client/src/utils/cityInteriorWindows.js`, `client/src/components/city/{Building,Borough}.jsx`)- **[issue-904] Generate N alternative image-gen prompts from one script fragment.** Comic panels and storyboard scenes already had an *"AI: refine"* button that rewrites a description in place into a single richer image-gen prompt. A new **"AI: N prompts"** action sits alongside it and instead generates several *candidate* prompts from the same fragment — non-destructively. A count picker (1–6) in each stage's toolbar controls how many; the candidates render in a list under the row where you can **Copy** any to the clipboard (to paste into Image Gen) or **Use** one to apply it to the description. Sampling variance across the independent LLM calls yields genuinely different takes on the same beat. Partial failure is tolerated — a few provider hiccups still return the survivors; only an all-failed batch errors. Reuses the existing `pipeline-comic-panel-image-prompt` / `pipeline-storyboard-image-prompt` stage templates (no prompt change, so no migration). New `POST .../panels/:i/image-prompts` and `.../scenes/:i/image-prompts` routes. (`server/services/pipeline/{visualStages,refineHelpers}.js`, `client/src/components/pipeline/{ImagePromptCandidates.jsx,stages/{ComicPagesStage,StoryboardsStage}.jsx}`, #904)diff --git a/client/src/components/UpcomingTasksWidget.jsx b/client/src/components/UpcomingTasksWidget.jsxindex b3a3b09a57..7f024ef0dd 100644--- a/client/src/components/UpcomingTasksWidget.jsx+++ b/client/src/components/UpcomingTasksWidget.jsx@@ -58,6 +58,7 @@ const UpcomingTasksWidget = memo(function UpcomingTasksWidget() {'feature-ideas': '💡','plan-task': '✅','claim-issue': '🎯',+ 'claim-work': '🎯','accessibility': '♿','dependency-updates': '📦','do-replan': '📋'diff --git a/client/src/components/apps/EditAppModal.jsx b/client/src/components/apps/EditAppModal.jsxindex cf151e601f..55409383f7 100644--- a/client/src/components/apps/EditAppModal.jsx+++ b/client/src/components/apps/EditAppModal.jsx@@ -9,6 +9,18 @@ import Modal from '../ui/Modal';import Banner from '../ui/Banner';import { copyToClipboard } from '../../lib/clipboard';+const WORK_TRACKER_OPTIONS = [+ { value: 'auto', label: 'Auto (detect from git origin)' },+ { value: 'plan', label: 'PLAN.md' },+ { value: 'github', label: 'GitHub Issues' },+ { value: 'gitlab', label: 'GitLab Issues' },+ { value: 'jira', label: 'JIRA' }+];++const WORK_TRACKER_LABELS = Object.fromEntries(+ WORK_TRACKER_OPTIONS.map(o => [o.value, o.label])+);+export default function EditAppModal({ app, onClose, onSave }) {const [formData, setFormData] = useState({name: app.name,@@ -22,6 +34,7 @@ export default function EditAppModal({ app, onClose, onSave }) {startCommands: (app.startCommands || []).join('\n'),pm2ProcessNames: (app.pm2ProcessNames || []).join(', '),editorCommand: app.editorCommand || 'code .',+ workTracker: app.workTracker || 'auto',defaultOpenPR: app.defaultOpenPR || false,defaultUseWorktree: app.defaultUseWorktree || app.defaultOpenPR || false,jiraEnabled: app.jira?.enabled || false,@@ -72,6 +85,7 @@ export default function EditAppModal({ app, onClose, onSave }) {setTlsUpgrading(false);}};+ const [workTrackerInfo, setWorkTrackerInfo] = useState(null);const [jiraExpanded, setJiraExpanded] = useState(app.jira?.enabled || false);const [jiraInstances, setJiraInstances] = useState([]);const [datadogExpanded, setDatadogExpanded] = useState(app.datadog?.enabled || false);@@ -92,6 +106,12 @@ export default function EditAppModal({ app, onClose, onSave }) {});}, []);+ useEffect(() => {+ api.getAppWorkTracker(app.id)+ .then(setWorkTrackerInfo)+ .catch(() => setWorkTrackerInfo(null));+ }, [app.id]);+useEffect(() => {if (!formData.jiraInstanceId) {setJiraProjects([]);@@ -130,6 +150,7 @@ export default function EditAppModal({ app, onClose, onSave }) {? formData.pm2ProcessNames.split(',').map(s => s.trim()).filter(Boolean): undefined,editorCommand: formData.editorCommand || undefined,+ workTracker: formData.workTracker || 'auto',defaultUseWorktree: formData.defaultUseWorktree || formData.defaultOpenPR,defaultOpenPR: formData.defaultOpenPR,jira: formData.jiraEnabled ? {@@ -349,6 +370,31 @@ export default function EditAppModal({ app, onClose, onSave }) {/></div>+ <div>+ <label htmlFor="edit-app-work-tracker" className="block text-sm text-gray-400 mb-1">Work Tracker</label>+ <select+ id="edit-app-work-tracker"+ value={formData.workTracker}+ onChange={e => setFormData(prev => ({ ...prev, workTracker: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"+ >+ {WORK_TRACKER_OPTIONS.map(opt => (+ <option key={opt.value} value={opt.value}>{opt.label}</option>+ ))}+ </select>+ {workTrackerInfo && (() => {+ const isAuto = formData.workTracker === 'auto';+ const tracker = isAuto ? workTrackerInfo.resolved : formData.workTracker;+ const label = WORK_TRACKER_LABELS[tracker] || tracker;+ const host = workTrackerInfo.host;+ return (+ <p className="text-xs text-gray-500 mt-1">+ {isAuto ? 'Auto → ' : 'Resolved: '}{label}{host ? ` (origin: ${host})` : ''}+ </p>+ );+ })()}+ </div>+<label className="flex items-center gap-2 cursor-pointer"><inputtype="checkbox"diff --git a/client/src/components/apps/EditAppModal.test.jsx b/client/src/components/apps/EditAppModal.test.jsxnew file mode 100644index 0000000000..2392fce9b5--- /dev/null+++ b/client/src/components/apps/EditAppModal.test.jsx@@ -0,0 +1,85 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';++// Mock the API surface EditAppModal touches on mount, plus the work-tracker+// resolver and the update path used on save.+vi.mock('../../services/api', () => ({+ getJiraInstances: vi.fn(),+ getDatadogInstances: vi.fn(),+ getJiraProjects: vi.fn(),+ getAppWorkTracker: vi.fn(),+ updateApp: vi.fn(),+ upgradeAppTls: vi.fn(),+}));++// react-router-dom <Link> is rendered inside the JIRA section.+vi.mock('react-router-dom', () => ({+ Link: ({ children, ...rest }) => <a {...rest}>{children}</a>,+}));++import * as api from '../../services/api';+import EditAppModal from './EditAppModal';++const APP = {+ id: 'app-1',+ name: 'My App',+ repoPath: '/repo',+ workTracker: 'auto',+};++beforeEach(() => {+ api.getJiraInstances.mockResolvedValue({ instances: {} });+ api.getDatadogInstances.mockResolvedValue({ instances: {} });+ api.getJiraProjects.mockResolvedValue([]);+ api.getAppWorkTracker.mockResolvedValue({+ configured: 'auto',+ resolved: 'github',+ host: 'github.com',+ forge: 'gh',+ source: 'origin',+ });+ api.updateApp.mockResolvedValue({});+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe('EditAppModal work tracker selector', () => {+ it('renders a labeled select with the five tracker options', async () => {+ render(<EditAppModal app={APP} onClose={() => {}} onSave={() => {}} />);++ const select = await screen.findByLabelText('Work Tracker');+ expect(select).toBeInTheDocument();+ expect(select).toHaveValue('auto');++ const optionValues = Array.from(select.querySelectorAll('option')).map(o => o.value);+ expect(optionValues).toEqual(['auto', 'plan', 'github', 'gitlab', 'jira']);+ });++ it('shows the resolved auto target from the work-tracker endpoint', async () => {+ render(<EditAppModal app={APP} onClose={() => {}} onSave={() => {}} />);++ await screen.findByLabelText('Work Tracker');+ expect(api.getAppWorkTracker).toHaveBeenCalledWith('app-1');+ await waitFor(() =>+ expect(screen.getByText(/Auto → GitHub Issues \(origin: github\.com\)/)).toBeInTheDocument()+ );+ });++ it('updates the selection locally and includes workTracker in the save payload', async () => {+ render(<EditAppModal app={APP} onClose={() => {}} onSave={() => {}} />);++ const select = await screen.findByLabelText('Work Tracker');+ fireEvent.change(select, { target: { value: 'gitlab' } });+ expect(select).toHaveValue('gitlab');++ fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));++ await waitFor(() => expect(api.updateApp).toHaveBeenCalled());+ const [id, payload] = api.updateApp.mock.calls[0];+ expect(id).toBe('app-1');+ expect(payload.workTracker).toBe('gitlab');+ });+});diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 5a24699400..f15e54a32d 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -94,6 +94,12 @@ export const ISSUE_AUTHOR_FILTER_OPTIONS = [{ value: 'any', label: 'Any author', description: 'Claim the next eligible open issue regardless of who filed it' }];+// Task types that claim from a forge issue tracker and therefore expose the+// issueAuthorFilter control. `claim-work` resolves to a concrete claim flow+// (github/gitlab) at dispatch but configures the filter here too. Add any new+// issue-claiming task type here rather than OR-ing literals across components.+export const ISSUE_AUTHOR_FILTER_TASK_TYPES = new Set(['claim-issue', 'claim-work']);+export const DEFAULT_REVIEWER = 'copilot';export const DEFAULT_REVIEWERS = ['copilot'];diff --git a/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx b/client/src/components/cos/tabs/schedule/AppOverrideRow.jsxindex 36156b897f..ec4335fee4 100644--- a/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx+++ b/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx@@ -1,7 +1,7 @@import { useState, memo } from 'react';import AppIcon from '../../../AppIcon';import CronInput from '../../../CronInput';-import { AGENT_OPTIONS, ISSUE_AUTHOR_FILTER_OPTIONS, toggleAppMetadataOverride, agentOptionButtonClass } from '../../constants';+import { AGENT_OPTIONS, ISSUE_AUTHOR_FILTER_OPTIONS, ISSUE_AUTHOR_FILTER_TASK_TYPES, toggleAppMetadataOverride, agentOptionButtonClass } from '../../constants';import { isCronExpression, describeCron } from '../../../../utils/cronHelpers';import ToggleSwitch from '../../../ToggleSwitch';import { INTERVAL_LABELS } from './scheduleConstants';@@ -133,7 +133,7 @@ const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalInter})}</div>- {taskType === 'claim-issue' && (+ {ISSUE_AUTHOR_FILTER_TASK_TYPES.has(taskType) && (<selectvalue={override?.taskMetadata?.issueAuthorFilter || ''}onChange={(e) => handleIssueAuthorFilterChange(e.target.value)}diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsxindex 9752273298..6534176266 100644--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx@@ -1,7 +1,7 @@import { useState, useEffect, useRef } from 'react';import { Play, RotateCcw, ChevronDown, AlertCircle, Package, Info } from 'lucide-react';import CronInput from '../../../CronInput';-import { AGENT_OPTIONS, DEFAULT_REVIEW_STOP_MODE, PR_AUTHOR_FILTER_OPTIONS, ISSUE_AUTHOR_FILTER_OPTIONS } from '../../constants';+import { AGENT_OPTIONS, DEFAULT_REVIEW_STOP_MODE, PR_AUTHOR_FILTER_OPTIONS, ISSUE_AUTHOR_FILTER_OPTIONS, ISSUE_AUTHOR_FILTER_TASK_TYPES } from '../../constants';import ReviewerPicker from '../../ReviewerPicker';import Banner from '../../../ui/Banner';import { useCodeReviewDefaults } from '../../../../hooks/useCodeReviewDefaults';@@ -248,7 +248,7 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri</div>)}- {taskType === 'claim-issue' && (+ {ISSUE_AUTHOR_FILTER_TASK_TYPES.has(taskType) && (<div><label htmlFor={`issue-author-filter-${taskType}`} className="text-sm text-gray-400 block mb-2">Issue Author Filter</label><selectdiff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex 8994d79531..bbcfd23c7b 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -4,6 +4,11 @@ import { request, API_BASE } from './apiCore.js';// Appsexport const getApps = (options) => request('/apps', options);export const getApp = (id) => request(`/apps/${id}`);+// Resolves what the app's `workTracker` field ('auto' or explicit) actually+// points to: { configured, resolved, host, forge, source }. Read-only — the+// caller (EditAppModal) owns its own .catch fallback, so default to silent.+export const getAppWorkTracker = (id, options) =>+ request(`/apps/${id}/work-tracker`, { silent: true, ...options });export const createApp = (data) => request('/apps', {method: 'POST',body: JSON.stringify(data)diff --git a/server/lib/README.md b/server/lib/README.mdindex 8ed7f5b7cd..cd4a77b0a8 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -227,6 +227,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. || `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). || `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |+| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `forgeCliForTracker`, `trackerToClaimTaskType`, pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Consumed by the `claim-work` router in `cosTaskGenerator.js` and `routes/apps.js`. || `workspaceRoots.js` | Shared allow-list for routes that take a caller-supplied filesystem path. `ALLOWED_WORKSPACE_ROOTS` (defaults + `PORTOS_WORKSPACE_ROOTS`, symlink-resolved), `isWithinRoot(resolvedPath, root)` (separator-safe containment), `isWithinAllowedRoots(realPath)`, and `WORKSPACE_ROOTS_CONFIGURED` (true when the operator set the env var — lets a permissive-by-default route like `routes/detect.js` opt into confinement). Used by `routes/commands.js` (always scoped) and `routes/detect.js` (scoped only when configured). || `zodCompat.js` | Zod 4 compatibility helpers. `partialWithoutDefaults(objectSchema)` — like `.partial()` but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. |diff --git a/server/lib/index.js b/server/lib/index.jsindex ff39a0cc3c..ec8d46af3a 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -197,6 +197,7 @@ export * from './singleFlight.js';export * from './streamBackpressure.js';export * from './sseUtils.js';export * from './uuid.js';+export * from './workTracker.js';export * from './workspaceRoots.js';export * from './zodCompat.js';diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 9453616fda..6970ba1a8f 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -6,6 +6,7 @@ import { ALL_STYLE_IDS, STYLE_ID } from './writersRoomStylePresets.js';import { BIBLE_LIMITS, RELATIONSHIP_LINK_TYPES, RELATIONSHIP_OPPOSITION_AXES, ATTACHMENT_ROLES } from './storyBible.js';import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from './aiToolkit/constants.js';import { CHECK_SCOPES, CHECK_SEVERITIES } from './editorial/checkRegistry.js';+import { WORK_TRACKERS } from './workTracker.js';// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total// pixels. Mirror the ceiling for every image-gen route. Local mflux can@@ -290,7 +291,13 @@ export const appSchema = z.object({defaultUseWorktree: z.boolean().optional(),defaultOpenPR: z.boolean().optional(),jira: jiraConfigSchema.optional().nullable(),- datadog: datadogConfigSchema.optional().nullable()+ datadog: datadogConfigSchema.optional().nullable(),+ // Where this app's autonomous work items live (single source per app).+ // 'auto' (default) resolves to a concrete tracker from the git origin host+ // — see server/lib/workTracker.js + the `claim-work` router in+ // cosTaskGenerator.js. WORK_TRACKERS is the single source of truth for the+ // value set.+ workTracker: z.enum(WORK_TRACKERS).optional()// referenceRepos is INTENTIONALLY not part of the create/update API// surface. createApp() doesn't persist it and updateApp() (via the// omit() in appUpdateSchema) ignores it — the dedicateddiff --git a/server/lib/workTracker.js b/server/lib/workTracker.jsnew file mode 100644index 0000000000..e894e64bca--- /dev/null+++ b/server/lib/workTracker.js@@ -0,0 +1,120 @@+// Per-app "work tracker" resolution — where a managed app's autonomous work+// items live: PLAN.md, a GitHub issue tracker, a GitLab issue tracker, or JIRA.+//+// Each managed app carries a `workTracker` field (default `'auto'`). `'auto'`+// resolves to a concrete tracker from the app's git `origin` host: a github.com+// remote → GitHub issues, a gitlab.* remote → GitLab issues, anything else (or+// no remote) → PLAN.md. JIRA is never auto-selected — it requires explicit+// per-app JIRA config (`app.jira`) — so a user picks it deliberately.+//+// The pure mappers (hostToWorkTracker / forgeCliForTracker / trackerToClaimTaskType+// / resolveWorkTracker) are side-effect-free and unit-tested. resolveAppWorkTracker+// is the async wrapper that reads the app's origin host via getOriginInfo — it+// shells out to git, mirroring gitRemote.js (which also lives in lib/ despite+// running `git`). See server/services/cosTaskGenerator.js for the claim-work+// router that consumes trackerToClaimTaskType.++import { getOriginInfo } from './gitRemote.js';++// Every selectable value (UI + Zod enum). `'auto'` is the default; the rest are+// concrete sources.+export const WORK_TRACKERS = ['auto', 'plan', 'github', 'gitlab', 'jira'];++// The concrete sources `'auto'` can resolve to (i.e. WORK_TRACKERS minus auto).+export const CONCRETE_WORK_TRACKERS = WORK_TRACKERS.filter(t => t !== 'auto');++export const DEFAULT_WORK_TRACKER = 'auto';++const TRACKER_LABELS = {+ auto: 'Auto (detect from git origin)',+ plan: 'PLAN.md',+ github: 'GitHub Issues',+ gitlab: 'GitLab Issues',+ jira: 'JIRA',+};++/** Human-readable label for a tracker value (falls back to the raw value). */+export function workTrackerLabel(tracker) {+ return TRACKER_LABELS[tracker] || tracker;+}++/**+ * Map a git remote host to its concrete forge work tracker, or null when the+ * host isn't a recognized forge (so the caller falls back to PLAN.md). Mirrors+ * the host classification in gitForge.detectForgeCli — covers github.com /+ * gitlab.com plus self-hosted enterprise hosts (github.*, gitlab.*).+ */+export function hostToWorkTracker(host) {+ if (!host || typeof host !== 'string') return null;+ const h = host.toLowerCase();+ if (h === 'github.com' || /(^|\.)github\./.test(h)) return 'github';+ if (h === 'gitlab.com' || /(^|\.)gitlab\./.test(h)) return 'gitlab';+ return null;+}++/**+ * Which forge CLI a concrete tracker drives: github → `gh`, gitlab → `glab`.+ * PLAN.md and JIRA have no forge CLI, so they return null.+ */+export function forgeCliForTracker(tracker) {+ if (tracker === 'github') return 'gh';+ if (tracker === 'gitlab') return 'glab';+ return null;+}++/**+ * The CoS claim task type that ships work from a concrete tracker. The+ * claim-work router (cosTaskGenerator) delegates to one of these prompt bodies+ * after resolving the app's tracker:+ * plan → plan-task (PLAN.md flow)+ * github → claim-issue (gh issue flow)+ * gitlab → claim-issue-gitlab (glab issue flow)+ * jira → jira-sprint-manager (JIRA flow)+ * Returns null for an unknown tracker.+ */+export function trackerToClaimTaskType(tracker) {+ switch (tracker) {+ case 'plan': return 'plan-task';+ case 'github': return 'claim-issue';+ case 'gitlab': return 'claim-issue-gitlab';+ case 'jira': return 'jira-sprint-manager';+ default: return null;+ }+}++/**+ * Pure resolution: given a configured `workTracker` value (possibly `'auto'`,+ * undefined, or junk) and a known origin `host`, produce the concrete tracker.+ *+ * Returns `{ configured, resolved, source }`:+ * - configured: the normalized stored value ('auto' for absent/invalid)+ * - resolved: the concrete tracker ('plan' | 'github' | 'gitlab' | 'jira')+ * - source: 'configured' (explicit choice), 'origin' (auto → host), or+ * 'fallback' (auto with no recognizable forge host → PLAN.md)+ */+export function resolveWorkTracker({ configured, host } = {}) {+ const value = CONCRETE_WORK_TRACKERS.includes(configured) ? configured : 'auto';+ if (value !== 'auto') {+ return { configured: value, resolved: value, source: 'configured' };+ }+ const fromHost = hostToWorkTracker(host);+ if (fromHost) return { configured: 'auto', resolved: fromHost, source: 'origin' };+ return { configured: 'auto', resolved: 'plan', source: 'fallback' };+}++/**+ * Resolve a managed app's effective work tracker, reading its git origin host+ * when needed. Returns `{ configured, resolved, host, forge, source }` where+ * `forge` is the CLI ('gh' | 'glab' | null) for the resolved tracker. Never+ * throws — a missing repo / origin degrades to host=null (→ PLAN.md fallback).+ */+export async function resolveAppWorkTracker(app) {+ const configured = app?.workTracker;+ let host = null;+ if (app?.repoPath) {+ const info = await getOriginInfo(app.repoPath).catch(() => null);+ host = info?.host || null;+ }+ const base = resolveWorkTracker({ configured, host });+ return { ...base, host, forge: forgeCliForTracker(base.resolved) };+}diff --git a/server/lib/workTracker.test.js b/server/lib/workTracker.test.jsnew file mode 100644index 0000000000..95d8bc5c8a--- /dev/null+++ b/server/lib/workTracker.test.js@@ -0,0 +1,100 @@+import { describe, it, expect } from 'vitest';+import {+ WORK_TRACKERS,+ CONCRETE_WORK_TRACKERS,+ DEFAULT_WORK_TRACKER,+ workTrackerLabel,+ hostToWorkTracker,+ forgeCliForTracker,+ trackerToClaimTaskType,+ resolveWorkTracker,+} from './workTracker.js';++describe('workTracker constants', () => {+ it('auto is the default and the only non-concrete value', () => {+ expect(DEFAULT_WORK_TRACKER).toBe('auto');+ expect(WORK_TRACKERS).toContain('auto');+ expect(CONCRETE_WORK_TRACKERS).not.toContain('auto');+ expect(WORK_TRACKERS).toEqual(['auto', ...CONCRETE_WORK_TRACKERS]);+ });+});++describe('hostToWorkTracker', () => {+ it('maps github hosts (incl. enterprise) to github', () => {+ expect(hostToWorkTracker('github.com')).toBe('github');+ expect(hostToWorkTracker('GitHub.com')).toBe('github');+ expect(hostToWorkTracker('github.mycorp.com')).toBe('github');+ });+ it('maps gitlab hosts (incl. self-hosted) to gitlab', () => {+ expect(hostToWorkTracker('gitlab.com')).toBe('gitlab');+ expect(hostToWorkTracker('gitlab.example.com')).toBe('gitlab');+ });+ it('returns null for unknown / empty hosts', () => {+ expect(hostToWorkTracker('bitbucket.org')).toBeNull();+ expect(hostToWorkTracker('')).toBeNull();+ expect(hostToWorkTracker(null)).toBeNull();+ expect(hostToWorkTracker(undefined)).toBeNull();+ });+});++describe('forgeCliForTracker', () => {+ it('maps forge trackers to their CLI, others to null', () => {+ expect(forgeCliForTracker('github')).toBe('gh');+ expect(forgeCliForTracker('gitlab')).toBe('glab');+ expect(forgeCliForTracker('plan')).toBeNull();+ expect(forgeCliForTracker('jira')).toBeNull();+ expect(forgeCliForTracker('auto')).toBeNull();+ });+});++describe('trackerToClaimTaskType', () => {+ it('routes each concrete tracker to its claim prompt task type', () => {+ expect(trackerToClaimTaskType('plan')).toBe('plan-task');+ expect(trackerToClaimTaskType('github')).toBe('claim-issue');+ expect(trackerToClaimTaskType('gitlab')).toBe('claim-issue-gitlab');+ expect(trackerToClaimTaskType('jira')).toBe('jira-sprint-manager');+ expect(trackerToClaimTaskType('auto')).toBeNull();+ expect(trackerToClaimTaskType('nonsense')).toBeNull();+ });+});++describe('resolveWorkTracker (pure)', () => {+ it('honors an explicit concrete choice regardless of host', () => {+ expect(resolveWorkTracker({ configured: 'jira', host: 'github.com' }))+ .toEqual({ configured: 'jira', resolved: 'jira', source: 'configured' });+ expect(resolveWorkTracker({ configured: 'plan', host: 'gitlab.com' }))+ .toEqual({ configured: 'plan', resolved: 'plan', source: 'configured' });+ });++ it('auto resolves from the origin host', () => {+ expect(resolveWorkTracker({ configured: 'auto', host: 'github.com' }))+ .toEqual({ configured: 'auto', resolved: 'github', source: 'origin' });+ expect(resolveWorkTracker({ configured: 'auto', host: 'gitlab.example.com' }))+ .toEqual({ configured: 'auto', resolved: 'gitlab', source: 'origin' });+ });++ it('auto with an unrecognized / missing host falls back to PLAN.md', () => {+ expect(resolveWorkTracker({ configured: 'auto', host: 'bitbucket.org' }))+ .toEqual({ configured: 'auto', resolved: 'plan', source: 'fallback' });+ expect(resolveWorkTracker({ configured: 'auto', host: null }))+ .toEqual({ configured: 'auto', resolved: 'plan', source: 'fallback' });+ });++ it('treats absent / invalid configured values as auto', () => {+ expect(resolveWorkTracker({ host: 'github.com' }).resolved).toBe('github');+ expect(resolveWorkTracker({ configured: 'garbage', host: 'gitlab.com' }))+ .toEqual({ configured: 'auto', resolved: 'gitlab', source: 'origin' });+ expect(resolveWorkTracker({}).resolved).toBe('plan');+ });+});++describe('workTrackerLabel', () => {+ it('returns a human label for every value, falling back to the raw value', () => {+ for (const t of WORK_TRACKERS) {+ expect(typeof workTrackerLabel(t)).toBe('string');+ expect(workTrackerLabel(t).length).toBeGreaterThan(0);+ }+ expect(workTrackerLabel('github')).toBe('GitHub Issues');+ expect(workTrackerLabel('unmapped-value')).toBe('unmapped-value');+ });+});diff --git a/server/routes/apps.js b/server/routes/apps.jsindex 617a46225d..4c89c99732 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -492,6 +492,16 @@ router.get('/:id/task-types', loadApp, asyncHandler(async (req, res) => {res.json({ appId: app.id, appName: app.name, taskTypeOverrides: overrides });}));+// GET /api/apps/:id/work-tracker - Resolve where this app's autonomous work+// items live (PLAN.md / GitHub / GitLab / JIRA). 'auto' resolves from the git+// origin host; see server/lib/workTracker.js. Read-only — the value itself is+// saved through the generic PUT /api/apps/:id (appUpdateSchema.workTracker).+router.get('/:id/work-tracker', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const info = await appsService.getAppWorkTracker(app.id);+ res.json({ appId: app.id, appName: app.name, ...info });+}));+// PUT /api/apps/:id/task-types/all - Toggle all task types for an approuter.put('/:id/task-types/all', loadApp, asyncHandler(async (req, res) => {const { enabled } = req.body;diff --git a/server/services/apps.js b/server/services/apps.jsindex bcb4657e34..ee0f1ff6b4 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -6,6 +6,7 @@ import { NON_PM2_TYPES, usesPm2 } from './streamingDetect.js';import { listProcessesStrict } from './pm2.js';import { SELF_IMPROVEMENT_TASK_TYPES } from './taskSchedule.js';import { sanitizeTaskMetadata } from '../lib/validation.js';+import { resolveAppWorkTracker } from '../lib/workTracker.js';import { PORTS } from '../lib/ports.js';import { hasTailscaleCert } from '../../lib/tailscale-https.js';import { certPaths } from '../../lib/certPaths.js';@@ -312,6 +313,10 @@ export async function createApp(appData) {|| (NON_PM2_TYPES.has(appData.type) && process.platform === 'darwin' ? 'xed .' : 'code .'),archived: false,jira: appData.jira || null,+ // Where this app's autonomous work items live. 'auto' resolves to a+ // concrete tracker (PLAN.md / GitHub / GitLab / JIRA) from the git origin+ // host at dispatch time — see server/lib/workTracker.js.+ workTracker: appData.workTracker || 'auto',taskTypeOverrides: Object.fromEntries(SELF_IMPROVEMENT_TASK_TYPES.map(t => [t, { enabled: false }])),@@ -405,6 +410,17 @@ async function migrateTaskTypeOverrides(id) {console.log(`📋 Migrated ${id} from disabledTaskTypes to taskTypeOverrides`);}+/**+ * Resolve an app's effective work tracker (the single source its `claim-work`+ * task ships from). Returns `{ configured, resolved, host, forge, source }`;+ * see resolveAppWorkTracker. Returns null when the app id is unknown.+ */+export async function getAppWorkTracker(id) {+ const app = await getAppById(id);+ if (!app) return null;+ return resolveAppWorkTracker(app);+}+/*** Get task type overrides for an app*/diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 0c91f9f63a..f6e9c9ceb1 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -1274,9 +1274,28 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stinitializePipelineMetadata(metadata);if (!skipPreconditions && shouldSkipForPrecondition(metadata, app, taskType)) return null;+ // claim-work is the single-source router: one toggle that ships the next+ // work item from whatever tracker the app is configured for. Resolve+ // the app's workTracker (default 'auto' → git origin host) and delegate to the+ // concrete claim flow's prompt body. `taskType` stays 'claim-work' for+ // interval/cadence/recording; `promptTaskType` drives prompt selection, PLAN+ // gating, and the forge-specific author-filter directive below.+ let promptTaskType = taskType;+ if (taskType === 'claim-work') {+ const { resolveAppWorkTracker, trackerToClaimTaskType } = await import('../lib/workTracker.js');+ const wt = await resolveAppWorkTracker(app);+ promptTaskType = trackerToClaimTaskType(wt.resolved) || 'plan-task';+ emitLog('info', `claim-work for ${app.name}: tracker=${wt.resolved} (${wt.source}) → ${promptTaskType}`, { appId: app.id, analysisType: taskType });+ }+ // Honor a direct claim-work prompt customization if the user set one;+ // otherwise delegate to the resolved tracker's (possibly itself customized)+ // prompt body. getTaskPrompt(promptTaskType) reads THAT type's interval.prompt+ // override, so a user's claim-issue/plan-task customization flows through too.+ const promptKeyForBody = (taskType === 'claim-work' && !interval.prompt) ? promptTaskType : taskType;+const promptTemplate = metadata.pipeline?.stages? await getStagePrompt(taskType, 0)- : await getTaskPrompt(taskType);+ : await getTaskPrompt(promptKeyForBody);// reference-watch: dynamically inject {referenceData} — a Markdown chunk// describing each ref configured on the app + commits since lastReviewedSha.@@ -1378,7 +1397,10 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stemitLog('info', `pr-watcher dispatching for ${app.name}: ${check.newPrs.length} new PR(s)`, { appId: app.id, analysisType: taskType });}- const planMeta = await applyPlanIdMetadata(taskType, app.repoPath, metadata);+ // Gate on PLAN.md using the RESOLVED type so a claim-work run routed to the+ // PLAN.md flow still skips cleanly on an empty/all-in-flight queue. For+ // standalone tasks promptTaskType === taskType, so behavior is unchanged.+ const planMeta = await applyPlanIdMetadata(promptTaskType, app.repoPath, metadata);if (planMeta.skipReason) {emitLog('info', `Skipping ${taskType} for ${app.name}: ${planMeta.skipReason}`, { appId: app.id });return null;@@ -1407,9 +1429,27 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st// (global → per-app override) and value-constrained by sanitizeTaskMetadata,// so read it from `metadata`. 'owner' (the default, matching /claim --issues)// restricts to repo-owner-filed issues; 'any' claims any open issue.- const issueAuthorFilterBlock = (metadata.issueAuthorFilter || 'owner') === 'any'- ? '**Author filter: any author.** Claim the next eligible open issue regardless of who filed it — omit `--author` from `gh issue list` entirely.'- : '**Author filter: repository owner only.** Only claim issues filed by the repository owner/creator. Resolve the owner with `OWNER="$(gh repo view --json owner -q .owner.login)"` and pass `--author "$OWNER"` (a quoted single token) to `gh issue list`; skip issues opened by anyone else.';+ // The forge whose CLI the resolved prompt body documents — `glab` for the+ // GitLab claim flow, `gh` for the GitHub one, null for plan/jira (whose+ // prompts carry no {issueAuthorFilter} placeholder, so the replace is a+ // harmless no-op there).+ const issueForge = promptTaskType === 'claim-issue-gitlab' ? 'glab'+ : promptTaskType === 'claim-issue' ? 'gh'+ : null;+ const authorFilterMode = (metadata.issueAuthorFilter || 'owner') === 'any' ? 'any' : 'owner';+ const ISSUE_AUTHOR_FILTER_BLOCKS = {+ gh: {+ any: '**Author filter: any author.** Claim the next eligible open issue regardless of who filed it — omit `--author` from `gh issue list` entirely.',+ owner: '**Author filter: repository owner only.** Only claim issues filed by the repository owner/creator. Resolve the owner with `OWNER="$(gh repo view --json owner -q .owner.login)"` and pass `--author "$OWNER"` (a quoted single token) to `gh issue list`; skip issues opened by anyone else.'+ },+ glab: {+ any: '**Author filter: any author.** Claim the next eligible open issue regardless of who opened it — omit `--author` from `glab issue list`.',+ owner: '**Author filter: project owner only.** Only claim issues opened by the project owner. Resolve the owner from the project namespace (e.g. `glab repo view`), then pass `--author <owner>` to `glab issue list`; skip issues opened by anyone else.'+ }+ };+ // Default to the gh block for plan/jira (null forge) — their prompts have no+ // {issueAuthorFilter} placeholder so the value is never substituted anyway.+ const issueAuthorFilterBlock = (ISSUE_AUTHOR_FILTER_BLOCKS[issueForge] || ISSUE_AUTHOR_FILTER_BLOCKS.gh)[authorFilterMode];const description = promptTemplate.replace(/\{appName\}/g, app.name)diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex 78c5be42cc..b03a2f2090 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -78,6 +78,40 @@ describe('{reviewers} interpolation honors Code Review Defaults', () => {});});+// claim-work is the single-source router: one toggle that resolves the app's+// workTracker (default 'auto' → git origin host) and delegates to the matching+// claim prompt body — plan→plan-task, github→claim-issue, gitlab→claim-issue-gitlab,+// jira→jira-sprint-manager. These source-level guards pin that wiring so a+// future edit can't silently drop the resolution, the delegated prompt+// selection, the PLAN gate routing, or the GitLab forge directive.+describe('claim-work single-source routing', () => {+ it('resolves the app work tracker and maps it to a concrete claim task type', () => {+ expect(GEN_SRC).toContain("taskType === 'claim-work'");+ expect(GEN_SRC).toContain('resolveAppWorkTracker, trackerToClaimTaskType');+ // Pin the call shape without coupling to the local variable name.+ expect(GEN_SRC).toMatch(/trackerToClaimTaskType\(\w+\.resolved\)/);+ });++ it('selects the delegated prompt body (promptTaskType), honoring a direct claim-work customization', () => {+ expect(GEN_SRC).toContain('promptKeyForBody');+ expect(GEN_SRC).toContain('await getTaskPrompt(promptKeyForBody)');+ // A claim-work customization (interval.prompt) wins; otherwise delegate.+ expect(GEN_SRC).toMatch(/promptKeyForBody\s*=\s*\(taskType === 'claim-work' && !interval\.prompt\)\s*\?\s*promptTaskType\s*:\s*taskType/);+ });++ it('gates PLAN.md on the RESOLVED type so a claim-work→plan run still skips an empty queue', () => {+ expect(GEN_SRC).toContain('applyPlanIdMetadata(promptTaskType,');+ // The only other occurrence is the function definition's parameter list;+ // the CALL must route the resolved type, never the raw 'claim-work' type.+ expect(GEN_SRC).not.toContain('await applyPlanIdMetadata(taskType,');+ });++ it('emits a GitLab (glab) author-filter directive for the claim-issue-gitlab body', () => {+ expect(GEN_SRC).toContain("promptTaskType === 'claim-issue-gitlab' ? 'glab'");+ expect(GEN_SRC).toContain('glab issue list');+ });+});+describe('exceedsMaxSpawns', () => {it('is false below the ceiling and true at/above it — no mutation', () => {expect(exceedsMaxSpawns(task('a', { totalSpawnCount: 0 }))).toBe(false);diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.jsonindex a043aed57b..0a11204f8f 100644--- a/server/services/taskPromptDefaults/integrity.snapshot.json+++ b/server/services/taskPromptDefaults/integrity.snapshot.json@@ -13,6 +13,7 @@"feature-ideas": "0741418bd275b8953131155f8bc89460","plan-task": "5425306bf082b15b6a17f972557d4dd9","claim-issue": "28f09436566c281a6915d6ad4c1b80f8",+ "claim-issue-gitlab": "b8480ab0196aacac5d7ecc149d937b2a","code-reviewer-review": "1cd13ee5142d130f95cc390098d0f278","code-reviewer-implement": "ab2c3e16d54e195bdf856574b7702042","error-handling": "9afba2e99b90a8d5771c75e7f0615d96",@@ -33,6 +34,7 @@"feature-ideas": 9,"plan-task": 8,"claim-issue": 2,+ "claim-issue-gitlab": 1,"pr-reviewer": 3,"code-reviewer-a": 1,"code-reviewer-b": 1,diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.jsindex 40d885537e..a2882542b2 100644--- a/server/services/taskPromptDefaults/prompts.js+++ b/server/services/taskPromptDefaults/prompts.js@@ -605,6 +605,126 @@ 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.`,+ // GitLab sibling of 'claim-issue' above. SAME 7-phase flow, branch naming,+ // and no-local-merge cleanup — only the forge CLI differs (\`glab\` issues ++ // merge requests instead of \`gh\` issues + pull requests). Reached only via+ // the claim-work router when an app's resolved workTracker is 'gitlab'. Keep+ // this in lockstep with 'claim-issue' when the flow changes; the two diverge+ // only on glab-vs-gh commands. glab's exact flags evolve — the agent should+ // run \`glab <command> --help\` when a flag is rejected rather than failing.+ '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):+glab issue update "\${NUM}" --assignee @me 2>/dev/null || glab issue update "\${NUM}" --assignee "$(glab api user -F json | sed -n 's/.*"username":"\\([^"]*\\)".*/\\1/p')" 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\`:+ \`\`\`bash+ glab mr merge "\${NUM}" --yes --remove-source-branch \\+ || glab mr merge "\${NUM}" --yes --squash --remove-source-branch+ \`\`\`+ (\`glab mr merge\` takes the MR IID; if it differs from the issue number, resolve it with \`glab mr list --source-branch "claim/issue-\${NUM}" -F json\` first.)++## 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.`,+'code-reviewer-review': `[Review: {appName}] Deep Codebase Review (Stage 1)Perform a comprehensive review of {appName} and write your findings to REVIEW.md.diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.jsindex daaac587f2..a93b7da6bd 100644--- a/server/services/taskPromptDefaults/versions.js+++ b/server/services/taskPromptDefaults/versions.js@@ -10,6 +10,7 @@ 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'.'pr-reviewer': 3, // v3: multi-stage pipeline (security scan → code review + merge)'code-reviewer-a': 1, // v1: 2-stage pipeline (codebase review → triage & implement)'code-reviewer-b': 1, // v1: 2-stage pipeline (codebase review → triage & implement)diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 4524ae2312..3428af441a 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -139,7 +139,7 @@ async function getPerformanceAdjustedInterval(taskType, baseIntervalMs) {export const SELF_IMPROVEMENT_TASK_TYPES = ['security', 'code-quality', 'test-coverage', 'performance','accessibility', 'branch-cleanup', 'console-errors', 'dependency-updates', 'documentation',- 'ui-bugs', 'mobile-responsive', 'feature-ideas', 'plan-task', 'claim-issue', 'error-handling',+ 'ui-bugs', 'mobile-responsive', 'feature-ideas', 'plan-task', 'claim-issue', 'claim-work', 'error-handling','typing', 'release-check', 'pr-reviewer', 'code-reviewer-a', 'code-reviewer-b','jira-sprint-manager', 'jira-status-report', 'do-replan',// Polls the app's GitHub repo for pull requests newly opened against the@@ -199,6 +199,18 @@ export const DEFAULT_TASK_INTERVALS = {// matching /claim --issues) only claims issues the repo owner filed; 'any'// claims any open issue. Per-app override supported via taskTypeOverrides.'claim-issue': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, simplify: true, issueAuthorFilter: 'owner' } },+ // claim-work is the SINGLE-SOURCE router: one toggle per app that ships the+ // next work item from whatever tracker the app is configured for+ // (app.workTracker, default 'auto' → resolved from the git origin host). At+ // dispatch the generator resolves the tracker and delegates to the matching+ // prompt body — plan→plan-task, github→claim-issue, gitlab→claim-issue-gitlab,+ // jira→jira-sprint-manager — so the agent still creates its OWN worktree and+ // opens its OWN PR. Both `useWorktree` and `openPR` are OFF on the CoS side+ // for the SAME reasons as plan-task/claim-issue (a CoS-managed worktree would+ // hide the claim slug and trigger cleanupAgentWorktree's auto-merge).+ // `issueAuthorFilter` applies only when the resolved tracker is a forge+ // (github/gitlab); it's inert for plan/jira.+ 'claim-work': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, simplify: true, issueAuthorFilter: 'owner' } },'error-handling': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null },'typing': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null },'release-check': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null },@@ -248,7 +260,10 @@ export const MANAGED_AGENT_OPTIONS = {'plan-task': ['useWorktree', 'openPR'],// claim-issue's prompt creates its own claim/issue-<num> worktree (same// rationale as plan-task), so CoS must not pre-create one or open the PR.- 'claim-issue': ['useWorktree', 'openPR']+ 'claim-issue': ['useWorktree', 'openPR'],+ // claim-work delegates to one of the above prompt bodies, each of which+ // creates its own worktree + PR — so the same lock applies to the router.+ 'claim-work': ['useWorktree', 'openPR']};// Strip managed-agent fields from a per-app override map before merging on top