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: scheduled 'Claim Issue' CoS task with per-app issue-author filter

[._.]/ Adam Eivy81e03a26c9b7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 23922a0f8c..e5d294b48e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -3,6 +3,7 @@
## Added
- **Daily budgets for the Chief of Staff's domains** — each domain (Brain auto-classify, Memory auto-extract, CoS auto-run, Messages auto-send) can now carry a daily cap on how many automatic actions it takes and how many minutes of work it does. When a domain reaches its cap it pauses that automatic work for the rest of the day and resumes after the counters reset at midnight; the Chief of Staff config panel shows each domain's usage so far today. Caps are off by default (blank means unlimited), so nothing changes until you set one. This rounds out the per-domain guardrails alongside the off / dry-run / execute controls.
+- **Scheduled "Claim Issue" task** — a new built-in CoS schedule (CoS → Schedule → Claim Issue) that runs the `/claim --issues` flow on a cadence: it picks the next open GitHub issue, creates its own `claim/issue-<num>` worktree, implements the fix, opens a PR that closes the issue, runs the configured reviewers, merges, and cleans up. Configurable per app via an **Issue Author Filter** — claim only issues filed by the repository owner (default) or any open issue regardless of author. Off by default; enable and pick a provider/model per app like the other improvement tasks.
## Changed
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index 26cf7db2ab..24f58f3c71 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -86,6 +86,14 @@ export const PR_AUTHOR_FILTER_OPTIONS = [
{ value: 'others', label: 'Opened by others', description: 'Only PRs opened by someone other than the gh-authenticated user' }
];
+// claim-issue author gate (taskMetadata.issueAuthorFilter). Mirrors
+// ISSUE_AUTHOR_FILTERS in server/lib/validation.js. 'owner' = only claim issues
+// the repo owner filed (matches /claim --issues); 'any' = claim any open issue.
+export const ISSUE_AUTHOR_FILTER_OPTIONS = [
+ { value: 'owner', label: 'Owner-filed only', description: 'Only claim open issues filed by the repository owner/creator' },
+ { value: 'any', label: 'Any author', description: 'Claim the next eligible open issue regardless of who filed it' }
+];
+
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.jsx
index 837b48cde0..36156b897f 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, toggleAppMetadataOverride, agentOptionButtonClass } from '../../constants';
+import { AGENT_OPTIONS, ISSUE_AUTHOR_FILTER_OPTIONS, toggleAppMetadataOverride, agentOptionButtonClass } from '../../constants';
import { isCronExpression, describeCron } from '../../../../utils/cronHelpers';
import ToggleSwitch from '../../../ToggleSwitch';
import { INTERVAL_LABELS } from './scheduleConstants';
@@ -45,6 +45,19 @@ const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalInter
setUpdating(false);
};
+ // claim-issue per-app author filter. '' = inherit the global default; any
+ // other value writes a per-app override. The server replaces taskMetadata
+ // wholesale, so preserve the app's other override keys (worktree, etc.).
+ const handleIssueAuthorFilterChange = async (value) => {
+ setUpdating(true);
+ const next = { ...(override?.taskMetadata || {}) };
+ if (value === '') delete next.issueAuthorFilter;
+ else next.issueAuthorFilter = value;
+ const taskMetadata = Object.keys(next).length ? next : null;
+ await onUpdate(app.id, taskType, { taskMetadata }).catch(() => {});
+ setUpdating(false);
+ };
+
return (
<div className="flex flex-col sm:flex-row sm:flex-wrap sm:items-center gap-2 sm:gap-3 py-2 px-3 rounded hover:bg-port-card/30">
<div className="flex items-center gap-2 min-w-0 w-full sm:w-auto sm:flex-1">
@@ -120,6 +133,22 @@ const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalInter
})}
</div>
+ {taskType === 'claim-issue' && (
+ <select
+ value={override?.taskMetadata?.issueAuthorFilter || ''}
+ onChange={(e) => handleIssueAuthorFilterChange(e.target.value)}
+ disabled={updating}
+ aria-label={`Issue author filter for ${app.name}`}
+ title="Which open issues this app may claim"
+ className="bg-port-card border border-port-border rounded px-2 py-1.5 text-xs text-white min-w-[120px] min-h-[40px]"
+ >
+ <option value="">Inherit ({ISSUE_AUTHOR_FILTER_OPTIONS.find(o => o.value === (globalTaskMetadata?.issueAuthorFilter || 'owner'))?.label})</option>
+ {ISSUE_AUTHOR_FILTER_OPTIONS.map(opt => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
+ )}
+
<div className="hidden sm:block">
<ToggleSwitch
enabled={isEnabled}
diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
index 026a727448..9752273298 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 } from '../../constants';
+import { AGENT_OPTIONS, DEFAULT_REVIEW_STOP_MODE, PR_AUTHOR_FILTER_OPTIONS, ISSUE_AUTHOR_FILTER_OPTIONS } from '../../constants';
import ReviewerPicker from '../../ReviewerPicker';
import Banner from '../../../ui/Banner';
import { useCodeReviewDefaults } from '../../../../hooks/useCodeReviewDefaults';
@@ -114,6 +114,14 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
setUpdating(false);
};
+ const handleIssueAuthorFilterChange = async (value) => {
+ setUpdating(true);
+ await onUpdate(taskType, {
+ taskMetadata: { ...(config.taskMetadata || {}), issueAuthorFilter: value }
+ });
+ setUpdating(false);
+ };
+
const handleSavePrompt = async () => {
setUpdating(true);
const prompt = promptValue.trim() === '' ? null : promptValue;
@@ -240,6 +248,27 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
</div>
)}
+ {taskType === 'claim-issue' && (
+ <div>
+ <label htmlFor={`issue-author-filter-${taskType}`} className="text-sm text-gray-400 block mb-2">Issue Author Filter</label>
+ <select
+ id={`issue-author-filter-${taskType}`}
+ value={config.taskMetadata?.issueAuthorFilter || 'owner'}
+ onChange={(e) => handleIssueAuthorFilterChange(e.target.value)}
+ disabled={updating}
+ className="w-full bg-port-card border border-port-border rounded px-3 py-2 text-white text-sm"
+ >
+ {ISSUE_AUTHOR_FILTER_OPTIONS.map(opt => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
+ <p className="text-xs text-gray-500 mt-1">
+ {ISSUE_AUTHOR_FILTER_OPTIONS.find(o => o.value === (config.taskMetadata?.issueAuthorFilter || 'owner'))?.description}.
+ {' '}This is the global default — individual apps can override it below.
+ </p>
+ </div>
+ )}
+
<PromptEditor
config={config}
promptValue={promptValue}
diff --git a/server/lib/validation.js b/server/lib/validation.js
index f2585e51f1..c49ee76367 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1350,6 +1350,12 @@ const ALLOWED_TASK_METADATA_KEYS = [...PIPELINE_BEHAVIOR_FLAGS, 'readOnly'];
// agree on the vocabulary.
export const PR_AUTHOR_FILTERS = ['any', 'self', 'others'];
+// claim-issue author-gate values. 'owner' = only claim issues filed by the
+// repository owner/creator (matches the `/claim --issues` default); 'any' =
+// claim any open issue regardless of who filed it. Kept here so both the
+// sanitizer and the claim-issue prompt-builder agree on the vocabulary.
+export const ISSUE_AUTHOR_FILTERS = ['owner', 'any'];
+
/**
* Sanitize taskMetadata to an allow-list of agent-option keys. Boolean flags
* (`useWorktree`/`openPR`/`simplify`/`reviewLoop`/`readOnly`/`reviewerApplies`)
@@ -1400,6 +1406,13 @@ export function sanitizeTaskMetadata(raw) {
clean.prAuthorFilter = raw.prAuthorFilter;
hasKeys = true;
}
+ // `issueAuthorFilter` gates claim-issue dispatch on issue authorship —
+ // constrained to a known value so a hand-edited config can't smuggle in an
+ // arbitrary string the claim flow would silently treat as "owner".
+ if (Object.prototype.hasOwnProperty.call(raw, 'issueAuthorFilter') && ISSUE_AUTHOR_FILTERS.includes(raw.issueAuthorFilter)) {
+ clean.issueAuthorFilter = raw.issueAuthorFilter;
+ hasKeys = true;
+ }
// Pass through pipeline config (validated shape: object with stages array)
if (raw.pipeline && typeof raw.pipeline === 'object' && Array.isArray(raw.pipeline.stages)) {
clean.pipeline = raw.pipeline;
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index 221ca769c2..a39c1e068d 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -574,6 +574,16 @@ describe('validation.js', () => {
.toEqual({ useWorktree: true });
});
+ it('should accept a valid issueAuthorFilter and drop invalid ones', () => {
+ expect(sanitizeTaskMetadata({ issueAuthorFilter: 'owner' })).toEqual({ issueAuthorFilter: 'owner' });
+ expect(sanitizeTaskMetadata({ issueAuthorFilter: 'any' })).toEqual({ issueAuthorFilter: 'any' });
+ // Arbitrary strings must not slip through (would silently read as "owner").
+ expect(sanitizeTaskMetadata({ issueAuthorFilter: 'self' })).toBeNull();
+ expect(sanitizeTaskMetadata({ issueAuthorFilter: 42 })).toBeNull();
+ expect(sanitizeTaskMetadata({ useWorktree: true, issueAuthorFilter: 'bogus' }))
+ .toEqual({ useWorktree: true });
+ });
+
it('should accept an ordered reviewers list, dedupe, and drop unknowns', () => {
expect(sanitizeTaskMetadata({ reviewers: ['codex', 'antigravity', 'copilot'] }))
.toEqual({ reviewers: ['codex', 'antigravity', 'copilot'] });
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index e17c0748fb..ba957f0a3a 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1248,12 +1248,21 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
}
const planConstraintBlock = buildPlanConstraintBlock(metadata.planId);
const reviewersCsv = normalizeReviewers(metadata).join(',');
+ // claim-issue: expand {issueAuthorFilter} into a concrete directive telling
+ // the agent which open issues are claimable. The filter was already merged
+ // (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 — do NOT pass `--author` to `gh issue list` (leave `OWNER_FLAG` empty).'
+ : '**Author filter: repository owner only.** Only claim issues filed by the repository owner/creator. Resolve the owner with `gh repo view --json owner -q .owner.login` and set `OWNER_FLAG="--author <owner>"`; skip issues opened by anyone else.';
const description = promptTemplate
.replace(/\{appName\}/g, app.name)
.replace(/\{repoPath\}/g, app.repoPath)
.replace(/\{appId\}/g, app.id)
.replace(/\{reviewers\}/g, reviewersCsv)
+ .replace(/\{issueAuthorFilter\}/g, () => issueAuthorFilterBlock)
// Use a replacer function — String.replace with a replacement STRING
// interprets `$&`, `$1`, etc. as backreferences. Commit subjects/authors
// legitimately contain `$` (env-var docs, prices, awk snippets) and
diff --git a/server/services/taskPromptService.js b/server/services/taskPromptService.js
index 5159c651d8..e1620e81ad 100644
--- a/server/services/taskPromptService.js
+++ b/server/services/taskPromptService.js
@@ -497,6 +497,119 @@ If \`git branch -d\` refuses (the PR squash-merged on GitHub but local doesn't k
_(Phase 3b is defined above, right after Phase 3 — see the "alternative exit from Phase 3" section.)_`,
+ 'claim-issue': `[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:
+ \`\`\`bash
+ git fetch --prune 2>/dev/null
+ # OWNER_FLAG is "--author <owner>" for owner-only mode, or empty for any-author mode (see the author-filter block above)
+ gh issue list --state open $OWNER_FLAG --json number,title,author,assignees,labels,createdAt --limit 50
+ \`\`\`
+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 itself a tracking/umbrella issue labeled \`plan\` (those are split by \`/claim --issues\` into per-slice PRs, not claimed wholesale here).
+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.`,
+
'code-reviewer-review': `[Review: {appName}] Deep Codebase Review (Stage 1)
Perform a comprehensive review of {appName} and write your findings to REVIEW.md.
@@ -1156,6 +1269,7 @@ you did for each (one line per PR with its number).`
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': 1, // v1: /claim --issues flow — pick next open GitHub issue (owner-filtered or any-author), claim/issue-<num> worktree + assignee/in-progress markers, PR closes the issue
'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.js
index c4a31ccb3f..81ed465b5f 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -136,7 +136,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', 'error-handling',
+ 'ui-bugs', 'mobile-responsive', 'feature-ideas', 'plan-task', 'claim-issue', '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
@@ -180,6 +180,16 @@ export const DEFAULT_TASK_INTERVALS = {
// and merges via `gh pr merge`, so CoS doesn't need to.
// The agent runs in the source repo's working directory; `git worktree add` doesn't touch that working tree, so it's safe even with uncommitted user changes.
'plan-task': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, simplify: true } },
+ // claim-issue drives the /claim --issues flow — the agent creates its OWN
+ // claim/issue-<num> worktree, opens the PR (Closes #<num>), merges via
+ // `gh pr merge`, and cleans up. Both `useWorktree` and `openPR` are OFF on the
+ // CoS side for the SAME reasons as plan-task (a CoS-managed worktree under
+ // cos/<task>/<agent> would hide the issue-<num> slug from the in-flight scan
+ // and trigger cleanupAgentWorktree's auto-merge into the source repo's HEAD).
+ // `issueAuthorFilter` gates which issues are claimable: 'owner' (default,
+ // 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' } },
'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 },
@@ -220,7 +230,10 @@ export const DEFAULT_TASK_INTERVALS = {
// (e.g., plan-task's prompt creates its own claim/<slug> worktree, so a
// CoS-managed worktree would clobber it).
export const MANAGED_AGENT_OPTIONS = {
- 'plan-task': ['useWorktree', 'openPR']
+ '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']
};
// Strip managed-agent fields from a per-app override map before merging on top
@@ -1186,6 +1199,7 @@ function getTaskTypeDescription(taskType) {
'documentation': 'Update documentation',
'feature-ideas': 'Implement next planned feature or brainstorm new one',
'plan-task': 'Execute next PLAN.md item, remove it from PLAN.md, log to changelog (worktree+PR)',
+ 'claim-issue': 'Claim and ship the next open GitHub issue (owner-filed or any author), PR closes it',
'accessibility': 'Accessibility audit',
'branch-cleanup': 'Clean up merged branches',
'dependency-updates': 'Update dependencies',
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 45fe842eab..b7f3f52caf 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -96,6 +96,7 @@ import {
getScheduleStatus,
PROMPT_VERSIONS,
DEFAULT_TASK_INTERVALS,
+ MANAGED_AGENT_OPTIONS,
REFERENCE_WATCH_AUDITED_VERSION
} from './taskSchedule.js'
@@ -836,6 +837,37 @@ describe('taskSchedule', () => {
expect(prompt).toContain('claim/<slug>')
expect(prompt).toContain('in-flight set')
})
+
+ it('claim-issue drives the /claim --issues flow against GitHub issues', async () => {
+ const prompt = await getTaskPrompt('claim-issue')
+ // Work source is the GitHub issue tracker, not PLAN.md.
+ expect(prompt).toContain('claim/issue-')
+ expect(prompt).toContain('gh issue list')
+ expect(prompt).toContain('Closes #')
+ // The author-filter placeholder is substituted at dispatch time
+ // (cosTaskGenerator), so it stays literal in the raw stored prompt.
+ expect(prompt).toContain('{issueAuthorFilter}')
+ // Issues mode ships GitHub issues only — it explicitly does not touch PLAN.md.
+ expect(prompt).toContain('does NOT touch PLAN.md')
+ })
+ })
+
+ describe('claim-issue defaults', () => {
+ it('is registered as a self-improvement task type', () => {
+ expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('claim-issue')
+ })
+
+ it('defaults to owner-filed issues with worktree/PR managed by the agent', () => {
+ const cfg = DEFAULT_TASK_INTERVALS['claim-issue']
+ expect(cfg.type).toBe(INTERVAL_TYPES.DAILY)
+ expect(cfg.enabled).toBe(false)
+ expect(cfg.taskMetadata.issueAuthorFilter).toBe('owner')
+ // Mirrors plan-task: the agent creates its own worktree + opens the PR,
+ // so CoS must keep both off (and lock them).
+ expect(cfg.taskMetadata.useWorktree).toBe(false)
+ expect(cfg.taskMetadata.openPR).toBe(false)
+ expect(MANAGED_AGENT_OPTIONS['claim-issue']).toEqual(['useWorktree', 'openPR'])
+ })
})
describe('resetExecutionHistory', () => {