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
gate plan-task LLM dispatch and wait for code review before merging (#419)
[._.]/ Adam Eivy6e66d391a96a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 402694358e..3ae80d82b3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,7 @@## Changed+- **`plan-task` scheduler now skips dispatch when PLAN.md has nothing to do, and the `plan-task` prompt waits for code review before merging.** The scheduled `plan-task` agent used to spin up an LLM round even when PLAN.md was empty, only had `<!-- NEEDS_INPUT -->` items, or had `> ⚠️ DRIFT:` flags on every unchecked entry — the agent would just exit cleanly, burning a model call for no work. The scheduler now classifies the plan locally (cheap, no git/gh round-trip) and short-circuits the dispatch entirely in those cases, plus when every otherwise-eligible item is already claimed by another agent in flight. `feature-ideas` is intentionally never gated — its job is to brainstorm into an empty plan. The `plan-task` prompt itself also gained an explicit "wait for the configured reviewer's findings" step in Phase 6 between `gh pr create` and `gh pr merge`; previously `gh pr merge --auto` waited only on required status checks and could merge before Copilot's auto-review even arrived (as happened to PR #418). The reviewer is now configurable per scheduled task — pick Copilot, Claude, Codex, or Gemini from the Schedule tab, same picker as the add-task form. Copilot polls for the auto-review and addresses comments before merging (cap 3 iterations); the local-CLI options hand off to `/do:rpr --review-with <agent>`. The prompt's opening line and Phase 1 header were also rewritten so the dual scheduler-pre-reserved / agent-picks paths read clearly instead of contradicting each other.- **GOALS.md now reflects the full app.** Added two missing core goals — **Creative Production Suite** (Writers Room, Universe Builder, Series Pipeline, Creative Director, Image/Video Gen, Timeline, LoRAs, Importer, Sharing) and **Cognitive Training & Lifelong Learning** (POST, Morse, Rapid Reader, Wiki). Reframed Purpose and tagline around "everything app," "create more than consume," and "interface with the world and with myself." Updated Status table and Secondary Goals (music/audio production, mood board, sketch canvas, federated sharing, cross-domain insights).- **[cover-prose-input-idea-input-in-canonusage-corpus] Universe canon cross-reference test suite now pins every stage the per-issue search reads** — a regression that silently drops a stage from the search now fails the test suite immediately.- **[extract-shared-requiretoolkit-helper] Internal: consolidated three duplicated AI toolkit accessors into one shared module.** No behavior change; cuts ~30 lines and makes future toolkit-state changes one-touch.diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsxindex 152063d298..8f5c1e5f8c 100644--- a/client/src/components/cos/tabs/ScheduleTab.jsx+++ b/client/src/components/cos/tabs/ScheduleTab.jsx@@ -5,7 +5,7 @@ import toast from '../../ui/Toast';import * as api from '../../../services/api';import AppIcon from '../../AppIcon';import CronInput from '../../CronInput';-import { AGENT_OPTIONS, toggleAppMetadataOverride, agentOptionButtonClass } from '../constants';+import { AGENT_OPTIONS, REVIEWER_OPTIONS, DEFAULT_REVIEWER, toggleAppMetadataOverride, agentOptionButtonClass } from '../constants';import { isCronExpression, describeCron } from '../../../utils/cronHelpers';import ToggleSwitch from '../../ToggleSwitch';import { filterSelectableModels } from '../../../utils/providers';@@ -497,6 +497,26 @@ function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset,);})}</div>+ {(config.taskMetadata?.reviewLoop || config.taskMetadata?.openPR) && (+ <div className="mt-3 flex items-center gap-2 pl-2">+ <label htmlFor={`reviewer-${taskType}`} className="text-xs text-gray-500">Reviewer:</label>+ <select+ id={`reviewer-${taskType}`}+ value={config.taskMetadata?.reviewer || DEFAULT_REVIEWER}+ onChange={e => onUpdate(taskType, {+ taskMetadata: { ...(config.taskMetadata || {}), reviewer: e.target.value }+ })}+ disabled={updating}+ className="px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-gray-300 min-h-[28px]"+ title="Reviewer for the post-PR review loop (--review-with). Copilot = GitHub's auto-review; the others run a local CLI critique via /do:rpr."+ aria-label="Reviewer for review loop"+ >+ {REVIEWER_OPTIONS.map(opt => (+ <option key={opt.value} value={opt.value} title={opt.description}>{opt.label}</option>+ ))}+ </select>+ </div>+ )}</div>{allTaskTypes?.length > 1 && (diff --git a/scripts/migrations/003-update-pipeline-stage-prompts.test.js b/scripts/migrations/003-update-pipeline-stage-prompts.test.jsindex 3cba9c657f..98fc06d3d0 100644--- a/scripts/migrations/003-update-pipeline-stage-prompts.test.js+++ b/scripts/migrations/003-update-pipeline-stage-prompts.test.js@@ -10,7 +10,7 @@* on every fresh install, not by this drift-catch suite.** Picked up via the vitest include glob in server/vitest.config.js- * (`../scripts/migrations/**\/*.test.js`).+ * (`../scripts/**\/*.test.js`).*/import { describe } from 'vitest';diff --git a/scripts/migrations/004-augment-idea-expansion-context.test.js b/scripts/migrations/004-augment-idea-expansion-context.test.jsindex 3cb12ac308..f9217e9f7c 100644--- a/scripts/migrations/004-augment-idea-expansion-context.test.js+++ b/scripts/migrations/004-augment-idea-expansion-context.test.js@@ -3,7 +3,7 @@* neighbor-issue context blocks.** Picked up via the vitest include glob in server/vitest.config.js- * (`../scripts/migrations/**\/*.test.js`).+ * (`../scripts/**\/*.test.js`).*/import { describe } from 'vitest';diff --git a/scripts/migrations/005-shape-aware-arc-prompts.test.js b/scripts/migrations/005-shape-aware-arc-prompts.test.jsindex a0918f38b0..2b3303a379 100644--- a/scripts/migrations/005-shape-aware-arc-prompts.test.js+++ b/scripts/migrations/005-shape-aware-arc-prompts.test.js@@ -3,7 +3,7 @@* gain Vonnegut-shape variables.** Picked up via the vitest include glob in server/vitest.config.js- * (`../scripts/migrations/**\/*.test.js`).+ * (`../scripts/**\/*.test.js`).*/import { describe } from 'vitest';diff --git a/scripts/migrations/013-comic-script-back-cover.test.js b/scripts/migrations/013-comic-script-back-cover.test.jsindex b61eb53b73..e3843f1d53 100644--- a/scripts/migrations/013-comic-script-back-cover.test.js+++ b/scripts/migrations/013-comic-script-back-cover.test.js@@ -3,7 +3,7 @@* concept` section.** Picked up via the vitest include glob in server/vitest.config.js- * (`../scripts/migrations/**\/*.test.js`).+ * (`../scripts/**\/*.test.js`).*/import { describe } from 'vitest';diff --git a/server/lib/planIds.js b/server/lib/planIds.jsindex 2c1bb5c6ac..d7c020b051 100644--- a/server/lib/planIds.js+++ b/server/lib/planIds.js@@ -18,6 +18,7 @@* @property {string|null} id slug if present, else null* @property {string} rest everything after the `[id]` slot (or after `[x]/[ ]` if no id)* @property {boolean} needsInput true if line carries the `<!-- NEEDS_INPUT -->` marker+ * @property {boolean} drifted true if the immediately-preceding line starts with `> ⚠️ DRIFT:`*/import { execGit } from './execGit.js';@@ -26,6 +27,7 @@ import { spawn } from 'child_process';const SLUG_MAX_LEN = 50;const CHECKBOX_RE = /^(?<indent>\s*)-\s+\[(?<box>[ xX])\]\s+(?:\[(?<id>[a-z0-9][a-z0-9-]*)\]\s+)?(?<rest>.*)$/;const NEEDS_INPUT_RE = /<!--\s*NEEDS_INPUT\s*-->/;+const DRIFT_LINE_RE = /^\s*>\s*⚠️\s*DRIFT:/;/*** Strip common markdown wrappers from a title fragment.@@ -106,7 +108,8 @@ export function parsePlanItems(markdown) {checked: box.toLowerCase() === 'x',id: id || null,rest: rest || '',- needsInput: NEEDS_INPUT_RE.test(rest || '')+ needsInput: NEEDS_INPUT_RE.test(rest || ''),+ drifted: DRIFT_LINE_RE.test(lines[i - 1] || '')});}return items;@@ -168,6 +171,49 @@ export function assignMissingIds(markdown, extraIds = []) {return { content: lines.join('\n'), assigned };}+/**+ * Classify why no PLAN.md item is currently dispatchable, for `plan-task`+ * gating. Returns null when an agent dispatch should proceed (an item is+ * pickable, or the state is recoverable — e.g. missing IDs that `do-replan`+ * will fix on its own pass). Returns a human-readable reason string when+ * the dispatch should be skipped entirely so the LLM isn't spun up just+ * to exit cleanly.+ *+ * Skip cases:+ * - PLAN.md missing or empty.+ * - No `- [ ]` items at all.+ * - Every unchecked item is blocked on human input (`<!-- NEEDS_INPUT -->`+ * annotation, or the preceding line starts with `> ⚠️ DRIFT:`).+ * - Every unchecked item is either blocked on human input OR already+ * claimed by another agent (in-flight by branch/PR scan).+ *+ * Either `planMd` or `parsedItems` must be supplied. When the caller has+ * already run `parsePlanItems(planMd)` (e.g. `applyPlanIdMetadata` does this+ * for the pick step), passing `parsedItems` here avoids a redundant parse;+ * `planMd` can then be passed as `null`.+ *+ * @param {string|null} planMd PLAN.md content, or null if parsedItems is supplied+ * @param {Set<string>|string[]} inFlightIds IDs currently claimed elsewhere+ * @param {PlanItem[]|null} [parsedItems] pre-parsed items, avoids re-parsing planMd+ * @returns {string | null} skip reason, or null when dispatch should proceed+ */+export function diagnoseUnpickablePlan(planMd, inFlightIds = new Set(), parsedItems = null) {+ if (!planMd && !parsedItems) return 'PLAN.md missing or empty';+ const inFlight = inFlightIds instanceof Set ? inFlightIds : new Set(inFlightIds);+ const items = parsedItems || parsePlanItems(planMd);+ const unchecked = items.filter(i => !i.checked);+ if (unchecked.length === 0) return 'PLAN.md has no unchecked items';++ const isBlockedByHuman = (i) => i.needsInput || i.drifted;+ if (unchecked.every(isBlockedByHuman)) {+ return 'all PLAN.md items are blocked on human input (NEEDS_INPUT / DRIFT)';+ }+ if (unchecked.every(i => isBlockedByHuman(i) || (i.id && inFlight.has(i.id)))) {+ return 'all PLAN.md items are claimed by other agents or blocked on human input';+ }+ return null;+}+/*** Pick the first `- [ ]` item that is not checked, not annotated NEEDS_INPUT,* not already in flight, and (if `requireId`) carries an ID.@@ -182,6 +228,7 @@ export function pickFirstAvailable(items, takenIds = new Set(), options = {}) {for (const item of items) {if (item.checked) continue;if (item.needsInput) continue;+ if (item.drifted) continue;if (requireId && !item.id) continue;if (item.id && taken.has(item.id)) continue;return item;@@ -213,9 +260,35 @@ function listOpenPullRequestHeadRefs(repoPath) {});}+/**+ * Extract the PLAN.md slug from a git ref ONLY when the ref matches one of+ * the two documented claim patterns:+ * - `claim/<slug>` (human / TUI / scheduler path)+ * - `cos/<task>/<slug>/<agent>` (CoS sub-agent path)+ * after stripping any single leading remote prefix (e.g. `origin/`).+ *+ * Returns null for refs that don't match — e.g. `feature/foo`, `main`,+ * `release`, or `origin/HEAD`. Without this gate, the segment-walking+ * approach would falsely flag any slug literally named `main`, `fix`,+ * `feature`, `release`, `dev`, etc. as in-flight against virtually every+ * branch in the repo, which would then suppress every plan-task dispatch.+ */+export function extractSlugFromRef(ref) {+ if (typeof ref !== 'string' || !ref) return null;+ const stripped = /^[^/]+\/(claim|cos)\//.test(ref)+ ? ref.replace(/^[^/]+\//, '')+ : ref;+ const m1 = /^claim\/(.+)$/.exec(stripped);+ if (m1) return m1[1];+ const m2 = /^cos\/[^/]+\/([^/]+)\/[^/]+$/.exec(stripped);+ if (m2) return m2[1];+ return null;+}+/*** Find which of `knownIds` are currently in flight, as evidenced by an open- * git branch (local or remote) or open PR with the slug as a path segment.+ * git branch (local or remote) or open PR with the slug encoded into a+ * documented claim ref pattern (`claim/<slug>` or `cos/<task>/<slug>/<agent>`).** `repoPath` is the repository to query. Best-effort: missing git, missing gh,* or fetch failure all degrade silently and return what evidence is available.@@ -247,10 +320,8 @@ export async function findInProgressIds(repoPath, knownIds) {const inFlight = new Set();for (const ref of refs) {- const segments = ref.split('/');- for (const seg of segments) {- if (known.has(seg)) inFlight.add(seg);- }+ const slug = extractSlugFromRef(ref);+ if (slug && known.has(slug)) inFlight.add(slug);}return inFlight;}diff --git a/server/lib/planIds.test.js b/server/lib/planIds.test.jsindex c248c1928c..ba1e07a92f 100644--- a/server/lib/planIds.test.js+++ b/server/lib/planIds.test.js@@ -4,7 +4,9 @@ import {parsePlanItems,assignMissingIds,extractAllIds,- pickFirstAvailable+ pickFirstAvailable,+ diagnoseUnpickablePlan,+ extractSlugFromRef} from './planIds.js';describe('planIds.js', () => {@@ -74,6 +76,20 @@ describe('planIds.js', () => {expect(parsePlanItems('')).toEqual([]);expect(parsePlanItems(null)).toEqual([]);});++ it('marks items whose preceding line is a `> ⚠️ DRIFT:` blockquote', () => {+ const md = [+ '## Next Up',+ '- [ ] [a] Clean item',+ '> ⚠️ DRIFT: function removed in #100',+ '- [ ] [b] Stale item',+ '- [ ] [c] Another clean item'+ ].join('\n');+ const items = parsePlanItems(md);+ expect(items[0].drifted).toBe(false);+ expect(items[1].drifted).toBe(true);+ expect(items[2].drifted).toBe(false);+ });});describe('extractAllIds', () => {@@ -130,11 +146,11 @@ describe('planIds.js', () => {describe('pickFirstAvailable', () => {const items = [- { id: 'a', checked: true, needsInput: false },- { id: 'b', checked: false, needsInput: true },- { id: 'c', checked: false, needsInput: false },- { id: 'd', checked: false, needsInput: false },- { id: null, checked: false, needsInput: false }+ { id: 'a', checked: true, needsInput: false, drifted: false },+ { id: 'b', checked: false, needsInput: true, drifted: false },+ { id: 'c', checked: false, needsInput: false, drifted: false },+ { id: 'd', checked: false, needsInput: false, drifted: false },+ { id: null, checked: false, needsInput: false, drifted: false }];it('skips checked, NEEDS_INPUT, and in-flight items', () => {@@ -147,13 +163,161 @@ describe('planIds.js', () => {expect(pick).toBeNull();});+ it('skips drifted items', () => {+ const itemsWithDrift = [+ { id: 'a', checked: false, needsInput: false, drifted: true },+ { id: 'b', checked: false, needsInput: false, drifted: false }+ ];+ const pick = pickFirstAvailable(itemsWithDrift);+ expect(pick?.id).toBe('b');+ });+it('with requireId:false, returns the first unchecked non-NEEDS_INPUT item even without an ID', () => {const pick = pickFirstAvailable(- [{ id: null, checked: false, needsInput: false }],+ [{ id: null, checked: false, needsInput: false, drifted: false }],new Set(),{ requireId: false });expect(pick?.id).toBeNull();});});++ describe('diagnoseUnpickablePlan', () => {+ it('flags missing/empty PLAN.md', () => {+ expect(diagnoseUnpickablePlan('')).toMatch(/missing or empty/);+ expect(diagnoseUnpickablePlan(null)).toMatch(/missing or empty/);+ });++ it('flags a plan with only checked items', () => {+ const md = '# Plan\n\n- [x] [a] Done one\n- [x] [b] Done two';+ expect(diagnoseUnpickablePlan(md)).toMatch(/no unchecked items/);+ });++ it('flags a plan with no checkbox items at all', () => {+ expect(diagnoseUnpickablePlan('# Plan\n\nNo checkboxes here.')).toMatch(/no unchecked items/);+ });++ it('flags when every unchecked item is NEEDS_INPUT', () => {+ const md = [+ '# Plan',+ '- [ ] [a] Item one <!-- NEEDS_INPUT -->',+ '- [ ] [b] Item two <!-- NEEDS_INPUT -->'+ ].join('\n');+ expect(diagnoseUnpickablePlan(md)).toMatch(/blocked on human input/);+ });++ it('flags when every unchecked item is preceded by a DRIFT marker', () => {+ const md = [+ '# Plan',+ '> ⚠️ DRIFT: function removed in #100',+ '- [ ] [a] Item one',+ '> ⚠️ DRIFT: file deleted',+ '- [ ] [b] Item two'+ ].join('\n');+ expect(diagnoseUnpickablePlan(md)).toMatch(/blocked on human input/);+ });++ it('flags when remaining items are all in-flight + NEEDS_INPUT mix', () => {+ const md = [+ '# Plan',+ '- [ ] [a] In flight elsewhere',+ '- [ ] [b] Blocked <!-- NEEDS_INPUT -->'+ ].join('\n');+ expect(diagnoseUnpickablePlan(md, new Set(['a']))).toMatch(/claimed by other agents/);+ });++ it('returns null when at least one item is pickable', () => {+ const md = [+ '# Plan',+ '- [ ] [a] Free to pick',+ '- [ ] [b] Blocked <!-- NEEDS_INPUT -->'+ ].join('\n');+ expect(diagnoseUnpickablePlan(md)).toBeNull();+ });++ it('returns null for the mixed missing-IDs case so do-replan can still run', () => {+ // The agent's Phase 1 step 2 handles missing IDs by exiting cleanly,+ // but that path is fast and `do-replan` is the recovery — not a skip+ // case for plan-task dispatch.+ const md = [+ '# Plan',+ '- [ ] Item without an ID'+ ].join('\n');+ expect(diagnoseUnpickablePlan(md)).toBeNull();+ });++ it('accepts an array as inFlightIds (not just a Set)', () => {+ const md = [+ '# Plan',+ '- [ ] [a] One',+ '- [ ] [b] Blocked <!-- NEEDS_INPUT -->'+ ].join('\n');+ expect(diagnoseUnpickablePlan(md, ['a'])).toMatch(/claimed by other agents/);+ });++ it('reuses pre-parsed items when supplied (no second parse)', () => {+ const md = [+ '# Plan',+ '- [ ] [a] One <!-- NEEDS_INPUT -->',+ '- [ ] [b] Two <!-- NEEDS_INPUT -->'+ ].join('\n');+ const items = parsePlanItems(md);+ expect(diagnoseUnpickablePlan(null, new Set(), items)).toMatch(/blocked on human input/);+ });+ });++ describe('extractSlugFromRef', () => {+ it('extracts the slug from claim/<slug>', () => {+ expect(extractSlugFromRef('claim/foo-bar')).toBe('foo-bar');+ expect(extractSlugFromRef('claim/some-slug-with-dashes-50chars')).toBe('some-slug-with-dashes-50chars');+ });++ it('strips a single leading remote prefix before matching claim/', () => {+ expect(extractSlugFromRef('origin/claim/foo')).toBe('foo');+ expect(extractSlugFromRef('upstream/claim/bar')).toBe('bar');+ expect(extractSlugFromRef('fork-remote/claim/baz')).toBe('baz');+ });++ it('extracts the slug-position segment from cos/<task>/<slug>/<agent>', () => {+ expect(extractSlugFromRef('cos/some-task/my-slug/agent-id')).toBe('my-slug');+ expect(extractSlugFromRef('origin/cos/task/slug/agent')).toBe('slug');+ });++ it('returns null for unrelated refs (the false-positive case)', () => {+ // Without this gate, a slug literally named "main"/"fix"/etc. would be+ // falsely flagged as in-flight against virtually every branch.+ expect(extractSlugFromRef('main')).toBeNull();+ expect(extractSlugFromRef('release')).toBeNull();+ expect(extractSlugFromRef('feature/foo')).toBeNull();+ expect(extractSlugFromRef('origin/main')).toBeNull();+ expect(extractSlugFromRef('origin/HEAD')).toBeNull();+ expect(extractSlugFromRef('fix-typo')).toBeNull();+ expect(extractSlugFromRef('refs/tags/v1.0.0')).toBeNull();+ });++ it('returns null for malformed cos refs', () => {+ expect(extractSlugFromRef('cos/task/slug')).toBeNull(); // missing agent segment+ expect(extractSlugFromRef('cos/task/slug/agent/extra')).toBeNull(); // too many segments+ });++ it('returns null for non-string / empty input', () => {+ expect(extractSlugFromRef('')).toBeNull();+ expect(extractSlugFromRef(null)).toBeNull();+ expect(extractSlugFromRef(undefined)).toBeNull();+ });++ it('rejects symbolic-ref alias lines that older git versions emit', () => {+ // `--format=%(refname:short)` strips these, but defense-in-depth covers+ // any caller that switches branch listings.+ expect(extractSlugFromRef('origin/HEAD -> origin/main')).toBeNull();+ expect(extractSlugFromRef('HEAD')).toBeNull();+ });++ it('greedy-captures everything after claim/ (slugs are kebab-case in practice)', () => {+ // Pins the current behavior: if a slug ever contained a `/`, the gate+ // would compare against the full string. Slugs are slash-free today;+ // this test fails loudly if that ever changes.+ expect(extractSlugFromRef('claim/foo/bar')).toBe('foo/bar');+ });+ });});diff --git a/server/services/cos.js b/server/services/cos.jsindex d08480f514..53346d84f0 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -28,7 +28,7 @@ import { generateProactiveTasks as generateMissionTasks, getStats as getMissionSimport { generateTaskFromJob, recordJobExecution, recordJobGateSkip, isScriptJob, executeScriptJob, isShellJob, executeShellJob } from './autonomousJobs.js';import { checkJobGate, hasGate } from './jobGates.js';import { ensureDir, formatDuration, safeJSONParse, PATHS } from '../lib/fileUtils.js';-import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS } from '../lib/validation.js';+import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, DEFAULT_REVIEWER } from '../lib/validation.js';import { addNotification, NOTIFICATION_TYPES } from './notifications.js';import { recordDecision, DECISION_TYPES } from './decisionLog.js';import { isRecoveryTask } from './recoveryTasks.js';@@ -93,31 +93,61 @@ let initialStartup = false;// Internal imports for functions used in this moduleimport { pruneOldAgentArchives, archiveStaleAgents as _archiveStaleAgents, loadAgentIndex } from './cosAgents.js';-import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable } from '../lib/planIds.js';+import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, diagnoseUnpickablePlan } from '../lib/planIds.js';// Task types where the scheduler pre-picks a PLAN.md item by ID so the agent's// worktree branch encodes the claim. `do-replan` is excluded — it assigns IDs// rather than picking one off the list.const PLAN_PICK_TASK_TYPES = new Set(['feature-ideas', 'plan-task']);+// Subset of PLAN_PICK_TASK_TYPES where the dispatch should be skipped entirely+// when no PLAN.md item is dispatchable. `feature-ideas` is intentionally+// excluded: it brainstorms new items when PLAN.md is empty/blocked, so it+// must run regardless. `plan-task` is a strict executor and would just exit+// cleanly — burning an LLM round for nothing.+const PLAN_GATE_TASK_TYPES = new Set(['plan-task']);+/*** For feature-ideas / plan-task, read the target repo's PLAN.md, find which* item IDs are already in flight via branch/PR scan, and pick the first* available item. Mutates `metadata` in place by setting `planId` when a- * pick succeeds. Falls back silently when PLAN.md is missing or every item- * is unavailable — the prompt's own brainstorm/exit-clean fallback handles- * those cases.+ * pick succeeds.+ *+ * Returns `{ skipReason }` so the caller can short-circuit the LLM dispatch+ * for `plan-task` when there's literally nothing to do (empty plan, all+ * items blocked on human input via NEEDS_INPUT/DRIFT, or all claimed+ * elsewhere). `feature-ideas` is never gated — its job is to brainstorm+ * from scratch when the plan is empty, so it always runs.+ *+ * @returns {Promise<{ skipReason: string | null }>}*/async function applyPlanIdMetadata(taskType, repoPath, metadata) {- if (!PLAN_PICK_TASK_TYPES.has(taskType)) return;- if (!repoPath) return;+ if (!PLAN_PICK_TASK_TYPES.has(taskType)) return { skipReason: null };+ if (!repoPath) return { skipReason: null };const planMd = await readFile(join(repoPath, 'PLAN.md'), 'utf-8').catch(() => '');- if (!planMd) return;+ const gateDispatch = PLAN_GATE_TASK_TYPES.has(taskType);+ if (!planMd) {+ return { skipReason: gateDispatch ? 'PLAN.md missing or empty' : null };+ }const items = parsePlanItems(planMd);++ // Short-circuit on local evidence before the network round-trip to+ // `git fetch --prune` + `gh pr list`. When every unchecked item is+ // already blocked on human input, no in-flight scan can change that.+ if (gateDispatch) {+ const localOnly = diagnoseUnpickablePlan(null, new Set(), items);+ if (localOnly) return { skipReason: localOnly };+ }+const knownIds = new Set(extractAllIds(planMd));const inFlight = await findInProgressIds(repoPath, knownIds).catch(() => new Set());const pick = pickFirstAvailable(items, inFlight);- if (pick?.id) metadata.planId = pick.id;+ if (pick?.id) {+ metadata.planId = pick.id;+ return { skipReason: null };+ }+ if (!gateDispatch) return { skipReason: null };+ return { skipReason: diagnoseUnpickablePlan(null, inFlight, items) };}/**@@ -1901,16 +1931,22 @@ async function generateManagedAppImprovementTask(app, state) {initializePipelineMetadata(metadata);if (shouldSkipForPrecondition(metadata, app, nextType)) return null;- await applyPlanIdMetadata(nextType, app.repoPath, metadata);+ const planMeta = await applyPlanIdMetadata(nextType, app.repoPath, metadata);+ if (planMeta.skipReason) {+ emitLog('info', `Skipping ${nextType} for ${app.name}: ${planMeta.skipReason}`, { appId: app.id });+ return null;+ }const planConstraintBlock = buildPlanConstraintBlock(metadata.planId);const promptTemplate = metadata.pipeline?.stages? await taskSchedule.getStagePrompt(nextType, 0): await taskSchedule.getTaskPrompt(nextType);+ const reviewer = metadata.reviewer || DEFAULT_REVIEWER;const description = promptTemplate.replace(/\{appName\}/g, app.name).replace(/\{repoPath\}/g, app.repoPath).replace(/\{appId\}/g, app.id)+ .replace(/\{reviewer\}/g, reviewer).replace(/\{planConstraint\}/g, () => planConstraintBlock);applyAppWorktreeDefault(metadata, app);@@ -2037,13 +2073,19 @@ async function generateManagedAppImprovementTaskForType(taskType, app, state, {referenceDataBlock = blocks.join('\n\n---\n\n');}- await applyPlanIdMetadata(taskType, app.repoPath, metadata);+ const planMeta = await applyPlanIdMetadata(taskType, app.repoPath, metadata);+ if (planMeta.skipReason) {+ emitLog('info', `Skipping ${taskType} for ${app.name}: ${planMeta.skipReason}`, { appId: app.id });+ return null;+ }const planConstraintBlock = buildPlanConstraintBlock(metadata.planId);+ const reviewer = metadata.reviewer || DEFAULT_REVIEWER;const description = promptTemplate.replace(/\{appName\}/g, app.name).replace(/\{repoPath\}/g, app.repoPath).replace(/\{appId\}/g, app.id)+ .replace(/\{reviewer\}/g, reviewer)// Use a replacer function — String.replace with a replacement STRING// interprets `$&`, `$1`, etc. as backreferences. Commit subjects/authors// legitimately contain `$` (env-var docs, prices, awk snippets) anddiff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex c4b99a6fb1..6184220ea7 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -399,12 +399,14 @@ When PLAN.md is missing, empty, or fully completed, brainstorm and implement a n'plan-task': `[Plan Task: {appName}] Claim and ship next PLAN.md item-Pick the next unclaimed PLAN.md item by its \`[<slug>]\` ID, **create your own worktree at \`claim/<slug>\`**, implement, ship a PR, and clean up. Mirrors the \`/claim\` slash command — same in-flight scan, same branch naming, same no-local-merge cleanup. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.+Ship the next PLAN.md item — either the one the scheduler pre-reserved (see **Item Constraint** below, if present) or the first available unclaimed item if no constraint is given. **Create your own worktree at \`claim/<slug>\`**, implement, ship a PR, and clean up. Mirrors the \`/claim\` slash command — same in-flight scan, same branch naming, same no-local-merge cleanup. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.{planConstraint}-**How claiming works.** Every PLAN.md checkbox carries a \`[<slug>]\` ID. A slug is "in flight" when it appears as the slug-position segment in either a \`claim/<slug>\` ref (the human/TUI pattern) or a \`cos/<task>/<slug>/<agent>\` ref (the CoS sub-agent pattern) — across local branches, remote branches, or open PR head refs. Pick the first \`- [ ]\` whose slug is NOT in flight and create a \`claim/<slug>\` branch — that branch name IS the claim, visible to every other agent and to the human running \`/claim\` in a TUI.+**How claiming works.** Every PLAN.md checkbox carries a \`[<slug>]\` ID. A slug is "in flight" when it appears as the slug-position segment in either a \`claim/<slug>\` ref (the human/TUI pattern) or a \`cos/<task>/<slug>/<agent>\` ref (the CoS sub-agent pattern) — across local branches, remote branches, or open PR head refs. The \`claim/<slug>\` branch you create IS the claim, visible to every other agent and to the human running \`/claim\` in a TUI.-## Phase 1 — Pick+## Phase 1 — Pick / accept the target slug++If the **Item Constraint** above named a \`[plan-id]\`, the slug is already chosen — you still need steps 2–3 to verify it isn't in-flight, then jump to step 4. If no Item Constraint is present, run steps 1–5 in order.1. Read PLAN.md from the repo root.2. **If any \`- [ ]\` line lacks an \`[<slug>]\` ID, stop and exit cleanly** — \`do-replan\` populates IDs in one pass; without IDs, this task has nothing to claim.@@ -525,10 +527,40 @@ Use \`feat:\` / \`fix:\` / \`refactor:\` / \`chore:\` / etc. (The bracketed-scop## Phase 6 — Review and ship+The configured reviewer for this task is \`{reviewer}\`. \`copilot\` waits for GitHub's auto-review; \`claude\` / \`codex\` / \`gemini\` invoke a local-CLI critique via \`/do:rpr --review-with <reviewer>\`.+1. Run \`/simplify\` (three-agent reuse/quality/efficiency review) against your own diff and fix findings in the same diff. BEFORE opening the PR, not retroactively.2. Push the branch: \`git push -u origin claim/<slug>\`3. Open the PR with \`gh pr create\` — title MUST encode the slug: \`<type>([<slug>]): <description>\`. Body should summarize what shipped + test plan.-4. **Merge via \`gh pr merge\`** — NEVER a local \`git merge\` into main or any other branch. The repo may allow only one of \`--merge\` / \`--squash\` / \`--rebase\`, so don't hardcode a method. Try in this order and use the first one that succeeds:+4. **Wait for the configured reviewer's findings BEFORE merging.** \`gh pr merge --auto\` only waits for required status checks; it does NOT wait for code-review feedback. Branch on \`{reviewer}\`:++ - **\`copilot\`** — This repo has GitHub Copilot Code Review configured to auto-run on every new PR. Poll until Copilot's review lands or a 10-minute timeout fires:+ \`\`\`bash+ PR=<num>+ # Match both forms: GraphQL/\`gh pr view\` returns the login without \`[bot]\`;+ # the REST request-a-reviewer endpoint requires the \`[bot]\` suffix. Future+ # GitHub API changes could flip which form callers see — accept either.+ for i in $(seq 1 20); do+ REVIEW=$(gh pr view "$PR" --json reviews \\+ -q '.reviews[] | select(.author.login | test("^copilot-pull-request-reviewer(\\\\[bot\\\\])?$")) | {state, submittedAt}')+ [ -n "$REVIEW" ] && break+ sleep 30+ done+ \`\`\`+ - **No review within 10 min**: proceed to merge (Copilot was slow or skipped).+ - **\`APPROVED\` with no inline comments**: proceed to merge.+ - **\`COMMENTED\` or \`CHANGES_REQUESTED\`**: fetch findings with \`gh api "repos/{owner}/{repo}/pulls/$PR/comments"\` (\`gh\` substitutes \`{owner}\`/\`{repo}\` from the current git checkout — those are gh path-placeholders, not prompt template vars) and \`gh pr view "$PR" --json reviews\`. Address each finding inside the worktree, commit, \`git push\`. Re-poll — Copilot re-reviews the new head SHA. Cap re-iterations at **3 rounds**; if findings keep arriving past that, exit to the **review-stuck cleanup** below — do NOT route to Phase 3b. Phase 3b is reserved for items that are blocked on *requirements clarification* and would inappropriately mutate PLAN.md and write \`.plan-questions.md\` for a review-feedback stall.++ **Review-stuck cleanup** (exit after 3 rounds of unresolved review feedback): add one final PR comment via \`gh pr comment $PR\` summarizing what was addressed across the rounds and what's still outstanding so the human picks up cold, then run the worktree-only cleanup (same shape as Phase 3b's, since the PR remains open and unmerged):+ \`\`\`bash+ cd {repoPath}+ git worktree remove "\${WORKTREE}"+ \`\`\`+ Leave the local \`claim/<slug>\` branch and the open PR alone. Do NOT run Phase 7 — that phase assumes a merged PR. PLAN.md and \`.changelog/NEXT.md\` were already updated in Phase 5, and that's fine even though the merge didn't happen: the next \`plan-task\` run will see the slug as in-flight via the open PR and pick a different item.++ - **\`claude\` / \`codex\` / \`gemini\`** — Invoke slashdo's \`/do:rpr --review-with {reviewer}\` against the PR. \`/do:rpr\` runs the chosen CLI in headless mode to critique the diff, applies fixes, and re-pushes. It owns its own iteration cap and clean-vs-dirty merge gate; on a clean status it returns control here for the merge.++5. **Merge via \`gh pr merge\`** — NEVER a local \`git merge\` into main or any other branch. The repo may allow only one of \`--merge\` / \`--squash\` / \`--rebase\`, so don't hardcode a method. Try in this order and use the first one that succeeds:\`\`\`bashgh pr merge <num> --auto --delete-branch \\|| gh pr merge <num> --squash --delete-branch \\