feat(writer-pipeline): aggregator-first andebol.net ingest, metrics, optional WP drafts
Add writer-pipeline package: RSS ingest to local store, shortlist, per-cycle token estimates (aggregator read context vs full HTML), optional Fastify aggregator API, optional WordPress draft creation via Application Passwords. Document runbook in docs/WRITER_PIPELINE_ANDEBOL.md; extend README structure. Refs: BIT-713 Made-with: Cursor
This commit is contained in:
1 parent
3579fdb837
commit
f18e1f9fed
18 files changed
+1823
-6
No files matched your search
@@ -6,12 +6,13 @@ Scalable multi-domain sports news platform — Astro 5 SSR frontend, Fastify bri
|
||||
|
||||
```
|
||||
news-platform/
|
||||
frontend/ # Astro 5 SSR frontend application
|
||||
bridge/ # Fastify bridge (WordPress REST API cache + normalizer)
|
||||
wordpress/ # WordPress config, themes, plugins
|
||||
config/domains/ # Per-domain configuration files
|
||||
docs/ # Architecture and runbooks
|
||||
deploy/ # LXC provisioning and deploy scripts
|
||||
frontend/ # Astro 5 SSR frontend application
|
||||
bridge/ # Fastify bridge (WordPress REST API cache + normalizer)
|
||||
writer-pipeline/ # RSS aggregator store, metrics, optional WP drafts (andebol.net)
|
||||
wordpress/ # WordPress config, themes, plugins
|
||||
config/domains/ # Per-domain configuration files
|
||||
docs/ # Architecture and runbooks
|
||||
deploy/ # LXC provisioning and deploy scripts
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# Writer pipeline — andebol.net (aggregator-first)
|
||||
|
||||
**Scope:** `writer-pipeline/` in this repo. **Parent:** aggregator epic (Paperclip **BIT-709**); delivery tracked under **BIT-713**.
|
||||
|
||||
## What it does
|
||||
|
||||
1. **Ingest** — Pulls RSS sources from `writer-pipeline/config/andebol.net.sources.json` into a local JSON store (`writer-pipeline/var/aggregated-items.json`, gitignored).
|
||||
2. **Shortlist** — Newest items that are not yet drafted in WordPress and not skipped.
|
||||
3. **Read path (aggregator-first)** — Before any LLM *reading* step, the writer uses only structured fields from the store (`title`, `summary`, `url`, `sourceFeedId`). No full-page fetch is required for the primary path.
|
||||
4. **Metrics** — Each cycle appends one JSON line to `writer-pipeline/var/metrics.jsonl` with estimated **read-phase** tokens for:
|
||||
- **Aggregator path:** `aggregatorReadContext()` (title + summary + URL + instruction block).
|
||||
- **Legacy path:** full HTML text fetch per shortlisted URL (for comparison only). If a fetch fails, that item falls back to summary-sized estimate so the cycle still completes.
|
||||
5. **Publish** — Optional: creates **WordPress drafts** from the shortlist using Application Passwords (never required for metrics-only runs).
|
||||
|
||||
## Fallback behaviour
|
||||
|
||||
- **Per feed:** a failing RSS URL is logged in `metrics.errors`; other feeds still run.
|
||||
- **Per URL (legacy comparison):** failed HTML fetch does not block the cycle; aggregator metrics still apply for production reads.
|
||||
- **WP publish:** if credentials are missing, the cycle completes with a clear error string and **no** draft creation.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
cd writer-pipeline
|
||||
npm install
|
||||
npm run build
|
||||
|
||||
# Ingest + metrics + optional legacy comparison (no WP)
|
||||
node dist/run-cycle.js --site andebol.net --dry-run --shortlist 10
|
||||
|
||||
# Create up to N drafts (needs ANDEBOL_WP_* env)
|
||||
node dist/run-cycle.js --site andebol.net --publish-max 1 --shortlist 10
|
||||
```
|
||||
|
||||
**Aggregator HTTP API** (optional, for cron or external tools):
|
||||
|
||||
```bash
|
||||
npm run aggregator
|
||||
# GET /health
|
||||
# GET /shortlist?site=andebol.net&limit=10
|
||||
# POST /ingest?site=andebol.net
|
||||
```
|
||||
|
||||
## Sample outcome (2026-04-02, dry-run, 5-item shortlist)
|
||||
|
||||
| Metric | Value |
|
||||
|--------|------|
|
||||
| `tokensReadAggregatorPath` | ~675 |
|
||||
| `tokensReadLegacyPath` | ~6.2k |
|
||||
| Ratio (legacy ÷ aggregator) | ~9× |
|
||||
|
||||
Pricing reference in code uses **USD 0.15 / 1M input tokens** (`token-metrics.ts`) for *read-phase* estimates only — adjust when the production model changes.
|
||||
|
||||
## Next steps
|
||||
|
||||
- Add more `feeds[]` entries (competition sites, press rooms) and tune dedup via canonical URLs.
|
||||
- Plug a real LLM **generation** step that receives only `aggregatorReadContext(item)` — no full HTML in the prompt unless a human toggles a break-glass flag.
|
||||
- Run `npm run aggregator` under systemd on the LXC with periodic `POST /ingest` and a single `run-cycle` cron for drafts.
|
||||
@@ -0,0 +1,8 @@
|
||||
# Optional: create WordPress drafts from the aggregator shortlist (andebol.net WP on :8081).
|
||||
# ANDEBOL_WP_BASE=http://127.0.0.1:8081/wp-json
|
||||
# ANDEBOL_WP_USER=editor_username
|
||||
# ANDEBOL_WP_APP_PASSWORD=xxxx xxxx xxxx xxxx
|
||||
|
||||
# Optional: aggregator HTTP service (default 127.0.0.1:3310)
|
||||
# AGGREGATOR_PORT=3310
|
||||
# AGGREGATOR_STORE_PATH=/opt/bitreport/news-platform/writer-pipeline/var/aggregated-items.json
|
||||
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
dist/
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"site": "andebol.net",
|
||||
"feeds": [
|
||||
{
|
||||
"id": "fpa_portal_main",
|
||||
"url": "https://portal.fpa.pt/feed/",
|
||||
"enabled": true,
|
||||
"note": "FPA portal WordPress main feed (category /noticias/feed is empty). Add more feeds as needed; failures are skipped per source."
|
||||
}
|
||||
]
|
||||
}
|
||||
Generated
+1142
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "news-writer-pipeline",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Aggregator-first writer pipeline for andebol.net (shortlist, token metrics, WP drafts)",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"aggregator": "node dist/aggregator-server.js",
|
||||
"aggregator:dev": "tsx src/aggregator-server.ts",
|
||||
"cycle": "node dist/run-cycle.js",
|
||||
"cycle:dev": "tsx src/run-cycle.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"fastify": "^4.28.1",
|
||||
"rss-parser": "^3.13.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.14.0",
|
||||
"tsx": "^4.15.0",
|
||||
"typescript": "^5.4.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import Fastify from 'fastify';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { readSourcesConfig } from './config-load.js';
|
||||
import { ingestSiteFeeds, sourcesConfigPath } from './rss-ingest.js';
|
||||
import { DEFAULT_STORE_PATH, loadStore, saveStore, shortlist } from './store.js';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const PKG_ROOT = path.resolve(__dirname, '..');
|
||||
const DEFAULT_CONFIG_DIR = path.join(PKG_ROOT, 'config');
|
||||
|
||||
async function buildServer() {
|
||||
const storePath = process.env.AGGREGATOR_STORE_PATH ?? DEFAULT_STORE_PATH;
|
||||
const configDir = process.env.AGGREGATOR_CONFIG_DIR ?? DEFAULT_CONFIG_DIR;
|
||||
const host = process.env.AGGREGATOR_HOST ?? '127.0.0.1';
|
||||
const port = parseInt(process.env.AGGREGATOR_PORT ?? '3310', 10);
|
||||
|
||||
const app = Fastify({ logger: true });
|
||||
|
||||
app.get('/health', async () => ({ ok: true, storePath }));
|
||||
|
||||
app.get<{
|
||||
Querystring: { site?: string; limit?: string };
|
||||
}>('/shortlist', async (req) => {
|
||||
const site = req.query.site ?? 'andebol.net';
|
||||
const limit = Math.min(50, Math.max(1, parseInt(req.query.limit ?? '10', 10)));
|
||||
const store = await loadStore(storePath);
|
||||
const items = shortlist(store, site, limit);
|
||||
return { site, limit, count: items.length, items };
|
||||
});
|
||||
|
||||
app.post<{
|
||||
Querystring: { site?: string };
|
||||
}>('/ingest', async (req, reply) => {
|
||||
const site = req.query.site ?? 'andebol.net';
|
||||
const cfgPath = sourcesConfigPath(site, configDir);
|
||||
const sources = await readSourcesConfig(cfgPath);
|
||||
let store = await loadStore(storePath);
|
||||
const result = await ingestSiteFeeds(store, sources);
|
||||
store = result.store;
|
||||
await saveStore(storePath, store);
|
||||
return reply.send({
|
||||
site,
|
||||
attempted: result.attempted,
|
||||
succeeded: result.succeeded,
|
||||
failed: result.failed,
|
||||
newItems: result.newItems,
|
||||
errors: result.errors,
|
||||
});
|
||||
});
|
||||
|
||||
await app.listen({ host, port });
|
||||
app.log.info(`Aggregator listening on http://${host}:${port}`);
|
||||
}
|
||||
|
||||
buildServer().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import type { SiteSourcesConfig } from './types.js';
|
||||
|
||||
export async function readSourcesConfig(filePath: string): Promise<SiteSourcesConfig> {
|
||||
const raw = await readFile(filePath, 'utf8');
|
||||
const data = JSON.parse(raw) as SiteSourcesConfig;
|
||||
if (!data?.site || !Array.isArray(data.feeds)) {
|
||||
throw new Error(`Invalid sources config: ${filePath}`);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Optional legacy read path: full HTML fetch for token comparison.
|
||||
* Not used for publishing when aggregator data is present.
|
||||
*/
|
||||
export async function fetchArticleText(url: string, timeoutMs = 10000): Promise<string | null> {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
headers: { 'User-Agent': 'BitReport-news-writer-pipeline/1.0 (metrics)' },
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const html = await res.text();
|
||||
return html
|
||||
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
|
||||
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
|
||||
.replace(/<[^>]+>/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.slice(0, 120_000);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import Parser from 'rss-parser';
|
||||
import type { AggregatedItem, SiteSourcesConfig, StoreFile } from './types.js';
|
||||
import { canonicalUrl, itemId, upsertItem } from './store.js';
|
||||
|
||||
const parser = new Parser();
|
||||
|
||||
async function parseFeedUrl(url: string) {
|
||||
const res = await fetch(url, {
|
||||
redirect: 'follow',
|
||||
headers: {
|
||||
'User-Agent': 'BitReport-news-writer-pipeline/1.0',
|
||||
Accept: 'application/rss+xml, application/xml, text/xml, */*',
|
||||
},
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const xml = await res.text();
|
||||
return parser.parseString(xml);
|
||||
}
|
||||
|
||||
function pickSummary(entry: { contentSnippet?: string; content?: string; summary?: string }): string {
|
||||
const s = entry.contentSnippet || entry.summary || '';
|
||||
if (s) return s.replace(/\s+/g, ' ').trim().slice(0, 2000);
|
||||
const c = entry.content || '';
|
||||
return c.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 2000);
|
||||
}
|
||||
|
||||
export interface IngestResult {
|
||||
store: StoreFile;
|
||||
attempted: number;
|
||||
succeeded: number;
|
||||
failed: number;
|
||||
newItems: number;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
export async function ingestSiteFeeds(
|
||||
store: StoreFile,
|
||||
config: SiteSourcesConfig,
|
||||
): Promise<IngestResult> {
|
||||
const errors: string[] = [];
|
||||
let current = store;
|
||||
let attempted = 0;
|
||||
let succeeded = 0;
|
||||
let failed = 0;
|
||||
let newItems = 0;
|
||||
const now = new Date().toISOString();
|
||||
|
||||
for (const feed of config.feeds) {
|
||||
if (!feed.enabled) continue;
|
||||
attempted += 1;
|
||||
try {
|
||||
const parsed = await parseFeedUrl(feed.url);
|
||||
succeeded += 1;
|
||||
const items = parsed.items ?? [];
|
||||
for (const entry of items) {
|
||||
const link = entry.link?.trim();
|
||||
if (!link) continue;
|
||||
const url = canonicalUrl(link);
|
||||
const id = itemId(url);
|
||||
const title = (entry.title || 'Sem título').replace(/\s+/g, ' ').trim();
|
||||
const summary = pickSummary(entry);
|
||||
const publishedAt =
|
||||
entry.isoDate || entry.pubDate || entry.date || now;
|
||||
|
||||
const agg: AggregatedItem = {
|
||||
id,
|
||||
site: config.site,
|
||||
sourceFeedId: feed.id,
|
||||
url,
|
||||
title,
|
||||
summary,
|
||||
publishedAt,
|
||||
ingestedAt: now,
|
||||
};
|
||||
const { store: next, isNew } = upsertItem(current, agg);
|
||||
current = next;
|
||||
if (isNew) newItems += 1;
|
||||
}
|
||||
} catch (e) {
|
||||
failed += 1;
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
errors.push(`feed ${feed.id} (${feed.url}): ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
return { store: current, attempted, succeeded, failed, newItems, errors };
|
||||
}
|
||||
|
||||
/** Resolve config path for a site key (e.g. andebol.net). */
|
||||
export function sourcesConfigPath(site: string, configDir: string): string {
|
||||
return `${configDir}/${site}.sources.json`;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env node
|
||||
import { appendFile, mkdir } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { readSourcesConfig } from './config-load.js';
|
||||
import { fetchArticleText } from './legacy-fetch.js';
|
||||
import { ingestSiteFeeds, sourcesConfigPath } from './rss-ingest.js';
|
||||
import {
|
||||
DEFAULT_STORE_PATH,
|
||||
loadStore,
|
||||
saveStore,
|
||||
shortlist,
|
||||
upsertItem,
|
||||
} from './store.js';
|
||||
import {
|
||||
aggregatorReadContext,
|
||||
estimateTokens,
|
||||
estimatedInputCostUsd,
|
||||
} from './token-metrics.js';
|
||||
import type { AggregatedItem, CycleMetrics } from './types.js';
|
||||
import { createDraftFromAggregatedItem } from './wp-publish.js';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const PKG_ROOT = path.resolve(__dirname, '..');
|
||||
const DEFAULT_CONFIG_DIR = path.join(PKG_ROOT, 'config');
|
||||
|
||||
function argValue(name: string, argv: string[]): string | undefined {
|
||||
const i = argv.indexOf(name);
|
||||
if (i >= 0 && argv[i + 1]) return argv[i + 1];
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function hasFlag(name: string, argv: string[]): boolean {
|
||||
return argv.includes(name);
|
||||
}
|
||||
|
||||
async function appendMetrics(metricsPath: string, m: CycleMetrics): Promise<void> {
|
||||
await mkdir(path.dirname(metricsPath), { recursive: true });
|
||||
await appendFile(metricsPath, `${JSON.stringify(m)}\n`, 'utf8');
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const argv = process.argv.slice(2);
|
||||
const site = argValue('--site', argv) ?? 'andebol.net';
|
||||
const dryRun = hasFlag('--dry-run', argv);
|
||||
const publishMax = Math.max(0, parseInt(argValue('--publish-max', argv) ?? '0', 10));
|
||||
const shortlistLimit = Math.max(1, parseInt(argValue('--shortlist', argv) ?? '10', 10));
|
||||
const storePath = argValue('--store', argv) ?? DEFAULT_STORE_PATH;
|
||||
const configDir = argValue('--config-dir', argv) ?? DEFAULT_CONFIG_DIR;
|
||||
const metricsPath =
|
||||
argValue('--metrics-file', argv) ?? path.join(PKG_ROOT, 'var', 'metrics.jsonl');
|
||||
|
||||
const cfgPath = sourcesConfigPath(site, configDir);
|
||||
const sources = await readSourcesConfig(cfgPath);
|
||||
|
||||
const startedAt = new Date().toISOString();
|
||||
const cycleId = randomUUID();
|
||||
let store = await loadStore(storePath);
|
||||
|
||||
const ingest = await ingestSiteFeeds(store, sources);
|
||||
store = ingest.store;
|
||||
await saveStore(storePath, store);
|
||||
|
||||
const list = shortlist(store, site, shortlistLimit);
|
||||
let tokensAgg = 0;
|
||||
let tokensLegacy = 0;
|
||||
let legacyUsed = 0;
|
||||
|
||||
for (const item of list) {
|
||||
tokensAgg += estimateTokens(aggregatorReadContext(item));
|
||||
const legacyText = await fetchArticleText(item.url);
|
||||
if (legacyText && legacyText.length > 200) {
|
||||
tokensLegacy += estimateTokens(legacyText);
|
||||
legacyUsed += 1;
|
||||
} else {
|
||||
/** If legacy fetch fails, production still proceeds with aggregator-only read; legacy tokens N/A for that item */
|
||||
tokensLegacy += estimateTokens(item.summary);
|
||||
}
|
||||
}
|
||||
|
||||
const errors = [...ingest.errors];
|
||||
let draftsCreated = 0;
|
||||
|
||||
const wpBase = process.env.ANDEBOL_WP_BASE ?? 'http://127.0.0.1:8081/wp-json';
|
||||
const wpUser = process.env.ANDEBOL_WP_USER ?? '';
|
||||
const wpPass = process.env.ANDEBOL_WP_APP_PASSWORD ?? '';
|
||||
|
||||
if (!dryRun && publishMax > 0 && wpUser && wpPass) {
|
||||
const toPublish = list.slice(0, publishMax);
|
||||
for (const item of toPublish) {
|
||||
try {
|
||||
const { id } = await createDraftFromAggregatedItem(item, {
|
||||
wpBase,
|
||||
username: wpUser,
|
||||
appPassword: wpPass,
|
||||
});
|
||||
draftsCreated += 1;
|
||||
const updated: AggregatedItem = { ...item, wpDraftId: id };
|
||||
store = upsertItem(store, updated).store;
|
||||
} catch (e) {
|
||||
errors.push(`draft ${item.url}: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
await saveStore(storePath, store);
|
||||
} else if (!dryRun && publishMax > 0) {
|
||||
errors.push(
|
||||
'Skipping WP publish: set ANDEBOL_WP_USER and ANDEBOL_WP_APP_PASSWORD (optional ANDEBOL_WP_BASE)',
|
||||
);
|
||||
}
|
||||
|
||||
const finishedAt = new Date().toISOString();
|
||||
const metrics: CycleMetrics = {
|
||||
cycleId,
|
||||
site,
|
||||
startedAt,
|
||||
finishedAt,
|
||||
feedsAttempted: ingest.attempted,
|
||||
feedsSucceeded: ingest.succeeded,
|
||||
feedsFailed: ingest.failed,
|
||||
newItemsIngested: ingest.newItems,
|
||||
shortlistSize: list.length,
|
||||
tokensReadAggregatorPath: tokensAgg,
|
||||
tokensReadLegacyPath: tokensLegacy,
|
||||
estimatedReadCostUsdAggregator: estimatedInputCostUsd(tokensAgg),
|
||||
estimatedReadCostUsdLegacy: estimatedInputCostUsd(tokensLegacy),
|
||||
draftsCreated,
|
||||
dryRun,
|
||||
fallbackLegacyFetchUsed: legacyUsed,
|
||||
errors,
|
||||
};
|
||||
|
||||
await appendMetrics(metricsPath, metrics);
|
||||
console.log(JSON.stringify(metrics, null, 2));
|
||||
if (errors.length) process.exitCode = 1;
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import type { AggregatedItem, StoreFile } from './types.js';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const DEFAULT_STORE_PATH = path.resolve(__dirname, '../var/aggregated-items.json');
|
||||
|
||||
export function canonicalUrl(raw: string): string {
|
||||
try {
|
||||
const u = new URL(raw);
|
||||
for (const key of [...u.searchParams.keys()]) {
|
||||
if (key.toLowerCase().startsWith('utm_')) u.searchParams.delete(key);
|
||||
}
|
||||
return u.toString();
|
||||
} catch {
|
||||
return raw.trim();
|
||||
}
|
||||
}
|
||||
|
||||
export function itemId(canonical: string): string {
|
||||
return createHash('sha256').update(canonical).digest('hex').slice(0, 20);
|
||||
}
|
||||
|
||||
async function ensureDir(filePath: string): Promise<void> {
|
||||
await mkdir(path.dirname(filePath), { recursive: true });
|
||||
}
|
||||
|
||||
export async function loadStore(storePath: string): Promise<StoreFile> {
|
||||
try {
|
||||
const raw = await readFile(storePath, 'utf8');
|
||||
const parsed = JSON.parse(raw) as StoreFile;
|
||||
if (parsed?.version === 1 && Array.isArray(parsed.items)) return parsed;
|
||||
} catch {
|
||||
// missing or corrupt
|
||||
}
|
||||
return { version: 1, items: [] };
|
||||
}
|
||||
|
||||
export async function saveStore(storePath: string, store: StoreFile): Promise<void> {
|
||||
await ensureDir(storePath);
|
||||
const tmp = `${storePath}.${process.pid}.tmp`;
|
||||
const body = `${JSON.stringify(store, null, 0)}\n`;
|
||||
await writeFile(tmp, body, 'utf8');
|
||||
await rename(tmp, storePath);
|
||||
}
|
||||
|
||||
export function upsertItem(store: StoreFile, item: AggregatedItem): { store: StoreFile; isNew: boolean } {
|
||||
const idx = store.items.findIndex((i) => i.id === item.id);
|
||||
const isNew = idx < 0;
|
||||
const next = { ...store, items: [...store.items] };
|
||||
if (idx >= 0) {
|
||||
const prev = next.items[idx];
|
||||
next.items[idx] = {
|
||||
...item,
|
||||
wpDraftId: prev.wpDraftId,
|
||||
skippedReason: prev.skippedReason,
|
||||
};
|
||||
} else next.items.push(item);
|
||||
return { store: next, isNew };
|
||||
}
|
||||
|
||||
export function shortlist(
|
||||
store: StoreFile,
|
||||
site: string,
|
||||
limit: number,
|
||||
): AggregatedItem[] {
|
||||
return store.items
|
||||
.filter((i) => i.site === site && !i.wpDraftId && !i.skippedReason)
|
||||
.sort((a, b) => (a.publishedAt < b.publishedAt ? 1 : a.publishedAt > b.publishedAt ? -1 : 0))
|
||||
.slice(0, limit);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/** Rough GPT-style token estimate (chars / 4). Good enough for before/after comparison. */
|
||||
export function estimateTokens(text: string): number {
|
||||
if (!text) return 0;
|
||||
return Math.ceil(text.length / 4);
|
||||
}
|
||||
|
||||
/** Reference pricing for reporting only — adjust in runbook when models change. */
|
||||
export const REF_INPUT_USD_PER_1M = 0.15;
|
||||
|
||||
export function estimatedInputCostUsd(tokens: number): number {
|
||||
return (tokens / 1_000_000) * REF_INPUT_USD_PER_1M;
|
||||
}
|
||||
|
||||
/** Build the minimal context the writer would send to an LLM after aggregator-first policy. */
|
||||
export function aggregatorReadContext(item: { title: string; summary: string; url: string }): string {
|
||||
return [
|
||||
'Use only the following structured source material (do not assume unseen article body):',
|
||||
`Title: ${item.title}`,
|
||||
`Summary: ${item.summary}`,
|
||||
`Source URL: ${item.url}`,
|
||||
].join('\n');
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
export interface FeedSource {
|
||||
id: string;
|
||||
url: string;
|
||||
enabled: boolean;
|
||||
note?: string;
|
||||
}
|
||||
|
||||
export interface SiteSourcesConfig {
|
||||
site: string;
|
||||
feeds: FeedSource[];
|
||||
}
|
||||
|
||||
export interface AggregatedItem {
|
||||
id: string;
|
||||
site: string;
|
||||
sourceFeedId: string;
|
||||
url: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
publishedAt: string;
|
||||
ingestedAt: string;
|
||||
ingestError?: string;
|
||||
/** Set when a draft was created in WordPress */
|
||||
wpDraftId?: number;
|
||||
skippedReason?: string;
|
||||
}
|
||||
|
||||
export interface StoreFile {
|
||||
version: 1;
|
||||
items: AggregatedItem[];
|
||||
}
|
||||
|
||||
export interface CycleMetrics {
|
||||
cycleId: string;
|
||||
site: string;
|
||||
startedAt: string;
|
||||
finishedAt: string;
|
||||
feedsAttempted: number;
|
||||
feedsSucceeded: number;
|
||||
feedsFailed: number;
|
||||
newItemsIngested: number;
|
||||
shortlistSize: number;
|
||||
/** Estimated prompt tokens if the writer uses only aggregator fields (read path) */
|
||||
tokensReadAggregatorPath: number;
|
||||
/** Estimated tokens if the writer fetched full HTML for each shortlisted item (legacy read path) */
|
||||
tokensReadLegacyPath: number;
|
||||
/** Assumed USD for read-phase only (see docs for model pricing reference) */
|
||||
estimatedReadCostUsdAggregator: number;
|
||||
estimatedReadCostUsdLegacy: number;
|
||||
draftsCreated: number;
|
||||
dryRun: boolean;
|
||||
fallbackLegacyFetchUsed: number;
|
||||
errors: string[];
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { AggregatedItem } from './types.js';
|
||||
|
||||
export interface WpPublishConfig {
|
||||
wpBase: string;
|
||||
username: string;
|
||||
appPassword: string;
|
||||
}
|
||||
|
||||
function stripTags(html: string): string {
|
||||
return html.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
function draftContent(item: AggregatedItem): string {
|
||||
const excerpt = stripTags(item.summary).slice(0, 400);
|
||||
return [
|
||||
'<!-- wp:paragraph -->',
|
||||
`<p><em>Resumo agregado (fonte primária antes de leitura LLM completa):</em> ${excerpt}</p>`,
|
||||
'<!-- /wp:paragraph -->',
|
||||
'<!-- wp:paragraph -->',
|
||||
`<p><a href="${item.url}" rel="nofollow noopener" target="_blank">Artigo original</a> (${item.sourceFeedId})</p>`,
|
||||
'<!-- /wp:paragraph -->',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
async function resolveCategoryId(
|
||||
base: string,
|
||||
authHeader: string,
|
||||
slug: string,
|
||||
): Promise<number | null> {
|
||||
const url = `${base}/wp/v2/categories?slug=${encodeURIComponent(slug)}`;
|
||||
const res = await fetch(url, {
|
||||
headers: { Accept: 'application/json', Authorization: authHeader },
|
||||
signal: AbortSignal.timeout(8000),
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const rows = (await res.json()) as { id: number }[];
|
||||
return rows[0]?.id ?? null;
|
||||
}
|
||||
|
||||
export async function createDraftFromAggregatedItem(
|
||||
item: AggregatedItem,
|
||||
cfg: WpPublishConfig,
|
||||
categorySlug = 'nacional',
|
||||
): Promise<{ id: number; link?: string }> {
|
||||
const base = cfg.wpBase.replace(/\/$/, '');
|
||||
const token = Buffer.from(`${cfg.username}:${cfg.appPassword}`, 'utf8').toString('base64');
|
||||
const authHeader = `Basic ${token}`;
|
||||
|
||||
const categoryId = await resolveCategoryId(base, authHeader, categorySlug);
|
||||
const body: Record<string, unknown> = {
|
||||
title: item.title,
|
||||
content: draftContent(item),
|
||||
status: 'draft',
|
||||
excerpt: stripTags(item.summary).slice(0, 300),
|
||||
};
|
||||
if (categoryId) body.categories = [categoryId];
|
||||
|
||||
const res = await fetch(`${base}/wp/v2/posts`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
Authorization: authHeader,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errText = await res.text().catch(() => '');
|
||||
throw new Error(`WP draft failed ${res.status}: ${errText.slice(0, 500)}`);
|
||||
}
|
||||
|
||||
const post = (await res.json()) as { id: number; link?: string };
|
||||
return { id: post.id, link: post.link };
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
*
|
||||
!.gitignore
|
||||
Reference in new issue
Block a user