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

fix: stop comparative ranking before budget-denied matches (#7929)

[._.]/ Adam Eivy8d1841a37cdd
diff --git a/client/src/components/pipeline/ComparativeRankView.jsx b/client/src/components/pipeline/ComparativeRankView.jsx
index 7535eff971..876ae2b387 100644
--- a/client/src/components/pipeline/ComparativeRankView.jsx
+++ b/client/src/components/pipeline/ComparativeRankView.jsx
@@ -40,7 +40,8 @@ export default function ComparativeRankView({ seriesId, hasContent }) {
const status = data?.status;
const ranking = Array.isArray(data?.ranking) ? data.ranking : [];
- const weakestIds = new Set((data?.weakest || []).map((w) => w.issueId));
+ const isPartial = status === 'partial' || data?.budgetStopped === true;
+ const weakestIds = new Set(status === 'complete' ? (data?.weakest || []).map((w) => w.issueId) : []);
return (
<div className="space-y-3">
@@ -52,6 +53,7 @@ export default function ComparativeRankView({ seriesId, hasContent }) {
<p className="mt-0.5 text-[11px] text-gray-600">
Forced-pick pairwise comparison + Elo — sharper than the per-issue score band.
{status === 'complete' ? ` ${data.entrants} issues · ${data.rounds} rounds · ${data.matches?.length ?? 0} matches` : ''}
+ {isPartial ? ` ${data.matches?.length ?? 0} completed matches — partial only` : ''}
</p>
</div>
<div className="flex items-center gap-2">
@@ -79,6 +81,17 @@ export default function ComparativeRankView({ seriesId, hasContent }) {
<p className="text-xs text-gray-500 italic">
Need at least two drafted issues to run a head-to-head ranking.
</p>
+ ) : isPartial ? (
+ <div className="rounded-lg border border-port-warning/40 bg-port-warning/5 p-3 text-xs text-port-warning">
+ <p className="font-medium">Partial ranking — not complete comparative evidence</p>
+ <p className="mt-1 text-gray-400">
+ The budget stopped this tournament after {data?.matches?.length ?? 0} completed comparison{data?.matches?.length === 1 ? '' : 's'}.
+ These standings are not used to choose an autopilot revision priority.
+ </p>
+ {ranking.length > 0 ? (
+ <p className="mt-1 text-gray-500">Run the ranking again after the budget is available to produce a complete order.</p>
+ ) : null}
+ </div>
) : status === 'complete' && ranking.length ? (
<div className="overflow-x-auto rounded-lg border border-port-border">
<table className="w-full text-sm">
diff --git a/client/src/components/pipeline/ComparativeRankView.test.jsx b/client/src/components/pipeline/ComparativeRankView.test.jsx
new file mode 100644
index 0000000000..af08c4afa4
--- /dev/null
+++ b/client/src/components/pipeline/ComparativeRankView.test.jsx
@@ -0,0 +1,38 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+
+vi.mock('../../services/apiPipeline', () => ({
+ getComparativeRank: vi.fn(),
+ runComparativeRank: vi.fn(),
+}));
+
+vi.mock('../../hooks/useAsyncAction', () => ({
+ useAsyncAction: (action) => [action, false],
+}));
+
+import { getComparativeRank } from '../../services/apiPipeline';
+import ComparativeRankView from './ComparativeRankView';
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('ComparativeRankView partial rankings', () => {
+ it('labels budget-stopped data as non-authoritative and hides revision priority claims', async () => {
+ getComparativeRank.mockResolvedValue({
+ status: 'partial',
+ budgetStopped: true,
+ entrants: 4,
+ matches: [],
+ ranking: [
+ { issueId: 'iss-1', label: 'E1', title: 'Example issue', rating: 1000, wins: 0, losses: 0 },
+ ],
+ weakest: [],
+ });
+
+ render(<ComparativeRankView seriesId="ser-1" hasContent />);
+
+ await waitFor(() => expect(screen.getByText('Partial ranking — not complete comparative evidence')).toBeTruthy());
+ expect(screen.getByText(/These standings are not used to choose an autopilot revision priority/)).toBeTruthy();
+ expect(screen.queryByText('revision priority')).toBeNull();
+ expect(screen.queryByRole('columnheader', { name: 'Elo' })).toBeNull();
+ });
+});
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 24cf39db5a..fa72e7b91e 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -734,9 +734,10 @@ export const cancelReaderPanel = (seriesId) =>
});
// ---- Head-to-head comparative Elo ranking (#2169, CWQE Phase 5) ----
-// Stored ranking: { status:'complete', ranking:[{ rank, issueId, number, label,
-// rating, wins, losses }], weakest[], matches[], entrants, rounds, stale } or
-// { status:'none' } / { status:'insufficient' }.
+// Stored ranking: { status:'complete'|'partial', ranking:[{ rank, issueId,
+// number, label, rating, wins, losses }], weakest[], matches[], entrants,
+// rounds, roundsCompleted, stale } — partial is budget-stopped and not
+// authoritative comparative evidence — or { status:'none' } / { status:'insufficient' }.
export const getComparativeRank = (seriesId, options = {}) =>
request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial/rank`, options);
diff --git a/server/routes/pipeline/editorial.js b/server/routes/pipeline/editorial.js
index fa628b753b..86dbcdfcbe 100644
--- a/server/routes/pipeline/editorial.js
+++ b/server/routes/pipeline/editorial.js
@@ -200,8 +200,9 @@ const comparativeRankRunSchema = z.object({
rounds: z.coerce.number().int().min(1).max(8).optional(),
});
-// Stored ranking: { status:'complete', ranking[], weakest[], matches[], stale, ... }
-// or { status:'none' } / { status:'insufficient' }.
+// Stored ranking: { status:'complete'|'partial', ranking[], weakest[], matches[], stale, ... }
+// A partial ranking is budget-stopped evidence and is never a revision-priority
+// source. Also { status:'none' } / { status:'insufficient' }.
router.get('/series/:id/editorial/rank', asyncHandler(async (req, res) => {
await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
res.json(await comparativeRank.getComparativeRank(req.params.id));
diff --git a/server/services/pipeline/editorial/comparativeRank.js b/server/services/pipeline/editorial/comparativeRank.js
index 942b8bbf0c..acc17e33e7 100644
--- a/server/services/pipeline/editorial/comparativeRank.js
+++ b/server/services/pipeline/editorial/comparativeRank.js
@@ -41,6 +41,7 @@ const STAGE = 'pipeline-judge-compare';
export const START_RATING = 1000;
export const ELO_K = 32;
export const SWISS_ROUNDS = 4;
+export const TOURNAMENT_STOP = 'stop';
const nowIso = () => new Date().toISOString();
@@ -130,10 +131,12 @@ export function effectiveRounds(n, rounds = SWISS_ROUNDS) {
/**
* Run a Swiss-style Elo tournament. `entrants` is `[{ id, … }]`; `playMatch(a, b)`
- * resolves to `'a'` or `'b'` (the winner side — never a tie). Ratings start at
- * START_RATING and update by K after every match. A bye awards a standings point
+ * resolves to `'a'`, `'b'`, or `TOURNAMENT_STOP`. Ratings start at START_RATING
+ * and update by K after every completed match. A bye awards a standings point
* (so the bye player keeps advancing) but does NOT touch Elo (no opponent to take
- * from). Returns `{ ranking, matches }` where `ranking` is best-first by rating.
+ * from). A stop outcome ends the current round before any mutation for the
+ * declined match and prevents later rounds. Returns `{ ranking, matches,
+ * stopped, roundsCompleted }` where `ranking` is best-first by rating.
*
* Pure aside from whatever `playMatch` does — with a deterministic playMatch the
* whole tournament is deterministic, which is what the unit tests exercise.
@@ -145,21 +148,26 @@ export async function runSwissTournament(entrants, playMatch, { rounds = SWISS_R
const playedPairs = new Set();
const byesGiven = new Set();
const matches = [];
+ let stopped = false;
+ let roundsCompleted = 0;
const total = effectiveRounds(state.size, rounds);
for (let r = 0; r < total; r += 1) {
const { pairs, bye } = pairSwissRound([...state.values()], playedPairs, byesGiven);
- if (bye != null) {
- const B = state.get(bye);
- B.score += 1;
- B.byes += 1;
- byesGiven.add(bye);
- }
+ let roundStopped = false;
for (const [a, b] of pairs) {
- playedPairs.add(pairKey(a, b));
// A forced pick — playMatch must return 'a' or 'b'. Anything else is
// treated as an 'a' win by the compare-caller's tiebreak (see runMatch).
- const winner = (await playMatch(a, b)) === 'b' ? 'b' : 'a';
+ // The explicit stop outcome is checked before touching ratings, scores,
+ // wins, losses, or the played-pair set for the declined match.
+ const outcome = await playMatch(a, b);
+ if (outcome === TOURNAMENT_STOP) {
+ stopped = true;
+ roundStopped = true;
+ break;
+ }
+ const winner = outcome === 'b' ? 'b' : 'a';
+ playedPairs.add(pairKey(a, b));
const A = state.get(a);
const Bp = state.get(b);
const next = updateRatings(A.rating, Bp.rating, winner, k);
@@ -168,12 +176,20 @@ export async function runSwissTournament(entrants, playMatch, { rounds = SWISS_R
if (winner === 'a') { A.score += 1; A.wins += 1; Bp.losses += 1; } else { Bp.score += 1; Bp.wins += 1; A.losses += 1; }
matches.push({ round: r + 1, a, b, winner: winner === 'a' ? a : b });
}
+ if (roundStopped) break;
+ if (bye != null) {
+ const B = state.get(bye);
+ B.score += 1;
+ B.byes += 1;
+ byesGiven.add(bye);
+ }
+ roundsCompleted += 1;
}
const ranking = [...state.values()]
.map((s) => ({ ...s, rating: Math.round(s.rating * 100) / 100 }))
.sort((x, y) => (y.rating - x.rating) || (y.score - x.score) || String(x.id).localeCompare(String(y.id)));
- return { ranking, matches };
+ return { ranking, matches, stopped, roundsCompleted };
}
// ---------- compare-call winner parsing ----------
@@ -311,7 +327,8 @@ export function eligibleIssues(issues) {
* billed once per match (autopilot budget); return false to STOP early.
* @param {Array} [opts.issues] pre-loaded issue list (tests / callers)
* @returns {Promise<object>} the stored snapshot, or `{ status:'insufficient' }`
- * when fewer than two issues have drafted content.
+ * when fewer than two issues have drafted content. A budget-stopped
+ * tournament is persisted as `status:'partial'`.
*/
export async function runComparativeRank(seriesId, opts = {}) {
assertValidSeriesId(seriesId);
@@ -330,10 +347,10 @@ export async function runComparativeRank(seriesId, opts = {}) {
let budgetStopped = false;
const playMatch = async (aId, bId) => {
- if (budgetStopped) return 'a';
+ if (budgetStopped) return TOURNAMENT_STOP;
if (chargeAction) {
const ok = await chargeAction({ a: aId, b: bId });
- if (ok === false) { budgetStopped = true; return 'a'; }
+ if (ok === false) { budgetStopped = true; return TOURNAMENT_STOP; }
}
const A = byId.get(aId);
const B = byId.get(bId);
@@ -345,7 +362,8 @@ export async function runComparativeRank(seriesId, opts = {}) {
return winner;
};
- const { ranking } = await runSwissTournament(entrants, playMatch, { rounds });
+ const { ranking, roundsCompleted } = await runSwissTournament(entrants, playMatch, { rounds });
+ const status = budgetStopped ? 'partial' : 'complete';
// Merge issue metadata onto the ranking rows for the Editorial page.
const ranked = ranking.map((row, idx) => {
@@ -366,14 +384,15 @@ export async function runComparativeRank(seriesId, opts = {}) {
const snapshot = {
seriesId,
- status: 'complete',
+ status,
sourceContentHash: await computeSourceContentHash(seriesId, { issues }).catch(() => null),
entrants: entrants.length,
rounds: effectiveRounds(entrants.length, rounds),
+ roundsCompleted,
k: ELO_K,
ranking: ranked,
- // Weakest-first slice — the revision-priority order Phase 7 consumes.
- weakest: [...ranked].reverse().slice(0, 5),
+ // Weakest-first slice — only complete rankings are safe revision evidence.
+ weakest: status === 'complete' ? [...ranked].reverse().slice(0, 5) : [],
matches: matchRecords,
budgetStopped,
providerId: providerId || null,
diff --git a/server/services/pipeline/editorial/comparativeRank.test.js b/server/services/pipeline/editorial/comparativeRank.test.js
index c349d031e4..9d6a15c9a2 100644
--- a/server/services/pipeline/editorial/comparativeRank.test.js
+++ b/server/services/pipeline/editorial/comparativeRank.test.js
@@ -50,6 +50,7 @@ const {
eligibleIssues,
START_RATING,
ELO_K,
+ TOURNAMENT_STOP,
__testing,
} = await import('./comparativeRank.js');
@@ -190,6 +191,19 @@ describe('runSwissTournament', () => {
expect(ranking).toHaveLength(3);
expect(ranking[0].id).toBe('iss-1');
});
+
+ it('stops before mutating the declined match', async () => {
+ const entrants = [makeIssue(1), makeIssue(2), makeIssue(3), makeIssue(4)];
+ const playMatch = vi.fn(async () => TOURNAMENT_STOP);
+ const result = await runSwissTournament(entrants, playMatch, { rounds: 4 });
+
+ expect(result.stopped).toBe(true);
+ expect(result.roundsCompleted).toBe(0);
+ expect(result.matches).toEqual([]);
+ expect(playMatch).toHaveBeenCalledTimes(1);
+ expect(result.ranking.every((row) => row.rating === START_RATING)).toBe(true);
+ expect(result.ranking.every((row) => row.wins === 0 && row.losses === 0)).toBe(true);
+ });
});
describe('parseCompareWinner (tie-refusal handling)', () => {
@@ -265,9 +279,29 @@ describe('runComparativeRank', () => {
const chargeAction = async () => { calls += 1; return calls <= 1; }; // allow one match then cut off
const snap = await runComparativeRank('ser-1', { issues, chargeAction });
expect(snap.budgetStopped).toBe(true);
+ expect(snap.status).toBe('partial');
+ expect(snap.matches).toHaveLength(1);
+ expect(snap.weakest).toEqual([]);
+ expect(snap.ranking.filter((row) => row.rating !== START_RATING)).toHaveLength(2);
+ expect(snap.ranking.filter((row) => row.rating === START_RATING)).toHaveLength(2);
// Only the first match actually ran the LLM (subsequent matches short-circuit).
expect(stageRunner.runStagedLLM).toHaveBeenCalledTimes(1);
});
+
+ it('persists an explicit partial result without inventing a first match', async () => {
+ stageRunner.runStagedLLM.mockResolvedValue({ content: { winner: 'A' } });
+ const chargeAction = vi.fn(async () => false);
+ const snap = await runComparativeRank('ser-1', {
+ issues: [makeIssue(1), makeIssue(2), makeIssue(3), makeIssue(4)],
+ chargeAction,
+ });
+
+ expect(snap).toMatchObject({ status: 'partial', budgetStopped: true, matches: [], weakest: [] });
+ expect(snap.ranking.every((row) => row.rating === START_RATING)).toBe(true);
+ expect(snap.ranking.every((row) => row.wins === 0 && row.losses === 0)).toBe(true);
+ expect(stageRunner.runStagedLLM).not.toHaveBeenCalled();
+ expect(chargeAction).toHaveBeenCalledTimes(1);
+ });
});
describe('getComparativeRank staleness pinning', () => {
diff --git a/server/services/pipeline/seriesAutopilot/revisionSteps.js b/server/services/pipeline/seriesAutopilot/revisionSteps.js
index 2f47fa55c7..4192114bef 100644
--- a/server/services/pipeline/seriesAutopilot/revisionSteps.js
+++ b/server/services/pipeline/seriesAutopilot/revisionSteps.js
@@ -133,7 +133,10 @@ export async function runRevisionCycle(sId, record) {
// else the judge's weakest-first (lowest qualityScore).
let weakestId = null;
const rank = await getComparativeRank(sId).catch(() => null);
- if (rank?.status === 'complete' && !rank.stale && Array.isArray(rank.weakest) && rank.weakest[0]) {
+ // A budget-stopped snapshot is deliberately `partial`; never let partial
+ // standings become the autopilot's comparative revision evidence.
+ if (rank?.status === 'complete' && rank.budgetStopped !== true && !rank.stale
+ && Array.isArray(rank.weakest) && rank.weakest[0]) {
weakestId = rank.weakest[0].issueId;
}
if (!weakestId) weakestId = seriesJudge.weakest?.[0]?.issueId || null;