spark 7020d88776
ai-news-writer-ci / test (pull_request) Successful in 51s
fix(deps): resolve high-severity npm audit findings, scope CI audit to prod deps
npm audit fix (non-breaking) clears axios, js-yaml, undici, brace-expansion
advisories. The one remaining high (braces, via nodemon->chokidar, dev-only)
has no non-breaking upgrade path and never ships; scope the CI gate to
--omit=dev so a dev-tooling transitive dep doesn't block merges that carry
no production risk. Matches the production-deps scoping already used in
paperclip-chat's CI.

Paperclip-Agent: Peter Spark (urlKey peter-spark; id 49ce66f8-6be6-4644-afd3-eb6d8d0d4b3e)
Paperclip-Issue: BIT-31604
Paperclip-Run: $PAPERCLIP_RUN_ID
2026-10-19 10:14:34 +01:00

AI News Writer

Autonomous news writing system for BitReport. Researches news from trusted sources, detects topics, and writes complete articles like a professional journalist — then exports to WordPress.

Paperclip issue: BIT-353 Gitea: https://git.bitreport.pt/BitReport.pt/ai-news-writer CI/CD: Gitea Actions — workflow ai-news-writer-ci (.gitea/workflows/test.yml); runs UI: https://git.bitreport.pt/BitReport.pt/ai-news-writer/actions Dev container: ai-news-writer-dev (planned CTID 223, VLAN 1050 — created only after you run tools/proxmox/create_ai_news_writer_lxc.sh on a Proxmox node) Domain: ainews.bitreport.pt (NPM configured manually)

CI/CD details (Gitea, not GitHub)

Forge automation lives under .gitea/workflows/ (Gitea Actions). Each push/PR to main, master, or develop runs npm ci, npm run lint, and npm test (Node’s built-in test runner under c8, with HTML + lcov coverage under coverage/).

  • Artifacts: the job uploads coverage/lcov.info as a downloadable workflow artifact.
  • Codecov (optional): set repository secret CODECOV_TOKEN in Gitea if you want uploads; if unset, the job still passes and keeps the artifact only.
  • Coverage thresholds: .nycrc.json keeps target percentages for reporting, but check-coverage is off until the suite exercises more of src/; CI still fails on test or lint errors.
  • Branch protection: after the first green run, org/repo admins should require the ai-news-writer-ci status check on protected branches (Gitea Settings → Branches).

Quick start

cp .env.example .env
# fill OPENAI_API_KEY in .env
npm install
node src/index.js write "FC Porto match result"

Commands

