Bring PaperTrail's flagship distortion detector into the mixture as the high-weight `discrepancy` agent (lib/verify/discrepancy.ts extract -> audit -> ground -> deterministic reconcile; catches magnitude/population/caveat/no-support distortions plain entailment misses). One clean healthy-API run: MoA 100% (20/20) vs Claude-alone 80% vs single-engine PaperTrail 75%. Harden the composition with 64 audit-driven fixes (24-agent audit -> 22-agent fix workflow, one file each, moat preserved): - aggregate.ts: fix qualityMult overwrite bug (only paper-qa's producer sets the global multiplier; verifiers no longer double-count or clobber it) - discrepancy: reconcile on the SAME truncated window the LLM saw; severity- and grounding-scaled refute confidence (no flat 0.7 floor); drop trust_score fallback - magnitude: borderline-tolerance guard, log-scaled confidence, support vote on an unambiguous significant source effect, ungrounded-effect audit trail - minicheck: calibrated gate, per-source try/catch, deterministic NEI tie-break - quant-extractor: only emit grounded effects; multivers: directional confidence; plus scispacy/indra/pytrials/storm/autogather/autoloop robustness - lib/claude.ts: exponential backoff on 429/529/503 (transient only) Resilience finding (honest): when the app key hit its usage cap mid-campaign (hard 400, regains 2026-08-01), every LLM call failed — Claude-alone and pure-LLM PaperTrail collapsed to 10%, but the MoA held 80-85% on its deterministic agents. docs/benchmark-clinical.md records the full multi-run story + the cap caveat (post-fix accuracy must be re-confirmed once the key resets).
202 lines
8.3 KiB
TypeScript
202 lines
8.3 KiB
TypeScript
// PaperTrail MoA v2 agent · paper-qa source-quality ENRICHER (produces "quality").
|
|
//
|
|
// paper-qa's synthesis treats every retrieved passage as equally trustworthy once it
|
|
// clears retrieval; PaperTrail cannot. This enricher wraps lib/paperqa/sourceQuality.ts
|
|
// to assign each source a QUALITY TIER (A/B/C/D) and a WEIGHT in [0,1] from its metadata
|
|
// alone, then PRODUCES a typed `quality` artifact onto the blackboard:
|
|
//
|
|
// SourceQuality { weightById: {sourceId:{tier,weight}}, meanWeight, retractedIds }
|
|
//
|
|
// Downstream verifiers/aggregation CONSUME this artifact to DOWN-WEIGHT low-tier evidence
|
|
// instead of counting it at face value. It does not read the claim and casts no
|
|
// support/refute vote — its signal is always `neutral` (it weights the mix, it does not
|
|
// vote on the claim). It CONSUMES nothing, so it sits in the first (enricher) layer.
|
|
//
|
|
// Deterministic end-to-end: tier and weight are a pure function of metadata, so the same
|
|
// input always yields the same contribution. No LLM, no I/O, no DB pool — usedClaude is
|
|
// always false. Stateless: safe to run inside the stateless scheduler.
|
|
|
|
import type {
|
|
MoaAgent,
|
|
OrchestrationContext,
|
|
AgentContribution,
|
|
Blackboard,
|
|
MoaSource,
|
|
SourceQuality,
|
|
} from "../types";
|
|
import {
|
|
makeContribution,
|
|
skippedContribution,
|
|
erroredContribution,
|
|
clamp01,
|
|
} from "../types";
|
|
import {
|
|
scoreSourceQualityBatch,
|
|
type SourceQualityMeta,
|
|
type SourceQualityResult,
|
|
} from "../../paperqa/sourceQuality";
|
|
|
|
const AGENT_ID = "paperqa";
|
|
|
|
// Per-source detail row surfaced to the UI detail panel. Ids/tiers/weights only — never
|
|
// raw source text or secrets.
|
|
interface SourceTierDetail {
|
|
id: string;
|
|
tier: SourceQualityResult["tier"];
|
|
tierLabel: string;
|
|
weight: number;
|
|
retracted: boolean;
|
|
}
|
|
|
|
// Translate an orchestrator MoaSource into the metadata shape the paper-qa scorer accepts.
|
|
// MoaSource carries no Retraction Watch id, so only the explicit `retracted` flag is
|
|
// forwarded; every field is optional and the scorer defensively narrows it.
|
|
function toQualityMeta(source: MoaSource): SourceQualityMeta {
|
|
return {
|
|
id: source.id,
|
|
journal: source.journal ?? null,
|
|
year: source.year ?? null,
|
|
citations: source.citations ?? null,
|
|
is_preprint: source.isPreprint ?? null,
|
|
is_open_access: source.isOpenAccess ?? null,
|
|
retracted: source.retracted ?? null,
|
|
};
|
|
}
|
|
|
|
const agent: MoaAgent = {
|
|
id: AGENT_ID,
|
|
name: "paper-qa Source-Quality Tiers",
|
|
category: "enricher",
|
|
description:
|
|
"Enricher: assigns each source a quality tier (A/B/C/D) and weight from its metadata and produces a `quality` artifact so downstream agents can down-weight preprints, low-cited, and retracted evidence. Weights the verdict; casts no support/refute vote.",
|
|
|
|
// ENRICHER: produces the typed quality weighting; consumes nothing (first layer).
|
|
produces: ["quality"] as const,
|
|
consumes: [] as const,
|
|
|
|
// Deterministic eligibility from the input alone: as long as >=1 source exists there is
|
|
// something to tier (the scorer works from metadata or documented defaults). No sources
|
|
// -> nothing to weight -> gate 0.
|
|
gate(ctx: OrchestrationContext): number {
|
|
return ctx.sources.length >= 1 ? 0.5 : 0;
|
|
},
|
|
|
|
async run(
|
|
ctx: OrchestrationContext,
|
|
_bb: Blackboard
|
|
): Promise<AgentContribution> {
|
|
// Enricher consumes nothing, so the blackboard is intentionally unused here.
|
|
void _bb;
|
|
|
|
if (ctx.sources.length === 0) {
|
|
return skippedContribution(
|
|
AGENT_ID,
|
|
"No sources to tier — source-quality weighting had nothing to score."
|
|
);
|
|
}
|
|
|
|
try {
|
|
const metas = ctx.sources.map(toQualityMeta);
|
|
const results = scoreSourceQualityBatch(metas);
|
|
|
|
// INVARIANT: scoreSourceQualityBatch is `metas.map(scoreSourceQuality)`, so
|
|
// results.length === metas.length === ctx.sources.length (> 0 here, guarded above).
|
|
// The explicit guard makes that invariant enforced rather than assumed: if the scorer
|
|
// ever returned [] for a non-empty input, the mean below would divide by zero. Rather
|
|
// than emit a NaN-derived (clamped-to-0) weight silently, we skip honestly. (fix 2)
|
|
if (results.length === 0) {
|
|
return skippedContribution(
|
|
AGENT_ID,
|
|
"No sources scored by sourceQuality — nothing to weight."
|
|
);
|
|
}
|
|
|
|
// Build the typed `quality` artifact for downstream consumers.
|
|
const weightById: SourceQuality["weightById"] = {};
|
|
for (const r of results) {
|
|
weightById[r.id] = { tier: r.tier, weight: r.weight };
|
|
}
|
|
|
|
const retractedIds = results.filter((r) => r.retracted).map((r) => r.id);
|
|
|
|
// Total-evidence-collapse detector: every source in the mix is retracted (each such
|
|
// source is hard-capped to Tier D / weight 0 by the scorer). This is NOT the same as
|
|
// "low quality" — it means the entire body of evidence is broken and the composition
|
|
// has nothing trustworthy to stand on. We surface it explicitly (fix 1).
|
|
const allRetracted = retractedIds.length === results.length;
|
|
|
|
// Mean quality weight: how much trust the tiers collectively confer on the available
|
|
// evidence. Deterministic, in [0,1]. This is the trust multiplier the aggregator reads.
|
|
// When ALL sources are retracted we pin the collective weight to exactly 0 (defending
|
|
// against float dust from the sum) so the "all evidence is broken" signal is emitted at
|
|
// its true floor. NOTE: the aggregator (aggregate.ts:qualityMultiplierFrom) currently
|
|
// maps any weight through q*0.5+0.5, so a 0 here still becomes a 0.5 multiplier there —
|
|
// the total-collapse signal cannot be fully honored without correcting that floor in
|
|
// aggregate.ts, which is out of this file's scope. Emitting a hard 0 (plus the explicit
|
|
// allRetracted flag below) preserves the signal so the fix in the aggregator lands cleanly.
|
|
const meanWeight = allRetracted
|
|
? 0
|
|
: clamp01(
|
|
results.reduce((sum, r) => sum + r.weight, 0) / results.length
|
|
);
|
|
|
|
const qualityArtifact: SourceQuality = {
|
|
weightById,
|
|
meanWeight,
|
|
retractedIds,
|
|
};
|
|
|
|
const detailRows: SourceTierDetail[] = results.map((r) => ({
|
|
id: r.id,
|
|
tier: r.tier,
|
|
tierLabel: r.tierLabel,
|
|
weight: r.weight,
|
|
retracted: r.retracted,
|
|
}));
|
|
|
|
const tierCounts = results.reduce<Record<string, number>>((acc, r) => {
|
|
acc[r.tier] = (acc[r.tier] ?? 0) + 1;
|
|
return acc;
|
|
}, {});
|
|
|
|
const summary = allRetracted
|
|
? `ALL ${results.length} source${results.length === 1 ? " is" : "s are"} RETRACTED (Tier D, weight 0) — the entire body of evidence is broken; collective trust weight 0.00.`
|
|
: retractedIds.length > 0
|
|
? `${retractedIds.length} RETRACTED source${retractedIds.length === 1 ? "" : "s"} flagged (Tier D, weight 0) — evidence down-weighted; tiered ${results.length} source${results.length === 1 ? "" : "s"}, mean trust ${meanWeight.toFixed(2)}.`
|
|
: `Tiered ${results.length} source${results.length === 1 ? "" : "s"} by quality; mean trust weight ${meanWeight.toFixed(2)}.`;
|
|
|
|
return makeContribution(AGENT_ID, {
|
|
ran: true,
|
|
// Enricher: contributes source-quality context, never a support/refute vote.
|
|
signal: "neutral",
|
|
// Confidence is the mean quality weight — collective trust in the evidence.
|
|
confidence: meanWeight,
|
|
summary,
|
|
detail: {
|
|
// The aggregator reads detail.qualityWeight as a trust multiplier.
|
|
qualityWeight: meanWeight,
|
|
sourceCount: results.length,
|
|
meanWeight,
|
|
tierCounts,
|
|
retractedIds,
|
|
retractedCount: retractedIds.length,
|
|
// Explicit total-collapse flag: true when every source is retracted. Lets a
|
|
// corrected aggregator (or the UI) recognize broken-evidence bodies without
|
|
// re-deriving it, and distinguishes "0 because all retracted" from "0 by chance".
|
|
allRetracted,
|
|
perSource: detailRows,
|
|
},
|
|
// No grounded quotes: tiering reads metadata only, never the source body.
|
|
groundedSpans: [],
|
|
usedClaude: false,
|
|
// Publish the typed artifact for the composition DAG.
|
|
produced: { quality: qualityArtifact },
|
|
});
|
|
} catch (err) {
|
|
return erroredContribution(AGENT_ID, err);
|
|
}
|
|
},
|
|
};
|
|
|
|
export default agent;
|