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
This commit is contained in:
Xika committed 2026-05-12 13:04:59 +00:00
1 parent 4175fe5b5c
commit ec203917d1
6 files changed
+227

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 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 {
+41
View File
@@ -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 };
+55
View File
@@ -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');
});
});
+20
View File
@@ -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`);
}