feat(ai): tone and audience controls per publication (BIT-3599)

Add config/writing-style.json (UI /ui/writing-style), resolveWritingParams,
and wire generateArticle for write and listen modes. Document optional
site JSON keys in config/sites/example.json.

Paperclip-Issue: BIT-3599
Paperclip-Run: 8e0126ab-909d-4548-b1ca-fbf1d660134c
This commit is contained in:
Xika (Agent) committed 2026-04-17 20:36:53 +00:00
1 parent 98a91bebf1
commit 42f22b3a5a
8 files changed
+429 -6

No files matched your search

+2
View File
@@ -1,5 +1,7 @@
{
"name": "sports news",
"writing_tone": "formal",
"audience_level": "general",
"wp_transport": "rest",
"wp_url": "https://wp.newsproject.bitreport.pt",
"user": "wp-api-user",
+12
View File
@@ -0,0 +1,12 @@
{
"default": {
"tone": "formal",
"audience_level": "general"
},
"by_site_name": {
"sports news": {
"tone": "casual",
"audience_level": "informed"
}
}
}
+214
View File
@@ -0,0 +1,214 @@
'use strict';
const fs = require('fs');
const path = require('path');
const logger = require('../logger');
const ROOT = path.resolve(__dirname, '..', '..');
const WRITING_STYLE_PATH = path.join(ROOT, 'config', 'writing-style.json');
function getWritingStylePath() {
const override = (process.env.WRITING_STYLE_CONFIG_PATH || '').trim();
return override ? path.resolve(override) : WRITING_STYLE_PATH;
}
const VALID_TONES = ['formal', 'casual', 'technical'];
const VALID_AUDIENCE_LEVELS = ['general', 'informed', 'expert'];
function normalizeTone(raw) {
const s = String(raw || '').trim().toLowerCase();
return VALID_TONES.includes(s) ? s : 'formal';
}
function normalizeAudienceLevel(raw) {
const s = String(raw || '').trim().toLowerCase();
return VALID_AUDIENCE_LEVELS.includes(s) ? s : 'general';
}
/**
* @returns {{ default: { tone: string, audience_level: string }, by_site_name: Record<string, { tone?: string, audience_level?: string }> }}
*/
function loadWritingStyleFile() {
const empty = {
default: { tone: 'formal', audience_level: 'general' },
by_site_name: {}
};
const cfgPath = getWritingStylePath();
if (!fs.existsSync(cfgPath)) {
return empty;
}
try {
const loaded = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
const def = loaded.default && typeof loaded.default === 'object' ? loaded.default : {};
const bySite =
loaded.by_site_name && typeof loaded.by_site_name === 'object' && !Array.isArray(loaded.by_site_name)
? loaded.by_site_name
: {};
return {
default: {
tone: normalizeTone(def.tone),
audience_level: normalizeAudienceLevel(def.audience_level)
},
by_site_name: bySite
};
} catch (err) {
logger.error(`config/writing-style.json invalid — using builtins: ${err.message}`);
return empty;
}
}
/**
* Merge order: optional fields on `site` JSON → per-publication map in writing-style.json → file default → env → builtins.
*
* @param {{ name?: string, writing_tone?: string, audience_level?: string } | null | undefined} site
* @returns {{ tone: string, audience_level: string }}
*/
function resolveWritingParams(site) {
const file = loadWritingStyleFile();
const fromFileDefault = file.default || { tone: 'formal', audience_level: 'general' };
let tone = normalizeTone(fromFileDefault.tone);
let audience_level = normalizeAudienceLevel(fromFileDefault.audience_level);
const envTone = (process.env.WRITING_TONE || '').trim();
const envAud = (process.env.AUDIENCE_LEVEL || '').trim();
if (envTone) {
tone = normalizeTone(envTone);
}
if (envAud) {
audience_level = normalizeAudienceLevel(envAud);
}
const name = site && typeof site.name === 'string' ? site.name.trim() : '';
if (name && file.by_site_name && typeof file.by_site_name[name] === 'object') {
const row = file.by_site_name[name];
if (row && row.tone !== undefined && row.tone !== null && String(row.tone).trim() !== '') {
tone = normalizeTone(row.tone);
}
if (row && row.audience_level !== undefined && row.audience_level !== null && String(row.audience_level).trim() !== '') {
audience_level = normalizeAudienceLevel(row.audience_level);
}
}
if (site && typeof site === 'object') {
if (site.writing_tone !== undefined && site.writing_tone !== null && String(site.writing_tone).trim() !== '') {
tone = normalizeTone(site.writing_tone);
}
if (site.audience_level !== undefined && site.audience_level !== null && String(site.audience_level).trim() !== '') {
audience_level = normalizeAudienceLevel(site.audience_level);
}
}
return { tone, audience_level };
}
function validateWritingStylePayload(obj) {
if (!obj || typeof obj !== 'object') {
throw new Error('JSON inválido: raiz tem de ser um objeto');
}
const def = obj.default;
if (!def || typeof def !== 'object') {
throw new Error('Falta o objeto default com tone e audience_level');
}
if (def.tone !== undefined && def.tone !== null && String(def.tone).trim() !== '') {
const t = String(def.tone).trim().toLowerCase();
if (!VALID_TONES.includes(t)) {
throw new Error(`tone inválido em default: "${def.tone}" (${VALID_TONES.join(', ')})`);
}
}
if (def.audience_level !== undefined && def.audience_level !== null && String(def.audience_level).trim() !== '') {
const a = String(def.audience_level).trim().toLowerCase();
if (!VALID_AUDIENCE_LEVELS.includes(a)) {
throw new Error(`audience_level inválido em default: "${def.audience_level}" (${VALID_AUDIENCE_LEVELS.join(', ')})`);
}
}
const by = obj.by_site_name;
if (by !== undefined && by !== null) {
if (typeof by !== 'object' || Array.isArray(by)) {
throw new Error('by_site_name tem de ser um objecto (mapa nome → definições)');
}
for (const [pub, row] of Object.entries(by)) {
if (!pub || typeof pub !== 'string' || !pub.trim()) {
throw new Error('Chaves em by_site_name têm de ser nomes de publicação não vazios');
}
if (!row || typeof row !== 'object' || Array.isArray(row)) {
throw new Error(`by_site_name["${pub}"] tem de ser um objecto`);
}
if (row.tone !== undefined && row.tone !== null && String(row.tone).trim() !== '') {
if (!VALID_TONES.includes(String(row.tone).trim().toLowerCase())) {
throw new Error(`tone inválido para "${pub}": "${row.tone}"`);
}
}
if (row.audience_level !== undefined && row.audience_level !== null && String(row.audience_level).trim() !== '') {
if (!VALID_AUDIENCE_LEVELS.includes(String(row.audience_level).trim().toLowerCase())) {
throw new Error(`audience_level inválido para "${pub}": "${row.audience_level}"`);
}
}
}
}
}
function buildWritingStylePayloadFromForm(params) {
const default_tone = normalizeTone(params.get('default_tone'));
const default_audience = normalizeAudienceLevel(params.get('default_audience'));
const by_site_name = {};
for (const [k, v] of params.entries()) {
if (!k.startsWith('tone__')) {
continue;
}
const encName = k.slice('tone__'.length);
if (!encName) {
continue;
}
let pub;
try {
pub = decodeURIComponent(encName);
} catch (_err) {
continue;
}
const tone = normalizeTone(v);
const audKey = `audience__${encName}`;
const audience_level = normalizeAudienceLevel(params.get(audKey) || 'general');
by_site_name[pub] = { tone, audience_level };
}
return {
default: { tone: default_tone, audience_level: default_audience },
by_site_name
};
}
function toneInstruction(tone) {
switch (normalizeTone(tone)) {
case 'casual':
return 'Use a conversational, approachable tone while staying accurate and neutral. Short paragraphs where natural.';
case 'technical':
return 'Use precise terminology appropriate for specialists; define acronyms on first use. Keep neutrality; no hype.';
default:
return 'Use a formal, newsroom-neutral register (no slang, no first-person editorializing).';
}
}
function audienceInstruction(level) {
switch (normalizeAudienceLevel(level)) {
case 'informed':
return 'Target readers who follow the beat: you may assume familiarity with major teams, leagues, and recurring storylines, but still explain non-obvious implications briefly.';
case 'expert':
return 'Target expert readers: you may use domain shorthand and deeper context, still without speculation beyond sources.';
default:
return 'Target a general audience: explain specialist terms briefly, avoid unexplained jargon, keep sentences clear.';
}
}
module.exports = {
WRITING_STYLE_PATH,
getWritingStylePath,
VALID_TONES,
VALID_AUDIENCE_LEVELS,
loadWritingStyleFile,
resolveWritingParams,
validateWritingStylePayload,
buildWritingStylePayloadFromForm,
normalizeTone,
normalizeAudienceLevel,
toneInstruction,
audienceInstruction
};
+72
View File
@@ -0,0 +1,72 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const path = require('path');
const fs = require('fs');
const os = require('os');
const {
buildWritingStylePayloadFromForm,
validateWritingStylePayload,
normalizeTone,
toneInstruction,
resolveWritingParams
} = require('./writing-style');
test('normalizeTone falls back for unknown', () => {
assert.equal(normalizeTone('fancy'), 'formal');
assert.equal(normalizeTone('CASUAL'), 'casual');
});
test('toneInstruction covers presets', () => {
assert.match(toneInstruction('technical'), /terminology/i);
assert.match(toneInstruction('casual'), /conversational/i);
});
test('resolveWritingParams prefers site JSON over file map', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wnw-style-'));
const wsPath = path.join(dir, 'writing-style.json');
fs.writeFileSync(
wsPath,
JSON.stringify({
default: { tone: 'formal', audience_level: 'general' },
by_site_name: { 'pub-a': { tone: 'casual', audience_level: 'general' } }
}),
'utf8'
);
const prev = process.env.WRITING_STYLE_CONFIG_PATH;
process.env.WRITING_STYLE_CONFIG_PATH = wsPath;
try {
const fromFile = resolveWritingParams({ name: 'pub-a' });
assert.equal(fromFile.tone, 'casual');
const siteOverride = resolveWritingParams({
name: 'pub-a',
writing_tone: 'technical',
audience_level: 'expert'
});
assert.equal(siteOverride.tone, 'technical');
assert.equal(siteOverride.audience_level, 'expert');
} finally {
if (prev === undefined) {
delete process.env.WRITING_STYLE_CONFIG_PATH;
} else {
process.env.WRITING_STYLE_CONFIG_PATH = prev;
}
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('buildWritingStylePayloadFromForm + validate', () => {
const p = new URLSearchParams();
p.set('default_tone', 'casual');
p.set('default_audience', 'informed');
p.set(`tone__${encodeURIComponent('Site One')}`, 'technical');
p.set(`audience__${encodeURIComponent('Site One')}`, 'expert');
const obj = buildWritingStylePayloadFromForm(p);
validateWritingStylePayload(obj);
assert.equal(obj.default.tone, 'casual');
assert.equal(obj.by_site_name['Site One'].tone, 'technical');
assert.equal(obj.by_site_name['Site One'].audience_level, 'expert');
});
+2 -1
View File
@@ -247,7 +247,7 @@ function buildLandingHtml() {
<section>
<h2>UI simples (admin)</h2>
<p style="margin:0">Listagem de títulos gerados, edição de <code>sources.json</code>, queries X, tema e vista só de leitura dos publishers: <a href="/ui"><strong>/ui</strong></a>. Gravações exigem <code>ADMIN_TOKEN</code> no servidor.</p>
<p style="margin:0">Listagem de títulos gerados, edição de <code>sources.json</code>, queries X, tom/audiência por publicação, tema e vista só de leitura dos publishers: <a href="/ui"><strong>/ui</strong></a>. Gravações exigem <code>ADMIN_TOKEN</code> no servidor.</p>
</section>
<section>
@@ -258,6 +258,7 @@ function buildLandingHtml() {
<li><code>GET, HEAD /health</code> — JSON de estado incl. <code>metrics_summary</code> (HEAD sem corpo)</li>
<li><code>GET, HEAD /metrics</code> — métricas (JSON por omissão; Prometheus: <code>?format=prometheus</code> ou <code>Accept:</code> openmetrics / text 0.0.4)</li>
<li><code>GET /ui</code> — painel simples</li>
<li><code>GET /ui/writing-style</code> — tom e audiência (IA) por publicação</li>
<li><code>GET /api/ui/articles</code> — JSON dos títulos registados</li>
</ul>
</section>
+108 -1
View File
@@ -7,6 +7,14 @@ const { mergeResponseHeaders } = require('./security-headers');
const { parseBodyReadTimeoutMs } = require('./body-read-timeout');
const { isAllowedAdminFormContentType } = require('./ui-form-post');
const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadSocialConfig } = require('../config/loader');
const {
getWritingStylePath,
loadWritingStyleFile,
validateWritingStylePayload,
buildWritingStylePayloadFromForm,
VALID_TONES,
VALID_AUDIENCE_LEVELS
} = require('../config/writing-style');
const { resolveWpTransport } = require('../publisher/wp-transport');
const { readLastArticles, updateArticleStatus, updateArticleMetadata, validateSlugUniqueness, articleRowId } = require('../store/article-log');
const { parseDomain } = require('../util/domain');
@@ -272,6 +280,7 @@ function layout(title, innerHtml, theme) {
<a href="/ui/sources">Fontes &amp; keywords</a>
<a href="/ui/social">X / social</a>
<a href="/ui/publishers">Publishers</a>
<a href="/ui/writing-style">Tom / audiência</a>
<a href="/ui/theme">Tema</a>
<a href="/">Ops</a>
<a href="/health">Health</a>
@@ -647,6 +656,67 @@ ${msg ? `<p class="${msg.type === 'err' ? 'err' : 'ok'}">${escapeHtml(msg.text)}
return layout('Fontes', inner, theme);
}
function selectOptionsHtml(selected, values) {
return values
.map((v) => `<option value="${escapeHtml(v)}"${v === selected ? ' selected' : ''}>${escapeHtml(v)}</option>`)
.join('');
}
function pageWritingStyle(theme, msg) {
const file = loadWritingStyleFile();
const sites = loadSiteConfigs();
const tokenSet = !!getAdminToken();
const defTone = file.default.tone;
const defAud = file.default.audience_level;
const toneOpts = selectOptionsHtml(defTone, VALID_TONES);
const audOpts = selectOptionsHtml(defAud, VALID_AUDIENCE_LEVELS);
let perSiteRows = '';
for (const s of sites) {
const name = s.name || '—';
const enc = encodeURIComponent(name);
const row = (file.by_site_name && file.by_site_name[name]) || {};
const t = row.tone ? String(row.tone).toLowerCase() : defTone;
const a = row.audience_level ? String(row.audience_level).toLowerCase() : defAud;
perSiteRows += `<tr>
<td>${escapeHtml(name)}</td>
<td><select id="tone__${escapeHtml(enc)}" name="tone__${escapeHtml(enc)}" aria-label="Tom para ${escapeHtml(name)}">${selectOptionsHtml(t, VALID_TONES)}</select></td>
<td><select name="audience__${escapeHtml(enc)}" aria-label="Audiência para ${escapeHtml(name)}">${selectOptionsHtml(a, VALID_AUDIENCE_LEVELS)}</select></td>
</tr>`;
}
const noSitesNote =
sites.length === 0
? '<p class="note">Não há ficheiros em <code>config/sites/*.json</code> — só os valores <strong>predefinidos</strong> abaixo se aplicam (publicação <code>default</code> no modo env).</p>'
: '';
const inner = `<h1>Tom e audiência (IA)</h1>
<p class="note">Grava <code>config/writing-style.json</code>. Os valores entram no prompt do modelo em <code>generateArticle</code> (modo <code>write</code> e <code>listen</code>). Opcionalmente pode definir <code>writing_tone</code> / <code>audience_level</code> directamente no JSON do site (têm prioridade sobre esta página).</p>
<p class="note">Variáveis de ambiente <code>WRITING_TONE</code> e <code>AUDIENCE_LEVEL</code> substituem o <strong>default</strong> do ficheiro; por publicação, esta página (<code>by_site_name</code>) ou campos <code>writing_tone</code> / <code>audience_level</code> no JSON do site prevalecem sobre o ambiente.</p>
${noSitesNote}
${msg ? `<p class="${msg.type === 'err' ? 'err' : 'ok'}">${escapeHtml(msg.text)}</p>` : ''}
<form method="post" action="/ui/writing-style">
<h2 style="font-size:1.05rem;margin-top:0">Predefinição global (ficheiro)</h2>
<label for="default_tone">Tom</label>
<select id="default_tone" name="default_tone" ${tokenSet ? '' : 'disabled'}>${toneOpts}</select>
<label for="default_audience">Nível de audiência</label>
<select id="default_audience" name="default_audience" ${tokenSet ? '' : 'disabled'}>${audOpts}</select>
<p class="note"><strong>formal</strong> — registo neutro estilo redacção; <strong>casual</strong> — mais conversacional; <strong>technical</strong> — vocabulário de especialista. <strong>general</strong> / <strong>informed</strong> / <strong>expert</strong> — profundidade assumida do leitor.</p>
${
sites.length
? `<h2 style="font-size:1.05rem">Por publicação (<code>name</code> no JSON do site)</h2>
<table><thead><tr><th>Publicação</th><th>Tom</th><th>Audiência</th></tr></thead><tbody>${perSiteRows}</tbody></table>`
: ''
}
<label for="admin_token_ws">Token admin</label>
<input type="password" name="admin_token" id="admin_token_ws" autocomplete="off" ${tokenSet ? '' : 'disabled'} />
<p><button type="submit" class="btn" ${tokenSet ? '' : 'disabled'}>Guardar</button></p>
</form>
`;
return layout('Tom / audiência', inner, theme);
}
function pageSocial(theme, msg) {
const social = loadSocialConfig();
const payload = { x: { queries: social?.x?.queries || [], max_results_per_query: social?.x?.max_results_per_query || 10 } };
@@ -762,6 +832,13 @@ async function tryHandleAdminUi(req, res) {
return true;
}
if (req.method === 'GET' && pathname === '/ui/writing-style') {
const html = pageWritingStyle(theme, null);
res.writeHead(200, mergeResponseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) }));
res.end(html);
return true;
}
if (req.method === 'GET' && pathname === '/ui/theme') {
const html = pageTheme(theme, null);
res.writeHead(200, mergeResponseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) }));
@@ -783,7 +860,13 @@ async function tryHandleAdminUi(req, res) {
if (
req.method === 'POST' &&
(pathname === '/ui/sources' || pathname === '/ui/social' || pathname === '/ui/theme' || isArticleActionPost || isArticleMetadataEdit || isBulkTagAssign)
(pathname === '/ui/sources' ||
pathname === '/ui/social' ||
pathname === '/ui/theme' ||
pathname === '/ui/writing-style' ||
isArticleActionPost ||
isArticleMetadataEdit ||
isBulkTagAssign)
) {
if (!isAllowedAdminFormContentType(req)) {
logger.warn(`UI: rejected POST ${pathname} — unsupported Content-Type: ${String(req.headers['content-type'])}`);
@@ -1013,6 +1096,30 @@ async function tryHandleAdminUi(req, res) {
return true;
}
if (req.method === 'POST' && pathname === '/ui/writing-style') {
let msg = null;
try {
const raw = await collectBody(req);
const params = new URLSearchParams(raw.toString('utf8'));
const token = params.get('admin_token') || '';
if (!adminOk(req, token)) {
msg = { type: 'err', text: 'Token inválido ou ADMIN_TOKEN não configurado.' };
} else {
const payload = buildWritingStylePayloadFromForm(params);
validateWritingStylePayload(payload);
fs.writeFileSync(getWritingStylePath(), `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
logger.info('UI: config/writing-style.json updated');
msg = { type: 'ok', text: 'Guardado. A próxima geração de artigos usa estes valores (reinicie o listener se já estiver em execução, para releitura consistente).' };
}
} catch (err) {
msg = { type: 'err', text: err.message || String(err) };
}
const html = pageWritingStyle(loadUiTheme(), msg);
res.writeHead(200, mergeResponseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) }));
res.end(html);
return true;
}
return false;
}
+9 -2
View File
@@ -21,6 +21,7 @@ const {
loadSocialConfig,
loadPublishHours
} = require('./config/loader');
const { resolveWritingParams } = require('./config/writing-style');
const { probeXQueries } = require('./crawler/x');
const { setRssListenerActive } = require('./runtime/listen-state');
const { resolveAutoCronExpression } = require('./config/listen-defaults');
@@ -103,11 +104,14 @@ async function runManualWrite(topic) {
enrichCount: 3
});
const voice = resolveWritingParams(site);
const article = await generateArticle({
topic: topic || enriched_sources[0]?.title || 'Latest sports news',
sources: enriched_sources.length > 0 ? enriched_sources : enriched_sources.slice(0, 5),
category: sources_config.rss[0]?.category || 'sports',
lang: site.lang || 'en'
lang: site.lang || 'en',
tone: voice.tone,
audience_level: voice.audience_level
});
metrics.incrementCounter('articles.generated', 1);
@@ -316,11 +320,14 @@ async function runAutoMode() {
const relevant = filterByKeywords(new_articles, top_topic.keywords || []);
const sources = relevant.length > 0 ? relevant : new_articles.slice(0, 5);
const voice = resolveWritingParams(site);
const article = await generateArticle({
topic: top_topic.topic,
sources: sources.slice(0, 5),
category: sources[0]?.category || 'sports',
lang: site.lang || 'en'
lang: site.lang || 'en',
tone: voice.tone,
audience_level: voice.audience_level
});
metrics.incrementCounter('articles.generated', 1);
+10 -2
View File
@@ -3,6 +3,7 @@
const OpenAI = require('openai');
const logger = require('../logger');
const { metrics } = require('../monitoring/metrics');
const { toneInstruction, audienceInstruction } = require('../config/writing-style');
let _openai_client = null;
@@ -99,13 +100,18 @@ If information is uncertain, say "according to sources" or "reportedly".`;
* @param {Array} params.sources - Array of {title, text, url, source} objects
* @param {string} [params.category] - Article category (sports, technology, etc.)
* @param {string} [params.lang] - Output language code (pt, en)
* @param {string} [params.tone] - formal | casual | technical
* @param {string} [params.audience_level] - general | informed | expert
* @returns {Promise<Object>} Article output with title, subtitle, slug, body, summary, tags, seo_title, seo_description, category, sources, dominance_warning
*/
async function generateArticle({ topic, sources, category = 'sports', lang = 'en' }) {
async function generateArticle({ topic, sources, category = 'sports', lang = 'en', tone, audience_level }) {
const startTime = Date.now();
const client = getOpenAIClient();
const model = process.env.AI_MODEL || 'gpt-4o';
const style_block = `${toneInstruction(tone)}\n${audienceInstruction(audience_level)}`;
const system_prompt = `${JOURNALIST_SYSTEM_PROMPT}\n\nStyle and audience:\n${style_block}`;
const lang_instruction = lang === 'pt'
? 'Write the article in European Portuguese (Portugal).'
: `Write the article in ${lang}.`;
@@ -119,6 +125,8 @@ async function generateArticle({ topic, sources, category = 'sports', lang = 'en
Category: ${category}
${lang_instruction}
Editorial voice: apply the tone and audience level described in the system message for this run.
Sources:
${sources_text}
@@ -144,7 +152,7 @@ Return a JSON object with these exact keys:
client.chat.completions.create({
model,
messages: [
{ role: 'system', content: JOURNALIST_SYSTEM_PROMPT },
{ role: 'system', content: system_prompt },
{ role: 'user', content: user_prompt }
],
response_format: { type: 'json_object' },