# aligned.click — one big pool, topics as embedding regions A Bluesky feed product. **A post belongs in a topic when its embedding is within the topic's distance threshold of one of the topic's exemplar posts or of the topic's own embedding (the closest anchor wins — the exemplars anchor the region where realistic posts live, the own embedding catches the concept phrase's pool posts the exemplars miss) AND the fit judge says yes.** Keywords are retrieval only — they widen the pool, they never decide membership. The main feed is the union of every fitted post. Anyone with an atproto handle can create a topic by writing a `click.aligned.feed.request` record to their own repo. ## The model - **Pool** (`feed/store.py` → `posts`) — every post any keyword ever retrieved (firehose match or backfill search), embedded with green-embedding (2560-dim), deduped by at:// URI. Grades are a property of the post, computed once and reused by every topic. - **Topics** (`topics`) — one per request record. The creator's verbatim words, embedded. No keywords on a topic. - **Membership** (`assignments`) — `cosine(post, topic) <= threshold` *and* `fit(post, topic) >= floor` (the LLM's 0-10 fit strength; default floor 5, `FIT_FLOOR`). The region is anchored on **exemplar posts** (`exemplars`): realistic posts the LLM writes for the topic at processing time (`feed/topics.exemplarize`), embedded like the pool so the region lands where actual posts live. A post is a candidate when it is within threshold of the topic's own embedding **or** of any exemplar (closest anchor wins — the exemplars anchor the region where the LLM's realistic posts live, the own embedding catches the concept phrase's pool posts the exemplars miss; both passes union them). Two passes: `pass_topic` (fit the pool posts inside a region) and `pass_post` (fit a fresh post against the topics whose region it falls in). - **Keywords** (`keywords`) — retrieval only. `candidate` → `indexed` → `disqualified` (too common) / `pruned` (no matches in too long). They only widen the pool; a topic's region gets covered by harvesting its text. ## Modules and their boundaries | Module | Job | May touch | Must never | |---|---|---|---| | `feed/` | the core: store, quality, fit, topics, keywords, state, common | everything (it is the interface) | run the servers or the worker | | `ingest/` | the background worker: jetstream, backfill, filter management | `feed.store`, `feed.topics`, `feed.keywords` writes | write app UI | | `feedgen/` | the atproto custom feed server (`getFeedSkeleton`) | `feed.store.main_feed` reads | write the store | | `app/` | the web product: public reads, the request write, the vote write, and the member fit/no-fit write | `feed.store` reads, topic creation (`start_topic` — it creates the topic immediately so it greys out in the pane, then runs the background pass; production leaves the pass to the worker's housekeeping), `feed.store.set_feedback` (member verdicts — private ground truth, not atproto records; gate is `admin/members.is_member`) | mutate grades or assignments | | `admin/` | the operator site (routed by the proxy at `/admin`): pool stats, keyword lifecycle, topic processing state + exemplars | `feed.store` reads, `feed.keywords.index_keywords` writes (retrieval only — it widens the pool, never membership); gate is `private/members.json` (`admin/members.py`) | mutate grades, assignments, or votes | | `shared/` | transport: greenpt, embed, post normalization, search | nothing — it is leaf code | import `feed/` or `ingest/` | | `lexicons/` | the atproto records (`click.aligned.feed.request`) | — | — | | `auth/` | the OAuth sidecar + session gate (own per product, no allowlist) | — | — | `feed/store.py` is the single interface between activities. `ingest` is the only writer of posts/keywords/assignments; `feedgen`, `app`, and `admin` read; `app` creates topics and votes (via records once auth lands — a topic is a `click.aligned.feed.request` record in the creator's repo, a +1 a `click.aligned.feed.vote` record in the voter's repo, so the truth lives on atproto and the store tables are its cache); `admin` adds retrieval keywords only. A topic appears in the store the moment its request is written (greyed in the pane until its pass is done); the firehose only pools posts, never request records — the worker's `sweep_requests` is just a safety net for requests written from another client. `shared/identity.py` resolves handles to DIDs and back (for `app` attribution lines and the proxy's login) — cached, network leaf. The main feed is chronological (`createdAt` desc), and each post carries the topics it fits with their creators' handles, plus its +1 vote count and the reader's own vote. `app/server.py` serves `/api/feeds` (reads `min_grade`/`min_fit` query params, sets `voted` for the caller) and `/api/vote` (writes a vote, 401 without a DID). **There is no dev mode**: the app never accepts a `did` query/body param to impersonate someone — the reader is whoever the proxy's `X-Forwarded-DID` says, so every write is a real record in a real account's repo. Login is the OAuth flow: `auth/proxy.py` serves the sign-in page at `/login` (atproto account intro, account-creation options — Eurosky, Bluesky — then the handle form), bounces to the sidecar, and lands a cookie that it forwards as `X-Forwarded-DID` to the app. ## Store tables (sqlite3 + numpy in `private/store.db`) The backend is SQLite for persistence plus in-process numpy for vector search (LanceDB was dropped — its wheels require AVX2 and crash on the mini-PC's Pentium G4400T; the pool is small, so brute-force cosine is milliseconds). `feed/store.py` is the only store interface; the DB lives on the mini-PC under `private/`. ## The admin gate: `private/members.json` The only allowlist in the product. A JSON file next to the store listing who is who: ```json { "admins": ["did:plc:…", "…"], "members": ["did:plc:…", "…"] } ``` `admins` may open the admin site (`/admin`, routed by the proxy) and use its writes. `members` — admins included — get the product's member surfaces, for now the fit/no-fit buttons under posts inside topics (the ground truth the judge will learn from). An entry may be a handle instead of a DID — `admin/members.py` resolves it against the public directory once and caches the result, so the file can be hand-edited with handles. `private/` is gitignored, so membership lives only on the host. - `posts` — uri (pk), handle, did, displayName, text, embedding, source_keyword (informational), createdAt, replyTo, media, like/reply/repost counts, grade, graded, why, first_seen, last_seen. `grade`/`graded`/`why` are owned by `mark_graded`; pool writes never merge them (`add_posts` overlays only `_POST_MERGE`, `_FIREHOSE_MERGE` narrower so a firehose re-see can't blank a handle the backfill filled). - `keywords` — keyword (pk), embedding, status, post_count, last_seen, last_indexed, provenance, created. - `topics` — rkey (pk), did, text, embedding, distance (threshold), status, processed, created, last_assigned. - `exemplars` — (topic, text) pk, embedding. The topic's region anchor: a handful of realistic posts the LLM wrote at processing time (`feed/topics.exemplarize`), so similarity lands where actual posts live instead of on the topic's concept-phrase embedding. - `assignments` — (uri, topic) pk, fit (score ≥ floor), score (0-10), why, judged, judgedAt. The score is the judge's cached strength; the feed filters on it (the web UI's sliders), never re-judges. - `votes` — (uri, did) pk, created. The web app's +1 buttons; count per post is informational, membership never depends on it. A +1 is really a `click.aligned.feed.vote` record in the voter's repo — this table is the cache that makes counts countable; `ingest/worker.sweep_votes` reconciles it from listRecords. - `feedback` — (uri, topic, did) pk, label (fit/no-fit), created. A member's verdict on a post inside a topic — the ground truth the judge prompt will learn from. Deliberately **not** atproto records: it is private, stored only here. Toggle semantics (the same verdict again clears it); the UI reads it back so the state persists. Written by `app/server.py /api/fit`, gated by `admin/members.is_member`. No worker touches it yet. - `parents` — (uri) pk, parent_uri, parent_did, parent_handle, parent_text, fetched. A reply's parent post, fetched once from the public AppView thread endpoint (`shared/search_posts.fetch_parent`) the first time the reply is judged and cached here, so the fit judge reads a reply in the context of what it replies to. The feed's display of a reply draws the parent itself via `` using the reply's `replyTo`, so this table serves the judge, not the render. - `llm` — id pk, kind (fit/quality/exemplar/harvest), uri, topic, prompt, response, created. Traceability: every LLM call (`feed/common.completion_tolerant`) is recorded with the user message sent and the raw model reply, so a category decision can be traced to the exact call. Append-only, bounded (kept at `LLM_KEEP` rows); the admin site shows the tail. - `private/progress.json` — per-topic status queue (`feed/store.log_progress`), written by the background passes (`feed/topics.start_topic`, plus a boot sweep in the app for stragglers — dev-mode; the worker's housekeeping is the production path). It is not part of the customer-facing product — a future dev/admin site can poll it to make a processing pass watchable. Distance is LanceDB cosine distance (1 − cosine similarity). Default topic threshold `TOPIC_DISTANCE=0.35`, env-tunable; feed grade floor `FEEDGEN_MIN_GRADE=6`. ## Post interaction: atproto-wc is display-only, writes are native records The page renders each pick as an `` element from the vendored `app/shared/atproto-wc.js` — it draws the post (text, images, engagement counts, and a built-in "Show replies" thread toggle) live from the author's PDS. **atproto-wc has no write widgets**: there are no like/repost/reply buttons that post records. All real interactions are written by `app/server.py` as atproto records through the auth sidecar, so they are real Bluesky activity, not our own: - `POST /api/vote` — our +1 (`click.aligned.feed.vote`), or +1 a topic (a vote record on the topic's `click.aligned.feed.request` uri). - `POST /api/engage {uri, kind: like|repost}` — a toggle that writes `app.bsky.feed.like` / `app.bsky.feed.repost` (subject = the post's strong ref; the CID is fetched from the author's PDS at click time, since the posts table keeps no CID). Clicking again removes the record via `listRecords` lookup. The feed/topic responses annotate each post with `liked`/`reposted` for the caller, read live from their repo (no mirror table). - Reply and quote **link out to bsky.app** (the post's thread URL) — bsky.app only implements the `compose` intent link, so there is no in-app composer for them yet. ## Conventions - **Stdlib first.** The repo's Python is stdlib plus the venv's two exceptions (LanceDB/pyarrow for the store, websockets for jetstream). All HTTP is `urllib`. The app/feedgen servers are `http.server`. No new dependencies without a reason and a `requirements.txt` bump. - **Imports** — `from feed import store` etc., modules import their siblings directly; never reach across the boundaries in the table above. - **The provider** is GreenPT. Chat via `shared.greenpt._completion` (`deepseek-v4-flash-0731`); embeddings via `shared.embed.embed` (`green-embedding`). The key comes from `GREENPT_API_KEY` in `.env`. - **Search** uses the crawler's own app password (`INDEX_BLUESKY_HANDLE` / `INDEX_BLUESKY_APP_PASSWORD`) via `shared.apppass`. Read-only. - **Judgement is per-post and parallel.** `feed/quality.py` grades a post once (fully static prompt, cacheable); `feed/fit.py` decides binary fit against a topic's text (criteria at the end of the prompt). No batch prompts — labels must be independent samples. The judge also keeps a topic feed **non-repetitive**: both passes feed it the topic's fitted posts around the post being judged — its chronological neighbours (`DUP_WINDOW`/2 each side, so a late-pooled post that lands mid-feed is read against what it sits between) plus the fitted posts most similar to it (`feed/store.judge_window` — similarity only selects what the judge reads), and its static system prompt scores a post that repeats one of them low, so a feed does not fill with reposts of the same article or an author stacking its posts. - **Everything env-tunable** (`feed/state.py`): caps, windows, concurrency, distance. Never hardcode a threshold. - A flaky provider must not kill a whole pass — use `feed.common.completion_tolerant`. - **Test writes go out under `testing2345.eurosky.social`** (`did:plc:7hn3f6avc5y76kh2yan3bygs`), never under a real person's handle. It is the dedicated throwaway account for exercising like/repost/vote/ request writes (log in through the proxy's `/login` handle form). Real accounts — including the aligned.click product account — must not be polluted with test records. ## Run ```sh .venv/bin/python ingest/worker.py # the pool grower + judge .venv/bin/python feedgen/server.py # the atproto feed server (127.0.0.1:8784) .venv/bin/python app/server.py # the web product (127.0.0.1:8782) .venv/bin/python admin/server.py # the admin site (127.0.0.1:8790, via /admin) ``` Environment lives in `.env` (gitignored): `GREENPT_API_KEY`, `INDEX_BLUESKY_HANDLE`, `INDEX_BLUESKY_APP_PASSWORD`, and the thresholds. ## Deploy: the only workflow is edit → commit → push → mini-PC pulls The mini-PC (the production host, `atproto-server@192.168.86.250`) is **read-only to this repo except through git**. Never edit code, config, or data directly on the mini-PC. The loop is always: 1. **Edit on this computer** (the checkout that has `origin` = tangled). 2. **Commit and push to tangled**: `git push tangled main`. 3. The mini-PC's systemd units each run `ExecStartPre=git fetch origin main && git reset --hard origin/main`, so **the next service start (or `systemctl restart …`, or a reboot) pulls latest `main` and runs it.** `deploy/install.sh` re-renders the units into `/etc/systemd/system/` from the pulled templates. Consequences: - **A deploy is a push, then a restart of the affected unit** — never a manual edit or rsync onto the mini-PC. `git pull` on the mini-PC is a manual debug step, not the normal path; the units do it for you. - **Change the store only from this repo's code.** The `feed/store.py` backend is sqlite3+numpy (the `private/` DB lives on the mini-PC). One-off data fixes (e.g. re-embedding a corrupted topic vector) are done by pushing a script or by a one-liner run over the mini-PC's own `.venv` — but any fix that should survive a redeploy must land in the code and be pushed. - **`deploy/*.service` templates are the source of truth for units.** If you change a unit on the mini-PC by hand, it is lost on the next `install.sh` run. Change the template, push, then re-run `install.sh`. - Remember the tunnel must be up for the site to answer; if it is down after a restart, `sudo systemctl start aligned-tunnel` (it is no longer bound to the proxy's lifecycle, so a proxy restart does not kill it). ## Testing There is no test framework. Verify by running the real flow: 1. `curl -X POST localhost:8782/api/request -d '{"text":"posts about X"}'` — creates a topic fast (one embed call). 2. Run `feed/topics.process_topic(rkey)` — the background half: seeds the pool's most-similar posts through the judge immediately (so a new topic shows posts before any keyword search), then harvests + indexes keywords to keep the pool growing into the region. Watch `feed/store.post_counts()` grow. 3. `curl 'localhost:8784/xrpc/app.bsky.feed.getFeedSkeleton?feed=at://aligned.click/app.bsky.feed.generator/main'` — the main feed. 4. `timeout 30 .venv/bin/python ingest/worker.py --once` — one jetstream round. Run `python -m pyflakes` over the Python after changes. ### Stale store cache after adding data A long-lived server caches table rows in memory for `STORE_TABLE_TTL` (15s, env-tunable) to avoid reloading on every query. After the worker adds topics or posts, a running app/feedgen can serve up to that long before it sees them. When verifying a brand-new topic's feed, restart the long-lived servers or wait out the TTL. Kill by PID, not `pkill -f` — the pattern matches the shell running the command.