- Python 84.8%
- TypeScript 10.2%
- CSS 3.9%
- JavaScript 0.6%
- Dockerfile 0.4%
- Other 0.1%
| docs | ||
| migrations | ||
| news | ||
| review | ||
| scripts | ||
| tests | ||
| web | ||
| .dockerignore | ||
| .env.example | ||
| .gitattributes | ||
| .gitignore | ||
| alembic.ini | ||
| docker-compose.yml | ||
| Dockerfile | ||
| Dockerfile.semantic-bench | ||
| pyproject.toml | ||
| README.md | ||
| requirements-rich.txt | ||
| requirements-semantic.txt | ||
| requirements.lock | ||
| requirements.txt | ||
News Intelligence
A self-hosted personal news reader and foundation for external company/industry intelligence. Reports are grouped into stories so you can compare publishers, inspect source health, and retrieve explainable company and industry signals through a REST API. Dynamics 365 integration is intentionally not implemented.
Architecture
Four Compose containers: PostgreSQL 17 + pgvector (news-db), FastAPI (news-api), a Python worker (news-worker), and Next.js (news-web). The API and worker share the news/ domain package. Discovery, normalization, deduplication, embeddings, clustering and classification are separate modules. Data lives in PostgreSQL, not Dynamics. See architecture and limitations and security.
Prerequisites and setup
Only Docker Engine/Desktop with Docker Compose is needed to run the stack. No host Python, Node, PostgreSQL or pgvector installation is required.
git clone https://git.eiyq41.ddnss.de/admin-forgejo/news-intelligence.git
cd news-intelligence
cp .env.example .env
Set POSTGRES_PASSWORD in .env to a long random hexadecimal string; hex avoids URL-escaping issues in the database connection string. For example, generate one with openssl rand -hex 24 on Linux, then save it in .env. Do not commit it. On PowerShell, use Copy-Item .env.example .env and a password manager to generate the value. Restrict .env permissions on multi-user hosts.
docker compose up -d --build
docker compose ps
Default UI: http://localhost:3010. API documentation: http://localhost:8011/docs. The database has no published host port. PostgreSQL data persists in the news-intelligence_news-data named volume. docker compose down retains this volume; do not use down -v unless you intend to erase the database.
The current Pop!_OS deployment uses /home/rolfkrauss/news-intelligence, with BIND_ADDRESS=192.168.29.126. UI: http://192.168.29.126:3010; API documentation: http://192.168.29.126:8011/docs. Use this only on the trusted private network. SSH: rolfkrauss@pop-os. No host credentials or deployment secrets are stored in this repository.
Configuration
| Variable | Default | Purpose |
|---|---|---|
POSTGRES_PASSWORD |
required | Database password, used by Compose to construct DATABASE_URL |
BIND_ADDRESS |
127.0.0.1 |
Address for published web/API ports |
WEB_PORT / API_PORT |
3010 / 8011 |
Host ports |
DATABASE_URL |
supplied by Compose | SQLAlchemy URL; override directly for standalone development |
INGESTION_INTERVAL |
900 |
Initial per-source polling interval, in seconds; stored on first seed |
CLUSTER_THRESHOLD |
0.48 |
Historical lexical mode only |
CLUSTER_WINDOW_HOURS |
72 |
Maximum cluster publication span |
EMBEDDING_PROVIDER |
local |
CPU MiniLM; alternatives: openai, lexical, disabled |
SEMANTIC_THRESHOLD / SEMANTIC_STRONG_THRESHOLD / SEMANTIC_SUPPORTED_THRESHOLD |
0.76 / 0.86 / 0.68 |
Evidence-dependent similarity gates |
CLUSTER_COHESION_THRESHOLD |
0.60 |
Minimum similarity to every member |
EMBEDDING_THREADS |
2 |
CPU inference threads |
SUMMARY_PROVIDER |
deterministic |
Attributed extractive brief; optional openai |
FALLBACK_SUMMARY_PROVIDER |
deterministic |
Fallback on missing key or provider failure |
LLM_PROVIDER |
none |
Legacy code setting; Compose uses SUMMARY_PROVIDER |
SUMMARY_MODEL |
gpt-4.1-mini |
Optional summary model |
SUMMARY_MIN_SOURCES |
3 |
Estimated unique reports needed for optional LLM synthesis (at least two publishers) |
PRIVATE_MODE |
true |
Use private-owner display gates; public mode additionally requires redistribution rights |
RICH_CONTENT_ENABLED |
false |
Enable the separately reviewed, policy-gated body extractor |
RICH_CONTENT_BATCH |
5 |
Maximum body attempts per worker cycle, at most one per host |
SUMMARY_NEW_SOURCES / SUMMARY_NEW_ARTICLES |
2 / 3 |
Material-change thresholds for another LLM attempt |
OPENAI_API_KEY |
empty | Only used by explicitly selected OpenAI providers |
DEMO_ENABLED |
true |
Seed clearly fictional examples on startup |
COMMERCIAL_MODE |
false |
Reject ingestion and hide stories from sources lacking commercial permission |
LOG_LEVEL |
INFO |
Worker logging level |
Changing INGESTION_INTERVAL does not overwrite existing source schedules. Edit sources.poll_interval through a controlled database administration process. DEMO_ENABLED=false stops demo seeding; existing demo rows remain available with mode=demo. The default API and UI mode is always live.
The default is the actual all-MiniLM-L6-v2 Sentence Transformer, pinned to revision 1110a243fdf4706b3f48f1d95db1a4f5529b4d41. Docker installs CPU-only PyTorch, produces normalized 384-dimensional vectors and caches the model in the persistent model-cache volume. First inference downloads the model; cached inference can run offline. Tests inject fakes and never download models. Real inference outside Docker also requires requirements-semantic.txt and the CPU torch version in the Dockerfile.
lexical retains the old hash baseline. disabled uses strict headline matching without embeddings. openai uses text-embedding-3-small, 384 dimensions with a configured key, otherwise local MiniLM. Paid embedding mode sends permitted metadata to OpenAI. No paid calls were made during this rollout. Database caches use exact input hashes and model/revision keys. Model spaces never mix; changing providers for an existing corpus requires explicit reconciliation.
Stories now have a controlled primary category and optional secondary categories, separate from extensible topics, industries and entities. Category pages and topic filters support discovery. Deterministic briefs attribute selected details from permitted bodies, descriptions or metadata, falling back to complete headlines and explicit uncertainty. Multi-publisher titles remain shared-subject/event labels. These are extractive briefs, not independently verified facts.
Optional SUMMARY_PROVIDER=openai uses Responses with store=false, at most 12 distinct reports, bounded permitted context and 400 output tokens. It runs after ingestion batches only for significant, materially changed clusters. Unchanged clusters and unchanged failed attempts do not repeatedly call the provider. Default deterministic mode makes no summary API calls. Logs show requests and usage without keys or input text. Image metadata/display/hotlink/cache permissions default to false; hero images require explicit scoped rights, otherwise category fallbacks appear. See the category and briefing rollout for configuration, provenance, image limits and validation.
See clustering benchmark and review for diagnostics, reconciliation commands and known ambiguity.
Migrations and seeds
The API startup takes a PostgreSQL advisory lock, applies Alembic migrations, seeds missing reference records, optionally seeds fictional examples, and starts serving. The worker and web wait for API health. Restarting does not duplicate reference data or demos. Source policies edited by an operator are preserved. Built-in topic and root-industry rules are maintained from code.
docker compose exec news-api python -m alembic current
docker compose exec news-api python -m alembic upgrade head
Run manual migration commands with only one operator; normal startup already coordinates migration concurrency. Back up before schema changes. Add future revisions under migrations/versions; do not modify applied schema definitions to introduce changes.
Tests and deployment checks
Tests do not require external feeds or paid APIs. RSS/Atom bytes, fake embeddings and fake LLMs are local fixtures.
# Default test suite, using isolated in-memory SQLite
docker compose exec news-api python -m pytest -q
# Same domain/API suite against pgvector/PostgreSQL, temporary transaction-scoped schemas
docker compose exec news-api python -m scripts.test_postgres
# Read-only live ingestion, schema, vector and deduplication counts
docker compose exec news-api python -m scripts.check_deployment
The PostgreSQL tests create uniquely named schemas and roll them back, retaining the live data. They require schema-creation permission. The migration round-trip test uses a temporary database file.
Frontend smoke tests can run in the existing container without host Node:
docker compose exec -e WEB_TEST_URL=http://127.0.0.1:3000 news-web node --test tests/smoke.test.mjs
For local Node testing: WEB_TEST_URL=http://localhost:3010 node --test web/tests/smoke.test.mjs. These five tests require the deployed UI with demos enabled. The production image build runs Next.js compilation and TypeScript checking. Browser QA covers navigation, company search, story coverage, source policy expansion and responsive layout.
Adding a source
- Find an official RSS/Atom endpoint or approved provider; verify a successful parse and the publisher's permissions. Never invent URLs or bypass access restrictions.
- Add a publisher entry to
news/source_registry.json, including country, domain, feed URL, verification timestamp, evidence URL and reason. Keepenabled=falseuntil permissions and operation are reviewed. A source without a usable discovery mechanism should havefeed_url=nulland a clear disabled reason. - Rebuild and restart. Missing publisher/source/policy records are inserted. Enabled, reviewed RSS entries use metadata-only policies; all body, snippet and commercial permissions remain false.
- For APIs/licensed feeds, implement
NewsSourceAdapterinnews/adapters.pyand register its discovery method. Do not add page scraping as an implicit RSS fallback. - Test with fixture bytes, policy denial, invalid entries and repeat polling before enabling.
scripts/verify_feeds.py can regenerate availability evidence during development. It makes network requests and replaces the checked-in registry, so review its diff before committing. Reachability checks are not legal-rights grants. See source registry notes.
Source policies
Policies independently record metadata ingestion, private body fetch/storage/owner display, body analysis, snippets, public redistribution and commercial use, plus license URL/type/notes and review date. New grants default to false. The RSS adapter still discards content:encoded and never fetches article pages. A separate reviewed-source extractor can store normalized plaintext in content-addressed ArticleContent blobs; the legacy Article.full_text column stays null. See the source-by-source review and enforcement.
The API omits denied snippets and bodies and hides metadata-disallowed articles, including direct story lookups. Story detail includes plaintext only when its source policy permits display; there is no direct blob endpoint. Private owner display requires PRIVATE_MODE=true; public mode additionally requires redistribution rights. Commercial mode requires an explicit commercial grant. Policy changes invalidate cached summary display immediately. Source administration remains outside the read-only API; retained blobs/backups still need separate operator review after revocation.
Articles retain their publisher links inside estimated ContentGroup reports inside a Story. Duplicate headlines, substantial matching descriptions/bylines and permitted body hashes can collapse likely syndicated copies into one report. Counts distinguish URLs, publishers and estimated unique reports; the latter drives coverage sorting and optional LLM eligibility. No count proves editorial independence. See the 34-pair reusable review workflow, which separates human labels from provisional assistant judgments.
To enable the reviewed private workflow, inspect python -m news.policy_review, apply with --apply, and set RICH_CONTENT_ENABLED=true in the private deployment's .env. Only NASA and Federal Reserve official release paths are approved by this review. Access/robots failures still deny retrieval. Stop the worker before running python -m news.maintenance content-groups to backfill existing stories without changing their IDs or membership. Default embeddings and summaries remain local; additional syndicated copies do not trigger paid summaries.
API overview
OpenAPI: /docs and /openapi.json. All endpoints are read-only and unauthenticated for the trusted-network V0.1 deployment.
| Endpoint | Purpose |
|---|---|
GET /api/health |
Database connectivity and story-table readiness |
GET /api/sources |
Publisher policy and polling health |
GET /api/sources/{id} |
Source details and latest 20 poll runs |
GET /api/stories |
Event clusters, source counts, entities, industry/topic tags |
GET /api/stories/{id} |
Reporting links, permissible snippets, publisher rating distribution and comparison limits |
GET /api/news/company?q=LANXESS |
Canonical name, exact alias or domain retrieval |
GET /api/news/industry?q=Aerospace |
Canonical name, ID or unambiguous prefix; includes descendants |
GET /api/entities |
Seeded companies, aliases and domains |
GET /api/industries |
Small hierarchical taxonomy |
Story collections support page, page_size (1–100), date_from, date_to (ISO timestamps), source_id, mode=live|demo|all, and sort=latest|oldest|coverage. Dates select stories whose publication interval overlaps the requested range. Company/industry queries also support min_relevance (0–1) and sort=relevance. Sorting has stable UUID tie-breakers. The UI's “Through” date includes that entire UTC day. Unknown companies return an empty collection; invalid filters return 422. Missing IDs return 404.
Company evidence distinguishes direct mentions (0.95), optional semantic company-profile similarity (threshold 0.55, relevance capped at 0.79), and related industry signals (0.40). These are explainable scores, not calibrated probabilities. The Company UI defaults to min_relevance=0.8 for direct mentions; choose All signals for wider coverage. Topic/industry matching remains approximate.
/api/news/company?q=LANXESS%20AG&mode=demo&min_relevance=0.8
/api/news/company?q=microsoft.com&sort=relevance
/api/news/industry?q=Aerospace&mode=demo
/api/stories?sort=coverage&page_size=20
See future Dynamics consumption. UUID story IDs persist across restarts and reclassification. Reconciliation preserves absorbed IDs as HTTP 307 redirects and creates new IDs for splits when needed.
Operations and troubleshooting
docker compose ps
docker compose logs --tail=100 news-api news-worker
docker compose restart news-worker
docker compose exec news-api python -m news.maintenance reclassify
- No stories yet: the first feed cycle and classification take a little time. Check Sources; explore Synthetic demo while waiting.
- A source fails: other sources continue. Inspect its last error and poll history. Errors expose exception categories, not credentials or publisher response bodies. Disabled/unverified feeds are not repeatedly retried.
- No company result: only seeded entities are resolved; try an exact alias/domain, check demo mode or lower the relevance filter for related industries.
- Brief platform summaries: headline-only inputs limit detail. Permitted descriptions/bodies produce richer attributed briefs; optional OpenAI synthesis remains separate from embedding configuration and explicitly unverified.
- Port conflict: change
WEB_PORT/API_PORTin.env, then recreate the stack. Pop!_OS port 8010 was already occupied, so this project uses 8011. - Unhealthy API: inspect startup logs for database/migration errors. The database password in
.envmust match the existing persistent PostgreSQL volume; changing.envalone does not rotate the database password. - Unhealthy worker: inspect source timeouts and processing errors. Failed articles remain unclustered and retry on a later cycle. Docker health status itself does not automatically restart an unhealthy but running process.
Back up with docker compose exec -T news-db pg_dump -U news -d news -Fc > news.backup. Keep backups outside Git and test restoration into a separate database before relying on them.
Development workflow
The local checkout is C:\Dev\news-intelligence; Git identity is separate. Inspect git status and git remote -v before changes. Use coherent milestone commits, run relevant tests, inspect diffs and never stage .env, backups, tokens or provider keys. Never force push or modify Forgejo authentication as a deployment workaround.
For local Python development: create a Python 3.12+ virtualenv, install requirements.lock and requirements-rich.txt, then run python -m pytest. For Next.js: cd web && npm ci && npm run dev. Set server-only API_INTERNAL_URL to a reachable API. Container builds use pinned direct Python dependencies and npm ci; the semantic/rich optional dependency files are not complete transitive locks. requirements.txt documents base direct dependency ranges; refresh the lock deliberately and validate on Linux/Python 3.12. npm run typecheck checks TypeScript. Use Ruff/Prettier for code formatting.
Changes deploy with docker compose up -d --build. The initial milestones and any deployment limitations are recorded in validation.