Command Description
npm run write Write one article (manual mode); merges RSS + X when social.json + bearer are set
npm run write -- "topic" Write article about specific topic
npm run listen Start auto RSS listener (cron)
npm run pm2:start PM2 via ecosystem.config.cjs (requires global pm2)
npm run deploy:lxc Server deploy: git pull --ff-only, npm ci --omit=dev, pm2 startOrReload ecosystem.config.cjs --update-env; append -- --with-ops-check for smoke tests
npm run verify:deploy -- <url> Smoke-test GET /health (expects listen mode); needs curl + node
npm run wp:test REST: GET /wp-json/wp/v2/users/me. XML-RPC: wp.getUsersBlogs when wp_transport or WP_TRANSPORT is xmlrpc. Same site selection as before.
npm run wp:probe-xmlrpc POST xmlrpc.php with system.listMethods — confirms XML-RPC is enabled (no credentials); same site selection as wp:test for wp_url
npm run rss:test Probe each RSS URL in config/sources.json (transient HTTP retries via HTTP_MAX_ATTEMPTS / HTTP_RETRY_BASE_MS, or legacy RSS_* vars); stdout { "ok", "feeds" }; exit 1 if any feed fails
npm run x:test X API v2 recent search for each x.queries[] in config/social.json; needs TWITTER_BEARER_TOKEN
npm run ops:check npm test first, then rss:test always; wp:test only if config/sites/*.json (≠ example) or WP_URL+WP_USER+WP_PASSWORD
npm start Same as write
npm run dev Auto-restart with nodemon

Web UI

Only when the app runs in listen mode (long-running service behind NPM):

Path Purpose
GET / Read-only ops landing page (version, uptime, RSS/X/WP flags — no secrets)
GET /dashboard Same as /
GET /health JSON for load balancers and monitoring
GET /ui Simple admin UI: table of generated article titles (from data/article-index.jsonl), nav to sources / social / publishers / theme
GET /ui/sources View or edit config/sources.json (needs ADMIN_TOKEN to save)
GET /ui/social View or edit config/social.json (X queries only; bearer stays in .env)
GET /ui/publishers Read-only WordPress targets (no passwords shown)
GET /ui/theme View or edit config/ui-theme.json (title + accent colour)
POST /ui/articles/:id/approve Set editorial_status to approved (ADMIN_TOKEN required) — :id is URL-encoded slug, or ISO at when slug is empty
POST /ui/articles/:id/reject Set editorial_status to rejected (ADMIN_TOKEN required)
GET /api/ui/articles?limit=50 JSON list of logged articles (includes editorial_status on new rows; restrict NPM access if sensitive)

Set ADMIN_TOKEN in .env to enable saving from the browser forms and editorial actions. Without it, pages are read-only except viewing states. POST /ui/* saves must use Content-Type: application/x-www-form-urlencoded (browser default); other types get 415. Protect /ui at the reverse proxy (VPN, SSO, IP allowlist) in production — this is a functional stopgap, not a hardened CMS. Approve/reject endpoints mutate persisted article metadata (data/article-index.jsonl); treat /ui like an internal admin surface.

A minimal editorial flow is available on GET /ui: each row shows editorial_status (pending / approved / rejected). Records written before this field existed are shown as pending. Rich editing is still out of scope; combine /ui with CLI (npm run write), logs, and WordPress as needed.

Architecture

RSS Feeds / News Sites
       ↓
  src/crawler/rss.js        — fetch + normalize RSS articles (GET retries align with `src/util/http-retry.js`)
  src/crawler/merge-sources.js — RSS + optional X, sorted
  src/crawler/scraper.js    — scrape full article content (GET retries on transient errors)
       ↓
  src/writer/ai.js          — OpenAI journalist AI (retries on 429 / 5xx / transient network)
       ↓
  src/publisher/wordpress.js — WP export: **REST** (default) or **XML-RPC** (`wp_transport` / `WP_TRANSPORT=xmlrpc`; retries shared)
       ↓
  WordPress (draft/publish)

Listener / auto mode:

  src/listener/rss-listener.js — cron-based RSS polling (+ optional X recent search)
       ↓
  detectTopics() → generateArticle() → publishToWordPress()

X (Twitter) — optional: copy config/social.example.json → config/social.json, set TWITTER_BEARER_TOKEN in .env. In listen mode, tweets are merged with RSS before keyword filtering. Recent-search HTTP uses axiosGetWithRetry (429 / 502–504 / transient network); tune with HTTP_MAX_ATTEMPTS and HTTP_RETRY_BASE_MS (unified across all clients), or legacy X_HTTP_MAX_ATTEMPTS and X_RETRY_BASE_MS (see .env.example). Uses X API v2 recent search (plan limits apply).

Configuration

Sources (config/sources.json)

Edit to add/remove RSS feeds, keywords, and trusted domains.
npm run rss:test walks every rss[] entry with the same retry logic as the crawler; stdout is { "ok": boolean, "feeds": [ { "ok", "name", "url", "item_count", "error" } ] }.
Default URLs are chosen for stability; publishers change endpoints often — if probes fail, swap the entry for a working RSS URL and re-run rss:test.

Social — X (config/social.json, gitignored)

Copy config/social.example.json → config/social.json. Define x.queries (recent-search strings, max 512 chars each per X rules) and optional max_results_per_query (10–100). Requires TWITTER_BEARER_TOKEN. Run npm run x:test to validate credentials and queries.

Sites (config/sites/*.json)

One JSON file per WordPress target site. Copy config/sites/example.json.
Credentials come from your vault — never commit real passwords.
npm run wp:test checks each site file (or env fallback if config/sites/ has no JSON except example); stdout is one JSON object { "ok": boolean, "sites": [ ... ] } and the process exits non-zero if any check fails.

{
  "name": "sports news",
  "wp_url": "https://wp.newsproject.bitreport.pt",
  "user": "wp-api-user",
  "password": "application-password-from-vault",
  "category_default": 5,
  "status_default": "draft",
  "lang": "pt"
}

Environment variables (.env)

Variable Purpose
OPENAI_API_KEY OpenAI API key
AI_MODEL Model (default: gpt-4o)
OPENAI_MAX_ATTEMPTS Retries for chat completions (default 3, max 5)
OPENAI_RETRY_BASE_MS First backoff delay for OpenAI retries (default 800)
HOST HTTP bind address in listen mode (default: 0.0.0.0)
PORT HTTP port in listen mode (default: 3200)
WP_URL WordPress base URL (fallback)
WP_USER WP application username
WP_PASSWORD WP application password
HTTP_MAX_ATTEMPTS Unified retry attempts (1–10, default 3). Used by RSS crawler, X API, WordPress, and article scraper. Takes precedence over component-specific vars.
HTTP_RETRY_BASE_MS Unified exponential backoff base in ms (100–120000, default 500)
HTTP_RETRY_MAX_MS Unified max delay cap for backoff (100–600000, default 60000)
WP_HTTP_MAX_ATTEMPTS ⚠️ Deprecated. Use HTTP_MAX_ATTEMPTS instead. Kept for backward compatibility.
WP_RETRY_BASE_MS ⚠️ Deprecated. Use HTTP_RETRY_BASE_MS instead. Kept for backward compatibility.
MODE auto or manual
AUTO_CRON Cron expression for auto mode
LOG_LEVEL debug, info, warn, error
HTTP_USER_AGENT Sent to RSS hosts and article scraper (identify your deployment)
RSS_TIMEOUT_MS Per-feed HTTP timeout for rss-parser (default 10000, max 120000)
RSS_FETCH_CONCURRENCY Parallel RSS fetches in fetchAllFeeds (default 3, max 20)
SCRAPER_TIMEOUT_MS Article scrape timeout (default 12000, max 120000)
TWITTER_BEARER_TOKEN X API v2 bearer (optional; required when using social.json + listen mode)
PUBLISH_HOURS Optional editorial window for WordPress post status, e.g. 8-20 (hours 8–19 inclusive in CRON_TIMEZONE, half-open range [start, end)). When set, posts inside the window use publish; outside the window they are saved as draft. When unset, only per-site status_default / wp_status applies (unchanged behaviour).
CRON_TIMEZONE IANA zone used for the RSS cron schedule and for interpreting PUBLISH_HOURS (e.g. Europe/Lisbon). If invalid or empty, the host local timezone is used for the publish window.

Article output format

{
  "title": "...",
  "subtitle": "...",
  "slug": "url-safe-slug",
  "body": "<p>...</p>",
  "summary": "...",
  "tags": ["...", "..."],
  "category": "sports",
  "seo_title": "...",
  "seo_description": "..."
}

Deploy (LXC dev container)

The public URL (ainews.bitreport.pt) expects something listening on PORT (default 3200) on the LXC. In listen mode the app starts a small HTTP server on HOST:PORT (HOST defaults to 0.0.0.0) so NPM can proxy to it. npm start / write does not start HTTP — use listen for long-running + NPM.

Was the LXC actually created?

Nothing in this repository creates Proxmox containers by itself. The bash script must be executed as root on a Proxmox node. If CT 223 (or ai-news-writer-dev) does not appear in pct list, the container was never provisioned.

(Nota PT: o domínio só responde se o CT existir, o Node estiver em modo listen na porta 3200, e o NPM apontar para o IP real desse CT — não assumir 10.10.50.23 sem confirmar no Proxmox.)

# --- On the Proxmox host (SSH as root) — create CT if missing ---
pct list | grep -E '223|ai-news-writer'
# If no row, from a clone of this repo:
bash tools/proxmox/create_ai_news_writer_lxc.sh

# Confirm guest IP for NPM (example VMID 223)
pct exec 223 -- ip -4 addr show eth0

# --- Inside the CT ---
git clone https://git.bitreport.pt/BitReport.pt/ai-news-writer.git /srv/ai-news-writer
cd /srv/ai-news-writer
npm install
cp .env.example .env
# edit .env: OPENAI_API_KEY, HOST=0.0.0.0, PORT=3200
# pm2 delete ai-news-writer   # only if replacing an old one-shot / wrong-args process
npm run ops:check
pm2 start ecosystem.config.cjs
pm2 save && pm2 startup

When you start from a git checkout, ecosystem.config.cjs sets DEPLOY_REVISION to git rev-parse --short HEAD if DEPLOY_REVISION / GIT_REVISION are not already in the environment — the app exposes this on GET /health as deploy_revision.

Repeatable deploy on the CT: from the repo root, npm run deploy:lxc (runs tools/deploy-lxc.sh: git pull --ff-only, npm ci --omit=dev, pm2 startOrReload ecosystem.config.cjs --update-env). Add --with-ops-check for post-restart smoke tests (npm run deploy:lxc -- --with-ops-check).

(Alternative, easier to mistype: pm2 start src/index.js --name ai-news-writer --cwd /srv/ai-news-writer --time -- listen — the -- before listen is required.)

NPM (CT 102): Proxy Host ainews.bitreport.pt → http://<lxc-ip>:3200 (forward scheme http unless you terminate TLS only at NPM). Quick check from another machine: curl -sS http://<lxc-ip>:3200/health — JSON includes version, mode: "listen", optional deploy_revision (git SHA / deploy tag when configured), and non-secret flags: rss_feed_count, rss_listener_active (false if the cron listener failed to start), rss_listener_last_tick_at / rss_listener_last_tick_ok / rss_listener_last_tick_error (cron liveness after the first tick), x_listening (bearer + social.json queries), wp_credentials_configured, wp_publish_by_transport ({ rest, xmlrpc } counts for publish-ready targets), openai_api_key_configured, ai_model, optional publish_hours (string like 8-20 or null) and publish_hours_active (true when PUBLISH_HOURS is configured).

Structured check (exit code 0/1): from a machine with curl + node (e.g. the CT or your laptop):

./tools/verify-deploy.sh "http://<lxc-ip>:3200"
# or: npm run verify:deploy -- "http://<lxc-ip>:3200"
# Through NPM (public URL) once upstream is healthy:
# npm run verify:deploy -- "https://ainews.bitreport.pt"

502 Bad Gateway (Nginx Proxy Manager)

A 502 means NPM received the browser request but could not get a valid response from the upstream (<lxc-ip>:3200). It is not an application “bug” inside Node until the proxy can reach the process.

Checklist (in order):

  1. Inside the LXC: pm2 status — ai-news-writer must be online. If errored/stopped, run pm2 logs ai-news-writer --lines 80 and fix the crash (missing .env, bad deploy path, etc.). Prefer pm2 start ecosystem.config.cjs from the app directory.
  2. Port listening: ss -lntp | grep 3200 (or curl -sS http://127.0.0.1:3200/health on the LXC). Expect JSON with "ok":true,"mode":"listen".
  3. NPM upstream: Proxy Host → Forward http → IP or hostname that NPM can route to (often the LXC IP on the same VLAN as NPM) → port 3200. If the IP is wrong, outdated, or the CT is down → 502.
  4. Firewall / routing: from the NPM container/host, curl -sS http://<lxc-ip>:3200/health. If this fails but works on localhost inside the LXC, the problem is network/firewall, not the app.
  5. SSL at NPM: “Websockets” / custom buffers rarely cause 502 for plain GET /health; focus on scheme = http to the upstream unless you terminate TLS on the app itself.

After fixing, re-test: npm run verify:deploy -- "https://ainews.bitreport.pt" (or direct LXC URL).

Typo check: the hostname must be ainews.bitreport.pt (not ainews.bitrepor.pt).

Backup & Disaster Recovery

The critical asset is data/article-index.jsonl (publication history and editorial decisions). RTO: 2 hours | RPO: 1 day.

Quick Links:

  • Manual backup: ./tools/backup-article-index.sh
  • Backup strategy: docs/BACKUP_STRATEGY.md (BIT-4285)
  • Test procedures: docs/runbooks/BACKUP_TESTING.md
  • Disaster recovery: docs/runbooks/DISASTER_RECOVERY.md (4 recovery scenarios)

Automated backups: Configured via cron on the LXC (daily @ 02:00 UTC, hourly incremental). See docs/runbooks/BACKUP_TESTING.md § Procedure 4 for test schedule.

Future

  • Multi-language output
  • Image generation (DALL-E / Stable Diffusion)
  • SEO scoring
  • Telegram / Discord social listening
  • Web dashboard (approve / edit / publish UI)
S
Description
AI News Writer — auto research, journalist AI, WP export, social listening (BIT-353)
Readme
776 KiB
0 Stars 32 Watchers 0 Forks
Languages
JavaScript 95.9%
Shell 4.1%