🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
dream(swarm): #4173 TaskOrchestrator.getQueuePosition() priority-map key typo (evaluated, ACCEPT) (#4174)
rUv16507b171ab5
diff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.mdindex c7db7bd98e..8e82d30fcd 100644--- a/docs/dream-cycle/LEDGER.md+++ b/docs/dream-cycle/LEDGER.md@@ -231,6 +231,9 @@ as a first-class, high-priority candidate, not a background note.| 2026-10-09 | swarm | `MessageBus.handleDeliveryError()`'s retry re-queue used the broadcast sentinel `message.to === 'broadcast'` as the queue key instead of the real subscriber `agentId` `enqueue()` had fanned the message out to — `processQueues()` skips any unsubscribed queue, so a failing broadcast subscriber's retries and eventual `message.failed` were silently dropped into an orphaned queue leaking until `shutdown()`; explicitly disclosed as a "KNOWN LIMITATION (pre-existing, not fixed here)" by the immediately-preceding #3562/#3563 rewrite, closed tonight by threading `subscription.agentId` through `deliverMessage()`→`handleDeliveryError()`→the re-queue | #3928 | #3929 | yes | ACCEPT | 2 new discriminating tests, baseline-fails/candidate-passes via stash isolation (independently reproduced byte-identical by an adversarial critic's own stash/pop cycle); full `@claude-flow/swarm` suite 274/274→276/276 (+2 new), 0 regressions, `tsc --noEmit` clean both ways; healthy co-subscriber in the same broadcast unaffected (explicit regression guard); independent adversarial critique CONFIRMED, no blocking issues | 1b7e818e... | 10-01 #3599 MERGED 2026-10-07; 10-02..10-03/10-05..10-08 open/draft or closed-not-merged (see 2026-10-09 note above); 10-04 no-run gap; also newly confirmed MERGED this session: #3339 (09-16), #3539 (09-29) || 2026-10-10 | performance | `fallbackLouvain()`'s `communityTotal` map was rebuilt via a full O(n) scan of every node, once per node, once per local-moving pass — O(n²) per pass — instead of maintained incrementally like networkx's `Stot`/python-louvain's `status.degrees` (O(1) per accepted move); this is the *only* community-detection path that ever runs (`loadRuVector()`'s native-acceleration checks for `hooks_graph_mincut`/`hooks_graph_cluster`/`@ruvector/wasm`'s `GraphAnalyzer`, none of which exist in any published `ruvector`/`@ruvector/wasm` version, confirmed by direct inspection of the installed `[email protected]`'s real exports — correcting 2026-10-09's own "wire the real exports in" recommendation, which had the wrong premise) | #3976 | #3977 | yes | ACCEPT | 4 new discriminating tests (3 correctness + 1 complexity-growth) with a frozen pre-fix copy inline for CI-safe comparison; stash-isolated baseline-fails/candidate-passes on the growth assertion, independently reproduced by an adversarial critic's own stash/pop cycle; standalone `tsx` probe: baseline 10.37ms→837.29ms (~81x growth, N=200→1600), candidate 5.00ms→22.33ms (~4.5x growth), per-N speedup 2.1x→37.5x; full `@claude-flow/cli` suite failed-file set byte-identical baseline vs. candidate (200 vs. 199 — the one difference is the new test file itself), `tsc --noEmit` byte-identical (498 pre-existing errors); independent adversarial critique CONFIRMED, no blocking issues | 81e21481... | 10-01 #3599 MERGED; 10-02/10-03/10-06/10-07/10-08 open/draft, none stale; 10-04 no-run gap; 10-05 #3754 closed as duplicate of #3517 (not a fresh rejection — same fix had already shipped) || 2026-10-11 | security | settings.json risk scanner (#3043) never ran on the one path that fires automatically on every real session boot — `hook-handler.cjs`'s `session-restore` command (Claude Code's own `SessionStart` hook) — a gap #3835 (10-06) itself disclosed as a future-night item; ported the TS scanner's logic (no build step for `.cjs`) into `scanSessionStartSettingsForRisk()`, validated against a real 2026 npm-worm campaign ("Mini Shai-Hulud") and CVE-2026-25725, both of which use this exact persistence mechanism | #4052 | #4053 | yes | ACCEPT-scoped (post-critique) | 12 new discriminating tests, stash-isolated 10/12 fail baseline → 12/12 pass candidate; adversarial critic found and this session fixed a non-SyntaxError `JSON.parse` failure that would have aborted session-restore itself (narrowed catch copied from the opt-in #3835 MCP path onto an unconditional-boot path); related suites 72/72 pass; full `@claude-flow/cli` suite 207 pre-existing environmental failures unchanged (unbuilt sibling packages), zero touching this change | 016fe07f... | 10-01 #3599 MERGED; 10-02/10-03/10-06/10-07/10-08 open/draft, none stale; 10-04 no-run gap; 10-05 #3754 closed as duplicate; 10-09 #3929, 10-10 #3977 open/draft, not stale. Prior gist (10-10, performance) scored 10/10 (2+2+2+2+1(1489 words)+1) |+**Note (2026-10-14):** 2026-10-12 (intelligence, #4080/#4081 — SONA learning-state persistence wiring into `LearningBridge`, ACCEPT) and 2026-10-13 (memory, #4137/#4138 — `AutoMemoryBridge` delete-sync wiring, ACCEPT) both ran (real branches+issues+draft-PRs confirmed via `git ls-remote --heads origin "dream/*"` and `pull_request_read`, not inferred) but aren't transcribed as their own rows here — same "ledger rows only reach `main` via PR merge" structural gap noted since 2026-08-19. Both open/draft, neither stale (2d/1d old respectively). Prior gist (10-13, memory) scored 10/10 (2+2+2+2+1(~1490 words)+1). GitHub-verified fates for the full trailing week before tonight's own row: 10-05 #3754 **closed, not merged** (duplicate of #3517); 10-06 #3835, 10-07 #3879, 10-08 #3909 open/draft, none stale; 10-09 #3929, 10-10 #3977, 10-11 #4053 **MERGED**; 10-12 #4081, 10-13 #4138 open/draft, not stale. Swarm-surface historical merge rate: 6/6 (08-24, 08-29, 09-09, 09-19, 09-29, 10-09) once reviewed.++| 2026-10-14 | swarm | `TaskOrchestrator.getQueuePosition()`'s priority map used keys `critical/high/normal/low/background` — `TaskPriority` is `critical/high/medium/low`, and `createTask()` defaults to `'medium'`, so the lookup always fell through to 0, ranking default-priority tasks behind even `'low'` in the `taskQueuedEvent` position field; real dispatch (`getNextTask`/`getPriorityQueue`) uses a separate, already-correct map and was unaffected. Scan also resolved a direct contradiction between the 10-09 and 10-10 nights: real `[email protected]` graph exports (`minCut`/`louvainCommunities`/`buildGraph`) DO exist under different names than `graph-analyzer.ts`'s dead detection checks — 10-09 was right, 10-10's "nothing real exists" was wrong | #4173 | #4174 | yes | ACCEPT | 3 new discriminating tests, stash-isolated baseline 278/280 (2 predicted failures) → candidate 280/280, 0 other regressions; `tsc --noEmit` clean both ways (fix also adds compile-time exhaustiveness via `Record<TaskPriority, number>`); independent adversarial critique CONFIRMED, no blocking issues | fab09db0... | 10-05 closed-not-merged (dup); 10-06/10-07/10-08 open/draft, none stale; 10-09/10-10/10-11 MERGED; 10-12/10-13 open/draft, not stale |**Note (2026-10-15):** verified via `git ls-remote --heads origin "dream/*"` + GitHub MCP tools (not inferred) that 2026-10-12 (intelligence, #4080/#4081), 2026-10-13 (memory, #4137/#4138), and 2026-10-14 (swarm, #4173/#4174) all ran with real branches/issues/draft PRs — same "ledger rows only reach `main` via PR merge" structural gap noted since 2026-08-19; not transcribed as their own rows here. Trailing-7-night fates before tonight (GitHub-verified via `pull_request_read`): 10-08 #3909 open/draft; 10-09 #3929 **MERGED** 2026-10-09; 10-10 #3977 **MERGED** 2026-10-10; 10-11 #4053 **MERGED** 2026-10-11; 10-12 #4081 open/draft; 10-13 #4138 open/draft; 10-14 #4174 open/draft — none stale (<14d). 10-05 #3754 remains closed-not-merged (duplicate, already recorded). Prior gist (10-14, swarm) scored 10/10 (2+2+2+2+1(1372 words)+1).| 2026-10-15 | performance | `RaftConsensus.awaitConsensus()` (Ruflo's default hive-mind consensus, reachable via `UnifiedSwarmCoordinator.proposeConsensus()`) busy-polled `this.proposals` via `setInterval(...,10)` even though `checkConsensus()` already emits `'consensus.achieved'` on every accept/reject transition — third instance of a busy-poll bug class already fixed twice (UnifiedSwarmCoordinator #3378, MessageBus #3563); also resolved a 3-night research thread (10-09/10-10/10-14) by confirming `ruvector`'s real `minCut`/`louvainCommunities` exports are plain JS, not native-accelerated, so wiring them into `graph-analyzer.ts` would not be a performance win (REJECT, with evidence, not fixed) | #4214 | #4215 | yes | ACCEPT | 4 new discriminating tests, baseline-fails-3-of-4/candidate-passes-4-of-4 via stash isolation (1 correct non-discriminating control); full `@claude-flow/swarm` suite 281/281 (277+4 new), 0 regressions, `tsc --noEmit` clean both ways; standalone wall-clock probe 3.639ms/30 poll-timers → 0.058ms/0 timers (N=30, ~63x mean-latency reduction); independent adversarial critique CONFIRMED, no blocking issues (verified concurrency via 200 simultaneous proposals + same-tick timeout/vote race) | 2ca9c495... | 10-09/10-10/10-11 MERGED; 10-12/10-13/10-14 open/draft, none stale; 10-05 closed-not-merged (duplicate) |**Note (2026-10-16):** #4053 (10-11, security) and #3977 (10-10, performance) confirmed **MERGED** via GitHub MCP tools (`gh` CLI's `GH_TOKEN` is invalid this session, but MCP tools work fine — not FALLBACK). Confirmed real `dream/*` branches for every night 10-12 (intelligence, #4081), 10-13 (memory, #4138), 10-14 (swarm, #4174), 10-15 (performance, #4215) via `git ls-remote` — no run gap, all currently open/draft, none stale. **Correction**: 10-11's own PR (#4053) cited "CVE-2026-25725" as a future-candidate CVE — direct NVD/MITRE lookup this session found **this ID does not resolve to any real record**, likely garbled; flagging so it isn't re-cited without a fresh, verified ID.diff --git a/docs/dream-cycle/dream-gist-2026-10-14.md b/docs/dream-cycle/dream-gist-2026-10-14.mdnew file mode 100644index 0000000000..8092cbbc12--- /dev/null+++ b/docs/dream-cycle/dream-gist-2026-10-14.md@@ -0,0 +1,79 @@+# Swarm Coordination SOTA Report — 2026-10-14++TL;DR: Tonight's 2026 deep-dive on Ruflo's `@claude-flow/swarm` package resolves a direct factual contradiction between two prior Dream Cycle nights (10-09 vs 10-10) about whether the real `ruvector` package exports usable graph-analysis functions — it does, under different names than the dead detection code checks for — and ships a small, discriminating fix for `TaskOrchestrator.getQueuePosition()`'s priority-map key mismatch, which silently misranks every default-priority ('medium') task behind even 'low'-priority ones in the emitted `taskQueuedEvent` position.++## What's New in 2026++| Finding | Source | Confidence |+|---|---|---|+| ProtocolBench: benchmarks LLM multi-agent communication protocols on task success/latency/overhead/failure-robustness | Zheng et al., ICML 2026 / PMLR v306 | A |+| MS Agent Framework (AutoGen successor, GA ~Apr 2026) checkpoints per-superstep, explicitly at-least-once; no raft/byzantine/gossip layer | learn.microsoft.com, 2026 | B |+| AGNTCY messaging ecosystem IETF draft compares AMQP/MQTT/NATS/Kafka delivery-guarantee semantics | IETF draft-mpsb-agntcy-messaging v02, Jul 2026 | B |+| CP-WBFT: confidence-probe-weighted Byzantine consensus holds accuracy at 85.7% simulated fault rate | arXiv:2511.10400, Nov 2025/rev. Dec 2025 | B |+| `[email protected]` (the version this repo pins) really does export `minCut`/`louvainCommunities`/`buildGraph`/`spectralClustering` — confirmed by direct install + `Object.keys()`, resolving last night-to-night's contradiction | This session, direct inspection | A |++## Ruflo Current Capability++`@claude-flow/swarm` has two parallel coordination stacks: the canonical, live `UnifiedSwarmCoordinator` (recent nights' fixes — broadcast-retry queue key #3929, mirror-edges #3357, spawnAgent pool.add #3539 — all land here) and a `@deprecated` compatibility layer, `SwarmHub` (+ its private `AgentRegistry`/`TaskOrchestrator`), kept for a documented legacy public API (`createSwarmHub()`/`initializeV3Swarm()`) but verified tonight to have **zero callers from the shipped CLI** — only docs/README reference it. Both of tonight's two leading candidates live in that compatibility layer: `AgentRegistry.heartbeat()` (zero production callers — any real `SwarmHub` user would see every spawned agent falsely flip to `'error'` status ~15s after spawn, confirmed via direct read of `agent-registry.ts`/`swarm-hub.ts`) and `TaskOrchestrator.getQueuePosition()`'s priority-map typo (confirmed: its local map has `normal`/`background` keys that never match `TaskPriority`'s real `critical|high|medium|low`, so `createTask()`'s default `'medium'` priority falls through to `priorityOrder[...] || 0`, sorting behind `'low'`(2) in the one place that reads it — the `taskQueuedEvent` position field; real dispatch via `getNextTask()`/`getPriorityQueue()` uses a separate, correct map and is unaffected).++## Competitor Comparison++| System | Mechanism handling | Grade | Source |+|---|---|---|---|+| Temporal (reference) | At-least-once activities; app-level Heartbeats distinguish stuck-vs-slow; per-op RetryPolicy | A | docs.temporal.io, 2025 |+| LangGraph | Checkpointer persists state, not execution — resume is externally triggered, no message-bus/retry layer | B | LangChain docs + Temporal's own gap analysis |+| MS Agent Framework | Per-superstep checkpoints, at-least-once; no consensus layer | B | learn.microsoft.com, 2026 |+| CrewAI | `@persist` SQLite snapshots; retry count widely reported as hard to control | C | CrewAI community threads, 2025-2026 |+| OpenAI Agents SDK | No delivery guarantee/health-check/consensus — deliberate scope decision, not a gap | C | SDK review + Swarm README lineage |+| CP-WBFT / WBFT (academic) | Confidence/trust-weighted BFT; neither ships a production message bus or topology-repair story | B/C | arXiv:2511.10400, arXiv:2505.05103 |++None of the five LLM frameworks pair delivery-retry rigor with Ruflo's raft/byzantine/gossip consensus options — that combination only exists in 2025-2026 academic prototypes, not shipped products. Nobody (Ruflo included) publishes a reproducible topology-self-repair-under-churn benchmark — a genuine open gap across the whole landscape.++## Hypothesis++> Given a `TaskOrchestrator` queue containing tasks across multiple priorities including at least one default (`'medium'`) priority task, when `getQueuePosition()`'s local `priorityOrder` map is corrected to use `TaskPriority`'s real keys (`critical`/`high`/`medium`/`low`) — matching the already-correct map in the same file's `getNextTask()`/`getPriorityQueue()` — then the `position` value emitted via `taskQueuedEvent` for a medium-priority task should rank it ahead of same-or-lower-priority `'low'` tasks instead of falling through to the unmatched-key default of `0` and sorting last, subject to: (1) real dispatch order via `getNextTask()`/`getPriorityQueue()` stays byte-identical (already correct, untouched); (2) all existing tests remain green; (3) deterministic, $0, zero-LLM evaluation.++**STEP 3.2 candidate scoring** (0.25·fit + 0.20·testability + 0.20·measurability + 0.15·production_value + 0.10·novelty + 0.10·reviewability, 1-5 each):++| Candidate | fit | test | meas. | prod. | novel | review | Score |+|---|---|---|---|---|---|---|---|+| **TaskOrchestrator.getQueuePosition() priority typo** | 5 | 5 | 5 | 3 | 4 | 5 | **4.60** |+| AgentRegistry.heartbeat() never called (false 'error' flip) | 5 | 4 | 5 | 3 | 5 | 3 | 4.30 |+| ruvector-integration: wire real `minCut`/`louvainCommunities`/`buildGraph` exports | 3.5 | 4 | 4 | 4 | 5 | 3 | 3.88 |+| TopologyManager.updateNode() 3rd edge-mirroring gap (currently unreachable — `updateNode()` has no production caller) | 4 | 4 | 4 | 2 | 3 | 4 | 3.50 |+| QueenCoordinator unbounded cache growth (leak, not correctness) | 3 | 3 | 3 | 2 | 2 | 4 | 2.85 |+| ruview-integration: unwired RuView product-plane module | 2 | 1 | 1 | 2 | 2 | 2 | 1.60 |++Highest score selected. Note on fairness: `heartbeat()` initially looked more impactful (a live false-positive vs. a telemetry-field typo), but direct verification found **both** candidates live inside the same unreachable-from-shipped-CLI `SwarmHub` layer — once `production_value` is scored consistently across both, the smaller, cleaner, equally-real fix wins on testability/measurability/reviewability. `heartbeat()`'s fix also requires a real design decision (where should a liveness signal come from?) rather than a pure wiring correction, raising its risk. Carried forward for a future night, not discarded.++## Benchmarks++No `.harness/bench.json` corpus exists in this repo (confirmed, same as every recent night). Real evaluator: Vitest 4.1.8, deterministic, $0, zero LLM calls — matching the established pattern for this correctness-bug-fix class (near-unanimous across the ledger since 2026-08-18).++## Evaluation++**evaluated: accepted.** Real evaluator: Vitest 4.1.8, deterministic, $0, zero LLM calls, against a freshly `pnpm install`-ed `v3/` workspace.++New test file `task-orchestrator.queue-position.test.ts` (3 tests). Stash-isolated (`git stash push -- .../task-orchestrator.ts`, test file kept): 2/3 fail exactly as hand-predicted (`expected 2 to be 1`; `expected 4 to be 3`); the dispatch-order control test (unaffected `getNextTask()`) passes on both. Candidate: 3/3 pass. Full `@claude-flow/swarm` suite, run both ways (not just the new file): baseline (stashed fix) 278/280 passed, 1/19 files failed — exactly the 2 discriminating tests, nothing else; candidate 280/280 passed, 19/19 files green. Zero other regressions. `tsc --noEmit`: clean, 0 errors, both ways — and the fix's `Record<TaskPriority, number>` (replacing the old untyped `Record<string, number>`) now makes TypeScript itself reject a future key mismatch at compile time. Independently re-reproduced end-to-end by an adversarial critic (own stash/pop cycle, own hand-trace of the enqueue-order math, own full-suite + tsc run): **CONFIRMED, no blocking issues.**++Blast radius: `getQueuePosition()` has exactly one call site (`queueTask()`), emitting `taskQueuedEvent`'s `position` field. Grep-confirmed no other consumer of that field anywhere in `v3/` (a same-named `taskQueuedEvent` in the sibling `@claude-flow/shared` package is a different, unrelated event shape whose handler never reads `position`).++## Darwin Results++Skipped — binary correctness fix (swap a map's keys to match the real `TaskPriority` type), no continuous/categorical parameter for Darwin's real interface (`npx ruvector harness darwin <config> --execute`, confirmed available in STEP 0.5) to search over. Same skip class as nearly every accepted fix since 2026-08-18 (#3110/.../#4138).++## SOTA Proof & Witness++```+Session commit: 55e2c9011c20d25e347a175427ca8084dacde40c+Candidate commit: (this branch's head — see PR for exact SHA)+Gist SHA-256 (pre-witness, this block stripped back to PENDING): f24b247c36ec96f21cd717fc9b760b85dda5780f087fc039ad16ceb9ad2ce348+Witness stamp: fab09db09b34d6878ec1ee15e94fae9aaab818c3fb9c2cf7a7d4b02d6de4b444+```+Verifier: fetch `docs/dream-cycle/dream-gist-2026-10-14.md` from this branch, strip this witness block's filled-in values back to `PENDING`, SHA-256 the file, concatenate with the session commit above, SHA-256 again — must equal the witness stamp.++## Recommended Next Steps++1. **Wire a real liveness signal into `AgentRegistry.heartbeat()`** (or disable its false-positive health-check path) in `v3/@claude-flow/swarm/src/coordination/agent-registry.ts` — every `SwarmHub`-based consumer currently sees agents falsely flip to `'error'` ~15s after spawn. Needs a design call on the signal source; deferred from tonight to keep the patch to one conceptual change.+2. **Fix `graph-analyzer.ts`'s native-acceleration detection** (`v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts`) to probe for the real `[email protected]` exports (`buildGraph`/`minCut`/`louvainCommunities`) instead of the always-false `hooks_graph_mincut`/`hooks_graph_cluster`/`GraphAnalyzer` checks — resolves the 10-09/10-10 contradiction with a concrete adapter fix; `louvainCommunities()`'s real return shape needs closer verification (returned `{}` in a 3-node smoke test) before wiring.+3. **Mirror `TopologyManager.updateNode()`'s connection updates into neighbor adjacency lists** — third occurrence of the edge-mirroring bug class (after 08-29 mesh, 09-19 hierarchical/centralized); currently unreachable from production (`UnifiedSwarmCoordinator` never calls `updateNode()`), so lower urgency than #1, but a real latent correctness gap for any future caller.diff --git a/v3/@claude-flow/swarm/__tests__/task-orchestrator.queue-position.test.ts b/v3/@claude-flow/swarm/__tests__/task-orchestrator.queue-position.test.tsnew file mode 100644index 0000000000..d4e26ff493--- /dev/null+++ b/v3/@claude-flow/swarm/__tests__/task-orchestrator.queue-position.test.ts@@ -0,0 +1,122 @@+/**+ * Discriminating regression test for the Dream Cycle 2026-10-14 (swarm) fix:+ * TaskOrchestrator.getQueuePosition()'s private `priorityOrder` map used keys+ * `critical/high/normal/low/background`, but `TaskPriority` (shared/types.ts)+ * is `critical/high/medium/low` — there is no `'normal'` key. `createTask()`+ * defaults `priority` to `'medium'` when unspecified, so a default-priority+ * task's lookup (`priorityOrder['medium']`) was always `undefined`, falling+ * back to `0` in the sort comparator — ranking it BELOW even `'low'` (value+ * 2) instead of between `'high'` and `'low'` where it belongs. This only+ * affected the `position` number emitted on the `task:queued` event+ * (`taskQueuedEvent`); real dispatch order via `getNextTask()`/+ * `getPriorityQueue()` uses a separate, already-correct map and was never+ * affected.+ */++import { describe, it, expect, beforeEach } from 'vitest';+import { EventBus } from '../src/shared/events.js';+import { createAgentRegistry } from '../src/coordination/agent-registry.js';+import { createTaskOrchestrator, type ITaskOrchestrator } from '../src/coordination/task-orchestrator.js';+import type { IEventBus } from '../src/shared/events.js';+import type { SwarmEvent } from '../src/shared/types.js';++describe('TaskOrchestrator.getQueuePosition() — priority ranking', () => {+ let eventBus: IEventBus;+ let orchestrator: ITaskOrchestrator;+ let queuedPositions: Map<string, number>;++ beforeEach(() => {+ eventBus = new EventBus();+ const agentRegistry = createAgentRegistry(eventBus);+ orchestrator = createTaskOrchestrator(eventBus, agentRegistry);++ queuedPositions = new Map();+ eventBus.subscribe<{ taskId: string; position: number }>('task:queued', (event: SwarmEvent) => {+ const payload = event.payload as { taskId: string; position: number };+ queuedPositions.set(payload.taskId, payload.position);+ });+ });++ it('ranks a default-priority (medium) task ahead of an already-queued low-priority task', () => {+ const lowTask = orchestrator.createTask({+ type: 'implementation',+ title: 'low priority task',+ description: 'control',+ domain: 'core',+ phase: 'phase-1-foundation',+ priority: 'low',+ });+ orchestrator.queueTask(lowTask.id);+ expect(queuedPositions.get(lowTask.id)).toBe(1);++ // No `priority` given — createTask() defaults to 'medium'.+ const mediumTask = orchestrator.createTask({+ type: 'implementation',+ title: 'default priority task',+ description: 'discriminating case',+ domain: 'core',+ phase: 'phase-1-foundation',+ });+ expect(mediumTask.priority).toBe('medium');+ orchestrator.queueTask(mediumTask.id);++ // Baseline (buggy map): medium falls through to `|| 0`, sorts behind+ // low (value 2) → position 2. Fixed: medium (2) ranks above low (1)+ // → position 1.+ expect(queuedPositions.get(mediumTask.id)).toBe(1);+ });++ it('ranks medium correctly relative to low/critical/high as each is queued in turn', () => {+ // Positions are a snapshot computed at the moment each task is queued+ // (queueTask() -> getQueuePosition() -> emitSync), not retroactively+ // recalculated for already-queued tasks — that enqueue-time-snapshot+ // behavior is pre-existing and unchanged by this fix. Queuing in+ // low -> critical -> high -> medium order isolates medium's own+ // ranking: baseline (buggy map) has medium fall through to `|| 0`,+ // landing it last (position 4) behind every other priority including+ // the already-queued low; fixed, it correctly lands between high and+ // low (position 3). low/critical/high's positions are identical+ // between baseline and fixed — only medium's is expected to differ.+ const specs: Array<{ title: string; priority: 'low' | 'critical' | 'high' | 'medium' }> = [+ { title: 'low', priority: 'low' },+ { title: 'critical', priority: 'critical' },+ { title: 'high', priority: 'high' },+ { title: 'medium', priority: 'medium' },+ ];++ const ids: Record<string, string> = {};+ for (const spec of specs) {+ const task = orchestrator.createTask({+ type: 'implementation',+ title: spec.title,+ description: 'ranking case',+ domain: 'core',+ phase: 'phase-1-foundation',+ priority: spec.priority,+ });+ ids[spec.priority] = task.id;+ orchestrator.queueTask(task.id);+ }++ expect(queuedPositions.get(ids.low)).toBe(1);+ expect(queuedPositions.get(ids.critical)).toBe(1);+ expect(queuedPositions.get(ids.high)).toBe(2);+ expect(queuedPositions.get(ids.medium)).toBe(3);+ });++ it('leaves real dispatch order (getNextTask) unaffected — already correct, untouched by this fix', () => {+ const low = orchestrator.createTask({+ type: 'implementation', title: 'low', description: 'd', domain: 'core',+ phase: 'phase-1-foundation', priority: 'low',+ });+ const medium = orchestrator.createTask({+ type: 'implementation', title: 'medium', description: 'd', domain: 'core',+ phase: 'phase-1-foundation', priority: 'medium',+ });+ orchestrator.queueTask(low.id);+ orchestrator.queueTask(medium.id);++ const next = orchestrator.getNextTask();+ expect(next?.id).toBe(medium.id);+ });+});diff --git a/v3/@claude-flow/swarm/src/coordination/task-orchestrator.ts b/v3/@claude-flow/swarm/src/coordination/task-orchestrator.tsindex 49d0075756..6c6b697134 100644--- a/v3/@claude-flow/swarm/src/coordination/task-orchestrator.ts+++ b/v3/@claude-flow/swarm/src/coordination/task-orchestrator.ts@@ -598,12 +598,11 @@ export class TaskOrchestrator implements ITaskOrchestrator {}private getQueuePosition(taskId: TaskId): number {- const priorityOrder: Record<string, number> = {- critical: 5,- high: 4,- normal: 3,- low: 2,- background: 1,+ const priorityOrder: Record<TaskPriority, number> = {+ critical: 4,+ high: 3,+ medium: 2,+ low: 1,};const queuedTasks = Array.from(this.tasks.values())