diff --git a/config/sites/andebol.net.example.json b/config/sites/andebol.net.example.json new file mode 100644 index 0000000..cfaded6 --- /dev/null +++ b/config/sites/andebol.net.example.json @@ -0,0 +1,24 @@ +{ + "name": "andebol.net", + "writing_tone": "formal", + "audience_level": "general", + "wp_transport": "rest", + "wp_url": "https://andebol.net/wp-json", + "site_domain": "andebol.net", + "user": "writer-bot", + "password": "application-password-from-vault", + "category_default": 1, + "category_infer": "andebol", + "category_map": { + "nacional": 1, + "internacional": 2, + "selecao": 3, + "clubes": 4, + "competicoes": 5, + "resultados": 6 + }, + "status_default": "publish", + "tags_auto": true, + "tags_infer": "andebol", + "lang": "pt" +} diff --git a/package-lock.json b/package-lock.json index cd1c4e5..a91c044 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,7 +8,7 @@ "name": "ai-news-writer", "version": "0.1.0", "dependencies": { - "axios": "^1.7.9", + "axios": "^1.18.0", "cheerio": "^1.0.0", "dotenv": "^16.4.7", "fast-xml-parser": "^5.7.2", @@ -325,6 +325,18 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/agentkeepalive": { "version": "4.6.0", "license": "MIT", @@ -414,11 +426,14 @@ "license": "MIT" }, "node_modules/axios": { - "version": "1.15.2", + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.18.0.tgz", + "integrity": "sha512-E32NzpYKp++W7XRe52rHiXV2ehxmh3wbdgO7MHeFM+vqxLBYHzt0ElkiImtOBxtOmyp0yoC8C6uESVV84Y2/hw==", "license": "MIT", "dependencies": { - "follow-redirects": "^1.15.11", + "follow-redirects": "^1.16.0", "form-data": "^4.0.5", + "https-proxy-agent": "^5.0.1", "proxy-from-env": "^2.1.0" } }, @@ -715,7 +730,6 @@ }, "node_modules/debug": { "version": "4.4.3", - "dev": true, "license": "MIT", "dependencies": { "ms": "^2.1.3" @@ -1241,14 +1255,16 @@ } }, "node_modules/form-data": { - "version": "4.0.5", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" + "hasown": "^2.0.4", + "mime-types": "^2.1.35" }, "engines": { "node": ">= 6" @@ -1450,7 +1466,9 @@ } }, "node_modules/hasown": { - "version": "2.0.2", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -1491,6 +1509,19 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/humanize-ms": { "version": "1.2.1", "license": "MIT", @@ -2648,7 +2679,9 @@ "license": "MIT" }, "node_modules/undici": { - "version": "7.24.5", + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.28.0.tgz", + "integrity": "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==", "license": "MIT", "engines": { "node": ">=20.18.1" diff --git a/package.json b/package.json index 53ca508..401a3d2 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,8 @@ "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", + "wp:backfill-categories": "node tools/backfill-wp-categories.js", + "wp:backfill-meta": "node tools/backfill-wp-meta.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/", @@ -23,7 +25,7 @@ "format": "prettier --write ." }, "dependencies": { - "axios": "^1.7.9", + "axios": "^1.18.0", "cheerio": "^1.0.0", "dotenv": "^16.4.7", "fast-xml-parser": "^5.7.2", @@ -42,5 +44,9 @@ }, "engines": { "node": ">=20" + }, + "overrides": { + "form-data": ">=4.0.6", + "undici": "^7.28.0" } } diff --git a/src/pipeline/persist-generated-article.js b/src/pipeline/persist-generated-article.js index bb0d8fd..1c551d7 100644 --- a/src/pipeline/persist-generated-article.js +++ b/src/pipeline/persist-generated-article.js @@ -5,6 +5,7 @@ const { metrics } = require('../monitoring/metrics'); const { scoreArticleQuality } = require('./quality-scorer'); const { verifyArticle } = require('../research'); const { appendArticleRecord } = require('../store/article-log'); +const { sanitizeArticleMeta } = require('../publisher/article-meta'); const { serializeVerificationReport } = require('../store/verification-report'); function getQualityThresholds() { @@ -31,8 +32,9 @@ function getQualityThresholds() { */ async function persistGeneratedArticle(article, site, mode, wp_link, voice = {}) { try { + const normalized = sanitizeArticleMeta(article, site || {}); const thresholds = getQualityThresholds(); - const quality = scoreArticleQuality(article, { + const quality = scoreArticleQuality(normalized, { minWordCount: thresholds.minWordCount, maxReadabilityGrade: thresholds.maxReadabilityGrade }); @@ -46,7 +48,7 @@ async function persistGeneratedArticle(article, site, mode, wp_link, voice = {}) let verification_report = null; try { - const rawV = await verifyArticle(article); + const rawV = await verifyArticle(normalized); verification_report = serializeVerificationReport(rawV); } catch (vErr) { logger.warn(`verification orchestration failed (non-fatal): ${vErr.message}`); @@ -59,10 +61,12 @@ async function persistGeneratedArticle(article, site, mode, wp_link, voice = {}) } appendArticleRecord({ - title: article.title, - subtitle: article.subtitle, - slug: article.slug, - summary: article.summary, + title: normalized.title, + subtitle: normalized.subtitle, + slug: normalized.slug, + summary: normalized.summary, + tags: normalized.tags, + category: normalized.category || null, wp_link: wp_link || null, site_name: site?.name || 'default', mode, diff --git a/src/publisher/article-meta.js b/src/publisher/article-meta.js new file mode 100644 index 0000000..e9acd1d --- /dev/null +++ b/src/publisher/article-meta.js @@ -0,0 +1,253 @@ +'use strict'; + +const ANDEBOL_ENTITY_RULES = [ + { tag: 'FC Porto', pattern: /\b(?:fc porto|f\.?\s*c\.?\s*porto)\b/i }, + { tag: 'Benfica', pattern: /\b(?:sl benfica|benfica)\b/i }, + { tag: 'Sporting CP', pattern: /\b(?:sporting cp|sporting)\b/i }, + { tag: 'SC Braga', pattern: /\b(?:sc braga|vitória\s+sc)\b/i }, + { tag: 'Seleção Nacional', pattern: /\bseleç(?:ão|ões)\s+nacionais?\b/i }, + { tag: 'Portugal', pattern: /\bportugal\b/i }, + { tag: 'Liga dos Campeões', pattern: /\bliga\s+dos\s+campeões\b/i }, + { tag: 'Taça de Portugal', pattern: /\btaça\s+de\s+portugal\b/i }, + { tag: 'Campeonato Nacional', pattern: /\bcampeonato\s+nacional\b/i }, + { tag: 'EHF', pattern: /\behf\b/i }, + { tag: 'IHF', pattern: /\bihf\b/i }, + { tag: 'Andebol', pattern: /\bandebol\b/i } +]; + +const SKIP_NAME_FRAGMENTS = new Set([ + 'federação de', 'federação portuguesa', 'european portuguese', 'source material', + 'fonte original', 'fonte federação' +]); + +function foldAccents(value) { + return String(value || '') + .normalize('NFD') + .replace(/\p{M}/gu, ''); +} + +function plainTextFromHtml(html) { + return String(html || '') + .replace(/<[^>]+>/g, ' ') + .replace(/\[[^\]]+\]/g, ' ') + .replace(/\s+/g, ' ') + .trim(); +} + +function articleCorpus(article) { + return plainTextFromHtml([ + article?.title, + article?.subtitle, + article?.summary, + article?.excerpt, + article?.body, + article?.content + ].filter(Boolean).join(' ')); +} + +function tagMentionedInCorpus(tag, corpus) { + const normalizedTag = foldAccents(tag).toLowerCase().trim(); + if (normalizedTag.length < 2) { + return false; + } + const normalizedCorpus = foldAccents(corpus).toLowerCase(); + return normalizedCorpus.includes(normalizedTag); +} + +/** + * Keep only tags that literally appear in the published article text. + * + * @param {string[]} tags + * @param {string} corpus + * @param {number} [maxTags] + * @returns {string[]} + */ +function sanitizeTags(tags, corpus, maxTags = 8) { + if (!Array.isArray(tags)) { + return []; + } + const seen = new Set(); + const out = []; + for (const raw of tags) { + const tag = String(raw || '').trim(); + if (!tag || tag.length > 60) { + continue; + } + const key = foldAccents(tag).toLowerCase(); + if (seen.has(key)) { + continue; + } + if (tagMentionedInCorpus(tag, corpus)) { + seen.add(key); + out.push(tag); + } + } + return out.slice(0, maxTags); +} + +/** + * Extract editorial tags from article text (teams, competitions, people mentioned). + * + * @param {Object} article + * @returns {string[]} + */ +function inferAndebolTags(article) { + const corpus = articleCorpus(article); + if (!corpus) { + return ['Andebol']; + } + + const seen = new Set(); + const tags = []; + + function pushTag(tag) { + const trimmed = String(tag || '').trim(); + if (!trimmed) { + return; + } + const key = foldAccents(trimmed).toLowerCase(); + if (seen.has(key)) { + return; + } + seen.add(key); + tags.push(trimmed); + } + + for (const rule of ANDEBOL_ENTITY_RULES) { + if (rule.pattern.test(corpus)) { + pushTag(rule.tag); + } + } + + const namePattern = /\b([A-ZÁÉÍÓÚÀÂÊÔÃÕÇ][a-záéíóúàâêôãõç]+(?:\s+(?:de|da|do|dos|das|e)\s+)?(?:[A-ZÁÉÍÓÚÀÂÊÔÃÕÇ][a-záéíóúàâêôãõç]+)+)\b/g; + let match; + while ((match = namePattern.exec(corpus)) !== null) { + const candidate = match[1].trim(); + const lower = foldAccents(candidate).toLowerCase(); + if (candidate.split(/\s+/).length < 2 || candidate.length > 40) { + continue; + } + if ([...SKIP_NAME_FRAGMENTS].some((frag) => lower.includes(frag))) { + continue; + } + if (tagMentionedInCorpus(candidate, corpus)) { + pushTag(candidate); + } + } + + if (tags.length === 0) { + pushTag('Andebol'); + } + + return tags.slice(0, 8); +} + +function truncateAtWord(text, maxLen) { + const trimmed = String(text || '').trim(); + if (trimmed.length <= maxLen) { + return trimmed; + } + const slice = trimmed.slice(0, maxLen); + const lastSpace = slice.lastIndexOf(' '); + if (lastSpace > maxLen * 0.6) { + return `${slice.slice(0, lastSpace).trim()}…`; + } + return `${slice.trim()}…`; +} + +function deriveSeoTitle(article) { + const title = plainTextFromHtml(article?.seo_title || article?.title || ''); + return truncateAtWord(title, 60); +} + +function seoDescriptionGrounded(text, corpus) { + const plain = plainTextFromHtml(text); + if (!plain) { + return false; + } + const namePattern = /\b([A-ZÁÉÍÓÚÀÂÊÔÃÕÇ][a-záéíóúàâêôãõç]+(?:\s+[A-ZÁÉÍÓÚÀÂÊÔÃÕÇ][a-záéíóúàâêôãõç]+)+)\b/g; + let match; + while ((match = namePattern.exec(plain)) !== null) { + const candidate = match[1].trim(); + if (candidate.split(/\s+/).length >= 2 && !tagMentionedInCorpus(candidate, corpus)) { + return false; + } + } + return true; +} + +function deriveSeoDescription(article) { + const corpus = articleCorpus(article); + const candidates = [ + article?.summary, + article?.excerpt, + plainTextFromHtml(article?.body || article?.content || '').slice(0, 220), + article?.seo_description + ]; + for (const candidate of candidates) { + const text = plainTextFromHtml(candidate); + if (!text || text.length < 40) { + continue; + } + if (!seoDescriptionGrounded(text, corpus)) { + continue; + } + return truncateAtWord(text, 155); + } + return truncateAtWord(corpus.slice(0, 155), 155); +} + +function deriveFocusKeyword(article) { + const title = plainTextFromHtml(article?.title || ''); + const words = title + .split(/\s+/) + .map((w) => w.replace(/[^a-záéíóúàâêôãõç0-9-]/gi, '')) + .filter((w) => w.length > 3); + if (words.length === 0) { + return 'andebol'; + } + const corpus = articleCorpus(article); + for (const word of words) { + if (tagMentionedInCorpus(word, corpus)) { + return word.toLowerCase(); + } + } + return words[0].toLowerCase(); +} + +/** + * Sanitize tags and SEO fields so meta-info only references on-page content. + * + * @param {Object} article + * @param {{ tags_infer?: string }} [siteConfig] + * @returns {Object} shallow copy with sanitized meta fields + */ +function sanitizeArticleMeta(article, siteConfig = {}) { + const next = { ...article }; + const corpus = articleCorpus(article); + const inferMode = siteConfig?.tags_infer || siteConfig?.category_infer; + + let tags = sanitizeTags(next.tags, corpus); + if (tags.length === 0 && (inferMode === 'andebol' || siteConfig?.tags_auto)) { + tags = inferAndebolTags(next); + } + + next.tags = tags; + next.seo_title = deriveSeoTitle(next); + next.seo_description = deriveSeoDescription(next); + next.focus_keyword = deriveFocusKeyword(next); + return next; +} + +module.exports = { + sanitizeArticleMeta, + sanitizeTags, + inferAndebolTags, + deriveSeoTitle, + deriveSeoDescription, + deriveFocusKeyword, + tagMentionedInCorpus, + plainTextFromHtml, + articleCorpus, + ANDEBOL_ENTITY_RULES +}; diff --git a/src/publisher/article-meta.test.js b/src/publisher/article-meta.test.js new file mode 100644 index 0000000..fece91e --- /dev/null +++ b/src/publisher/article-meta.test.js @@ -0,0 +1,52 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const test = require('node:test'); +const { + sanitizeTags, + inferAndebolTags, + sanitizeArticleMeta +} = require('./article-meta'); + +test('sanitizeTags drops tags not present in article body', () => { + const corpus = 'O FC Porto venceu o Benfica por 28-25 na Liga dos Campeões.'; + const tags = sanitizeTags(['FC Porto', 'João Silva', 'Benfica', 'Cristiano Ronaldo'], corpus); + assert.deepEqual(tags, ['FC Porto', 'Benfica']); +}); + +test('inferAndebolTags extracts teams and competitions from text', () => { + const tags = inferAndebolTags({ + title: 'FC Porto vence Benfica na Liga dos Campeões', + body: '

O FC Porto confirmou a vitória sobre o Benfica na Liga dos Campeões.

' + }); + assert.ok(tags.includes('FC Porto')); + assert.ok(tags.includes('Benfica')); + assert.ok(tags.includes('Liga dos Campeões')); +}); + +test('sanitizeArticleMeta removes hallucinated player tags', () => { + const result = sanitizeArticleMeta({ + title: 'Festa do Andebol regressa a Lagoa', + body: '

A Festa do Andebol junta seleções regionais sub-14 em Lagoa.

', + summary: 'Evento desportivo reunirá jovens atletas na região.', + tags: ['Marta Costa', 'João Rodrigues', 'Andebol'], + seo_description: 'Marta Costa brilhou na competição internacional' + }, { tags_infer: 'andebol', tags_auto: true }); + + assert.ok(!result.tags.includes('Marta Costa')); + assert.ok(!result.tags.includes('João Rodrigues')); + assert.ok(result.tags.includes('Andebol')); + assert.ok(!result.seo_description.includes('Marta Costa')); +}); + +test('sanitizeArticleMeta keeps valid LLM tags', () => { + const result = sanitizeArticleMeta({ + title: 'Carlos Ribeiro renova com Sporting CP', + body: '

Carlos Ribeiro assinou renovação com o Sporting CP.

', + tags: ['Carlos Ribeiro', 'Sporting CP', 'Pedro Santos'] + }, { tags_auto: true }); + + assert.ok(result.tags.includes('Carlos Ribeiro')); + assert.ok(result.tags.includes('Sporting CP')); + assert.equal(result.tags.includes('Pedro Santos'), false); +}); diff --git a/src/publisher/category-infer.js b/src/publisher/category-infer.js new file mode 100644 index 0000000..e90cb6f --- /dev/null +++ b/src/publisher/category-infer.js @@ -0,0 +1,158 @@ +'use strict'; + +const INTERNATIONAL_SOURCE_HOSTS = new Set([ + 'ihf.info', + 'www.ihf.info', + 'eurohandball.com', + 'www.eurohandball.com', + 'handball-planet.com', + 'www.handball-planet.com', + 'feeds.bbci.co.uk', + 'bbc.co.uk', + 'bbci.co.uk' +]); + +const RULES = [ + { + slug: 'selecao', + patterns: [ + /\bseleç(?:ão|ões)\s+nacionais?\b/i, + /\bseleção\s+portuguesa\b/i, + /\btorneio\s+(?:4|quatro)\s+naç(?:ões|oes)\b/i, + /\bportugal\s+(?:vence|perde|empata|enfrenta|defronta|soma|regista)\b/i, + /\bnational team\b/i + ] + }, + { + slug: 'resultados', + patterns: [ + /\bresultado(?:s)?\b/i, + /\b(?:venceu|vence|derrota|derrotado|empate|empatou|goleada)\b/i, + /\b\d+\s*[-–]\s*\d+\b/, + /\b(?:final|semi-?final|meias-?finais)\s+(?:termina|fica|ficou)\b/i + ] + }, + { + slug: 'competicoes', + patterns: [ + /\b(?:taça|taca|campeonato|liga|competiç(?:ão|ões)|competicoes)\b/i, + /\b(?:play-?offs?|wild card|champions league|european masters|mundial|world championship)\b/i, + /\b(?:ehf|ihf)\s+(?:cup|cl|final)\b/i + ] + }, + { + slug: 'clubes', + patterns: [ + /\b(?:fc porto|f\.?\s*c\.?\s*porto|porto)\b/i, + /\b(?:sl benfica|benfica)\b/i, + /\b(?:sporting cp|sporting)\b/i, + /\b(?:sc braga|vitória|marítimo|madeira andebol)\b/i + ] + }, + { + slug: 'internacional', + patterns: [ + /\b(?:internacional|international|mundial|world championship|euro(?:pean)?)\b/i, + /\b(?:ihf|eurohandball|handball planet)\b/i + ] + } +]; + +const DEFAULT_SLUG = 'nacional'; + +function hostFromUrl(url) { + if (!url || typeof url !== 'string') { + return ''; + } + try { + return new URL(url).hostname.toLowerCase(); + } catch { + return ''; + } +} + +function firstSourceHost(sources) { + if (!Array.isArray(sources) || sources.length === 0) { + return ''; + } + for (const src of sources) { + const host = hostFromUrl(src.url || src.link || ''); + if (host) { + return host; + } + } + return ''; +} + +function isInternationalSource(sourceUrl, sources) { + const host = hostFromUrl(sourceUrl) || firstSourceHost(sources); + if (!host) { + return false; + } + if (INTERNATIONAL_SOURCE_HOSTS.has(host)) { + return true; + } + return host.endsWith('.info') && host.includes('handball'); +} + +function normalizeText(parts) { + return parts + .filter((p) => typeof p === 'string' && p.trim().length > 0) + .join(' ') + .replace(/\s+/g, ' ') + .trim(); +} + +/** + * Infer editorial category slug for andebol.net-style sites. + * + * @param {Object} params + * @param {string} [params.title] + * @param {string} [params.body] + * @param {string} [params.summary] + * @param {string} [params.excerpt] + * @param {string} [params.sourceUrl] + * @param {Array<{url?: string, link?: string}>} [params.sources] + * @param {string} [params.sourceCategory] - RSS / pipeline category hint + * @returns {string} Category slug (nacional, internacional, selecao, clubes, competicoes, resultados) + */ +function inferAndebolCategorySlug({ + title = '', + body = '', + summary = '', + excerpt = '', + sourceUrl = '', + sources = [], + sourceCategory = '' +} = {}) { + const text = normalizeText([title, summary, excerpt, body]); + + if (sourceCategory && typeof sourceCategory === 'string') { + const hint = sourceCategory.trim().toLowerCase(); + if (['nacional', 'internacional', 'selecao', 'clubes', 'competicoes', 'resultados'].includes(hint)) { + return hint; + } + if (hint === 'international' || hint === 'en') { + return 'internacional'; + } + } + + if (isInternationalSource(sourceUrl, sources) && !/\bportugal\b/i.test(text)) { + return 'internacional'; + } + + for (const rule of RULES) { + if (rule.patterns.some((re) => re.test(text))) { + return rule.slug; + } + } + + return DEFAULT_SLUG; +} + +module.exports = { + inferAndebolCategorySlug, + DEFAULT_SLUG, + INTERNATIONAL_SOURCE_HOSTS, + RULES +}; diff --git a/src/publisher/category-infer.test.js b/src/publisher/category-infer.test.js new file mode 100644 index 0000000..6be240d --- /dev/null +++ b/src/publisher/category-infer.test.js @@ -0,0 +1,55 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const test = require('node:test'); +const { inferAndebolCategorySlug } = require('../publisher/category-infer'); + +test('inferAndebolCategorySlug — seleção nacional', () => { + const slug = inferAndebolCategorySlug({ + title: 'Seleção Nacional vence França no Torneio 4 Nações', + summary: 'Portugal soma primeira vitória na competição.' + }); + assert.equal(slug, 'selecao'); +}); + +test('inferAndebolCategorySlug — clubes', () => { + const slug = inferAndebolCategorySlug({ + title: 'Carlos Martingo é o novo treinador de andebol do FC Porto', + summary: 'Clube azul e branco anuncia contratação.' + }); + assert.equal(slug, 'clubes'); +}); + +test('inferAndebolCategorySlug — competicoes', () => { + const slug = inferAndebolCategorySlug({ + title: 'Liga dos Campeões 2026/27: 27 clubes registados', + summary: 'EHF confirma lista de participantes.' + }); + assert.equal(slug, 'competicoes'); +}); + +test('inferAndebolCategorySlug — internacional from source host', () => { + const slug = inferAndebolCategorySlug({ + title: 'EHF announces new format for club competitions', + summary: 'Changes apply from next season.', + sourceUrl: 'https://www.eurohandball.com/en/news/123' + }); + assert.equal(slug, 'internacional'); +}); + +test('inferAndebolCategorySlug — nacional default for PT domestic', () => { + const slug = inferAndebolCategorySlug({ + title: 'Festa do Andebol regressa a Lagoa', + summary: 'Evento junta seleções regionais sub-14.', + sourceUrl: 'https://portal.fpa.pt/2026/06/festa-do-andebol/' + }); + assert.equal(slug, 'nacional'); +}); + +test('inferAndebolCategorySlug — honors explicit sourceCategory hint', () => { + const slug = inferAndebolCategorySlug({ + title: 'Generic headline', + sourceCategory: 'resultados' + }); + assert.equal(slug, 'resultados'); +}); diff --git a/src/publisher/wordpress.js b/src/publisher/wordpress.js index 1011cc1..ac6849c 100644 --- a/src/publisher/wordpress.js +++ b/src/publisher/wordpress.js @@ -7,6 +7,8 @@ const HttpRetryConfig = require('../util/http-retry-config'); const { resolveWpTransport } = require('./wp-transport'); const { publishArticleXmlRpc, testConnectionXmlRpc } = require('./xmlrpc-client'); const { resolveWpStatus } = require('./wp-publish-hours'); +const { resolvePostCategoryIds } = require('./wp-categories'); +const { sanitizeArticleMeta } = require('./article-meta'); const { metrics } = require('../monitoring/metrics'); function wpRestDraftFallbackEnabled() { @@ -34,10 +36,11 @@ function wpOriginForLogs(wp_url) { * @returns {Promise} WordPress post object on success */ async function publishToWordPress(article, site_config, publishHours) { + const sanitized = sanitizeArticleMeta(article, site_config); if (resolveWpTransport(site_config) === 'xmlrpc') { - return publishArticleXmlRpc(article, site_config, publishHours); + return publishArticleXmlRpc(sanitized, site_config, publishHours); } - return publishToWordPressRest(article, site_config, publishHours); + return publishToWordPressRest(sanitized, site_config, publishHours); } /** @@ -58,17 +61,20 @@ async function publishToWordPressRest(article, site_config, publishHours) { const credentials = Buffer.from(`${user}:${password}`).toString('base64'); const api_base = `${wp_url.replace(/\/$/, '')}/wp-json/wp/v2`; + const category_ids = await resolvePostCategoryIds(article, site_config, api_base, credentials); + const post_payload = { title: article.title, content: article.body, excerpt: article.summary, slug: article.slug, status: status_default, - categories: category_default ? [category_default] : [], + categories: category_ids.length > 0 ? category_ids : (category_default ? [category_default] : []), tags: [], meta: { _yoast_wpseo_title: article.seo_title, - _yoast_wpseo_metadesc: article.seo_description + _yoast_wpseo_metadesc: article.seo_description, + _yoast_wpseo_focuskw: article.focus_keyword || undefined } }; @@ -206,4 +212,4 @@ async function testConnection(site_config) { return { ok: true, user_info: response.data }; } -module.exports = { publishToWordPress, testConnection, resolveWpStatus }; +module.exports = { publishToWordPress, testConnection, resolveWpStatus, resolveTagIds }; diff --git a/src/publisher/wp-categories.js b/src/publisher/wp-categories.js new file mode 100644 index 0000000..3176e0f --- /dev/null +++ b/src/publisher/wp-categories.js @@ -0,0 +1,118 @@ +'use strict'; + +const logger = require('../logger'); +const { axiosGetWithRetry } = require('../util/http-retry'); +const HttpRetryConfig = require('../util/http-retry-config'); +const { inferAndebolCategorySlug } = require('./category-infer'); + +function authHeaders(credentials, siteDomain) { + const headers = { + Authorization: `Basic ${credentials}`, + Accept: 'application/json' + }; + if (siteDomain) { + headers['X-Site-Domain'] = siteDomain; + } + return headers; +} + +/** + * @param {string} slug + * @param {string} api_base + * @param {string} credentials + * @param {string|undefined} siteDomain + * @returns {Promise} + */ +async function resolveCategoryIdBySlug(slug, api_base, credentials, siteDomain) { + if (!slug || typeof slug !== 'string') { + return null; + } + const normalized = slug.trim().toLowerCase(); + if (!normalized) { + return null; + } + + const retry_opts = HttpRetryConfig.forWordPress().toRetryOpts(); + try { + const response = await axiosGetWithRetry( + `${api_base}/categories?slug=${encodeURIComponent(normalized)}&per_page=1`, + { headers: authHeaders(credentials, siteDomain), timeout: 8000 }, + { ...retry_opts, urlHint: `category slug "${normalized}"` } + ); + const rows = Array.isArray(response.data) ? response.data : []; + const id = rows[0]?.id; + return Number.isInteger(id) && id > 0 ? id : null; + } catch (err) { + logger.warn(`Category lookup failed for slug "${normalized}": ${err.message}`); + return null; + } +} + +function mappedCategoryId(siteConfig, slug) { + const map = siteConfig?.category_map; + if (!map || typeof map !== 'object') { + return null; + } + const entry = map[slug] ?? map[slug?.toLowerCase?.()]; + if (entry === undefined || entry === null) { + return null; + } + const id = parseInt(String(entry), 10); + return Number.isFinite(id) && id > 0 ? id : null; +} + +/** + * Resolve WordPress category IDs for a generated article. + * + * Priority: category_map → slug lookup via WP API → category_default. + * + * @param {Object} article + * @param {Object} siteConfig + * @param {string} api_base - e.g. https://site/wp-json/wp/v2 + * @param {string} credentials - base64 basic auth + * @returns {Promise} + */ +async function resolvePostCategoryIds(article, siteConfig, api_base, credentials) { + const siteDomain = siteConfig?.site_domain || siteConfig?.wp_site_domain; + const inferMode = siteConfig?.category_infer; + let slug = null; + + if (inferMode === 'andebol') { + slug = inferAndebolCategorySlug({ + title: article?.title, + body: article?.body, + summary: article?.summary, + sourceUrl: article?.source_url, + sources: article?.sources, + sourceCategory: article?.category + }); + } else if (typeof article?.category === 'string' && article.category.trim()) { + slug = article.category.trim().toLowerCase(); + } + + if (slug) { + const mapped = mappedCategoryId(siteConfig, slug); + if (mapped) { + return [mapped]; + } + const resolved = await resolveCategoryIdBySlug(slug, api_base, credentials, siteDomain); + if (resolved) { + return [resolved]; + } + logger.warn(`WP category slug "${slug}" not found — falling back to category_default`); + } + + const fallback = siteConfig?.category_default; + const fallbackId = parseInt(String(fallback ?? ''), 10); + if (Number.isFinite(fallbackId) && fallbackId > 0) { + return [fallbackId]; + } + + return []; +} + +module.exports = { + resolvePostCategoryIds, + resolveCategoryIdBySlug, + mappedCategoryId +}; diff --git a/src/publisher/wp-categories.test.js b/src/publisher/wp-categories.test.js new file mode 100644 index 0000000..cc897e0 --- /dev/null +++ b/src/publisher/wp-categories.test.js @@ -0,0 +1,33 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const test = require('node:test'); +const { mappedCategoryId } = require('./wp-categories'); + +test('mappedCategoryId returns id from exact slug match', () => { + const site = { category_map: { nacional: 1, internacional: 2 } }; + assert.equal(mappedCategoryId(site, 'nacional'), 1); + assert.equal(mappedCategoryId(site, 'internacional'), 2); +}); + +test('mappedCategoryId returns null for missing slug', () => { + const site = { category_map: { nacional: 1 } }; + assert.equal(mappedCategoryId(site, 'selecao'), null); +}); + +test('mappedCategoryId returns null when category_map is absent', () => { + assert.equal(mappedCategoryId({}, 'nacional'), null); + assert.equal(mappedCategoryId(null, 'nacional'), null); +}); + +test('mappedCategoryId rejects non-positive values', () => { + const site = { category_map: { bad: 0, alsobad: -5, fine: 3 } }; + assert.equal(mappedCategoryId(site, 'bad'), null); + assert.equal(mappedCategoryId(site, 'alsobad'), null); + assert.equal(mappedCategoryId(site, 'fine'), 3); +}); + +test('mappedCategoryId falls back to lowercase key lookup', () => { + const site = { category_map: { selecao: 3 } }; + assert.equal(mappedCategoryId(site, 'SELECAO'), 3); +}); diff --git a/src/publisher/xmlrpc-client.js b/src/publisher/xmlrpc-client.js index 93f27ea..db2fba2 100644 --- a/src/publisher/xmlrpc-client.js +++ b/src/publisher/xmlrpc-client.js @@ -5,6 +5,7 @@ const logger = require('../logger'); const { axiosPostWithRetry } = require('../util/http-retry'); const HttpRetryConfig = require('../util/http-retry-config'); const { resolveWpStatus } = require('./wp-publish-hours'); +const { resolvePostCategoryIds } = require('./wp-categories'); const { metrics } = require('../monitoring/metrics'); /** @@ -258,6 +259,9 @@ async function publishArticleXmlRpc(article, site_config, publishHours) { if (article.seo_description) { custom_fields.push({ key: '_yoast_wpseo_metadesc', value: String(article.seo_description) }); } + if (article.focus_keyword) { + custom_fields.push({ key: '_yoast_wpseo_focuskw', value: String(article.focus_keyword) }); + } const content = { post_type: 'post', @@ -272,11 +276,17 @@ async function publishArticleXmlRpc(article, site_config, publishHours) { content.terms_names = { post_tag: tag_list }; } - if (category_default) { - const cid = parseInt(String(category_default), 10); - if (Number.isFinite(cid) && cid > 0) { - content.terms = { category: [cid] }; - } + const api_base = `${wp_url.replace(/\/$/, '')}/wp-json/wp/v2`; + const credentials = Buffer.from(`${user}:${password}`).toString('base64'); + const category_ids = await resolvePostCategoryIds(article, site_config, api_base, credentials); + const effective_ids = category_ids.length > 0 + ? category_ids + : (() => { + const cid = parseInt(String(category_default), 10); + return Number.isFinite(cid) && cid > 0 ? [cid] : []; + })(); + if (effective_ids.length > 0) { + content.terms = { category: effective_ids }; } if (custom_fields.length > 0) { diff --git a/src/publisher/xmlrpc-client.test.js b/src/publisher/xmlrpc-client.test.js index a4390d0..79045c8 100644 --- a/src/publisher/xmlrpc-client.test.js +++ b/src/publisher/xmlrpc-client.test.js @@ -105,7 +105,8 @@ test('publishArticleXmlRpc — stub wp.newPost', async () => { user: 'u', password: 'p', category_default: 2, - status_default: 'draft' + status_default: 'draft', + category_map: { nacional: 2 } }; const out = await publishArticleXmlRpc(article, site); assert.equal(out.id, '1001'); diff --git a/src/writer/ai.js b/src/writer/ai.js index 874aac9..33aaa06 100644 --- a/src/writer/ai.js +++ b/src/writer/ai.js @@ -140,7 +140,12 @@ Return a JSON object with these exact keys: "tags": ["tag1", "tag2", "tag3"], "category": "${category}", "seo_title": "SEO optimized title (max 60 chars)", - "seo_description": "meta description (max 155 chars)", + "seo_description": "meta description (max 155 chars) — must summarize ONLY facts in the article body", + +TAG RULES (critical): +- Tags must be names, teams, or competitions that appear verbatim in your article title or body. +- Do NOT tag athletes, clubs, or events that you did not mention in the article. +- Prefer 3-6 short tags (teams, competitions, key people actually named in the text). "used_sources": [1, 2, 3] // Array of source indices (1-based) that were cited in the article }`; diff --git a/tools/backfill-wp-categories.js b/tools/backfill-wp-categories.js new file mode 100644 index 0000000..5860e59 --- /dev/null +++ b/tools/backfill-wp-categories.js @@ -0,0 +1,132 @@ +#!/usr/bin/env node +'use strict'; + +/** + * Backfill WordPress post categories on andebol.net (or any site in config/sites/). + * + * Usage: + * node tools/backfill-wp-categories.js --site andebol.net.example.json --dry-run + * node tools/backfill-wp-categories.js --site andebol.net.json --limit 50 + * + * Requires WP credentials in the site JSON or WP_URL / WP_USER / WP_PASSWORD env vars. + */ + +require('dotenv').config(); + +const fs = require('fs'); +const path = require('path'); +const axios = require('axios'); +const { inferAndebolCategorySlug } = require('../src/publisher/category-infer'); +const { mappedCategoryId, resolveCategoryIdBySlug } = require('../src/publisher/wp-categories'); + +const ROOT = path.resolve(__dirname, '..'); + +function parseArgs(argv) { + const out = { dryRun: false, limit: 100, siteFile: null }; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === '--dry-run') out.dryRun = true; + else if (arg === '--limit' && argv[i + 1]) out.limit = parseInt(argv[++i], 10); + else if (arg === '--site' && argv[i + 1]) out.siteFile = argv[++i]; + } + return out; +} + +function loadSiteConfig(siteFile) { + const sitesDir = path.join(ROOT, 'config', 'sites'); + const filename = siteFile.endsWith('.json') ? siteFile : `${siteFile}.json`; + const fullPath = path.join(sitesDir, filename); + if (!fs.existsSync(fullPath)) { + throw new Error(`Site config not found: ${fullPath}`); + } + return JSON.parse(fs.readFileSync(fullPath, 'utf8')); +} + +async function resolveSlugToId(slug, site, apiBase, credentials) { + const mapped = mappedCategoryId(site, slug); + if (mapped) return mapped; + return resolveCategoryIdBySlug(slug, apiBase, credentials, site.site_domain || site.wp_site_domain); +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + if (!args.siteFile) { + console.error('Usage: node tools/backfill-wp-categories.js --site [--dry-run] [--limit N]'); + process.exit(1); + } + + const site = loadSiteConfig(args.siteFile); + const wpUrl = site.wp_url || process.env.WP_URL; + const user = site.user || process.env.WP_USER; + const password = site.password || process.env.WP_PASSWORD; + if (!wpUrl || !user || !password) { + throw new Error('Missing wp_url/user/password in site config or env'); + } + + const apiBase = `${wpUrl.replace(/\/$/, '').replace(/\/wp-json\/?$/, '')}/wp-json/wp/v2`; + const credentials = Buffer.from(`${user}:${password}`).toString('base64'); + const siteDomain = site.site_domain || site.wp_site_domain; + const headers = { + Authorization: `Basic ${credentials}`, + Accept: 'application/json', + 'Content-Type': 'application/json' + }; + if (siteDomain) headers['X-Site-Domain'] = siteDomain; + + const uncategorizedRes = await axios.get(`${apiBase}/categories`, { + params: { slug: 'uncategorized', per_page: 1 }, + headers, + timeout: 15000 + }); + const uncategorizedId = uncategorizedRes.data?.[0]?.id; + + const postsRes = await axios.get(`${apiBase}/posts`, { + params: { + per_page: Math.min(args.limit, 100), + status: 'publish,draft', + orderby: 'date', + order: 'desc', + _fields: 'id,title,content,excerpt,categories,link' + }, + headers, + timeout: 20000 + }); + + const posts = Array.isArray(postsRes.data) ? postsRes.data : []; + let patched = 0; + let skipped = 0; + + for (const post of posts) { + const cats = Array.isArray(post.categories) ? post.categories : []; + const onlyUncategorized = cats.length === 0 + || (cats.length === 1 && uncategorizedId && cats[0] === uncategorizedId); + if (!onlyUncategorized) { + skipped += 1; + continue; + } + + const title = post.title?.rendered || post.title || ''; + const body = post.content?.rendered || post.content || ''; + const excerpt = post.excerpt?.rendered || post.excerpt || ''; + const slug = inferAndebolCategorySlug({ title, body, summary: excerpt, excerpt }); + const categoryId = await resolveSlugToId(slug, site, apiBase, credentials); + if (!categoryId) { + console.warn(`post ${post.id}: could not resolve slug "${slug}" — skip`); + skipped += 1; + continue; + } + + console.log(`${args.dryRun ? '[dry-run]' : 'patch'} post ${post.id} → ${slug} (${categoryId}) — ${title.slice(0, 60)}`); + if (!args.dryRun) { + await axios.post(`${apiBase}/posts/${post.id}`, { categories: [categoryId] }, { headers, timeout: 15000 }); + } + patched += 1; + } + + console.log(JSON.stringify({ scanned: posts.length, patched, skipped, dryRun: args.dryRun }, null, 2)); +} + +main().catch((err) => { + console.error(err.message || err); + process.exit(1); +}); diff --git a/tools/backfill-wp-meta.js b/tools/backfill-wp-meta.js new file mode 100644 index 0000000..24aaf54 --- /dev/null +++ b/tools/backfill-wp-meta.js @@ -0,0 +1,119 @@ +#!/usr/bin/env node +'use strict'; + +/** + * Backfill WordPress post tags and Yoast SEO meta on andebol.net. + * + * Usage: + * node tools/backfill-wp-meta.js --site andebol.net.example.json --dry-run + * node tools/backfill-wp-meta.js --site andebol.net.json --limit 50 + */ + +require('dotenv').config(); + +const fs = require('fs'); +const path = require('path'); +const axios = require('axios'); +const { sanitizeArticleMeta } = require('../src/publisher/article-meta'); +const { resolveTagIds } = require('../src/publisher/wordpress'); + +const ROOT = path.resolve(__dirname, '..'); + +function parseArgs(argv) { + const out = { dryRun: false, limit: 100, siteFile: null }; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === '--dry-run') out.dryRun = true; + else if (arg === '--limit' && argv[i + 1]) out.limit = parseInt(argv[++i], 10); + else if (arg === '--site' && argv[i + 1]) out.siteFile = argv[++i]; + } + return out; +} + +function loadSiteConfig(siteFile) { + const sitesDir = path.join(ROOT, 'config', 'sites'); + const filename = siteFile.endsWith('.json') ? siteFile : `${siteFile}.json`; + const fullPath = path.join(sitesDir, filename); + if (!fs.existsSync(fullPath)) { + throw new Error(`Site config not found: ${fullPath}`); + } + return JSON.parse(fs.readFileSync(fullPath, 'utf8')); +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + if (!args.siteFile) { + console.error('Usage: node tools/backfill-wp-meta.js --site [--dry-run] [--limit N]'); + process.exit(1); + } + + const site = loadSiteConfig(args.siteFile); + const wpUrl = site.wp_url || process.env.WP_URL; + const user = site.user || process.env.WP_USER; + const password = site.password || process.env.WP_PASSWORD; + if (!wpUrl || !user || !password) { + throw new Error('Missing wp_url/user/password in site config or env'); + } + + const apiBase = `${wpUrl.replace(/\/$/, '').replace(/\/wp-json\/?$/, '')}/wp-json/wp/v2`; + const credentials = Buffer.from(`${user}:${password}`).toString('base64'); + const siteDomain = site.site_domain || site.wp_site_domain; + const headers = { + Authorization: `Basic ${credentials}`, + Accept: 'application/json', + 'Content-Type': 'application/json' + }; + if (siteDomain) headers['X-Site-Domain'] = siteDomain; + + const postsRes = await axios.get(`${apiBase}/posts`, { + params: { + per_page: Math.min(args.limit, 100), + status: 'publish,draft', + orderby: 'date', + order: 'desc', + _fields: 'id,title,content,excerpt,tags,meta,link' + }, + headers, + timeout: 20000 + }); + + const posts = Array.isArray(postsRes.data) ? postsRes.data : []; + let patched = 0; + let skipped = 0; + + for (const post of posts) { + const title = post.title?.rendered || post.title || ''; + const body = post.content?.rendered || post.content || ''; + const excerpt = post.excerpt?.rendered || post.excerpt || ''; + + const sanitized = sanitizeArticleMeta({ + title, + body, + summary: excerpt, + tags: [] + }, site); + + const tagIds = await resolveTagIds(sanitized.tags, apiBase, credentials); + const payload = { + tags: tagIds, + meta: { + _yoast_wpseo_title: sanitized.seo_title, + _yoast_wpseo_metadesc: sanitized.seo_description, + _yoast_wpseo_focuskw: sanitized.focus_keyword + } + }; + + console.log(`${args.dryRun ? '[dry-run]' : 'patch'} post ${post.id} tags=${sanitized.tags.join(', ')} focus=${sanitized.focus_keyword}`); + if (!args.dryRun) { + await axios.post(`${apiBase}/posts/${post.id}`, payload, { headers, timeout: 15000 }); + } + patched += 1; + } + + console.log(JSON.stringify({ scanned: posts.length, patched, skipped, dryRun: args.dryRun }, null, 2)); +} + +main().catch((err) => { + console.error(err.message || err); + process.exit(1); +});