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
feat(cos): heal zombie issues — partial-ship hybrid + issue-reconcile task
Adam Eivy975735ac8a5e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fc2584bbe0..1ae761f219 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -18,6 +18,8 @@- **Local-model Claude agents now launch in a lean, isolated mode.** CoS agents on the Ollama-backed Claude providers (`claude-ollama`, `claude-ollama-tui`) previously inherited your full personal Claude Code environment — hooks, plugins, MCP servers, global CLAUDE.md — which reliably derailed small local models (a live eval showed qwen3.6:35b answering a session-start hook instead of its task). These sessions now spawn with `--bare --strict-mcp-config` (no hooks, no plugins, no MCP tool schemas, no CLAUDE.md auto-discovery), authenticating through the provider's existing `ANTHROPIC_BASE_URL` + `ANTHROPIC_AUTH_TOKEN` (pointed at your local Ollama), and get the same plain-`git`/`gh` completion workflow OpenCode agents use instead of slashdo commands bare mode can't load. In the same eval, once isolated this way qwen3.6:35b wrote a correct, test-passing helper (verified 46/46) end to end — the failures were the environment, not the model.- **Every Claude Code agent now separates its task from the PortOS operating contract.** For all Claude providers (TUI and headless CLI, local and hosted), the PortOS coordination boilerplate — worktree branch, completion-sentinel protocol, git/PR workflow — now rides in a real system prompt via `--append-system-prompt-file` (saved beside the agent's `prompt.txt` as `system-prompt.md`), while the pasted/stdin prompt carries only the task. The model weights the contract as standing instructions rather than conversation, and hosted providers get better prompt-cache reuse on the stable system block. The prompt content is byte-identical to before — only its placement changed. Codex, Antigravity, and OpenCode agents (no equivalent flag) keep the combined prompt unchanged.+- **Partially-completed issues no longer become un-claimable "zombies," and a new scheduled task heals any that already exist.** When a claim run shipped only PART of an issue's scope and merged the PR, the issue was left OPEN with its `in-progress` label (and assignee) still on — and since the claim queue treats `in-progress` as "claimed and being worked," the remaining scope was never re-picked and never finished (real cases: #2220, #2179, #2175). The completion flow was binary (fully-done → close + unlabel) with no "partial ship" path, and the branch reconciler is branch-centric so it never touched the linked issue. Two fixes: **(1)** the `claim-issue` / `-gitlab` / `-jira` prompts now choose the PR trailer deliberately (`Closes` for a full ship, `Refs` + a `## Remaining` section for a partial one) and Phase 7 reconciles the issue with an agent-judged hybrid — close + file a scoped follow-up when the remainder is a clean separable chunk, else post a `Done ✓ / Remaining ▢` comment and release the `in-progress` claim so the queue re-picks it (JIRA records remaining scope + files a follow-up ticket). **(2)** a new opt-in per-app `issue-reconcile` CoS task (sibling to `branch-reconcile`, disabled by default) runs a deterministic `gh`/`git` scan for zombie issues — open + `in-progress` yet with their PR merged and no live claim anywhere (no open PR, no local/remote/CoS claim branch, no active agent) — and dispatches a coordinator agent that applies the same hybrid per issue, with an `autoClose` toggle (OFF ⇒ comment + release only) and follow-up dedup so two federated peers can't file duplicates. Perpetual drain with a convergence signature, exactly like branch-reconcile. (`server/services/issueReconcile.js`, `server/services/cosTaskGenerator.js`, `server/services/taskSchedule.js`, `server/lib/cosValidation.js`, `server/services/taskPromptDefaults/`)+## Creative Writing Quality Engine- **[issue-2165] Editorial review now catches recognizable "AI slop" writing tells automatically.** Four new deterministic editorial checks join the existing 68: a tiered banned-word scan (hard-bans like "delve"/"myriad"/"utilize"; suspicious words like "robust"/"seamless" only flagged when 3+ cluster in one paragraph), fiction-specific AI-tell idioms ("a sense of dread", "couldn't help but", "eyes widened", "a wave of relief washed over him"), rhetorical structural tics ("not just X, but Y", runs of "did not [verb]", punchy three-sentence-in-a-row bursts like "Fast. Precise. Deadly."), and structural burstiness (em-dash overuse, essay-style transition-word openers, mechanically uniform paragraph lengths). Each surfaces as an editorial finding with the exact offending quote, same as the existing prose checks — configurable thresholds and house-style allowlists included.diff --git a/docs/plans/2026-07-06-issue-reconcile.md b/docs/plans/2026-07-06-issue-reconcile.mdnew file mode 100644index 0000000000..d883d4d4c0--- /dev/null+++ b/docs/plans/2026-07-06-issue-reconcile.md@@ -0,0 +1,84 @@+# Issue Reconcile — kill zombie issues, self-heal partial ships++**Date:** 2026-07-06+**Status:** approved → implementing+**Related:** #2220 (closed, follow-up #2241), #2179, #2175 (released); epic tie-in with the branch-reconcile CoS task (#2237/#2240)++## Problem++An issue that is only PARTIALLY completed by a merged PR becomes a **zombie**:+`OPEN` + `in-progress` label + assignee, with its PR already merged. The claim+queue treats `in-progress` as "claimed and being worked" and skips it, so the+remaining scope is never re-claimed and never completed.++Root cause — the completion flow has no "partial completion" state:++1. **`/do:next` Phase 7** (`taskPromptDefaults/prompts.js`) is *binary*: it verifies+ the issue auto-closed via a `Closes #NUM` trailer, and if still open closes it ++ removes `in-progress`. There is no branch for "I shipped part of the scope." The+ only pre-ship escape (`needs-input`, `:558`) releases *without shipping*.+2. **Branch reconciler** (`branchReconcile.js`) is entirely branch-centric — after it+ merges an `IN_REVIEW` PR it deletes the branch/worktree but **never touches the+ linked issue's label or state**.++So a sensible partial ship with `Refs #NUM` (not `Closes`) merged via the+reconciler/swarm path → zombie. Live examples: #2220, #2179, #2175.++## Design++Agent-judged **hybrid** partial-ship policy, applied in two places.++### Part A — teach the completion flow "partial ship" (future direct claims)++`claim-issue`, `claim-issue-gitlab`, `claim-issue-jira` Phase 5/7:++- Phase 5: the PR body uses `Closes #NUM` only when the PR fully satisfies the+ issue; a partial ship uses `Refs #NUM` + a "Remaining" section.+- Phase 7: after merge, decide *did this PR fully satisfy the issue?*+ - **Yes** → existing close + remove `in-progress`.+ - **No, remainder is a clean separable chunk** → close original (comment:+ shipped ✓ / moved to #NEW), file a scoped follow-up (`plan` + inherited area+ labels, `Refs #orig`).+ - **No, remainder is a continuation of the same scope** → keep open, post+ `Done ✓ / Remaining ▢` comment, remove `in-progress` + assignee → re-claimable.++Prompt-version discipline (CLAUDE.md "Distribution model"): bump `PROMPT_VERSIONS`+for all three keys, append the outgoing bodies verbatim to+`PREVIOUS_DEFAULT_PROMPTS`, regenerate `integrity.snapshot.json`.++### Part B — new `issue-reconcile` per-app CoS task (self-heal + reconciler path)++Mirrors the `branch-reconcile` shape:++- **`server/services/issueReconcile.js`** (pure classifier + `gh` gatherers, unit-tested):+ scan open + `in-progress` issues; classify each `ZOMBIE` iff a linked **merged**+ PR references it (head ref encodes `issue-<num>`, or body mentions `#<num>`) **and**+ there is no **live** claim (no open PR / local / remote / `cos/*/issue-<num>/*`+ branch for it) **and** no active CoS agent. Emit a `zombieSignature` convergence+ guard so the perpetual drain parks instead of looping.+- **`cosTaskGenerator.js`**: deterministic pre-step + dispatch block parallel to the+ branch-reconcile block — zombies → dispatch a coordinator agent that reads each+ issue+PR and applies the SAME hybrid decision; none → park on `recheckCron`.+- **Registration**: `SELF_IMPROVEMENT_TASK_TYPES`, `DEFAULT_TASK_INTERVALS`+ (PERPETUAL, disabled, `recheckCron: '0 4 * * *'`, `taskMetadata.autoClose: true`),+ `MANAGED_AGENT_OPTIONS` (lock `useWorktree`/`openPR` off — the coordinator works+ over `gh`, no worktree), the task-description map, `PROMPT_VERSIONS`+ (`issue-reconcile: 1`), `ALLOWED_TASK_METADATA_KEYS` (`autoClose`), and the new+ coordinator prompt body.+- **Disabled by default** → no migration needed (new opt-in task).+- **`autoClose` toggle** (default ON): when OFF the coordinator never closes an+ issue, only comments + unlabels — a safety valve for users who prefer one thread+ per feature.++**Peer safety** (differs from branch-reconcile, which is local-ref-only): issue+state is shared GitHub state across federated peers (void/null/NaN/undefined).+Close/unlabel are idempotent; the one real race is *filing a duplicate follow-up+from two machines*, so the coordinator dedupes by searching for an existing+follow-up (`Refs #orig` marker) before filing. v1 pre-step is `gh`-only and parks+on non-GitHub apps; GitLab/JIRA siblings are deferred (see PLAN.md).++## Part C — heal the three current zombies (done)++- **#2220** — separable remainder → **closed**, follow-up **#2241** filed.+- **#2179**, **#2175** — continuation → kept open, `Done/Remaining` comment,+ `in-progress` + assignee removed.diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex a76188c1cf..1d3e7438ef 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -266,13 +266,16 @@ export const PIPELINE_BEHAVIOR_FLAGS = ['useWorktree', 'openPR', 'simplify', 'reexport const MAX_TOTAL_SPAWNS = 5;// `cleanupMerged` / `openPr` / `resolveConflicts` / `autoMerge` are the-// per-app action toggles for the `branch-reconcile` task type (each ON unless-// explicitly false). They live in the shared task-metadata allowlist — like-// `prAuthorFilter` / `issueAuthorFilter` — so a per-app override can disable an-// individual rectification behavior and survive sanitizeTaskMetadata.+// per-app action toggles for the `branch-reconcile` task type; `autoClose` is+// the `issue-reconcile` toggle (ON unless explicitly false — OFF forbids the+// coordinator from closing an issue or filing a follow-up, leaving it to only+// comment + release the claim). Each lives in the shared task-metadata+// allowlist — like `prAuthorFilter` / `issueAuthorFilter` — so a per-app+// override can disable an individual rectification behavior and survive+// sanitizeTaskMetadata.const ALLOWED_TASK_METADATA_KEYS = [...PIPELINE_BEHAVIOR_FLAGS, 'readOnly',- 'cleanupMerged', 'openPr', 'resolveConflicts', 'autoMerge'+ 'cleanupMerged', 'openPr', 'resolveConflicts', 'autoMerge', 'autoClose'];// pr-watcher author-gate values. 'self' = PRs opened by the gh-authenticateddiff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex e4403d3359..78b27196a2 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -1582,11 +1582,13 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st// 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).- // branch-reconcile is PERPETUAL but is NOT gated by the generic work-detector- // registry — its "detector" and its actual work are the SAME scan (the- // deterministic reconcile below), so splitting them would double the git/gh- // I/O. Its dedicated block further down does the park/clear itself.- if (interval.type === taskSchedule.INTERVAL_TYPES.PERPETUAL && taskType !== 'branch-reconcile') {+ // branch-reconcile and issue-reconcile are PERPETUAL but are NOT gated by the+ // generic work-detector registry — for each, the "detector" and the actual+ // work are the SAME scan (the deterministic reconcile below), so splitting them+ // would double the git/gh I/O. Their dedicated blocks further down do the+ // park/clear themselves.+ if (interval.type === taskSchedule.INTERVAL_TYPES.PERPETUAL+ && taskType !== 'branch-reconcile' && taskType !== 'issue-reconcile') {const { detectActionableWork } = await import('./perpetualWork.js');const detection = await detectActionableWork(promptTaskType, app, {issueAuthorFilter: metadata.issueAuthorFilter || 'self'@@ -1682,6 +1684,59 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stemitLog('info', `🔀 branch-reconcile dispatching for ${app.name}: ${actionable.length} in-flight branch(es)`, { appId: app.id, analysisType: taskType });}+ // issue-reconcile: deterministic pre-step — scan the app's GitHub repo for+ // ZOMBIE issues (open + `in-progress` yet with their PR merged and no live+ // claim anywhere) and hand the set to the coordinator agent. Same perpetual+ // drain shape as branch-reconcile: the scan IS the work-detector (gh/git only,+ // no LLM), and the coordinator dispatches only while zombies remain — else it+ // PARKS on the daily recheckCron. `{zombieIssues}` carries the set into the+ // prompt. No worktree: the coordinator mutates issue state over `gh` only.+ let zombieIssuesBlock = '';+ if (taskType === 'issue-reconcile') {+ const { reconcile, zombieSignature, formatZombiesForPrompt } = await import('./issueReconcile.js');+ // The live-claim guard (open PR + local/remote/CoS claim branch, scanned via+ // for-each-ref inside reconcile) already covers every agent past Phase 2 of+ // the claim flow — the point at which it creates its claim/worktree branch.+ // The sub-minute pre-branch window is left to the coordinator's per-zombie+ // re-verification, so no separate active-agent set is threaded here.+ const autoClose = metadata.autoClose !== false;+ const result = await reconcile(app.repoPath).catch((err) => {+ emitLog('warn', `issue-reconcile pre-step failed for ${app.name}: ${err.message}`, { appId: app.id });+ return null;+ });+ // null = non-GitHub remote OR transient gh failure → skip WITHOUT parking so+ // the next tick retries (gh/git-only cost), mirroring branch-reconcile.+ if (!result) return null;+ if (result.stalled.length) {+ // In-progress issues with NO merged PR and NO live claim — a different stuck+ // state (claimed, nothing shipped) that issue-reconcile deliberately does+ // NOT auto-heal. Surface them so they're not silently ignored.+ emitLog('info', `🧟 issue-reconcile ${app.name}: ${result.stalled.length} stalled in-progress issue(s) with no merged PR (left for human/branch-reconcile)`, { appId: app.id, analysisType: taskType });+ }+ if (result.zombies.length === 0) {+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-zombie-issues', actionableCount: 0, signature: null });+ emitLog('info', `🧟 issue-reconcile parked for ${app.name}: no zombie issues`, { appId: app.id });+ return null;+ }+ // Convergence guard — identical to branch-reconcile's: a productive run closes+ // or releases zombies (changing the signature) → keep draining; an unchanged+ // signature (coordinator errored, or a case it punted to a human) → park on+ // the recheck cadence and CLEAR the signature so the next daily recheck+ // re-drives unconditionally rather than re-parking forever.+ const signature = zombieSignature(result.zombies);+ const lastSignature = await taskSchedule.getPerpetualSignature(taskType, app.id);+ if (signature === lastSignature) {+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-progress', actionableCount: result.zombies.length, signature: null });+ emitLog('info', `🧟 issue-reconcile parked for ${app.name}: ${result.zombies.length} zombie issue(s) unchanged since last run (no progress — will re-drive on next recheck)`, { appId: app.id });+ return null;+ }+ await taskSchedule.clearPerpetualPark(taskType, app.id);+ await taskSchedule.setPerpetualSignature(taskType, app.id, signature);+ metadata.perpetual = true;+ zombieIssuesBlock = formatZombiesForPrompt(result.zombies, { fullName: result.fullName, autoClose });+ emitLog('info', `🧟 issue-reconcile dispatching for ${app.name}: ${result.zombies.length} zombie issue(s)`, { appId: app.id, analysisType: taskType });+ }+// 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@@ -1846,6 +1901,7 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st.replace(/\{referenceData\}/g, () => referenceDataBlock).replace(/\{prData\}/g, () => prDataBlock).replace(/\{inFlightBranches\}/g, () => inFlightBranchesBlock)+ .replace(/\{zombieIssues\}/g, () => zombieIssuesBlock).replace(/\{repoFullName\}/g, () => prRepoFullName).replace(/\{defaultBranch\}/g, () => prDefaultBranch).replace(/\{planConstraint\}/g, () => planConstraintBlock);diff --git a/server/services/issueReconcile.js b/server/services/issueReconcile.jsnew file mode 100644index 0000000000..802a759a5d--- /dev/null+++ b/server/services/issueReconcile.js@@ -0,0 +1,268 @@+/**+ * Issue Reconciler — deterministic core.+ *+ * Finds ZOMBIE issues: open + `in-progress` (claimed-and-being-worked) yet with+ * their linked PR already MERGED and NO live claim anywhere (no open PR, no+ * local/remote/CoS claim branch, no active CoS agent). A zombie is an issue a+ * partial ship left stranded — the claim queue skips `in-progress`, so its+ * remaining scope is never re-picked and never finished.+ *+ * The scheduler runs the deterministic scan here (gh + git only — no LLM), then+ * hands the zombie set to a coordinator CoS agent that reads each issue + its+ * merged PR and applies the partial-ship hybrid (close + file a scoped follow-up+ * when the remainder is separable, or comment "done/remaining" + release the+ * claim when it's a continuation). This module never spawns an agent, so it+ * stays pure enough to unit-test — mirroring `branchReconcile.js`.+ *+ * PEER SAFETY differs from branch-reconcile. Branch-reconcile only ever touches+ * LOCAL refs, so a peer's branch is structurally invisible. Issue state, by+ * contrast, is SHARED GitHub state across every federated peer. So the live-claim+ * guard deliberately consults REMOTE refs and OPEN PRs too — a claim in flight on+ * another machine shows up here as an `origin/*` ref or an open PR, and must+ * suppress the zombie classification. Close/unlabel are idempotent across peers;+ * the one real race (two machines filing a duplicate follow-up) is deduped by the+ * coordinator, not here.+ */++import { execGit } from '../lib/execGit.js';+import { execGh } from './github.js';+import { getOriginInfo } from '../lib/gitRemote.js';+import { safeJSONParse, PATHS } from '../lib/fileUtils.js';++// Bound the gh queries (single-user repos never realistically truncate at 200).+const GH_LIST_LIMIT = 200;++// The `in-progress` label = "claimed and being worked". Kept as a constant so+// the scan, the classifier docs, and any future config share one spelling.+export const IN_PROGRESS_LABEL = 'in-progress';++/**+ * Extract the issue number a git ref claims, or null. Recognizes both claim+ * conventions:+ * - human / TUI: `claim/issue-<num>`+ * - CoS sub-agent: `cos/<task>/issue-<num>/<agent>`+ * The number must be a whole path segment (terminated by `/` or end-of-ref), so+ * `issue-222` never matches inside `issue-2220`. Remote-tracking refs+ * (`origin/claim/issue-<num>`) match the same way — the `refs/remotes/origin/`+ * prefix is just more leading segments.+ * @param {string} refName+ * @returns {number|null}+ */+export function issueNumberFromRef(refName) {+ const m = /(?:^|\/)issue-(\d+)(?=\/|$)/.exec(refName || '');+ return m ? Number(m[1]) : null;+}++/**+ * Does a PR body reference issue #num as a whole token? `#222` must not match+ * inside `#2220`, so the digits are followed by a non-digit boundary. Matches+ * plain `#num` as well as `Closes/Fixes/Resolves/Refs #num`.+ * @param {string} body+ * @param {number} num+ * @returns {boolean}+ */+export function bodyReferencesIssue(body, num) {+ if (!body || !Number.isInteger(num)) return false;+ return new RegExp(`#${num}(?!\\d)`).test(body);+}++/**+ * Does a PR (by head ref OR body) reference issue #num?+ * @param {{headRefName?:string, body?:string}} pr+ * @param {number} num+ * @returns {boolean}+ */+export function prReferencesIssue(pr, num) {+ if (!pr) return false;+ if (issueNumberFromRef(pr.headRefName) === num) return true;+ return bodyReferencesIssue(pr.body, num);+}++/**+ * Pure classifier: map one issue's facts to a reconcile state. First match wins.+ * ZOMBIE — merged PR shipped for it, no live claim, no active agent → heal+ * LIVE — an open PR / claim branch / active agent still owns it → leave+ * STALLED — no merged PR and no live claim (claimed but nothing shipped)→ report+ * Only issues that already carry `in-progress` are ever passed in.+ * @param {{ hasMergedPr:boolean, hasLiveClaim:boolean, hasActiveAgent:boolean }} input+ * @returns {'ZOMBIE'|'LIVE'|'STALLED'}+ */+export function classifyIssue({ hasMergedPr, hasLiveClaim, hasActiveAgent }) {+ if (hasLiveClaim || hasActiveAgent) return 'LIVE';+ if (hasMergedPr) return 'ZOMBIE';+ return 'STALLED';+}++/**+ * Classify a list of gathered issue inputs. Pure.+ * @param {object[]} inputs - each from `gatherIssueState`+ * @returns {object[]} inputs with a `state` field added+ */+export function classifyIssues(inputs) {+ return inputs.map((input) => ({ ...input, state: classifyIssue(input) }));+}++/**+ * Every issue number that has a LIVE claim ref (local OR remote). A live ref+ * means some machine (this one or a peer) is mid-claim, so the issue is NOT a+ * zombie even if a different PR already merged.+ * @param {string} repoPath+ * @returns {Promise<Set<number>>}+ */+async function getLiveClaimIssueNums(repoPath) {+ const { stdout } = await execGit(+ ['for-each-ref', '--format=%(refname)', 'refs/heads/', 'refs/remotes/'],+ repoPath,+ { ignoreExitCode: true }+ ).catch(() => ({ stdout: '' }));+ const nums = new Set();+ for (const line of (stdout || '').split('\n')) {+ const num = issueNumberFromRef(line.trim());+ if (num != null) nums.add(num);+ }+ return nums;+}++/**+ * Fetch issue/PR facts from GitHub. Returns null on any gh failure or non-GitHub+ * remote (degrade: the caller treats null as "nothing to reconcile / transient").+ * @param {string} repoPath+ * @returns {Promise<{fullName:string, inProgress:object[], mergedPrs:object[], openPrs:object[]}|null>}+ */+async function getGithubState(repoPath) {+ const origin = await getOriginInfo(repoPath).catch(() => null);+ if (!origin?.isGithub || !origin.fullName) return null;+ const { fullName } = origin;++ const [issuesRaw, mergedRaw, openRaw] = await Promise.all([+ execGh(['issue', 'list', '--repo', fullName, '--state', 'open',+ '--label', IN_PROGRESS_LABEL, '--limit', String(GH_LIST_LIMIT),+ '--json', 'number,title,labels,assignees,url']).catch(() => null),+ execGh(['pr', 'list', '--repo', fullName, '--state', 'merged',+ '--limit', String(GH_LIST_LIMIT),+ '--json', 'number,headRefName,body,url,mergedAt']).catch(() => null),+ execGh(['pr', 'list', '--repo', fullName, '--state', 'open',+ '--limit', String(GH_LIST_LIMIT),+ '--json', 'number,headRefName,body']).catch(() => null),+ ]);++ const inProgress = safeJSONParse(issuesRaw, null);+ // A failed ISSUE list is the load-bearing query — treat the whole scan as a+ // transient blip (return null → skip without parking). Empty is a valid,+ // different answer (no in-progress issues) and returns [].+ if (!Array.isArray(inProgress)) return null;+ return {+ fullName,+ inProgress,+ mergedPrs: safeJSONParse(mergedRaw, []) || [],+ openPrs: safeJSONParse(openRaw, []) || [],+ };+}++/**+ * Gather the raw facts for every open `in-progress` issue in `repoPath`'s GitHub+ * repo. Effectful (gh + git). Returns null on a non-GitHub remote or a transient+ * gh failure so the scheduler can skip without parking.+ *+ * @param {string} repoPath+ * @param {{ activeAgentIssueNums?: Set<number> }} [ctx] - issue numbers an active+ * CoS agent is currently claiming (from agent metadata); suppresses zombie+ * classification for an issue whose agent is still running.+ * @returns {Promise<{fullName:string, issues:object[]}|null>}+ */+export async function gatherIssueState(repoPath, { activeAgentIssueNums = new Set() } = {}) {+ const [gh, liveClaimNums] = await Promise.all([+ getGithubState(repoPath),+ getLiveClaimIssueNums(repoPath),+ ]);+ if (!gh) return null;++ const issues = gh.inProgress.map((issue) => {+ const num = issue.number;+ const mergedPr = gh.mergedPrs.find((pr) => prReferencesIssue(pr, num)) || null;+ const openPr = gh.openPrs.find((pr) => prReferencesIssue(pr, num)) || null;+ return {+ number: num,+ title: issue.title || '',+ url: issue.url || '',+ labels: Array.isArray(issue.labels) ? issue.labels.map((l) => l.name) : [],+ assignees: Array.isArray(issue.assignees) ? issue.assignees.map((a) => a.login) : [],+ mergedPr,+ hasMergedPr: Boolean(mergedPr),+ // Live claim = an OPEN PR for this issue, OR a local/remote claim branch,+ // OR an active CoS agent — any means "still being worked".+ hasLiveClaim: Boolean(openPr) || liveClaimNums.has(num),+ hasActiveAgent: activeAgentIssueNums.has(num),+ };+ });+ return { fullName: gh.fullName, issues };+}++/**+ * Full reconcile: gather → classify → split. Returns the zombie set (for the+ * coordinator agent) plus stalled/live for reporting. Pure-ish (delegates all+ * I/O to gatherIssueState).+ *+ * @param {string} [repoPath=PATHS.root]+ * @param {{ activeAgentIssueNums?: Set<number> }} [opts]+ * @returns {Promise<{ fullName:string, zombies:object[], stalled:object[], live:object[] }|null>}+ * null on non-GitHub remote / transient gh failure (skip, don't park).+ */+export async function reconcile(repoPath = PATHS.root, { activeAgentIssueNums = new Set() } = {}) {+ const gathered = await gatherIssueState(repoPath, { activeAgentIssueNums });+ if (!gathered) return null;+ const classified = classifyIssues(gathered.issues);+ return {+ fullName: gathered.fullName,+ zombies: classified.filter((c) => c.state === 'ZOMBIE'),+ stalled: classified.filter((c) => c.state === 'STALLED'),+ live: classified.filter((c) => c.state === 'LIVE'),+ };+}++/**+ * Stable signature of the zombie set — the perpetual drain compares it across+ * dispatches to detect PROGRESS. A productive coordinator run closes or releases+ * zombies (removing them here) or a new partial ship adds one; either changes the+ * signature. An unchanged signature means the last run left the same zombies in+ * the same state (coordinator errored, or the human hasn't acted on a case it+ * punted) → "no progress → park" instead of re-dispatching an identical run.+ * Order-independent (sorted).+ * @param {object[]} zombies+ * @returns {string}+ */+export function zombieSignature(zombies) {+ return zombies+ .map((z) => `${z.number}:${z.mergedPr?.number ?? 'none'}`)+ .sort()+ .join('|');+}++/**+ * Render the zombie set into the coordinator prompt body (injected as+ * `{zombieIssues}`). The per-issue entries stay factual; the partial-ship+ * mechanics live once in the prompt template. Only the dynamic `autoClose`+ * directive is surfaced here (the template can't know it), as a single header+ * line rather than repeated per issue.+ * @param {object[]} zombies+ * @param {{ fullName:string, autoClose:boolean }} ctx+ * @returns {string}+ */+export function formatZombiesForPrompt(zombies, { fullName, autoClose }) {+ const lines = [+ `Repo: \`${fullName}\`. Zombie issues to reconcile (${zombies.length}):`,+ '',+ autoClose+ ? '**autoClose is ON** — apply the full partial-ship hybrid below (close + file a scoped follow-up when the remainder is separable; otherwise comment + release the claim).'+ : '**autoClose is OFF** — never close an issue or file a follow-up. Only post a `Done ✓ / Remaining ▢` comment and release the `in-progress` claim so the queue re-picks it.',+ '',+ ];+ for (const z of zombies) {+ const pr = z.mergedPr ? `merged PR #${z.mergedPr.number}${z.mergedPr.url ? ` (${z.mergedPr.url})` : ''}` : 'a merged PR';+ lines.push(`### #${z.number} — ${z.title}`);+ if (z.url) lines.push(`- Issue: ${z.url}`);+ lines.push(`- Shipped by: ${pr}`);+ lines.push('');+ }+ return lines.join('\n');+}diff --git a/server/services/issueReconcile.test.js b/server/services/issueReconcile.test.jsnew file mode 100644index 0000000000..7f7ed6bc9d--- /dev/null+++ b/server/services/issueReconcile.test.js@@ -0,0 +1,267 @@+/**+ * Unit tests for the Issue Reconciler deterministic core.+ *+ * - issueNumberFromRef / bodyReferencesIssue / prReferencesIssue — the boundary-+ * safe reference matchers (no `issue-222` matching inside `issue-2220`).+ * - classifyIssue / classifyIssues — the pure ZOMBIE/LIVE/STALLED state machine.+ * - reconcile / gatherIssueState — end-to-end over mocked gh + git: an+ * in-progress issue with a merged PR and no live claim is a ZOMBIE; an open PR+ * or a live claim branch or an active agent keeps it LIVE.+ * - zombieSignature / formatZombiesForPrompt — the convergence signature and the+ * autoClose-aware prompt body.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../lib/execGit.js', () => ({+ execGit: vi.fn(async () => ({ stdout: '', exitCode: 0 })),+}));+vi.mock('./github.js', () => ({ execGh: vi.fn(async () => '[]') }));+vi.mock('../lib/gitRemote.js', () => ({+ getOriginInfo: vi.fn(async () => ({ isGithub: true, fullName: 'atomantic/PortOS' })),+}));+vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { root: '/repo' },+ safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw); } catch { return fallback; } },+}));++import {+ issueNumberFromRef, bodyReferencesIssue, prReferencesIssue,+ classifyIssue, classifyIssues, reconcile, gatherIssueState,+ zombieSignature, formatZombiesForPrompt,+} from './issueReconcile.js';+import { execGit } from '../lib/execGit.js';+import { execGh } from './github.js';+import { getOriginInfo } from '../lib/gitRemote.js';++beforeEach(() => {+ vi.clearAllMocks();+ execGit.mockResolvedValue({ stdout: '', exitCode: 0 });+ getOriginInfo.mockResolvedValue({ isGithub: true, fullName: 'atomantic/PortOS' });+});++describe('issueNumberFromRef', () => {+ it('matches the human claim convention', () => {+ expect(issueNumberFromRef('claim/issue-2220')).toBe(2220);+ });+ it('matches the CoS sub-agent convention', () => {+ expect(issueNumberFromRef('cos/branch-reconcile/issue-2220/agent-x')).toBe(2220);+ });+ it('matches a remote-tracking ref', () => {+ expect(issueNumberFromRef('refs/remotes/origin/claim/issue-2220')).toBe(2220);+ });+ it('does NOT match a shorter number inside a longer one', () => {+ // issue-222 must not match inside claim/issue-2220+ expect(issueNumberFromRef('claim/issue-2220')).not.toBe(222);+ });+ it('returns null for a non-claim ref', () => {+ expect(issueNumberFromRef('feat/some-feature')).toBeNull();+ expect(issueNumberFromRef('refs/heads/main')).toBeNull();+ expect(issueNumberFromRef('')).toBeNull();+ });+});++describe('bodyReferencesIssue', () => {+ it('matches a plain #num token', () => {+ expect(bodyReferencesIssue('Refs #2220 in the body', 2220)).toBe(true);+ });+ it('matches Closes/Fixes trailers', () => {+ expect(bodyReferencesIssue('Closes #2220', 2220)).toBe(true);+ });+ it('does NOT match a shorter number inside a longer one', () => {+ expect(bodyReferencesIssue('Closes #2220', 222)).toBe(false);+ });+ it('is false for empty / missing', () => {+ expect(bodyReferencesIssue('', 2220)).toBe(false);+ expect(bodyReferencesIssue(null, 2220)).toBe(false);+ });+});++describe('prReferencesIssue', () => {+ it('matches by head ref', () => {+ expect(prReferencesIssue({ headRefName: 'claim/issue-2220', body: '' }, 2220)).toBe(true);+ });+ it('matches by body when head ref does not encode it', () => {+ expect(prReferencesIssue({ headRefName: 'feat/covers', body: 'Refs #2220' }, 2220)).toBe(true);+ });+ it('is false when neither references it', () => {+ expect(prReferencesIssue({ headRefName: 'feat/x', body: 'Closes #99' }, 2220)).toBe(false);+ });+});++describe('classifyIssue', () => {+ it('merged PR + no live claim + no agent → ZOMBIE', () => {+ expect(classifyIssue({ hasMergedPr: true, hasLiveClaim: false, hasActiveAgent: false })).toBe('ZOMBIE');+ });+ it('a live claim wins even with a merged PR → LIVE', () => {+ expect(classifyIssue({ hasMergedPr: true, hasLiveClaim: true, hasActiveAgent: false })).toBe('LIVE');+ });+ it('an active agent wins even with a merged PR → LIVE', () => {+ expect(classifyIssue({ hasMergedPr: true, hasLiveClaim: false, hasActiveAgent: true })).toBe('LIVE');+ });+ it('no merged PR and no live claim → STALLED', () => {+ expect(classifyIssue({ hasMergedPr: false, hasLiveClaim: false, hasActiveAgent: false })).toBe('STALLED');+ });+});++describe('classifyIssues', () => {+ it('adds a state field to each', () => {+ const out = classifyIssues([+ { number: 1, hasMergedPr: true, hasLiveClaim: false, hasActiveAgent: false },+ { number: 2, hasMergedPr: false, hasLiveClaim: true, hasActiveAgent: false },+ ]);+ expect(out.map((o) => o.state)).toEqual(['ZOMBIE', 'LIVE']);+ });+});++// --- end-to-end gather/reconcile over mocked gh + git ---++/** Wire execGh's three list calls (issue / merged pr / open pr) by argv shape. */+function mockGh({ issues = [], merged = [], open = [] }) {+ execGh.mockImplementation(async (argv) => {+ if (argv[0] === 'issue' && argv[1] === 'list') return JSON.stringify(issues);+ if (argv[0] === 'pr' && argv.includes('merged')) return JSON.stringify(merged);+ if (argv[0] === 'pr' && argv.includes('open')) return JSON.stringify(open);+ return '[]';+ });+}++describe('reconcile', () => {+ it('flags an in-progress issue whose PR merged with no live claim as a ZOMBIE', async () => {+ mockGh({+ issues: [{ number: 2220, title: 'CDO covers', labels: [{ name: 'in-progress' }], assignees: [{ login: 'atomantic' }], url: 'u' }],+ merged: [{ number: 2234, headRefName: 'feat/covers', body: 'Refs #2220', url: 'p' }],+ open: [],+ });+ execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // no claim refs++ const result = await reconcile('/repo');+ expect(result.zombies.map((z) => z.number)).toEqual([2220]);+ expect(result.zombies[0].mergedPr.number).toBe(2234);+ expect(result.stalled).toHaveLength(0);+ expect(result.live).toHaveLength(0);+ });++ it('a live open PR keeps the issue LIVE (not a zombie)', async () => {+ mockGh({+ issues: [{ number: 2220, title: 't', labels: [{ name: 'in-progress' }], assignees: [], url: 'u' }],+ merged: [{ number: 2234, headRefName: 'x', body: 'Refs #2220' }],+ open: [{ number: 2300, headRefName: 'claim/issue-2220', body: '' }],+ });+ const result = await reconcile('/repo');+ expect(result.zombies).toHaveLength(0);+ expect(result.live.map((l) => l.number)).toEqual([2220]);+ });++ it('a live LOCAL/REMOTE claim branch keeps the issue LIVE', async () => {+ mockGh({+ issues: [{ number: 2220, title: 't', labels: [{ name: 'in-progress' }], assignees: [], url: 'u' }],+ merged: [{ number: 2234, headRefName: 'x', body: 'Refs #2220' }],+ open: [],+ });+ // for-each-ref reports a live claim branch (this machine or a peer)+ execGit.mockResolvedValue({ stdout: 'refs/remotes/origin/claim/issue-2220\nrefs/heads/main\n', exitCode: 0 });+ const result = await reconcile('/repo');+ expect(result.zombies).toHaveLength(0);+ expect(result.live.map((l) => l.number)).toEqual([2220]);+ });++ it('an active CoS agent on the issue keeps it LIVE', async () => {+ mockGh({+ issues: [{ number: 2220, title: 't', labels: [{ name: 'in-progress' }], assignees: [], url: 'u' }],+ merged: [{ number: 2234, headRefName: 'x', body: 'Refs #2220' }],+ open: [],+ });+ const result = await reconcile('/repo', { activeAgentIssueNums: new Set([2220]) });+ expect(result.zombies).toHaveLength(0);+ expect(result.live.map((l) => l.number)).toEqual([2220]);+ });++ it('no merged PR and no live claim → STALLED (not healed here)', async () => {+ mockGh({+ issues: [{ number: 2220, title: 't', labels: [{ name: 'in-progress' }], assignees: [], url: 'u' }],+ merged: [],+ open: [],+ });+ const result = await reconcile('/repo');+ expect(result.zombies).toHaveLength(0);+ expect(result.stalled.map((s) => s.number)).toEqual([2220]);+ });++ it('returns null (skip, do not park) on a non-GitHub remote', async () => {+ getOriginInfo.mockResolvedValue({ isGithub: false, fullName: null });+ const result = await reconcile('/repo');+ expect(result).toBeNull();+ });++ it('returns null (transient) when the issue list query fails', async () => {+ execGh.mockImplementation(async (argv) => {+ if (argv[0] === 'issue') return null; // load-bearing query failed+ return '[]';+ });+ const result = await reconcile('/repo');+ expect(result).toBeNull();+ });++ it('empty in-progress list is a valid answer (no zombies), not a skip', async () => {+ mockGh({ issues: [], merged: [], open: [] });+ const result = await reconcile('/repo');+ expect(result).not.toBeNull();+ expect(result.zombies).toHaveLength(0);+ });+});++describe('gatherIssueState carries labels/assignees for the follow-up', () => {+ it('surfaces area labels + assignees on the zombie record', async () => {+ mockGh({+ issues: [{ number: 2220, title: 't', labels: [{ name: 'in-progress' }, { name: 'area:create' }], assignees: [{ login: 'atomantic' }], url: 'u' }],+ merged: [{ number: 2234, headRefName: 'x', body: 'Refs #2220' }],+ open: [],+ });+ const gathered = await gatherIssueState('/repo');+ expect(gathered.issues[0].labels).toContain('area:create');+ expect(gathered.issues[0].assignees).toEqual(['atomantic']);+ });+});++describe('zombieSignature', () => {+ it('is order-independent and keys on issue+merged PR', () => {+ const a = zombieSignature([{ number: 2, mergedPr: { number: 20 } }, { number: 1, mergedPr: { number: 10 } }]);+ const b = zombieSignature([{ number: 1, mergedPr: { number: 10 } }, { number: 2, mergedPr: { number: 20 } }]);+ expect(a).toBe(b);+ expect(a).toBe('1:10|2:20');+ });+ it('changes when a zombie is healed away', () => {+ const before = zombieSignature([{ number: 1, mergedPr: { number: 10 } }, { number: 2, mergedPr: { number: 20 } }]);+ const after = zombieSignature([{ number: 2, mergedPr: { number: 20 } }]);+ expect(before).not.toBe(after);+ });+});++describe('formatZombiesForPrompt', () => {+ it('lists each zombie factually with its merged PR', () => {+ const md = formatZombiesForPrompt(+ [{ number: 2220, title: 'CDO', url: 'u', mergedPr: { number: 2234, url: 'p' } }],+ { fullName: 'atomantic/PortOS', autoClose: true }+ );+ expect(md).toContain('#2220');+ expect(md).toContain('CDO');+ expect(md).toContain('merged PR #2234');+ });+ it('autoClose:true surfaces the close+file-new arm in the header directive', () => {+ const md = formatZombiesForPrompt(+ [{ number: 2220, title: 'CDO', url: 'u', mergedPr: { number: 2234 } }],+ { fullName: 'atomantic/PortOS', autoClose: true }+ );+ expect(md).toContain('autoClose is ON');+ expect(md).toContain('file a scoped follow-up');+ });+ it('autoClose:false forbids closing — comment+release only', () => {+ const md = formatZombiesForPrompt(+ [{ number: 2220, title: 'CDO', url: 'u', mergedPr: { number: 2234 } }],+ { fullName: 'atomantic/PortOS', autoClose: false }+ );+ expect(md).toContain('autoClose is OFF');+ expect(md).toContain('never close an issue or file a follow-up');+ });+});diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.jsonindex b491567264..6852c071e6 100644--- a/server/services/taskPromptDefaults/integrity.snapshot.json+++ b/server/services/taskPromptDefaults/integrity.snapshot.json@@ -12,9 +12,9 @@"mobile-responsive": "16d8e7f63a673a2de48994c0ac08ef3d","feature-ideas": "0741418bd275b8953131155f8bc89460","plan-task": "5425306bf082b15b6a17f972557d4dd9",- "claim-issue": "89308f712f99ad8134224639cd99f135",- "claim-issue-gitlab": "271ad9c6efa9dce424103711292fd055",- "claim-issue-jira": "157cfc80c3d00bcbf3e97aae3998c372",+ "claim-issue": "8fbe8036e753a3ef5411b94be0aefbd1",+ "claim-issue-gitlab": "f85cef7bd97bd675c504655b673589d1",+ "claim-issue-jira": "4094d2a07cdc33179eedfaaecc2a6104","code-reviewer-review": "1cd13ee5142d130f95cc390098d0f278","code-reviewer-implement": "ab2c3e16d54e195bdf856574b7702042","error-handling": "9afba2e99b90a8d5771c75e7f0615d96",@@ -25,6 +25,7 @@"jira-status-report": "9d374a9d8ccb92c5c8fd0aa9899e79a5","branch-cleanup": "8fdeb4acc2749816a47ca318b6602721","branch-reconcile": "7ef2b5f7d8f05937d4912b26ad45f42e",+ "issue-reconcile": "c57a39aaa118173a496f030f5878bfc1","pr-reviewer": "add27b67daa6aa2c75717ac96a6bd625","pr-reviewer-security": "2050297d1cdb081a8576a781828ee44f","pr-reviewer-review": "21ccd5d3a6f3eea16c479db9ed9aedaa",@@ -35,15 +36,16 @@"PROMPT_VERSIONS": {"feature-ideas": 9,"plan-task": 8,- "claim-issue": 3,- "claim-issue-gitlab": 2,- "claim-issue-jira": 1,+ "claim-issue": 4,+ "claim-issue-gitlab": 3,+ "claim-issue-jira": 2,"pr-reviewer": 3,"code-reviewer-a": 1,"code-reviewer-b": 1,"reference-watch": 3,"pr-watcher": 1,"branch-reconcile": 1,+ "issue-reconcile": 1,"refresh-local-llm-catalog": 1,"security": 2,"code-quality": 2,@@ -83,10 +85,15 @@"722ca590fb4b6323c98850a176b9b309"],"pr-watcher": [],+ "claim-issue-jira": [+ "157cfc80c3d00bcbf3e97aae3998c372"+ ],"claim-issue-gitlab": [+ "271ad9c6efa9dce424103711292fd055","880dd7820ac90c689065e28cdca032fb"],"claim-issue": [+ "89308f712f99ad8134224639cd99f135","06190b8089adf1cb2c84bddeb6596af7","28f09436566c281a6915d6ad4c1b80f8"],diff --git a/server/services/taskPromptDefaults/previousDefaults.js b/server/services/taskPromptDefaults/previousDefaults.jsindex 8f18c54a19..dba1e0fcf1 100644--- a/server/services/taskPromptDefaults/previousDefaults.js+++ b/server/services/taskPromptDefaults/previousDefaults.js@@ -1374,7 +1374,234 @@ Repository: {repoPath}// 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-jira': [+ // v1 default (pre-partial-ship reconcile — bumped to v2)+ `[Claim Issue: {appName}] Claim and ship the next ready JIRA ticket++Pick the next ready JIRA ticket assigned to me in the current sprint, move it to **In Progress**, **create your own worktree at \`claim/<KEY>\`**, implement it, open a merge/pull request that references the ticket, move the ticket to **In Review**, and clean up. This is the \`/claim --issues\` flow for JIRA: same self-managed worktree and no-local-merge cleanup, but the work source is the app's **JIRA** project (via the PortOS JIRA API) and the ticket *status* — not an assignee/label — is the claim. **YOU pick the ticket in Phase 1.** Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.++All PortOS API calls below are relative to this base URL: http://localhost:5555++**How claiming works.** A ticket is "in flight" when (a) a \`claim/<KEY>\` or \`cos/<task>/<KEY>/<agent>\` ref exists across local branches, remote branches, or open MR/PR source refs, OR (b) its JIRA status is anything other than a not-started status (so "In Progress", "In Review", "Done", etc. are already taken). Moving the ticket to **In Progress** + the \`claim/<KEY>\` branch ARE the claim, visible to every other agent and to the human looking at the sprint board.++## Phase 1 — Pick the target ticket++Run steps 1–5 in order.++1. Resolve the app's JIRA config: GET http://localhost:5555/api/apps and find the app whose \`id\` is \`{appId}\`. Read \`jira.enabled\`, \`jira.instanceId\`, and \`jira.projectKey\`. If \`jira.enabled\` is not true or either id is missing, exit cleanly — this task only works against JIRA-configured apps.+2. Fetch my current-sprint tickets: GET http://localhost:5555/api/jira/instances/<instanceId>/my-sprint-tickets/<projectKey>. This returns the tickets assigned to me in the active sprint.+3. Build the in-flight set from git refs:+ \`\`\`bash+ cd {repoPath}+ git fetch --prune 2>/dev/null+ git branch -a --no-color --format='%(refname:short)'+ \`\`\`+ For each ref (after stripping any leading \`origin/\` / \`upstream/\` prefix), extract the ticket KEY **only when the ref matches** \`claim/<KEY>\` (the segment after \`claim/\`) or \`cos/<task>/<KEY>/<agent>\` (the \`<KEY>\` third segment). A KEY looks like \`PROJ-1234\`.+4. **Pick the target ticket:** walk the sprint tickets and pick the FIRST where ALL of the following are true (prefer higher priority — Blocker/Highest/High — then oldest):+ - Its status is a not-started status (e.g. "To Do", "Open", "Backlog", "Selected for Development", "Ready"). Skip tickets already "In Progress", "In Review", "Done", or any closed/resolved status — those are claimed or finished.+ - Its KEY is NOT in the in-flight set from step 3.+ - It is well-defined: a summary plus enough description/acceptance criteria to implement without further clarification.+ - It is NOT an Epic (issue type "Epic", or a title ending in "(epic)"). Leave epics for a human to split.+5. **If no eligible ticket exists**, exit cleanly — an empty actionable queue is a healthy state, not a failure. If a ticket is in the sprint but too vague or blocked to start, create a Review Hub todo (POST http://localhost:5555/api/review/todo with title "[<KEY>] Needs clarification" or "[<KEY>] Blocked" and a description of what's missing) instead of claiming it.++Capture the ticket KEY as \`KEY\`, its summary, and its full description — you'll reuse them in the branch, the MR/PR, and the commit trailer.++## Phase 2 — Claim (In Progress + worktree)++First move the ticket to **In Progress** (this is the claim, and it must happen BEFORE you start coding), then create the worktree. Transition names vary per project workflow, so resolve the id dynamically:++1. GET http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/transitions to list available transitions.+2. Pick the transition whose target status best matches "In Progress" (e.g. "In Progress", "Start Progress", "Start Work"); match case-insensitively. If none clearly matches, pick the transition that moves the ticket out of the To Do / Backlog column.+3. POST http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/transition with body {"transitionId": "<id>"}. If this fails (the status is unreachable), the ticket may have been claimed concurrently — return to Phase 1 and pick the next eligible ticket.++Then create the worktree on a branch named \`claim/<KEY>\`. Do all editing inside the worktree, NEVER in the source repo's working tree:++\`\`\`bash+KEY=<picked-key>+DEFAULT_BRANCH="$(git -C {repoPath} symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's@^origin/@@')"+DEFAULT_BRANCH="\${DEFAULT_BRANCH:-main}"+WORKTREE="{repoPath}/data/cos/worktrees/claim-\${KEY}"+mkdir -p "{repoPath}/data/cos/worktrees"+git -C {repoPath} fetch origin "\${DEFAULT_BRANCH}"+git -C {repoPath} worktree add -b "claim/\${KEY}" "\${WORKTREE}" "origin/\${DEFAULT_BRANCH}"+cd "\${WORKTREE}"+\`\`\`++**If \`git worktree add\` fails because the \`claim/<KEY>\` branch already exists** (a concurrent run won the race), do NOT force or reuse it — that branch IS another run's claim. Move the ticket back to its prior status if you transitioned it, treat the ticket as in-flight, return to Phase 1, and pick the next eligible ticket. Stash \`WORKTREE\` — you'll need it for Phase 6 cleanup.++## Phase 3 — Verify still valid++Re-read the ticket (GET http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>) before writing any code. **If ANY of these are true, release the claim and re-pick** (transition the ticket back to its not-started status, remove the worktree, return to Phase 1):++- The ticket references a function, file, or component that no longer exists (\`grep -rn\` the named identifiers — if they're gone, it's stale).+- The work would require touching files far outside the ticket's scope (>5 unrelated files), suggesting it's bigger than a single claim.+- The requirements are too ambiguous to implement without user clarification — in that case also create a Review Hub todo ("[<KEY>] Needs clarification") so a human can refine it.++Do NOT leave a half-claimed ticket parked "In Progress" with no branch.++## Phase 4 — Implement++Write the code, tests, and any docs the ticket 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 MR/PR** — small supporting helpers, refactors, and tests the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work.++Commit with a conventional message referencing the ticket so the trail is grep-able:++\`\`\`+<type>: <one-line description> (<KEY>)+\`\`\`++## Phase 5 — Open the MR/PR and move to In Review++The audit trail is the merged MR/PR + \`git log\`. Detect the forge from the git origin and use the matching CLI (\`gh\` for GitHub, \`glab\` for GitLab).++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. Otherwise skip it.+2. Push the branch: \`git push -u origin "claim/\${KEY}"\`+3. Open the MR/PR. Reference the JIRA \`KEY\` in the title and description (there is NO \`Closes\` auto-close for JIRA). Summarize what shipped + a short test plan.+ - GitHub: \`gh pr create --fill --head "claim/\${KEY}"\` (then edit the body to mention \`KEY\` if \`--fill\` didn't).+ - GitLab: \`glab mr create --fill --source-branch "claim/\${KEY}" --target-branch "\${DEFAULT_BRANCH}" --yes\`.+ Capture the MR/PR URL as \`PR_URL\`.+4. **Move the ticket to "In Review" — REQUIRED, not optional. Do not finish while it is still "In Progress":**+ - GET http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/transitions again (transitions change once In Progress).+ - Pick the transition whose target status best matches "In Review" (e.g. "In Review", "Code Review", "Review", "Ready for Review"); match case-insensitively.+ - POST http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/transition with body {"transitionId": "<id>"}.+5. Add the MR/PR link to the ticket: POST http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/comments with body {"comment": "Implementation complete. MR/PR: \${PR_URL}\\n\\nReady for code review."}. If a transition in step 4 failed (status unreachable), say so in this comment AND in the Phase 6 summary — do not silently drop it.++## Phase 6 — Review and clean up++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.++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. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent by hand.+2. **Run each configured CLI reviewer** headless against the MR/PR diff, apply fixes, run tests, re-push — capped at 3 rounds — then advance to the next reviewer.+3. **Leave the MR/PR open for a human to land.** Unlike the GitHub/GitLab issue flows, this flow does NOT auto-merge — the ticket is "In Review" and a human reviews + merges. After the reviewers finish, run the worktree-only cleanup so the source checkout is left clean:+ \`\`\`bash+ cd {repoPath}+ git worktree remove "\${WORKTREE}"+ \`\`\`+ Leave the local \`claim/<KEY>\` branch and the open MR/PR in place. **Do NOT \`git merge\`, \`gh pr merge\`, \`glab mr merge\`, or \`git pull\`** — landing the change and moving the ticket to Done is the human's call.++## Phase 7 — Report++Generate a short summary: the ticket KEY + summary worked, the MR/PR URL, the ticket's FINAL JIRA status (confirm it is "In Review"), reviewers run, and any status transition that failed and why.`,+ ],+'claim-issue-gitlab': [+ // v2 default (pre-partial-ship reconcile — bumped to v3)+ `[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 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++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: {appName}] Claim and ship the next open GitLab issuePick 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.@@ -1495,6 +1722,124 @@ If \`git branch -d\` refuses, use \`-D\` — the MR is confirmed merged, so the// 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.'claim-issue': [+ // v3 default (pre-partial-ship reconcile — bumped to v4)+ `[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 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++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.`,`[Claim Issue: {appName}] Claim and ship the next open GitHub issuePick 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.diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.jsindex 996bbb7902..83ce56ec79 100644--- a/server/services/taskPromptDefaults/prompts.js+++ b/server/services/taskPromptDefaults/prompts.js@@ -575,7 +575,7 @@ This flow ships GitHub issues — it does NOT touch PLAN.md. The audit trail is1. 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.+3. Open the PR with \`gh pr create\`. Summarize what shipped + a short test plan. **Choose the issue trailer deliberately:** if this PR FULLY satisfies the issue's scope, the body MUST contain \`Closes #\${NUM}\` so the merge auto-closes it. If you deliberately shipped only PART of the issue (a valuable slice, with real scope still remaining), use \`Refs #\${NUM}\` instead (NOT \`Closes\`) and add a \`## Remaining\` section listing what's left — Phase 7 reconciles the issue so it is never stranded.## Phase 6 — Review and ship@@ -603,7 +603,14 @@ 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.`,+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.++**Reconcile the issue — did this PR FULLY satisfy its scope?**+- **Yes (full)** — the \`Closes #\${NUM}\` trailer already auto-closed it; if it's somehow still open, close it (\`gh issue close "\${NUM}"\`) and remove the label (\`gh issue edit "\${NUM}" --remove-label in-progress\`).+- **No — the remainder is a clean, separable chunk** — close THIS issue with a summarizing comment (shipped ✓ / moved to #NEW), remove \`in-progress\`, and file ONE tightly-scoped follow-up for the remainder: \`gh issue create --title "…" --label plan --body "…\\n\\nRefs #\${NUM}"\` (carry over any \`area:*\` labels the issue had).+- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` comment, and release the claim so the queue re-picks it: \`gh issue edit "\${NUM}" --remove-label in-progress --remove-assignee @me\`.++NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **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 +@@ -699,7 +706,7 @@ This flow ships GitLab issues — it does NOT touch PLAN.md. The audit trail is1. 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).+3. Open the MR with \`glab mr create --fill --source-branch "claim/issue-\${NUM}" --target-branch "\${DEFAULT_BRANCH}" --yes\`. **Choose the issue trailer deliberately:** if this MR FULLY satisfies the issue's scope, the description MUST contain \`Closes #\${NUM}\` so the merge auto-closes it; if you deliberately shipped only PART of the issue (a valuable slice with real scope remaining), use \`Refs #\${NUM}\` instead (NOT \`Closes\`) and add a \`## Remaining\` section listing what's left — Phase 7 reconciles the issue so it is never stranded. Summarize what shipped + a short test plan (pass \`--description\` if \`--fill\` didn't capture it).## Phase 6 — Review and ship@@ -726,7 +733,14 @@ 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.`,+If \`git branch -d\` refuses, use \`-D\` — the MR is confirmed merged, so the local branch is redundant.++**Reconcile the issue — did this MR FULLY satisfy its scope?**+- **Yes (full)** — the \`Closes #\${NUM}\` line already auto-closed it on merge to the default branch; if it's somehow still open, close it (\`glab issue close "\${NUM}"\`) and remove the label (\`glab issue update "\${NUM}" --unlabel in-progress\`).+- **No — the remainder is a clean, separable chunk** — close THIS issue with a summarizing note (shipped ✓ / moved to #NEW), remove \`in-progress\`, and file ONE tightly-scoped follow-up for the remainder: \`glab issue create --title "…" --label plan --description "…\\n\\nRefs #\${NUM}"\` (carry over any \`area:*\` labels the issue had).+- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` note, and release the claim so the queue re-picks it: \`glab issue update "\${NUM}" --unassign --unlabel in-progress\`.++NEVER leave the issue OPEN with \`in-progress\` still on it — that strands it as a zombie (the claim queue skips \`in-progress\`, so the remaining scope is never re-picked). **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.`,// JIRA sibling of 'claim-issue' / 'claim-issue-gitlab'. SAME claim-one-item,// self-managed-worktree, ship-and-review shape — but the work source is the@@ -828,7 +842,7 @@ The audit trail is the merged MR/PR + \`git log\`. Detect the forge from the git- GET ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/transitions again (transitions change once In Progress).- Pick the transition whose target status best matches "In Review" (e.g. "In Review", "Code Review", "Review", "Ready for Review"); match case-insensitively.- POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/transition with body {"transitionId": "<id>"}.-5. Add the MR/PR link to the ticket: POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/comments with body {"comment": "Implementation complete. MR/PR: \${PR_URL}\\n\\nReady for code review."}. If a transition in step 4 failed (status unreachable), say so in this comment AND in the Phase 6 summary — do not silently drop it.+5. Add the MR/PR link to the ticket: POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/comments with body {"comment": "Implementation complete. MR/PR: \${PR_URL}\\n\\nReady for code review."}. **If you shipped only PART of the ticket's scope** (a valuable slice with real work remaining), make the comment a \`Done ✓ / Remaining ▢\` summary so the remaining scope is not lost when a human lands the MR/PR; when that remainder is a clean, separable chunk, ALSO file a new follow-up ticket for it (POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets with a summary + a description referencing \`KEY\`) so it re-enters the sprint queue. If a transition in step 4 failed (status unreachable), say so in this comment AND in the Phase 6 summary — do not silently drop it.## Phase 6 — Review and clean up@@ -1252,6 +1266,31 @@ Spawn ONE sub-agent per branch (they are independent — run them in parallel) t- If a sub-agent reports a branch is incomplete or blocked, leave it as-is and note it in your summary.- Summarize what each branch ended up doing (PR opened / conflicts resolved / merged / left incomplete).`,+ 'issue-reconcile': `[Improvement: {appName}] Zombie Issue Reconciliation++You are the coordinator for healing {appName}'s ZOMBIE issues. A zombie is an issue that is OPEN and still carries the \`in-progress\` label (which the claim queue reads as "claimed and being worked") — yet its pull request already MERGED and no live claim exists anywhere (no open PR, no local/remote/CoS claim branch, no running agent). A partial ship left the claim marker on, so the queue skips it forever and the remaining scope is never finished. The scheduler already ran the deterministic scan and handed you ONLY the confirmed zombie set.++Repository: {repoPath}++{zombieIssues}++Work through the issues above one at a time (they touch shared GitHub state — do NOT parallelize), applying the hybrid below to each and honoring the **autoClose** directive shown above the list.++## Verify before you act+- Read the issue (\`gh issue view <num> --comments\`) AND the merged PR (\`gh pr view <pr> \`) before touching anything. Confirm the merged PR actually shipped work FOR this issue (not just a coincidental \`#<num>\` mention) AND that real scope REMAINS. If the PR fully satisfied the issue, just close it (\`gh issue close <num>\`) and remove \`in-progress\` — it was mislabeled, not partial. If the PR did NOT address this issue at all, leave it untouched and note it in your summary — it is not a zombie.++## The partial-ship hybrid (per the "Do:" line)+- **Separable remainder** → close the original with a comment summarizing what shipped (✓) and what moved out, then file ONE tightly-scoped follow-up issue for the remainder: \`gh issue create --title "…" --label plan --body "…\\n\\nRefs #<num>"\`. Carry over any \`area:*\` labels the original had. Then remove the label: \`gh issue edit <num> --remove-label in-progress\` (closing already drops it from the queue, but be explicit).+- **Continuation of the same scope** → keep the issue OPEN, post a \`Done ✓ / Remaining ▢\` comment, and release the claim so the queue re-picks it: \`gh issue edit <num> --remove-label in-progress --remove-assignee @me\`.++## Peer safety — avoid duplicate follow-ups+{appName} may run on several federated machines that share one GitHub repo. Before filing a follow-up, search for one you (or a peer) may already have filed: \`gh issue list --state open --search "Refs #<num> in:body"\`. If a matching open follow-up already exists, do NOT file another — just close/relabel the original and reference the existing follow-up.++## Rules+- Work ONLY on the issues listed above. Never open, close, or relabel an issue that is not listed.+- Every follow-up you file MUST contain \`Refs #<num>\` in its body (the dedup key above) and be labeled \`plan\` so the claim queue can pick it up.+- Summarize what each issue ended up doing (closed + follow-up #NEW / released for re-claim / left as-is because it was not a zombie).`,+// pr-reviewer is now a pipeline — this prompt is kept as fallback for non-pipeline mode'pr-reviewer': `[Improvement: {appName}] PR Review — Security Scan & Code Review Pipelinediff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.jsindex ec05013c19..f2f6557c59 100644--- a/server/services/taskPromptDefaults/versions.js+++ b/server/services/taskPromptDefaults/versions.js@@ -9,15 +9,16 @@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': 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).+ 'claim-issue': 4, // v4: Phase 5 chooses the issue trailer deliberately (Closes for a full ship, Refs + a `## Remaining` section for a partial one) and Phase 7 reconciles the issue with the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the `in-progress` claim — so a partial ship is never left OPEN + `in-progress` (a zombie the claim queue skips forever). 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': 3, // v3: mirrors claim-issue v4 — Phase 5 chooses Closes-vs-Refs deliberately and Phase 7 reconciles the issue with the partial-ship hybrid (close + scoped follow-up when separable, else "done/remaining" note + release the `in-progress` claim) so a partial ship is never stranded. 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': 2, // v2: Phase 5 records remaining scope in the ticket (Done/Remaining comment) and files a follow-up ticket when a partial ship's remainder is separable, so remaining work isn't lost when a human lands the MR/PR. 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)'code-reviewer-b': 1, // v1: 2-stage pipeline (codebase review → triage & implement)'reference-watch': 3, // v3: record proposals in the app's RESOLVED work tracker (PLAN.md / GitHub / GitLab / JIRA) via the {trackerInstructions} block — no longer hardcodes PLAN.md, so an app configured for GitHub issues gets `gh issue create` proposals. v2: append slug-tagged checklist items to PLAN.md (Adopt + Maybe) instead of writing REFERENCE_REVIEW.md; security-flagged commits get no PLAN entry (mentioned only in final summary)'pr-watcher': 1, // v1: review-and-comment default for newly-opened PRs on the app's default branch'branch-reconcile': 1, // v1: per-app coordinator that finishes in-flight LOCAL branches (open PR / resolve conflicts / drive review / auto-merge) after the deterministic merged-branch cleanup pass. Peer-safe (local refs only). Replaced the PortOS-only branchReconcileScheduler.+ 'issue-reconcile': 1, // v1: per-app coordinator that heals ZOMBIE issues (open + in-progress but their PR merged with no live claim) after the deterministic gh/git scan. Applies the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the claim so the queue re-picks it.'refresh-local-llm-catalog': 1, // v1: research current local models, refresh LOCAL_LLM_CATALOG + EDITORIAL_FAMILY_RANK, PR (PortOS repo only)// Basic self-improvement tasks — versioned so installs created before thediff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 7995360449..14a9ec8ef6 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -148,7 +148,7 @@ async function getPerformanceAdjustedInterval(taskType, baseIntervalMs) {// Unified default interval settings for all task typesexport const SELF_IMPROVEMENT_TASK_TYPES = ['security', 'code-quality', 'test-coverage', 'performance',- 'accessibility', 'branch-cleanup', 'branch-reconcile', 'console-errors', 'dependency-updates', 'documentation',+ 'accessibility', 'branch-cleanup', 'branch-reconcile', 'issue-reconcile', 'console-errors', 'dependency-updates', 'documentation','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',@@ -194,6 +194,21 @@ export const DEFAULT_TASK_INTERVALS = {// trigger cleanupAgentWorktree's auto-merge. Off by default — enabling it is the// user's explicit consent to let it drive PRs on a schedule.'branch-reconcile': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 3 * * *', taskMetadata: { useWorktree: false, openPR: false, cleanupMerged: true, openPr: true, resolveConflicts: true, autoMerge: true } },+ // issue-reconcile heals ZOMBIE issues: open + `in-progress` (claimed) yet with+ // their PR already MERGED and no live claim anywhere — a partial ship left the+ // claim marker on, so the queue (which skips `in-progress`) never re-picks the+ // remaining scope. PERPETUAL (drain-until-done): the generator runs the+ // deterministic gh/git scan every dispatch and dispatches the coordinator agent+ // only while zombies remain — then PARKS on the daily recheckCron (offset an+ // hour after branch-reconcile so merged-branch cleanup lands first). The+ // coordinator applies the partial-ship hybrid per zombie (close + file a scoped+ // follow-up when the remainder is separable, else comment "done/remaining" ++ // release the claim). `autoClose` (ON unless explicitly false) is the only+ // per-app toggle: OFF forbids closing/filing — comment + unlabel only.+ // useWorktree/openPR are LOCKED off (MANAGED_AGENT_OPTIONS): the coordinator+ // works over `gh` (no code changes, no worktree). Off by default — enabling it+ // is the user's explicit consent to let it mutate issue state on a schedule.+ 'issue-reconcile': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 4 * * *', taskMetadata: { useWorktree: false, openPR: false, autoClose: true } },'console-errors': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null },'dependency-updates': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },'documentation': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null },@@ -290,6 +305,10 @@ export const MANAGED_AGENT_OPTIONS = {// of the in-flight branches; a managed worktree would hide those branches from// the scan AND could trip cleanupAgentWorktree's auto-merge. Lock both off.'branch-reconcile': ['useWorktree', 'openPR'],+ // issue-reconcile's coordinator works purely over `gh` (issue label/state ++ // follow-up filing) — it makes no code changes, so it needs neither a worktree+ // nor a PR. Lock both off so a hand-edited config can't attach one.+ 'issue-reconcile': ['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'],@@ -1504,6 +1523,7 @@ export const TASK_TYPE_DESCRIPTIONS = {'accessibility': 'Accessibility audit','branch-cleanup': 'Clean up merged branches','branch-reconcile': "Finish this machine's in-flight local branches: clean up merged ones, open PRs, resolve conflicts, drive review, auto-merge when green",+ 'issue-reconcile': "Heal zombie issues: open + in-progress but their PR already merged with no live claim — close + file a scoped follow-up when work remains, or release the claim so the queue re-picks it",'dependency-updates': 'Update dependencies','release-check': 'Check for release readiness','error-handling': 'Improve error handling',