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
route branch-reconcile sub-agents by their issue's model:/effort: labels (#6373)
[._.]/ Adam Eivy3593a12edde8
diff --git a/server/lib/README.md b/server/lib/README.mdindex 20101255fe..a8b705df43 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -484,7 +484,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `assetRoutePrefixes.js` | Import-free leaf holding the URL prefixes the server owns: `ASSET_ROUTE_PREFIXES` (every `/data/**` static mount) and `SERVER_OWNED_PREFIXES` (what must never reach the SPA fallback, each with the exact `spaPaths` that ARE client routes). `scripts/dev-proxy-drift.test.js` checks the dev proxy's `^/data/` wildcard against the mounts, pins the route-registration order in `server/index.js` (a router added below the terminators is shadowed), and fails if a client route — from `NAV_COMMANDS` or `App.jsx`'s nested `<Route>` tree — is ever added under a server-owned prefix without being declared. || `asyncMutex.js` | Promise-based async mutex. || `concurrencyGate.js` | `createConcurrencyGate(limit)` → `run(fn)` — cap on simultaneous async work for ONE module-scoped budget, released FIFO. Sibling to `mapWithConcurrency.js`, which caps in-flight work *within one array map*; a gate is shared state, so several call sites fanning out at the same remote respect one budget instead of each respecting its own while the host sees the sum. `createMutex` (`asyncMutex.js`) is this with `limit` fixed at 1 — prefer it for mutual exclusion. Note the budget is per-MODULE, not per-host: two modules calling one host each get their own gate. Used by `huggingFaceCatalog.js` (4) and `ollamaRegistryCatalog.js` (16), whose cold catalog-enrichment bursts otherwise arrive at a free public API as a thundering herd — which the Hub answers with an HTTP/2 GOAWAY that surfaces as a bare `fetch failed`. |-| `dispatchLabels.js` | slashdo dispatch-hint contract: `model:light/medium/heavy` + `effort:low/medium/high/xhigh/max` vocabulary, prescribed forge colors, validation (`normalizeDispatchModel` / `normalizeDispatchEffort`), GitHub/GitLab vs Jira label formatting, optional contributor labels (`good first issue` / `help wanted`, never implied by `model:light`, and released at claim time by `formatContributorLabelReleaseCommands` — one best-effort command per label, since a forge fails the whole edit when a named label is absent), the one shared volunteer-claim policy (`volunteerClaimLabels` / `formatVolunteerClaimCommands` — a human comment claiming an unassigned issue is resolved by BOTH issueWatcher.js's deterministic pass and the claim prompt's Phase 1 handoff, so both stamp `in-progress` and retire the invitations rather than writing opposite state), the open-ended planner-attribution axis (`planner:<model>`, `normalizePlannerId` / `resolvePlannerId` / `formatPlannerLabelGuidance` — records WHICH model wrote the plan, prefix-matched by `dispatchLabelSpec` so it lazily creates like the fixed labels; a filing agent takes the value from its prompt, never from self-identification), the workflow-state markers (`EPIC_LABEL`/`EPIC_DECOMPOSED_LABEL` and `IN_PROGRESS_LABEL` — state, not hints: shared with perpetualWork.js#isActionableIssue, issueReconcile.js's zombie scan, issueWatcher.js's volunteer assignment, and the claim prompts), lazy-create command text, the optional `--label` slots a rendered `issue create` example offers (`OPTIONAL_ISSUE_LABEL_FLAG_SLOTS` / `formatOptionalIssueLabelFlags` — one list so a new axis reaches every prompt template's copy-pasteable command, not just its prose), and shared dispatch plus issue-quality guidance (`ISSUE_QUALITY_GUIDANCE`, `DISPATCH_HINT_GUIDANCE`, `JIRA_DISPATCH_HINT_GUIDANCE`, plus the consumer-side pair `DISPATCH_HINT_READING_GUIDANCE` / `DISPATCH_HINT_FANOUT_GUIDANCE` — what the labels mean to an agent that RECEIVES them (the preloaded `open-issues` task data input) and, for an orchestrator only, how to route each sub-agent by its own issue (the swarm block); the fan-out form is the reading form plus one line, never a second copy of the vocabulary). Omit an unjustified axis; never invent `medium`; reject future-only/speculative work while keeping useful current refactors claimable. Consumed by work-tracker instructions, quota-burn audits, Layered Intelligence filing, and claim follow-up prompts. |+| `dispatchLabels.js` | slashdo dispatch-hint contract: `model:light/medium/heavy` + `effort:low/medium/high/xhigh/max` vocabulary, prescribed forge colors, validation (`normalizeDispatchModel` / `normalizeDispatchEffort`), the read-side inverse (`dispatchHintFromLabels` — recovers `{model, effort}` from a raw label-name list, used by branch-reconcile's per-branch routing hint), GitHub/GitLab vs Jira label formatting, optional contributor labels (`good first issue` / `help wanted`, never implied by `model:light`, and released at claim time by `formatContributorLabelReleaseCommands` — one best-effort command per label, since a forge fails the whole edit when a named label is absent), the one shared volunteer-claim policy (`volunteerClaimLabels` / `formatVolunteerClaimCommands` — a human comment claiming an unassigned issue is resolved by BOTH issueWatcher.js's deterministic pass and the claim prompt's Phase 1 handoff, so both stamp `in-progress` and retire the invitations rather than writing opposite state), the open-ended planner-attribution axis (`planner:<model>`, `normalizePlannerId` / `resolvePlannerId` / `formatPlannerLabelGuidance` — records WHICH model wrote the plan, prefix-matched by `dispatchLabelSpec` so it lazily creates like the fixed labels; a filing agent takes the value from its prompt, never from self-identification), the workflow-state markers (`EPIC_LABEL`/`EPIC_DECOMPOSED_LABEL` and `IN_PROGRESS_LABEL` — state, not hints: shared with perpetualWork.js#isActionableIssue, issueReconcile.js's zombie scan, issueWatcher.js's volunteer assignment, and the claim prompts), lazy-create command text, the optional `--label` slots a rendered `issue create` example offers (`OPTIONAL_ISSUE_LABEL_FLAG_SLOTS` / `formatOptionalIssueLabelFlags` — one list so a new axis reaches every prompt template's copy-pasteable command, not just its prose), and shared dispatch plus issue-quality guidance (`ISSUE_QUALITY_GUIDANCE`, `DISPATCH_HINT_GUIDANCE`, `JIRA_DISPATCH_HINT_GUIDANCE`, plus the consumer-side pair `DISPATCH_HINT_READING_GUIDANCE` / `DISPATCH_HINT_FANOUT_GUIDANCE` — what the labels mean to an agent that RECEIVES them (the preloaded `open-issues` task data input) and, for an orchestrator only, how to route each sub-agent by its own issue (the swarm block); the fan-out form is the reading form plus one line, never a second copy of the vocabulary). Omit an unjustified axis; never invent `medium`; reject future-only/speculative work while keeping useful current refactors claimable. Consumed by work-tracker instructions, quota-burn audits, Layered Intelligence filing, and claim follow-up prompts. || `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). Also `CREATIVE_DOMAIN`/`getCreativeAutonomyMode(config)` (#2183) — the Creative Director orchestrator domain, kept out of `DOMAIN_IDS` and defaulting to mirror the `cos` mode. || `domainBudgets.js` | Per-domain daily autonomy budgets (pure). `BUDGET_LIMIT_FIELDS` (`maxActionsPerDay`/`maxMinutesPerDay`), `getDomainBudget(config, id)`, `normalizeDomainBudgets(raw)`, `hasBudget(budget)`, and `evaluateBudget(budget, usage)` → `{ withinBudget, exceeded }`. A `null`/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in `services/domainUsage.js`. || `eidoverseWorldDesign.js` | Immutable Eidoverse World Design V1/V2/V3 registry, override migration, semantic districts, 48-signal ceiling, and install-local asset locks for PortOS Commons. |diff --git a/server/lib/dispatchLabels.js b/server/lib/dispatchLabels.jsindex b3776a85f2..874f081d5a 100644--- a/server/lib/dispatchLabels.js+++ b/server/lib/dispatchLabels.js@@ -285,6 +285,28 @@ export function normalizeDispatchEffort(value) {return isDispatchEffort(value) ? value : null;}+/**+ * Recover `{ model, effort }` from a raw forge label-name list — the read side+ * of `forgeDispatchLabels`. Used by any consumer (branch-reconcile's per-branch+ * routing hint, a future one) that reads an issue's labels back OFF the forge+ * rather than writing them. Each `model:<tier>` / `effort:<level>` label is+ * validated through the same `normalizeDispatchModel` / `normalizeDispatchEffort`+ * the write side uses, so a foreign or stale label (`model:huge`) reads as+ * absent rather than being misreported. Non-dispatch labels are ignored.+ * @param {string[]} labels - plain label names (e.g. from `gh issue view --json labels`, mapped to `.name`)+ * @returns {{ model: string|null, effort: string|null }}+ */+export function dispatchHintFromLabels(labels) {+ let model = null;+ let effort = null;+ for (const label of Array.isArray(labels) ? labels : []) {+ if (typeof label !== 'string') continue;+ if (label.startsWith('model:')) model = normalizeDispatchModel(label.slice('model:'.length)) || model;+ else if (label.startsWith('effort:')) effort = normalizeDispatchEffort(label.slice('effort:'.length)) || effort;+ }+ return { model, effort };+}+/*** Forge (GitHub/GitLab) label name for one axis, or null when the value is* unrecognized. `axis` is `'model'` or `'effort'`.diff --git a/server/lib/dispatchLabels.test.js b/server/lib/dispatchLabels.test.jsindex 601cdb23a3..90398dd231 100644--- a/server/lib/dispatchLabels.test.js+++ b/server/lib/dispatchLabels.test.js@@ -24,6 +24,7 @@ import {jiraDispatchLabel,forgeDispatchLabels,jiraDispatchLabels,+ dispatchHintFromLabels,forgeContributorLabels,jiraContributorLabels,forgeIssueLabels,@@ -115,6 +116,24 @@ describe('forge vs Jira label formatting', () => {});});+describe('dispatchHintFromLabels', () => {+ it('recovers both axes from a raw label-name list, ignoring unrelated labels', () => {+ expect(dispatchHintFromLabels(['model:heavy', 'effort:max', 'area:cos-agents']))+ .toEqual({ model: 'heavy', effort: 'max' });+ });++ it('reports each missing axis as null rather than guessing', () => {+ expect(dispatchHintFromLabels(['model:light'])).toEqual({ model: 'light', effort: null });+ expect(dispatchHintFromLabels(['bug', 'plan'])).toEqual({ model: null, effort: null });+ expect(dispatchHintFromLabels([])).toEqual({ model: null, effort: null });+ expect(dispatchHintFromLabels(undefined)).toEqual({ model: null, effort: null });+ });++ it('treats an unrecognized axis value as absent, not as a misread', () => {+ expect(dispatchHintFromLabels(['model:huge', 'effort:max'])).toEqual({ model: null, effort: 'max' });+ });+});+describe('label specs and CLI formatting', () => {it('returns a spec only for known dispatch labels', () => {expect(dispatchLabelSpec('model:light')).toEqual({diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex 32fc575839..a506ac14ae 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -27,7 +27,8 @@ import { getBranches, getDefaultBranch, isBranchMergedInto, deleteBranch } fromimport { execGit } from '../lib/execGit.js';import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, reapMergedWorktrees } from './worktreeManager.js';import { isAgentWorktreeId, worktreeOwnershipReason, worktreeHoldExpiresAt } from '../lib/worktreeOwnership.js';-import { execGh, ensureForgeReachable } from './github.js';+import { execGh, ensureForgeReachable, getIssueDispatchHint } from './github.js';+import { issueNumberFromRef } from './issueReconcile.js';import { getOriginInfo } from '../lib/gitRemote.js';import { githubRepoSpec, githubApiHost } from '../lib/workTracker.js';import { safeJSONParse, PATHS } from '../lib/fileUtils.js';@@ -1447,14 +1448,35 @@ export function limitBranchesForAgent(inFlight, branchesPerAgent) {return inFlight.slice(0, branchesPerAgent);}+/**+ * The recommended `model:`/`effort:` line for one issue-derived branch, or ''+ * when the branch is not issue-derived, the issue carries neither label, or+ * the forge read fails. A failed read must never block or reshape+ * reconciliation — `getIssueDispatchHint` already collapses every failure mode+ * to `status: 'unavailable'`, so this just omits the line for that branch.+ * @param {string} branchName+ * @param {string} [repoPath] - repo dir gh resolves the remote from+ * @returns {Promise<string>}+ */+async function dispatchHintLineForBranch(branchName, repoPath) {+ const issueNumber = issueNumberFromRef(branchName);+ if (!issueNumber) return '';+ const hint = await getIssueDispatchHint(issueNumber, { cwd: repoPath }).catch(() => ({ status: 'unavailable', model: null, effort: null }));+ if (hint.status !== 'known' || (!hint.model && !hint.effort)) return '';+ const parts = [hint.model ? `model:${hint.model}` : null, hint.effort ? `effort:${hint.effort}` : null].filter(Boolean);+ return `- Recommended dispatch (issue #${issueNumber}'s labels): ${parts.join(', ')} — run this branch's work at that capability/effort.`;+}+/*** Render the actionable in-flight branch set into the coordinator prompt body- * (injected as `{inFlightBranches}`).+ * (injected as `{inFlightBranches}`). Async because each issue-derived branch+ * gets one forge read for its issue's `model:`/`effort:` labels — see+ * `dispatchHintLineForBranch`.* @param {object[]} inFlight - actionable branches (post-filterActionable)- * @param {{ defaultBranch:string, actions:object, branchesPerAgent?:number }} ctx- * @returns {string}+ * @param {{ defaultBranch:string, actions:object, branchesPerAgent?:number, repoPath?:string }} ctx+ * @returns {Promise<string>}*/-export function formatInFlightForPrompt(inFlight, { defaultBranch, actions, branchesPerAgent } = {}) {+export async function formatInFlightForPrompt(inFlight, { defaultBranch, actions, branchesPerAgent, repoPath } = {}) {const lines = [`Default branch: \`${defaultBranch}\`. Branches to reconcile (${inFlight.length}):`, ''];if (Number.isInteger(branchesPerAgent) && branchesPerAgent > 0) {lines.splice(1, 0, `This coordinator run is limited to up to ${branchesPerAgent} branch(es); finish every branch listed below before reporting done.`);@@ -1477,6 +1499,8 @@ export function formatInFlightForPrompt(inFlight, { defaultBranch, actions, branif (b.collisionPaths?.length) {lines.push(`- Also changed on \`${defaultBranch}\` since this branch diverged (**read these first — they are where supersession shows up**): ${b.collisionPaths.map((p) => `\`${p}\``).join(', ')}`);}+ const dispatchLine = await dispatchHintLineForBranch(b.branch, repoPath);+ if (dispatchLine) lines.push(dispatchLine);lines.push(`- Do: ${desiredEndState(b.state, actions, {prNumber: b.openPr?.number,worktreePath: b.worktreePath,diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex 4786241a24..cde64dbdb3 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -49,9 +49,11 @@ vi.mock('node:fs/promises', () => ({stat: vi.fn(async () => ({ mtimeMs: worktreeMtimeMs })),}));const ensureForgeReachableMock = vi.fn(async () => ({ ok: true, status: 'ok', detail: null, remedy: null }));+const getIssueDispatchHintMock = vi.fn(async () => ({ status: 'unavailable', model: null, effort: null }));vi.mock('./github.js', () => ({execGh: vi.fn(async () => '[]'),ensureForgeReachable: (...args) => ensureForgeReachableMock(...args),+ getIssueDispatchHint: (...args) => getIssueDispatchHintMock(...args),}));vi.mock('../lib/gitRemote.js', () => ({getOriginInfo: vi.fn(async () => ({@@ -63,7 +65,12 @@ vi.mock('../lib/gitRemote.js', () => ({// which is the fail-open "analyze everything" path the pre-#3842 suite assumes.const tryReadFileMock = vi.fn(async () => null);vi.mock('../lib/fileUtils.js', () => ({- PATHS: { root: '/repo', cos: '/repo/data/cos' },+ // `data` added alongside `root`/`cos` because `formatInFlightForPrompt`'s+ // dispatch-hint lookup now reaches `issueNumberFromRef` from+ // `issueReconcile.js`, whose module graph (via jira.js) reads `PATHS.data`+ // at import time — an incomplete PATHS here crashed with a raw TypeError+ // rather than a test failure.+ PATHS: { root: '/repo', cos: '/repo/data/cos', data: '/repo/data' },safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw); } catch { return fallback; } },isPathInsideDir: (dir, candidate) => typeof dir === 'string' && typeof candidate === 'string'&& candidate.startsWith(`${dir}/`),@@ -1612,8 +1619,15 @@ describe('actionableSignature', () => {});describe('formatInFlightForPrompt', () => {- it('renders the default branch, each branch with its PR + worktree + Do line', () => {- const block = formatInFlightForPrompt([+ beforeEach(() => {+ // Default: no dispatch hint. Keeps these tests from asserting on a line+ // that only the dedicated dispatch-hint tests below exercise.+ getIssueDispatchHintMock.mockReset();+ getIssueDispatchHintMock.mockResolvedValue({ status: 'unavailable', model: null, effort: null });+ });++ it('renders the default branch, each branch with its PR + worktree + Do line', async () => {+ const block = await formatInFlightForPrompt([{ branch: 'next/issue-1', state: 'IN_REVIEW', worktreePath: '/wt/1', openPr: { number: 42, mergeable: 'MERGEABLE', url: 'https://pr/42' } },{ branch: 'next/issue-2', state: 'NEEDS_PR' }], { defaultBranch: 'main', actions: {} });@@ -1625,8 +1639,8 @@ describe('formatInFlightForPrompt', () => {expect(block).toContain('- Do: ');});- it('flags a never-pushed NEEDS_PR branch so the agent knows the push needs -u', () => {- const block = formatInFlightForPrompt([+ it('flags a never-pushed NEEDS_PR branch so the agent knows the push needs -u', async () => {+ const block = await formatInFlightForPrompt([{ branch: 'claim/issue-1', state: 'NEEDS_PR', hasUpstream: false },{ branch: 'claim/issue-2', state: 'NEEDS_PR', hasUpstream: true }], { defaultBranch: 'main', actions: {} });@@ -1635,8 +1649,8 @@ describe('formatInFlightForPrompt', () => {expect(second).not.toContain('Never pushed');});- it('states the configured batch limit when supplied', () => {- const block = formatInFlightForPrompt(+ it('states the configured batch limit when supplied', async () => {+ const block = await formatInFlightForPrompt([{ branch: 'next/issue-1', state: 'NEEDS_PR' }],{ defaultBranch: 'main', actions: {}, branchesPerAgent: 3 });@@ -1645,8 +1659,8 @@ describe('formatInFlightForPrompt', () => {// The collision set gets its own line, not just prose inside the Do: text, so// the agent can open those files directly instead of re-deriving the set.- it('surfaces drift and the collision files as their own lines', () => {- const block = formatInFlightForPrompt([{+ it('surfaces drift and the collision files as their own lines', async () => {+ const block = await formatInFlightForPrompt([{branch: 'cos/task-x/agent-deadbeef',state: 'ABANDONED_WIP',worktreePath: '/wt/agent-deadbeef',@@ -1660,14 +1674,66 @@ describe('formatInFlightForPrompt', () => {expect(block).toContain('holds UNCOMMITTED work');});- it('omits the drift and collision lines when there is nothing to report', () => {- const block = formatInFlightForPrompt(+ it('omits the drift and collision lines when there is nothing to report', async () => {+ const block = await formatInFlightForPrompt([{ branch: 'fresh', state: 'NEEDS_PR', behind: 0, ahead: 3, collisionPaths: [] }],{ defaultBranch: 'main', actions: {} });expect(block).toContain('- Drift: 0 commit(s) behind');expect(block).not.toContain('supersession shows up');});++ // Dispatch-hint routing (#6373) — mirrors the swarm block's per-issue+ // routing, but here it's real code reading the forge rather than prose+ // telling an LLM coordinator to do it.+ it("names the issue's model:/effort: labels for a claim/issue-<num> branch", async () => {+ getIssueDispatchHintMock.mockResolvedValue({ status: 'known', model: 'heavy', effort: 'max' });+ const block = await formatInFlightForPrompt(+ [{ branch: 'claim/issue-77', state: 'NEEDS_PR' }],+ { defaultBranch: 'main', actions: {}, repoPath: '/repo' }+ );+ expect(block).toContain("Recommended dispatch (issue #77's labels): model:heavy, effort:max");+ expect(getIssueDispatchHintMock).toHaveBeenCalledWith(77, expect.objectContaining({ cwd: '/repo' }));+ });++ it("names the issue's number from a cos/<task>/issue-<num>/<agent> branch", async () => {+ getIssueDispatchHintMock.mockResolvedValue({ status: 'known', model: 'light', effort: null });+ const block = await formatInFlightForPrompt(+ [{ branch: 'cos/branch-reconcile/issue-5/agent-abc', state: 'NEEDS_PR' }],+ { defaultBranch: 'main', actions: {} }+ );+ expect(block).toContain("Recommended dispatch (issue #5's labels): model:light");+ expect(getIssueDispatchHintMock).toHaveBeenCalledWith(5, expect.anything());+ });++ it('omits the line when the branch is not issue-derived', async () => {+ const block = await formatInFlightForPrompt(+ [{ branch: 'cos/task-x/agent-deadbeef', state: 'NEEDS_PR' }],+ { defaultBranch: 'main', actions: {} }+ );+ expect(getIssueDispatchHintMock).not.toHaveBeenCalled();+ expect(block).not.toContain('Recommended dispatch');+ });++ it('omits the line when the issue carries neither dispatch label', async () => {+ getIssueDispatchHintMock.mockResolvedValue({ status: 'known', model: null, effort: null });+ const block = await formatInFlightForPrompt(+ [{ branch: 'claim/issue-9', state: 'NEEDS_PR' }],+ { defaultBranch: 'main', actions: {} }+ );+ expect(block).not.toContain('Recommended dispatch');+ });++ it('a failed forge read omits the line rather than blocking or reshaping the rest of the block', async () => {+ getIssueDispatchHintMock.mockRejectedValue(new Error('gh: rate limited'));+ const block = await formatInFlightForPrompt(+ [{ branch: 'claim/issue-9', state: 'NEEDS_PR' }],+ { defaultBranch: 'main', actions: {} }+ );+ expect(block).not.toContain('Recommended dispatch');+ expect(block).toContain('### `claim/issue-9` [NEEDS_PR] — no PR');+ expect(block).toContain('- Do: ');+ });});describe('orphaned remote branches', () => {diff --git a/server/services/cosTaskPreStepBlocks.compose.test.js b/server/services/cosTaskPreStepBlocks.compose.test.jsindex 829eadd512..5250d6c0c5 100644--- a/server/services/cosTaskPreStepBlocks.compose.test.js+++ b/server/services/cosTaskPreStepBlocks.compose.test.js@@ -77,6 +77,15 @@ vi.mock('./branchReconcile.js', async (importActual) => ({reconcile: vi.fn((...args) => reconcileMock(...args)),}));+// formatInFlightForPrompt (real, via importActual above) fetches a dispatch+// hint per issue-derived branch — mock just that one gh call so this suite+// never shells out to a real `gh`. `getIssueDispatchHint` already collapses+// every failure mode to `unavailable`, so this mirrors "no forge reachable".+vi.mock('./github.js', async (importActual) => ({+ ...(await importActual()),+ getIssueDispatchHint: vi.fn(async () => ({ status: 'unavailable', model: null, effort: null })),+}));+vi.mock('./agentState.js', async (importActual) => ({...(await importActual()),getActiveAgentIds: vi.fn(() => []),diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.jsindex 509ac0f7d1..ff320df98c 100644--- a/server/services/cosTaskPreStepBlocks.js+++ b/server/services/cosTaskPreStepBlocks.js@@ -439,10 +439,11 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskSmetadata.perpetual = true;const supersededBlock = formatSupersededForPrompt(result.superseded || []);const block = [- formatInFlightForPrompt(actionable, {+ await formatInFlightForPrompt(actionable, {defaultBranch: result.defaultBranch,actions,- branchesPerAgent: metadata.branchesPerAgent+ branchesPerAgent: metadata.branchesPerAgent,+ repoPath: app.repoPath}),supersededBlock].filter(Boolean).join('\n');diff --git a/server/services/github.js b/server/services/github.jsindex edd9bc597c..c8aa323c5a 100644--- a/server/services/github.js+++ b/server/services/github.js@@ -6,6 +6,7 @@ import { ServerError } from '../lib/errorHandler.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { createMutex } from '../lib/asyncMutex.js';import { getSettings, updateSettings } from './settings.js';+import { dispatchHintFromLabels } from '../lib/dispatchLabels.js';const DATA_DIR = PATHS.data;const REPOS_FILE = join(DATA_DIR, 'github-repos.json');@@ -872,3 +873,35 @@ export async function getPullRequestState(prRef, { cwd = null, env = null } = {}if (!state) return { status: 'unavailable', state: null, detail: 'gh returned unparseable output' };return { status: 'known', state, detail: null };}++/**+ * Read one issue's `model:`/`effort:` dispatch-hint labels, for a caller (e.g.+ * branch-reconcile's per-branch prompt line) that wants to route an+ * issue-derived branch by the same labels a planner already chose. GitHub only+ * — same scope as `findPullRequestForBranch` / `getPullRequestState`.+ *+ * Same two-not-three-answers discipline as those two: `unavailable` means we+ * could not ask (gh firewalled, issue deleted, unparseable output) and a+ * caller must never read it as "no labels" — the whole point is to let a+ * failed read be silently omitted rather than misreported as an actual+ * absence of dispatch hints.+ *+ * @param {number|string} issueNumber+ * @param {{ cwd?: string, env?: object|null }} [opts] - repo dir gh resolves the remote from, and the env overlay to run under+ * @returns {Promise<{ status: 'known'|'unavailable', model: string|null, effort: string|null }>}+ */+export async function getIssueDispatchHint(issueNumber, { cwd = null, env = null } = {}) {+ if (!issueNumber) return { status: 'unavailable', model: null, effort: null };+ const raw = await execGh(+ ['issue', 'view', String(issueNumber), '--json', 'labels'],+ DEFAULT_EXEC_GH_TIMEOUT_MS,+ { cwd, env }+ ).catch(err => err);+ if (raw instanceof Error) return { status: 'unavailable', model: null, effort: null };+ const parsed = safeJSONParse(raw, null);+ const labels = Array.isArray(parsed?.labels) ? parsed.labels : null;+ // A zero-exit gh that emitted nothing parseable told us nothing.+ if (!labels) return { status: 'unavailable', model: null, effort: null };+ const names = labels.map((l) => (typeof l?.name === 'string' ? l.name : '')).filter(Boolean);+ return { status: 'known', ...dispatchHintFromLabels(names) };+}diff --git a/server/services/github.test.js b/server/services/github.test.jsindex e2199167f8..dcc5f4cd5b 100644--- a/server/services/github.test.js+++ b/server/services/github.test.js@@ -37,6 +37,7 @@ import {__resetGhCallBackoff,execGh,getGitHubAuthStatus,+ getIssueDispatchHint,getPullRequestState,setRepoArchived,setSecret,@@ -358,6 +359,80 @@ describe('getPullRequestState', () => {});});+// branch-reconcile's per-branch dispatch-hint line (#6373) reads exactly this+// answer, and a failed/unavailable read must be indistinguishable from "no+// labels" to that caller — never a thrown error, never a state that could be+// mistaken for a real (if empty) hint.+describe('getIssueDispatchHint', () => {+ beforeEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+ });++ const run = (issueNumber, drive) => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const promise = getIssueDispatchHint(issueNumber);+ drive(child);+ return promise;+ };++ it('recovers both axes from the issue\'s labels', async () => {+ const res = await run(77, (c) => {+ c.stdout.emit('data', Buffer.from(JSON.stringify({+ labels: [{ name: 'model:heavy' }, { name: 'effort:max' }, { name: 'area:cos-agents' }]+ })));+ c.emit('close', 0);+ });+ expect(res).toEqual({ status: 'known', model: 'heavy', effort: 'max' });+ });++ it('reports known with both axes null when the issue carries neither label', async () => {+ const res = await run(77, (c) => {+ c.stdout.emit('data', Buffer.from(JSON.stringify({ labels: [{ name: 'bug' }] })));+ c.emit('close', 0);+ });+ expect(res).toEqual({ status: 'known', model: null, effort: null });+ });++ it('ignores an unrecognized axis value rather than misreading it', async () => {+ const res = await run(77, (c) => {+ c.stdout.emit('data', Buffer.from(JSON.stringify({ labels: [{ name: 'model:huge' }] })));+ c.emit('close', 0);+ });+ expect(res).toEqual({ status: 'known', model: null, effort: null });+ });++ it('passes the issue number straight to `gh issue view --json labels`', async () => {+ await run(77, (c) => {+ c.stdout.emit('data', Buffer.from('{"labels":[]}'));+ c.emit('close', 0);+ });+ expect(spawn).toHaveBeenCalledWith('gh', ['issue', 'view', '77', '--json', 'labels'], expect.anything());+ });++ it('reports unavailable — never a thrown error — when gh fails', async () => {+ const res = await run(77, (c) => {+ c.stderr.emit('data', Buffer.from('dial tcp: connect: bad file descriptor'));+ c.emit('close', 1);+ });+ expect(res).toEqual({ status: 'unavailable', model: null, effort: null });+ });++ it('reports unavailable when a zero-exit gh emits nothing parseable', async () => {+ const res = await run(77, (c) => {+ c.stdout.emit('data', Buffer.from('not json'));+ c.emit('close', 0);+ });+ expect(res).toEqual({ status: 'unavailable', model: null, effort: null });+ });++ it('reports unavailable without shelling out when given no issue number', async () => {+ await expect(getIssueDispatchHint(null)).resolves.toEqual({ status: 'unavailable', model: null, effort: null });+ expect(spawn).not.toHaveBeenCalled();+ });+});+const childReturning = (stdout) => {const child = new EventEmitter();child.stdout = new EventEmitter();diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.jsindex 759336caee..03a79035d6 100644--- a/server/services/taskPromptDefaults.test.js+++ b/server/services/taskPromptDefaults.test.js@@ -12,7 +12,7 @@ import { hashPromptBody, buildPromptIntegritySnapshot } from './taskPromptDefaulimport { EPIC_DECOMPOSED_LABEL } from './perpetualWork.js';// The claim prompts build their contributor-label release from this helper, so the// test asserts against the same source rather than re-typing the command text.-import { formatContributorLabelReleaseCommands, formatVolunteerClaimCommands } from '../lib/dispatchLabels.js';+import { DISPATCH_HINT_FANOUT_GUIDANCE, formatContributorLabelReleaseCommands, formatVolunteerClaimCommands } from '../lib/dispatchLabels.js';// Hash snapshot of every exported prompt body and version. This pins the// cross-install prompt-upgrade contract (see AGENTS.md "Distribution model"):@@ -703,18 +703,38 @@ describe('taskPromptDefaults integrity snapshot', () => {// regression. The tell is the conflict itself, which is why the prompt has to// say outright that a resolvable conflict proves nothing.it('branch-reconcile v3 makes SUPERSEDED an outcome and denies conflicts as evidence, preserving the v2 default', () => {+ const previous = PREVIOUS_DEFAULT_PROMPTS['branch-reconcile'];+ const v3 = previous[previous.length - 1];+ const v2 = previous[previous.length - 2];+ expect(v3).toContain('SUPERSEDED');+ expect(v3).toContain('not evidence the work is still needed');+ expect(v3).toContain('Nothing reaches a PR unverified');++ // v2 already drove branches to merged, but had no supersession concept.+ expect(v2).toContain('not finished until it IS merged');+ expect(v2).not.toContain('SUPERSEDED');+ expect(v2).not.toBe(v3);+ });++ // branch-reconcile v4 (#6373): the coordinator fans out one sub-agent per+ // branch just like v3 did, but now routes each sub-agent by ITS OWN branch's+ // issue labels — the same per-issue routing DISPATCH_HINT_FANOUT_GUIDANCE+ // already gives the claim swarm's Phase B, imported verbatim rather than+ // retyped so the two consumers can't drift on vocabulary.+ it('branch-reconcile v4 routes each fan-out sub-agent by its own branch\'s dispatch labels', () => {const current = DEFAULT_TASK_PROMPTS['branch-reconcile'];+ expect(PROMPT_VERSIONS['branch-reconcile']).toBe(4);+ expect(current).toContain(DISPATCH_HINT_FANOUT_GUIDANCE);+ expect(current).toContain('Dispatch each sub-agent at ITS OWN branch\'s recommended model and effort');+ // Still carries every v3 behavior — v4 only adds the routing guidance.expect(current).toContain('SUPERSEDED');expect(current).toContain('not evidence the work is still needed');expect(current).toContain('Nothing reaches a PR unverified');- expect(PROMPT_VERSIONS['branch-reconcile']).toBe(3);const previous = PREVIOUS_DEFAULT_PROMPTS['branch-reconcile'];- const v2 = previous[previous.length - 1];- // v2 already drove branches to merged, but had no supersession concept.- expect(v2).toContain('not finished until it IS merged');- expect(v2).not.toContain('SUPERSEDED');- expect(v2).not.toBe(current);+ const v3 = previous[previous.length - 1];+ expect(v3).not.toContain(DISPATCH_HINT_FANOUT_GUIDANCE);+ expect(v3).not.toBe(current);});// Phase 1's candidate fetch must match perpetualWork.js's detector — bothdiff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.jsonindex dc19580bb1..86cafa427e 100644--- a/server/services/taskPromptDefaults/integrity.snapshot.json+++ b/server/services/taskPromptDefaults/integrity.snapshot.json@@ -3,7 +3,7 @@"accessibility": "372916803f32b82da38a5b2130a54baf","api-contract": "cf02b10a5993baf473e0d320771f26b6","branch-cleanup": "8fdeb4acc2749816a47ca318b6602721",- "branch-reconcile": "16479f4b64395103fd222dc9608830b1",+ "branch-reconcile": "7c296ced3f0dec6e764d123f24009ccc","claim-issue": "5600fde65e31874bd96c3ad83ce72a92","claim-issue-gitlab": "bb83608738b6517f3f05df116994a6fd","claim-issue-jira": "b14a5dde5519fda59c2ba1ae7a3d8989",@@ -50,7 +50,7 @@"PROMPT_VERSIONS": {"accessibility": 2,"api-contract": 1,- "branch-reconcile": 3,+ "branch-reconcile": 4,"claim-issue": 25,"claim-issue-gitlab": 22,"claim-issue-jira": 16,@@ -99,7 +99,8 @@],"branch-reconcile": ["7ef2b5f7d8f05937d4912b26ad45f42e",- "ecb0621588a751b1383ecd89cf514382"+ "ecb0621588a751b1383ecd89cf514382",+ "16479f4b64395103fd222dc9608830b1"],"claim-issue": ["37949d1b1fa8d461a15658f8f4192d97",diff --git a/server/services/taskPromptDefaults/previousDefaults.js b/server/services/taskPromptDefaults/previousDefaults.jsindex 5767dc4b02..cd9336992f 100644--- a/server/services/taskPromptDefaults/previousDefaults.js+++ b/server/services/taskPromptDefaults/previousDefaults.js@@ -10979,6 +10979,33 @@ Spawn ONE sub-agent per branch (they are independent — run them in parallel) t- Merging is gated by the "Do:" line itself — required CI green, MERGEABLE, and the review that branch's flow ran (\`/do:pr\`'s reviewer loop for a PR this task opens; the named review for one already in review). That gate, not a blanket ban, is what keeps unreviewed work out of the default branch. Merge only via \`gh pr merge\`, never a local \`git merge\` into the default branch.- If a sub-agent reports a branch is incomplete or blocked, leave it as-is and note it in your summary.- Summarize what each branch ended up doing (merged / PR opened but blocked on <what> / conflicts resolved / left incomplete). When a PR is left open, name the check or review that blocked it.`,+ // v3 default — superseded by v4, which interpolates DISPATCH_HINT_FANOUT_GUIDANCE+ // next to the fan-out instruction and tells the coordinator to route each+ // sub-agent by its own branch's issue model:/effort: labels (#6373). v3 added+ // SUPERSEDED as a first-class outcome and the rebase+test-verify gate before a+ // branch reaches a PR.+ `[Improvement: {appName}] Branch & PR Reconciliation++You are the coordinator for finishing {appName}'s unfinished local git work. The scheduler has already run the deterministic pass (removed fully-merged, orphaned local branches + their worktrees) and handed you ONLY the branches that need judgment.++Repository: {repoPath}++Each branch listed below is a LOCAL branch in THIS clone of {appName}. On a machine that is a federated sync peer, branches created on OTHER machines exist here only as remote-tracking refs (\`origin/*\`) and are deliberately NOT listed — never open, rebase, or merge anything that is not in the list below.++{inFlightBranches}++Spawn ONE sub-agent per branch (they are independent — run them in parallel) to carry out that branch's "Do:" instruction, each working in the branch's existing worktree when it has one.++## Rules+- Work ONLY on the branches listed above. Never touch a branch that is not listed.+- Never force-push the default branch.+- **A branch can be finished, correct, and still not wanted.** Work that sat while the default branch moved may have been solved there a different way in the meantime; merging it then UNDOES what already shipped. Each branch's "Do:" line opens with the files the default branch has also changed since that branch diverged — the sub-agent reads those first and reports **SUPERSEDED** if the default branch already solves that branch's problem, by any means (a differently-named function, a policy object where the branch has a boolean, a scheduled tick where the branch has a watcher). A SUPERSEDED branch is left completely untouched: no commit, no rebase, no conflict resolution, no merge.+- **A conflict you can resolve is not evidence the work is still needed.** It is the most common way a superseded branch gets merged looking deliberate — the resolution is mechanically sound and semantically a regression. Treat every conflict as a question about supersession first and a merge chore second.+- **Nothing reaches a PR unverified.** Each sub-agent rebases onto the default branch before opening or updating a PR (so the PR is conflict-free by construction), then runs the touched workspaces' test suites and lint and reads the result — a rebase can break code that passed on the old base. A branch whose tests the sub-agent has not seen pass is never pushed.+- **A branch whose "Do:" line ends in a merge is not finished until it IS merged.** Its sub-agent stays alive through CI — waiting out the check run, fixing what goes red, then merging — and reports back only when the PR is merged or a specific check/review is blocking it. "PR opened, left open for review" is a completed STEP, not a completed branch: the PR just sits green until the next run re-drives it. Do not end your own run while a sub-agent is still waiting on CI.+- Merging is gated by the "Do:" line itself — required CI green, MERGEABLE, and the review that branch's flow ran (\`/do:pr\`'s reviewer loop for a PR this task opens; the named review for one already in review). That gate, not a blanket ban, is what keeps unreviewed work out of the default branch. Merge only via \`gh pr merge\`, never a local \`git merge\` into the default branch.+- If a sub-agent reports a branch is incomplete, superseded, or blocked, leave it as-is and note it in your summary.+- Summarize what each branch ended up doing (merged / PR opened but blocked on <what> / conflicts resolved / superseded / left incomplete). For a SUPERSEDED branch, name the file(s) and what on the default branch replaced it, so the user can delete the branch with confidence. When a PR is left open, name the check or review that blocked it.`,],'issue-reconcile': [diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.jsindex 93ba2e6a57..94e19de49b 100644--- a/server/services/taskPromptDefaults/prompts.js+++ b/server/services/taskPromptDefaults/prompts.js@@ -12,6 +12,7 @@// PORTOS_API_URL is interpolated into the jira-status-report default prompt below.import { PORTOS_API_URL } from '../../lib/ports.js';import {+ DISPATCH_HINT_FANOUT_GUIDANCE,EPIC_DECOMPOSED_LABEL,EPIC_LABEL,ISSUE_QUALITY_GUIDANCE,@@ -2240,7 +2241,9 @@ Each branch listed below is a LOCAL branch in THIS clone of {appName}. On a mach{inFlightBranches}-Spawn ONE sub-agent per branch (they are independent — run them in parallel) to carry out that branch's "Do:" instruction, each working in the branch's existing worktree when it has one.+Spawn ONE sub-agent per branch (they are independent — run them in parallel) to carry out that branch's "Do:" instruction, each working in the branch's existing worktree when it has one. **Dispatch each sub-agent at ITS OWN branch's recommended model and effort** — a branch's block above names one when its issue carries \`model:\`/\`effort:\` labels; a batch is one partition decision, not one routing decision, and two branches in the same run routinely deserve different capability. Name the model/effort you used for each branch in your final summary.++${DISPATCH_HINT_FANOUT_GUIDANCE}## Rules- Work ONLY on the branches listed above. Never touch a branch that is not listed.diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.jsindex 2df686256e..2786eb7642 100644--- a/server/services/taskPromptDefaults/versions.js+++ b/server/services/taskPromptDefaults/versions.js@@ -21,7 +21,7 @@ export const PROMPT_VERSIONS = {'code-reviewer-b': 1, // v1: 2-stage pipeline (codebase review → triage & implement)'reference-watch': 3, // v3: record proposals in the app's RESOLVED work tracker (PLAN.md / GitHub / GitLab / JIRA) via the {trackerInstructions} block — no longer hardcodes PLAN.md, so an app configured for GitHub issues gets `gh issue create` proposals. v2: append slug-tagged checklist items to PLAN.md (Adopt + Maybe) instead of writing REFERENCE_REVIEW.md; security-flagged commits get no PLAN entry (mentioned only in final summary)'pr-watcher': 2, // v1: review-and-comment default for newly-opened PRs on the app's default branch- 'branch-reconcile': 3, // v3: SUPERSEDED is a first-class outcome — a branch whose problem the default branch already solved a different way is reported and left untouched, never merged (merging it undoes shipped work). A resolvable conflict is explicitly NOT evidence the work is still wanted, and every branch is rebased + test-verified before it reaches a PR. v2: a branch whose "Do:" line ends in a merge isn't finished until it IS merged — the sub-agent waits CI out in-session instead of handing back a green-but-open PR, and the old blanket "never merge unreviewed work" rule (which vetoed the per-branch merge instruction) is replaced by the explicit CI-green + MERGEABLE + review gate. v1: per-app coordinator that finishes in-flight LOCAL branches (open PR / resolve conflicts / drive review / auto-merge) after the deterministic merged-branch cleanup pass. Peer-safe (local refs only). Replaced the PortOS-only branchReconcileScheduler.+ 'branch-reconcile': 4, // v4: the prompt now interpolates DISPATCH_HINT_FANOUT_GUIDANCE next to the "spawn one sub-agent per branch" instruction and tells the coordinator to dispatch each sub-agent at ITS OWN branch's recommended model/effort — the same per-issue routing the claim swarm's Phase B already does, applied here because branch-reconcile fans out over issue-derived branches too (#6373). v3: SUPERSEDED is a first-class outcome — a branch whose problem the default branch already solved a different way is reported and left untouched, never merged (merging it undoes shipped work). A resolvable conflict is explicitly NOT evidence the work is still wanted, and every branch is rebased + test-verified before it reaches a PR. v2: a branch whose "Do:" line ends in a merge isn't finished until it IS merged — the sub-agent waits CI out in-session instead of handing back a green-but-open PR, and the old blanket "never merge unreviewed work" rule (which vetoed the per-branch merge instruction) is replaced by the explicit CI-green + MERGEABLE + review gate. v1: per-app coordinator that finishes in-flight LOCAL branches (open PR / resolve conflicts / drive review / auto-merge) after the deterministic merged-branch cleanup pass. Peer-safe (local refs only). Replaced the PortOS-only branchReconcileScheduler.'issue-reconcile': 5, // v4: follow-up recipes apply independent slashdo dispatch hints and contributor labels (`good first issue`/`help wanted`, Jira hyphenated equivalents) instead of only `plan`. v3: adds a JIRA arm — status-based zombies (a ticket left In Review with remaining scope + no live claim; JIRA has no `in-progress` label) detected via the PortOS JIRA API and healed through ticket transitions + `POST tickets`, routed in via the app's resolved workTracker ('jira') rather than the git host. v2: forge-aware — the scan + coordinator now cover GitLab (`glab` issues + MRs) as well as GitHub, resolved from the app's origin host; every heal command is shown as gh/glab and the injected header names the forge. v1: per-app coordinator that heals ZOMBIE issues (open + in-progress but their PR merged with no live claim) after the deterministic gh/git scan. Applies the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the claim so the queue re-picks it.'refresh-local-llm-catalog': 4, // v4: follows the current no-per-branch-changelog contract and relies on a release-note-quality commit subject. v3: catalog maintenance now preserves the primary-lane + cross-lane recommendation taxonomy and reserves featured treatment for a deliberate first choice. v2: PortOS-only task, so it names the retired fragment command directly. v1: research current local models, refresh LOCAL_LLM_CATALOG + EDITORIAL_FAMILY_RANK, PR (PortOS repo only)'user-action-review': 2, // v2: leftover-branch idle detector interpolates via {userActionDetectors}; empty-ledger skip is waived when detector findings exist; leftover findings are propose-only (never reconcile / Run Now). v1: install-wide review of the operator-action ledger (#5595) — query the last 7 days, group repetition by type + target, propose 1–5 automations delivered per {userActionDelivery} (tracker issues by default, queued CoS tasks when the operator flips fileIssues off); never mutates settings or schedule types, summarizes CoS prompts instead of pasting them, exits immediately on an empty log.