feat(aggregator): searchable store, bridge AGGREGATOR_URL, writer candidates
Implement BIT-709 acceptance: GET /search and /stats on the writer-pipeline aggregator; bridge AggregatorClient calls /search and maps items with source_url. /writers/:id/candidates merges aggregator-first with WordPress, exposes candidate_source and matched_sources, and passes max_age_hours into ranking. Add docs/AGGREGATOR_OPERATIONS.md and store unit tests. Paperclip-Issue: BIT-709 Made-with: Cursor
This commit is contained in:
1 parent
fa64f29445
commit
7f0deae75f
11 files changed
+474
-122
No files matched your search
@@ -1,6 +1,8 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import type { ArticleListItem } from '../types.js';
|
||||
import { writer_config_service, type WriterSource } from '../services/writer-config.js';
|
||||
import { aggregator_client } from '../services/aggregator-client.js';
|
||||
import { aggregator_item_to_article_list_item } from '../services/aggregator-mapper.js';
|
||||
import { rank_articles, filter_by_score, take_top_n } from '../services/ranking.js';
|
||||
import { WpClient } from '../services/wp-client.js';
|
||||
import { swr_fetch } from '../services/cache.js';
|
||||
@@ -145,46 +147,59 @@ export async function writers_routes(app: FastifyInstance) {
|
||||
Querystring: { limit?: string; min_score?: string; max_age_hours?: string };
|
||||
}>('/writers/:agentId/candidates', async (req, reply) => {
|
||||
const { agentId } = req.params;
|
||||
const limit = parseInt(req.query.limit ?? '10', 10);
|
||||
const max_age_hours = parseInt(req.query.max_age_hours ?? '168', 10); // 1 week default
|
||||
const limit = Math.min(50, Math.max(1, parseInt(req.query.limit ?? '10', 10)));
|
||||
const max_age_hours = Math.max(1, parseInt(req.query.max_age_hours ?? '168', 10)); // 1 week default
|
||||
|
||||
const config = writer_config_service.loadConfig(agentId);
|
||||
if (!config) {
|
||||
return reply.code(404).send({ error: `No config found for agent ${agentId}` });
|
||||
}
|
||||
|
||||
// Try to fetch from aggregator first (when BIT-709 is ready)
|
||||
// For now, fetch from WordPress and rank locally
|
||||
const host = resolve_site_host(req);
|
||||
const domain_config = get_domain_config(host);
|
||||
const cache_key = `writers:${agentId}:${host}:candidates:${limit}`;
|
||||
const cache_key = `writers:${agentId}:${host}:candidates:${limit}:${max_age_hours}`;
|
||||
|
||||
const cached = await swr_fetch(cache_key, async () => {
|
||||
const wp_client = new WpClient(domain_config.wp_endpoint);
|
||||
const articles: ArticleListItem[] = [];
|
||||
let from_aggregator = 0;
|
||||
|
||||
// Fetch latest articles from WordPress
|
||||
if (aggregator_client.isEnabled()) {
|
||||
const raw = await aggregator_client.fetchItemsForSite(
|
||||
config.domain,
|
||||
limit * 8,
|
||||
max_age_hours,
|
||||
);
|
||||
from_aggregator = raw.length;
|
||||
for (const row of raw) {
|
||||
articles.push(aggregator_item_to_article_list_item(row));
|
||||
}
|
||||
}
|
||||
|
||||
const wp_client = new WpClient(domain_config.wp_endpoint);
|
||||
const result = await wp_client.get_posts({
|
||||
page: 1,
|
||||
per_page: Math.min(50, limit * 5), // Fetch more to allow for filtering
|
||||
per_page: Math.min(50, limit * 5),
|
||||
});
|
||||
const wp_items = result.items || [];
|
||||
articles.push(...wp_items);
|
||||
|
||||
const articles = result.items || [];
|
||||
const candidate_source =
|
||||
from_aggregator > 0 ? (wp_items.length > 0 ? 'mixed' : 'aggregator') : 'wordpress';
|
||||
|
||||
// Rank by config
|
||||
const scored = rank_articles(articles, config);
|
||||
|
||||
// Filter and take top N
|
||||
const scored = rank_articles(articles, config, max_age_hours);
|
||||
const filtered = filter_by_score(scored, config.ranking_preferences.min_score);
|
||||
const top = take_top_n(filtered, limit);
|
||||
|
||||
return {
|
||||
agent_id: agentId,
|
||||
candidate_source,
|
||||
candidates: top.map((item) => ({
|
||||
article: item.article,
|
||||
score: Math.round(item.combined_score * 100) / 100, // Round to 2 decimals
|
||||
score: Math.round(item.combined_score * 100) / 100,
|
||||
freshness_score: Math.round(item.freshness_score * 100) / 100,
|
||||
relevance_score: Math.round(item.relevance_score * 100) / 100,
|
||||
matched_topics: item.matched_topics,
|
||||
matched_sources: item.matched_sources,
|
||||
freshness_hours: item.freshness_hours,
|
||||
})),
|
||||
total_candidates: scored.length,
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
import type { ArticleListItem } from '../types.js';
|
||||
import type { WriterConfig } from './writer-config.js';
|
||||
import {
|
||||
aggregator_item_to_article_list_item,
|
||||
type AggregatorApiItem,
|
||||
} from './aggregator-mapper.js';
|
||||
|
||||
/**
|
||||
* Aggregator Client - Interface to the content aggregation service (BIT-709).
|
||||
*
|
||||
* This service will be enhanced once the aggregator is built.
|
||||
* For now, it provides a stub implementation that can be expanded later.
|
||||
*
|
||||
* Expected aggregator API (when BIT-709 is complete):
|
||||
* GET /aggregated?topics=X,Y&sources=Z&limit=N&sort=freshness
|
||||
* → { items: ArticleListItem[], aggregated_from: string[], total_count: int }
|
||||
* Client for the internal content aggregator (`writer-pipeline` HTTP server, BIT-709).
|
||||
* Base URL: `AGGREGATOR_URL` (e.g. http://127.0.0.1:3310). No trailing slash required.
|
||||
*/
|
||||
|
||||
export interface AggregatorResponse {
|
||||
@@ -20,11 +18,22 @@ export interface AggregatorResponse {
|
||||
}
|
||||
|
||||
export interface AggregatorSearchParams {
|
||||
/** Site key matching `writer-pipeline` store (e.g. andebol.net). */
|
||||
site: string;
|
||||
topics?: string[];
|
||||
sources?: string[];
|
||||
limit?: number;
|
||||
sort?: 'freshness' | 'relevance';
|
||||
max_age_hours?: number;
|
||||
/** Space-separated tokens; passed to aggregator as `q`. */
|
||||
q?: string;
|
||||
}
|
||||
|
||||
export interface AggregatorStatsResponse {
|
||||
total: number;
|
||||
bySite: Record<string, number>;
|
||||
bySource: Record<string, number>;
|
||||
storePath?: string;
|
||||
}
|
||||
|
||||
export class AggregatorClient {
|
||||
@@ -32,35 +41,94 @@ export class AggregatorClient {
|
||||
private enabled: boolean;
|
||||
|
||||
constructor(aggregator_url?: string) {
|
||||
this.aggregator_url = aggregator_url || process.env['AGGREGATOR_URL'] || '';
|
||||
this.aggregator_url = (aggregator_url || process.env['AGGREGATOR_URL'] || '').replace(/\/$/, '');
|
||||
this.enabled = !!this.aggregator_url;
|
||||
|
||||
if (!this.enabled) {
|
||||
console.warn('[AggregatorClient] No aggregator URL configured - using stub mode');
|
||||
console.warn('[AggregatorClient] No AGGREGATOR_URL — candidates use WordPress only');
|
||||
}
|
||||
}
|
||||
|
||||
isEnabled(): boolean {
|
||||
return this.enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull recent / matching items for ranking in the bridge. Calls `GET /search`.
|
||||
*/
|
||||
async fetchItemsForSite(
|
||||
site: string,
|
||||
limit: number,
|
||||
max_age_hours: number,
|
||||
q?: string,
|
||||
): Promise<AggregatorApiItem[]> {
|
||||
if (!this.enabled) return [];
|
||||
const url = new URL('/search', `${this.aggregator_url}/`);
|
||||
url.searchParams.set('site', site);
|
||||
url.searchParams.set('limit', String(Math.min(200, Math.max(1, limit))));
|
||||
if (max_age_hours > 0) {
|
||||
url.searchParams.set('max_age_hours', String(max_age_hours));
|
||||
}
|
||||
if (q?.trim()) {
|
||||
url.searchParams.set('q', q.trim());
|
||||
}
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 10_000);
|
||||
const response = await fetch(url.toString(), { signal: controller.signal });
|
||||
clearTimeout(timeout);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Aggregator returned ${response.status}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as { items?: AggregatorApiItem[] };
|
||||
return Array.isArray(data.items) ? data.items : [];
|
||||
} catch (error) {
|
||||
console.error('[AggregatorClient] fetchItemsForSite failed:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search aggregated content by topics and sources.
|
||||
* Falls back to stub implementation if aggregator is not available.
|
||||
* Search aggregated content; maps JSON to `ArticleListItem` with `source_url` set.
|
||||
*/
|
||||
async search(params: AggregatorSearchParams): Promise<AggregatorResponse> {
|
||||
if (this.enabled) {
|
||||
return this.search_remote(params);
|
||||
if (!this.enabled) {
|
||||
return {
|
||||
items: [],
|
||||
aggregated_from: [],
|
||||
total_count: 0,
|
||||
fetched_at: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
// Stub: no remote aggregator configured
|
||||
|
||||
const limit = params.limit ?? 20;
|
||||
const maxAge = params.max_age_hours ?? 168;
|
||||
const q =
|
||||
params.q?.trim() ||
|
||||
(params.topics?.length ? params.topics.slice(0, 3).join(' ') : undefined);
|
||||
|
||||
const raw = await this.fetchItemsForSite(params.site, limit, maxAge, q);
|
||||
let filtered = raw;
|
||||
|
||||
if (params.sources?.length) {
|
||||
const allow = new Set(params.sources);
|
||||
filtered = raw.filter((i) => allow.has(i.sourceFeedId));
|
||||
}
|
||||
|
||||
const items = filtered.map(aggregator_item_to_article_list_item);
|
||||
const aggregated_from = [...new Set(filtered.map((i) => i.sourceFeedId))];
|
||||
|
||||
return {
|
||||
items: [],
|
||||
aggregated_from: [],
|
||||
total_count: 0,
|
||||
items,
|
||||
aggregated_from,
|
||||
total_count: filtered.length,
|
||||
fetched_at: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get aggregation statistics for an agent.
|
||||
* Returns what sources and topics are being tracked.
|
||||
*/
|
||||
async get_stats(
|
||||
agent_id: string,
|
||||
config: WriterConfig,
|
||||
@@ -70,69 +138,41 @@ export class AggregatorClient {
|
||||
sources_count: number;
|
||||
aggregator_available: boolean;
|
||||
last_aggregated_at: string | null;
|
||||
aggregator_total_items: number | null;
|
||||
aggregator_site_items: number | null;
|
||||
}> {
|
||||
let aggregator_total_items: number | null = null;
|
||||
let aggregator_site_items: number | null = null;
|
||||
let last_aggregated_at: string | null = null;
|
||||
|
||||
if (this.enabled) {
|
||||
try {
|
||||
const url = new URL('/stats', `${this.aggregator_url}/`);
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 8_000);
|
||||
const response = await fetch(url.toString(), { signal: controller.signal });
|
||||
clearTimeout(timeout);
|
||||
|
||||
if (response.ok) {
|
||||
const data = (await response.json()) as AggregatorStatsResponse;
|
||||
aggregator_total_items = data.total ?? null;
|
||||
aggregator_site_items = data.bySite?.[config.domain] ?? null;
|
||||
}
|
||||
} catch {
|
||||
/* stats are optional */
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
agent_id,
|
||||
topics_count: config.topics.length,
|
||||
sources_count: config.sources.length,
|
||||
aggregator_available: this.enabled,
|
||||
last_aggregated_at: null, // Will be set when BIT-709 is complete
|
||||
last_aggregated_at,
|
||||
aggregator_total_items,
|
||||
aggregator_site_items,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Remote search - call actual aggregator API (when available).
|
||||
*/
|
||||
private async search_remote(params: AggregatorSearchParams): Promise<AggregatorResponse> {
|
||||
const url = new URL('/aggregated', this.aggregator_url);
|
||||
|
||||
if (params.topics && params.topics.length > 0) {
|
||||
url.searchParams.set('topics', params.topics.join(','));
|
||||
}
|
||||
if (params.sources && params.sources.length > 0) {
|
||||
url.searchParams.set('sources', params.sources.join(','));
|
||||
}
|
||||
if (params.limit) {
|
||||
url.searchParams.set('limit', String(params.limit));
|
||||
}
|
||||
if (params.sort) {
|
||||
url.searchParams.set('sort', params.sort);
|
||||
}
|
||||
if (params.max_age_hours) {
|
||||
url.searchParams.set('max_age_hours', String(params.max_age_hours));
|
||||
}
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 10000); // 10s timeout
|
||||
|
||||
const response = await fetch(url.toString(), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
clearTimeout(timeout);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Aggregator returned ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return {
|
||||
items: data.items || [],
|
||||
aggregated_from: data.aggregated_from || [],
|
||||
total_count: data.total_count || 0,
|
||||
fetched_at: new Date().toISOString(),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[AggregatorClient] Remote search failed:', error);
|
||||
// Return empty result rather than failing hard
|
||||
return {
|
||||
items: [],
|
||||
aggregated_from: [],
|
||||
total_count: 0,
|
||||
fetched_at: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const aggregator_client = new AggregatorClient();
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { ArticleListItem } from '../types.js';
|
||||
|
||||
/** Shape returned by `writer-pipeline` aggregator `GET /search`. */
|
||||
export interface AggregatorApiItem {
|
||||
id: string;
|
||||
site: string;
|
||||
sourceFeedId: string;
|
||||
url: string;
|
||||
sourceKind?: string;
|
||||
topics?: string[];
|
||||
title: string;
|
||||
summary: string;
|
||||
publishedAt: string;
|
||||
ingestedAt: string;
|
||||
ingestError?: string;
|
||||
}
|
||||
|
||||
export function aggregator_item_to_article_list_item(item: AggregatorApiItem): ArticleListItem {
|
||||
const hex = item.id.replace(/[^0-9a-f]/gi, '');
|
||||
const slice = (hex.slice(0, 7) || '0').padEnd(7, '0');
|
||||
const numericId = parseInt(slice, 16) % 2_000_000_000;
|
||||
|
||||
return {
|
||||
id: numericId,
|
||||
slug: `agg-${item.id}`,
|
||||
title: item.title,
|
||||
excerpt: item.summary.length > 500 ? `${item.summary.slice(0, 497)}...` : item.summary,
|
||||
featured_image: null,
|
||||
featured_image_alt: '',
|
||||
author: {
|
||||
id: 0,
|
||||
name: item.sourceFeedId,
|
||||
slug: item.sourceFeedId.replace(/[^a-z0-9-]+/gi, '-').toLowerCase() || 'source',
|
||||
avatar: null,
|
||||
},
|
||||
category: {
|
||||
id: 0,
|
||||
slug: 'aggregated',
|
||||
name: 'Aggregated',
|
||||
description: '',
|
||||
count: 0,
|
||||
},
|
||||
published_at: item.publishedAt,
|
||||
reading_time: Math.max(1, Math.ceil(item.summary.length / 800)),
|
||||
is_featured: false,
|
||||
is_trending: false,
|
||||
source_url: item.url,
|
||||
};
|
||||
}
|
||||
@@ -45,6 +45,14 @@ export function calculate_freshness_score(publishedAt: string, maxAgeHours: numb
|
||||
return Math.max(0, 1 - normalized * normalized);
|
||||
}
|
||||
|
||||
function hostname_of(url: string): string | null {
|
||||
try {
|
||||
return new URL(url).hostname.replace(/^www\./i, '').toLowerCase();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate relevance score based on topic and source matching.
|
||||
* Score is normalized to 0-1.
|
||||
@@ -60,7 +68,6 @@ export function calculate_relevance_score(
|
||||
const matched_topics: string[] = [];
|
||||
const matched_sources: string[] = [];
|
||||
|
||||
// Simple text-based topic matching (article title/excerpt vs config topics)
|
||||
const text_to_search = `${article.title} ${article.excerpt}`.toLowerCase();
|
||||
for (const topic of config.topics) {
|
||||
if (text_to_search.includes(topic.toLowerCase())) {
|
||||
@@ -68,23 +75,33 @@ export function calculate_relevance_score(
|
||||
}
|
||||
}
|
||||
|
||||
// Note: In a full implementation, we'd check the article's source URL
|
||||
// For now, we'll assume source matching happens at the aggregation level
|
||||
// and just focus on topic matching
|
||||
if (matched_topics.length > 0) {
|
||||
// Score: how many topics matched relative to total topics
|
||||
return {
|
||||
score: Math.min(1, matched_topics.length / config.topics.length + 0.5),
|
||||
matched_topics,
|
||||
matched_sources,
|
||||
};
|
||||
const article_host = article.source_url ? hostname_of(article.source_url) : null;
|
||||
if (article_host) {
|
||||
for (const s of config.sources) {
|
||||
const sh = hostname_of(s.url);
|
||||
if (!sh) continue;
|
||||
if (article_host === sh || article_host.endsWith(`.${sh}`) || sh.endsWith(`.${article_host}`)) {
|
||||
matched_sources.push(s.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let score = 0.2;
|
||||
if (matched_topics.length > 0) {
|
||||
score = Math.min(1, matched_topics.length / Math.max(1, config.topics.length) + 0.5);
|
||||
}
|
||||
if (matched_sources.length > 0) {
|
||||
score = Math.min(1, score + 0.15);
|
||||
}
|
||||
|
||||
if (matched_topics.length > 0 || matched_sources.length > 0) {
|
||||
return { score, matched_topics, matched_sources };
|
||||
}
|
||||
|
||||
// No topic match: low relevance, but not zero (unexpected articles can be valuable)
|
||||
return {
|
||||
score: 0.2,
|
||||
matched_topics: [],
|
||||
matched_sources: [],
|
||||
matched_topics,
|
||||
matched_sources,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -95,9 +112,13 @@ export function calculate_relevance_score(
|
||||
* @param config - Writer config with topics, sources, and ranking preferences
|
||||
* @returns Sorted list of scored articles (highest score first)
|
||||
*/
|
||||
export function rank_articles(articles: ArticleListItem[], config: WriterConfig): ScoredArticle[] {
|
||||
export function rank_articles(
|
||||
articles: ArticleListItem[],
|
||||
config: WriterConfig,
|
||||
max_age_hours: number = 168,
|
||||
): ScoredArticle[] {
|
||||
const scored: ScoredArticle[] = articles.map((article) => {
|
||||
const freshness_score = calculate_freshness_score(article.published_at);
|
||||
const freshness_score = calculate_freshness_score(article.published_at, max_age_hours);
|
||||
const relevance_data = calculate_relevance_score(article, config);
|
||||
|
||||
const combined_score =
|
||||
|
||||
@@ -72,6 +72,8 @@ export interface ArticleListItem {
|
||||
reading_time: number;
|
||||
is_featured: boolean;
|
||||
is_trending: boolean;
|
||||
/** Original article URL when the row comes from the internal aggregator (BIT-709). */
|
||||
source_url?: string;
|
||||
}
|
||||
|
||||
export interface Article extends ArticleListItem {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# Internal news aggregator — operations & costs (BIT-709)
|
||||
|
||||
This runbook covers the **self-hosted** multi-source aggregator in `writer-pipeline/` and how the **bridge** uses it for writer candidates.
|
||||
|
||||
## Components
|
||||
|
||||
| Piece | Role |
|
||||
|--------|------|
|
||||
| JSON store | `writer-pipeline/var/aggregated-items.json` (default path; override with `AGGREGATOR_STORE_PATH`) |
|
||||
| Ingest config | `writer-pipeline/config/{site}.sources.json` (e.g. `andebol.net.sources.json`) |
|
||||
| HTTP API | Fastify server (`npm run aggregator` → `dist/aggregator-server.js`) |
|
||||
| Bridge integration | Set `AGGREGATOR_URL` (e.g. `http://127.0.0.1:3310`) so `/writers/:id/candidates` queries the aggregator **before** merging WordPress posts |
|
||||
|
||||
## HTTP API (aggregator process)
|
||||
|
||||
| Method | Path | Purpose |
|
||||
|--------|------|---------|
|
||||
| GET | `/health` | Liveness + resolved `storePath` |
|
||||
| GET | `/search?site=&limit=&q=&topic=&max_age_hours=` | Searchable listing: tokenized `q` matches title+summary; deduped store keyed by canonical URL at ingest |
|
||||
| GET | `/shortlist?site=&limit=&topic=` | Newest eligible items (no draft/skip) for one site |
|
||||
| GET | `/stats` | Total items, counts by site and by `site:sourceFeedId` |
|
||||
| POST | `/ingest?site=` | Run ingest for that site’s sources config and persist the store |
|
||||
|
||||
Environment:
|
||||
|
||||
- `AGGREGATOR_HOST` (default `127.0.0.1`), `AGGREGATOR_PORT` (default `3310`)
|
||||
- `AGGREGATOR_CONFIG_DIR` — directory of `*.sources.json`
|
||||
- `AGGREGATOR_STORE_PATH` — JSON backing file
|
||||
|
||||
## Bridge
|
||||
|
||||
- **`AGGREGATOR_URL`**: base URL of the aggregator (no trailing slash required). If unset, candidates come only from WordPress (previous behaviour).
|
||||
- **`GET /writers/:agentId/candidates`**: loads aggregated items for `config.domain`, maps them to the same candidate shape as WordPress rows, adds **`source_url`** for external URLs, then merges WordPress posts and ranks. Response includes **`candidate_source`**: `aggregator` | `wordpress` | `mixed`.
|
||||
- **`GET /writers/:agentId/stats`**: when the aggregator is enabled, also calls `GET /stats` and returns `aggregator_total_items` and `aggregator_site_items` when available.
|
||||
|
||||
## Data contract (per item)
|
||||
|
||||
Each aggregated item includes **source** (`sourceFeedId`, optional `sourceKind`), **timestamps** (`publishedAt`, `ingestedAt`), **technical summary** (`summary` + `title`), and **original URL** (`url`). Deduplication at ingest uses **canonical URL** → stable `id` (`store.itemId`).
|
||||
|
||||
## Cost model (read-phase, LLM)
|
||||
|
||||
Structured read context for one item is built in `writer-pipeline/src/token-metrics.ts` (`aggregatorReadContext`). Reference **input** pricing used in metrics: **USD 0.15 / 1M tokens** (`REF_INPUT_USD_PER_1M`) — adjust when the production model changes.
|
||||
|
||||
Typical savings vs full-page fetch for the same shortlist are documented in `docs/WRITER_PIPELINE_ANDEBOL.md` (example ratio ~9× fewer tokens on the read path).
|
||||
|
||||
## Suggested scheduling (self-hosted)
|
||||
|
||||
1. **Ingest** — `POST /ingest?site=andebol.net` on a timer (e.g. every 6–12 hours per feed stability), or run `node dist/run-cycle.js` where you already use the pipeline.
|
||||
2. **Aggregator process** — `systemd` or PM2 keeping `npm run aggregator` up on the same host (or container) as the bridge; bridge reaches it via loopback or private network.
|
||||
3. **Bridge** — ensure `AGGREGATOR_URL` is set in the bridge environment alongside Redis/WordPress settings.
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
cd writer-pipeline && npm run build && npm test
|
||||
cd ../bridge && npm run build
|
||||
# With aggregator running:
|
||||
curl -sS "http://127.0.0.1:3310/search?site=andebol.net&limit=5"
|
||||
```
|
||||
|
||||
## Related docs
|
||||
|
||||
- `docs/AGGREGATOR_ARCHITECTURE.md` — long-term schema and phased plan
|
||||
- `docs/WRITER_PIPELINE_ANDEBOL.md` — pipeline commands and metrics
|
||||
- `docs/writer-tools.md` — bridge writer API
|
||||
@@ -38,9 +38,13 @@ node dist/run-cycle.js --site andebol.net --publish-max 1 --shortlist 10
|
||||
npm run aggregator
|
||||
# GET /health
|
||||
# GET /shortlist?site=andebol.net&limit=10
|
||||
# GET /search?site=andebol.net&limit=20&q=benfica&max_age_hours=168
|
||||
# GET /stats
|
||||
# POST /ingest?site=andebol.net
|
||||
```
|
||||
|
||||
Set **`AGGREGATOR_URL`** on the bridge (e.g. `http://127.0.0.1:3310`) so writer candidates use this API first; see `docs/AGGREGATOR_OPERATIONS.md`.
|
||||
|
||||
## Sample outcome (2026-04-02, dry-run, 5-item shortlist)
|
||||
|
||||
| Metric | Value |
|
||||
|
||||
+13
-14
@@ -288,8 +288,10 @@ curl http://localhost:3200/writers/f0251a61-38e1-4a9b-8cd1-38d96a320cab/stats
|
||||
"agent_id": "f0251a61-38e1-4a9b-8cd1-38d96a320cab",
|
||||
"topics_count": 3,
|
||||
"sources_count": 6,
|
||||
"aggregator_available": false,
|
||||
"last_aggregated_at": null
|
||||
"aggregator_available": true,
|
||||
"last_aggregated_at": null,
|
||||
"aggregator_total_items": 1200,
|
||||
"aggregator_site_items": 400
|
||||
}
|
||||
```
|
||||
|
||||
@@ -371,20 +373,17 @@ This prevents hammering WordPress when multiple agent instances query frequently
|
||||
|
||||
## Integration with Content Aggregator (BIT-709)
|
||||
|
||||
When BIT-709 completes the content aggregator service, the writer tools will automatically integrate:
|
||||
With **`AGGREGATOR_URL`** set on the bridge (base URL of `writer-pipeline`’s HTTP server):
|
||||
|
||||
1. **Aggregator API Contract:**
|
||||
- `GET /aggregated?topics=X,Y&sources=Z&limit=N&sort=freshness`
|
||||
- Returns deduplicated, pre-ranked articles from all configured sources
|
||||
1. **Aggregator API** (see `docs/AGGREGATOR_OPERATIONS.md`):
|
||||
- `GET /search?site={writerConfig.domain}&limit=N&max_age_hours=…&q=…`
|
||||
- Items include `title`, `summary`, `url`, `sourceFeedId`, `publishedAt` (dedup by canonical URL at ingest).
|
||||
|
||||
2. **What changes:**
|
||||
- `/writers/:agentId/candidates` will call the aggregator instead of WordPress
|
||||
- Much faster performance (aggregator pre-ranks and deduplicates)
|
||||
- Access to articles from external RSS/API sources, not just WordPress
|
||||
2. **Bridge behaviour:**
|
||||
- `/writers/:agentId/candidates` loads aggregated items **first**, merges WordPress posts, then ranks. Response includes **`candidate_source`**: `aggregator`, `wordpress`, or `mixed`.
|
||||
- Aggregated rows expose the original link as **`article.source_url`** (WordPress-sourced rows omit it).
|
||||
|
||||
3. **No breaking changes:**
|
||||
- CLI and API surface remain the same
|
||||
- Agent code doesn't need to change
|
||||
3. **No breaking changes** to query parameters; agents should prefer `source_url` when present for the read/fetch step.
|
||||
|
||||
---
|
||||
|
||||
@@ -401,7 +400,7 @@ curl http://bridge:3200/writers/$AGENT_ID/sources
|
||||
CANDIDATES=$(curl "http://bridge:3200/writers/$AGENT_ID/candidates?limit=5")
|
||||
|
||||
# 3. Process each candidate (highest score first)
|
||||
# — Read full article at candidate.article.url
|
||||
# — Open candidate.article.source_url if set, else use the WordPress article as today
|
||||
# — Write summary in target language
|
||||
# — Publish via WordPress API
|
||||
|
||||
|
||||
@@ -3,7 +3,13 @@ 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';
|
||||
import {
|
||||
DEFAULT_STORE_PATH,
|
||||
loadStore,
|
||||
saveStore,
|
||||
searchItems,
|
||||
shortlist,
|
||||
} from './store.js';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const PKG_ROOT = path.resolve(__dirname, '..');
|
||||
@@ -30,6 +36,57 @@ async function buildServer() {
|
||||
return { site, limit, topic: topic ?? null, count: items.length, items };
|
||||
});
|
||||
|
||||
app.get<{
|
||||
Querystring: {
|
||||
site?: string;
|
||||
limit?: string;
|
||||
topic?: string;
|
||||
q?: string;
|
||||
max_age_hours?: string;
|
||||
};
|
||||
}>('/search', async (req) => {
|
||||
const site = req.query.site ?? 'andebol.net';
|
||||
const limit = Math.min(200, Math.max(1, parseInt(req.query.limit ?? '20', 10)));
|
||||
const topic = req.query.topic?.trim() || undefined;
|
||||
const q = req.query.q?.trim() || undefined;
|
||||
const maxAgeRaw = req.query.max_age_hours?.trim();
|
||||
const maxAgeHours =
|
||||
maxAgeRaw != null && maxAgeRaw !== '' ? Math.max(0, parseInt(maxAgeRaw, 10)) : undefined;
|
||||
const store = await loadStore(storePath);
|
||||
const items = searchItems(store, site, {
|
||||
limit,
|
||||
topic,
|
||||
q,
|
||||
maxAgeHours,
|
||||
});
|
||||
return {
|
||||
site,
|
||||
limit,
|
||||
topic: topic ?? null,
|
||||
q: q ?? null,
|
||||
max_age_hours: maxAgeHours ?? null,
|
||||
count: items.length,
|
||||
items,
|
||||
};
|
||||
});
|
||||
|
||||
app.get('/stats', async () => {
|
||||
const store = await loadStore(storePath);
|
||||
const bySite: Record<string, number> = {};
|
||||
const bySource: Record<string, number> = {};
|
||||
for (const i of store.items) {
|
||||
bySite[i.site] = (bySite[i.site] ?? 0) + 1;
|
||||
const key = `${i.site}:${i.sourceFeedId}`;
|
||||
bySource[key] = (bySource[key] ?? 0) + 1;
|
||||
}
|
||||
return {
|
||||
total: store.items.length,
|
||||
bySite,
|
||||
bySource,
|
||||
storePath,
|
||||
};
|
||||
});
|
||||
|
||||
app.post<{
|
||||
Querystring: { site?: string };
|
||||
}>('/ingest', async (req, reply) => {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { searchItems } from './store.js';
|
||||
import type { StoreFile } from './types.js';
|
||||
|
||||
const baseItem = {
|
||||
id: 'a',
|
||||
site: 'andebol.net',
|
||||
sourceFeedId: 'feed1',
|
||||
url: 'https://example.com/a',
|
||||
title: 'Benfica vence jogo de andebol',
|
||||
summary: 'Resumo técnico da partida.',
|
||||
publishedAt: new Date().toISOString(),
|
||||
ingestedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
function storeWith(items: StoreFile['items']): StoreFile {
|
||||
return { version: 1, items };
|
||||
}
|
||||
|
||||
test('searchItems matches all query tokens in title or summary', () => {
|
||||
const store = storeWith([
|
||||
baseItem,
|
||||
{
|
||||
...baseItem,
|
||||
id: 'b',
|
||||
url: 'https://example.com/b',
|
||||
title: 'Futebol: clássico hoje',
|
||||
summary: 'Sem andebol.',
|
||||
},
|
||||
]);
|
||||
const hits = searchItems(store, 'andebol.net', { q: 'andebol benfica', limit: 10 });
|
||||
assert.equal(hits.length, 1);
|
||||
assert.equal(hits[0].id, 'a');
|
||||
});
|
||||
|
||||
test('searchItems respects maxAgeHours', () => {
|
||||
const old = new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString();
|
||||
const store = storeWith([
|
||||
{ ...baseItem, id: 'new', publishedAt: new Date().toISOString() },
|
||||
{ ...baseItem, id: 'old', publishedAt: old },
|
||||
]);
|
||||
const hits = searchItems(store, 'andebol.net', { limit: 10, maxAgeHours: 24 });
|
||||
assert.equal(hits.length, 1);
|
||||
assert.equal(hits[0].id, 'new');
|
||||
});
|
||||
|
||||
test('searchItems excludes drafted and skipped', () => {
|
||||
const store = storeWith([
|
||||
{ ...baseItem, id: 'ok' },
|
||||
{ ...baseItem, id: 'draft', wpDraftId: 9 },
|
||||
{ ...baseItem, id: 'skip', skippedReason: 'dup' },
|
||||
]);
|
||||
const hits = searchItems(store, 'andebol.net', { limit: 10 });
|
||||
assert.equal(hits.length, 1);
|
||||
assert.equal(hits[0].id, 'ok');
|
||||
});
|
||||
@@ -88,3 +88,46 @@ export function shortlist(
|
||||
.sort((a, b) => (a.publishedAt < b.publishedAt ? 1 : a.publishedAt > b.publishedAt ? -1 : 0))
|
||||
.slice(0, limit);
|
||||
}
|
||||
|
||||
export interface SearchItemsOptions {
|
||||
/** Space-separated tokens; every token must appear in title or summary (case-insensitive). */
|
||||
q?: string;
|
||||
topic?: string;
|
||||
limit: number;
|
||||
/** Drop items older than this many hours (from publishedAt). */
|
||||
maxAgeHours?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter items by site, optional topic, optional full-text-ish token match, and recency.
|
||||
* Results sorted newest first.
|
||||
*/
|
||||
export function searchItems(store: StoreFile, site: string, options: SearchItemsOptions): AggregatedItem[] {
|
||||
const now = Date.now();
|
||||
const maxAgeMs =
|
||||
options.maxAgeHours != null && options.maxAgeHours > 0
|
||||
? options.maxAgeHours * 60 * 60 * 1000
|
||||
: null;
|
||||
const words = (options.q ?? '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
|
||||
return store.items
|
||||
.filter((i) => {
|
||||
if (i.site !== site || i.wpDraftId || i.skippedReason) return false;
|
||||
if (maxAgeMs != null) {
|
||||
const t = new Date(i.publishedAt).getTime();
|
||||
if (Number.isNaN(t) || now - t > maxAgeMs) return false;
|
||||
}
|
||||
if (options.topic && !(i.topics?.includes(options.topic) ?? false)) return false;
|
||||
if (words.length) {
|
||||
const hay = `${i.title}\n${i.summary}`.toLowerCase();
|
||||
if (!words.every((w) => hay.includes(w))) return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.sort((a, b) => (a.publishedAt < b.publishedAt ? 1 : a.publishedAt > b.publishedAt ? -1 : 0))
|
||||
.slice(0, options.limit);
|
||||
}
|
||||
Reference in new issue
Block a user