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
fix(cos): self-pick plan-task slugs, unblock Codex PRs, provider-aware simplify (#465)
[._.]/ Adam Eivy7649bb72abc8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1513adfa53..7150335bda 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -23,6 +23,9 @@## Fixed+- **`plan-task` agents now claim their own PLAN.md item instead of one the scheduler pre-picks.** The scheduled "plan-task" job used to reserve a PLAN.md slug at dispatch time and hand it to the agent as a hard constraint, but the actual lock (the `claim/<slug>` branch) isn't created until the agent runs — so two runs firing close together could both be handed the same first-available item, and one would waste its turn (the failure mode behind the 2026-05-21 duplicate-PR incident). The agent now picks the next unclaimed item itself at execution time and immediately creates the claim branch, exactly like the `/claim` command, so concurrent runs naturally land on different items. The dispatch-time scan is kept only as a gate that skips the run when nothing is claimable. Existing scheduled-task prompts auto-upgrade on next load (`plan-task` prompt v6 → v7); `feature-ideas` is unaffected.+- **Codex agents can now open PRs.** Codex CLI agents were spawned as `codex exec` with no sandbox/approval bypass, while Claude (`--dangerously-skip-permissions`) and Gemini (`--yolo`) got one — so Codex ran under the default sandbox that blocks network (its `gh pr create` couldn't resolve `api.github.com`) and, in non-interactive mode, silently cancelled any command needing approval. A Codex agent could push a branch over SSH yet fail to open the PR over HTTPS. Codex now gets `--dangerously-bypass-approvals-and-sandbox`, matching the other CLIs' unrestricted posture on PortOS's private single-user machine.+- **Non-Claude agents get a working "simplify" step.** `/simplify` is a Claude Code built-in slash command, so Codex/Gemini agents couldn't run the literal `/simplify` instruction baked into task prompts. The reuse/quality/efficiency self-review step is now phrased so any CLI can do it — Claude Code still runs `/simplify`, while other CLIs are told to do the equivalent diff review by hand. Applies to the scheduled-task templates and the per-agent completion sections.- Providers (`/ai`) and Prompts (`/prompts`) pages now render the same Settings sub-nav tabbed header as the other settings pages, so users can hop between Backup / Database / General / MortalLoom / Prompts / Providers / Sharing / Telegram / Voice without going back to the sidebar. Extracted a shared `SettingsTabsHeader` component used by `Settings.jsx`, `AIProviders.jsx`, and `PromptManager.jsx`.- **[test-autosubscribe-fanout-getpeers-guard-remaining] Apply the `getPeers → []` test stub to the remaining record-creating test files (and consider a shared guard).** Added `mockNoPeers()` to the shared test helper module and applied it across the remaining universe/series-creating suites, preserving the sharing tests' explicit identity stubs. Documented the convention in `CLAUDE.md` so new record-creating tests do not leak fixtures into live peer sync data.- **Test fixtures no longer leak into the real `data/universes/` via peer-sync fan-out.** `createUniverse` fires a non-awaited `autoSubscribeRecordToAllPeers`, which reads the live peer registry through `instances.js#getPeers` — a `dataPath` closure that resolves to the REAL `PATHS.data` once the post-return microtask escapes a test's `fileUtils` mock window. Three universe-creating suites (`universeBuilder.test.js`, `universeBuilderPromote.test.js`, `universeCanon.test.js`) created non-ephemeral fixtures without stubbing `getPeers`, so their "Moebius SciFi" universes were pushed across the federation and persisted into real `data/` by receiving instances (and re-leaked intermittently on every run). Each suite now mocks `getPeers → []`, matching the existing guard in `importer.test.js` / `promoteToPipeline.test.js`.diff --git a/CLAUDE.md b/CLAUDE.mdindex a8cfac2761..98a15a9cf8 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -27,7 +27,15 @@ pm2 logs## Security Model-PortOS is a **single-user, single-instance** application running on a private network behind Tailscale VPN. It is not exposed to the public internet. There is exactly one user and one server process — concurrent request races, mutex locking on file I/O, and atomic write patterns are unnecessary and should not be added or flagged as concerns. Simple re-entrancy guards (e.g., per-account sync locks to prevent duplicate in-flight operations) are fine and expected. As such, it intentionally omits authentication, CORS restrictions, rate limiting, HTTPS, and full concurrency controls — these are non-issues for its deployment context. Do not add these or flag their absence as security concerns.+**Trust model (within one install).** Each PortOS install serves exactly one human user, on a private network behind Tailscale VPN, never exposed to the public internet. Within an install there is one server process and one user — so concurrent *request* races, mutex locking on file I/O, and atomic write patterns are unnecessary as defenses against competing actors and should not be added or flagged as concerns. Simple re-entrancy guards (per-account sync locks to prevent duplicate in-flight operations; serializing two write paths that mutate the same record) are fine and expected. PortOS intentionally omits authentication, CORS restrictions, rate limiting, HTTPS, and full concurrency controls — these are non-issues for a single-user private-network deployment. Do not add them or flag their absence as security concerns. **"Single-user" means: do not defend against multiple competing humans inside one install. It does NOT mean "assume only one install exists."**++**Distribution model (across installs).** PortOS is distributed software: many independent people each run their own install, on their own machine(s), each upgrading on their own schedule — and a single user commonly runs **several machines federated as sync peers**. So backward/forward compatibility across installs and versions is first-class, NOT optional:++- **Never delete or skip migration / compatibility code on the grounds that "there's only one install."** There isn't — other people and other machines run this code and update it independently.+- On-disk format changes need a migration in `scripts/migrations/` (applied-list tracked per install in `data/migrations.applied.json`). Seed files must ship in `data.reference/`.+- Prompt-default changes need a `PROMPT_VERSIONS` bump AND the prior default preserved in `PREVIOUS_DEFAULT_PROMPTS`, so other installs recognize their stored prompt and auto-upgrade it (see `server/services/taskSchedule.js`).+- Cross-machine sync payloads stay version-gated (`server/lib/schemaVersions.js`) so a newer peer can't corrupt an older one.+- The self-update path stays fork-aware (`server/services/updateChecker.js`, `update.sh`) — other users run forks, not just upstream.The default database password `portos` (in `ecosystem.config.cjs`, `docker-compose.yml`, and `.env.example`) is an intentional backward-compatible fallback for local development. Do not remove it or flag it as a security concern. Production deployments override it via the `PGPASSWORD` environment variable.diff --git a/PLAN.md b/PLAN.mdindex 8f1f9c48a6..07050d521c 100644--- a/PLAN.md+++ b/PLAN.md@@ -4,7 +4,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel## Next Up-- [ ] [test-autosubscribe-fanout-getpeers-guard-remaining] **Apply the `getPeers → []` test stub to the remaining record-creating test files (and consider a shared guard).** Root-caused 2026-05-23: `createUniverse` (universeBuilder.js:939) and `createSeries` (pipeline/series.js:223) fire a non-awaited `import('./sharing/peerSync.js').then(autoSubscribeRecordToAllPeers)`. `autoSubscribeRecordToAllPeers` reads the live peer registry via `getPeers()` (instances.js, `dataPath` closure to the REAL PATHS), so any test that creates a non-ephemeral universe/series and does NOT mock `getPeers` fans the fixture out to real peers (void/null/NaN), which persist it into real `data/`. Fixed in `universeBuilder.test.js`, `universeBuilderPromote.test.js`, `universeCanon.test.js` (this is how the "Moebius SciFi"/uuid-0000 leak happened). **Still unguarded** (create subscribable records, no `getPeers` mock — verified via `grep -L getPeers` against the createUniverse/createSeries/createIssue caller set): `pipeline/arcPlanner.test.js`, `pipeline/autoRunner.test.js`, `pipeline/coverUniverseFiler.test.js`, `pipeline/episodeVideo.test.js`, `pipeline/issues.test.js`, `pipeline/migrateSeriesCanon.test.js`, `pipeline/seasons.test.js`, `pipeline/series.test.js`, `pipeline/textStages.test.js`, `pipeline/volumeBeatsRunner.test.js`, `sharing/subscriptions.test.js`, `sharing/integration.test.js`, `universeBuilderAutoSort.test.js` (the last is safe-by-accident: its synthetic in-memory fileUtils mock lacks `dataPath`, which breaks the peerSync import chain — but that's fragile). These create *series*, so they'd pollute `data/pipeline-series/` not `data/universes/` (no residue found yet, but same race). The `sharing/*` ones likely set up real peers intentionally — handle carefully (don't blanket-stub). **Better fix to evaluate:** a shared `mockNoPeers()` helper in `server/lib/mockPathsDataRoot.js` (or a vitest `setupFiles` default stub that individual sharing tests can override) so every new record-creating test is protected by default instead of relying on each author remembering. Add the `getPeers→[]` convention to CLAUDE.md's test section.+- [x] [test-autosubscribe-fanout-getpeers-guard-remaining] **Apply the `getPeers → []` test stub to the remaining record-creating test files.** Completed 2026-05-23: `server/lib/mockPathsDataRoot.js` now exposes `mockNoPeers()` / `mockNoPeerSync()`, the remaining universe/series-creating suites use the guard, sharing suites preserve explicit identity stubs, and `CLAUDE.md` documents the convention for new record-creating tests.- [ ] [prune-orphan-subscriptions-for-deleted-records] **Sweep orphaned peer subscriptions left by tombstone prune.** `pruneTombstonedUniverses` / `pruneTombstonedSeries` rm the record dir but leave its rows in `data/peer_subscriptions.json`. After the 2026-05-23 leaked-fixture cleanup (22 universes force-pruned), the matching subs are now orphaned — on `peer:online`, `retryPendingPushesForPeer` walks them, `loadOne` returns null, and the push no-ops (harmless but inflates the "retrying N pending pushes" count — saw 141). Add an orphan-subscription sweep (drop subs whose `recordKind/recordId` no longer resolves to an on-disk record) to the tombstone GC path, or call it from the prune helpers. Low urgency; cosmetic + minor wasted work per sync cycle. Surfaced by /simplify efficiency review during the ai-fallback PR (2026-05-22). When a stuck provider has N simultaneous in-flight calls, each failure independently runs `pickFallbackProvider` → `getAllProviders()` → `loadProviders()` (which reads `providers.json` from disk every time — no in-memory cache) → `markUnavailable` (writing `provider-status.json`). Two fixes that compound: (a) add a tiny TTL cache (~1s) to `aiToolkit/providers.js#loadProviders` so the read cost is amortized; (b) coalesce per-provider failure handling in `promptRunner.js` with a `Map<providerId, Promise>` so subsequent failures for the same provider await the first's mark-and-pick result and skip the duplicate work. Together they cut N-way failure storms to one disk-write + one mark. Acceptance: under a simulated 10-concurrent-failure load, providers.json is read at most twice and provider-status.json is written once.- [ ] [propagate-runner-errorAnalysis-into-onRunFailed-context] **Propagate `metadata.errorAnalysis` into the `onRunFailed` event context** so `promptRunner.js#markProviderUnavailableFromError` doesn't re-run `analyzeError` on the same text the runner already analyzed. The runner writes `errorAnalysis` to `metadata` (`server/lib/aiToolkit/runner.js:245`, 343, 433) but `server/index.js:202` only forwards a subset to the error event, so the analysis pass is duplicated on every failure. Either add `errorAnalysis` to the event context AND to the rejected error thrown to promptRunner, or attach it to the metadata object that the rejection carries. Microsecond-class perf, but cleaner. Surfaced by /simplify efficiency review during the ai-fallback PR (2026-05-22).- [ ] [upcoming-tasks-widget-drop-catch-to-empty] **Drop the `.catch(() => [])` in `UpcomingTasksWidget.jsx:21`.** Pre-existing tech debt (not touched in v2.6.0): `useAutoRefetch(() => api.getCosUpcomingTasks(6).catch(() => []), 60000)` wipes the prior list on transient errors. The seven sibling callers (Brain, DigitalTwin, QuickSummary, ActionableInsightsBanner, ProcessesTab, SystemHealthPage, CyberCity) were fixed during the v2.6.0 release review by dropping the catch and passing `{ silent: true }` to the API helper instead. Apply the same pattern here: add an `options` parameter to `getCosUpcomingTasks` (in `client/src/services/apiAgents.js`, mirroring `getCosQuickSummary`), drop the catch, and pass `{ silent: true }` in the call site. Surfaced by reviewer-4 in the v2.6.0 release review (2026-05-21).diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 726e9abdf9..3ef5998fb6 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -233,9 +233,19 @@ export function buildCliSpawnConfig(provider, model) {const providerId = provider?.id || 'claude-code';const effectiveModel = providerId === 'codex' && model === 'codex-configured-default' ? null : model;- // Codex CLI uses different invocation pattern+ // Codex CLI uses different invocation pattern.+ // `--dangerously-bypass-approvals-and-sandbox` is the Codex equivalent of+ // Claude's `--dangerously-skip-permissions` / Gemini's `--yolo`: it skips all+ // approval prompts AND disables the sandbox. Without it, `codex exec` runs+ // under the default workspace-write sandbox (network blocked, so `gh pr create`+ // can't resolve api.github.com) and, in non-interactive `exec` mode, any+ // command that needs approval is silently cancelled — which is exactly how a+ // codex agent could push a branch over SSH yet fail to open the PR over HTTPS.+ // PortOS runs on a private, single-user, trusted machine (the "externally+ // sandboxed" context this flag documents), matching how we already spawn the+ // other CLIs unrestricted.if (providerId === 'codex') {- const args = ['exec'];+ const args = ['exec', '--dangerously-bypass-approvals-and-sandbox'];if (effectiveModel) {args.push('--model', effectiveModel);}diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 7a9ed0885e..90f345888f 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -135,16 +135,19 @@ describe('createStreamJsonParser.getFinalResult', () => {});describe('buildCliSpawnConfig', () => {- it('omits --model for Codex configured-default sentinel', () => {+ it('omits --model for Codex configured-default sentinel but bypasses sandbox/approvals', () => {const config = buildCliSpawnConfig({ id: 'codex', command: 'codex' }, 'codex-configured-default');- expect(config.args).toEqual(['exec']);+ // The bypass flag is the Codex equivalent of Claude's --dangerously-skip-permissions+ // / Gemini's --yolo. Without it, codex exec runs sandboxed (no network → `gh`+ // can't reach api.github.com) and non-interactive approval prompts get cancelled.+ expect(config.args).toEqual(['exec', '--dangerously-bypass-approvals-and-sandbox']);});- it('passes explicit Codex model selections through', () => {+ it('passes explicit Codex model selections through alongside the sandbox bypass', () => {const config = buildCliSpawnConfig({ id: 'codex', command: 'codex' }, 'gpt-5.4');- expect(config.args).toEqual(['exec', '--model', 'gpt-5.4']);+ expect(config.args).toEqual(['exec', '--dangerously-bypass-approvals-and-sandbox', '--model', 'gpt-5.4']);});});diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex b41c80641a..eca4933e72 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -155,6 +155,11 @@ ${hints.map(h => `- ${h}`).join('\n')}*/const LIGHT_CONTEXT_PROVIDER_TYPES = new Set([PROVIDER_TYPES.TUI, PROVIDER_TYPES.CLI]);+// Inline reuse/quality/efficiency self-review wording for agents that can't run+// the Claude Code `/simplify` built-in (API providers + codex/gemini CLIs).+// Shared by both prompt paths so the two phrasings can't drift apart.+const SIMPLIFY_INLINE_REVIEW = 'review your changed code for reuse, quality, and efficiency (DRY, dead code, naming, simpler equivalents, missed edge cases)';+/*** Build the shared task block — the description plus optional `**Target App**`* and `**Screenshots**` fields. Used by BOTH the light and full prompt paths@@ -458,9 +463,16 @@ Use the findings from the previous stage to inform your work. If the previous st// section above. TUI agents own the full simplify+push+PR sequence in the// Completion Workflow section below, so this section is suppressed for TUI.const simplifyEnabled = isTruthyMetaFn(task.metadata?.simplify);+ // `/simplify` is a Claude Code built-in slash command — only Claude providers+ // can run it. Everyone else (API/CLI) gets the inline equivalent describing the+ // same reuse/quality/efficiency self-review so the pass still happens.+ const canRunSlashCommands = providerId === 'claude-code' || providerId === 'claude-code-bedrock';+ const simplifyInstruction = canRunSlashCommands+ ? 'run `/simplify` to review the changed code for reuse, quality, and efficiency'+ : SIMPLIFY_INLINE_REVIEW;const simplifySection = simplifyEnabled && !isTui ? `## Simplify Step-After completing your work and before committing, run \`/simplify\` to review the changed code for reuse, quality, and efficiency. Fix any issues found, then ${worktreeInfo && willOpenPR ? 'commit your changes (do NOT push — on a successful run the system will push and open the PR after you exit; if the run fails, no push or PR happens)' : 'commit and push using `/do:push`'}.+After completing your work and before committing, ${simplifyInstruction}. Fix any issues found, then ${worktreeInfo && willOpenPR ? 'commit your changes (do NOT push — on a successful run the system will push and open the PR after you exit; if the run fails, no push or PR happens)' : 'commit and push using `/do:push`'}.` : '';// Resolve the user's ordered reviewer list + flags (default `[copilot]`). Declared@@ -477,7 +489,7 @@ After completing your work and before committing, run \`/simplify\` to review thconst tuiCompletionCommand = willOpenPR ? '/do:pr' : '/do:push';const tuiCompletionSection = isTui? buildTuiCompletionSection({- willOpenPR, willReviewLoop, simplifyEnabled,+ willOpenPR, willReviewLoop, simplifyEnabled, providerId,sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,reviewers: taskReviewers,reviewStopMode: taskReviewStopMode,@@ -751,7 +763,7 @@ export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTrutsections.push(buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: false }));} else if (isTui) {sections.push(buildTuiCompletionSection({- willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,+ willOpenPR, willReviewLoop, simplifyEnabled, providerId, sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,reviewers: lightReviewers, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies}));} else {@@ -824,7 +836,7 @@ function buildPostPRMergeSteps(startStep, { reviewers = DEFAULT_REVIEWERS, revie* TUI completion-workflow block. The TUI owns its own commit → push → PR* pipeline via slashdo commands and signals "done" with a sentinel file.*/-function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, reviewers = DEFAULT_REVIEWERS, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {+function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, providerId = null, reviewers = DEFAULT_REVIEWERS, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {const cmd = willOpenPR ? '/do:pr' : '/do:push';const reviewArgs = willOpenPR && willReviewLoop ? buildReviewWithArgs(reviewers, reviewStopMode, reviewerApplies) : '';const reviewerArg = reviewArgs ? ` ${reviewArgs}` : '';@@ -834,7 +846,13 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled? ' — `/do:pr` runs the Copilot review loop after the PR opens.': ` — \`/do:pr\` runs the review loop for ${reviewers.join(', ')} in order after the PR opens.`): '';- const simplifyStep = simplifyEnabled ? '1. `/simplify`' : '1. (simplify disabled — skip)';+ // `/simplify` is a Claude Code TUI built-in. Non-Claude TUI providers+ // (codex-tui, gemini-tui) can't run it, so give them the inline equivalent.+ // Default (no providerId) stays Claude-shaped for backward compatibility.+ const canRunSimplifyCommand = !providerId || /claude/i.test(providerId);+ const simplifyStep = simplifyEnabled+ ? (canRunSimplifyCommand ? '1. `/simplify`' : `1. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`)+ : '1. (simplify disabled — skip)';const sentinelTail = willOpenPR ? ' ## PR\n <PR URL>' : ' ## Branch\n <branch name>';const merge = willOpenPR ? buildPostPRMergeSteps(3, { reviewers, reviewStopMode }) : { lines: [], nextStep: 3 };const sentinelStep = merge.nextStep;@@ -909,7 +927,13 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, hasSlashdo = fals} else {body = 'Commit and push your changes (`git pull --rebase && git push`, conventional commit prefix, no `git add -A`).';}- return `## Completion\n${body}`;+ // Non-slashdo CLIs (codex/gemini) have no `/simplify` command; when the task+ // enabled simplify, inline the equivalent self-review so the quality pass still+ // runs before they commit.+ const simplifyLine = simplifyEnabled+ ? `Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings. `+ : '';+ return `## Completion\n${simplifyLine}${body}`;}/**diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 9db64b944c..5d7d5b7fe8 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -182,6 +182,19 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/MERGED/);});+ it('TUI simplify step is provider-aware — non-Claude TUI (codex-tui) gets the inline equivalent, not /simplify', () => {+ // /simplify is a Claude Code TUI built-in; codex-tui / gemini-tui can't run it.+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { simplify: true, openPR: true } }),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt' },+ isTruthyMeta,+ { isTui: true, providerId: 'codex-tui' });+ expect(prompt).toMatch(/## Completion Workflow/);+ expect(prompt).not.toMatch(/`\/simplify`/);+ expect(prompt).toMatch(/review your changed code for reuse, quality, and efficiency/i);+ });+it('renders the Completion Workflow with /do:push when openPR is false', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { simplify: true, openPR: false } }),@@ -205,6 +218,22 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/PortOS will push and open the PR/);});+ it('inlines a simplify-equivalent self-review (no /simplify command) for non-Claude CLI agents', () => {+ // /simplify is a Claude Code built-in; codex/gemini can't run it. With+ // simplify enabled they must still get the reuse/quality/efficiency pass,+ // phrased inline so any CLI can perform it.+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, simplify: true } }),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt' },+ isTruthyMeta,+ { isTui: false }); // no providerId → not Claude → no slashdo+ expect(prompt).toMatch(/^## Completion$/m);+ expect(prompt).not.toMatch(/`\/simplify`/);+ expect(prompt).toMatch(/review your changed code for reuse, quality, and efficiency/i);+ expect(prompt).toMatch(/PortOS will push and open the PR/);+ });+it('emits a slashdo Completion block (/simplify + /do:pr) for Claude Code CLI + openPR', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { openPR: true, simplify: true } }),diff --git a/server/services/cos.js b/server/services/cos.jsindex cdef2500ba..f042770a77 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -104,11 +104,23 @@ let initialStartup = false;import { pruneOldAgentArchives, archiveStaleAgents as _archiveStaleAgents, loadAgentIndex } from './cosAgents.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.+// Task types where the scheduler reads PLAN.md to find an in-flight-aware pick.+// `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 AGENT picks (and claims) its own slug+// at execution time — mirroring the `/claim` slash command. For these, the+// scheduler must NOT stamp `metadata.planId`: a dispatch-time pre-pick happens+// before the agent creates its `claim/<slug>` branch (the real lock), so two+// near-simultaneous dispatches would both target the same first-available item.+// We still run the in-flight scan below purely as a DISPATCH GATE (skip the run+// when nothing is pickable), but leave the actual pick to the agent's Phase 1+// scan, which immediately precedes branch creation. The 2026-05-21 duplicate-PR+// incident (see cos.test.js) is guarded by the full Phase 1–7 self-pick prompt,+// not by the pre-pick. `feature-ideas` is intentionally NOT in this set — it+// uses a scheduler-managed worktree whose branch name encodes `planId`.+const PLAN_SELF_CLAIM_TASK_TYPES = new Set(['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@@ -120,7 +132,9 @@ 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.+ * pick succeeds — EXCEPT for self-claiming task types (PLAN_SELF_CLAIM_TASK_TYPES),+ * where the agent picks its own slug at execution time and the scan is used+ * only as the dispatch gate (no `planId` stamp).** Returns `{ skipReason }` so the caller can short-circuit the LLM dispatch* for `plan-task` when there's literally nothing to do (empty plan, all@@ -152,7 +166,12 @@ async function applyPlanIdMetadata(taskType, repoPath, metadata) {const inFlight = await findInProgressIds(repoPath, knownIds).catch(() => new Set());const pick = pickFirstAvailable(items, inFlight);if (pick?.id) {- metadata.planId = pick.id;+ // Self-claiming task types pick their own slug at execution time (like+ // `/claim`); stamping it here would pin concurrent dispatches to the same+ // item. For them this scan only serves as the gate above.+ if (!PLAN_SELF_CLAIM_TASK_TYPES.has(taskType)) {+ metadata.planId = pick.id;+ }return { skipReason: null };}if (!gateDispatch) return { skipReason: null };@@ -1703,7 +1722,7 @@ Your goal is to implement ONE feature.- Follow existing patterns in the codebase- Run tests to ensure nothing is broken-9. Run \`/simplify\` to review changed code for reuse, quality, and efficiency. Fix any issues found.+9. **Review your changed code for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix any findings. Claude Code can run \`/simplify\` for this pass; on other CLIs, do the equivalent diff review by hand.10. Commit with a clear description of the feature and rationalediff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 2fb2fb3e44..658f63ab61 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -784,6 +784,36 @@ describe('cos.js source — priority + capacity invariants', () => {'Generation log must not claim "(on-demand)" — function is shared by queue + on-demand callers').not.toMatch(/Generating improvement task[^`'"\n]*\(on-demand\)/);});++ it('applyPlanIdMetadata does NOT pre-stamp planId for self-claiming task types', () => {+ // Regression guard: `plan-task` agents pick (and claim) their own slug at+ // execution time, mirroring `/claim`. A dispatch-time pre-pick stamps a+ // slug before the agent creates its `claim/<slug>` branch (the real lock),+ // so two near-simultaneous dispatches both target the same first-available+ // item — the exact race behind the 2026-05-21 duplicate-PR incident. The+ // in-flight scan in applyPlanIdMetadata must stay (it gates dispatch), but+ // the planId stamp must be fenced behind PLAN_SELF_CLAIM_TASK_TYPES.+ expect(+ COS_SRC,+ 'plan-task must be registered as a self-claiming task type'+ ).toMatch(/PLAN_SELF_CLAIM_TASK_TYPES\s*=\s*new Set\(\[\s*'plan-task'\s*\]\)/);++ const fnStart = COS_SRC.indexOf('async function applyPlanIdMetadata');+ expect(fnStart, 'applyPlanIdMetadata must exist').toBeGreaterThan(-1);+ const fnBody = extractFnBody(COS_SRC, fnStart);++ // The planId stamp must be guarded so self-claiming types never pre-pick.+ expect(+ fnBody,+ 'metadata.planId stamp must be fenced behind a PLAN_SELF_CLAIM_TASK_TYPES check'+ ).toMatch(/if\s*\(\s*!PLAN_SELF_CLAIM_TASK_TYPES\.has\(taskType\)\s*\)\s*\{\s*metadata\.planId\s*=/);++ // The gate (skipReason) machinery must still run — we only dropped the stamp.+ expect(+ fnBody,+ 'applyPlanIdMetadata must still scan in-flight slugs to gate dispatch'+ ).toMatch(/findInProgressIds\(/);+ });});describe('addTask — first-line dedup', () => {diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex f39ca4da04..c9a3513bf5 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -353,7 +353,7 @@ Repository: {repoPath}9. Implement the feature:- Write clean, tested code following existing patterns- Run tests to ensure nothing is broken-10. Run \`/simplify\` to review changed code for reuse, quality, and efficiency. Fix any issues found.+10. **Review your changed code for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix any findings. Claude Code can run \`/simplify\` for this pass; on other CLIs, do the equivalent diff review by hand.11. Check the PLAN.md item: change \`- [ ]\` to \`- [x]\`. **Preserve the \`[plan-id]\` slug verbatim** — only the box character flips, never the ID. Reference the slug in the commit message (e.g. \`feat([plan-id]): …\`).12. Commit with a clear description referencing the PLAN.md item@@ -390,7 +390,7 @@ When PLAN.md is missing, empty, or fully completed, brainstorm and implement a n5. Implement the feature:- Write clean, tested code following existing patterns- Run tests to ensure nothing is broken-6. Run \`/simplify\` to review changed code for reuse, quality, and efficiency. Fix any issues found.+6. **Review your changed code for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix any findings. Claude Code can run \`/simplify\` for this pass; on other CLIs, do the equivalent diff review by hand.7. Add the feature as a checked item in PLAN.md (create the file if needed) **with a slug ID** derived from the feature title (lowercase kebab-case, ≤50 chars, unique against every existing \`[slug]\` in PLAN.md):\`\`\`- [x] [<slug-of-feature>] <description of the feature you implemented>@@ -399,14 +399,13 @@ 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-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}+Pick the next available 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. **YOU pick the item in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately creating the \`claim/<slug>\` branch **narrows** the window for two concurrent runs to collide on the same slug — it does NOT eliminate it: two runs can still complete Phase 1 before either creates a branch, then race at \`git worktree add\`. That race is handled in Phase 2 — the loser re-picks the next item. (A dispatch-time pre-pick is strictly worse: it commits both runs to the same slug long before any branch exists.) Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.**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 / accept the target slug+## Phase 1 — Pick 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.+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.@@ -421,12 +420,10 @@ If the **Item Constraint** above named a \`[plan-id]\`, the slug is already chos- \`cos/<task>/<slug>/<agent>\` — the slug is the third \`/\`-separated segment.A slug is "in flight" iff it appears in a ref matching one of those patterns AND is present in PLAN.md. **Do NOT** flag a slug just because the bare word appears as some other segment of a ref — that would falsely flag any slug literally named \`main\`, \`fix\`, \`feature\`, \`release\`, \`dev\`, etc. against virtually every branch in the repo.-4. **Pick the target slug:**- - **If the Item Constraint above named a specific \`[plan-id]\`**: use that. If the line is missing, has been checked, carries \`<!-- NEEDS_INPUT -->\`, or its slug IS in the in-flight set, exit cleanly without commits or PR.- - **Otherwise**: walk PLAN.md top-to-bottom and pick the FIRST \`- [ ]\` line where ALL of the following are true:- - The slug is NOT in the in-flight set.- - The immediately-preceding line does NOT start with \`> ⚠️ DRIFT:\`.- - The line does NOT carry the \`<!-- NEEDS_INPUT -->\` annotation.+4. **Pick the target slug:** walk PLAN.md top-to-bottom and pick the FIRST \`- [ ]\` line where ALL of the following are true:+ - The slug is NOT in the in-flight set.+ - The immediately-preceding line does NOT start with \`> ⚠️ DRIFT:\`.+ - The line does NOT carry the \`<!-- NEEDS_INPUT -->\` annotation.5. **If no eligible item exists**, exit cleanly — that's a healthy plan state, not a failure. Brainstorming is handled by the \`feature-ideas\` task; do NOT add new items here.Capture the exact text of the selected item (without the leading \`- [ ]\`) verbatim, **including its \`[<slug>]\` ID** — the changelog entry will reuse both.@@ -444,6 +441,8 @@ git worktree add -b "claim/\${SLUG}" "\${WORKTREE}" origin/maincd "\${WORKTREE}"\`\`\`+**If the worktree-creation command fails because the claim/<slug> branch already exists** (a concurrent run won the branch-creation race, or a remote claim/<slug> is now visible), do NOT force or reuse it — that branch IS another run's claim. Treat the slug as in-flight, return to Phase 1, and pick the next eligible item; if nothing else is eligible, exit cleanly.+Stash the worktree path; you'll need it for Phase 7 cleanup.## Phase 3 — Verify still valid@@ -529,7 +528,7 @@ Use \`feat:\` / \`fix:\` / \`refactor:\` / \`chore:\` / etc. (The bracketed-scopThe configured reviewers for this task, in order, are \`{reviewers}\`. \`copilot\` waits for GitHub's auto-review; \`claude\` / \`codex\` / \`gemini\` 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>\` (the lone default \`copilot\` needs no flag; multi-reviewer runs may also carry \`--review-stop-on-*\` / \`--reviewer-applies\`).-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.+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 opening the PR, not retroactively. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.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. **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 each one, apply the matching handling below before advancing to the next:@@ -675,7 +674,7 @@ Categorize into:- Run tests to verify nothing is broken- Commit with a clear message referencing the review recommendation-7. Run \`/simplify\` to review all changed code for reuse, quality, and efficiency+7. **Review all changed code for reuse, quality, and efficiency** and fix any findings. Claude Code can run \`/simplify\` for this pass; on other CLIs, do the equivalent diff review by hand.## Phase 4 — Update Project Files@@ -1211,7 +1210,7 @@ Repository: {repoPath}// Only non-customized prompts (promptCustomized !== true) are upgraded.const PROMPT_VERSIONS = {'feature-ideas': 9, // v9: drop DONE.md reads — use `.changelog/` + `git log` (last 50) as the completed-work signal- 'plan-task': 6, // v6: drop DONE.md reads/writes — agent removes the item from PLAN.md outright and logs to `.changelog/NEXT.md`; audit trail = git log + changelog+ 'plan-task': 7, // v7: drop the scheduler's dispatch-time pre-pick / Item Constraint — the agent self-picks its slug in Phase 1 like /claim, so concurrent dispatches can't both target the same first-available item before either has created its claim/<slug> branch'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)@@ -1839,6 +1838,196 @@ If \`git branch -d\` refuses (the PR squash-merged on GitHub but local doesn't k**Do NOT \`git pull\` from inside this phase** (no \`--rebase\`, no \`--autostash\`, no plain \`pull\`). The agent's work is already integrated on GitHub via \`gh pr merge\`; pulling locally provides no functional benefit and risks rebasing the user's in-progress branch / shuffling their uncommitted changes through stash if the source repo HEAD happens to be on a tracking feature branch when the agent runs. Leave the user's working tree alone.+_(Phase 3b is defined above, right after Phase 3 — see the "alternative exit from Phase 3" section.)_`,+ // v6 default prompt (scheduler pre-pick / Item Constraint flow — superseded by v7, which drops the dispatch-time pre-pick: the agent self-picks its slug at execution time like /claim, eliminating the same-slug race between concurrent dispatches)+ `[Plan Task: {appName}] Claim and ship next PLAN.md item++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. 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 / 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.+3. Build the in-flight set. Collect every ref from these sources:+ \`\`\`bash+ git fetch --prune 2>/dev/null+ git branch -a --no-color --format='%(refname:short)'+ gh pr list --state open --json headRefName -q '.[].headRefName' 2>/dev/null+ \`\`\`+ For each ref, extract the slug **only when the ref matches one of these documented patterns** (after stripping any leading remote prefix like \`origin/\` or \`upstream/\`):+ - \`claim/<slug>\` — the slug is everything after \`claim/\`.+ - \`cos/<task>/<slug>/<agent>\` — the slug is the third \`/\`-separated segment.++ A slug is "in flight" iff it appears in a ref matching one of those patterns AND is present in PLAN.md. **Do NOT** flag a slug just because the bare word appears as some other segment of a ref — that would falsely flag any slug literally named \`main\`, \`fix\`, \`feature\`, \`release\`, \`dev\`, etc. against virtually every branch in the repo.+4. **Pick the target slug:**+ - **If the Item Constraint above named a specific \`[plan-id]\`**: use that. If the line is missing, has been checked, carries \`<!-- NEEDS_INPUT -->\`, or its slug IS in the in-flight set, exit cleanly without commits or PR.+ - **Otherwise**: walk PLAN.md top-to-bottom and pick the FIRST \`- [ ]\` line where ALL of the following are true:+ - The slug is NOT in the in-flight set.+ - The immediately-preceding line does NOT start with \`> ⚠️ DRIFT:\`.+ - The line does NOT carry the \`<!-- NEEDS_INPUT -->\` annotation.+5. **If no eligible item exists**, exit cleanly — that's a healthy plan state, not a failure. Brainstorming is handled by the \`feature-ideas\` task; do NOT add new items here.++Capture the exact text of the selected item (without the leading \`- [ ]\`) verbatim, **including its \`[<slug>]\` ID** — the changelog entry will reuse both.++## Phase 2 — Claim (worktree)++Create the worktree on a branch named \`claim/<slug>\`. This branch name is the claim — once created and pushed, no other agent or \`/claim\` session will pick the same slug. Do all editing inside the worktree, NEVER in the source repo's working tree (which may have the user's in-flight work).++\`\`\`bash+SLUG=<picked-slug>+WORKTREE="data/cos/worktrees/claim-\${SLUG}"+mkdir -p data/cos/worktrees+git fetch origin main+git worktree add -b "claim/\${SLUG}" "\${WORKTREE}" origin/main+cd "\${WORKTREE}"+\`\`\`++Stash the worktree path; you'll need it for Phase 7 cleanup.++## Phase 3 — Verify still valid++Before writing any code, sanity-check that executing the item won't regress newer work. **If ANY of these are true, jump to Phase 3b** (clarification path, not implementation):++- The picked line is preceded by a \`> ⚠️ DRIFT:\` blockquote (you should already have filtered it; double-check).+- The item description references a function, file, or component that no longer exists. Run \`grep -rn\` for the named identifiers — if they're gone, the item is stale.+- The item depends on a predecessor that hasn't shipped (e.g. "Phase B work" when Phase B isn't done).+- The work would require touching files outside the inferred scope (>5 unrelated files), suggesting the item is bigger than originally estimated.++Otherwise: can this be implemented without user clarification (requirements clear, no ambiguous design choices)? If NOT, jump to Phase 3b. If yes, proceed to Phase 4.++## Phase 3b — Request Clarification (alternative exit from Phase 3)++Done from INSIDE the worktree (you've already created \`claim/<slug>\` in Phase 2):++1. Create \`.plan-questions.md\` in the worktree:+ \`\`\`+ # Plan Question: <short title summarizing the PLAN.md item>++ ## PLAN.md Item+ <the exact text of the unchecked item, including its [<slug>]>++ ## Questions+ - <question 1>+ - <question 2>+ \`\`\`+2. **Move the unchecked item to the bottom of PLAN.md and annotate it with \` <!-- NEEDS_INPUT -->\`** — remove from its current position and append at the end with the annotation, **preserving the \`[<slug>]\` ID**. This keeps the queue moving so the next \`plan-task\` run picks a different actionable item.+3. Commit, push the branch (\`git push -u origin claim/<slug>\`), and open a PR with \`gh pr create\` so the user can see the questions. **Do NOT merge** — the user resolves \`.plan-questions.md\` first.+4. Then run the **Phase 3b cleanup** (which differs from Phase 7 — the PR is intentionally unmerged here, so the local branch must NOT be deleted):+ \`\`\`bash+ cd {repoPath}+ git worktree remove "\${WORKTREE}"+ \`\`\`+ Leave the local \`claim/<slug>\` branch alone — \`git branch -d\` will refuse (PR not merged) and \`-D\` would discard work that's still in flight. The branch lives on locally and remotely until the user resolves the questions and the PR merges; \`git branch -d "claim/<slug>"\` becomes safe only after that point.++After Phase 3b runs, **exit** — do NOT proceed to Phase 4. The implementing path resumes only when the user reopens the slug post-clarification.++## Phase 4 — Implement++Write the code, tests, and any docs the item 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.++**Commit messages reference the slug** so the work is grep-able across the changelog, branches, and PR titles:++\`\`\`+<type>([<slug>]): <one-line description>++<optional body>+\`\`\`++Use \`feat:\` / \`fix:\` / \`refactor:\` / \`chore:\` / etc. (The bracketed-scope form \`([<slug>])\` is intentional and matches the project's existing convention — grep \`git log --oneline\` for prior examples. The brackets carry the PLAN.md \`[<slug>]\` ID syntax through to commits, branches, and PRs so a single slug grep finds the whole trail.)++## Phase 5 — Update PLAN.md and the changelog++**Remove the item from PLAN.md outright.** The audit trail for shipped work lives in \`git log\` and the project's changelog (e.g. \`.changelog/NEXT.md\`) — do NOT archive to a \`DONE.md\`, that file has been retired. Do NOT leave a checked \`- [x]\` behind in PLAN.md.++1. Remove the picked \`- [ ]\` line from PLAN.md entirely. If removing it leaves a heading empty, leave the heading alone — section curation is \`do-replan\`'s job.+2. Detect the repo's changelog convention (in this order — pick the first match):+ - \`.changelog/NEXT.md\` (PortOS-style staged-release file)+ - \`CHANGELOG.md\` at repo root with an \`## Unreleased\` or \`## [Unreleased]\` heading+ - any other \`changelog\`-shaped file the repo already maintains (look at recent \`git log\` for examples of where prior entries landed)++ If exactly one is found, append an entry there. Mirror the prose style of recent entries; lead with the slug in brackets so \`git log --grep='<slug>'\` and changelog greps line up:++ \`\`\`markdown+ - **[<slug>] <Title from the PLAN.md line>** — <1–3 sentences on what shipped, key files touched, any caveats>+ \`\`\`++ Remember the exact path you wrote to as \`CHANGELOG_FILE\` — you'll stage it in step 3. If no changelog convention exists, skip the changelog append and leave \`CHANGELOG_FILE\` unset; the commit message + \`git log\` becomes the audit trail.++3. Stage PLAN.md plus the changelog file you actually edited (if any) and commit. **Do NOT use a glob or a swallow-on-failure fallback** — staging the exact file you edited is what keeps the audit trail honest:++ \`\`\`bash+ git add PLAN.md+ [ -n "$CHANGELOG_FILE" ] && git add "$CHANGELOG_FILE"+ git commit -m "docs([<slug>]): remove from PLAN.md and log to changelog"+ \`\`\`++## Phase 6 — Review and ship++The configured reviewers for this task, in order, are \`{reviewers}\`. \`copilot\` waits for GitHub's auto-review; \`claude\` / \`codex\` / \`gemini\` 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>\` (the lone default \`copilot\` needs no flag; multi-reviewer runs may also carry \`--review-stop-on-*\` / \`--reviewer-applies\`).++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. **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 each one, apply the matching handling below before advancing to the next:++ - **\`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 that CLI in headless mode against the PR diff to critique it, apply the fixes, run tests, and re-push. Iterate until the CLI reports no further blocking findings, then advance to the next configured reviewer (or merge if it's the last). Cap at **3 rounds** here — this inline claim flow is intentionally more conservative than the dedicated CoS-spawned review-loop follow-up (which allows up to 10 iterations per reviewer); after 3 rounds, leave the PR for human follow-up.++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:+ \`\`\`bash+ gh pr merge <num> --auto --delete-branch \\+ || gh pr merge <num> --squash --delete-branch \\+ || gh pr merge <num> --merge --delete-branch \\+ || gh pr merge <num> --rebase --delete-branch+ \`\`\`+ \`--auto\` lets GitHub apply the repo's configured default once required checks pass; the explicit-method fallbacks cover repos that disallow auto-merge or restrict to a single method. \`--delete-branch\` removes the remote branch atomically on merge.++## Phase 7 — Clean up (post-merge ONLY)++This phase runs only after the PR was merged via Phase 6. If you exited via Phase 3b instead, you already did the 3b-specific cleanup — do NOT also run Phase 7.++From the **source repo** (cd back to {repoPath} first; you are currently inside the worktree):++\`\`\`bash+cd {repoPath}+git worktree remove "\${WORKTREE}"+git branch -d "claim/\${SLUG}"+\`\`\`++If \`git branch -d\` refuses (the PR squash-merged on GitHub but local doesn't know yet), use \`-D\` — the PR is confirmed merged via Phase 6, so the local branch is genuinely redundant.++**Do NOT \`git pull\` from inside this phase** (no \`--rebase\`, no \`--autostash\`, no plain \`pull\`). The agent's work is already integrated on GitHub via \`gh pr merge\`; pulling locally provides no functional benefit and risks rebasing the user's in-progress branch / shuffling their uncommitted changes through stash if the source repo HEAD happens to be on a tracking feature branch when the agent runs. Leave the user's working tree alone.+_(Phase 3b is defined above, right after Phase 3 — see the "alternative exit from Phase 3" section.)_`],'pr-reviewer': [diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex b0468a0edc..7876ba411e 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -776,6 +776,20 @@ describe('taskSchedule', () => {expect(prompt).toContain('Sentinel body for substitution test.')expect(loadSlashdoFile).toHaveBeenCalledWith('replan', { stripFrontmatter: true })})++ it('plan-task default self-picks like /claim — no scheduler pre-pick / Item Constraint', async () => {+ // The agent picks its own slug at execution time (Phase 1) rather than+ // accepting a slug the scheduler pre-reserved. Pin the absence of the+ // pre-pick scaffolding so a future edit can't quietly reintroduce the+ // dispatch-time reservation race (see cos.js PLAN_SELF_CLAIM_TASK_TYPES).+ const prompt = await getTaskPrompt('plan-task')+ expect(prompt).not.toContain('{planConstraint}')+ expect(prompt).not.toContain('Item Constraint')+ expect(prompt).not.toContain('scheduler pre-reserved')+ // It still drives the /claim flow: in-flight scan + claim/<slug> branch.+ expect(prompt).toContain('claim/<slug>')+ expect(prompt).toContain('in-flight set')+ })})describe('resetExecutionHistory', () => {