Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
name: ci

on:
push:
branches: [main]
pull_request:

jobs:
backend:
runs-on: ubuntu-latest
defaults:
run:
working-directory: backend
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: loopwire_test
ports: ["5432:5432"]
options: >-
--health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10
env:
TEST_DATABASE_URL: postgresql+psycopg2://postgres:postgres@localhost:5432/loopwire_test
DATABASE_URL: postgresql+psycopg2://postgres:postgres@localhost:5432/loopwire_test
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v5
- run: uv sync --frozen
- name: Lint
run: uvx ruff check app tests evals scripts
- name: Unit tests (real Postgres, no network/LLM)
run: uv run pytest
- name: Migrations apply cleanly and match models
run: |
psql postgresql://postgres:postgres@localhost:5432/postgres -c "CREATE DATABASE loopwire_migrate"
DATABASE_URL=postgresql+psycopg2://postgres:postgres@localhost:5432/loopwire_migrate uv run alembic upgrade head
DATABASE_URL=postgresql+psycopg2://postgres:postgres@localhost:5432/loopwire_migrate uv run alembic check

dashboard:
runs-on: ubuntu-latest
defaults:
run:
working-directory: dashboard
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: dashboard/package-lock.json
- run: npm ci
- run: npx tsc --noEmit
- run: npm run lint
- run: npx next build
env:
AUTH_SECRET: ci-placeholder
AUTH_GOOGLE_ID: ci-placeholder
AUTH_GOOGLE_SECRET: ci-placeholder
34 changes: 34 additions & 0 deletions .github/workflows/evals.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: evals

# Real-LLM evals cost quota, so they run on demand and weekly, not per push.
# Exit code 1 when a regression gate fails (see backend/evals/run_all.py).
on:
workflow_dispatch:
inputs:
only:
description: "Comma-separated: extraction,summary,recall,ranking"
default: "extraction,summary,recall,ranking"
schedule:
- cron: "0 3 * * 1"

jobs:
evals:
runs-on: ubuntu-latest
defaults:
run:
working-directory: backend
env:
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
EVAL_JUDGE_MODEL: ${{ vars.EVAL_JUDGE_MODEL }}
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v5
- run: uv sync --frozen
- run: uv run python -m evals.run_all --only "${{ github.event.inputs.only || 'extraction,summary,recall,ranking' }}"
- uses: actions/upload-artifact@v4
if: always()
with:
name: eval-report
path: |
backend/evals/REPORT.md
backend/evals/results/
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,8 @@ dashboard/.env*.local
prd.md

.claude
prdv2.md
prdv2.md

# Eval caches (scraped article text, model outputs) and per-run results
backend/evals/.cache/
backend/evals/results/
608 changes: 354 additions & 254 deletions README.md

Large diffs are not rendered by default.

