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: inline CoS challenge resolve controls + unify challenge cap with retry budget (#2471)

Adam Eivy4c805dc9fa1b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1aa9ec313d..6ff0fbe15e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -48,6 +48,8 @@
## Features
+- **A challenged CoS task can now be upheld or escalated inline from the task card, and a challenge is bounded by the shared retry budget (#2471).** Follow-up to #2470/#2472 (the challenge-protocol backbone + agent auto-invocation and reviewer re-check). When a sub-agent disputes a reviewer rejection and the task parks in `challenged`, the task card previously only *showed* the worker's case read-only — resolving it meant an out-of-band API call. Each unresolved challenge now carries inline **Uphold** (overturn the rejection → re-queue the work) and **Escalate** (let the rejection stand → block + file an arbitration task) controls that call `POST /challenge/resolve` and refresh in place; the buttons disable while a verdict is in flight and disappear once the challenge settles. Separately, the one-shot challenge cap is now unified with the shared `MAX_TOTAL_SPAWNS` retry budget: a task that has already burned its total-spawn budget is refused a challenge (`409 CHALLENGE_BUDGET_EXHAUSTED`) up front, since overturning it would only re-queue work that `agentLifecycle`'s spawn gate immediately re-blocks — making the module's "a challenge shares the retry budget" promise real. No migration needed (metadata-only, read on demand).
+
- **CoS confidence auto-approval now has a safety-kind override, so outward-facing / irreversible work always needs human sign-off (#2440).** Confidence auto-approval used to gate on ONE axis — a task type's historical success rate — so once a type crossed the threshold, *any* task of that type could auto-run, including inherently outward-facing work: publishing content that goes live, federating records to sync peers, opening external/upstream PRs, or releasing/deploying. A new **safety-kind** axis, orthogonal to confidence, classifies each generated task (`server/services/taskLearning/safetyKind.js`): outward-facing/irreversible kinds (`content`, `publish`, `federation`, `external-pr`) always require the user's approval regardless of how high the success rate is — a 100% score can't undo work that has already left the install — while reversible internal work (analysis, refactor, code-review, same-repo improvement PRs) keeps today's success-rate gate unchanged. Classification is driven by explicit task metadata (`safetyKind` / `outwardFacing` / capability flags) then conservative keyword signatures, defaulting to *reversible* so existing behavior is preserved unless a task carries an outward signal. The reason is surfaced on the task record (`safetyKind` + `approvalReason`) and in the approval log line, so the UI can show why a high-confidence task still needs review. Tunable via the new `safetyKindApproval` CoS config (`{ enabled, alwaysApproveKinds }`, default on) — additive optional key merged on read, no migration needed.
- **The CoS Schedule Timeline can now expand each task track to see and edit its per-app overrides inline.** Which apps run a given scheduled task type (and each app's interval / agent-option / issue-author / swarm overrides) was previously only visible on the Schedule tab's per-task drawer — the Timeline showed the task cadence but not who it runs for. Every task track — both the pinned timeline rows and the unpinned rotation/on-demand tasks in the "Unpinned runner queue" — now carries a chevron that expands to the same `PerAppOverrideList` used on the Schedule tab (enable/disable per app, "Enable/Disable All", per-app interval and metadata), plus an `enabled/total` app-count badge (shown even at `0/N` so "runs for none of my apps" is distinguishable from "no app scope") so an at-a-glance "3/5 apps" is visible without expanding. Edits save through the existing per-app override endpoints and refresh the timeline in place. System-job tracks (which are not per-app) show no expand toggle. The timeline graph node now forwards the `appOverrides`/`enabledAppCount`/`totalAppCount` plus the global `taskMetadata`/`managedAgentOptions` defaults that `getScheduleStatus` already computes; no migration needed (read-only surfacing of existing data).
diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsx
index 678eb79a9b..4bb1319b0d 100644
--- a/client/src/components/cos/tabs/TaskItem.jsx
+++ b/client/src/components/cos/tabs/TaskItem.jsx
@@ -230,6 +230,21 @@ export default function TaskItem({ task, isSystem, awaitingApproval, onRefresh,
onRefresh();
};
+ // Resolve a parked challenge inline (#2471). `upheld` overturns the reviewer
+ // rejection and re-queues the work (→ pending); `escalated` surfaces the dispute
+ // for arbitration (→ blocked + an approval-required task). Gated while a resolve
+ // is in flight so a double-click can't fire two verdicts.
+ const [resolvingChallenge, setResolvingChallenge] = useState(false);
+ const handleResolveChallenge = async (outcome) => {
+ setResolvingChallenge(true);
+ const result = await api.resolveCosTaskChallenge(task.id, { outcome, resolvedBy: 'user' }, { silent: true })
+ .catch(err => { toast.error(err.message); return null; });
+ setResolvingChallenge(false);
+ if (!result) return;
+ toast.success(outcome === 'upheld' ? 'Challenge upheld — task re-queued' : 'Challenge escalated for arbitration');
+ onRefresh();
+ };
+
const handleApprove = async () => {
const result = await api.approveCosTask(task.id, { silent: true }).catch(err => {
toast.error(err.message);
@@ -459,6 +474,31 @@ export default function TaskItem({ task, isSystem, awaitingApproval, onRefresh,
{task.metadata.challengeResolution.note ? ` — ${task.metadata.challengeResolution.note}` : ''}
</div>
)}
+ {/* Inline resolve controls while parked in `challenged` and not
+ yet settled (#2471) — Uphold overturns the rejection and
+ re-queues the work, Escalate surfaces it for arbitration. */}
+ {task.status === 'challenged' && !task.metadata.challengeResolution?.outcome && (
+ <div className="flex items-center gap-2 mt-2">
+ <button
+ type="button"
+ onClick={() => handleResolveChallenge('upheld')}
+ disabled={resolvingChallenge}
+ className="flex items-center gap-1 px-2.5 py-1 min-h-[32px] text-xs text-port-success bg-port-success/10 hover:bg-port-success/20 rounded transition-colors disabled:opacity-50"
+ title="Overturn the rejection and re-queue this task"
+ >
+ <CheckCircle size={12} aria-hidden="true" /> Uphold
+ </button>
+ <button
+ type="button"
+ onClick={() => handleResolveChallenge('escalated')}
+ disabled={resolvingChallenge}
+ className="flex items-center gap-1 px-2.5 py-1 min-h-[32px] text-xs text-port-error bg-port-error/10 hover:bg-port-error/20 rounded transition-colors disabled:opacity-50"
+ title="Let the rejection stand and file an arbitration task"
+ >
+ <Ban size={12} aria-hidden="true" /> Escalate
+ </button>
+ </div>
+ )}
</div>
</div>
)}
diff --git a/client/src/components/cos/tabs/TaskItem.test.jsx b/client/src/components/cos/tabs/TaskItem.test.jsx
index 8da75e0e7e..820793cbc2 100644
--- a/client/src/components/cos/tabs/TaskItem.test.jsx
+++ b/client/src/components/cos/tabs/TaskItem.test.jsx
@@ -6,6 +6,7 @@ const api = vi.hoisted(() => ({
deleteCosTask: vi.fn(),
approveCosTask: vi.fn(),
forceSpawnTask: vi.fn(),
+ resolveCosTaskChallenge: vi.fn(),
}));
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
@@ -84,3 +85,51 @@ describe('TaskItem blocked reason', () => {
expect(screen.queryByText(/Max total spawns/)).not.toBeInTheDocument();
});
});
+
+describe('TaskItem challenge resolve controls (#2471)', () => {
+ const challenged = {
+ id: 'sys-challenged',
+ description: 'Disputed work',
+ status: 'challenged',
+ metadata: { challenge: { reason: 'reviewer misread the diff', reviewer: 'ollama' } },
+ };
+
+ it('upholds a parked challenge via the inline control', async () => {
+ api.resolveCosTaskChallenge.mockResolvedValue({ status: 'pending' });
+ const onRefresh = vi.fn();
+ render(<TaskItem task={challenged} isSystem onRefresh={onRefresh} providers={providers} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Uphold' }));
+
+ await waitFor(() => expect(api.resolveCosTaskChallenge).toHaveBeenCalledWith(
+ 'sys-challenged',
+ { outcome: 'upheld', resolvedBy: 'user' },
+ { silent: true },
+ ));
+ await waitFor(() => expect(onRefresh).toHaveBeenCalled());
+ });
+
+ it('escalates a parked challenge via the inline control', async () => {
+ api.resolveCosTaskChallenge.mockResolvedValue({ status: 'blocked' });
+ render(<TaskItem task={challenged} isSystem onRefresh={vi.fn()} providers={providers} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Escalate' }));
+
+ await waitFor(() => expect(api.resolveCosTaskChallenge).toHaveBeenCalledWith(
+ 'sys-challenged',
+ { outcome: 'escalated', resolvedBy: 'user' },
+ { silent: true },
+ ));
+ });
+
+ it('hides the resolve controls once the challenge is already settled', () => {
+ const settled = {
+ ...challenged,
+ id: 'sys-challenged-done',
+ metadata: { ...challenged.metadata, challengeResolution: { outcome: 'upheld' } },
+ };
+ render(<TaskItem task={settled} isSystem onRefresh={vi.fn()} providers={providers} />);
+ expect(screen.queryByRole('button', { name: 'Uphold' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Escalate' })).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 1769f15c34..e2b86ff768 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -85,6 +85,14 @@ export const reorderCosTasks = (taskIds, options = {}) => request('/cos/tasks/re
...options
});
export const approveCosTask = (id, options = {}) => request(`/cos/tasks/${id}/approve`, { method: 'POST', ...options });
+// Resolve a parked challenge (#2441, #2471). `body` carries the manual verdict
+// (`{ outcome: 'upheld' | 'escalated', note?, resolvedBy? }`) — `upheld` overturns
+// the rejection (task → pending), `escalated` surfaces it for arbitration (→ blocked).
+export const resolveCosTaskChallenge = (id, body, options = {}) => request(`/cos/tasks/${id}/challenge/resolve`, {
+ method: 'POST',
+ body: JSON.stringify(body),
+ ...options
+});
export const forceCosEvaluate = (options = {}) => request('/cos/evaluate', { method: 'POST', ...options });
export const forceSpawnTask = (taskId, options = {}) => request(`/cos/tasks/${taskId}/spawn`, { method: 'POST', ...options });
export const getCosHealth = () => request('/cos/health');
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index 6d907c610a..03c42ea0e2 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -328,7 +328,7 @@ router.post('/tasks/:id/challenge', asyncHandler(async (req, res) => {
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' || result.code === 'CANNOT_CHALLENGE_COMPLETED') ? 409
+ const status = (result.code === 'CHALLENGE_EXHAUSTED' || result.code === 'CHALLENGE_BUDGET_EXHAUSTED' || result.code === 'CANNOT_CHALLENGE_COMPLETED') ? 409
: result.code === 'NOT_FOUND' ? 404 : 400;
throw new ServerError(result.error, { status, code: result.code || 'CHALLENGE_FAILED' });
}
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 511c02b353..2dc1a28f49 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -382,13 +382,14 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
// from the review loop. When a reviewer's BLOCKING finding is a false positive,
// the agent disputes it once via POST /challenge instead of silently complying
// or accepting a false block, then RE-CHECKS (re-run reviewer) to overturn or
- // escalate. One challenge per task (409 CHALLENGE_EXHAUSTED on a second).
+ // escalate. One challenge per task, also bounded by the task's retry budget —
+ // a second dispute or an out-of-retries task returns 409.
const challengeProtocolNote = [
'**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:',
'```bash',
`curl -sS -X POST http://localhost:5555/api/cos/tasks/${sourceTaskId}/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'`,
'```',
- 'A `409 CHALLENGE_EXHAUSTED` means the one challenge is spent — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user.' + (hasLocalLlm ? ' For a local reviewer you may instead POST `{"recheck":{"backend":"<lmstudio|ollama>","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.' : ''),
+ 'A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can\'t dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user.' + (hasLocalLlm ? ' For a local reviewer you may instead POST `{"recheck":{"backend":"<lmstudio|ollama>","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.' : ''),
].join('\n');
const extraNotes = [stopModeNote, applyNote].filter(Boolean);
diff --git a/server/services/cosChallenge.js b/server/services/cosChallenge.js
index 8a28c1f73e..6d3f9a889b 100644
--- a/server/services/cosChallenge.js
+++ b/server/services/cosChallenge.js
@@ -53,10 +53,25 @@ export function getChallengeCount(metadata) {
}
/**
- * May this task still be challenged? True until the per-task cap is reached.
+ * May this task still be challenged? Bounded by BOTH the one-shot per-task cap
+ * AND — when `maxTotalSpawns` is supplied — the task's shared retry budget (#2471).
+ *
+ * The one-shot cap (`max`) is the acceptance contract: exactly one dispute per task.
+ * The retry-budget bound makes the module's "shares the retry budget so an agent
+ * can't loop forever disputing" promise real: a challenge that succeeds re-queues
+ * the task, so once it has burned its total-spawn budget (`totalSpawnCount` ≥
+ * `maxTotalSpawns`) a further dispute is pointless — the re-queued task would only
+ * be re-blocked by agentLifecycle's spawn-cap gate. Callers pass `maxTotalSpawns`
+ * (the shared `MAX_TOTAL_SPAWNS` from validation.js) to opt into that bound; when
+ * omitted only the one-shot cap applies, so this stays a pure, import-free module.
*/
-export function canChallenge(metadata, { max = MAX_CHALLENGES_PER_TASK } = {}) {
- return getChallengeCount(metadata) < max;
+export function canChallenge(metadata, { max = MAX_CHALLENGES_PER_TASK, maxTotalSpawns } = {}) {
+ if (getChallengeCount(metadata) >= max) return false;
+ if (maxTotalSpawns != null) {
+ const spawns = Number(metadata?.totalSpawnCount) || 0;
+ if (spawns >= maxTotalSpawns) return false;
+ }
+ return true;
}
/**
diff --git a/server/services/cosChallenge.test.js b/server/services/cosChallenge.test.js
index 2abd3d11a4..9466b45cfe 100644
--- a/server/services/cosChallenge.test.js
+++ b/server/services/cosChallenge.test.js
@@ -36,6 +36,19 @@ describe('cosChallenge', () => {
// string form (post-round-trip) is refused too
expect(canChallenge({ challengeCount: String(MAX_CHALLENGES_PER_TASK) })).toBe(false);
});
+
+ it('also refuses once the shared retry budget is spent when maxTotalSpawns is supplied (#2471)', () => {
+ // Under the one-shot cap but out of total spawns → refused only when the
+ // budget bound is opted into; omitting maxTotalSpawns keeps the old behavior.
+ expect(canChallenge({ totalSpawnCount: 5 })).toBe(true);
+ expect(canChallenge({ totalSpawnCount: 5 }, { maxTotalSpawns: 5 })).toBe(false);
+ expect(canChallenge({ totalSpawnCount: '5' }, { maxTotalSpawns: 5 })).toBe(false);
+ expect(canChallenge({ totalSpawnCount: 4 }, { maxTotalSpawns: 5 })).toBe(true);
+ // absent spawn count coerces to 0 → still allowed under budget
+ expect(canChallenge({}, { maxTotalSpawns: 5 })).toBe(true);
+ // the one-shot cap still wins even with budget remaining
+ expect(canChallenge({ challengeCount: 1, totalSpawnCount: 0 }, { maxTotalSpawns: 5 })).toBe(false);
+ });
});
describe('buildChallengePatch', () => {
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 06efef5170..f283d2d370 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -22,6 +22,7 @@ import { cosEvents } from './cosEvents.js';
import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';
import { mergeTaskLists } from './cosTaskMerge.js';
import { canChallenge, getChallengeCount, buildChallengePatch, buildChallengeResolutionPatch, classifyRecheckOutcome, MAX_CHALLENGES_PER_TASK } from './cosChallenge.js';
+import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { runLocalCodeReview, getCodeReviewDefaults } from './codeReview.js';
// First non-empty line of a string. Used by addTask dedup: stored descriptions
@@ -622,10 +623,17 @@ export async function challengeTask(taskId, { reason, evidence, reviewer } = {},
if (task.status === 'completed') {
return { error: 'Cannot challenge a completed task', code: 'CANNOT_CHALLENGE_COMPLETED' };
}
- if (!canChallenge(task.metadata)) {
+ // 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: `Challenge budget exhausted (${getChallengeCount(task.metadata)}/${MAX_CHALLENGES_PER_TASK} used)`,
- code: 'CHALLENGE_EXHAUSTED',
+ 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 });
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index c60e27abe2..77733f4c1b 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -75,6 +75,7 @@ import {
resolveTaskChallenge,
resolveTaskChallengeWithRecheck
} from './cosTaskStore.js';
+import { MAX_TOTAL_SPAWNS } from '../lib/cosValidation.js';
const USER_FILE = '/root/TASKS.md';
const COS_FILE = '/root/COS-TASKS.md';
@@ -617,6 +618,16 @@ describe('cosTaskStore.challengeTask / resolveTaskChallenge (#2441)', () => {
expect(second.code).toBe('CHALLENGE_EXHAUSTED');
});
+ it('refuses a challenge once the shared retry budget is spent (#2471)', async () => {
+ const id = await seedTask('out of retries');
+ // Burn the total-spawn budget — a fresh challenge would only re-queue into a
+ // task agentLifecycle will immediately re-block, so it is refused up front.
+ await updateTask(id, { metadata: { totalSpawnCount: MAX_TOTAL_SPAWNS } }, 'user');
+ const result = await challengeTask(id, { reason: 'let me back in' });
+ expect(result.code).toBe('CHALLENGE_BUDGET_EXHAUSTED');
+ expect(result.error).toMatch(/Retry budget exhausted/);
+ });
+
it('returns NOT_FOUND for an unknown task', async () => {
const result = await challengeTask('task-nope', { reason: 'x' });
expect(result.code).toBe('NOT_FOUND');