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).
90 lines
56 KiB
JavaScript
90 lines
56 KiB
JavaScript
export const meta = {
|
|
name: 'moa-fix-round1',
|
|
description: 'Apply audit-ranked fixes per file (one agent per file, disjoint) so the MoA robustly beats Claude',
|
|
phases: [
|
|
{ title: 'Fix', detail: 'one agent per file applies its audit fixes' },
|
|
{ title: 'Verify', detail: 'adversarial build + moat review' },
|
|
],
|
|
}
|
|
|
|
const CONTRACT = [
|
|
'PAPERTRAIL MoA — apply the audited fixes to YOUR ONE file to make the composition robustly BEAT Claude-alone.',
|
|
'MOAT RULES (do not break): NO LLM in any numeric/scoring/verdict path — deterministic math decides; Claude only',
|
|
'for grounded language steps already present. Keep every public export name + signature stable (registry.ts,',
|
|
'types.ts, aggregate.ts, orchestrate.ts and other agents import these — do NOT change the default export shape or',
|
|
'the MoaAgent interface). Preserve produces/consumes correctness. TS strict, no any, no TODOs. Grounded spans stay',
|
|
'verbatim. Apply EACH listed fix precisely; if a fix would break the moat or a public contract, implement the',
|
|
'SAFEST variant that achieves the intent and say so in notes. Touch ONLY your file. Do NOT run npm/tsc/git.',
|
|
].join('\n')
|
|
|
|
const FILES = [{"file": "lib/moa/agents/minicheck.ts", "issues": [{"s": "high", "c": "wrong_verdict", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/minicheck.ts:203-211", "p": "When best.moaLabel === 'NEI', the agent votes with signal='insufficient' and confidence=0, but then the aggregator computes weight = 0.9 * 0 * 1.0 = 0, making minicheck's contribution invisible. However, minicheck still increments the 'ran' count in aggregate.ts line 70, lowering the overall agreement denominator without contributing to supports/refutes numerator. This can flip a close verdict to ", "fix": "Either (1) conditionally lower the gate when all usable sources are predicted to return NEI, or (2) split the agent into a deterministic polarity detector (enricher) and an LLM-dependent verifier, or (3) at line 211, when best.moaLabel === 'NEI', emit confidence = best.weightedConfidence (which is 0 anyway) so the vote is truly neutral instead of consuming a vote slot. Best: add a second pass in g"}, {"s": "high", "c": "robustness", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/minicheck.ts:202-206", "p": "When decisive.length === 0 (no SUPPORTS/REFUTES), the fallback at lines 205-206 uses reduce((a,b) => b.w > a.w ? b : a) on all NEI entries with weightedConfidence=0. Since all are equal, the comparator a.w > b.w is always false, so reduce returns the FIRST element (a always wins ties). This means the 'best' NEI is arbitrary\u2014it's whatever source order the filter produced\u2014and minicheck's detail.best", "fix": "When all evaluated are NEI, pick a representative source deterministically: either the source with the longest text (most evidence to work with), the highest raw score before quality weighting, or the first if truly tie-breaking. Or, add a tiebreaker: (a,b) => b.weightedConfidence > a.weightedConfidence || (b.weightedConfidence === a.weightedConfidence && b.source.id > a.source.id) to ensure deter"}, {"s": "high", "c": "wrong_verdict", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/minicheck.ts:176-180, 203-206", "p": "Quality down-weighting at line 180 can invert the decisiveness ranking: a high-confidence REFUTES from a low-quality source can be out-voted by a low-confidence SUPPORTS from a high-quality source. This is intentional down-weighting (honest), but minicheck doesn't expose the raw-score ranking separately, so downstream verifiers that read sourceLabels see the weighted-down confidence but can't know", "fix": "Expose the raw (unweighted) confidence in the sourceLabels artifact alongside the weighted confidence. Add a field: sourceLabels now include { sourceId, label, confidence, rawConfidence, qualityWeight, span }. This allows downstream verifiers to decide whether to trust quality weighting or re-weight themselves. Or, document this behavior clearly in the summary so consumers know why the 'best' labe"}, {"s": "high", "c": "robustness", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/minicheck.ts:173-189", "p": "The for-loop at lines 173-189 iterates and pushes to evaluated[] for each source. If verifyAbsenceClaim(C) throws (e.g., schema validation failure, network timeout, JSON parse error), the loop breaks, the try-catch at line 255 catches it, and the agent returns erroredContribution(), setting ran=false and signal='insufficient'. However, sources A and B were already successfully evaluated and added ", "fix": "Wrap the verifyAbsenceClaim call in a try-catch within the loop: for (const source of usableSources) { try { const result = await verifyAbsenceClaim(...); ... evaluated.push(...); } catch (e) { /* log warning, skip this source, continue */ } }. If any source fails, still return the sourceLabels for the sources that succeeded, with an explanatory note in the summary that N out of M sources were eva"}, {"s": "medium", "c": "calibration", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/minicheck.ts:57-58, 121-126", "p": "The gate is constant (0.9) regardless of source count. Intuitively, minicheck should have higher confidence (higher gate) when evaluating 10 well-written sources vs. 1 sparse source, because more evidence typically increases label reliability. Instead, both are gated at 0.9. This is a calibration miss: the gate should reflect the expected quality of the resulting verdict. With 1 source, the gate s", "fix": "Make gate conditional on source count and text length: gate(ctx) { ... const avgSourceLength = usable > 0 ? usable.map(s => s.text.length).reduce((a,b) => a+b) / usable : 0; return Math.min(0.95, 0.5 + 0.05*usable + 0.0001*avgSourceLength); } This increases gate from 0.6 (1 short source) to 0.9+ (10+ long sources), aligning gate with evidence density."}, {"s": "medium", "c": "calibration", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/minicheck.ts:210-211", "p": "More subtly: at line 211, the code is confidence = best.moaLabel === 'NEI' ? 0 : best.weightedConfidence. But best.result.score (the raw model confidence in the presence/absence judgement) is discarded. If Claude says 'I'm 0.95 confident this source doesn't address the effect', that should count for something\u2014it's not uncertainty, it's a strong 'neither'. Currently, that gets zeroed.", "fix": "Preserve the raw score even for NEI: const confidence = best.moaLabel === 'NEI' ? clamp01(best.result.score * best.qualityWeight * 0.1) : best.weightedConfidence; The 0.1 factor downweights NEI-confidence so it's subordinate to decisive signals (SUPPORTS/REFUTES confidence stays at full weight), but it's not completely 0. Alternatively, document why confidence=0 for NEI and leave it as-is if the i"}, {"s": "medium", "c": "robustness", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/minicheck.ts:85-93", "p": "The spanFromResult function at lines 85-93 assumes result.supporting_span has a valid grounding object with start and end. If verifyAbsenceClaim returns a supporting_span with grounding=null or undefined, spanFromResult accesses null.start and throws. Although verifyAbsenceClaim.ts shouldn't produce null grounding for a non-null supporting_span, defensive coding should check. If it does happen, th", "fix": "Add a guard: if (!result.supporting_span || !result.supporting_span.grounding) return null; at the start of spanFromResult."}]}, {"file": "lib/moa/agents/magnitude.ts", "issues": [{"s": "high", "c": "wrong_verdict", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/magnitude.ts:130", "p": "Agent votes 'refutes' when reconcile() returns magnitude_overstated, but this verdict is reflexive without checking if the source and claim magnitudes are actually consistent within tolerance. Edge cases near the materiality threshold can produce false refutes votes.", "fix": "Before voting refutes on distorted verdicts, cross-check that claimedValue and sourceEffect.point are not within tight tolerance (\u00b15%) when both represent the same reduction metric. Alternatively, refactor reconcile to return 'borderline' for marginal cases and treat borderline as insufficient rather than distorted."}, {"s": "high", "c": "calibration", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/magnitude.ts:131", "p": "Confidence formula inverts proper weighting: distorted starts at 0.7 base, consistent at 0.5 base. This makes a single distortion (0.8) more confident than modest consistent evidence (0.7), reversing signal priority. Distortions are rare catches and should start cautious; consistent verdicts should start strong.", "fix": "Swap confidence bases: distorted should start at 0.55 (rare, needs corroboration), consistent at 0.75 (agreement is strong). Use logarithmic scaling (e.g., 0.5 + 0.2 * log2(count+1)) instead of linear to avoid over-rewarding single cases."}, {"s": "high", "c": "missed_capability", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/magnitude.ts:121-135", "p": "Agent votes insufficient when source has significant effect but claim makes no numeric assertion. Reconcile returns cannot_reconcile because claimedReductionPercent is null, conflating 'incomparable framing' (relative vs absolute) with 'source has numbers, claim does not'. Should vote supports when source effect is significant and unambiguous.", "fix": "After cannot_reconcile, check if source has significant effect (ratio CI does not cross null, or absolute change is meaningful). If yes and claim asserts benefit, vote supports with confidence 0.6 and detail explaining the source numeric finding."}, {"s": "medium", "c": "robustness", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/magnitude.ts:107-118", "p": "Grounding failures are silently dropped without logging. For a deterministic system claiming 100% determinism, losing spans silently is a subtle loss: contribution appears weakly evidenced even though reconciliation succeeded.", "fix": "Add detail tracking for ungrounded effects: when locateSpan returns null, append to detail object: ungroundedEffects: [{ sourceId, attempted, reason }]. This preserves audit trail without throwing."}, {"s": "medium", "c": "composition", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/magnitude.ts:71", "p": "Agent declares consumes: ['effect_sizes'] but confidence formula does not adjust for artifact presence/absence. When artifact present, grounding is pre-validated; when absent, degrades gracefully with same confidence. Should reflect this uncertainty in confidence scoring.", "fix": "Increase confidence by 0.05 when effects !== undefined (line 162). Alternatively, gate confidence scaling explicitly: if effectSizesConsumed is false, apply 0.9x multiplier to the confidence formula."}, {"s": "medium", "c": "calibration", "loc": "lib/moa/agents/magnitude.ts:131", "p": "The confidence formula 0.7 + 0.1 * distorted.length can exceed 1.0 for 4+ distorted sources. A single consistent source gets drowned out by four distortions, giving confidence=1.0 on refutes. There is no discount for mixed results, overconfidently punishing claims with mostly (not entirely) consistent evidence.", "fix": "Use a ratio-based confidence: clamp01(0.5 + 0.5 * (distorted.length / perSource.length)). This makes 2 distorted in 5 = 0.5 + 0.5 * 0.4 = 0.7, and 5 distorted in 5 = 1.0. Reflects evidence balance and prevents single-evidence distortions from claiming maximum confidence."}]}, {"file": "lib/moa/aggregate.ts", "issues": [{"s": "high", "c": "calibration", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/aggregate.ts:82-85", "p": "Double-weighting of quality: minicheck folds quality into per-label confidence, so low-quality sources already contribute less. Then the aggregator reads paperqa's meanWeight and applies it again as a global multiplier. A Tier-C source's label (confidence 0.5) gets multiplied by 0.5 again in minicheck, then all votes are multiplied by 0.5 globally, resulting in effective weight 0.25 instead of 0.5", "fix": "Remove the detail.qualityWeight read from aggregate.ts:82-85, OR remove the per-source quality weighting from minicheck.ts:180. The current design double-counts quality in a way that dramatically under-weights evidence."}, {"s": "high", "c": "wrong_verdict", "loc": "lib/moa/aggregate.ts:82-85", "p": "The qualityMult variable is overwritten in every loop iteration (line 84). Only the LAST agent in the weighted array that carries a qualityWeight in detail determines the final qualityMult, which then applies to the trust calculation (lines 124, 126). If paper-qa runs first but a later verifier provides a different qualityWeight, the later one silently overwrites it. This is a composition bug: the", "fix": "Extract qualityMult calculation outside the loop. Instead of iterating through all weighted contributions, read it once from the agent that actually produces the quality artifact (identify which agent is the producer via bb.producerOf('quality'), or use only the paper-qa contribution's detail.qualityWeight). Alternatively, only read qualityWeight from the paper-qa agent (category 'enricher', id 'p"}, {"s": "high", "c": "calibration", "loc": "lib/moa/aggregate.ts:82-85", "p": "If a verifier copies or inherits qualityWeight into its detail field, it will overwrite the true quality weight from paper-qa. The logic reads `c.detail?.['qualityWeight']` for every agent, not just the producer. This creates an undeclared, implicit dependency: verifiers that put qualityWeight in detail (even for tracing/logging) will accidentally change the trust score. The composition contract d", "fix": "Make the qualityWeight reading explicit and safe: (1) declare qualityWeight as a first-class artifact itself (like other sources of truth), OR (2) read it only from paper-qa's contribution by matching agentId === 'paperqa', OR (3) document and enforce in detail field naming that NO other agent may include 'qualityWeight'. Currently it is a silent composition hazard."}]}, {"file": "lib/moa/agents/autogather.ts", "issues": [{"s": "high", "c": "robustness", "loc": "lib/moa/agents/autogather.ts:296-300", "p": "locateCue() uses indexOf() to find the FIRST occurrence of a cue substring in raw text. If a cue appears multiple times with different semantic contexts (e.g., one supported and one negated), the function returns the wrong span location. This violates the contract that grounded spans must be clinically/semantically grounded, not just syntactically matched.", "fix": "Either (1) return all matching spans and let the caller select contextually appropriate one, (2) use NLP context detection to skip negated/speculative contexts, or (3) document that returned spans are 'representative locations' not 'clinically validated positions' and warn downstream consumers."}, {"s": "high", "c": "wrong_verdict", "loc": "lib/moa/agents/autogather.ts:221-225 vs 274", "p": "keyEntities() preserves entity text from scispaCy as-is (including non-ASCII like '\u03b1'), but termMatches() normalizes BOTH normalized source text AND search terms by stripping all non-alphanumeric characters (/[^a-z0-9]+/g). This causes Greek letters (\u03b1, \u03b2, \u03b3) and other special characters common in biomedical entities (TNF-\u03b1, IL-6, CYP2D6*4) to strip to empty, collapsing multi-part entities into un", "fix": "Before storing entity terms from scispaCy in keyEntities(), normalize them using the SAME normalize() function applied to source text (line 190), so that 'TNF-\u03b1' becomes 'tnf a' and matches the normalized source. Alternatively, transliterate Greek letters to ASCII before normalization (\u03b1\u2192a, \u03b2\u2192b, \u03b3\u2192g)."}, {"s": "high", "c": "composition", "loc": "lib/moa/agents/autogather.ts:296-300 (locateCue function)", "p": "locateCue() returns a GroundedSpan with sourceId HARDCODED to empty string ''. The sourceId is only set correctly when the span is destructured and reassigned at line 393 ({ ...span, sourceId: firstId }). If the span is ever used or logged BEFORE that reassignment, or if the contract changes, downstream code receives an invalid sourceId. This violates semantic correctness of GroundedSpan.", "fix": "Pass sourceId as a parameter to locateCue(sourceId: string, rawText, cue) and return it initialized correctly: { sourceId, text: ..., start: ..., end: ... }. Or set sourceId immediately after calling locateCue without destructuring."}, {"s": "medium", "c": "robustness", "loc": "lib/moa/agents/autogather.ts:173-174 (STOP_WORDS) combined with 78 (efficacy cues) and 234-235 (keyEntities fallback)", "p": "The keyEntities() fallback path filters stop-words from claim tokens to avoid seeding sub-queries from filler. However, several cue terms appear in STOP_WORDS: 'reduced' (line 173 + 78), 'reduces' (line 174 + 80 'reduction'). When a claim explicitly uses these words (e.g., 'Drug X reduced mortality'), the fallback discards them as unimportant, causing the agent to miss that the claim is ABOUT effi", "fix": "Exclude from STOP_WORDS filtering any token that appears in any FACETS.cues array. Create a const FACET_CUE_TERMS = new Set([...FACETS.flatMap(f => f.cues)]); then filter: if (raw.length < 4 || (STOP_WORDS.has(raw) && !FACET_CUE_TERMS.has(raw)) || seen.has(raw)) continue;"}, {"s": "medium", "c": "calibration", "loc": "lib/moa/agents/autogather.ts:375, 408", "p": "Confidence is set to coverageFraction = covered.length / total (line 408). This fraction alone does NOT account for SCOPE\u2014the number of distinct entities/facets the agent tested. A 75% coverage of 4 sub-queries is qualitatively different (weaker evidence) than 75% coverage of 24 sub-queries. The agent votes NEUTRAL in both cases with very similar confidence, which UNDERCALIBRATES the second case a", "fix": "Confidence should incorporate both coverage fraction AND scope breadth: confidence = (covered.length / total) * (1 - Math.exp(-keyTerms.length / 2)). This dampens confidence when scope is narrow (< 2 entities), amplifies it when scope is broad (4+ entities), and caps the boost as scope grows. Alternative: Confidence = coverageFraction * min(1, keyTerms.length / 4) so that 1 entity caps confidence "}, {"s": "medium", "c": "robustness", "loc": "lib/moa/agents/autogather.ts:351 (sort comparator)", "p": "The sort comparator at line 351 uses lexicographic id ordering (a.id < b.id) as the tie-breaker when ranks are equal. The comment says 'stable tie-break on input order' (line 262), but the code does NOT preserve input order\u2014it sorts alphabetically. This is deterministic but violates the stated intent. When multiple sources tie on relevance, the agent picks the lexicographically first one rather th", "fix": "Preserve input order by tracking original indices before filtering: const sortedOnTopic = usable.filter(...).map((s, idx) => ({s, originalIndex: idx})).filter(...).map(({s, originalIndex}) => ({...s, originalIndex})).sort((a, b) => (b.rank !== a.rank ? b.rank - a.rank : a.originalIndex - b.originalIndex)). Then use originalIndex in the final array."}, {"s": "medium", "c": "missed_capability", "loc": "lib/moa/agents/autogather.ts:270-289 (generateAndCover function)", "p": "The agent requires BOTH entity AND cue in the SAME source to mark a sub-query COVERED. It does NOT attempt entailment across sources. If Source A proves drug efficacy and Source B proves disease-relevant population, the agent cannot synthesize 'drug efficacy in this population' because no single source ties them together. This is HONEST (it avoids false positives) but MISSES CAPABILITY to recogniz", "fix": "This is NOT a bug\u2014it is intentional design. The agent measures DIRECT coverage, not entailment. If cross-source composition is needed, that should be handled by a separate entailment/synthesis agent (e.g., valsci, evidence-integrator). To enhance autogather, add an optional entailment check: for each uncovered (entity, facet) pair, check if ANY source discusses the entity and ANY OTHER source disc"}]}, {"file": "lib/verify/discrepancy.ts", "issues": [{"s": "high", "c": "wrong_verdict", "loc": "lib/verify/discrepancy.ts:140", "p": "reconcile(claim, sourceText) receives the FULL untruncated sourceText, but Claude only saw sourceText[0:12000] during extraction and sourceText[0:8000] during verification. Effect sizes or caveats outside Claude's visible window can trigger reconcile demotion (magnitude_overstated, caveat_dropped) without any grounded evidence, because the flagged spans would fail grounding since they weren't in t", "fix": "Replace line 140 with: const rec = reconcile(claim, source); (pass the same truncated source text Claude saw, not sourceText)"}, {"s": "medium", "c": "robustness", "loc": "lib/verify/discrepancy.ts:112 and 128", "p": "Asymmetric truncation between extraction (12KB) and verification (8KB) steps. If a finding appears in [8000:12000], Claude extracts it in step 1 but cannot meaningfully reference it in step 2 when building the verification result, creating internally inconsistent reasoning about the same source.", "fix": "Standardize truncation lengths: either truncate both to 8000 characters, or don't truncate sources under 12000 chars. At minimum, verify both steps use the same boundary: source.slice(0, 8000) in both line 112 and 128."}]}, {"file": "lib/moa/agents/discrepancy.ts", "issues": [{"s": "high", "c": "wrong_verdict", "loc": "lib/moa/agents/discrepancy.ts:109", "p": "The confidence formula clamp01(Math.max(0.7, 1 - trustScore/100)) sets a hard floor of 0.7 for ALL distortions regardless of severity. Per VERIFICATION_SYSTEM prompt (line 73-75), trustScore 60-89 is 'minor drift', not 'meaningful distortion'. This makes weak refute votes (confidence 0.7) almost as strong as supports votes (typically 75-90 confidence) in aggregation. A single weak distortion vote ", "fix": "Scale confidence by trustScore severity and grounding quality: const groundingFactor = result.groundedSpans.length > 0 ? 1 : 0.3; const minConfidence = result.trustScore <= 30 ? 0.8 : (result.trustScore <= 60 ? 0.5 : 0.3); confidence = clamp01(Math.max(minConfidence, 1 - result.trustScore/100) * groundingFactor);"}, {"s": "medium", "c": "calibration", "loc": "lib/moa/agents/discrepancy.ts:106-109", "p": "When multiple flagged spans fail grounding (reported in droppedUngroundedSpans), the agent still votes with the fixed 0.7 confidence floor. This creates a contradiction: the vote claims a distortion is refuted but provides minimal (1/5) grounded evidence to the user. The confidence should degrade proportionally to grounding success.", "fix": "Adjust line 109: const groundingRate = result.groundedSpans.length / Math.max(1, result.groundedSpans.length + result.droppedUngroundedSpans); confidence = clamp01(Math.max(0.7, 1 - result.trustScore/100) * (0.3 + 0.7 * groundingRate));"}, {"s": "medium", "c": "calibration", "loc": "lib/moa/agents/discrepancy.ts:106-109", "p": "High trustScore (90+) contradicts a distortion verdict. The confidence formula max(0.7, 1-95/100) = 0.7 does not flag or lower confidence for this LLM contradiction (high confidence + distortion claim). This indicates either LLM confusion or conflicting signals in the audit.", "fix": "Add a guard: if (result.trustScore > 80 && DISTORTIONS.has(result.discrepancyType)) { confidence = 0.3; } before the normal confidence calculation to handle this anomalous case."}]}, {"file": "lib/moa/agents/multivers.ts", "issues": [{"s": "high", "c": "calibration", "loc": "lib/moa/agents/multivers.ts:168", "p": "Confidence is derived from Math.abs(netConfidence), which becomes 0 when support and refute masses are exactly balanced. This causes the agent's 'mixed' signal to be weighted as 0 in the final aggregator (weight = gate * confidence * categoryWeight = 0.7 * 0 * 1.0 = 0), completely drowning the conflict signal. The agent detects genuine disagreement but votes with zero confidence, so Claude-alone's", "fix": "Use the directional mass magnitude (supports + refutes) as a confidence signal instead of netConfidence magnitude. For example: confidence = clamp01((supportMass + refuteMass) / (supportMass + refuteMass + neiMass)) to reflect the total directional evidence strength, not just the balance. Alternatively, use aggregate.consideredCount or another structural measure of evidence that survives ties."}, {"s": "medium", "c": "composition", "loc": "lib/moa/agents/multivers.ts:192", "p": "Composition gap: multivers declares it reads quality from the blackboard and applies it (lines 155-160 correctly fold quality into per-source confidence), but it doesn't propagate this fact to the aggregator correctly. The aggregator needs a numeric qualityWeight in detail to adjust trust (aggregate.ts:82-85), but multivers only returns a boolean qualityWeighted. This causes quality-weighting logi", "fix": "Add detail.qualityWeight: number (the mean quality weight or a representative scalar) alongside or instead of detail.qualityWeighted: boolean. Recommend: use aggregate.tally.supportMass / max(1, consideredCount) or the per-source quality weight average to match paper-qa's detail.qualityWeight intent."}, {"s": "medium", "c": "robustness", "loc": "lib/moa/agents/multivers.ts:62-73", "p": "signalFromVerdict is a switch statement with no default case or exhaustiveness check. If aggregateCrossSource ever returns an unexpected verdict string (through a bug or if the verdict enum expands), TypeScript will compile without error, the switch will fall through, and the function will return undefined, which will then be assigned to signal. This will cause agent failure or silent corruption o", "fix": "Add a default case: `default: throw new Error(`Unexpected verdict: ${verdict}`)` to fail fast and loudly, or return 'insufficient' as a safe fallback, making the bug visible immediately rather than during aggregation."}]}, {"file": "lib/moa/agents/storm.ts", "issues": [{"s": "high", "c": "calibration", "loc": "lib/moa/agents/storm.ts:142-148 (confidenceFromMargin function) + line 228 check", "p": "The confidence formula is computed from grounded counts only (supportingCount=1, refutingCount=1), yielding confidence=0.5 for balanced case. However, the original evidence split was 2:1 and one source dropped during grounding. The confidence does not account for this loss of evidence, making a 1v1 debate (that started as 2v1) appear as legitimate as an originally 1v1 debate. The agent reports det", "fix": "Modify confidenceFromMargin to account for grounding loss: pass droppedUngrounded count and apply a dampening factor. Example: `const dampening = 1.0 - (droppedUngrounded / (debate.supportingCount + debate.refutingCount + droppedUngrounded)) * 0.3; return clamp01((0.5 + 0.5 * (margin / total)) * dampening);` Or: document that confidence only reflects grounded evidence quality and downstream aggreg"}, {"s": "medium", "c": "calibration", "loc": "lib/moa/agents/storm.ts:142-148 (confidenceFromMargin function)", "p": "The confidence formula yields 0.5 for any perfectly balanced debate, regardless of total evidence count. A 2v2 balanced debate receives confidence=0.5, and so does a 100v100 balanced debate. This treats high-evidence balanced cases (where both sides are strongly grounded) the same as minimal-evidence balanced cases, potentially undervaluing the credibility of well-researched balanced findings.", "fix": "Consider modifying the formula to reward total evidence count for balanced cases: `const balanceFactor = margin === 0 ? Math.min(1, total / 10) : 0; return clamp01(0.5 + 0.5 * (margin / total) + balanceFactor * 0.2);` This gives 100v100 a boost to ~0.7 confidence while keeping 1v1 at 0.5, reflecting the higher evidence density. Alternatively, document the current design as intentional ('balanced i"}, {"s": "medium", "c": "robustness", "loc": "lib/moa/agents/storm.ts:214 and 229", "p": "Lines 214 and 229 both return skippedContribution with 'no two grounded sides to debate'. The first is a pre-debate guard, the second post-grounding. While both are honest skips, they conflate two failure modes, making the trace ambiguous. If buildDebate fails to ground but doesn't zero a side, the agent votes on ungrounded sources.", "fix": "Distinguish the two skip reasons. Line 214 should say 'no labeled sides to debate' (composition). Line 229 should distinguish which side lost grounding ('supporting side lost all grounded evidence' vs 'refuting side...'). This preserves safety but clarifies the failure mode for debugging."}]}, {"file": "lib/moa/agents/quant-extractor.ts", "issues": [{"s": "high", "c": "wrong_verdict", "loc": "lib/moa/agents/quant-extractor.ts:166-206", "p": "Effects that fail grounding are still included in the produced effect_sizes artifact. Lines 166-171 ground each effect, but only ungrounded effects are excluded from groundedSpans (UI detail). The effects array at line 206 includes ALL effects that passed isKeepableRatio, even those where groundEffect returned null. These ungrounded effects then get consumed by downstream agents like PyMARE and po", "fix": "Filter effects to only include those that pass grounding before adding to the produced artifact. After the loop at 168-171, only add effect e to the effects array if its grounding span is not null. Alternatively, build the effects array in a single pass where effects are only added if they successfully ground: for each ParsedEffect, call groundEffect first; if it returns null, skip; otherwise, add"}, {"s": "medium", "c": "robustness", "loc": "lib/moa/agents/quant-extractor.ts:110-124", "p": "The groundEffect function does not defensively check if source.text is defined before passing it to locateSpan, which calls indexOf on the text. Although MoaSource.text is a required string in the type signature, runtime JavaScript could pass undefined/null, causing locateSpan to throw when trying to call indexOf. The try-catch at line 208 would catch this and return erroredContribution, but a def", "fix": "Add a check in groundEffect after finding the source: if (!source.text) return null; before calling locateSpan. Or at the callsite (line 169), check that the source.text is truthy. This makes the agent gracefully skip ungroundable effects rather than throwing."}]}, {"file": "lib/moa/agents/paperqa.ts", "issues": [{"s": "high", "c": "wrong_verdict", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/paperqa.ts:110-112", "p": "When all sources are retracted or low-quality (meanWeight near 0), the agent correctly sets confidence to the low meanWeight. However, the aggregator applies qualityMult = clamp01(q) * 0.5 + 0.5 (aggregate.ts:84), which ALWAYS stays in [0.5, 1.0]. When q=0 (all retracted), qualityMult becomes 0.5, effectively hiding total evidence collapse. The aggregator should receive the raw evidence strength s", "fix": "Either (a) set confidence to 0 when all sources are retracted, or (b) rethink the qualityMult transform in aggregate.ts to not floor at 0.5. The current design loses the signal 'all evidence is broken' because the multiplier never reaches <0.5."}, {"s": "medium", "c": "robustness", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/paperqa.ts:98-112", "p": "The code assumes results.length >= 1 at line 111 (divides by results.length without checking). If scoreSourceQualityBatch ever returns [] even when passed non-empty metas, meanWeight would be NaN, but clamp01(NaN) = 0, which is safe. However, the assumption is undocumented. scoreSourceQualityBatch always returns results.map per input, so the length invariant holds implicitly.", "fix": "Document the invariant that results.length === metas.length, or add an explicit guard: if (results.length === 0) return skippedContribution(AGENT_ID, 'No sources scored by sourceQuality.')."}]}, {"file": "lib/moa/agents/scispacy.ts", "issues": [{"s": "high", "c": "wrong_verdict", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/scispacy.ts:185-186", "p": "CONFIDENCE MISCALIBRATION: `linkedFraction = totalLinked / totalEntities` naively averages the link success rate. When only some entities resolve, the confidence reflects a false middle ground. But scispacy is an ENRICHER that votes 'neutral' \u2014 the issue is that downstream VERIFIERS that consume these entities (indra, loki) may make WRONG decisions based on entity presence when the entity LINKING ", "fix": "Split the confidence signal: (1) Emit 0.0 confidence when linkedFraction is poor (< threshold, e.g., 0.3), signaling 'enrichment quality is low'; (2) OR, remove the linkedFraction-based confidence entirely and emit a FIXED 1.0 (enricher ran), since scispacy is deterministic and its value is in PRESENCE OF GROUNDED TEXT, not linking score. The grounded-span count (not linked-concept count) should b"}, {"s": "medium", "c": "composition", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/moa/agents/scispacy.ts:79-94", "p": "COMPOSITION GAP: scispacy PRODUCES entities including claim entities (detail shows unitsScanned=1+N), but CONSUMES entities logic in downstream agents (indra, loki) filters on sourceId against ctx.sources[]. The CLAIM entities exist on the blackboard but are invisible to agents because they carry sourceId='__claim__' which is never in the real source ID set. This breaks the composition promise: cl", "fix": "Option A: Do NOT include claim entities in the produced artifact; extract them to detail only (set entities = entities.filter(e => e.sourceId !== CLAIM_UNIT_ID) before returning). Option B: Document that entities artifact INCLUDES synthetic claim entities and update consuming agents (indra, loki) to skip them during composition (check e.sourceId !== '__claim__'). Option A is cleaner: claim is NOT "}]}, {"file": "lib/moa/agents/indra.ts", "issues": [{"s": "high", "c": "wrong_verdict", "loc": "lib/moa/agents/indra.ts:94-105 (claimIsMechanistic function)", "p": "The word-boundary check in claimIsMechanistic is insufficient. The function only checks characters immediately before/after the cue (isWordChar tests /[a-z0-9]/). This will MISS word boundaries created by hyphens, apostrophes, underscores, and punctuation. Examples: 'state-mechanism' would match 'mechanism' even though it's compound; 'it's-mechanism' would also match. More critically, a claim like", "fix": "Replace the word-boundary check with a proper regex word boundary: use /\\b/ instead of manual char testing. Example: change the indexOf + manual boundary check to a regex like `new RegExp('\\\\b' + escapeRegex(cue) + '\\\\b', 'i')` and test with `test(lowered)` instead of indexOf. This ensures true word boundaries regardless of surrounding punctuation."}, {"s": "medium", "c": "calibration", "loc": "lib/moa/agents/indra.ts:276", "p": "The confidence signal is set to topBelief directly (line 276: `confidence: topBelief`), which is the epistemic belief that a single mechanism statement is correct \u2014 NOT a confidence that the agent's CONTRIBUTION to the verdict is sound. For a non-mechanistic claim (gated at 0.15), the agent still returns confidence = topBelief from assembled statements. This creates miscalibration: a low-gate (0.1", "fix": "Decouple confidence from belief. For enrichers like indra, confidence should reflect the RICHNESS and CORROBORATION of the assembled findings. Use a metric like: confidence = (number of grounded statements / (1 + number of input sources)) clamped to [0, 1], OR confidence = mean(belief of all statements). This way, a low gate on a non-mechanistic claim correctly reflects 'we're uncertain this is th"}, {"s": "medium", "c": "composition", "loc": "lib/moa/agents/indra.ts:188", "p": "The consumes declaration lists ['entities'] but the agent never validates that the entities artifact actually CONTAINS linked entities (with non-null curie). The curieIndexFromEntities function filters out entries where curie is null or empty (line 128), so if scispaCy produces only unlinked mentions, the index will be empty. The agent then happily produces mechanisms WITHOUT enriching the partici", "fix": "Either (1) strengthen the consumption: read entities as a soft dependency and explicitly count how many extracted participants match (case-insensitive) entities from the blackboard, then adjust confidence by the match rate; or (2) clarify the composition contract: document that indra consumes entities only for CURIE tagging, not for validation, and remove the declaration if CURIEs are optional. Cu"}, {"s": "medium", "c": "robustness", "loc": "lib/moa/agents/indra.ts:226", "p": "The buildContextText function (line 110-119) slices the concatenated text to MAX_TEXT_CHARS (line 118: `.slice(0, MAX_TEXT_CHARS)`). This truncation happens AFTER joining with '\\n\\n' separators. If the join creates text of 25kb and we slice to 20kb, we may split a source body mid-sentence or even mid-word. The grounding engine then tries to locate spans verbatim in this truncated text. If Claude p", "fix": "Truncate BEFORE joining, or truncate at a sentence boundary. Option A: Iterate through sources and accumulate text in a list, checking the accumulated byte length before appending each source; stop when you'd exceed MAX_TEXT_CHARS. Option B: After joining, find the last newline within MAX_TEXT_CHARS and truncate there, ensuring we don't split a source body. Log the truncation in the detail trace s"}, {"s": "medium", "c": "robustness", "loc": "lib/moa/agents/indra.ts:226-227", "p": "The agent calls `assembleMechanisms({ text: contextText }, null)` with pool=null (line 226), which tells the engine to skip KG persistence but still run the full EXTRACT \u2192 GROUND \u2192 ASSEMBLE \u2192 SCORE pipeline. The engine's grounding step (in lib/mechanism/assemble.ts:113-131) drops candidates that cannot be located verbatim. However, the agent assumes every statement in result.statements was success", "fix": "After building groundedSpans, validate that the count of non-null spans roughly matches the statement count. If > 10% of spans are null, log a warning in detail or lower confidence. Alternatively, ensure that every produced mechanism has its span grounded: if spanFromStatement returns null, skip that statement instead of including it with null span."}]}, {"file": "lib/moa/agents/pytrials.ts", "issues": [{"s": "high", "c": "composition", "loc": "lib/moa/agents/pytrials.ts:1-10 (docstring) + lib/moa/types.ts:64", "p": "Agent declares PRODUCES design_priors (line 281) and the docstring (line 8) explicitly states 'downstream verification/aggregation agents CONSUME' it. However, no agent in the codebase declares consumes: ['design_priors'] in its contract. The artifact is produced but never read by any downstream agent, making the entire enrichment step wasted computation. This breaks the promised composition desig", "fix": "Either: (1) Wire a downstream consumer agent to read and apply design_priors to weight source confidence (preferred), or (2) Remove design_priors from produces[] and the enricher's run() to avoid wasted work."}, {"s": "medium", "c": "robustness", "loc": "lib/moa/agents/pytrials.ts:155", "p": "Regex pattern /\\bphase\\s*(1|2|3|4|i{1,3}|iv)\\b/gi uses a word boundary \\b after the phase number, which fails to match phase modifiers like IIIa, IIIb, IIa, IIb (common in trial publications). The captured group (1|2|3|4|i{1,3}|iv) stops at the letter, and the word boundary check fails because 'b' is a word character. As a result, Phase IIIb trials are not detected by the phase probe, causing infe", "fix": "Change line 155 from:\n const PHASE_MENTION = /\\bphase\\s*(1|2|3|4|i{1,3}|iv)\\b/gi;\nTo:\n const PHASE_MENTION = /\\bphase\\s*(1|2|3|4|i{1,3}|iv)(?![a-z])/gi;\nOr use negative lookahead to allow modifiers: /\\bphase\\s*(1|2|3|4|i{1,3}|iv)[a-z]?\\b/gi"}, {"s": "medium", "c": "composition", "loc": "lib/moa/agents/pytrials.ts:282-283", "p": "Agent declares consumes: [] as const (line 283), so the scheduler places it in Layer 0 (root layer). However, downstream agents that should consume design_priors cannot declare the dependency because design_priors has no safe semantics for composition yet (no consumer exists). This creates a staging gap: the composition DAG doesn't enforce ordering between pytrials and its (missing) consumers.", "fix": "Once a downstream consumer is wired (see first issue), ensure it declares consumes: ['design_priors'] so the scheduler enforces the dependency and places pytrials in an earlier layer."}]}, {"file": "lib/moa/agents/autoloop.ts", "issues": [{"s": "high", "c": "wrong_verdict", "loc": "lib/moa/agents/autoloop.ts:123-125", "p": "AutoLoop signals 'insufficient' (line 124) when evidence is inadequate, but the aggregate function (aggregate.ts lines 50, 74-80) only counts votes in VOTES={supports, refutes, mixed}. 'insufficient' is NOT a voting signal, so AutoLoop never participates in the verdict tally. This creates a composition gap: the MoA can return 'supported' (verdict, high trust ~70+) even when AutoLoop explicitly say", "fix": "Either: (A) Change aggregate to treat 'insufficient' as a downweight multiplier on all votes (architectural change, high effort), or (B) Change AutoLoop to vote 'mixed' instead of 'insufficient' to dilute high-agreement verdicts when evidence is inadequate (semantic shift, moderate effort), or (C) Document that AutoLoop cannot veto and accept the system will return wrong verdicts when other agents"}, {"s": "medium", "c": "robustness", "loc": "lib/moa/agents/autoloop.ts:113-114", "p": "Any fractional sufficiency.k is truncated toward zero (Math.trunc). If upstream reports k=2.9 as a weighted count (intentionally between 2 and 3), AutoLoop treats it as 2 studies. The gate then fails the enoughStudies criterion (2 < 3), voting insufficient. But the truncation is silent\u2014the detail.consumedSufficiency shows k=2.9, but detail.round shows k=2, creating inconsistency. The system over-p", "fix": "Either: (A) Change line 113 to Math.round(sufficiency.k) to round to nearest integer (more forgiving, can round 2.5 up to 3), or (B) Use Math.ceil(sufficiency.k) to always round up (most forgiving, treats 2.1 as 3), or (C) Add a field to detail documenting the truncation: detail.truncationNote: 'studies count truncated from ${sufficiency.k} to ${round.k}' so downstream understands the discrepancy."}, {"s": "medium", "c": "missed_capability", "loc": "lib/moa/agents/autoloop.ts:98-102", "p": "openContradictionsFrom returns only 1 or 0 (line 77, CONTRADICTION_PRESENT constant=1), never counting the actual magnitude of disagreement. A 50-50 split (5 benefit vs 5 harm) is treated identically to a 1-1 split. The severity of disagreement is lost. A 50-50 contested claim might reasonably warrant 'stop with mixed verdict' rather than 'vote insufficient and demand more evidence.' The gate (evi", "fix": "Either: (A) Return a true contradiction count: openContradictions = benefit > 0 && harm > 0 ? Math.abs(benefit - harm) : 0 (counts severity), then adjust the gate threshold (MIN_CONTRADICTIONS) to allow small disagreement, or (B) Add a detail field for directional balance: detail.contradictionSeverity: { disagreementRatio: harm/(benefit+harm), studyCount: effects.length } so upstream/UI can see th"}, {"s": "medium", "c": "missed_capability", "loc": "lib/moa/agents/autoloop.ts:88-93", "p": "The contradiction detection ignores null-effect saturation. If 90% of effects show no directionality (point=1.0), a 6-4 split on the remaining 10% is a weak signal. But countDirections(effects) treats this the same as a 6-4 split in a pool of 10 directional studies. A 1-1 contradiction out of 2 studies demands resolution; a 1-1 contradiction out of 100 studies should be less concerning. The gate d", "fix": "Either: (A) Add a directionality check: directional = benefit + harm; saturation = directional / effects.length; only flag contradiction if saturation >= MIN_SATURATION (e.g., 0.3) AND contradiction > 0, or (B) Weight the contradiction: openContradictions = (benefit > 0 && harm > 0) * (1 - Math.abs(benefit - harm) / (benefit + harm)) to reduce severity when one side dominates, or (C) Add a detail "}]}, {"file": "lib/moa/agents/valsci.ts", "issues": [{"s": "medium", "c": "calibration", "loc": "lib/moa/agents/valsci.ts:171-182", "p": "The agent assigns confidence=0.3 to all 'unattributed_conflict' outcomes regardless of how sparse the design-feature evidence is. A contradiction attributed to zero design features should have substantially lower confidence than one where both sides report features on multiple dimensions but disagree. The hard-coded 0.3 does not scale with the sparsity of supporting evidence.", "fix": "Compute confidence dynamically for 'unattributed_conflict': scale 0.3 by a measure of feature coverage. For example: confidence = 0.3 * (mean_feature_count / max_possible_features), so that two sides with zero design features together get confidence much lower than 0.3 (e.g., 0.05), while two sides with rich feature coverage get closer to the 0.3 floor."}, {"s": "medium", "c": "composition", "loc": "lib/moa/agents/valsci.ts:312 (consumes declaration) vs. 369-385 (run implementation)", "p": "The agent declares 'consumes: [\"source_labels\", \"entities\"]' but the consumed source_labels never affect the vote, confidence, or produced contested artifact. The agent partitions sources using only Valsci's internal signed support scores (sideForSupport), not the MiniCheck labels. The labels are read on line 336 and extracted on line 347 but only used for the summary trace (line 393-395), not for", "fix": "Remove 'source_labels' from the consumes declaration on line 312, since the agent does not actually depend on its contents for voting. Alternatively, if the design intent is to partition sides based on MiniCheck's labels rather than Valsci's internal scores, rewrite the partition logic in resolveContradiction to accept a pre-assigned side for each source, so the agent actually consumes and uses th"}, {"s": "medium", "c": "composition", "loc": "lib/moa/agents/valsci.ts:336-345", "p": "Valsci declares consumes: ['source_labels', 'entities']. The run method checks if labels exist and are non-empty but does NOT verify that labels actually span two sides (SUPPORTS and REFUTES). If MiniCheck labelled all sources as NEI, Valsci skips honestly. However, if the atlas somehow finds a contested result despite zero MiniCheck-side-labels (labelledStraddle=false), the published contested ar", "fix": "In run() after line 352, add a guard: if (!labelledStraddle && no contradiction found in atlas) skip. Ensure contested artifact aligns with upstream composition."}]}, {"file": "lib/paperqa/sourceQuality.ts", "issues": [{"s": "medium", "c": "missed_capability", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/paperqa/sourceQuality.ts:84-88", "p": "asNonNegInt() accepts any finite number and truncates it, treating negative years as 0 with no validation. A source with year: 999999 is accepted and treated identically to a modern paper. is_preprint omitted (null) is treated as false, assuming the source is peer-reviewed, so a real preprint without explicit metadata would be mis-tiered to Tier B instead of Tier C.", "fix": "Add year validation: reject years outside [1800, currentYear+1] by treating them as null (unknown). For is_preprint: document that missing or null is treated as false, or implement an 'unknown' tier that conservatively assumes unreviewed status."}]}, {"file": "lib/moa/agents/iterative.ts", "issues": [{"s": "medium", "c": "composition", "loc": "lib/moa/agents/iterative.ts:174", "p": "Agent declares consumes:['effect_sizes'] (line 209) and the header comment (lines 8-15) states it 'COMPOSES on the upstream effect_sizes artifact' to strengthen the study-count signal. However, buildRound() (lines 161-176) passes the `effects` parameter only to pooledStudyProxy() for deduplication by sourceId, never extracting the point estimates to detect directional contradictions. Line 174 hard", "fix": "Extract directional contradictions from the consumed effect_sizes in buildRound(), similar to autoloop's openContradictionsFrom() logic (autoloop.ts:98-102). Count benefit/harm point estimates (point<1 vs point>1) and set openContradictions=(benefitCount>0 && harmCount>0)?1:0. This makes iterative's contradiction detection compositionally sound and prevents confidence miscalibration when contradic"}, {"s": "medium", "c": "calibration", "loc": "lib/moa/agents/iterative.ts:250-251", "p": "When effect_sizes exist with mixed directions (one beneficial, one harmful), the confidence is calculated as passed/4. With openContradictions hardcoded to 0, the contradictionsResolved criterion always passes, inflating passed from 1/4 to 2/4 (confidence 0.5 instead of 0.25). In aggregate.ts, this translates to weight = 0.5 * 0.5 * 0.7 = 0.175 instead of 0.5 * 0.25 * 0.7 = 0.0875. While both yiel", "fix": "Implement the contradiction detection fix above (Issue #1). Once openContradictions is correctly derived from effect_sizes directions, confidence will naturally fall when contradictions fail the criterion."}]}, {"file": "lib/entities/schemas.ts", "issues": [{"s": "medium", "c": "robustness", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/entities/schemas.ts:88-102 (LinkedEntitySchema)", "p": "MISSING VALIDATION: start and end offsets lack a constraint that start < end (or start <= end for zero-length). While locateSpan (lib/grounding.ts) always returns valid offsets, the NER engine could in theory (or via test mocks) produce invalid LinkedEntity objects. The Zod schema should enforce invariants.", "fix": "Add a .refine() constraint to LinkedEntitySchema: `.refine(obj => obj.start <= obj.end, { message: 'start must be <= end' })` \u2014 or stricter, `obj.start < obj.end` if zero-length spans are forbidden."}]}, {"file": "lib/entities/ner.ts", "issues": [{"s": "medium", "c": "calibration", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/entities/ner.ts:276-287 (overlapScore)", "p": "WEAK OVERLAP SCORE LOGIC: The overlapScore metric is token-based and symmetric-ish, but it does NOT penalize OMITTED tokens in the mention. 'type 2 diabetes' matches ALL its tokens in the alias, so it scores high, even though it's dropping a key modifier. This is a classic DISTORTION CLASS: the mention is narrower than the concept. In medical linking, this is dangerous \u2014 a treatment for 'type 2 di", "fix": "Modify overlapScore to penalize short mentions: e.g., if mTokens.length < aTokens.size, apply a penalty factor (e.g., * (mTokens.length / aTokens.size)). OR: only link if aliasLength / mentionLength < 1.5 (alias is not too much longer). OR: use a stricter threshold (0.8+) for fuzzy links. The intent: prefer exact matches; fuzzy links should require mention and alias to be close in size."}, {"s": "medium", "c": "robustness", "loc": "/Users/arhansubasi/Downloads/papertrail/lib/entities/ner.ts:502-503 (recognizeEntities)", "p": "ERROR SWALLOWING: The NER pipeline catches all extraction errors and degrades to empty, but it does not SURFACE the error to the agent trace. The scispacy agent's try-catch (lines 144-220) WILL catch errors and emit erroredContribution(), but if the only error is in extractMentions, it gets swallowed before reaching the agent layer. This violates observability: a malformed or failing response is m", "fix": "In recognizeEntities(), distinguish between 'extraction failed' and 'extraction succeeded but found no mentions'. Catch the error separately and return a special result shape (e.g., { entities: [], groundingDroppedCount: 0, linkedCount: 0, extractionFailed: true }) or throw a labeled error. OR: let the error bubble and let the agent handle it. Current behavior: `const mentions = await deps.extract"}]}, {"file": "lib/moa/agents/autoreview.ts", "issues": [{"s": "medium", "c": "robustness", "loc": "lib/moa/agents/autoreview.ts:230-248 (connectiveSummary function)", "p": "The prose system prompt (line 185-190) instructs Claude to not invent evidence, not take a verdict, and not add numbers not given. However, the returned prose is not validated against these constraints. Claude could hallucinate verdict language ('strongly suggests', 'indicates', 'conclusive'), causation claims, or implicit quantification that violates the neutral-prose contract. While autoreview v", "fix": "Add a validation function that checks the returned prose doesn't contain verdict language (supports, refutes, conclusive, inconclusive, suggests effect, indicates cause, etc.). Reject prose and fall back to baseSummary if validation fails. Example forbidden tokens: 'support', 'refute', 'suggest', 'indicate', 'conclude', 'prove', 'demonstrate' in claim-verdict context."}, {"s": "medium", "c": "calibration", "loc": "lib/moa/agents/autoreview.ts:314-315 (coverage calculation)", "p": "Coverage = 3/8 = 0.375 confidence. The metric penalizes ungroundable labels equally with successfully grounded ones, even though they may fail through no fault of the source text. A review that grounds 3 distinct sources gets conf=0.375, same as a review that grounds 1.5 sources if 4 others are in the pool. This makes the confidence poorly calibrated relative to the actual breadth of sources cited", "fix": "Consider recalibrating coverage as: (distinctSources.size / max(distinctSources.size, 2)) to better reflect that we have a real, useful review once we hit 2+ sources. Alternatively, keep current metric but document that it's intentionally conservative \u2014 measuring 'completeness relative to all labeled sources' rather than 'utility of selected citations'."}]}, {"file": "lib/moa/agents/pyalex.ts", "issues": [{"s": "medium", "c": "calibration", "loc": "lib/moa/agents/pyalex.ts, line 92-96", "p": "When addressableCount returns 0, the summary line is 'needs OpenAlex ingestion context \u2014 run via Living Evidence.' This is an incomplete message that doesn't explain WHAT was checked. The agent correctly skips (ran=false, signal=insufficient, confidence=0), but a user or auditor reading the trace cannot tell whether: (a) the sources had no DOIs or OpenAlex ids at all, or (b) the addressable-count ", "fix": "Include addressable count in the summary even when 0: e.g., `const summary = addressable > 0 ? (...) : \"No sources with a resolvable DOI or OpenAlex id found. Citation velocity requires OpenAlex ingestion context \u2014 run via Living Evidence.\";` This way the trace is transparent about what was checked."}]}];
|
|
|
|
const SCHEMA = {
|
|
type: 'object', additionalProperties: false,
|
|
required: ['file', 'applied'],
|
|
properties: {
|
|
file: { type: 'string' },
|
|
applied: { type: 'array', items: { type: 'string' } },
|
|
skipped: { type: 'array', items: { type: 'string' } },
|
|
notes: { type: 'string' },
|
|
},
|
|
}
|
|
|
|
phase('Fix')
|
|
const built = (await parallel(
|
|
FILES.map((g) => () =>
|
|
agent(
|
|
[
|
|
'Apply these audited fixes to ONE file: ' + g.file + '.',
|
|
'',
|
|
CONTRACT,
|
|
'',
|
|
'FIXES (apply each — the problem, then the suggested fix):',
|
|
g.issues
|
|
.map((it, idx) =>
|
|
(idx + 1) + '. [' + it.s + '/' + it.c + '] near ' + it.loc + '\n PROBLEM: ' + it.p + '\n FIX: ' + it.fix
|
|
)
|
|
.join('\n\n'),
|
|
'',
|
|
'READ ' + g.file + ' fully first, plus lib/moa/types.ts and lib/moa/aggregate.ts for how the vote is weighted.',
|
|
'Edit ONLY ' + g.file + '. Return which fixes you applied vs skipped (with why).',
|
|
].join('\n'),
|
|
{ label: 'fix:' + g.file.split('/').pop(), phase: 'Fix', schema: SCHEMA }
|
|
)
|
|
)
|
|
)).filter(Boolean)
|
|
|
|
phase('Verify')
|
|
const review = await agent(
|
|
[
|
|
'Adversarially review the PaperTrail MoA fix round for BUILD SAFETY and the MOAT. READ lib/moa/types.ts,',
|
|
'lib/moa/aggregate.ts, lib/moa/registry.ts, lib/moa/orchestrate.ts, every file under lib/moa/agents/, and',
|
|
'lib/verify/discrepancy.ts. Verify each: default export is still a valid MoaAgent (id, name, category,',
|
|
'description, produces, consumes, gate, run); no public export name or signature changed; NO LLM entered any',
|
|
'numeric or verdict-scoring path; no obvious TypeScript build risk (bad import, any-usage, wrong return type,',
|
|
'missing await, undefined variable). Report only concrete BLOCKING issues with file + exact fix.',
|
|
].join('\n'),
|
|
{
|
|
label: 'verify:fixes', phase: 'Verify', agentType: 'Explore',
|
|
schema: {
|
|
type: 'object', additionalProperties: false, required: ['issues'],
|
|
properties: {
|
|
issues: {
|
|
type: 'array',
|
|
items: {
|
|
type: 'object', additionalProperties: false,
|
|
required: ['severity', 'file', 'problem', 'fix'],
|
|
properties: {
|
|
severity: { type: 'string', enum: ['high', 'medium', 'low'] },
|
|
file: { type: 'string' }, problem: { type: 'string' }, fix: { type: 'string' },
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
}
|
|
)
|
|
|
|
log('MoA fix round: ' + built.length + ' files fixed; ' + (review.issues ? review.issues.length : 0) + ' blocking issues.')
|
|
return { built, review }
|