From 7bec3ed03f5341efe99902ec4163298f68dd5e16 Mon Sep 17 00:00:00 2001 From: Xika Date: Tue, 12 May 2026 03:47:05 +0000 Subject: [PATCH 1/3] feat(research): BIT-3602 wire orchestrator for multi-source fact verification MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add src/research/index.js as the single entry point that composes the existing source modules already on main (Google Fact Check, ClaimBuster, cross-reference) plus extractClaims and aggregateVerificationResults into one verifyArticle(article) call. Behaviour: - Honours researchConfig() — short-circuits with status:'disabled' when RESEARCH_ENABLED is false (opt-in feature flag, no default network calls). - Returns status:'skipped' for empty articles. - Queries the three sources in parallel via Promise.all. - Wraps each source in safeQuery so a thrown error is contained as status:'error', logged, and excluded from the aggregate — partial outage of one source never blocks the publish pipeline. - Result shape: { status, overall_confidence, sources, claims } matching the surface aggregateVerificationResults already produces. Tests: 5 new cases in src/research/index.test.js cover disabled, empty article, three-source aggregation (matches aggregator weighted contract: 0.50/0.35/0.15 → 72), partial-outage containment, and all-skipped → status:'skipped'. Source modules and their tests (aggregator, claims, config, sources/*) are not touched: prior PRs already merged refined versions of those files to main; this change only adds the missing orchestrator that wires them together. Paperclip-Issue: BIT-3602 Paperclip-Run: 31991727-135e-4c6b-ba11-982068f121de --- src/research/index.js | 68 +++++++++++++++++++++++++ src/research/index.test.js | 100 +++++++++++++++++++++++++++++++++++++ 2 files changed, 168 insertions(+) create mode 100644 src/research/index.js create mode 100644 src/research/index.test.js diff --git a/src/research/index.js b/src/research/index.js new file mode 100644 index 0000000..e6d4a88 --- /dev/null +++ b/src/research/index.js @@ -0,0 +1,68 @@ +'use strict'; + +const logger = require('../logger'); +const { researchConfig } = require('./config'); +const { extractClaims } = require('./claims'); +const { queryGoogleFactCheck } = require('./sources/google-factcheck'); +const { queryClaimBuster } = require('./sources/claimcheck'); +const { queryCrossReference } = require('./sources/cross-reference'); +const { aggregateVerificationResults } = require('./aggregator'); + +/** + * Verify an article against multiple fact-checking sources and return a + * single verification report aggregating per-source confidence. + * + * Sources query in parallel; any source that throws is recorded as + * `status:'error'` and excluded from the aggregate, so a partial outage + * never blocks the publish pipeline. + * + * @param {{ title?: string, subtitle?: string, body?: string, sources?: Array }} article + * @param {{ enabled?: boolean, timeoutMs?: number, claimsMax?: number, + * googleApiKey?: string, claimBusterApiKey?: string }} [overrides] + * Optional overrides; `researchConfig()` is used when absent. + * @returns {Promise<{ + * status: 'disabled' | 'verified' | 'unverified' | 'disputed' | 'skipped', + * overall_confidence: number | null, + * sources: Array, + * claims: string[] + * }>} + */ +async function verifyArticle(article, overrides) { + const cfg = overrides || researchConfig(); + + if (!cfg.enabled) { + return { status: 'disabled', overall_confidence: null, sources: [], claims: [] }; + } + if (!article || (!article.title && !article.body)) { + return { status: 'skipped', overall_confidence: null, sources: [], claims: [] }; + } + + const claims = extractClaims(article, cfg.claimsMax); + + const queries = [ + safeQuery('google_factcheck', () => queryGoogleFactCheck(claims, cfg.googleApiKey, cfg.timeoutMs)), + safeQuery('claimcheck', () => queryClaimBuster(claims, cfg.claimBusterApiKey, cfg.timeoutMs)), + safeQuery('cross_reference', () => queryCrossReference(article, cfg.timeoutMs)) + ]; + + const sources = await Promise.all(queries); + const aggregate = aggregateVerificationResults(sources); + + return { + status: aggregate.overall_status, + overall_confidence: aggregate.overall_confidence, + sources, + claims + }; +} + +async function safeQuery(name, fn) { + try { + return await fn(); + } catch (err) { + logger.warn(`research source ${name} failed: ${err.message}`); + return { source_name: name, status: 'error', confidence: null, error: err.message, results: [] }; + } +} + +module.exports = { verifyArticle }; diff --git a/src/research/index.test.js b/src/research/index.test.js new file mode 100644 index 0000000..16a481b --- /dev/null +++ b/src/research/index.test.js @@ -0,0 +1,100 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +// Stub source modules before loading the orchestrator so verifyArticle +// composes deterministic results without hitting the network. +const googleMod = require('./sources/google-factcheck'); +const claimMod = require('./sources/claimcheck'); +const xrefMod = require('./sources/cross-reference'); + +const _origGoogle = googleMod.queryGoogleFactCheck; +const _origClaim = claimMod.queryClaimBuster; +const _origXref = xrefMod.queryCrossReference; + +let _googleStub = null; +let _claimStub = null; +let _xrefStub = null; + +googleMod.queryGoogleFactCheck = async (...a) => (_googleStub ? _googleStub(...a) : _origGoogle(...a)); +claimMod.queryClaimBuster = async (...a) => (_claimStub ? _claimStub(...a) : _origClaim(...a)); +xrefMod.queryCrossReference = async (...a) => (_xrefStub ? _xrefStub(...a) : _origXref(...a)); + +delete require.cache[require.resolve('./index')]; +const { verifyArticle } = require('./index'); + +function reset() { + _googleStub = null; + _claimStub = null; + _xrefStub = null; +} + +test('verifyArticle — disabled config short-circuits without calling sources', async () => { + reset(); + let called = false; + _googleStub = async () => { called = true; return { source_name: 'google_factcheck', status: 'found', confidence: 90 }; }; + const r = await verifyArticle({ title: 'Anything', body: 'x'.repeat(50) }, + { enabled: false }); + assert.equal(r.status, 'disabled'); + assert.equal(r.overall_confidence, null); + assert.deepEqual(r.sources, []); + assert.equal(called, false); +}); + +test('verifyArticle — empty article returns skipped', async () => { + reset(); + const r = await verifyArticle({}, { enabled: true, claimsMax: 3, timeoutMs: 1000 }); + assert.equal(r.status, 'skipped'); +}); + +test('verifyArticle — aggregates three found sources into a verified report', async () => { + reset(); + _googleStub = async () => ({ source_name: 'google_factcheck', status: 'found', confidence: 80 }); + _claimStub = async () => ({ source_name: 'claimcheck', status: 'found', confidence: 70 }); + _xrefStub = async () => ({ source_name: 'cross_reference', status: 'found', confidence: 60 }); + + const r = await verifyArticle( + { title: 'Real article with at least twenty chars to count', body: 'Statistics showed 42% growth in Q1.' }, + { enabled: true, claimsMax: 3, timeoutMs: 1000, googleApiKey: 'k', claimBusterApiKey: 'k' } + ); + + assert.equal(r.status, 'verified'); + assert.equal(r.overall_confidence, 72); // weighted avg matches aggregator contract + assert.equal(r.sources.length, 3); + assert.ok(Array.isArray(r.claims)); +}); + +test('verifyArticle — source throw is contained as status:error and excluded from aggregate', async () => { + reset(); + _googleStub = async () => { throw new Error('boom'); }; + _claimStub = async () => ({ source_name: 'claimcheck', status: 'skipped', confidence: null }); + _xrefStub = async () => ({ source_name: 'cross_reference', status: 'found', confidence: 75 }); + + const r = await verifyArticle( + { title: 'Article that survives a partial outage cleanly', body: 'Body text long enough to count.' }, + { enabled: true, claimsMax: 3, timeoutMs: 1000, googleApiKey: 'k', claimBusterApiKey: 'k' } + ); + + // cross_reference at 75 alone — verified + assert.equal(r.status, 'verified'); + assert.equal(r.overall_confidence, 75); + const google = r.sources.find((s) => s.source_name === 'google_factcheck'); + assert.equal(google.status, 'error'); + assert.equal(google.error, 'boom'); +}); + +test('verifyArticle — disabled when sources skipped (no API keys) and xref returns not_found', async () => { + reset(); + _googleStub = async () => ({ source_name: 'google_factcheck', status: 'skipped', confidence: null }); + _claimStub = async () => ({ source_name: 'claimcheck', status: 'skipped', confidence: null }); + _xrefStub = async () => ({ source_name: 'cross_reference', status: 'not_found', confidence: null }); + + const r = await verifyArticle( + { title: 'Article without third-party API coverage at all', body: 'Body text.' }, + { enabled: true, claimsMax: 3, timeoutMs: 1000 } + ); + + assert.equal(r.status, 'skipped'); + assert.equal(r.overall_confidence, null); +}); -- 2.47.3 From e77fc46a7005ccbb8475b6f2ee40db22da8dca2d Mon Sep 17 00:00:00 2001 From: Xika Date: Tue, 12 May 2026 03:55:01 +0000 Subject: [PATCH 2/3] BIT-3602: Persist verification_report and editorial verification column MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Run verifyArticle before appending article JSONL via persistGeneratedArticle (index, CLI write/listen). Article rows store a bounded snapshot; /ui dashboard shows Verificação with per-source details in a disclosure. Paperclip-Issue: BIT-21733 Paperclip-Run: 87279bca-68e7-410b-bdc5-ff25cc08e671 --- src/cli/listen.js | 20 +-- src/cli/write.js | 20 +-- src/http/ui-handlers.js | 19 ++- src/http/ui-pages.js | 19 ++- src/index.js | 64 +-------- src/pipeline/persist-generated-article.js | 90 ++++++++++++ .../persist-generated-article.test.js | 70 +++++++++ src/store/article-log.js | 9 +- src/store/article-log.test.js | 14 ++ src/store/verification-report.js | 133 ++++++++++++++++++ src/store/verification-report.test.js | 63 +++++++++ 11 files changed, 416 insertions(+), 105 deletions(-) create mode 100644 src/pipeline/persist-generated-article.js create mode 100644 src/pipeline/persist-generated-article.test.js create mode 100644 src/store/verification-report.js create mode 100644 src/store/verification-report.test.js diff --git a/src/cli/listen.js b/src/cli/listen.js index 0272b07..418087a 100644 --- a/src/cli/listen.js +++ b/src/cli/listen.js @@ -10,23 +10,7 @@ const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadPublishHours } const { resolveWritingParams } = require('../config/writing-style'); const { setRssListenerActive } = require('../runtime/listen-state'); const { resolveAutoCronExpression } = require('../config/listen-defaults'); -const { appendArticleRecord } = require('../store/article-log'); - -function safeAppendArticle(article, site, mode, wp_link) { - try { - appendArticleRecord({ - title: article.title, - subtitle: article.subtitle, - slug: article.slug, - summary: article.summary, - wp_link: wp_link || null, - site_name: site?.name || 'default', - mode - }); - } catch (err) { - logger.warn(`article log append failed: ${err.message}`); - } -} +const { persistGeneratedArticle } = require('../pipeline/persist-generated-article'); async function runAutoMode() { logger.info('Auto mode starting — RSS listener active'); @@ -81,7 +65,7 @@ async function runAutoMode() { } else { logger.warn('No WP config — article saved to logs only'); } - safeAppendArticle(article, site, 'listen', wp_link); + await persistGeneratedArticle(article, site, 'listen', wp_link, voice); }); setRssListenerActive(true); } catch (err) { diff --git a/src/cli/write.js b/src/cli/write.js index 73bf4be..cc9d5ac 100644 --- a/src/cli/write.js +++ b/src/cli/write.js @@ -6,23 +6,7 @@ const { generateArticle } = require('../writer/ai'); const { publishToWordPress } = require('../publisher/wordpress'); const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadPublishHours } = require('../config/loader'); const { resolveWritingParams } = require('../config/writing-style'); -const { appendArticleRecord } = require('../store/article-log'); - -function safeAppendArticle(article, site, mode, wp_link) { - try { - appendArticleRecord({ - title: article.title, - subtitle: article.subtitle, - slug: article.slug, - summary: article.summary, - wp_link: wp_link || null, - site_name: site?.name || 'default', - mode - }); - } catch (err) { - logger.warn(`article log append failed: ${err.message}`); - } -} +const { persistGeneratedArticle } = require('../pipeline/persist-generated-article'); async function runManualWrite(topic) { logger.info(`Manual write mode — topic: "${topic}"`); @@ -73,7 +57,7 @@ async function runManualWrite(topic) { logger.warn('No WordPress config found — article not published (set WP_URL, WP_USER, WP_PASSWORD)'); } - safeAppendArticle(article, site, 'write', wp_link); + await persistGeneratedArticle(article, site, 'write', wp_link, voice); return article; } diff --git a/src/http/ui-handlers.js b/src/http/ui-handlers.js index 4d277b3..d319819 100644 --- a/src/http/ui-handlers.js +++ b/src/http/ui-handlers.js @@ -17,6 +17,7 @@ const { } = require('../config/writing-style'); const { resolveWpTransport } = require('../publisher/wp-transport'); const { readLastArticles, updateArticleStatus, updateArticleMetadata, articleRowId } = require('../store/article-log'); +const { verificationReportCellHtml } = require('../store/verification-report'); const { parseDomain } = require('../util/domain'); const { getArticleEngagement, getCategoryBenchmarks, getTopArticles, exportAnalyticsCSV } = require('./analytics-api'); const { escapeHtml, getAdminToken, adminOk } = require('./ui-auth'); @@ -238,6 +239,17 @@ function layout(title, innerHtml, theme) { .badge-pending { background: #e5e7eb; color: #374151; } .badge-approved { background: #dcfce7; color: #166534; } .badge-rejected { background: #fee2e2; color: #991b1b; } + .badge-verify-verified { background: #dcfce7; color: #166534; } + .badge-verify-unverified { background: #fef9c3; color: #854d0e; } + .badge-verify-disputed { background: #fee2e2; color: #991b1b; } + .badge-verify-muted { background: #e5e7eb; color: #4b5563; } + .verify-cell { font-size: 0.82rem; } + .verify-cell .vconf { color: var(--muted); font-weight: 500; } + .verify-details { margin-top: 0.35rem; } + .verify-details summary { cursor: pointer; color: var(--link); font-size: 0.8rem; } + .verify-sub { margin: 0.35rem 0 0.15rem; font-size: 0.78rem; } + .verify-list { margin: 0 0 0.35rem 1rem; padding: 0; font-size: 0.78rem; } + .muted-cell { color: var(--muted); } .row-actions { white-space: nowrap; } .row-actions .btn { padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.35rem; } label { display: block; margin: 0.75rem 0 0.25rem; font-size: 0.9rem; font-weight: 500; } @@ -358,15 +370,16 @@ function pageDashboard(theme, flash) { }).join(', ') + (a.sources.length > 3 ? ` +${a.sources.length - 3}` : '') : '—'; const tagsHtml = a.tags && a.tags.length > 0 ? a.tags.map(t => `${escapeHtml(t)}`).join('') : '—'; + const verifyHtml = verificationReportCellHtml(a, escapeHtml); const editBtn = tokenSet ? `` : ''; - return `${checkbox}${escapeHtml(a.at || '')}${escapeHtml(a.title || '')}${escapeHtml(a.site_name || '—')}${sourcesHtml}${tagsHtml}${ + return `${checkbox}${escapeHtml(a.at || '')}${escapeHtml(a.title || '')}${escapeHtml(a.site_name || '—')}${sourcesHtml}${tagsHtml}${verifyHtml}${ a.wp_link ? `WP` : '—' }${badge}${actions}${editBtn ? ' ' + editBtn : ''}`; }) .join(''); if (!rows) { rows = - 'Ainda não há artigos gerados registados (corre write ou listen).'; + 'Ainda não há artigos gerados registados (corre write ou listen).'; } const flashHtml = flash ? '' @@ -431,7 +444,7 @@ ${flashHtml} ${tokenBlock}

Listagem dos títulos guardados em data/article-index.jsonl (últimos 80).

${bulkOpsSection} -${rows}
${selectAllCheckbox}DataTítuloSiteFontesTagsWPEstadoAções
+${rows}
${selectAllCheckbox}DataTítuloSiteFontesTagsVerificaçãoWPEstadoAções
${editModalHtml} ${bulkTagsModalHtml}