Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: keep active agents on upheld review challenges (#8946)
[._.]/ Adam Eivyd3cf1e7bbe44
diff --git a/server/services/agentSpawnPreparation.js b/server/services/agentSpawnPreparation.jsindex 55d7e6c9a2..4b3987af16 100644--- a/server/services/agentSpawnPreparation.js+++ b/server/services/agentSpawnPreparation.js@@ -1,4 +1,6 @@import { cosEvents, emitLog } from './cosEvents.js';+import { loadState } from './cosState.js';+import { hasActiveTaskOwner } from './agentState.js';import { getTaskById, updateTask } from './cos.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';import { isInternalTaskId } from '../lib/taskParser.js';@@ -90,6 +92,14 @@ export async function prepareAgentSpawn(task, context = createAgentSpawnContext(task.taskType = isInternalTaskId(task.id || '') ? 'internal' : 'user';}+ // The spawn lock only covers dispatch. A prior run can own this task long+ // after that lock and the presentation-only spawn grace window end.+ const state = await loadState();+ if (hasActiveTaskOwner(task.id, state.agents)) {+ console.warn(`⚠️ Task ${task.id} already has an active owner — skipping duplicate dispatch`);+ return null;+ }+let instanceId;try {instanceId = await ensureInstanceId();diff --git a/server/services/agentState.js b/server/services/agentState.jsindex 03f2952010..3192431640 100644--- a/server/services/agentState.js+++ b/server/services/agentState.js@@ -160,6 +160,22 @@ export const protectedAgentIds = (agents = []) => {// let a stray runner `agent:completed` event double-finalize them.export const isAgentOwnedLocally = (agentId) => activeAgents.has(agentId) || runnerAgents.has(agentId);+/**+ * Keep task ownership through the whole run, including completion bookkeeping.+ * Durable running records protect restart survivors; local maps protect the+ * gap between agent completion and task completion. Age alone never releases+ * ownership: orphan/zombie recovery must retire a dead run first.+ */+export const hasActiveTaskOwner = (taskId, agents = {}) => {+ if (Object.values(agents).some(agent => agent.taskId === taskId && agent.status === 'running')) return true;+ for (const entries of [activeAgents, runnerAgents]) {+ for (const agent of entries.values()) {+ if ((agent.taskId || agent.task?.id) === taskId) return true;+ }+ }+ return false;+};+// Metadata booleans may arrive as true/'true' or false/'false' (JSON vs TASKS.md string round-trip)export const isTruthyMeta = (value) => value === true || value === 'true';export const isFalsyMeta = (value) => value === false || value === 'false';diff --git a/server/services/cosChallengeOwnership.test.js b/server/services/cosChallengeOwnership.test.jsnew file mode 100644index 0000000000..45dd7daf3a--- /dev/null+++ b/server/services/cosChallengeOwnership.test.js@@ -0,0 +1,165 @@+import { beforeEach, afterAll, describe, expect, it, vi } from 'vitest';+import { mkdtempSync } from 'node:fs';+import { rm } from 'node:fs/promises';+import { join, relative } from 'node:path';++const fixture = vi.hoisted(() => ({ root: null, state: null, ready: [] }));+vi.mock('../lib/fileUtils.js', async (original) => {+ const actual = await original();+ const { makePathsProxy, createTempDataRoot } = await import('../lib/mockPathsDataRoot.js');+ fixture.root = createTempDataRoot('portos-challenge-ownership-');+ return makePathsProxy(actual, { dataRoot: fixture.root, extraOverrides: { root: fixture.root } });+});+vi.mock('./cosState.js', async (original) => {+ const actual = await original();+ return {+ ...actual,+ isDaemonRunning: () => true,+ loadState: vi.fn(async () => fixture.state),+ };+});+vi.mock('./cos.js', async () => {+ const store = await import('./cosTaskStore.js');+ return { getTaskById: store.getTaskById, updateTask: store.updateTask, isRunning: () => false };+});+vi.mock('./instances.js', async () => {+ const { mockNoPeers } = await import('../lib/mockPathsDataRoot.js');+ return mockNoPeers();+});+vi.mock('./sharing/peerSync.js', async () => {+ const { mockNoPeerSync } = await import('../lib/mockPathsDataRoot.js');+ return mockNoPeerSync();+});+vi.mock('./notifications.js', () => ({ removeByMetadata: vi.fn(async () => 0) }));+vi.mock('./codeReview.js', () => ({ runLocalCodeReview: vi.fn(), getCodeReviewDefaults: vi.fn() }));+vi.mock('./instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'instance-test') }));+vi.mock('./agentPromptBuilder.js', () => ({ getAppWorkspace: vi.fn() }));+vi.mock('./appActivity.js', () => ({ releaseAppReviewMarker: vi.fn(async () => {}) }));+vi.mock('./toolStateMachine.js', () => ({+ createToolExecution: vi.fn(() => ({ id: 'tool-test' })),+ startExecution: vi.fn(), completeExecution: vi.fn(), errorExecution: vi.fn(),+}));+vi.mock('./executionLanes.js', () => ({+ determineLane: () => 'background', acquire: () => ({ success: true }), release: vi.fn(),+}));++vi.mock('./cosEvents.js', () => ({+ cosEvents: {+ emit: (event, task) => { if (event === 'task:ready') fixture.ready.push(task); },+ on: vi.fn(), off: vi.fn(),+ },+ emitLog: vi.fn(),+}));+vi.mock('./onDemandDrain.js', () => ({ drainOnDemandRequests: async () => ({ schedule: { tasks: {} } }) }));+vi.mock('./domainUsage.js', () => ({ getDomainBudgetStatus: async () => ({ budget: {}, usage: {} }) }));+vi.mock('./cosLocalEndpointSlots.js', () => ({+ buildLocalEndpointSlotContext: async () => ({+ endpointForAgent: () => null, resolveLocalEndpoint: () => null, limit: Infinity,+ }),+}));++import { addTask, updateTask, challengeTask, resolveTaskChallenge, getTaskById, __resetTaskCache } from './cosTaskStore.js';+import { activeAgents, runnerAgents } from './agentState.js';+import { withStateLock } from './cosState.js';+import { prepareAgentSpawn } from './agentSpawnPreparation.js';+const { dequeueNextTask } = await vi.importActual('./cos.js');++beforeEach(() => {+ __resetTaskCache();+ activeAgents.clear();+ runnerAgents.clear();+ fixture.ready = [];+ const root = relative(fixture.root, mkdtempSync(join(fixture.root, 'case-')));+ fixture.state = {+ config: { userTasksFile: join(root, 'TASKS.md'), cosTasksFile: join(root, 'COS-TASKS.md'), maxConcurrentAgents: 4 },+ agents: {},+ paused: false,+ };+});+afterAll(async () => {+ activeAgents.clear();+ runnerAgents.clear();+ await rm(fixture.root, { recursive: true, force: true });+});++async function seedOwner({ running = true } = {}) {+ const task = await addTask({ id: 'task-example', description: 'Example disputed work' });+ await updateTask(task.id, { status: 'in_progress' });+ fixture.state.agents['agent-owner'] = {+ id: 'agent-owner', taskId: task.id, status: running ? 'running' : 'completed',+ startedAt: new Date(Date.now() - 10 * 60_000).toISOString(),+ };+ return task;+}++// Run the real dequeue engine, then its task:ready dispatch admission. No+// listener starts a provider or process; the emitted tasks are captured above.+async function dequeue() {+ fixture.ready = [];+ await dequeueNextTask();+ const prepared = await Promise.all(fixture.ready.map(task => prepareAgentSpawn(task)));+ return prepared.filter(Boolean);+}++describe('challenge ownership workflow', () => {+ it('keeps an old running owner through upheld resolution and dequeue, rejecting stale direct dispatch too', async () => {+ const task = await seedOwner();+ await challengeTask(task.id, { reason: 'incorrect rejection' });+ const resolved = await resolveTaskChallenge(task.id, { outcome: 'upheld' });+ expect(resolved.status).toBe('in_progress');+ expect(await dequeue()).toEqual([]);+ expect(await prepareAgentSpawn(task)).toBeNull();+ expect(Object.keys(fixture.state.agents)).toEqual(['agent-owner']);+ // Even an independent requeue cannot dispatch a second run.+ await updateTask(task.id, { status: 'pending' });+ expect(await dequeue()).toEqual([]);+ });++ it('requeues once when the owner has been retired, allowing dead-owner recovery', async () => {+ const task = await seedOwner({ running: false });+ await challengeTask(task.id, { reason: 'incorrect rejection' });+ const results = await Promise.all([+ resolveTaskChallenge(task.id, { outcome: 'upheld' }),+ resolveTaskChallenge(task.id, { outcome: 'upheld' }),+ ]);+ expect(results.map(r => r.status || r.code)).toEqual(['pending', 'NOT_CHALLENGED']);+ expect(await dequeue()).toHaveLength(1);+ });++ it.each(['direct', 'runner'])('protects %s completion bookkeeping after the durable agent completes', async (mode) => {+ const task = await seedOwner({ running: false });+ const owners = mode === 'direct' ? activeAgents : runnerAgents;+ owners.set('agent-owner', mode === 'direct' ? { task } : { taskId: task.id });+ await challengeTask(task.id, { reason: 'incorrect rejection' });+ expect((await resolveTaskChallenge(task.id, { outcome: 'upheld' })).status).toBe('in_progress');+ expect(await prepareAgentSpawn(task)).toBeNull();+ owners.delete('agent-owner');+ await updateTask(task.id, { status: 'pending' });+ expect(await dequeue()).toHaveLength(1);+ });++ it.each(['completion-first', 'resolution-first'])('does not regress completion when racing resolution (%s)', async (order) => {+ const task = await seedOwner();+ await challengeTask(task.id, { reason: 'incorrect rejection' });+ let release;+ const held = withStateLock(() => new Promise(resolve => { release = resolve; }));+ await Promise.resolve();+ const complete = () => updateTask(task.id, { status: 'completed' });+ const resolve = () => resolveTaskChallenge(task.id, { outcome: 'upheld' });+ const first = order === 'completion-first' ? complete() : resolve();+ // updateTask performs pause preparation before queuing its write.+ await new Promise(setImmediate);+ const second = order === 'completion-first' ? resolve() : complete();+ release();+ await Promise.all([held, first, second]);+ expect((await getTaskById(task.id)).status).toBe('completed');+ });++ it('serializes challenge budget checks against competing requests', async () => {+ const task = await seedOwner();+ const results = await Promise.all([+ challengeTask(task.id, { reason: 'first' }), challengeTask(task.id, { reason: 'second' }),+ ]);+ expect(results.map(r => r.status || r.code)).toEqual(['challenged', 'CHALLENGE_EXHAUSTED']);+ });+});diff --git a/server/services/cosDequeue.js b/server/services/cosDequeue.jsindex 8ecdbd583a..2bdc88f6e7 100644--- a/server/services/cosDequeue.js+++ b/server/services/cosDequeue.js@@ -1,9 +1,9 @@/**- * CoS Dequeue — pure priority/capacity helpers (issue #2530)+ * CoS Dequeue — priority/capacity helpers (issue #2530)** The spawn-side scheduler `dequeueNextTask` (in cos.js) fills open agent slots- * by draining four priority tiers in order. This module holds the *pure*,- * side-effect-free pieces of that decision — the per-cycle capacity tracker and+ * by draining four priority tiers in order. This module holds the capacity and+ * ownership decisions — the per-cycle capacity tracker and* the idle tier-eligibility predicate — so the scheduler and its unit* tests share ONE implementation instead of the tests re-deriving a local* replica of the guards.@@ -18,6 +18,8 @@* 3 idle review.*/+import { hasActiveTaskOwner } from './agentState.js';+/*** Per-cycle spawn-capacity tracker. Owns the running `spawned` count and the* per-project tally, and exposes the exact `canSpawn` / `trackSpawn` closure the@@ -82,6 +84,7 @@ export function createDequeueCapacity(state, {let spawned = 0;const admit = (task, ceiling, gateLocalEndpoint) => {+ if (hasActiveTaskOwner(task.id, state.agents)) return false;if (spawned >= ceiling) return false;const project = task.metadata?.app || '_self';if ((spawnProjectCounts[project] || 0) >= perProjectLimit) return false;diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex 28e72a7753..3893d89f6a 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -30,6 +30,7 @@ import { PAUSED_BLOCKED_CATEGORIES, USER_DECISION_BLOCKED_CATEGORIES } from '../import { splitTaskPromptFields, TASK_PROMPT_KEY, TASK_CONTEXT_KEY } from '../lib/cosTaskPrompt.js';import { normalizeOrchestrationMode, normalizeOrchestrationProfile } from '../lib/orchestrationProfile.js';import { loadState, withStateLock, ROOT_DIR } from './cosState.js';+import { hasActiveTaskOwner } from './agentState.js';import { cosEvents } from './cosEvents.js';import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';import { mergeTaskLists } from './cosTaskMerge.js';@@ -617,7 +618,11 @@ function mergeUpdateMetadata(existingMetadata, updates) {}async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue = false, expectedStatus = null }) {- return withStateLock(async () => {+ return withStateLock(() => writeTaskUpdateLocked(taskId, updates, taskType, { now, suppressDequeue, expectedStatus }));+}++// Caller holds withStateLock, including its status and ownership decision.+async function writeTaskUpdateLocked(taskId, updates, taskType, { now, suppressDequeue = false, expectedStatus = null }) {const state = await loadState();const filePath = taskType === 'user'? join(ROOT_DIR, state.config.userTasksFile)@@ -770,7 +775,6 @@ async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeueif (suppressDequeue) change.suppressDequeue = true;cosEvents.emit('tasks:changed', change);return updatedTask;- });}/**@@ -1153,45 +1157,47 @@ export async function approveTask(taskId, { now = Date.now() } = {}) {* Parks the task in the `challenged` status with the worker's case attached and* consumes one of its bounded challenge slots (MAX_CHALLENGES_PER_TASK). A second* dispute on the same task is refused — the acceptance contract is "exactly one- * per task." The read (getTaskById, lock-free) precedes the write (updateTask,- * lock-held): single-user trust model, no competing writer to race.+ * per task." Read, budget check, and write share the completion/state lock.** @returns the updated task, or `{ error, code }` on not-found / budget-exhausted.*/export async function challengeTask(taskId, { reason, evidence, reviewer } = {}, taskType = 'user', { now = Date.now() } = {}) {- const task = await getTaskById(taskId);- if (!task) return { error: 'Task not found', code: 'NOT_FOUND' };- const resolvedType = task.taskType || taskType;- // A challenge disputes a REJECTION of in-flight work — never a finished task.- // Parking a `completed` task in `challenged` would also regress it out of a- // terminal state (a completed task never re-completes), so refuse it outright.- if (task.status === 'completed') {- return { error: 'Cannot challenge a completed task', code: 'CANNOT_CHALLENGE_COMPLETED' };- }- // Bounded by BOTH the one-shot dispute cap AND the shared retry budget (#2471) —- // a challenge that overturns re-queues the task, so refuse one that's already out- // of total spawns (it would only get re-blocked by agentLifecycle's spawn gate).- if (!canChallenge(task.metadata, { maxTotalSpawns: MAX_TOTAL_SPAWNS })) {- const spawns = Number(task.metadata?.totalSpawnCount) || 0;- const budgetExhausted = spawns >= MAX_TOTAL_SPAWNS;- return {- error: budgetExhausted- ? `Retry budget exhausted (${spawns}/${MAX_TOTAL_SPAWNS} spawns) — cannot challenge a task out of retries`- : `Challenge budget exhausted (${getChallengeCount(task.metadata)}/${MAX_CHALLENGES_PER_TASK} used)`,- code: budgetExhausted ? 'CHALLENGE_BUDGET_EXHAUSTED' : 'CHALLENGE_EXHAUSTED',- };- }- const patch = buildChallengePatch(task.metadata, { reason, evidence, reviewer, now });- const updated = await updateTask(taskId, { status: 'challenged', metadata: patch }, resolvedType, { now });- if (updated?.error) return updated;- console.log(`⚖️ Task ${taskId} challenged (${patch.challengeCount}/${MAX_CHALLENGES_PER_TASK})${patch.challenge.reviewer ? ` — disputing ${patch.challenge.reviewer}` : ''}`);- cosEvents.emit('task:challenged', { taskId, taskType: resolvedType, reviewer: patch.challenge.reviewer || null });- return updated;+ return withStateLock(async () => {+ const task = await getTaskById(taskId);+ if (!task) return { error: 'Task not found', code: 'NOT_FOUND' };+ const resolvedType = task.taskType || taskType;+ // A challenge disputes a REJECTION of in-flight work — never a finished task.+ // Parking a `completed` task in `challenged` would also regress it out of a+ // terminal state (a completed task never re-completes), so refuse it outright.+ if (task.status === 'completed') {+ return { error: 'Cannot challenge a completed task', code: 'CANNOT_CHALLENGE_COMPLETED' };+ }+ // Bounded by BOTH the one-shot dispute cap AND the shared retry budget (#2471) —+ // a challenge that overturns re-queues the task, so refuse one that's already out+ // of total spawns (it would only get re-blocked by agentLifecycle's spawn gate).+ if (!canChallenge(task.metadata, { maxTotalSpawns: MAX_TOTAL_SPAWNS })) {+ const spawns = Number(task.metadata?.totalSpawnCount) || 0;+ const budgetExhausted = spawns >= MAX_TOTAL_SPAWNS;+ return {+ error: budgetExhausted+ ? `Retry budget exhausted (${spawns}/${MAX_TOTAL_SPAWNS} spawns) — cannot challenge a task out of retries`+ : `Challenge budget exhausted (${getChallengeCount(task.metadata)}/${MAX_CHALLENGES_PER_TASK} used)`,+ code: budgetExhausted ? 'CHALLENGE_BUDGET_EXHAUSTED' : 'CHALLENGE_EXHAUSTED',+ };+ }+ const patch = buildChallengePatch(task.metadata, { reason, evidence, reviewer, now });+ const updated = await writeTaskUpdateLocked(taskId, { status: 'challenged', metadata: patch }, resolvedType, { now });+ if (updated?.error) return updated;+ console.log(`⚖️ Task ${taskId} challenged (${patch.challengeCount}/${MAX_CHALLENGES_PER_TASK})${patch.challenge.reviewer ? ` — disputing ${patch.challenge.reviewer}` : ''}`);+ cosEvents.emit('task:challenged', { taskId, taskType: resolvedType, reviewer: patch.challenge.reviewer || null });+ return updated;+ });}/*** Resolve a parked challenge (#2441). `upheld` overturns the rejection and- * re-queues the task (→ pending); `escalated` hands the unresolved dispute to+ * preserves its active owner (→ in_progress), or requeues an unowned task+ * (→ pending); `escalated` hands the unresolved dispute to* the user — the task is blocked with a challenge-escalation reason AND an* approval-required arbitration task is filed into COS-TASKS.md (reusing the same* investigation/escalation surface `createInvestigationTask` writes to), so a@@ -1202,23 +1208,31 @@ export async function challengeTask(taskId, { reason, evidence, reviewer } = {},* invalid-outcome.*/export async function resolveTaskChallenge(taskId, { outcome, note, resolvedBy } = {}, taskType = 'user', { now = Date.now() } = {}) {- const task = await getTaskById(taskId);- if (!task) return { error: 'Task not found', code: 'NOT_FOUND' };- if (task.status !== 'challenged') {- return { error: 'Task is not under challenge', code: 'NOT_CHALLENGED' };- }- const resolvedType = task.taskType || taskType;- const resolutionPatch = buildChallengeResolutionPatch({ outcome, note, resolvedBy, now });- if (!resolutionPatch) return { error: `Invalid challenge outcome: ${outcome}`, code: 'INVALID_OUTCOME' };+ const resolution = await withStateLock(async () => {+ const task = await getTaskById(taskId);+ if (!task) return { error: 'Task not found', code: 'NOT_FOUND' };+ if (task.status !== 'challenged') {+ return { error: 'Task is not under challenge', code: 'NOT_CHALLENGED' };+ }+ const resolvedType = task.taskType || taskType;+ const resolutionPatch = buildChallengeResolutionPatch({ outcome, note, resolvedBy, now });+ if (!resolutionPatch) return { error: `Invalid challenge outcome: ${outcome}`, code: 'INVALID_OUTCOME' };- const nextStatus = outcome === 'upheld' ? 'pending' : 'blocked';- const metadataPatch = { ...resolutionPatch };- if (outcome === 'escalated') {- metadataPatch.blockedReason = 'Challenge unresolved — escalated to user for arbitration';- metadataPatch.blockedCategory = 'challenge-escalation';- }- const updated = await updateTask(taskId, { status: nextStatus, metadata: metadataPatch }, resolvedType, { now });- if (updated?.error) return updated;+ const state = await loadState();+ const nextStatus = outcome === 'upheld'+ ? (hasActiveTaskOwner(taskId, state.agents) ? 'in_progress' : 'pending')+ : 'blocked';+ const metadataPatch = { ...resolutionPatch };+ if (outcome === 'escalated') {+ metadataPatch.blockedReason = 'Challenge unresolved — escalated to user for arbitration';+ metadataPatch.blockedCategory = 'challenge-escalation';+ }+ const updated = await writeTaskUpdateLocked(taskId, { status: nextStatus, metadata: metadataPatch }, resolvedType, { now });+ if (updated?.error) return updated;+ return { task, updated, nextStatus, resolvedType };+ });+ if (resolution.error) return resolution;+ const { task, updated, nextStatus, resolvedType } = resolution;if (outcome === 'escalated') {// Surface the dispute to the single PortOS user as an approval-required