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

feat: add bounded `challenged` status so a CoS sub-agent can dispute a wrong reviewer rejection (#2441)

Adam Eivy5775caad9ca6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c9775e5579..67c002ba41 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,8 @@
- **CoS investigation tasks now use a human-facing "What happened / What to approve / What unblocks" template with a redacted failure snippet (#2442).** When a CoS agent failure is classified as *actionable*, `createInvestigationTask()` filed a fixed 6-field stub (Failed Agent / Original Task / Error Category / Suggested Fix / Model) that read identically for every category, while the useful diagnostic context stayed buried in `learning.json` telemetry. The body is now restructured into three sections — **What happened** (plain-language category + provider/model attribution + a short captured failure snippet), **What to approve** (the concrete decision/action to take), and **What unblocks** (which original task resumes) — and each `ERROR_PATTERN` may optionally supply category-specific escalation prose so the note varies by failure kind (model-not-found, context-length, spawn-error, task-rejected, content-filtered, etc.) instead of being uniform. The folded-in snippet and task description are passed through a new `redactFailureSnippet()` helper that strips OS usernames from home paths, emails, IPs, Tailscale/mDNS hostnames, and bearer/secret tokens before anything lands in the human-facing (and potentially federated) task body. Additive copy/structure change to one function plus optional per-pattern fields — no status-model change.
+- **A CoS sub-agent can now challenge a wrong reviewer rejection instead of silently fixing it or getting blocked (#2441).** When a review-loop reviewer rejects work — common with noisy local/CLI reviewers — the task can be parked in a new `challenged` status with the worker's case attached (`reason` + optional `evidence` + which `reviewer` is disputed) via `POST /api/cos/tasks/:id/challenge`. Disputes are bounded to exactly one per task (a second is refused with `409 CHALLENGE_EXHAUSTED`), so an agent can't loop forever. Resolving via `POST /api/cos/tasks/:id/challenge/resolve` either **overturns** the rejection (`upheld` → task re-queues to pending) or **escalates** the unresolved dispute to the single PortOS user (`escalated` → task blocked with a `challenge-escalation` reason AND an approval-required arbitration task filed into `COS-TASKS.md`) — surfacing a sustained disagreement rather than quietly fixing or blocking. The full challenge trio (case + resolution + count) rides task metadata, so it round-trips the TASKS.md store, is auditable in the CoS task UI, and federates + converges across sync peers: `challenged` is wired into the claim-aware merge rank (above `in_progress`, below the terminal states), the peer-sync wire status vocab, and a `cosTasks` schema bump (v1→v2) so an older peer gently pauses cos-task sync instead of choking on the unknown status. Partial slice of the Conductor↔CoS challenge protocol — the automatic reviewer re-check and the agent-side auto-invocation land in a follow-up.
+
- **The dashboard's Quick Image widget now offers custom output dimensions and no longer shows a blank size dropdown for off-preset sizes (#2437).** The quick widget had its own inline resolution `<select>` over the universal presets and never gained the **Custom…** option added to the full Image Gen page, so its size picker was inconsistent — and a remix/off-preset size (any width/height not on the preset list) rendered a blank dropdown because no matching `<option>` existed. It now reuses the shared `ResolutionField` control, so selecting **Custom…** reveals Width/Height inputs (any edge 64–3840px, total ≤ 8,294,400px, matching the server's `imageEdgeSchema` + pixel cap), and an off-preset size auto-opens those inputs with the exact dimensions visible instead of collapsing to a blank select. No behavior change to the presets themselves.
- **Duplicated child-process stream/discovery helpers converged into shared lib modules (#2392).** Three hand-copied "split a stdout/stderr chunk stream into lines with a carry buffer" implementations (`ytdlpAudioImport.js`, `videoDownload.js`, `hfDownload.js`) had already drifted — only hfDownload's copy flushed the final unterminated line. They now share `server/lib/streamLines.js#createLineReader(onLine, {splitRe?, maxCarry?})`, which carries the partial trailing line across chunks, exposes a `flush()` for the last newline-less line (so the two yt-dlp paths stop dropping it — and skip the flush on cancel so a partial marker can't fire a stray progress frame), clamps the carry buffer against a newline-less runaway stream, and takes a `splitRe: /[\r\n]+/` option for bare-`\r` torch/tqdm progress redraws. The four bare-`\r` progress-splitter siblings (`midiRuntime.js`, `videoGen.js`, `music.js` install-log routes, and `pythonSetup.js#streamSpawn`) are converged onto the same reader with that option, so a progress line split across a chunk boundary is no longer torn. Separately, the inline `which`/`where` PATH probes in `ytdlp.js`, `ffmpeg.js` (×2), `pythonSetup.js`, and voice `bootstrap.js` are replaced by a single `whichFirst(name)` in `server/lib/processEnv.js` (Malloc-stripped env, 5s timeout, first-line result). The vendored `aiToolkit/providers.js` copy is intentionally left alone (self-contained by design). Behavior-preserving; both new helpers are unit-tested.
diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsx
index 9fbadd7063..678eb79a9b 100644
--- a/client/src/components/cos/tabs/TaskItem.jsx
+++ b/client/src/components/cos/tabs/TaskItem.jsx
@@ -17,7 +17,8 @@ import {
TrendingUp,
Play,
ChevronDown,
- ChevronUp
+ ChevronUp,
+ Scale
} from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
@@ -31,7 +32,9 @@ const statusIcons = {
pending: <Clock size={16} aria-hidden="true" className="text-yellow-500" />,
in_progress: <Activity size={16} aria-hidden="true" className="text-port-accent animate-pulse" />,
completed: <CheckCircle size={16} aria-hidden="true" className="text-port-success" />,
- blocked: <Ban size={16} aria-hidden="true" className="text-port-error" />
+ blocked: <Ban size={16} aria-hidden="true" className="text-port-error" />,
+ // A sub-agent disputing a reviewer rejection (#2441) — awaiting resolution.
+ challenged: <Scale size={16} aria-hidden="true" className="text-port-warning" />
};
// Extract task type from description for duration lookup (matches AgentCard logic)
@@ -440,6 +443,25 @@ export default function TaskItem({ task, isSystem, awaitingApproval, onRefresh,
<span className="text-port-error/90">{task.metadata.blocker || task.metadata.blockedReason}</span>
</div>
)}
+ {/* Challenge case + resolution (#2441). Both sides of a disputed
+ rejection are logged on the task metadata so the outcome is
+ auditable here: the worker's case while parked in `challenged`,
+ and the resolver's verdict once it settles. */}
+ {task.metadata?.challenge?.reason && (
+ <div className="flex items-start gap-2 mt-2 px-2 py-1.5 bg-port-warning/10 border border-port-warning/20 rounded text-sm">
+ <Scale size={14} className="text-port-warning shrink-0 mt-0.5" aria-hidden="true" />
+ <div className="text-port-warning/90 min-w-0">
+ <span className="font-medium">Challenge{task.metadata.challenge.reviewer ? ` (${task.metadata.challenge.reviewer})` : ''}:</span>{' '}
+ <span className="break-words">{task.metadata.challenge.reason}</span>
+ {task.metadata.challengeResolution?.outcome && (
+ <div className="mt-1 text-gray-400">
+ Resolved: {task.metadata.challengeResolution.outcome}
+ {task.metadata.challengeResolution.note ? ` — ${task.metadata.challengeResolution.note}` : ''}
+ </div>
+ )}
+ </div>
+ </div>
+ )}
</>
)}
</div>
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index ca8db460b9..e4f1d791bf 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -265,6 +265,27 @@ export const updateCosTaskSchema = z.object({
type: z.string().optional().default('user'),
});
+// Worker's dispute of a reviewer rejection (#2441). `reason` is the required
+// case; `evidence` is optional supporting detail; `reviewer` names which reviewer
+// verdict is being disputed (constrained to the known reviewer vocab). Bounds are
+// generous but present so a hand-crafted request can't smuggle in an unbounded
+// blob that then round-trips the TASKS.md store.
+export const challengeTaskSchema = z.object({
+ reason: z.string().trim().min(1).max(5000),
+ evidence: z.string().trim().max(20_000).optional(),
+ reviewer: z.enum(REVIEWER_VALUES).optional(),
+});
+
+// Resolution of a parked challenge (#2441). `outcome` mirrors CHALLENGE_OUTCOMES
+// in server/services/cosChallenge.js (source of truth; a parity test keeps them
+// in lockstep). `upheld` overturns the rejection (task → pending); `escalated`
+// surfaces the unresolved dispute to the user (task → blocked + arbitration task).
+export const resolveChallengeSchema = z.object({
+ outcome: z.enum(['upheld', 'escalated']),
+ note: z.string().trim().max(5000).optional(),
+ resolvedBy: z.string().trim().max(200).optional(),
+});
+
// =============================================================================
// LOOP SCHEMAS
// =============================================================================
diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.js
index 245d975e8c..dccfe78864 100644
--- a/server/lib/peerSyncValidation.js
+++ b/server/lib/peerSyncValidation.js
@@ -345,7 +345,10 @@ export const peerCosHistoryManifestSchema = z.object({
// receiver's next file read, so we only bound the key length + entry count here.
// `.strict()` on the entry rejects a smuggled extra top-level field; the metadata
// record stays open.
-const TASK_STATUSES = ['pending', 'in_progress', 'blocked', 'completed'];
+// `challenged` (#2441) rides the wire like any other status — the challenge
+// case + resolution live in `metadata` (permissive record below), so they
+// federate verbatim with no extra top-level fields.
+const TASK_STATUSES = ['pending', 'in_progress', 'challenged', 'blocked', 'completed'];
const TASK_PRIORITIES = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
const peerCosTaskEntrySchema = z.object({
id: z.string().trim().min(1).max(200),
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 11729293c0..981bad88ef 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -441,7 +441,17 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// an authoritative record transfer. Only the payload envelope + task-entry
// shape is gated; the FIRST incompatible change (new required entry field, new
// claim semantics) MUST bump this to 2.
- cosTasks: 1,
+ // v2 = the `challenged` task status + its challenge case/resolution metadata
+ // (#2441). A ≤v1 receiver's `TASK_STATUSES` enum lacks `challenged`, so its
+ // wire validation would REJECT the whole payload (peerCosTasksSchema.safeParse
+ // fails → the sweep skips, never mis-merges). Bumping makes the receiver's
+ // GENTLE schema-ahead skip fire FIRST with a clear "schema v2 > local v1"
+ // log, instead of a confusing blanket "failed validation" skip. The challenge
+ // record itself (`challenge`/`challengeResolution`/`challengeCount`) rides the
+ // permissive `metadata` map and round-trips the markdown store like any other
+ // metadata, so no new top-level wire field is added — only the status vocab
+ // widened. Per-category gate → only cos-tasks sync pauses with old peers.
+ cosTasks: 2,
// NOTE: `videoHistory` is intentionally NOT listed here. The version gate
// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the
// comparator walks the union of keys), so declaring a brand-new key would
diff --git a/server/lib/taskParser.js b/server/lib/taskParser.js
index 5a27545c8c..487d03e821 100644
--- a/server/lib/taskParser.js
+++ b/server/lib/taskParser.js
@@ -39,7 +39,10 @@ const STATUS_MAP = {
'[ ]': 'pending',
'[~]': 'in_progress',
'[x]': 'completed',
- '[!]': 'blocked'
+ '[!]': 'blocked',
+ // A sub-agent disputing a reviewer rejection parks the task here (#2441): work
+ // is neither in-flight nor terminally blocked while the challenge is resolved.
+ '[?]': 'challenged'
};
export const PRIORITY_VALUES = {
@@ -56,7 +59,7 @@ export const PRIORITY_VALUES = {
*/
function parseTaskLine(line) {
// First try: - [status] #id | PRIORITY | APPROVAL_FLAG | description
- let match = line.match(/^-\s*\[([ x~!])\]\s*#([\w-]+)\s*\|\s*(CRITICAL|HIGH|MEDIUM|LOW)\s*\|\s*(AUTO|APPROVAL)\s*\|\s*(.+)$/i);
+ let match = line.match(/^-\s*\[([ x~!?])\]\s*#([\w-]+)\s*\|\s*(CRITICAL|HIGH|MEDIUM|LOW)\s*\|\s*(AUTO|APPROVAL)\s*\|\s*(.+)$/i);
if (match) {
const [, statusChar, id, priority, approvalFlag, description] = match;
@@ -75,7 +78,7 @@ function parseTaskLine(line) {
}
// Fallback: - [status] #id | PRIORITY | description (no approval flag)
- match = line.match(/^-\s*\[([ x~!])\]\s*#([\w-]+)\s*\|\s*(CRITICAL|HIGH|MEDIUM|LOW)\s*\|\s*(.+)$/i);
+ match = line.match(/^-\s*\[([ x~!?])\]\s*#([\w-]+)\s*\|\s*(CRITICAL|HIGH|MEDIUM|LOW)\s*\|\s*(.+)$/i);
if (!match) return null;
@@ -254,6 +257,7 @@ export function groupTasksByStatus(tasks) {
return {
pending: tasks.filter(t => t.status === 'pending'),
in_progress: tasks.filter(t => t.status === 'in_progress'),
+ challenged: tasks.filter(t => t.status === 'challenged'),
blocked: tasks.filter(t => t.status === 'blocked'),
completed: tasks.filter(t => t.status === 'completed')
};
@@ -277,6 +281,7 @@ export function generateTasksMarkdown(tasks, includeApprovalFlags = false) {
const statusToCheckbox = {
'pending': '[ ]',
'in_progress': '[~]',
+ 'challenged': '[?]',
'blocked': '[!]',
'completed': '[x]'
};
@@ -284,6 +289,7 @@ export function generateTasksMarkdown(tasks, includeApprovalFlags = false) {
const sections = [
{ key: 'pending', title: 'Pending' },
{ key: 'in_progress', title: 'In Progress' },
+ { key: 'challenged', title: 'Challenged' },
{ key: 'blocked', title: 'Blocked' },
{ key: 'completed', title: 'Completed' }
];
@@ -418,7 +424,7 @@ export function validateTask(task) {
errors.push('Task must have a description');
}
- if (!['pending', 'in_progress', 'blocked', 'completed'].includes(task.status)) {
+ if (!['pending', 'in_progress', 'challenged', 'blocked', 'completed'].includes(task.status)) {
errors.push('Invalid task status');
}
diff --git a/server/lib/taskParser.test.js b/server/lib/taskParser.test.js
index 13036f0ba6..efa785863a 100644
--- a/server/lib/taskParser.test.js
+++ b/server/lib/taskParser.test.js
@@ -676,3 +676,50 @@ describe('Task Parser', () => {
});
});
});
+
+describe('Task Parser — challenged status (#2441)', () => {
+ it('parses a [?] challenged task line', () => {
+ const tasks = parseTasksMarkdown(`# Tasks
+
+## Challenged
+- [?] #task-900 | HIGH | Disputed rejection task`);
+ expect(tasks).toHaveLength(1);
+ expect(tasks[0].status).toBe('challenged');
+ expect(tasks[0].id).toBe('task-900');
+ });
+
+ it('round-trips a challenged task (parse → generate → parse) with its metadata', () => {
+ const tasks = [{
+ id: 'task-901',
+ status: 'challenged',
+ priority: 'HIGH',
+ priorityValue: 3,
+ description: 'Dispute',
+ metadata: {
+ challengeCount: 1,
+ challenge: { reason: 'reviewer misread the diff', reviewer: 'ollama' },
+ },
+ }];
+ const md = generateTasksMarkdown(tasks);
+ expect(md).toContain('## Challenged');
+ expect(md).toContain('- [?] #task-901');
+ const reparsed = parseTasksMarkdown(md);
+ expect(reparsed[0].status).toBe('challenged');
+ // challengeCount survives as a string after the markdown round-trip.
+ expect(String(reparsed[0].metadata.challengeCount)).toBe('1');
+ expect(reparsed[0].metadata.challenge.reason).toBe('reviewer misread the diff');
+ });
+
+ it('groups challenged tasks into their own bucket', () => {
+ const grouped = groupTasksByStatus([
+ { id: 'a', status: 'challenged' },
+ { id: 'b', status: 'pending' },
+ ]);
+ expect(grouped.challenged.map((t) => t.id)).toEqual(['a']);
+ });
+
+ it('validates challenged as a legal status', () => {
+ const result = validateTask({ id: 'task-902', description: 'x', status: 'challenged', priority: 'HIGH' });
+ expect(result.valid).toBe(true);
+ });
+});
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index b88c208d30..abcf6468b9 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -17,6 +17,8 @@ import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.j
import {
createCosTaskSchema,
updateCosTaskSchema,
+ challengeTaskSchema,
+ resolveChallengeSchema,
validateRequest,
normalizeReviewers,
buildReviewersCsv,
@@ -318,6 +320,36 @@ router.post('/tasks/:id/approve', asyncHandler(async (req, res) => {
res.json(result);
}));
+// POST /api/cos/tasks/:id/challenge - A sub-agent disputes a reviewer rejection
+// (#2441). Parks the task in `challenged` and consumes one bounded challenge slot;
+// a second dispute on the same task is refused (409 CHALLENGE_EXHAUSTED).
+router.post('/tasks/:id/challenge', asyncHandler(async (req, res) => {
+ const { id } = req.params;
+ const { reason, evidence, reviewer } = validateRequest(challengeTaskSchema, req.body);
+ const result = await cos.challengeTask(id, { reason, evidence, reviewer });
+ if (result?.error) {
+ const status = result.code === 'CHALLENGE_EXHAUSTED' ? 409
+ : result.code === 'NOT_FOUND' ? 404 : 400;
+ throw new ServerError(result.error, { status, code: result.code || 'CHALLENGE_FAILED' });
+ }
+ res.json(result);
+}));
+
+// POST /api/cos/tasks/:id/challenge/resolve - Resolve a parked challenge (#2441).
+// `upheld` overturns the rejection (→ pending); `escalated` surfaces the
+// unresolved dispute to the user (→ blocked + arbitration task).
+router.post('/tasks/:id/challenge/resolve', asyncHandler(async (req, res) => {
+ const { id } = req.params;
+ const { outcome, note, resolvedBy } = validateRequest(resolveChallengeSchema, req.body);
+ const result = await cos.resolveTaskChallenge(id, { outcome, note, resolvedBy });
+ if (result?.error) {
+ const status = result.code === 'NOT_FOUND' ? 404
+ : result.code === 'NOT_CHALLENGED' ? 409 : 400;
+ throw new ServerError(result.error, { status, code: result.code || 'RESOLVE_FAILED' });
+ }
+ res.json(result);
+}));
+
// POST /api/cos/evaluate - Force task evaluation
router.post('/evaluate', asyncHandler(async (req, res) => {
await cos.evaluateTasks();
diff --git a/server/services/cos.js b/server/services/cos.js
index d80b9f0135..2d4510f31e 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -54,8 +54,8 @@ export { runHealthCheck, getHealthStatus };
// backward compat with `import * as cos` and the cos route handlers. The store
// emits `tasks:changed`; init() below turns that into tryImmediateSpawn /
// dequeueNextTask so the spawn-side logic stays here, not in the store.
-import { firstLine, PRIORITY_VALUES, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask } from './cosTaskStore.js';
-export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask };
+import { firstLine, PRIORITY_VALUES, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge } from './cosTaskStore.js';
+export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge };
import { ensureInstanceId } from './instances.js';
import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';
diff --git a/server/services/cosChallenge.js b/server/services/cosChallenge.js
new file mode 100644
index 0000000000..433f0d964f
--- /dev/null
+++ b/server/services/cosChallenge.js
@@ -0,0 +1,102 @@
+/**
+ * CoS Task Challenge — bounded worker↔reviewer dispute protocol (#2441)
+ *
+ * When a review-loop reviewer REJECTS a sub-agent's work, the agent's only prior
+ * outcomes were "silently fix whatever was flagged" or "get blocked" — a wrong
+ * rejection (common with noisy local/CLI reviewers) burned budget on an unneeded
+ * fix or false-blocked good work. This module is the safety primitive for the
+ * alternative: a worker may DISPUTE a rejection exactly once per task, parking it
+ * in the `challenged` status with its full case attached, and the dispute either
+ * resolves back to work (`upheld`) or escalates to the single PortOS user
+ * (`escalated`) — never an unbounded fix/challenge loop.
+ *
+ * Bounded by design (Conductor's challenge protocol shares the retry budget so an
+ * agent can't loop forever disputing): `MAX_CHALLENGES_PER_TASK` caps disputes at
+ * one; `canChallenge` refuses a second. Single-user trust model — "escalate to the
+ * user" = surface a decision to the one operator, not multi-actor arbitration.
+ *
+ * Pure + side-effect-free (mirrors cosTaskClaim.js): every function operates on a
+ * plain task-metadata object and returns a partial-metadata patch to merge via
+ * `cosTaskStore.updateTask`, a boolean, or a number. Persistence, the status
+ * transition, and the escalation task live in the caller (cosTaskStore.js).
+ *
+ * The challenge record round-trips the TASKS.md markdown store like any other
+ * metadata (objects/numbers via the JSON sentinel — see taskParser.js), and is
+ * part of the merge's content signature, so a challenge federates + converges
+ * across peers with no bespoke wire field (#1712 cosTasks federation).
+ */
+
+// One dispute per task. Sized as a hard cap (not a knob) so the acceptance
+// contract — "a worker can dispute exactly one rejection per task; further
+// disputes are refused" — is enforced in one place.
+export const MAX_CHALLENGES_PER_TASK = 1;
+
+// Resolution outcomes. `upheld` overturns the rejection (work re-queues);
+// `escalated` hands an unresolved/failed dispute to the user rather than
+// silently fixing or blocking. Mirrored by the route enum in cosValidation.js
+// (`resolveChallengeSchema`) — a parity test keeps the two in lockstep.
+export const CHALLENGE_OUTCOMES = Object.freeze(['upheld', 'escalated']);
+
+// The metadata keys this module owns on a task. Exported so callers/tests can
+// reason about (or strip) the challenge trio in one place.
+export const CHALLENGE_METADATA_KEYS = Object.freeze(['challengeCount', 'challenge', 'challengeResolution']);
+
+/**
+ * How many challenges a task has already consumed. Coerces the value defensively:
+ * after a TASKS.md round-trip the number arrives as the string `"1"`, so parse it
+ * and treat anything non-positive/unparseable as 0 ("never challenged").
+ */
+export function getChallengeCount(metadata) {
+ const raw = metadata?.challengeCount;
+ const n = typeof raw === 'number' ? raw : Number.parseInt(raw, 10);
+ return Number.isInteger(n) && n > 0 ? n : 0;
+}
+
+/**
+ * May this task still be challenged? True until the per-task cap is reached.
+ */
+export function canChallenge(metadata, { max = MAX_CHALLENGES_PER_TASK } = {}) {
+ return getChallengeCount(metadata) < max;
+}
+
+/**
+ * Build the metadata patch that RECORDS a worker's dispute and consumes a
+ * challenge slot. Increments `challengeCount`, stores the worker's case under
+ * `challenge` ({ reason, evidence?, reviewer?, challengedAt }), and clears any
+ * prior `challengeResolution` (undefined → updateTask strips it) so a re-dispute
+ * doesn't carry a stale verdict. Merge over the task's existing metadata.
+ *
+ * The caller is responsible for the `canChallenge` guard + the `challenged`
+ * status transition; this only shapes the metadata.
+ */
+export function buildChallengePatch(metadata, { reason, evidence, reviewer, now = Date.now() } = {}) {
+ const challenge = {
+ reason: String(reason ?? '').trim(),
+ challengedAt: new Date(now).toISOString(),
+ };
+ if (typeof evidence === 'string' && evidence.trim()) challenge.evidence = evidence.trim();
+ if (typeof reviewer === 'string' && reviewer.trim()) challenge.reviewer = reviewer.trim();
+ return {
+ challengeCount: getChallengeCount(metadata) + 1,
+ challenge,
+ // A fresh dispute is unresolved — drop any prior verdict.
+ challengeResolution: undefined,
+ };
+}
+
+/**
+ * Build the metadata patch that RESOLVES a dispute. Returns null for an unknown
+ * outcome so the caller can reject it. `challengeResolution` records the verdict
+ * ({ outcome, resolvedAt, note?, resolvedBy? }); the caller maps the outcome to
+ * the next task status (`upheld` → pending, `escalated` → blocked + user surface).
+ */
+export function buildChallengeResolutionPatch({ outcome, note, resolvedBy, now = Date.now() } = {}) {
+ if (!CHALLENGE_OUTCOMES.includes(outcome)) return null;
+ const resolution = {
+ outcome,
+ resolvedAt: new Date(now).toISOString(),
+ };
+ if (typeof note === 'string' && note.trim()) resolution.note = note.trim();
+ if (typeof resolvedBy === 'string' && resolvedBy.trim()) resolution.resolvedBy = resolvedBy.trim();
+ return { challengeResolution: resolution };
+}
diff --git a/server/services/cosChallenge.test.js b/server/services/cosChallenge.test.js
new file mode 100644
index 0000000000..152a6429d7
--- /dev/null
+++ b/server/services/cosChallenge.test.js
@@ -0,0 +1,107 @@
+import { describe, it, expect } from 'vitest';
+import {
+ MAX_CHALLENGES_PER_TASK,
+ CHALLENGE_OUTCOMES,
+ CHALLENGE_METADATA_KEYS,
+ getChallengeCount,
+ canChallenge,
+ buildChallengePatch,
+ buildChallengeResolutionPatch,
+} from './cosChallenge.js';
+import { resolveChallengeSchema } from '../lib/cosValidation.js';
+
+const NOW = Date.parse('2026-07-12T12:00:00.000Z');
+
+describe('cosChallenge', () => {
+ describe('getChallengeCount', () => {
+ it('returns 0 for absent / non-positive / unparseable values', () => {
+ expect(getChallengeCount(undefined)).toBe(0);
+ expect(getChallengeCount({})).toBe(0);
+ expect(getChallengeCount({ challengeCount: 0 })).toBe(0);
+ expect(getChallengeCount({ challengeCount: -1 })).toBe(0);
+ expect(getChallengeCount({ challengeCount: 'nope' })).toBe(0);
+ });
+
+ it('coerces the markdown-round-tripped string form ("1") to a number', () => {
+ expect(getChallengeCount({ challengeCount: '1' })).toBe(1);
+ expect(getChallengeCount({ challengeCount: 2 })).toBe(2);
+ });
+ });
+
+ describe('canChallenge', () => {
+ it('allows a first dispute and refuses once the cap is reached', () => {
+ expect(canChallenge({})).toBe(true);
+ expect(canChallenge({ challengeCount: MAX_CHALLENGES_PER_TASK })).toBe(false);
+ // string form (post-round-trip) is refused too
+ expect(canChallenge({ challengeCount: String(MAX_CHALLENGES_PER_TASK) })).toBe(false);
+ });
+ });
+
+ describe('buildChallengePatch', () => {
+ it('records the case, increments the count, and clears any prior resolution', () => {
+ const patch = buildChallengePatch(
+ { challengeResolution: { outcome: 'escalated' } },
+ { reason: ' the reviewer misread the diff ', evidence: ' see line 42 ', reviewer: 'ollama', now: NOW }
+ );
+ expect(patch.challengeCount).toBe(1);
+ expect(patch.challenge.reason).toBe('the reviewer misread the diff');
+ expect(patch.challenge.evidence).toBe('see line 42');
+ expect(patch.challenge.reviewer).toBe('ollama');
+ expect(patch.challenge.challengedAt).toBe(new Date(NOW).toISOString());
+ // undefined so updateTask's undefined-strip drops the stale resolution
+ expect(patch.challengeResolution).toBeUndefined();
+ expect('challengeResolution' in patch).toBe(true);
+ });
+
+ it('increments from an existing count (string form)', () => {
+ const patch = buildChallengePatch({ challengeCount: '1' }, { reason: 'x', now: NOW });
+ expect(patch.challengeCount).toBe(2);
+ });
+
+ it('omits optional evidence/reviewer when blank', () => {
+ const patch = buildChallengePatch({}, { reason: 'x', evidence: ' ', reviewer: '', now: NOW });
+ expect('evidence' in patch.challenge).toBe(false);
+ expect('reviewer' in patch.challenge).toBe(false);
+ });
+ });
+
+ describe('buildChallengeResolutionPatch', () => {
+ it('returns null for an unknown outcome', () => {
+ expect(buildChallengeResolutionPatch({ outcome: 'bogus', now: NOW })).toBeNull();
+ expect(buildChallengeResolutionPatch({ now: NOW })).toBeNull();
+ });
+
+ it('records outcome + timestamp and trims optional note/resolvedBy', () => {
+ const patch = buildChallengeResolutionPatch({ outcome: 'upheld', note: ' agreed ', resolvedBy: ' user ', now: NOW });
+ expect(patch.challengeResolution.outcome).toBe('upheld');
+ expect(patch.challengeResolution.resolvedAt).toBe(new Date(NOW).toISOString());
+ expect(patch.challengeResolution.note).toBe('agreed');
+ expect(patch.challengeResolution.resolvedBy).toBe('user');
+ });
+
+ it('accepts every CHALLENGE_OUTCOMES value', () => {
+ for (const outcome of CHALLENGE_OUTCOMES) {
+ expect(buildChallengeResolutionPatch({ outcome, now: NOW })).not.toBeNull();
+ }
+ });
+ });
+
+ describe('constants / parity', () => {
+ it('caps disputes at exactly one per task', () => {
+ expect(MAX_CHALLENGES_PER_TASK).toBe(1);
+ });
+
+ it('owns exactly the three challenge metadata keys', () => {
+ expect([...CHALLENGE_METADATA_KEYS].sort()).toEqual(['challenge', 'challengeCount', 'challengeResolution']);
+ });
+
+ it('the route resolution enum stays in lockstep with CHALLENGE_OUTCOMES', () => {
+ // Drift guard: the Zod enum in cosValidation.js is a mirror; both must match.
+ for (const outcome of CHALLENGE_OUTCOMES) {
+ expect(resolveChallengeSchema.safeParse({ outcome }).success).toBe(true);
+ }
+ // An outcome NOT in the list must be rejected by the schema.
+ expect(resolveChallengeSchema.safeParse({ outcome: 'overruled' }).success).toBe(false);
+ });
+ });
+});
diff --git a/server/services/cosTaskMerge.js b/server/services/cosTaskMerge.js
index 9d858a59ba..baa1327377 100644
--- a/server/services/cosTaskMerge.js
+++ b/server/services/cosTaskMerge.js
@@ -25,7 +25,7 @@
* resurrect from the peer on the next sweep. See cosTaskStore.deleteTask.)
*
* 2. For a task on BOTH sides, choose the CONTENT by lifecycle rank: a task
- * only ever advances pending → in_progress → (completed|blocked), so the
+ * advances pending → in_progress → (challenged) → (completed|blocked), so the
* higher-ranked status is the newer truth and wins. This makes completion
* converge: once either peer marks a task done, the other adopts it instead
* of holding it `in_progress` forever (a live claim alone can't carry that
@@ -51,7 +51,14 @@ import { PRIORITY_VALUES } from '../lib/taskParser.js';
// Lifecycle rank — higher wins the content tiebreak (rule 2). Each status has a
// distinct rank so two DIFFERENT statuses never tie (full convergence); the only
// genuine tie is same-status-both-sides, where the content is already equivalent.
-const STATUS_RANK = Object.freeze({ completed: 4, blocked: 3, in_progress: 2, pending: 1 });
+//
+// `challenged` (#2441) sits ABOVE in_progress (a fresh dispute is newer truth than
+// a stale in_progress snapshot on the other peer) but BELOW the terminal states:
+// a `completed` or `blocked`/escalated resolution supersedes an unresolved
+// challenge, so those still win the merge. It is NOT terminal (the dispute
+// resolves back to pending or forward to blocked), so it keeps a live claim the
+// same way in_progress does.
+const STATUS_RANK = Object.freeze({ completed: 5, blocked: 4, challenged: 3, in_progress: 2, pending: 1 });
const statusRank = (status) => STATUS_RANK[status] || 0;
const isTerminalStatus = (status) => status === 'completed' || status === 'blocked';
diff --git a/server/services/cosTaskMerge.test.js b/server/services/cosTaskMerge.test.js
index c805c5a5bb..1df93ea581 100644
--- a/server/services/cosTaskMerge.test.js
+++ b/server/services/cosTaskMerge.test.js
@@ -240,4 +240,30 @@ describe('mergeTaskLists', () => {
// Entries missing an id are skipped, not adopted.
expect(mergeTaskLists([{ status: 'pending' }], [], { now: NOW })).toEqual([]);
});
+
+ describe('challenged status rank (#2441)', () => {
+ it('a fresh challenged status wins over a stale in_progress on the other peer', () => {
+ const local = [task('task-c', 'challenged')];
+ const remote = [task('task-c', 'in_progress')];
+ // Symmetric: whichever side initiates, the challenged content wins.
+ expect(mergeTaskLists(local, remote, { now: NOW })[0].status).toBe('challenged');
+ expect(mergeTaskLists(remote, local, { now: NOW })[0].status).toBe('challenged');
+ });
+
+ it('a terminal resolution (blocked / completed) supersedes an unresolved challenge', () => {
+ const challenged = [task('task-c', 'challenged')];
+ const blocked = [task('task-c', 'blocked')];
+ const completed = [task('task-c', 'completed')];
+ expect(mergeTaskLists(challenged, blocked, { now: NOW })[0].status).toBe('blocked');
+ expect(mergeTaskLists(blocked, challenged, { now: NOW })[0].status).toBe('blocked');
+ expect(mergeTaskLists(challenged, completed, { now: NOW })[0].status).toBe('completed');
+ });
+
+ it('keeps a live claim on a challenged (non-terminal) task, mirroring in_progress', () => {
+ const local = [task('task-c', 'challenged', { metadata: { ...liveClaim('peer-A') } })];
+ const remote = [task('task-c', 'challenged')];
+ const merged = mergeTaskLists(local, remote, { now: NOW })[0];
+ expect(merged.metadata.claimedBy).toBe('peer-A');
+ });
+ });
});
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 51c384728e..085043092e 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -21,6 +21,7 @@ import { loadState, withStateLock, ROOT_DIR } from './cosState.js';
import { cosEvents } from './cosEvents.js';
import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';
import { mergeTaskLists } from './cosTaskMerge.js';
+import { canChallenge, getChallengeCount, buildChallengePatch, buildChallengeResolutionPatch, MAX_CHALLENGES_PER_TASK } from './cosChallenge.js';
// First non-empty line of a string. Used by addTask dedup: stored descriptions
// are flattened to a single line by generateTasksMarkdown, so the comparison
@@ -598,3 +599,93 @@ export async function approveTask(taskId, { now = Date.now() } = {}) {
return tasks[taskIndex];
});
}
+
+/**
+ * Record a sub-agent's challenge of a reviewer rejection (#2441).
+ *
+ * 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.
+ *
+ * @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;
+ if (!canChallenge(task.metadata)) {
+ return {
+ error: `Challenge budget exhausted (${getChallengeCount(task.metadata)}/${MAX_CHALLENGES_PER_TASK} used)`,
+ code: '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;
+}
+
+/**
+ * Resolve a parked challenge (#2441). `upheld` overturns the rejection and
+ * re-queues the 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
+ * sustained disagreement surfaces to the user rather than silently fixing or
+ * quietly blocking.
+ *
+ * @returns the updated task, or `{ error, code }` on not-found / not-challenged /
+ * 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 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;
+
+ if (outcome === 'escalated') {
+ // Surface the dispute to the single PortOS user as an approval-required
+ // arbitration task (mirrors createInvestigationTask's escalation surface).
+ // Best-effort: a failed escalation-task write must not fail the resolution
+ // itself (the original task is already blocked with the reason attached).
+ const caseReason = task.metadata?.challenge?.reason || '(no reason recorded)';
+ const disputedReviewer = task.metadata?.challenge?.reviewer;
+ const escalationDescription = `[Challenge] Arbitrate disputed rejection on ${taskId}`;
+ const escalationContext = [
+ `A sub-agent challenged a reviewer rejection on task ${taskId} and the dispute is unresolved.`,
+ disputedReviewer ? `Disputed reviewer: ${disputedReviewer}` : null,
+ `Worker's case: ${caseReason}`,
+ note ? `Resolver note: ${note}` : null,
+ 'Decide: approve to overturn the rejection, or delete to let the rejection stand.',
+ ].filter(Boolean).join('\n');
+ await addTask({
+ description: escalationDescription,
+ priority: 'HIGH',
+ context: escalationContext,
+ approvalRequired: true,
+ }, 'internal', { now }).catch((err) => {
+ console.error(`❌ Failed to file challenge-escalation task for ${taskId}: ${err.message}`);
+ });
+ }
+
+ console.log(`⚖️ Task ${taskId} challenge resolved: ${outcome} → ${nextStatus}`);
+ cosEvents.emit('task:challenge-resolved', { taskId, taskType: resolvedType, outcome });
+ return updated;
+}
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 9f8bb3b8ac..b709ad3cfe 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -61,7 +61,9 @@ import {
deleteTask,
reorderTasks,
approveTask,
- mergePeerTasks
+ mergePeerTasks,
+ challengeTask,
+ resolveTaskChallenge
} from './cosTaskStore.js';
const USER_FILE = '/root/TASKS.md';
@@ -577,3 +579,68 @@ describe('cosTaskStore.mergePeerTasks', () => {
expect(adopted.description).toBe('no metadata here');
});
});
+
+describe('cosTaskStore.challengeTask / resolveTaskChallenge (#2441)', () => {
+ async function seedTask(desc = 'work under dispute') {
+ const created = await addTask({ description: desc, priority: 'HIGH' }, 'user');
+ return created.id;
+ }
+
+ it('parks a task in challenged and records the worker case', async () => {
+ const id = await seedTask();
+ const result = await challengeTask(id, { reason: 'reviewer misread the diff', reviewer: 'ollama' });
+ expect(result.error).toBeUndefined();
+ expect(result.status).toBe('challenged');
+ expect(String(result.metadata.challengeCount)).toBe('1');
+ expect(result.metadata.challenge.reason).toBe('reviewer misread the diff');
+ expect(result.metadata.challenge.reviewer).toBe('ollama');
+ expect(mock.events.some(e => e.name === 'task:challenged')).toBe(true);
+ });
+
+ it('refuses a second dispute on the same task (bounded to one)', async () => {
+ const id = await seedTask();
+ await challengeTask(id, { reason: 'first' });
+ const second = await challengeTask(id, { reason: 'second' });
+ expect(second.code).toBe('CHALLENGE_EXHAUSTED');
+ });
+
+ it('returns NOT_FOUND for an unknown task', async () => {
+ const result = await challengeTask('task-nope', { reason: 'x' });
+ expect(result.code).toBe('NOT_FOUND');
+ });
+
+ it('upheld resolution overturns the rejection → pending', async () => {
+ const id = await seedTask();
+ await challengeTask(id, { reason: 'wrong verdict' });
+ const resolved = await resolveTaskChallenge(id, { outcome: 'upheld', resolvedBy: 'user' });
+ expect(resolved.status).toBe('pending');
+ expect(resolved.metadata.challengeResolution.outcome).toBe('upheld');
+ });
+
+ it('escalated resolution blocks the task AND files an approval-required arbitration task', async () => {
+ const id = await seedTask('escalate me');
+ await challengeTask(id, { reason: 'still disputed', reviewer: 'codex' });
+ const resolved = await resolveTaskChallenge(id, { outcome: 'escalated', note: 'need a human' });
+ expect(resolved.status).toBe('blocked');
+ expect(resolved.metadata.blockedCategory).toBe('challenge-escalation');
+ expect(resolved.metadata.challengeResolution.outcome).toBe('escalated');
+ // The escalation surfaces to the user as an internal approval-required task.
+ const internal = await getCosTasks();
+ const arbitration = internal.tasks.find(t => t.description.includes(`Arbitrate disputed rejection on ${id}`));
+ expect(arbitration).toBeTruthy();
+ expect(arbitration.approvalRequired).toBe(true);
+ });
+
+ it('refuses to resolve a task that is not under challenge', async () => {
+ const id = await seedTask();
+ const result = await resolveTaskChallenge(id, { outcome: 'upheld' });
+ expect(result.code).toBe('NOT_CHALLENGED');
+ });
+
+ it('rejects an invalid outcome', async () => {
+ const id = await seedTask();
+ await challengeTask(id, { reason: 'x' });
+ const result = await resolveTaskChallenge(id, { outcome: 'bogus' });
+ expect(result.code).toBe('INVALID_OUTCOME');
+ });
+});