Merge pull request 'BIT-3602: orchestrator for multi-source fact verification' (#18) from task/BIT-3602-multi-source-fact-verification into main
ai-news-writer-ci / test (push) Successful in 50s
ai-news-writer-ci / test (push) Successful in 50s
This commit was merged in pull request #18.
This commit is contained in:
commit
d31b50b846
13 files changed
+586
-105
No files matched your search
+2
-18
@@ -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) {
|
||||
|
||||
+2
-18
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+16
-3
@@ -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 => `<span class="tag-pill">${escapeHtml(t)}</span>`).join('') : '—';
|
||||
const verifyHtml = verificationReportCellHtml(a, escapeHtml);
|
||||
const editBtn = tokenSet ? `<button type="button" class="js-edit-btn edit-btn" data-rid="${escapeHtml(enc)}" data-title="${escapeHtml(a.title || '')}" data-subtitle="${escapeHtml(a.subtitle || '')}" data-slug="${escapeHtml(a.slug || '')}" data-tags="${escapeHtml((a.tags || []).join(', '))}" data-category="${escapeHtml(a.category || '')}" aria-label="Editar artigo ${escapeHtml(a.title || '')}">Editar</button>` : '';
|
||||
return `<tr><td>${checkbox}</td><td>${escapeHtml(a.at || '')}</td><td>${escapeHtml(a.title || '')}</td><td>${escapeHtml(a.site_name || '—')}</td><td>${sourcesHtml}</td><td>${tagsHtml}</td><td>${
|
||||
return `<tr><td>${checkbox}</td><td>${escapeHtml(a.at || '')}</td><td>${escapeHtml(a.title || '')}</td><td>${escapeHtml(a.site_name || '—')}</td><td>${sourcesHtml}</td><td>${tagsHtml}</td><td>${verifyHtml}</td><td>${
|
||||
a.wp_link ? `<a href="${escapeHtml(a.wp_link)}" rel="noopener">WP</a>` : '—'
|
||||
}</td><td>${badge}</td><td>${actions}${editBtn ? ' ' + editBtn : ''}</td></tr>`;
|
||||
})
|
||||
.join('');
|
||||
if (!rows) {
|
||||
rows =
|
||||
'<tr><td colspan="10">Ainda não há artigos gerados registados (corre <code>write</code> ou <code>listen</code>).</td></tr>';
|
||||
'<tr><td colspan="11">Ainda não há artigos gerados registados (corre <code>write</code> ou <code>listen</code>).</td></tr>';
|
||||
}
|
||||
const flashHtml = flash
|
||||
? '<p id="flash-message" class="' + (flash.type === 'err' ? 'err' : 'ok') + '" role="alert" aria-live="assertive">' + escapeHtml(flash.text) + '</p>'
|
||||
@@ -431,7 +444,7 @@ ${flashHtml}
|
||||
${tokenBlock}
|
||||
<p class="note">Listagem dos títulos guardados em <code>data/article-index.jsonl</code> (últimos 80).</p>
|
||||
${bulkOpsSection}
|
||||
<table><thead><tr><th>${selectAllCheckbox}</th><th>Data</th><th>Título</th><th>Site</th><th>Fontes</th><th>Tags</th><th>WP</th><th>Estado</th><th>Ações</th></tr></thead><tbody>${rows}</tbody></table>
|
||||
<table><thead><tr><th>${selectAllCheckbox}</th><th>Data</th><th>Título</th><th>Site</th><th>Fontes</th><th>Tags</th><th>Verificação</th><th>WP</th><th>Estado</th><th>Ações</th></tr></thead><tbody>${rows}</tbody></table>
|
||||
${editModalHtml}
|
||||
${bulkTagsModalHtml}
|
||||
<script>
|
||||
|
||||
+16
-3
@@ -6,6 +6,7 @@ const { escapeHtml, getAdminToken } = require('./ui-auth');
|
||||
const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadSocialConfig } = require('../config/loader');
|
||||
const { resolveWpTransport } = require('../publisher/wp-transport');
|
||||
const { readLastArticles, articleRowId } = require('../store/article-log');
|
||||
const { verificationReportCellHtml } = require('../store/verification-report');
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..', '..');
|
||||
const THEME_PATH = path.join(ROOT, 'config', 'ui-theme.json');
|
||||
@@ -91,6 +92,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(--accent); font-size: 0.8rem; text-decoration: underline; }
|
||||
.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; min-width: 44px; min-height: 44px; }
|
||||
.btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
@@ -184,14 +196,15 @@ function pageDashboard(theme, flash) {
|
||||
const actions = tokenSet
|
||||
? `<span class="row-actions"><form class="js-article-action" method="post" action="/ui/articles/${enc}/approve" style="display:inline"><input type="hidden" name="admin_token" value="" /><button type="submit" class="btn">Aprovar</button></form><form class="js-article-action" method="post" action="/ui/articles/${enc}/reject" style="display:inline"><input type="hidden" name="admin_token" value="" /><button type="submit" class="btn">Rejeitar</button></form></span>`
|
||||
: '—';
|
||||
return `<tr><td>${escapeHtml(a.at || '')}</td><td>${escapeHtml(a.title || '')}</td><td>${escapeHtml(a.site_name || '—')}</td><td>${
|
||||
const verifyHtml = verificationReportCellHtml(a, escapeHtml);
|
||||
return `<tr><td>${escapeHtml(a.at || '')}</td><td>${escapeHtml(a.title || '')}</td><td>${escapeHtml(a.site_name || '—')}</td><td>${verifyHtml}</td><td>${
|
||||
a.wp_link ? `<a href="${escapeHtml(a.wp_link)}" rel="noopener">WP</a>` : '—'
|
||||
}</td><td>${badge}</td><td>${actions}</td></tr>`;
|
||||
})
|
||||
.join('');
|
||||
if (!rows) {
|
||||
rows =
|
||||
'<tr><td colspan="6">Ainda não há artigos gerados registados (corre <code>write</code> ou <code>listen</code>).</td></tr>';
|
||||
'<tr><td colspan="7">Ainda não há artigos gerados registados (corre <code>write</code> ou <code>listen</code>).</td></tr>';
|
||||
}
|
||||
const flashHtml = flash
|
||||
? `<p class="${flash.type === 'err' ? 'err' : 'ok'}">${escapeHtml(flash.text)}</p>`
|
||||
@@ -203,7 +216,7 @@ function pageDashboard(theme, flash) {
|
||||
${flashHtml}
|
||||
${tokenBlock}
|
||||
<p class="note">Listagem simples dos títulos guardados em <code>data/article-index.jsonl</code> (últimos 80).</p>
|
||||
<table><thead><tr><th>Data</th><th>Título</th><th>Site</th><th>WP</th><th>Estado</th><th>Ações</th></tr></thead><tbody>${rows}</tbody></table>
|
||||
<table><thead><tr><th>Data</th><th>Título</th><th>Site</th><th>Verificação</th><th>WP</th><th>Estado</th><th>Ações</th></tr></thead><tbody>${rows}</tbody></table>
|
||||
<script>
|
||||
(function () {
|
||||
var tok = document.getElementById('dash_admin_token');
|
||||
|
||||
+3
-61
@@ -25,9 +25,8 @@ const { resolveWritingParams } = require('./config/writing-style');
|
||||
const { probeXQueries } = require('./crawler/x');
|
||||
const { setRssListenerActive } = require('./runtime/listen-state');
|
||||
const { resolveAutoCronExpression } = require('./config/listen-defaults');
|
||||
const { appendArticleRecord } = require('./store/article-log');
|
||||
const { persistGeneratedArticle } = require('./pipeline/persist-generated-article');
|
||||
const { notifyPipelineAlert } = require('./monitoring/pipeline-alert');
|
||||
const { scoreArticleQuality } = require('./pipeline/quality-scorer');
|
||||
const { QueueBackpressure } = require('./queue/backpressure');
|
||||
const { setQueueBackpressure } = require('./runtime/listen-state');
|
||||
const analytics = require('./analytics');
|
||||
@@ -37,63 +36,6 @@ const path = require('path');
|
||||
const LOGS_DIR = path.join(__dirname, '..', 'logs');
|
||||
if (!fs.existsSync(LOGS_DIR)) fs.mkdirSync(LOGS_DIR, { recursive: true });
|
||||
|
||||
function getQualityThresholds() {
|
||||
const minScore = parseInt(process.env.QUALITY_MIN_SCORE || '60', 10);
|
||||
const minWordCount = parseInt(process.env.QUALITY_MIN_WORD_COUNT || '300', 10);
|
||||
const maxReadabilityGrade = parseInt(process.env.QUALITY_MAX_READABILITY_GRADE || '8', 10);
|
||||
|
||||
return {
|
||||
minScore: Number.isFinite(minScore) ? minScore : 60,
|
||||
minWordCount: Number.isFinite(minWordCount) ? minWordCount : 300,
|
||||
maxReadabilityGrade: Number.isFinite(maxReadabilityGrade) ? maxReadabilityGrade : 8
|
||||
};
|
||||
}
|
||||
|
||||
function safeAppendArticle(article, site, mode, wp_link, voice = {}) {
|
||||
try {
|
||||
// Score article quality
|
||||
const thresholds = getQualityThresholds();
|
||||
const quality = scoreArticleQuality(article, {
|
||||
minWordCount: thresholds.minWordCount,
|
||||
maxReadabilityGrade: thresholds.maxReadabilityGrade
|
||||
});
|
||||
|
||||
const qualityStatus = quality.score >= thresholds.minScore ? 'approved' : 'needs_review';
|
||||
|
||||
// Record quality metrics
|
||||
metrics.recordValue('quality.score', quality.score);
|
||||
if (qualityStatus === 'needs_review') {
|
||||
metrics.incrementCounter('articles.quality_needs_review', 1);
|
||||
}
|
||||
|
||||
appendArticleRecord({
|
||||
title: article.title,
|
||||
subtitle: article.subtitle,
|
||||
slug: article.slug,
|
||||
summary: article.summary,
|
||||
wp_link: wp_link || null,
|
||||
site_name: site?.name || 'default',
|
||||
mode,
|
||||
sources: article.sources,
|
||||
quality_score: quality.score,
|
||||
quality_issues: quality.issues,
|
||||
quality_status: qualityStatus,
|
||||
writing_tone: voice.tone || null,
|
||||
audience_level: voice.audience_level || null
|
||||
});
|
||||
|
||||
if (article.dominance_warning) {
|
||||
logger.warn(`Article "${article.title}": ${article.dominance_warning}`);
|
||||
}
|
||||
|
||||
if (quality.issues.length > 0) {
|
||||
logger.info(`Quality assessment: ${quality.issues.join('; ')}`);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn(`article log append failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runManualWrite(topic) {
|
||||
logger.info(`Manual write mode — topic: "${topic}"`);
|
||||
|
||||
@@ -153,7 +95,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, voice);
|
||||
await persistGeneratedArticle(article, site, 'write', wp_link, voice);
|
||||
return article;
|
||||
}
|
||||
|
||||
@@ -451,7 +393,7 @@ async function runAutoMode() {
|
||||
} else {
|
||||
logger.warn('No WP config — article saved to logs only');
|
||||
}
|
||||
safeAppendArticle(article, site, 'listen', wp_link, voice);
|
||||
await persistGeneratedArticle(article, site, 'listen', wp_link, voice);
|
||||
} finally {
|
||||
// Always release the queue slot when done processing
|
||||
backpressure.release();
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
'use strict';
|
||||
|
||||
const logger = require('../logger');
|
||||
const { metrics } = require('../monitoring/metrics');
|
||||
const { scoreArticleQuality } = require('./quality-scorer');
|
||||
const { verifyArticle } = require('../research');
|
||||
const { appendArticleRecord } = require('../store/article-log');
|
||||
const { serializeVerificationReport } = require('../store/verification-report');
|
||||
|
||||
function getQualityThresholds() {
|
||||
const minScore = parseInt(process.env.QUALITY_MIN_SCORE || '60', 10);
|
||||
const minWordCount = parseInt(process.env.QUALITY_MIN_WORD_COUNT || '300', 10);
|
||||
const maxReadabilityGrade = parseInt(process.env.QUALITY_MAX_READABILITY_GRADE || '8', 10);
|
||||
|
||||
return {
|
||||
minScore: Number.isFinite(minScore) ? minScore : 60,
|
||||
minWordCount: Number.isFinite(minWordCount) ? minWordCount : 300,
|
||||
maxReadabilityGrade: Number.isFinite(maxReadabilityGrade) ? maxReadabilityGrade : 8
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Quality score, async multi-source verification, then append to article JSONL.
|
||||
*
|
||||
* @param {object} article
|
||||
* @param {object|null} site
|
||||
* @param {'write'|'listen'|'unknown'} mode
|
||||
* @param {string|null} wp_link
|
||||
* @param {{ tone?: string|null, audience_level?: string|null }} [voice]
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function persistGeneratedArticle(article, site, mode, wp_link, voice = {}) {
|
||||
try {
|
||||
const thresholds = getQualityThresholds();
|
||||
const quality = scoreArticleQuality(article, {
|
||||
minWordCount: thresholds.minWordCount,
|
||||
maxReadabilityGrade: thresholds.maxReadabilityGrade
|
||||
});
|
||||
|
||||
const qualityStatus = quality.score >= thresholds.minScore ? 'approved' : 'needs_review';
|
||||
|
||||
metrics.recordValue('quality.score', quality.score);
|
||||
if (qualityStatus === 'needs_review') {
|
||||
metrics.incrementCounter('articles.quality_needs_review', 1);
|
||||
}
|
||||
|
||||
let verification_report = null;
|
||||
try {
|
||||
const rawV = await verifyArticle(article);
|
||||
verification_report = serializeVerificationReport(rawV);
|
||||
} catch (vErr) {
|
||||
logger.warn(`verification orchestration failed (non-fatal): ${vErr.message}`);
|
||||
verification_report = serializeVerificationReport({
|
||||
status: 'unverified',
|
||||
overall_confidence: null,
|
||||
sources: [{ source_name: 'pipeline', status: 'error', confidence: null, error: vErr.message }],
|
||||
claims: []
|
||||
});
|
||||
}
|
||||
|
||||
appendArticleRecord({
|
||||
title: article.title,
|
||||
subtitle: article.subtitle,
|
||||
slug: article.slug,
|
||||
summary: article.summary,
|
||||
wp_link: wp_link || null,
|
||||
site_name: site?.name || 'default',
|
||||
mode,
|
||||
sources: article.sources,
|
||||
quality_score: quality.score,
|
||||
quality_issues: quality.issues,
|
||||
quality_status: qualityStatus,
|
||||
writing_tone: voice.tone || null,
|
||||
audience_level: voice.audience_level || null,
|
||||
verification_report
|
||||
});
|
||||
|
||||
if (article.dominance_warning) {
|
||||
logger.warn(`Article "${article.title}": ${article.dominance_warning}`);
|
||||
}
|
||||
|
||||
if (quality.issues.length > 0) {
|
||||
logger.info(`Quality assessment: ${quality.issues.join('; ')}`);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn(`article log append failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { persistGeneratedArticle, getQualityThresholds };
|
||||
@@ -0,0 +1,70 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { describe, it, beforeEach, afterEach } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
function loadFresh(modulePath) {
|
||||
const resolved = require.resolve(modulePath);
|
||||
delete require.cache[resolved];
|
||||
return require(modulePath);
|
||||
}
|
||||
|
||||
describe('persist-generated-article', () => {
|
||||
let tmpDir;
|
||||
let prevLog;
|
||||
let prevResearch;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'anw-persist-'));
|
||||
prevLog = process.env.ARTICLE_LOG_PATH;
|
||||
process.env.ARTICLE_LOG_PATH = path.join(tmpDir, 'idx.jsonl');
|
||||
prevResearch = process.env.RESEARCH_ENABLED;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (prevLog !== undefined) {
|
||||
process.env.ARTICLE_LOG_PATH = prevLog;
|
||||
} else {
|
||||
delete process.env.ARTICLE_LOG_PATH;
|
||||
}
|
||||
if (prevResearch !== undefined) {
|
||||
process.env.RESEARCH_ENABLED = prevResearch;
|
||||
} else {
|
||||
delete process.env.RESEARCH_ENABLED;
|
||||
}
|
||||
delete require.cache[require.resolve('../research/index')];
|
||||
delete require.cache[require.resolve('./persist-generated-article')];
|
||||
delete require.cache[require.resolve('../store/article-log')];
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('persists verification_report when research is disabled (orchestrator short-circuit)', async () => {
|
||||
process.env.RESEARCH_ENABLED = '0';
|
||||
loadFresh('../research/index');
|
||||
const { persistGeneratedArticle } = loadFresh('./persist-generated-article');
|
||||
const al = loadFresh('../store/article-log');
|
||||
await persistGeneratedArticle(
|
||||
{
|
||||
title: 'Hello',
|
||||
subtitle: '',
|
||||
body: 'y'.repeat(400),
|
||||
summary: 'Short summary for the index.',
|
||||
slug: 'persist-verify-1',
|
||||
sources: []
|
||||
},
|
||||
{ name: 'default' },
|
||||
'write',
|
||||
null,
|
||||
{ tone: 'neutral', audience_level: 'general' }
|
||||
);
|
||||
const rows = al.readLastArticles(5);
|
||||
const r = rows.find((x) => x.slug === 'persist-verify-1');
|
||||
assert.ok(r);
|
||||
assert.ok(r.verification_report);
|
||||
assert.equal(r.verification_report.status, 'disabled');
|
||||
assert.ok(typeof r.quality_score === 'number');
|
||||
});
|
||||
});
|
||||
@@ -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<object>,
|
||||
* 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 };
|
||||
@@ -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);
|
||||
});
|
||||
@@ -74,6 +74,7 @@ function trimArticleLogIfNeeded() {
|
||||
* @param {string} [rec.site_name]
|
||||
* @param {string} [rec.mode] write | listen
|
||||
* @param {Array} [rec.sources] Array of {url, publication} objects
|
||||
* @param {object|null} [rec.verification_report] Bounded multi-source verify snapshot (JSON-serializable)
|
||||
*/
|
||||
/**
|
||||
* Stable row id for matching: slug when non-empty, else ISO `at`.
|
||||
@@ -211,7 +212,7 @@ function appendArticleRecord(rec) {
|
||||
})).filter(s => s.url) : [];
|
||||
const tags = Array.isArray(rec.tags) ? rec.tags.filter(t => String(t || '').trim()).map(t => String(t).trim()).slice(0, 20) : [];
|
||||
const qualityIssues = Array.isArray(rec.quality_issues) ? rec.quality_issues.slice(0, 10) : [];
|
||||
const line = JSON.stringify({
|
||||
const row = {
|
||||
at: new Date().toISOString(),
|
||||
title: rec.title || '',
|
||||
subtitle: rec.subtitle || '',
|
||||
@@ -229,7 +230,11 @@ function appendArticleRecord(rec) {
|
||||
quality_status: rec.quality_status || null,
|
||||
writing_tone: rec.writing_tone ? String(rec.writing_tone).trim().slice(0, 32) : null,
|
||||
audience_level: rec.audience_level ? String(rec.audience_level).trim().slice(0, 32) : null
|
||||
});
|
||||
};
|
||||
if (rec.verification_report !== undefined && rec.verification_report !== null && typeof rec.verification_report === 'object') {
|
||||
row.verification_report = rec.verification_report;
|
||||
}
|
||||
const line = JSON.stringify(row);
|
||||
const logPath = getArticleLogPath();
|
||||
const release = acquireLock(`${logPath}.lock`);
|
||||
try {
|
||||
|
||||
@@ -65,6 +65,20 @@ describe('article-log', () => {
|
||||
assert.equal(rows[0].editorial_status, 'pending');
|
||||
});
|
||||
|
||||
it('appendArticleRecord stores verification_report', () => {
|
||||
const al = loadFreshArticleLog();
|
||||
const vr = {
|
||||
status: 'verified',
|
||||
overall_confidence: 80,
|
||||
sources: [{ source_name: 'google_factcheck', status: 'found', confidence: 82 }],
|
||||
claims: ['Alpha claim']
|
||||
};
|
||||
al.appendArticleRecord({ title: 'V', slug: 'v1', mode: 'write', verification_report: vr });
|
||||
const rows = al.readLastArticles(10);
|
||||
const r = rows.find((x) => x.slug === 'v1');
|
||||
assert.deepEqual(r.verification_report, vr);
|
||||
});
|
||||
|
||||
it('updateArticleStatus by slug', () => {
|
||||
const al = loadFreshArticleLog();
|
||||
al.appendArticleRecord({ title: 'A', slug: 's1', mode: 'write' });
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
'use strict';
|
||||
|
||||
const MAX_CLAIMS_STORE = 8;
|
||||
const MAX_CLAIM_LEN = 200;
|
||||
const MAX_SOURCES_STORE = 6;
|
||||
const MAX_ERR_LEN = 240;
|
||||
|
||||
/**
|
||||
* Shrink verifyArticle() output for JSONL storage (no secrets; bounded size).
|
||||
*
|
||||
* @param {object|null|undefined} raw
|
||||
* @returns {object|null}
|
||||
*/
|
||||
function serializeVerificationReport(raw) {
|
||||
if (!raw || typeof raw !== 'object') {
|
||||
return null;
|
||||
}
|
||||
const claims = Array.isArray(raw.claims)
|
||||
? raw.claims
|
||||
.slice(0, MAX_CLAIMS_STORE)
|
||||
.map((c) => String(c || '').trim().slice(0, MAX_CLAIM_LEN))
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const sources = Array.isArray(raw.sources)
|
||||
? raw.sources.slice(0, MAX_SOURCES_STORE).map((s) => {
|
||||
const o = {
|
||||
source_name: String(s.source_name || '').slice(0, 64),
|
||||
status: String(s.status || '').slice(0, 32),
|
||||
confidence:
|
||||
typeof s.confidence === 'number' && Number.isFinite(s.confidence) ? Math.round(s.confidence) : null
|
||||
};
|
||||
if (s.error) {
|
||||
o.error = String(s.error).slice(0, MAX_ERR_LEN);
|
||||
}
|
||||
return o;
|
||||
})
|
||||
: [];
|
||||
const oc = raw.overall_confidence;
|
||||
const overall_confidence =
|
||||
oc !== null && oc !== undefined && Number.isFinite(Number(oc)) ? Math.round(Number(oc)) : null;
|
||||
return {
|
||||
status: String(raw.status || 'skipped').slice(0, 32),
|
||||
overall_confidence,
|
||||
sources,
|
||||
claims
|
||||
};
|
||||
}
|
||||
|
||||
function researchVerificationBadgeClass(status) {
|
||||
const s = status || 'skipped';
|
||||
if (s === 'verified') {
|
||||
return 'badge-verify-verified';
|
||||
}
|
||||
if (s === 'unverified') {
|
||||
return 'badge-verify-unverified';
|
||||
}
|
||||
if (s === 'disputed') {
|
||||
return 'badge-verify-disputed';
|
||||
}
|
||||
return 'badge-verify-muted';
|
||||
}
|
||||
|
||||
function researchVerificationLabel(status) {
|
||||
const s = status || 'skipped';
|
||||
if (s === 'verified') {
|
||||
return 'Verificado';
|
||||
}
|
||||
if (s === 'unverified') {
|
||||
return 'Incerto';
|
||||
}
|
||||
if (s === 'disputed') {
|
||||
return 'Contestado';
|
||||
}
|
||||
if (s === 'disabled') {
|
||||
return 'Inativo';
|
||||
}
|
||||
if (s === 'skipped') {
|
||||
return 'Omitido';
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} article — row from article log
|
||||
* @param {(s: string) => string} escapeHtmlFn
|
||||
* @returns {string}
|
||||
*/
|
||||
function verificationReportCellHtml(article, escapeHtmlFn) {
|
||||
const esc = typeof escapeHtmlFn === 'function' ? escapeHtmlFn : (s) => String(s);
|
||||
const vr = article.verification_report;
|
||||
if (!vr || typeof vr !== 'object') {
|
||||
return '<span class="muted-cell">—</span>';
|
||||
}
|
||||
const st = vr.status || 'skipped';
|
||||
const badge = `<span class="badge ${researchVerificationBadgeClass(st)}">${esc(researchVerificationLabel(st))}</span>`;
|
||||
const conf =
|
||||
vr.overall_confidence !== null && vr.overall_confidence !== undefined
|
||||
? ` <span class="vconf">(${esc(String(vr.overall_confidence))}%)</span>`
|
||||
: '';
|
||||
const srcLines =
|
||||
Array.isArray(vr.sources) && vr.sources.length > 0
|
||||
? vr.sources
|
||||
.map((s) => {
|
||||
const bits = [
|
||||
esc(s.source_name || ''),
|
||||
esc(s.status || ''),
|
||||
s.confidence !== null && s.confidence !== undefined
|
||||
? esc(String(s.confidence))
|
||||
: '—'
|
||||
];
|
||||
const err = s.error ? ` — ${esc(s.error)}` : '';
|
||||
return `<li><code>${bits[0]}</code>: ${bits[1]} (${bits[2]})${err}</li>`;
|
||||
})
|
||||
.join('')
|
||||
: '';
|
||||
const claimLines =
|
||||
Array.isArray(vr.claims) && vr.claims.length > 0
|
||||
? vr.claims.map((c) => `<li>${esc(c)}</li>`).join('')
|
||||
: '';
|
||||
const inner =
|
||||
(srcLines ? `<p class="verify-sub"><strong>Fontes</strong></p><ul class="verify-list">${srcLines}</ul>` : '') +
|
||||
(claimLines ? `<p class="verify-sub"><strong>Claims extraídos</strong></p><ul class="verify-list">${claimLines}</ul>` : '');
|
||||
const details =
|
||||
inner.length > 0
|
||||
? `<details class="verify-details"><summary>Detalhes</summary>${inner}</details>`
|
||||
: '';
|
||||
return `<div class="verify-cell">${badge}${conf}${details}</div>`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
serializeVerificationReport,
|
||||
researchVerificationBadgeClass,
|
||||
researchVerificationLabel,
|
||||
verificationReportCellHtml
|
||||
};
|
||||
@@ -0,0 +1,63 @@
|
||||
'use strict';
|
||||
|
||||
const { describe, it } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const {
|
||||
serializeVerificationReport,
|
||||
researchVerificationBadgeClass,
|
||||
researchVerificationLabel,
|
||||
verificationReportCellHtml
|
||||
} = require('./verification-report');
|
||||
|
||||
describe('verification-report', () => {
|
||||
it('serializeVerificationReport trims claims and sources', () => {
|
||||
const claims = Array.from({ length: 20 }, (_, i) => `claim ${i} ` + 'x'.repeat(300));
|
||||
const sources = Array.from({ length: 10 }, (_, i) => ({
|
||||
source_name: `s${i}`,
|
||||
status: 'found',
|
||||
confidence: 50 + i,
|
||||
error: i === 0 ? 'e'.repeat(500) : undefined
|
||||
}));
|
||||
const out = serializeVerificationReport({
|
||||
status: 'verified',
|
||||
overall_confidence: 71.4,
|
||||
sources,
|
||||
claims
|
||||
});
|
||||
assert.ok(out.claims.length <= 8);
|
||||
assert.ok(out.sources.length <= 6);
|
||||
assert.ok(out.claims[0].length <= 200);
|
||||
assert.ok(!out.sources[0].error || out.sources[0].error.length <= 240);
|
||||
assert.equal(out.overall_confidence, 71);
|
||||
});
|
||||
|
||||
it('researchVerificationBadgeClass maps statuses', () => {
|
||||
assert.equal(researchVerificationBadgeClass('verified'), 'badge-verify-verified');
|
||||
assert.equal(researchVerificationBadgeClass('unverified'), 'badge-verify-unverified');
|
||||
assert.equal(researchVerificationBadgeClass('disputed'), 'badge-verify-disputed');
|
||||
assert.equal(researchVerificationBadgeClass('skipped'), 'badge-verify-muted');
|
||||
});
|
||||
|
||||
it('researchVerificationLabel uses Portuguese defaults', () => {
|
||||
assert.equal(researchVerificationLabel('verified'), 'Verificado');
|
||||
assert.equal(researchVerificationLabel('disabled'), 'Inativo');
|
||||
});
|
||||
|
||||
it('verificationReportCellHtml escapes HTML in claims', () => {
|
||||
const esc = (s) => String(s).replace(/&/g, '&').replace(/</g, '<');
|
||||
const html = verificationReportCellHtml(
|
||||
{
|
||||
verification_report: {
|
||||
status: 'disputed',
|
||||
overall_confidence: 12,
|
||||
sources: [{ source_name: 'x<script>', status: 'error', confidence: null, error: '<bad>' }],
|
||||
claims: ['<img onerror=alert(1)>']
|
||||
}
|
||||
},
|
||||
esc
|
||||
);
|
||||
assert.ok(!html.includes('<script>'));
|
||||
assert.ok(!html.includes('<img'));
|
||||
assert.ok(html.includes('<'));
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user