13 changes: 9 additions & 4 deletions SETUP.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ for the real Telegram → Supabase → Gemini → Resend flow.
from `postgresql://` to `postgresql+psycopg2://` (SQLAlchemy needs the driver
name), e.g.:
`DATABASE_URL=postgresql+psycopg2://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:5432/postgres`
6. Run `cd backend && uv run python -m app.init_db` to create tables (each
6. Run `cd backend && uv run python -m app.init_db` to apply the database
migrations (Alembic; safe to re-run, and Render runs it on every start). (Each
user's interest profile starts blank until they set it in Settings —
there's no seeded default anymore, since Phase A made this multi-tenant).

Expand Down Expand Up @@ -125,12 +126,16 @@ a schedule, which also happens to wake the service up if it was asleep.
- URL: `https://<your-render-url>/send-digest?key=<SEND_LOOPWIRE_SECRET>`
- Schedule: whatever you want (e.g. daily at 08:00 in your timezone)
- Request method: `POST`
- Better: drop `?key=` from the URL and send the secret as an
`X-Cron-Key` header instead (query strings end up in access logs)
3. Save. That's the entire schedule - no code or redeploy needed to change
the time later, just edit the cron job.
4. Test it immediately with the "Execute now" button in cron-job.org's UI,
or manually: `curl -X POST "https://<your-render-url>/send-digest?key=<SEND_LOOPWIRE_SECRET>"`
Expect `{"status": "sent", "items_count": N}` (or `"no_new_items"` if
nothing's been summarized since the last dispatch).
Expect `202 {"status": "accepted"}` - the dispatch is built in the
background because it makes several LLM calls and cron-job.org times out
after 30s. Add `&wait=true` to block and get
`{"status": "sent", "sent_count": N}` (or `"no_new_items"`) instead.

If you'd rather self-host on something that supports always-on processes
(a paid Render plan, a VPS, etc.), `app/scheduler.py`'s `start_scheduler()`
Expand Down Expand Up @@ -345,7 +350,7 @@ Google sign-in button.

From `backend/`:
```bash
uv run python -m app.init_db # one-time: create tables
uv run python -m app.init_db # apply migrations (safe to re-run; --reset wipes local data)
uv run uvicorn app.main:app --reload --port 8000 # API + webhook + /send-digest + /process-pending
```

Expand Down
14 changes: 13 additions & 1 deletion backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ TELEGRAM_BOT_TOKEN=

# --- Gemini (Google AI Studio) ---
GEMINI_API_KEY=
GEMINI_MODEL=gemini-2.5-flash
GEMINI_MODEL=gemini-3.5-flash-lite

# --- Resend (email delivery) - sender only; recipient is each user's own
# account email now that Loopwire is multi-tenant. ---
Expand Down Expand Up @@ -43,6 +43,18 @@ PROCESS_PENDING_SECRET=
# Generate the same way as the other secrets above.
INTERNAL_AUTH_SECRET=

# --- Signed engagement links (required) ---
# HMAC key for the public /r/, /f/ and open-pixel links in emails. Without a
# signature those links would be enumerable by id. Generate like the others.
TRACKING_SIGNING_SECRET=

# Timezone for per-day caps and dispatch dates.
APP_TIMEZONE=Asia/Kolkata

# --- Evals (optional) ---
# Judge model for evals/; blank = newest Gemini Flash your key can access.
EVAL_JUDGE_MODEL=

# --- Webshare residential proxy (optional) ---
# Without this, YouTube extraction fails on any cloud host (Render, AWS,
# GCP, etc.) - YouTube blocks transcript requests from datacenter IPs
Expand Down
149 changes: 149 additions & 0 deletions backend/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/migrations

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .


# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the tzdata library which can be installed by adding
# `alembic[tz]` to the pip requirements.
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =

# max length of characters to apply to the "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions

# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os

# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
# sqlalchemy.url is set from app settings (DATABASE_URL) in migrations/env.py


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME

# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME

# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARNING
handlers = console
qualname =

[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
20 changes: 19 additions & 1 deletion backend/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class Settings(BaseSettings):

# LLM
gemini_api_key: str = ""
gemini_model: str = "gemini-2.5-flash"
gemini_model: str = "gemini-3.5-flash-lite" # 2.5-flash routes here from 2026-12-01 anyway

# Email (Resend) - sender address is fixed/branded; the recipient is
# each user's own account email now (Phase A), passed per-call instead
Expand Down Expand Up @@ -69,6 +69,24 @@ class Settings(BaseSettings):
webshare_proxy_username: str = ""
webshare_proxy_password: str = ""

# --- Signed engagement links ---
# HMAC key for /r/<token>, /f/<token> and the per-send open pixel. These
# links are public (email clients can't send auth headers), so they used to
# take a bare sequential item id: anyone could walk /r/1, /r/2, ... and
# read every user's saved URLs, or forge clicks into someone's ranking.
# Falls back to internal_auth_secret so a missing value never means
# "unsigned" - see tracking.py.
tracking_signing_secret: str = ""

# Timezone used for "per day" caps and the dispatch date. Caps used to
# reset at UTC midnight, i.e. 5:30am for the IST users this targets.
app_timezone: str = "Asia/Kolkata"

# --- Evals (evals/) ---
# Judge model for LLM-graded evals. Kept separate from gemini_model so the
# system under test isn't grading itself with the same checkpoint.
eval_judge_model: str = ""


@lru_cache
def get_settings() -> Settings:
Expand Down
Loading
Loading