From ec203917d1ab2bd764fbe68483dfa7f9aa0bb811 Mon Sep 17 00:00:00 2001 From: Xika Date: Tue, 12 May 2026 13:04:59 +0000 Subject: [PATCH 1/3] Restore /api/ui/articles and add staging verification smoke seed Wire GET /api/ui/articles (documented but missing) so curl/JQ checks work against the article log. Add idempotent seed helper, npm run seed:smoke-verification, and admin POST /ui/seed/smoke-verification for operators without SSH to the CT. Paperclip-Issue: BIT-21924 Paperclip-Run: 4105a0ac-e90c-477f-8065-10419988abdf --- package.json | 1 + src/http/ui-handlers-api-articles.test.js | 66 +++++++++++++++++++++++ src/http/ui-handlers.js | 44 +++++++++++++++ src/store/smoke-verification-seed.js | 41 ++++++++++++++ src/store/smoke-verification-seed.test.js | 55 +++++++++++++++++++ tools/seed-smoke-verification-article.js | 20 +++++++ 6 files changed, 227 insertions(+) create mode 100644 src/http/ui-handlers-api-articles.test.js create mode 100644 src/store/smoke-verification-seed.js create mode 100644 src/store/smoke-verification-seed.test.js create mode 100644 tools/seed-smoke-verification-article.js diff --git a/package.json b/package.json index f308acd..53ca508 100644 --- a/package.json +++ b/package.json @@ -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/", diff --git a/src/http/ui-handlers-api-articles.test.js b/src/http/ui-handlers-api-articles.test.js new file mode 100644 index 0000000..d4a3ce4 --- /dev/null +++ b/src/http/ui-handlers-api-articles.test.js @@ -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'); + }); +}); diff --git a/src/http/ui-handlers.js b/src/http/ui-handlers.js index d319819..e057512 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 { 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 multi-fonte inserida (slug smoke-verification-report).' }; + } 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 { diff --git a/src/store/smoke-verification-seed.js b/src/store/smoke-verification-seed.js new file mode 100644 index 0000000..cd06ad0 --- /dev/null +++ b/src/store/smoke-verification-seed.js @@ -0,0 +1,41 @@ +'use strict'; + +const { readLastArticles, appendArticleRecord } = require('./article-log'); +const { serializeVerificationReport } = require('./verification-report'); + +const SMOKE_SLUG = 'smoke-verification-report'; + +/** + * Idempotent: appends one dashboard row with a bounded multi-source verification_report + * (staging / QA smoke — BIT-21924). + * + * @returns {{ seeded: boolean, slug: string }} + */ +function seedSmokeVerificationArticle() { + const articles = readLastArticles(500); + if (articles.some((a) => String(a.slug || '').trim() === SMOKE_SLUG)) { + return { seeded: false, slug: SMOKE_SLUG }; + } + const rawV = { + status: 'verified', + overall_confidence: 87, + claims: ['Afirmação de smoke para validação da coluna Verificação em staging.'], + sources: [ + { source_name: 'Fonte A', status: 'match', confidence: 0.91 }, + { source_name: 'Fonte B', status: 'partial', confidence: 0.72 }, + { source_name: 'Fonte C', status: 'mismatch', confidence: 0.41 } + ] + }; + appendArticleRecord({ + title: '[Smoke] Relatório de verificação multi-fonte', + 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 }; diff --git a/src/store/smoke-verification-seed.test.js b/src/store/smoke-verification-seed.test.js new file mode 100644 index 0000000..76420b5 --- /dev/null +++ b/src/store/smoke-verification-seed.test.js @@ -0,0 +1,55 @@ +'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'); + }); +}); diff --git a/tools/seed-smoke-verification-article.js b/tools/seed-smoke-verification-article.js new file mode 100644 index 0000000..2ee5dad --- /dev/null +++ b/tools/seed-smoke-verification-article.js @@ -0,0 +1,20 @@ +#!/usr/bin/env node +'use strict'; + +const path = require('path'); + +try { + // eslint-disable-next-line global-require, import/no-extraneous-dependencies + 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`); +} -- 2.47.3 From 492ab8f67873322348ea44170f8eea7e15a0733c Mon Sep 17 00:00:00 2001 From: Xika Date: Tue, 12 May 2026 15:41:43 +0000 Subject: [PATCH 2/3] Align BIT-21924 smoke seed with verification AC paths verification_report.sources now use google_factcheck, claimcheck, and cross_reference with per-source status/confidence. Slug smoke-verification-bit21924; skip if any row already has the three paths (idempotent across legacy smoke rows). Paperclip-Issue: BIT-21924 Paperclip-Run: 6be4879b-b739-479f-a6f9-f08d0654678d --- src/http/ui-handlers.js | 2 +- src/store/smoke-verification-seed.js | 33 ++++++++++++++++------- src/store/smoke-verification-seed.test.js | 31 +++++++++++++++++++++ 3 files changed, 56 insertions(+), 10 deletions(-) diff --git a/src/http/ui-handlers.js b/src/http/ui-handlers.js index e057512..4ef2b01 100644 --- a/src/http/ui-handlers.js +++ b/src/http/ui-handlers.js @@ -1023,7 +1023,7 @@ async function tryHandleAdminUi(req, res) { } 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 multi-fonte inserida (slug smoke-verification-report).' }; + 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.' }; } diff --git a/src/store/smoke-verification-seed.js b/src/store/smoke-verification-seed.js index cd06ad0..bbea080 100644 --- a/src/store/smoke-verification-seed.js +++ b/src/store/smoke-verification-seed.js @@ -3,31 +3,46 @@ const { readLastArticles, appendArticleRecord } = require('./article-log'); const { serializeVerificationReport } = require('./verification-report'); -const SMOKE_SLUG = 'smoke-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). * - * @returns {{ seeded: boolean, slug: string }} + * 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 }; + 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.'], + claims: ['Afirmação de smoke para validação da coluna Verificação em staging (BIT-21924).'], sources: [ - { source_name: 'Fonte A', status: 'match', confidence: 0.91 }, - { source_name: 'Fonte B', status: 'partial', confidence: 0.72 }, - { source_name: 'Fonte C', status: 'mismatch', confidence: 0.41 } + { 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', + 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', @@ -38,4 +53,4 @@ function seedSmokeVerificationArticle() { return { seeded: true, slug: SMOKE_SLUG }; } -module.exports = { seedSmokeVerificationArticle, SMOKE_SLUG }; +module.exports = { seedSmokeVerificationArticle, SMOKE_SLUG, verificationReportHasAcPaths }; diff --git a/src/store/smoke-verification-seed.test.js b/src/store/smoke-verification-seed.test.js index 76420b5..698524b 100644 --- a/src/store/smoke-verification-seed.test.js +++ b/src/store/smoke-verification-seed.test.js @@ -51,5 +51,36 @@ describe('smoke-verification-seed', () => { 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); }); }); -- 2.47.3 From 65fa4014d0917ae53edb3d2dcbb932b03141321e Mon Sep 17 00:00:00 2001 From: Xika Date: Wed, 13 May 2026 04:36:09 +0000 Subject: [PATCH 3/3] fix(lint): drop missing import/no-extraneous-dependencies rule disable CI lint job has no eslint-plugin-import installed, so the inline disable-next-line for that rule itself raises an "unknown rule" error on `tools/seed-smoke-verification-article.js`. Drop the import-related token from the disable comment and keep only the still-valid `global-require` disable for the lazy require of `dotenv`. No behaviour change; the file still tries dotenv and silently continues without it. Paperclip-Issue: BIT-21924 Paperclip-Run: bb6e49a5-4f6d-4a8e-a4dd-ee75d961b36f --- tools/seed-smoke-verification-article.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/seed-smoke-verification-article.js b/tools/seed-smoke-verification-article.js index 2ee5dad..3c374fd 100644 --- a/tools/seed-smoke-verification-article.js +++ b/tools/seed-smoke-verification-article.js @@ -4,7 +4,7 @@ const path = require('path'); try { - // eslint-disable-next-line global-require, import/no-extraneous-dependencies + // eslint-disable-next-line global-require require('dotenv').config({ path: path.join(__dirname, '..', '.env') }); } catch (_err) { /* optional */ -- 2.47.3