This file documents community discovery (`devplacepy/services/community/`, `routers/admin/communities.py`, `cli/community.py`): finding an external community, learning its structure once, generating collectors, and feeding what they collect through the sync API. Claude Code auto-loads it whenever a file under `devplacepy/services/community/` is read or edited. The design record is `add_community.md`. ## What exists today | Piece | File | State | |-------|------|-------| | Constants, caps, statuses | `spec.py` (`CommunityLimits`) | built | | Path, feed and CSS extraction (stdlib only) | `extract.py` | built, tested | | Collector engine (retry, backoff, pagination, incremental, comments) | `runtime.py` | built, tested | | Search (rsearch), feed detection, structure learning, metadata | `search.py`, `feeds.py`, `learner.py`, `discoverer.py` | built, tested | | Code generation | `generator.py` | built, tested | | Persistence | `store.py` (`communities`, `community_runs`), `files.py` | built | | Push into sync, with dry run | `pusher.py` | built | | Run orchestration | `runner.py` (`CommunityRunner`) | built | | Scheduled service | `service.py` (`CommunityService`, opt-in, dry run by default) | built | | Admin pages | `/admin/communities`, `/admin/communities/{slug}` | built | | CLI | `devplace community discover\|run\|login\|list` | built | | Devii tools (`community_*`), docs group, privacy row | `services/devii/actions/catalog/community.py`, `docs_api/groups/community.py` | built, all administrator-only | | AI structure assistant | `ai.py` | built, optional, every proposal validated against the sample | | Login and credentials | `extract.find_login_form`, `runtime.Collector.login`, `discoverer.LoginLearner` | built | ## Flow `discover` -> `SearchPhase` (a direct address skips rsearch; otherwise `rsearch.app.molodetz.nl/search`, ranked by host/title match, social sites dropped, at most 5 candidates) -> `FeedDetector` (the page itself, ``, same-host "latest/posts/..." links one level deep, then a fixed list of probe paths; JS-only pages escalate to `Fetcher.render`) -> `StructureLearner` per feed -> `MetadataLearner` (name, description, language, favicon, member count, rules text) -> `Collector` verification run on a small sample. A community is only `ready` when the verification run collected at least one post. No feed plus a login wall is `login_required`; anything else is `failed` with the reason. Feed types: `rss`, `atom`, `json_api`, `html_list`. Learned field maps use the **sync record field names** (`id`, `title`, `content`, `created_at`, `updated_at`, author `username`/`id`, comment `parent_id`), each an ordered list of alternates; the collector emits records ready for `UserRecord`/`PostRecord`/`CommentRecord`. JSON paths are `$.a.b[0]`, `[*]`. XML feeds are converted to dicts so the same paths work (`$.link.@href`). HTML fields are `selector::text` or `selector::attr(name)`. ## Browser, JavaScript, login, AI - **stealthii is a project dependency** (`pyproject.toml`, git URL; the Dockerfile installs `git`). `fetcher.Fetcher` shares one stealth Chromium per event loop (`SharedBrowser`), applies the SSRF guard (`guard_public_url`) before every request and every `page.goto`, and waits at least `delay_seconds` between requests to one host. Without the browser it falls back to the guarded plain client and logs that JavaScript rendering is unavailable. `CommunityService.on_disable` closes the browser. - **JavaScript pages.** If a page yields nothing statically, detection renders it (`Fetcher.render_html`, `page.content()`); the feed is then marked `"render": true` and the collector renders it on every run. The same fallback applies to post pages when comments only exist after rendering. - **Comments and post bodies from HTML pages.** For any feed (RSS, Atom, JSON, HTML list) whose posts expose an address, `PageProbe` opens up to three post pages, finds the repeated comment element (class hint `comment|reply|response|answer`, nesting from DOM containment, id from `::attr(id)` else a stable hash), and learns a `mode: "page"` comments spec. It also learns a `post.detail.content` selector when the post page carries more text than the listing. JSON feeds still prefer `inline`/`url` comment modes. - **Login.** A community can store a username, an email and a password (columns `login_*`, never returned by any endpoint, admin form, Devii tool or CLI). Discovery finds the login form (page, login links, `/login`-style paths, rendered page), logs in with the session `community:`, then learns behind the wall. `schema.login` holds the form (action, field names, hidden defaults re-read at login for CSRF tokens, or selectors for a JavaScript page); `login_required` makes a missing account a clear `LoginRequired`. A rejected password raises `LoginFailed` and the community goes to `login_required`. Not supported: JSON-API logins, two-factor, captchas. - **AI.** When HTML heuristics are weak (no author, no title, content only raw text, no date) or find no item container, comment structure or post body, `AiAssistant` asks the internal gateway model (site setting `community_ai_model`, default `molodetz`; `community_ai=0` turns it off) for selectors. A proposal is accepted per field only if it matches at least 60% of the sampled elements. If the gateway is unreachable the learner continues with heuristics and logs it. - **Duplicate feeds.** Feeds whose sample posts overlap by half or more are learned once (the one with comments wins); comment feeds (`/comments.rss`) are never treated as post feeds; generic probe paths are only tried when no feed is advertised. ## Output: one engine, concrete file `runtime.py` is the only collector implementation. `CodeGenerator` writes `data/communities//collectors.py` by inlining `extract.py` and `runtime.py` (stdlib only), the learned `SCHEMA` as a literal, and one `collect_` wrapper per feed with the selectors in comments; plus `schema.json`. The service imports that file, so a human edit to `SCHEMA` takes effect. `python collectors.py` runs it standalone with `stealthii`; a login-protected community reads `COMMUNITY_USERNAME`/`COMMUNITY_EMAIL`/`COMMUNITY_PASSWORD` from the environment. The database row holds the schema; the files are regenerated when missing. ## Rules that are deliberate - **Dry run is first class.** `devplace community run --dry-run`, the admin "Dry run" button and the service setting `community_dry_run` (default on) collect and validate through the real sync processors with `dry_run=True`, log every step, write nothing and keep the watermark. Dependent records (a post whose author this dry run would create) are projected as `created` instead of `unknown_author`. A live run needs `sync_enabled=1` and honors `sync_origins` (`services/sync/gate.py`, shared with the `/sync` routes). - **Nothing unbounded.** Pages, posts, comment fetches, request delay, retries, body size, run time, runs kept (30) and communities per tick are static constants in `CommunityLimits`; no autotuning. - **Floor.** After `max_failures` (5) consecutive failed runs a community is disabled with status `failing` and the log says to relearn. The machine never deletes; a human relearns or deletes (`delete` is soft, `communities` is in `SOFT_DELETE_TABLES` and `UNREPORTABLE_TABLES`). - **Incremental.** The watermark is the newest `updated_at`/`created_at` per feed; a page that is entirely older ends pagination. The newest 10 posts have their comments re-fetched every run; duplicates are absorbed by the sync fingerprint (`unchanged`). - **Outbound HTTP** goes through `Fetcher` (stealthii plus the SSRF guard), never a bare client. - **Order.** users, posts, comments, in batches of 50. A comment's post and parent are always earlier in the batch. - Admin add and relearn run as per-worker `asyncio` tasks; the page shows a `busy` banner and a run row while they work. ## Measured Real run against `https://lobste.rs` (dry run, scratch database): RSS, JSON and HTML feeds detected, description/favicon/language/rules text learned, 25 posts and 24 authors collected from one page. Fixture tests cover RSS, Atom, JSON with inline comments and page pagination, and HTML lists. With stealthii and Chromium the same run learned lobste.rs from its `/rss` feed plus post-page comments (`li.comments_subtree`). Not measured: a real login-protected site, cursor pagination against a live site, the AI path against a live gateway (the local gateway rejected the scratch key, so heuristics ran). Fixtures cover JavaScript rendering, form login, a rejected password, RSS and HTML comments from post pages, feed deduplication and the AI validation. ## Gaps - Comment pagination on HTML post pages is not followed (first page only); `max_comment_posts` bounds the pages opened per run. - No two-factor, captcha or JSON-API login. - HTML learning is heuristic plus AI; a site whose markup defeats both needs a hand-edited `SCHEMA`. - Votes, reactions and attachments are not collected (the sync API does not take them). - Cross-feed duplicate detection compares the sampled post addresses at discovery time only. - Passwords are stored in plain text in the database, as chosen for now; they are masked everywhere they could be displayed. ## Selection, aliasing, translation Per-community options (`sync_options`) and the `community_alias_enabled` kill switch are documented in `devplacepy/services/sync/CLAUDE.md` ("Selection, identity aliasing and translation"). The runner calls `prepare` between collection and `SyncPusher`; skip counts appear in the run's `pushed["skipped"]` and in the totals as `skipped_`.