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): plan-item ID system for parallel-safe agent work
[._.]/ Adam Eivyace879a8dfbd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2d65916434..15f8a7a344 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,11 @@## Features+### CoS / Scheduled Tasks++- **Plan-item ID system for parallel-safe agent work.** Every `- [ ]` checkbox in a managed app's PLAN.md now carries a stable `[<slug>]` ID, and CoS scheduled `feature-ideas` / `plan-task` jobs encode the slug in their worktree branch name (`cos/<task>/<slug>/<agent>`). Before spawning, the scheduler reads PLAN.md, parses checkboxes, scans `git branch -a` + `gh pr list` for any slug already in flight, and pre-picks the first unclaimed item — concurrent agents now sit on distinct items instead of stomping on the same one. Brainstorm runs (no eligible item) generate a slug at insert time. New helper `server/lib/planIds.js` (slugify + parser + scanner + picker, 17 tests). `taskSchedule.js` prompts bump to feature-ideas v8 / plan-task v4 with a new `{planConstraint}` block; `worktreeManager.createWorktree` accepts `options.planId`; `agentLifecycle.js` plumbs it through both spawn paths. Backed by slashdo v2.15.0 which owns the ID-assignment pass via `do:replan` Phase 0 and preserves slugs across all `do:*` commands that edit PLAN.md.+- **slashdo submodule bumped to v2.15.0.** Brings drift detection in `do:replan` (flags pending items whose execution would regress newer features) and a persistent `Monitor` in `do:rpr` (one stream emits events for new Copilot reviews + CI bucket transitions, replacing the 5+ background subshells that previously accumulated per multi-round review).+### Universe Builder- **Other tab — manual trunk assignment.** Each bucket on the Other tab now has an **Assign to…** menu (Cast / Places / Objects) that retags `categories[bucket].kind` so the bucket moves out of Other into the matching trunk on next render. Variations stay in place; per-variation promote-to-canon remains a separate action.diff --git a/lib/slashdo b/lib/slashdoindex 50011ef25d..90fbd08bac 160000--- a/lib/slashdo+++ b/lib/slashdo@@ -1 +1 @@-Subproject commit 50011ef25d2581145ecd1866d5d79293091b3fd9+Subproject commit 90fbd08bac3ef3a3511dc4323a00a1e591848f7ddiff --git a/server/lib/planIds.js b/server/lib/planIds.jsnew file mode 100644index 0000000000..de04586a50--- /dev/null+++ b/server/lib/planIds.js@@ -0,0 +1,253 @@+/**+ * Plan-item IDs — utilities for giving every `- [ ]` checkbox in PLAN.md a+ * stable slug ID so concurrent agents can claim distinct items by encoding+ * the ID in their worktree branch name (`cos/<task.id>/<planId>/<agentId>`).+ *+ * Public API:+ * - slugify(title, takenIds) → string (deterministic, unique within `takenIds`)+ * - parsePlanItems(markdown) → PlanItem[]+ * - assignMissingIds(markdown, extraIds)→ { content, assigned[] }+ * - extractAllIds(markdown) → string[] (PLAN.md or DONE.md, every `[slug]`)+ * - findInProgressIds(repoPath, ids) → Set<string> (subset present in branch/PR names)+ * - pickFirstAvailable(items, takenIds) → PlanItem | null+ *+ * @typedef {Object} PlanItem+ * @property {number} lineNumber 1-indexed+ * @property {string} indent leading whitespace+ * @property {boolean} checked true for `- [x]`+ * @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+ */++import { execGit } from './execGit.js';+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*-->/;++/**+ * Strip common markdown wrappers from a title fragment.+ * - `**bold**` → `bold`+ * - `~~struck~~` → `struck`+ * - `` `code` `` → `code`+ * - `[text](url)` → `text`+ * - HTML comments → removed+ */+function stripMarkdown(text) {+ return text+ .replace(/<!--[\s\S]*?-->/g, ' ')+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')+ .replace(/`([^`]*)`/g, '$1')+ .replace(/\*\*([^*]+)\*\*/g, '$1')+ .replace(/~~([^~]+)~~/g, '$1')+ .replace(/[*_~]/g, ' ');+}++/**+ * Lowercase + kebab-case a string, ASCII-only, collapse repeats.+ */+function kebab(text) {+ return text+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/-+/g, '-')+ .replace(/^-+|-+$/g, '');+}++/**+ * Truncate a kebab string at the last `-` boundary at or before `max`.+ * Falls back to a hard cut if no boundary exists in range.+ */+function truncateOnBoundary(slug, max) {+ if (slug.length <= max) return slug;+ const cut = slug.lastIndexOf('-', max);+ return (cut > 0 ? slug.slice(0, cut) : slug.slice(0, max)).replace(/-+$/, '');+}++/**+ * Derive a unique slug for `title`, avoiding any string in `takenIds`.+ * Deterministic for the same (title, takenIds) inputs.+ *+ * `takenIds` may be a Set or an array. It is not mutated.+ */+export function slugify(title, takenIds = new Set()) {+ const taken = takenIds instanceof Set ? takenIds : new Set(takenIds);+ const base = truncateOnBoundary(kebab(stripMarkdown(String(title || ''))), SLUG_MAX_LEN) || 'item';+ if (!taken.has(base)) return base;+ // Collision: append -2, -3, ... — keep the suffix inside SLUG_MAX_LEN.+ for (let n = 2; n < 10000; n++) {+ const suffix = `-${n}`;+ const trimmedBase = base.length + suffix.length > SLUG_MAX_LEN+ ? truncateOnBoundary(base, SLUG_MAX_LEN - suffix.length)+ : base;+ const candidate = `${trimmedBase}${suffix}`;+ if (!taken.has(candidate)) return candidate;+ }+ throw new Error(`slugify exhausted collision space for title: ${title}`);+}++/**+ * Parse every `- [ ]` / `- [x]` line in a PLAN.md-style markdown document.+ * Returns one PlanItem per checkbox line, in document order.+ */+export function parsePlanItems(markdown) {+ if (!markdown) return [];+ const lines = markdown.split('\n');+ const items = [];+ for (let i = 0; i < lines.length; i++) {+ const m = CHECKBOX_RE.exec(lines[i]);+ if (!m) continue;+ const { indent, box, id, rest } = m.groups;+ items.push({+ lineNumber: i + 1,+ indent: indent || '',+ checked: box.toLowerCase() === 'x',+ id: id || null,+ rest: rest || '',+ needsInput: NEEDS_INPUT_RE.test(rest || '')+ });+ }+ return items;+}++/**+ * Return every `[slug]` ID that appears in a PLAN.md / DONE.md document.+ * Captures both checkbox-prefixed IDs (parsePlanItems) AND DONE.md archive+ * entries where IDs are embedded inline like `- **[slug] Title**`.+ */+export function extractAllIds(markdown) {+ if (!markdown) return [];+ const ids = new Set();+ for (const item of parsePlanItems(markdown)) {+ if (item.id) ids.add(item.id);+ }+ // Pick up DONE.md-style `[slug]` markers not on checkbox lines.+ // Length range 2–81 chars is intentionally wider than slugify()'s 50-char cap+ // so legacy DONE.md entries with longer slugs are still recognized for the+ // uniqueness check (we never want to re-issue a retired slug).+ const inlineRe = /\[([a-z0-9][a-z0-9-]{1,80})\]/g;+ let m;+ while ((m = inlineRe.exec(markdown)) !== null) {+ // Skip markdown links: `[text](url)` — only count when not immediately followed by `(`+ const after = markdown[m.index + m[0].length];+ if (after === '(') continue;+ ids.add(m[1]);+ }+ return [...ids];+}++/**+ * Assign a slug ID to every `- [ ]` / `- [x]` line that doesn't already have one.+ * Idempotent: existing IDs are preserved verbatim. `extraIds` lets the caller+ * pass IDs from a sibling document (e.g. DONE.md) into the uniqueness check.+ *+ * @param {string} markdown+ * @param {string[]|Set<string>} extraIds+ * @returns {{ content: string, assigned: Array<{ id: string, title: string, lineNumber: number }> }}+ */+export function assignMissingIds(markdown, extraIds = []) {+ if (!markdown) return { content: markdown || '', assigned: [] };+ const taken = new Set([...extractAllIds(markdown), ...extraIds]);+ const lines = markdown.split('\n');+ const assigned = [];+ for (let i = 0; i < lines.length; i++) {+ const m = CHECKBOX_RE.exec(lines[i]);+ if (!m) continue;+ if (m.groups.id) continue;+ const rest = m.groups.rest || '';+ const id = slugify(rest, taken);+ taken.add(id);+ lines[i] = `${m.groups.indent || ''}- [${m.groups.box}] [${id}] ${rest}`;+ assigned.push({ id, title: rest, lineNumber: i + 1 });+ }+ return { content: lines.join('\n'), assigned };+}++/**+ * Pick the first `- [ ]` item that is not checked, not annotated NEEDS_INPUT,+ * not already in flight, and (if `requireId`) carries an ID.+ *+ * @param {PlanItem[]} items+ * @param {Set<string>|string[]} takenIds IDs currently claimed by another agent+ * @param {{ requireId?: boolean }} [options]+ */+export function pickFirstAvailable(items, takenIds = new Set(), options = {}) {+ const taken = takenIds instanceof Set ? takenIds : new Set(takenIds);+ const requireId = options.requireId !== false; // default true+ for (const item of items) {+ if (item.checked) continue;+ if (item.needsInput) continue;+ if (requireId && !item.id) continue;+ if (item.id && taken.has(item.id)) continue;+ return item;+ }+ return null;+}++/**+ * Promise-wrapped `gh pr list` — separated from execGit because `gh` is+ * not always installed on every host. Returns an empty array on any failure.+ */+function listOpenPullRequestHeadRefs(repoPath) {+ return new Promise(resolve => {+ const child = spawn('gh', ['pr', 'list', '--state', 'open', '--json', 'headRefName', '-q', '.[].headRefName'], {+ cwd: repoPath,+ shell: false,+ windowsHide: true+ });+ let out = '';+ let errored = false;+ child.on('error', () => { errored = true; resolve([]); });+ child.stdout.on('data', chunk => { out += chunk.toString(); });+ child.on('close', code => {+ if (errored) return;+ if (code !== 0) return resolve([]);+ resolve(out.split('\n').map(s => s.trim()).filter(Boolean));+ });+ setTimeout(() => { try { child.kill(); } catch { /* noop */ } resolve([]); }, 15000);+ });+}++/**+ * 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.+ *+ * `repoPath` is the repository to query. Best-effort: missing git, missing gh,+ * or fetch failure all degrade silently and return what evidence is available.+ *+ * @param {string} repoPath+ * @param {string[]|Set<string>} knownIds+ * @returns {Promise<Set<string>>}+ */+export async function findInProgressIds(repoPath, knownIds) {+ const known = knownIds instanceof Set ? knownIds : new Set(knownIds);+ if (known.size === 0) return new Set();++ // Best-effort fetch so remote branches are current+ await execGit(['fetch', '--prune'], repoPath).catch(() => {});++ const [branchOutput, prHeadRefs] = await Promise.all([+ execGit(+ ['branch', '-a', '--no-color', '--format=%(refname:short)'],+ repoPath,+ { ignoreExitCode: true }+ ).then(r => r.stdout || '').catch(() => ''),+ listOpenPullRequestHeadRefs(repoPath)+ ]);++ const refs = [+ ...branchOutput.split('\n'),+ ...prHeadRefs+ ].map(s => s.trim()).filter(Boolean);++ 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);+ }+ }+ return inFlight;+}diff --git a/server/lib/planIds.test.js b/server/lib/planIds.test.jsnew file mode 100644index 0000000000..9f9fdee5f0--- /dev/null+++ b/server/lib/planIds.test.js@@ -0,0 +1,159 @@+import { describe, it, expect } from 'vitest';+import {+ slugify,+ parsePlanItems,+ assignMissingIds,+ extractAllIds,+ pickFirstAvailable+} from './planIds.js';++describe('planIds.js', () => {+ describe('slugify', () => {+ it('strips markdown wrappers and produces kebab-case', () => {+ expect(slugify('**Universe Builder redesign — trunks + sub-buckets layout.**'))+ .toBe('universe-builder-redesign-trunks-sub-buckets');+ });++ it('strips inline code and link wrappers', () => {+ expect(slugify('Extract `resolveProviderAndModel({providerId, model})` into `server/lib/promptRunner.js`.'))+ .toBe('extract-resolveproviderandmodel-providerid-model');+ });++ it('strips markdown links to their text', () => {+ expect(slugify('Read [the writer-room doc](./docs/writers-room.md)'))+ .toBe('read-the-writer-room-doc');+ });++ it('truncates at the last dash on or before the 50-char cap', () => {+ const id = slugify('Phase D follow-ups deferred from the Phase D pull request review pass');+ expect(id.length).toBeLessThanOrEqual(50);+ expect(id.endsWith('-')).toBe(false);+ expect(id.startsWith('phase-d-follow-ups')).toBe(true);+ });++ it('returns "item" for an empty / whitespace title', () => {+ expect(slugify(' ')).toBe('item');+ expect(slugify('')).toBe('item');+ });++ it('appends -2, -3 for collisions', () => {+ const taken = new Set(['foo-bar']);+ expect(slugify('Foo Bar', taken)).toBe('foo-bar-2');+ taken.add('foo-bar-2');+ expect(slugify('Foo Bar', taken)).toBe('foo-bar-3');+ });++ it('keeps the collision suffix inside the 50-char cap by trimming the base', () => {+ const taken = new Set(['x'.repeat(50)]);+ const id = slugify('x'.repeat(80), taken);+ expect(id.length).toBeLessThanOrEqual(50);+ expect(id.endsWith('-2')).toBe(true);+ });+ });++ describe('parsePlanItems', () => {+ it('captures checkbox lines, checked state, and existing IDs', () => {+ const md = [+ '## Next Up',+ '- [ ] [foo-bar] **Foo.** Description.',+ '- [x] **Already done.**',+ ' - [ ] Nested sub-item',+ 'Some prose that is not a checkbox',+ '- [ ] Plain item <!-- NEEDS_INPUT -->'+ ].join('\n');++ const items = parsePlanItems(md);+ expect(items).toHaveLength(4);+ expect(items[0]).toMatchObject({ id: 'foo-bar', checked: false, indent: '', lineNumber: 2 });+ expect(items[1]).toMatchObject({ id: null, checked: true, lineNumber: 3 });+ expect(items[2]).toMatchObject({ id: null, checked: false, indent: ' ', lineNumber: 4 });+ expect(items[3].needsInput).toBe(true);+ });++ it('returns empty for empty / non-string input', () => {+ expect(parsePlanItems('')).toEqual([]);+ expect(parsePlanItems(null)).toEqual([]);+ });+ });++ describe('extractAllIds', () => {+ it('collects IDs from checkbox lines AND inline brackets, ignoring markdown links', () => {+ const md = [+ '- [ ] [foo] **Foo.**',+ '- [x] [bar-baz] **Bar Baz.**',+ 'See [doc](./x.md) for the [legacy-thing] reference and [another](./y.md).'+ ].join('\n');+ const ids = extractAllIds(md);+ expect(ids).toEqual(expect.arrayContaining(['foo', 'bar-baz', 'legacy-thing']));+ expect(ids).not.toContain('doc');+ expect(ids).not.toContain('another');+ });+ });++ describe('assignMissingIds', () => {+ it('assigns IDs only to checkbox lines without one; existing IDs are preserved', () => {+ const md = [+ '- [ ] **Add tests.**',+ '- [ ] [keep-me] **Already IDed.**',+ '- [x] **Old work without an ID.**'+ ].join('\n');+ const { content, assigned } = assignMissingIds(md);+ expect(assigned).toHaveLength(2);+ expect(content).toContain('- [ ] [add-tests] **Add tests.**');+ expect(content).toContain('- [ ] [keep-me] **Already IDed.**');+ expect(content).toContain('- [x] [old-work-without-an-id] **Old work without an ID.**');+ });++ it('is idempotent — running twice produces no further changes', () => {+ const md = '- [ ] **Some item.**\n- [ ] **Another item.**';+ const once = assignMissingIds(md);+ const twice = assignMissingIds(once.content);+ expect(twice.content).toBe(once.content);+ expect(twice.assigned).toHaveLength(0);+ });++ it('respects extraIds (e.g. DONE.md) so retired slugs are not reused', () => {+ const planMd = '- [ ] **Foo.**';+ const { content } = assignMissingIds(planMd, ['foo']);+ expect(content).toContain('[foo-2]');+ expect(content).not.toContain('[foo] **Foo.**');+ });++ it('handles two items that would collide within the same document', () => {+ const md = '- [ ] **Foo bar.**\n- [ ] **Foo bar.**';+ const { content, assigned } = assignMissingIds(md);+ expect(assigned.map(a => a.id)).toEqual(['foo-bar', 'foo-bar-2']);+ expect(content).toContain('- [ ] [foo-bar] **Foo bar.**');+ expect(content).toContain('- [ ] [foo-bar-2] **Foo bar.**');+ });+ });++ 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 }+ ];++ it('skips checked, NEEDS_INPUT, and in-flight items', () => {+ const pick = pickFirstAvailable(items, new Set(['c']));+ expect(pick?.id).toBe('d');+ });++ it('returns null when every candidate is filtered', () => {+ const pick = pickFirstAvailable(items, new Set(['c', 'd']));+ expect(pick).toBeNull();+ });++ 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 }],+ new Set(),+ { requireId: false }+ );+ expect(pick?.id).toBeNull();+ });+ });+});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 98c3aec544..1063e43347 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -385,7 +385,8 @@ export async function spawnAgentForTask(task) {worktreeInfo = await createWorktree(agentId, workspacePath, task.id, {baseBranch: detectedBase || undefined,- existingBranch: existingBranch || undefined+ existingBranch: existingBranch || undefined,+ planId: task.metadata?.planId || undefined}).catch(err => {emitLog('warn', `🌳 Worktree creation failed, using shared workspace: ${err.message}`, { taskId: task.id });return null;@@ -414,7 +415,9 @@ export async function spawnAgentForTask(task) {reason: conflictResult.reason});- worktreeInfo = await createWorktree(agentId, workspacePath, task.id).catch(err => {+ worktreeInfo = await createWorktree(agentId, workspacePath, task.id, {+ planId: task.metadata?.planId || undefined+ }).catch(err => {emitLog('warn', `🌳 Worktree creation failed, using shared workspace: ${err.message}`, { taskId: task.id });return null;});diff --git a/server/services/cos.js b/server/services/cos.jsindex 72d770a8da..4de133aed0 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -84,6 +84,48 @@ 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';++// 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']);++/**+ * For feature-ideas / plan-task, read the target repo's PLAN.md (+ DONE.md+ * for the uniqueness set), 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.+ */+async function applyPlanIdMetadata(taskType, repoPath, metadata) {+ if (!PLAN_PICK_TASK_TYPES.has(taskType)) return;+ if (!repoPath) return;+ const [planMd, doneMd] = await Promise.all([+ readFile(join(repoPath, 'PLAN.md'), 'utf-8').catch(() => ''),+ readFile(join(repoPath, 'DONE.md'), 'utf-8').catch(() => '')+ ]);+ if (!planMd) return;+ const items = parsePlanItems(planMd);+ const knownIds = new Set([...extractAllIds(planMd), ...extractAllIds(doneMd)]);+ const inFlight = await findInProgressIds(repoPath, knownIds).catch(() => new Set());+ const pick = pickFirstAvailable(items, inFlight);+ if (pick?.id) metadata.planId = pick.id;+}++/**+ * Build the `{planConstraint}` substitution block. Empty when no planId —+ * the prompt's existing Phase 1 fallback (brainstorm or exit-clean) takes over.+ */+function buildPlanConstraintBlock(planId) {+ if (!planId) return '';+ return `+## Item Constraint++The scheduler has reserved PLAN.md item \`[${planId}]\` for you. You MUST work on that exact item — do not pick a different one, do not brainstorm. If the line is missing from PLAN.md, has already been checked, or carries \`<!-- NEEDS_INPUT -->\`, exit cleanly without commits or PR.+`;+}/*** Get current CoS status@@ -1847,13 +1889,17 @@ async function generateManagedAppImprovementTask(app, state) {initializePipelineMetadata(metadata);if (shouldSkipForPrecondition(metadata, app, nextType)) return null;+ await applyPlanIdMetadata(nextType, app.repoPath, metadata);+ const planConstraintBlock = buildPlanConstraintBlock(metadata.planId);+const promptTemplate = metadata.pipeline?.stages? await taskSchedule.getStagePrompt(nextType, 0): await taskSchedule.getTaskPrompt(nextType);const description = promptTemplate.replace(/\{appName\}/g, app.name).replace(/\{repoPath\}/g, app.repoPath)- .replace(/\{appId\}/g, app.id);+ .replace(/\{appId\}/g, app.id)+ .replace(/\{planConstraint\}/g, () => planConstraintBlock);applyAppWorktreeDefault(metadata, app);@@ -1974,6 +2020,9 @@ async function generateManagedAppImprovementTaskForType(taskType, app, state, {referenceDataBlock = blocks.join('\n\n---\n\n');}+ await applyPlanIdMetadata(taskType, app.repoPath, metadata);+ const planConstraintBlock = buildPlanConstraintBlock(metadata.planId);+const description = promptTemplate.replace(/\{appName\}/g, app.name).replace(/\{repoPath\}/g, app.repoPath)@@ -1982,7 +2031,8 @@ async function generateManagedAppImprovementTaskForType(taskType, app, state, {// interprets `$&`, `$1`, etc. as backreferences. Commit subjects/authors// legitimately contain `$` (env-var docs, prices, awk snippets) and// would get mangled. The function form passes the value verbatim.- .replace(/\{referenceData\}/g, () => referenceDataBlock);+ .replace(/\{referenceData\}/g, () => referenceDataBlock)+ .replace(/\{planConstraint\}/g, () => planConstraintBlock);applyAppWorktreeDefault(metadata, app);diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex e9ece6e29b..a100ff1960 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -330,45 +330,46 @@ Use Playwright MCP to test the app at different viewport sizes:Your goal is to implement the next planned item from PLAN.md, or brainstorm a new feature if no plan exists.Repository: {repoPath}-+{planConstraint}## Phase 1 — Find the Next Task1. Read PLAN.md from {repoPath}2. Read DONE.md from {repoPath} (if it exists) to understand what has already been implemented-3. If PLAN.md does not exist, is empty, or has no unchecked items (\`- [ ]\`), go to **Phase 4 — Brainstorm**.-4. Find the first unchecked item (\`- [ ]\`) that does NOT have a \`<!-- NEEDS_INPUT -->\` annotation-5. If all unchecked items have \`<!-- NEEDS_INPUT -->\`, go to **Phase 4 — Brainstorm**.+3. If the **Item Constraint** block above named a specific \`[plan-id]\`, find the matching \`- [ ]\` line and use that — do NOT pick a different one, do NOT brainstorm. If the line is missing, has been checked, or carries \`<!-- NEEDS_INPUT -->\`, exit cleanly without commits or PR.+4. Otherwise, if PLAN.md does not exist, is empty, or has no unchecked items (\`- [ ]\`), go to **Phase 4 — Brainstorm**.+5. Otherwise, find the first unchecked item (\`- [ ]\`) that does NOT have a \`<!-- NEEDS_INPUT -->\` annotation.+6. If all unchecked items have \`<!-- NEEDS_INPUT -->\`, go to **Phase 4 — Brainstorm**.## Phase 2 — Evaluate Feasibility-6. Read relevant source files to understand the scope of the item-7. Determine: can this be implemented without user clarification?+7. Read relevant source files to understand the scope of the item+8. Determine: can this be implemented without user clarification?- Consider: are requirements clear? Are there ambiguous design choices? Does it depend on external decisions?## Phase 3a — Implement (if feasible)-8. Implement the feature:+9. Implement the feature:- Write clean, tested code following existing patterns- Run tests to ensure nothing is broken-9. Run \`/simplify\` to review changed code for reuse, quality, and efficiency. Fix any issues found.-10. Check the PLAN.md item: change \`- [ ]\` to \`- [x]\`-11. Commit with a clear description referencing the PLAN.md item+10. Run \`/simplify\` to review changed code for reuse, quality, and efficiency. Fix any issues found.+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## Phase 3b — Request Clarification (if not feasible)-8. Create a file named \`.plan-questions.md\` in the repository root with this format:+9. Create a file named \`.plan-questions.md\` in the repository root with this format:\`\`\`# Plan Question: <short title summarizing the PLAN.md item>## PLAN.md Item- <the exact text of the unchecked item>+ <the exact text of the unchecked item, including its [plan-id]>## Questions- <question 1>- <question 2>\`\`\`-9. **Move the unchecked item to the bottom of PLAN.md and annotate it with \` <!-- NEEDS_INPUT -->\`** — remove the line from its current position and append it at the end of the file with the annotation. This keeps the queue moving so the next \`feature-ideas\` run picks up a different actionable item instead of repeatedly tripping on this one.-10. Commit both changes (the new \`.plan-questions.md\` file and the PLAN.md move) with message \`chore: flag PLAN.md item needing user input\`. Then proceed to the **Completion** section below so the clarification PR is opened for the user to review — do NOT leave the worktree orphaned.+10. **Move the unchecked item to the bottom of PLAN.md and annotate it with \` <!-- NEEDS_INPUT -->\`** — remove the line from its current position and append it at the end of the file with the annotation, **preserving its \`[plan-id]\` slug**. This keeps the queue moving so the next \`feature-ideas\` run picks up a different actionable item instead of repeatedly tripping on this one.+11. Commit both changes (the new \`.plan-questions.md\` file and the PLAN.md move) with message \`chore: flag PLAN.md item needing user input\`. Then proceed to the **Completion** section below so the clarification PR is opened for the user to review — do NOT leave the worktree orphaned.## Phase 4 — Brainstorm a New Feature@@ -388,23 +389,24 @@ When PLAN.md is missing, empty, or fully completed, brainstorm and implement a n- Write clean, tested code following existing patterns- Run tests to ensure nothing is broken6. Run \`/simplify\` to review changed code for reuse, quality, and efficiency. Fix any issues found.-7. Add the feature as a checked item in PLAN.md (create the file if needed):+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 and DONE.md):\`\`\`- - [x] <description of the feature you implemented>+ - [x] [<slug-of-feature>] <description of the feature you implemented>\`\`\`8. Commit with a clear description of the feature and rationale`,'plan-task': `[Plan Task: {appName}] Execute Next PLAN.md ItemImplement the next unchecked item from PLAN.md and archive it to DONE.md. No brainstorming, no scope expansion — just execute what is already planned.-+{planConstraint}## Phase 1 — Find the Next Task1. Read PLAN.md and DONE.md (if present, for archive-format reference).-2. Pick the first unchecked item (\`- [ ]\`) that does NOT have a \`<!-- NEEDS_INPUT -->\` annotation.-3. If PLAN.md is missing, has no unchecked items, or every unchecked item is annotated \`<!-- NEEDS_INPUT -->\`, **stop here** — exit cleanly without commits or PR. Brainstorming is handled by the \`feature-ideas\` task.+2. If the **Item Constraint** block above named a specific \`[plan-id]\`, find the matching \`- [ ]\` line and use that — do NOT pick a different one. If the line is missing, has been checked, or carries \`<!-- NEEDS_INPUT -->\`, exit cleanly without commits or PR.+3. Otherwise pick the first unchecked item (\`- [ ]\`) that does NOT have a \`<!-- NEEDS_INPUT -->\` annotation.+4. If PLAN.md is missing, has no unchecked items, or every unchecked item is annotated \`<!-- NEEDS_INPUT -->\`, **stop here** — exit cleanly without commits or PR. Brainstorming is handled by the \`feature-ideas\` task.-Capture the exact text of the selected item (without the leading \`- [ ]\`) verbatim — DONE.md will reuse it.+Capture the exact text of the selected item (without the leading \`- [ ]\`) verbatim, **including its \`[plan-id]\` slug** — DONE.md will reuse both.## Phase 2 — Decide@@ -416,7 +418,7 @@ Read relevant source files. Can this be implemented without user clarification (2. **Move the item from PLAN.md to DONE.md (do NOT leave a checked \`- [x]\` behind in PLAN.md):**- Remove the item's line(s) from PLAN.md entirely. If removing it leaves a heading empty, leave the heading alone — plan curation is the \`do-replan\` task's job.- Append the entry to DONE.md under today's date heading (\`## YYYY-MM-DD\`). Insert today's heading directly below the top-of-file preamble if it doesn't exist yet.- - Entry format: \`- **<short title from the PLAN.md item>** — <1–3 sentences on what was implemented, key files touched, and any caveats>\`. Mirror the prose style of recent DONE.md entries.+ - Entry format: \`- **[<plan-id>] <short title from the PLAN.md item>** — <1–3 sentences on what was implemented, key files touched, and any caveats>\`. The \`[plan-id]\` MUST match the slug from the PLAN.md line. Mirror the prose style of recent DONE.md entries.## Phase 3b — Request Clarification (if not feasible)@@ -425,13 +427,13 @@ Read relevant source files. Can this be implemented without user clarification (# Plan Question: <short title summarizing the PLAN.md item>## PLAN.md Item- <the exact text of the unchecked item>+ <the exact text of the unchecked item, including its [plan-id]>## 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. This keeps the queue moving so the next \`plan-task\` run picks up a different actionable item.`,+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 \`[plan-id]\` slug**. This keeps the queue moving so the next \`plan-task\` run picks up a different actionable item.`,'code-reviewer-review': `[Review: {appName}] Deep Codebase Review (Stage 1)@@ -1062,8 +1064,8 @@ For each reference above:// Prompt versions — bump when a default prompt changes so existing instances auto-upgrade.// Only non-customized prompts (promptCustomized !== true) are upgraded.const PROMPT_VERSIONS = {- 'feature-ideas': 7, // v7: Phase 3b reorders item to bottom + commits clarification PR instead of orphaning the worktree- 'plan-task': 3, // v3: drop Constraints section + {repoPath} refs + commit/simplify steps already covered by the Completion Workflow+ 'feature-ideas': 8, // v8: plan-item ID system — {planConstraint} placeholder, preserve [slug] on edits, brainstorm path generates a new slug+ 'plan-task': 4, // v4: plan-item ID system — {planConstraint} placeholder, DONE.md archive entry prefixed with [plan-id]'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)@@ -1302,6 +1304,75 @@ Repository: {repoPath}When PLAN.md is missing, empty, or fully completed, brainstorm and implement a new feature:+1. Read GOALS.md from {repoPath} for context on the app's goals and priorities.+ If no GOALS.md exists, focus on general improvements.+2. Read DONE.md from {repoPath} (if it exists) to avoid re-implementing completed features+3. Review the codebase structure, recent git log, and any README or docs to understand the app+4. Identify ONE small, high-impact feature that:+ - Aligns with GOALS.md priorities (if available)+ - Is NOT already in DONE.md (avoid re-implementing shipped features)+ - Saves user time, improves UX, or makes the app more useful+ - Is self-contained and completable in one session+ - Does NOT duplicate existing functionality+5. 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.+7. Add the feature as a checked item in PLAN.md (create the file if needed):+ \`\`\`+ - [x] <description of the feature you implemented>+ \`\`\`+8. Commit with a clear description of the feature and rationale`,+ // v7 default prompt (before plan-item ID system)+ `[Improvement: {appName}] Implement Next Planned Feature++Your goal is to implement the next planned item from PLAN.md, or brainstorm a new feature if no plan exists.++Repository: {repoPath}++## Phase 1 — Find the Next Task++1. Read PLAN.md from {repoPath}+2. Read DONE.md from {repoPath} (if it exists) to understand what has already been implemented+3. If PLAN.md does not exist, is empty, or has no unchecked items (\`- [ ]\`), go to **Phase 4 — Brainstorm**.+4. Find the first unchecked item (\`- [ ]\`) that does NOT have a \`<!-- NEEDS_INPUT -->\` annotation+5. If all unchecked items have \`<!-- NEEDS_INPUT -->\`, go to **Phase 4 — Brainstorm**.++## Phase 2 — Evaluate Feasibility++6. Read relevant source files to understand the scope of the item+7. Determine: can this be implemented without user clarification?+ - Consider: are requirements clear? Are there ambiguous design choices? Does it depend on external decisions?++## Phase 3a — Implement (if feasible)++8. Implement the feature:+ - Write clean, tested code following existing patterns+ - Run tests to ensure nothing is broken+9. Run \`/simplify\` to review changed code for reuse, quality, and efficiency. Fix any issues found.+10. Check the PLAN.md item: change \`- [ ]\` to \`- [x]\`+11. Commit with a clear description referencing the PLAN.md item++## Phase 3b — Request Clarification (if not feasible)++8. Create a file named \`.plan-questions.md\` in the repository root with this format:+ \`\`\`+ # Plan Question: <short title summarizing the PLAN.md item>++ ## PLAN.md Item+ <the exact text of the unchecked item>++ ## Questions+ - <question 1>+ - <question 2>+ \`\`\`+9. **Move the unchecked item to the bottom of PLAN.md and annotate it with \` <!-- NEEDS_INPUT -->\`** — remove the line from its current position and append it at the end of the file with the annotation. This keeps the queue moving so the next \`feature-ideas\` run picks up a different actionable item instead of repeatedly tripping on this one.+10. Commit both changes (the new \`.plan-questions.md\` file and the PLAN.md move) with message \`chore: flag PLAN.md item needing user input\`. Then proceed to the **Completion** section below so the clarification PR is opened for the user to review — do NOT leave the worktree orphaned.++## Phase 4 — Brainstorm a New Feature++When PLAN.md is missing, empty, or fully completed, brainstorm and implement a new feature:+1. Read GOALS.md from {repoPath} for context on the app's goals and priorities.If no GOALS.md exists, focus on general improvements.2. Read DONE.md from {repoPath} (if it exists) to avoid re-implementing completed features@@ -1321,6 +1392,47 @@ When PLAN.md is missing, empty, or fully completed, brainstorm and implement a n- [x] <description of the feature you implemented>\`\`\`8. Commit with a clear description of the feature and rationale`+ ],+ 'plan-task': [+ // v3 default prompt (before plan-item ID system)+ `[Plan Task: {appName}] Execute Next PLAN.md Item++Implement the next unchecked item from PLAN.md and archive it to DONE.md. No brainstorming, no scope expansion — just execute what is already planned.++## Phase 1 — Find the Next Task++1. Read PLAN.md and DONE.md (if present, for archive-format reference).+2. Pick the first unchecked item (\`- [ ]\`) that does NOT have a \`<!-- NEEDS_INPUT -->\` annotation.+3. If PLAN.md is missing, has no unchecked items, or every unchecked item is annotated \`<!-- NEEDS_INPUT -->\`, **stop here** — exit cleanly without commits or PR. Brainstorming is handled by the \`feature-ideas\` task.++Capture the exact text of the selected item (without the leading \`- [ ]\`) verbatim — DONE.md will reuse it.++## Phase 2 — Decide++Read relevant source files. Can this be implemented without user clarification (requirements clear, no ambiguous design choices, no blocking external decisions)?++## Phase 3a — Implement (if feasible)++1. Implement the change. Write clean, tested code following existing patterns and run tests.+2. **Move the item from PLAN.md to DONE.md (do NOT leave a checked \`- [x]\` behind in PLAN.md):**+ - Remove the item's line(s) from PLAN.md entirely. If removing it leaves a heading empty, leave the heading alone — plan curation is the \`do-replan\` task's job.+ - Append the entry to DONE.md under today's date heading (\`## YYYY-MM-DD\`). Insert today's heading directly below the top-of-file preamble if it doesn't exist yet.+ - Entry format: \`- **<short title from the PLAN.md item>** — <1–3 sentences on what was implemented, key files touched, and any caveats>\`. Mirror the prose style of recent DONE.md entries.++## Phase 3b — Request Clarification (if not feasible)++1. Create \`.plan-questions.md\`:+ \`\`\`+ # Plan Question: <short title summarizing the PLAN.md item>++ ## PLAN.md Item+ <the exact text of the unchecked item>++ ## 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. This keeps the queue moving so the next \`plan-task\` run picks up a different actionable item.`],'pr-reviewer': [// v1 default prompt (required global slash-do install)diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex a0fb48becc..15d96be578 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -38,6 +38,7 @@ const AUTO_GENERATED_LOCKFILES = ['package-lock.json', 'yarn.lock', 'pnpm-lock.y* @param {object} options - Optional configuration* @param {string} options.baseBranch - Branch to base the worktree on (auto-detected if omitted)* @param {string} options.existingBranch - Pre-existing branch to attach (creates from origin/<branch> if no local copy)+ * @param {string} options.planId - PLAN.md item slug ID — when provided, spliced into the branch name as `cos/<taskId>/<planId>/<agentId>` so other agents can detect this item is in flight by scanning branches/PRs* @returns {{ worktreePath: string, branchName: string, baseBranch: string|null, existingBranch?: boolean }} paths for the new worktree*/export async function createWorktree(agentId, sourceWorkspace, taskId, options = {}) {@@ -79,7 +80,9 @@ export async function createWorktree(agentId, sourceWorkspace, taskId, options =return { worktreePath, branchName, baseBranch: null, existingBranch: true };}- const branchName = `cos/${taskId}/${agentId}`;+ const branchName = options.planId+ ? `cos/${taskId}/${options.planId}/${agentId}`+ : `cos/${taskId}/${agentId}`;// Determine the base: explicit option > remote default branch > current HEADlet baseBranch = options.baseBranch;diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 4efc1d3236..aa715ae409 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -7,8 +7,10 @@ import { join } from 'path';*/describe('Worktree Branch Naming', () => {- function buildBranchName(taskId, agentId) {- return `cos/${taskId}/${agentId}`;+ function buildBranchName(taskId, agentId, planId) {+ return planId+ ? `cos/${taskId}/${planId}/${agentId}`+ : `cos/${taskId}/${agentId}`;}it('should include task ID and agent ID', () => {@@ -25,6 +27,16 @@ describe('Worktree Branch Naming', () => {const branch = buildBranchName('sys-001', 'agent-00000001');expect(branch).toBe('cos/sys-001/agent-00000001');});++ it('should splice planId between taskId and agentId when provided', () => {+ const branch = buildBranchName('task-abc', 'agent-xyz', 'extract-resolve-provider-helper');+ expect(branch).toBe('cos/task-abc/extract-resolve-provider-helper/agent-xyz');+ });++ it('should fall back to the two-segment form when planId is empty', () => {+ expect(buildBranchName('task-abc', 'agent-xyz', '')).toBe('cos/task-abc/agent-xyz');+ expect(buildBranchName('task-abc', 'agent-xyz', undefined)).toBe('cos/task-abc/agent-xyz');+ });});describe('Worktree Path Construction', () => {