Merge pull request 'BIT-21924: staging verification smoke seed + /api/ui/articles' (#22) from task/BIT-21924-staging-smoke-seed into main
ai-news-writer-ci / test (push) Successful in 38s

This commit was merged in pull request #22.
This commit is contained in:
spark committed 2026-05-13 06:01:58 +01:00
commit 5b5562a06c
6 files changed
+273

No files matched your search

+1
View File
@@ -15,6 +15,7 @@
"rss:test": "node src/index.js rss:test",
"x:test": "node src/index.js x:test",
"ops:check": "bash tools/ops-check.sh",
"seed:smoke-verification": "node tools/seed-smoke-verification-article.js",
"deploy:lxc": "bash tools/deploy-lxc.sh",
"test": "c8 --reporter=text --reporter=html --reporter=lcov node --test --test-concurrency=1 $(find src -type f -name '*.test.js' | sort | tr '\\n' ' ')",
"lint": "eslint src/",
+66
View File
@@ -0,0 +1,66 @@
'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 loadFreshArticleLog() {
delete require.cache[require.resolve('../store/article-log')];
return require('../store/article-log');
}
function loadFreshUiHandlers() {
delete require.cache[require.resolve('../store/article-log')];
delete require.cache[require.resolve('./ui-handlers')];
return require('./ui-handlers');
}
describe('ui-handlers GET /api/ui/articles', () => {
let tmpDir;
let prevPath;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'anw-uiapi-'));
prevPath = process.env.ARTICLE_LOG_PATH;
process.env.ARTICLE_LOG_PATH = path.join(tmpDir, 'idx.jsonl');
});
afterEach(() => {
if (prevPath !== undefined) {
process.env.ARTICLE_LOG_PATH = prevPath;
} else {
delete process.env.ARTICLE_LOG_PATH;
}
delete require.cache[require.resolve('../store/article-log')];
delete require.cache[require.resolve('./ui-handlers')];
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('returns ok and articles (newest first)', async () => {
const al = loadFreshArticleLog();
al.appendArticleRecord({ title: 'First', slug: 'z1', mode: 'write' });
al.appendArticleRecord({ title: 'Second', slug: 'z2', mode: 'write' });
const { tryHandleAdminUi } = loadFreshUiHandlers();
let code;
let body = '';
const res = {
writeHead(c) {
code = c;
},
end(b) {
body = typeof b === 'string' ? b : b.toString();
}
};
const req = { method: 'GET', url: '/api/ui/articles?limit=10', headers: {} };
const ok = await tryHandleAdminUi(req, res);
assert.equal(ok, true);
assert.equal(code, 200);
const j = JSON.parse(body);
assert.equal(j.ok, true);
assert.equal(j.articles.length, 2);
assert.equal(j.articles[0].slug, 'z2');
assert.equal(j.articles[1].slug, 'z1');
});
});
+44
View File
@@ -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 { seedSmokeVerificationArticle } = require('../store/smoke-verification-seed');
const { verificationReportCellHtml } = require('../store/verification-report');
const { parseDomain } = require('../util/domain');
const { getArticleEngagement, getCategoryBenchmarks, getTopArticles, exportAnalyticsCSV } = require('./analytics-api');
@@ -1021,6 +1022,10 @@ async function tryHandleAdminUi(req, res) {
flash = { type: 'err', text: 'Erro: Slug já existe. Por favor, use um slug único.' };
} else if (flashParam === 'err') {
flash = { type: 'err', text: 'Não foi possível atualizar (token, artigo, ou dados inválidos).' };
} else if (flashParam === 'seeded-vr') {
flash = { type: 'ok', text: 'Linha smoke de verificação inserida (slug smoke-verification-bit21924; fontes google_factcheck / claimcheck / cross_reference).' };
} else if (flashParam === 'seeded-vr-skip') {
flash = { type: 'ok', text: 'Smoke de verificação já existia — nada alterado.' };
}
const html = pageDashboard(theme, flash);
res.writeHead(200, mergeResponseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) }));
@@ -1028,6 +1033,14 @@ async function tryHandleAdminUi(req, res) {
return true;
}
if (req.method === 'GET' && pathname === '/api/ui/articles') {
const limit = Math.min(200, Math.max(1, parseInt(u.searchParams.get('limit') || '50', 10) || 50));
const body = JSON.stringify({ ok: true, articles: readLastArticles(limit) });
res.writeHead(200, mergeResponseHeaders({ 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(body) }));
res.end(body);
return true;
}
if (req.method === 'GET' && pathname === '/ui/sources') {
const html = pageSources(theme, null);
res.writeHead(200, mergeResponseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) }));
@@ -1080,6 +1093,7 @@ async function tryHandleAdminUi(req, res) {
pathname === '/ui/social' ||
pathname === '/ui/theme' ||
pathname === '/ui/writing-style' ||
pathname === '/ui/seed/smoke-verification' ||
isArticleActionPost ||
isArticleMetadataEdit ||
isBulkTagAssign)
@@ -1229,6 +1243,36 @@ async function tryHandleAdminUi(req, res) {
}
}
if (req.method === 'POST' && pathname === '/ui/seed/smoke-verification') {
if (!isAllowedAdminFormContentType(req)) {
logger.warn(`UI: rejected POST ${pathname} — unsupported Content-Type: ${String(req.headers['content-type'])}`);
res.writeHead(415, mergeResponseHeaders({ 'Content-Type': 'text/plain; charset=utf-8' }));
res.end('Unsupported Media Type: admin forms expect application/x-www-form-urlencoded');
return true;
}
try {
const raw = await collectBody(req);
const params = new URLSearchParams(raw.toString('utf8'));
const token = params.get('admin_token') || '';
if (!adminOk(req, token)) {
res.writeHead(303, mergeResponseHeaders({ Location: '/ui?flash=err' }));
res.end();
return true;
}
const r = seedSmokeVerificationArticle();
logger.info(`UI: smoke verification seed seeded=${r.seeded} slug=${r.slug}`);
const loc = r.seeded ? '/ui?flash=seeded-vr' : '/ui?flash=seeded-vr-skip';
res.writeHead(303, mergeResponseHeaders({ Location: loc }));
res.end();
return true;
} catch (err) {
logger.warn(`UI: smoke verification seed failed: ${err.message}`);
res.writeHead(303, mergeResponseHeaders({ Location: '/ui?flash=err' }));
res.end();
return true;
}
}
if (req.method === 'POST' && pathname === '/ui/sources') {
let msg = null;
try {
+56
View File
@@ -0,0 +1,56 @@
'use strict';
const { readLastArticles, appendArticleRecord } = require('./article-log');
const { serializeVerificationReport } = require('./verification-report');
/** Distinct from any legacy smoke slug so older rows do not block AC-compliant re-seed. */
const SMOKE_SLUG = 'smoke-verification-bit21924';
function verificationReportHasAcPaths(vr) {
if (!vr || typeof vr !== 'object' || !Array.isArray(vr.sources)) {
return false;
}
const names = new Set(vr.sources.map((s) => String(s.source_name || '')));
return names.has('google_factcheck') && names.has('claimcheck') && names.has('cross_reference');
}
/**
* Idempotent: appends one dashboard row with a bounded multi-source verification_report
* (staging / QA smoke — BIT-21924).
*
* AC: `verification_report.sources` must include the three pipeline paths
* (`google_factcheck`, `claimcheck`, `cross_reference`) with per-source status/confidence.
*
* @returns {{ seeded: boolean, slug: string, reason?: string }}
*/
function seedSmokeVerificationArticle() {
const articles = readLastArticles(500);
if (articles.some((a) => verificationReportHasAcPaths(a.verification_report))) {
return { seeded: false, slug: SMOKE_SLUG, reason: 'ac_compliant_row_exists' };
}
if (articles.some((a) => String(a.slug || '').trim() === SMOKE_SLUG)) {
return { seeded: false, slug: SMOKE_SLUG, reason: 'slug_exists' };
}
const rawV = {
status: 'verified',
overall_confidence: 87,
claims: ['Afirmação de smoke para validação da coluna Verificação em staging (BIT-21924).'],
sources: [
{ source_name: 'google_factcheck', status: 'found', confidence: 0.88 },
{ source_name: 'claimcheck', status: 'found', confidence: 0.74 },
{ source_name: 'cross_reference', status: 'found', confidence: 0.69 }
]
};
appendArticleRecord({
title: '[Smoke] Relatório de verificação multi-fonte (AC)',
slug: SMOKE_SLUG,
summary: 'Linha de smoke BIT-21924 para validar coluna Verificação (aggregação multi-fonte).',
mode: 'listen',
site_name: 'staging-smoke',
sources: [{ url: 'https://example.invalid/bitreport-smoke', publication: 'Smoke' }],
verification_report: serializeVerificationReport(rawV)
});
return { seeded: true, slug: SMOKE_SLUG };
}
module.exports = { seedSmokeVerificationArticle, SMOKE_SLUG, verificationReportHasAcPaths };
+86
View File
@@ -0,0 +1,86 @@
'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 loadFreshArticleLog() {
const resolved = require.resolve('./article-log');
delete require.cache[resolved];
return require('./article-log');
}
function loadFreshSeed() {
delete require.cache[require.resolve('./smoke-verification-seed')];
return require('./smoke-verification-seed');
}
describe('smoke-verification-seed', () => {
let tmpDir;
let prevPath;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'anw-svseed-'));
prevPath = process.env.ARTICLE_LOG_PATH;
process.env.ARTICLE_LOG_PATH = path.join(tmpDir, 'idx.jsonl');
loadFreshArticleLog();
});
afterEach(() => {
if (prevPath !== undefined) {
process.env.ARTICLE_LOG_PATH = prevPath;
} else {
delete process.env.ARTICLE_LOG_PATH;
}
delete require.cache[require.resolve('./article-log')];
delete require.cache[require.resolve('./smoke-verification-seed')];
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('appends once then skips on second call', () => {
const { seedSmokeVerificationArticle, SMOKE_SLUG } = loadFreshSeed();
const r1 = seedSmokeVerificationArticle();
assert.equal(r1.seeded, true);
assert.equal(r1.slug, SMOKE_SLUG);
const r2 = seedSmokeVerificationArticle();
assert.equal(r2.seeded, false);
const al = loadFreshArticleLog();
const rows = al.readLastArticles(20).filter((x) => x.slug === SMOKE_SLUG);
assert.equal(rows.length, 1);
assert.ok(rows[0].verification_report);
assert.equal(rows[0].verification_report.status, 'verified');
const names = new Set((rows[0].verification_report.sources || []).map((s) => s.source_name));
assert.ok(names.has('google_factcheck'));
assert.ok(names.has('claimcheck'));
assert.ok(names.has('cross_reference'));
});
it('skips when an AC-compliant row already exists (any slug)', () => {
const al = loadFreshArticleLog();
const { serializeVerificationReport } = require('./verification-report');
const rawV = {
status: 'verified',
overall_confidence: 80,
claims: ['Other row'],
sources: [
{ source_name: 'google_factcheck', status: 'found', confidence: 0.9 },
{ source_name: 'claimcheck', status: 'found', confidence: 0.8 },
{ source_name: 'cross_reference', status: 'found', confidence: 0.7 }
]
};
al.appendArticleRecord({
title: 'Pre-existing',
slug: 'other-smoke',
mode: 'listen',
verification_report: serializeVerificationReport(rawV)
});
const { seedSmokeVerificationArticle } = loadFreshSeed();
const r = seedSmokeVerificationArticle();
assert.equal(r.seeded, false);
assert.equal(r.reason, 'ac_compliant_row_exists');
const rows = al.readLastArticles(20);
assert.equal(rows.filter((x) => x.slug === 'smoke-verification-bit21924').length, 0);
});
});
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env node
'use strict';
const path = require('path');
try {
// eslint-disable-next-line global-require
require('dotenv').config({ path: path.join(__dirname, '..', '.env') });
} catch (_err) {
/* optional */
}
const { seedSmokeVerificationArticle } = require('../src/store/smoke-verification-seed');
const r = seedSmokeVerificationArticle();
if (r.seeded) {
console.log(`Seeded article slug=${r.slug}`);
} else {
console.log(`Skip: slug ${r.slug} already present`);
}