Skip to content

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

refactor(cos): collapse executionLanes to priority tags

Adam Eivy9d007bfdb457
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 47d0f338be..cc2e065c9a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -32,6 +32,7 @@
## Changed
+- **Execution lanes are now priority tags, not concurrency gates.** `server/services/executionLanes.js` previously had its own `maxConcurrent` caps per lane (critical: 1, standard: 2, background: 3) on top of the user-configurable global/per-app caps in `cos.js` (`maxConcurrentAgents`, `maxConcurrentAgentsPerProject`). The lane gates were silently shadowing the user's settings — bumping `maxConcurrentAgents` to 8 still capped throughput at 6 because the lane subsystem refused to accept the 7th and 8th agents — and on backpressure `agentLifecycle` would `waitForLane` for up to 30s before bailing, which manifested as "agent stuck queueing" in the UI for tasks that should have spawned immediately. Removed the per-lane cap, the lane-internal waiting queue, the timeout/promotion-on-capacity path, and the `hasCapacity`/`waitForLane`/`updateLaneConfig` exports; `acquire` now always succeeds for known lanes, `promote` no longer rejects when the target lane is "full", and `getStats`/`getLaneStatus` drop the `maxConcurrent`/`available`/`queueLength`/`utilizationPercent` fields. Lanes still carry `priority` and per-agent `{ startedAt, taskId, metadata }` for observability. `agentLifecycle.spawnAgentForTask` now just tags the agent's lane and continues — global capacity is enforced once, upstream, where the user can actually configure it. Existing tests rewritten to match: 5 deleted (capacity/wait/queue cases), 3 reframed to assert "lane is a tag, not a gate", and the `cleanupAgentWorktree` mock simplified to remove `hasCapacity`/`waitForLane`. Files: `server/services/executionLanes.js`, `server/services/executionLanes.test.js`, `server/services/agentLifecycle.js`, `server/services/cleanupAgentWorktree.test.js`.
- **Dashboard fills the full content area on wide monitors.** The Dashboard page was wrapped in `max-w-7xl mx-auto` like the rest of the app, so on monitors wider than ~1280px there were huge empty side margins next to a relatively narrow widget grid. Since the dashboard's grid renderer is already designed to flex across whatever space it's given (12-column grid, snap-to-grid drag/resize), the cap was wasted real estate — moved the dashboard route (`/`) out of the capped branch in `Layout.jsx` so widgets now fill the full width of the main content area while keeping the existing `p-4 md:p-6` gutter for a consistent margin. No behavior change on smaller viewports (where the cap was never reached) or on other pages. File: `client/src/components/Layout.jsx`.
- **Test coverage: +89 tests across 11 previously-uncovered modules.** Added focused unit tests for low-level utilities and route handlers that had 0% coverage in the baseline coverage report: `lib/sseUtils.js` (broadcast/attach/cleanup of SSE clients and the Python-noise filter), `lib/tailscale.js` (CLI-binary discovery across PATH and well-known install paths), `lib/zipStream.js` (streaming ZIP parser — stored + DEFLATE entries, multi-chunk arrival, path-traversal sanitization, autodrain), `lib/execGit.js` (timeout, maxBuffer overflow, ignoreExitCode, spawn-error paths), `routes/avatar.js` (404 + streaming + ENOENT/EIO mid-stream errors via deferred-emit Readable), `routes/agents.js` (kill/list/info with status + body-shape assertions), `routes/notifications.js` (full CRUD, 404 propagation), `routes/usage.js` (summary/raw/session/messages/tokens/reset), `routes/backup.js` (status, run with/without dest, snapshots, restore + zod validation), `services/agentDrafts.js` (per-agent CRUD, sort by createdAt via fake timers, scoping), `services/brainGraph.js` (Jaccard threshold, bridge remap, missing-bridge dropping, dedup with memory edges, getGraphData failure fallback). Total server suite: 2633 → 2722 tests across 103 → 114 files; all pass.
- **Refactor: 19 files now use `fetchWithTimeout` instead of hand-rolled `AbortController + setTimeout + fetch + clearTimeout` blocks.** Net 75 lines deleted across `server/services/{browserService, calendarApiSync, digital-twin-helpers, feeds, insightsService, lmStudioManager, memoryClassifier, memoryEmbeddings, messageApiSync, messagePlaywrightSync, messageTokenExtractor, pm2Standardizer, syncOrchestrator, visionTest}.js`, `server/services/voice/{bootstrap, health, stt}.js`, and `server/integrations/{moltbook, moltworld}/api.js`. The helper at `server/lib/fetchWithTimeout.js` already existed and was tested — most call sites just hadn't been migrated. Each file also extracts its magic timeout numbers (3000, 10000, 30000, 60000, 120000, 180000, 300000) to named constants like `HEALTH_TIMEOUT_MS`, `GRAPH_API_TIMEOUT_MS`, `MODEL_LOAD_TIMEOUT_MS`, `DEFAULT_AI_TIMEOUT_MS` so the request lifecycle stops being four scattered statements per call. `browserService.js` additionally hoists three duplicate dynamic `await import('child_process')` / `await import('util')` blocks (one per PM2 helper) to a single top-level import + `execFileAsync` / `PM2_SHELL` constants, and `messageApiSync.js` lifts a per-401 dynamic `await import('./messageTokenExtractor.js')` to a top-level import. All 2633 server tests still pass.
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 50f8aa07f6..5c01d9981e 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -20,7 +20,7 @@ import { isInternalTaskId } from '../lib/taskParser.js';
import { ensureDir, PATHS } from '../lib/fileUtils.js';
import { getAppById } from './apps.js';
import { createToolExecution, startExecution, completeExecution, errorExecution } from './toolStateMachine.js';
-import { determineLane, acquire, release, hasCapacity, waitForLane } from './executionLanes.js';
+import { determineLane, acquire, release } from './executionLanes.js';
import { detectConflicts } from './taskConflict.js';
import { createWorktree, removeWorktree } from './worktreeManager.js';
import * as jiraService from './jira.js';
@@ -135,24 +135,14 @@ export async function spawnAgentForTask(task) {
const agentId = `agent-${uuidv4().slice(0, 8)}`;
- // Determine execution lane and acquire slot
+ // Tag agent with execution lane (priority/observability only — concurrency
+ // is gated upstream by maxConcurrentAgents + maxConcurrentAgentsPerProject).
const laneName = determineLane(task);
- if (!hasCapacity(laneName)) {
- // Wait for lane availability (max 30 seconds)
- const laneResult = await waitForLane(laneName, agentId, { timeoutMs: 30000, metadata: { taskId: task.id } });
- if (!laneResult.success) {
- spawningTasks.delete(task.id);
- emitLog('warn', `Lane ${laneName} unavailable for task ${task.id}, deferring`, { taskId: task.id, lane: laneName });
- cosEvents.emit('agent:deferred', { taskId: task.id, reason: 'lane-capacity', lane: laneName });
- return null;
- }
- } else {
- const laneResult = acquire(laneName, agentId, { taskId: task.id });
- if (!laneResult.success) {
- spawningTasks.delete(task.id);
- emitLog('warn', `Failed to acquire lane ${laneName}: ${laneResult.error}`, { taskId: task.id });
- return null;
- }
+ const laneResult = acquire(laneName, agentId, { taskId: task.id });
+ if (!laneResult.success) {
+ spawningTasks.delete(task.id);
+ emitLog('warn', `Failed to tag lane ${laneName}: ${laneResult.error}`, { taskId: task.id });
+ return null;
}
// Create tool execution for state tracking
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 1a5e5e5821..7c100d2687 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -135,10 +135,8 @@ vi.mock('./thinkingLevels.js', () => ({
vi.mock('./executionLanes.js', () => ({
determineLane: vi.fn(),
- acquire: vi.fn(),
- release: vi.fn(),
- hasCapacity: vi.fn(() => true),
- waitForLane: vi.fn()
+ acquire: vi.fn(() => ({ success: true })),
+ release: vi.fn()
}));
vi.mock('./taskConflict.js', () => ({
diff --git a/server/services/executionLanes.js b/server/services/executionLanes.js
index aab95253df..048faf36c4 100644
--- a/server/services/executionLanes.js
+++ b/server/services/executionLanes.js
@@ -1,59 +1,47 @@
/**
* Execution Lanes Service
*
- * Lane-based concurrency control for agent execution.
- * Lanes: critical (1), standard (2), background (3)
+ * Lane-based tagging for agent execution (priority/observability only).
+ * Lanes carry priority intent — they no longer gate concurrency.
+ * Global slot caps and per-app caps live in cos.js (`maxConcurrentAgents`,
+ * `maxConcurrentAgentsPerProject`); duplicating them here was shadowing the
+ * user-configurable limits and is gone.
*/
import { cosEvents } from './cosEvents.js'
-// Lane configuration
const LANES = {
critical: {
name: 'critical',
- maxConcurrent: 1,
priority: 1,
description: 'High-priority user tasks, blocking operations'
},
standard: {
name: 'standard',
- maxConcurrent: 2,
priority: 2,
description: 'Normal task execution'
},
background: {
name: 'background',
- maxConcurrent: 3,
priority: 3,
description: 'Self-improvement, idle work, non-urgent tasks'
}
}
-// Lane occupancy tracking
const laneOccupancy = {
critical: new Map(), // agentId -> { taskId, startedAt, metadata }
standard: new Map(),
background: new Map()
}
-// Queue for tasks waiting for lane availability
-const waitingQueue = {
- critical: [],
- standard: [],
- background: []
-}
-
-// Statistics
const stats = {
acquired: 0,
released: 0,
- queued: 0,
- timeouts: 0,
promotions: 0
}
/**
- * Get lane by name or determine from task priority
+ * Get lane by name or determine from task priority.
* @param {string|Object} laneOrTask - Lane name or task object
* @returns {string} - Lane name
*/
@@ -81,36 +69,20 @@ function determineLane(laneOrTask) {
}
/**
- * Check if a lane has available capacity
- * @param {string} laneName - Lane name
- * @returns {boolean} - True if capacity available
- */
-function hasCapacity(laneName) {
- const lane = LANES[laneName]
- if (!lane) return false
-
- const occupancy = laneOccupancy[laneName]
- return occupancy.size < lane.maxConcurrent
-}
-
-/**
- * Get current lane status
+ * Get current lane status (occupancy snapshot for observability).
* @param {string} laneName - Lane name
- * @returns {Object} - Lane status
+ * @returns {Object|null}
*/
function getLaneStatus(laneName) {
const lane = LANES[laneName]
if (!lane) return null
const occupancy = laneOccupancy[laneName]
- const queue = waitingQueue[laneName]
return {
name: lane.name,
- maxConcurrent: lane.maxConcurrent,
+ priority: lane.priority,
currentOccupancy: occupancy.size,
- available: lane.maxConcurrent - occupancy.size,
- queueLength: queue.length,
occupants: Array.from(occupancy.entries()).map(([agentId, data]) => ({
agentId,
taskId: data.taskId,
@@ -121,11 +93,8 @@ function getLaneStatus(laneName) {
}
/**
- * Acquire a slot in a lane
- * @param {string} laneName - Lane name
- * @param {string} agentId - Agent identifier
- * @param {Object} metadata - Additional metadata (taskId, etc.)
- * @returns {Object} - Acquisition result
+ * Tag an agent with a lane. Always succeeds for known lanes — capacity
+ * gating happens upstream in cos.js, not here.
*/
function acquire(laneName, agentId, metadata = {}) {
const lane = LANES[laneName]
@@ -135,23 +104,10 @@ function acquire(laneName, agentId, metadata = {}) {
const occupancy = laneOccupancy[laneName]
- // Check if already in this lane
if (occupancy.has(agentId)) {
return { success: true, alreadyAcquired: true, lane: laneName }
}
- // Check capacity
- if (occupancy.size >= lane.maxConcurrent) {
- return {
- success: false,
- error: 'Lane at capacity',
- lane: laneName,
- currentOccupancy: occupancy.size,
- maxConcurrent: lane.maxConcurrent
- }
- }
-
- // Acquire slot
occupancy.set(agentId, {
taskId: metadata.taskId,
startedAt: Date.now(),
@@ -167,19 +123,13 @@ function acquire(laneName, agentId, metadata = {}) {
occupancy: occupancy.size
})
- console.log(`🛤️ Lane acquired: ${agentId} → ${laneName} (${occupancy.size}/${lane.maxConcurrent})`)
+ console.log(`🛤️ Lane acquired: ${agentId} → ${laneName} (${occupancy.size})`)
- return {
- success: true,
- lane: laneName,
- position: occupancy.size
- }
+ return { success: true, lane: laneName }
}
/**
- * Release a lane slot
- * @param {string} agentId - Agent identifier
- * @returns {Object} - Release result
+ * Release an agent's lane tag.
*/
function release(agentId) {
for (const [laneName, occupancy] of Object.entries(laneOccupancy)) {
@@ -201,14 +151,7 @@ function release(agentId) {
console.log(`🛤️ Lane released: ${agentId} ← ${laneName} (ran ${runningMs}ms)`)
- // Process waiting queue for this lane
- processWaitingQueue(laneName)
-
- return {
- success: true,
- lane: laneName,
- runningMs
- }
+ return { success: true, lane: laneName, runningMs }
}
}
@@ -216,83 +159,7 @@ function release(agentId) {
}
/**
- * Wait for lane availability (with timeout)
- * @param {string} laneName - Lane name
- * @param {string} agentId - Agent identifier
- * @param {Object} options - Wait options
- * @returns {Promise<Object>} - Acquisition result
- */
-async function waitForLane(laneName, agentId, options = {}) {
- const { timeoutMs = 60000, metadata = {} } = options
-
- // Try immediate acquisition
- const immediate = acquire(laneName, agentId, metadata)
- if (immediate.success) return immediate
-
- // Add to waiting queue
- return new Promise((resolve) => {
- const queueEntry = {
- agentId,
- metadata,
- resolve,
- enqueuedAt: Date.now()
- }
-
- waitingQueue[laneName].push(queueEntry)
- stats.queued++
-
- console.log(`⏳ Queued for lane: ${agentId} → ${laneName} (position ${waitingQueue[laneName].length})`)
-
- // Set timeout
- const timeoutId = setTimeout(() => {
- const idx = waitingQueue[laneName].indexOf(queueEntry)
- if (idx !== -1) {
- waitingQueue[laneName].splice(idx, 1)
- stats.timeouts++
- resolve({
- success: false,
- error: 'Lane wait timeout',
- lane: laneName,
- waitedMs: timeoutMs
- })
- }
- }, timeoutMs)
-
- queueEntry.timeoutId = timeoutId
- })
-}
-
-/**
- * Process waiting queue when a lane slot becomes available
- * @param {string} laneName - Lane name
- */
-function processWaitingQueue(laneName) {
- const queue = waitingQueue[laneName]
- if (queue.length === 0) return
-
- const lane = LANES[laneName]
- const occupancy = laneOccupancy[laneName]
-
- while (queue.length > 0 && occupancy.size < lane.maxConcurrent) {
- const entry = queue.shift()
- clearTimeout(entry.timeoutId)
-
- const result = acquire(laneName, entry.agentId, entry.metadata)
- if (result.success) {
- result.waitedMs = Date.now() - entry.enqueuedAt
- entry.resolve(result)
- } else {
- // Failed to acquire despite capacity - shouldn't happen
- entry.resolve(result)
- }
- }
-}
-
-/**
- * Promote a task to a higher priority lane
- * @param {string} agentId - Agent identifier
- * @param {string} targetLane - Target lane (must be higher priority)
- * @returns {Object} - Promotion result
+ * Re-tag an agent into a higher-priority lane.
*/
function promote(agentId, targetLane) {
const targetLaneConfig = LANES[targetLane]
@@ -300,7 +167,6 @@ function promote(agentId, targetLane) {
return { success: false, error: `Unknown lane: ${targetLane}` }
}
- // Find current lane
let currentLane = null
for (const [laneName, occupancy] of Object.entries(laneOccupancy)) {
if (occupancy.has(agentId)) {
@@ -313,17 +179,10 @@ function promote(agentId, targetLane) {
return { success: false, error: 'Agent not in any lane' }
}
- // Check if promotion makes sense
if (LANES[currentLane].priority <= targetLaneConfig.priority) {
return { success: false, error: 'Target lane is not higher priority' }
}
- // Check target capacity
- if (!hasCapacity(targetLane)) {
- return { success: false, error: 'Target lane at capacity' }
- }
-
- // Move agent
const data = laneOccupancy[currentLane].get(agentId)
laneOccupancy[currentLane].delete(agentId)
laneOccupancy[targetLane].set(agentId, data)
@@ -332,49 +191,28 @@ function promote(agentId, targetLane) {
console.log(`⬆️ Lane promotion: ${agentId} ${currentLane} → ${targetLane}`)
- // Process queue for old lane
- processWaitingQueue(currentLane)
-
- return {
- success: true,
- fromLane: currentLane,
- toLane: targetLane
- }
+ return { success: true, fromLane: currentLane, toLane: targetLane }
}
/**
- * Get overall lane statistics
- * @returns {Object} - Lane statistics
+ * Aggregate lane statistics for observability.
*/
function getStats() {
const laneStats = {}
-
for (const laneName of Object.keys(LANES)) {
laneStats[laneName] = getLaneStatus(laneName)
}
const totalOccupancy = Object.values(laneOccupancy)
.reduce((sum, map) => sum + map.size, 0)
- const totalCapacity = Object.values(LANES)
- .reduce((sum, lane) => sum + lane.maxConcurrent, 0)
- const totalQueued = Object.values(waitingQueue)
- .reduce((sum, queue) => sum + queue.length, 0)
return {
lanes: laneStats,
totalOccupancy,
- totalCapacity,
- utilizationPercent: ((totalOccupancy / totalCapacity) * 100).toFixed(1) + '%',
- totalQueued,
...stats
}
}
-/**
- * Get agent's current lane
- * @param {string} agentId - Agent identifier
- * @returns {string|null} - Lane name or null
- */
function getAgentLane(agentId) {
for (const [laneName, occupancy] of Object.entries(laneOccupancy)) {
if (occupancy.has(agentId)) {
@@ -385,9 +223,7 @@ function getAgentLane(agentId) {
}
/**
- * Force release all agents from a lane (for emergencies)
- * @param {string} laneName - Lane name
- * @returns {number} - Number of agents released
+ * Force-release every agent from a lane (test/recovery helper).
*/
function clearLane(laneName) {
const occupancy = laneOccupancy[laneName]
@@ -404,37 +240,14 @@ function clearLane(laneName) {
return count
}
-/**
- * Update lane configuration dynamically
- * @param {string} laneName - Lane name
- * @param {Object} config - New configuration
- * @returns {Object} - Updated lane config
- */
-function updateLaneConfig(laneName, config) {
- const lane = LANES[laneName]
- if (!lane) return null
-
- if (config.maxConcurrent !== undefined) {
- lane.maxConcurrent = config.maxConcurrent
-
- // Process queue if we increased capacity
- processWaitingQueue(laneName)
- }
-
- return { ...lane }
-}
-
export {
LANES,
determineLane,
- hasCapacity,
getLaneStatus,
acquire,
release,
- waitForLane,
promote,
getStats,
getAgentLane,
- clearLane,
- updateLaneConfig
+ clearLane
}
diff --git a/server/services/executionLanes.test.js b/server/services/executionLanes.test.js
index 8a1638d87b..09384b219c 100644
--- a/server/services/executionLanes.test.js
+++ b/server/services/executionLanes.test.js
@@ -2,28 +2,21 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
import {
LANES,
determineLane,
- hasCapacity,
getLaneStatus,
acquire,
release,
- waitForLane,
promote,
getStats,
getAgentLane,
- clearLane,
- updateLaneConfig
+ clearLane
} from './executionLanes.js';
-// Mock the cosEvents
-vi.mock('./cos.js', () => ({
- cosEvents: {
- emit: vi.fn()
- }
+vi.mock('./cosEvents.js', () => ({
+ cosEvents: { emit: vi.fn() }
}));
describe('Execution Lanes Service', () => {
beforeEach(() => {
- // Clear all lanes before each test
clearLane('critical');
clearLane('standard');
clearLane('background');
@@ -36,16 +29,16 @@ describe('Execution Lanes Service', () => {
expect(LANES.background).toBeDefined();
});
- it('should have correct max concurrent values', () => {
- expect(LANES.critical.maxConcurrent).toBe(1);
- expect(LANES.standard.maxConcurrent).toBe(2);
- expect(LANES.background.maxConcurrent).toBe(3);
- });
-
- it('should have priority ordering', () => {
+ it('should have priority ordering (critical < standard < background)', () => {
expect(LANES.critical.priority).toBeLessThan(LANES.standard.priority);
expect(LANES.standard.priority).toBeLessThan(LANES.background.priority);
});
+
+ it('should not expose maxConcurrent — lanes are tags, not gates', () => {
+ expect(LANES.critical.maxConcurrent).toBeUndefined();
+ expect(LANES.standard.maxConcurrent).toBeUndefined();
+ expect(LANES.background.maxConcurrent).toBeUndefined();
+ });
});
describe('determineLane', () => {
@@ -81,36 +74,13 @@ describe('Execution Lanes Service', () => {
});
});
- describe('hasCapacity', () => {
- it('should return true for empty lanes', () => {
- expect(hasCapacity('critical')).toBe(true);
- expect(hasCapacity('standard')).toBe(true);
- expect(hasCapacity('background')).toBe(true);
- });
-
- it('should return false for unknown lane', () => {
- expect(hasCapacity('unknown')).toBe(false);
- });
-
- it('should return false when lane is at capacity', () => {
- acquire('critical', 'agent-1');
- expect(hasCapacity('critical')).toBe(false);
- });
-
- it('should return true when lane has capacity', () => {
- acquire('standard', 'agent-1');
- expect(hasCapacity('standard')).toBe(true); // Can hold 2
- });
- });
-
describe('getLaneStatus', () => {
it('should return lane status', () => {
const status = getLaneStatus('standard');
expect(status.name).toBe('standard');
- expect(status.maxConcurrent).toBe(2);
+ expect(status.priority).toBe(LANES.standard.priority);
expect(status.currentOccupancy).toBe(0);
- expect(status.available).toBe(2);
});
it('should return null for unknown lane', () => {
@@ -128,7 +98,7 @@ describe('Execution Lanes Service', () => {
});
describe('acquire', () => {
- it('should acquire a lane slot', () => {
+ it('should tag an agent with a lane', () => {
const result = acquire('standard', 'agent-1', { taskId: 'task-1' });
expect(result.success).toBe(true);
@@ -142,12 +112,14 @@ describe('Execution Lanes Service', () => {
expect(result.error).toContain('Unknown lane');
});
- it('should fail when lane is at capacity', () => {
- acquire('critical', 'agent-1');
- const result = acquire('critical', 'agent-2');
-
- expect(result.success).toBe(false);
- expect(result.error).toBe('Lane at capacity');
+ it('should NOT gate on capacity — many agents can share a lane', () => {
+ // Concurrency gating moved upstream (maxConcurrentAgents in cos.js).
+ // The lane subsystem must accept any number of agents in a lane.
+ for (let i = 1; i <= 10; i++) {
+ const result = acquire('standard', `agent-${i}`);
+ expect(result.success).toBe(true);
+ }
+ expect(getLaneStatus('standard').currentOccupancy).toBe(10);
});
it('should return success if already acquired', () => {
@@ -160,7 +132,7 @@ describe('Execution Lanes Service', () => {
});
describe('release', () => {
- it('should release a lane slot', () => {
+ it('should release a lane tag', () => {
acquire('standard', 'agent-1');
const result = release('agent-1');
@@ -175,51 +147,6 @@ describe('Execution Lanes Service', () => {
expect(result.success).toBe(false);
expect(result.error).toBe('Agent not in any lane');
});
-
- it('should free up capacity', () => {
- acquire('critical', 'agent-1');
- expect(hasCapacity('critical')).toBe(false);
-
- release('agent-1');
- expect(hasCapacity('critical')).toBe(true);
- });
- });
-
- describe('waitForLane', () => {
- it('should acquire immediately if capacity available', async () => {
- const result = await waitForLane('standard', 'agent-1', {
- metadata: { taskId: 'task-1' }
- });
-
- expect(result.success).toBe(true);
- });
-
- it('should timeout when lane stays at capacity', async () => {
- acquire('critical', 'agent-1');
-
- const result = await waitForLane('critical', 'agent-2', {
- timeoutMs: 100
- });
-
- expect(result.success).toBe(false);
- expect(result.error).toBe('Lane wait timeout');
- });
-
- it('should acquire when slot becomes available', async () => {
- acquire('critical', 'agent-1');
-
- // Start waiting
- const waitPromise = waitForLane('critical', 'agent-2', {
- timeoutMs: 1000
- });
-
- // Release after short delay
- setTimeout(() => release('agent-1'), 50);
-
- const result = await waitPromise;
- expect(result.success).toBe(true);
- expect(result.waitedMs).toBeGreaterThan(0);
- });
});
describe('promote', () => {
@@ -254,13 +181,15 @@ describe('Execution Lanes Service', () => {
expect(result.error).toBe('Target lane is not higher priority');
});
- it('should fail if target lane at capacity', () => {
+ it('should NOT gate on target lane capacity', () => {
+ // Promote no longer cares about capacity — lanes are tags.
acquire('critical', 'agent-1');
acquire('standard', 'agent-2');
const result = promote('agent-2', 'critical');
- expect(result.success).toBe(false);
- expect(result.error).toBe('Target lane at capacity');
+ expect(result.success).toBe(true);
+ expect(result.toLane).toBe('critical');
+ expect(getLaneStatus('critical').currentOccupancy).toBe(2);
});
});
@@ -272,7 +201,6 @@ describe('Execution Lanes Service', () => {
const stats = getStats();
expect(stats.totalOccupancy).toBe(2);
- expect(stats.totalCapacity).toBe(6); // 1 + 2 + 3
expect(stats.lanes.standard.currentOccupancy).toBe(1);
expect(stats.lanes.background.currentOccupancy).toBe(1);
});
@@ -306,7 +234,6 @@ describe('Execution Lanes Service', () => {
const count = clearLane('standard');
expect(count).toBe(2);
- expect(hasCapacity('standard')).toBe(true);
expect(getLaneStatus('standard').currentOccupancy).toBe(0);
});
@@ -314,20 +241,4 @@ describe('Execution Lanes Service', () => {
expect(clearLane('unknown')).toBe(0);
});
});
-
- describe('updateLaneConfig', () => {
- it('should update lane max concurrent', () => {
- const originalMax = LANES.standard.maxConcurrent;
- updateLaneConfig('standard', { maxConcurrent: 5 });
-
- expect(LANES.standard.maxConcurrent).toBe(5);
-
- // Restore
- updateLaneConfig('standard', { maxConcurrent: originalMax });
- });
-
- it('should return null for unknown lane', () => {
- expect(updateLaneConfig('unknown', {})).toBeNull();
- });
- });
});