Peach: Local-first video metadata scraper and media manager.
feat: add bounded RSS and Atom follow adapter
Peach local maintenancedfc775347cd1
diff --git a/README.md b/README.mdindex 7d7faf625..23b573af3 100644--- a/README.md+++ b/README.md@@ -59,3 +59,5 @@ cd R:\peach-app`scripts/scrape_codes.py` 默认只把番号发送到已声明的元数据源并写复核 CSV;只有 `--apply` 才写 ledger。`scripts/clean_names.py` 默认只生成改名计划;`--apply` 会先备份 SQLite,并在数据库更新失败时把文件名回滚。两者导入模块时均无副作用,测试不得使用真实路径。`/api/providers` 是无副作用 capability health;`/api/providers/opencode-go/models` 只在显式访问时拉取 OpenCode Go 的公开模型清单,不发送推理请求或读取本机 CLI 凭据。++在线追更从 `FeedAdapter` 的 RSS/Atom 候选发现开始:只有显式调用才联网,支持条件请求和有界读取,当前不会自动写 ledger。diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex c8d128d84..a2cbed277 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -12,6 +12,7 @@ Peach 是逻辑前后端分离、部署仍为一个进程的 FastAPI 模块化4. **Web**:当前是无构建步骤的单页,保持移动端优先;不做 React 重写。5. **AI providers**:`InferenceProvider` 与 `AgentProvider` 分离。AI 只产出带 provenance/confidence 的候选。6. **Profiles**:默认单用户,数据模型预留 user/profile,不引入完整账号体系。+7. **Follow sources**:RSS/Atom 等成熟协议先归一化为只读候选;原始证据、review 和 ledger 写入分层。## Data flowdiff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex d37a069c4..b43da85be 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -41,6 +41,7 @@ This is durable operating knowledge, not a per-session transcript.- Item/detail/filter/search/facets/index/stats/top lists/related ranking use canonical relations. Flattened creator/studio fields remain only as response compatibility projections; do not use them for identity or matching.- Keep FastAPI and the front end logically separate but deploy as a monolith.- External sources and AI are supported only through explicit adapters and declared data boundaries.+- `FeedAdapter` is the first online-follow connector. It performs explicit bounded RSS/Atom discovery only; do not make it poll on application startup or write ledger rows directly.- AI provider layers are not equivalent: inference APIs and local coding/agent runtimes remain separate.## Recoverydiff --git a/docs/STATUS.md b/docs/STATUS.mdindex af1bdc2f8..6a97d6bf6 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -4,7 +4,7 @@ Last verified: 2026-08-14## Runtime-- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, server PID observed as 58832; health mode is `fastapi`.+- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, server PID observed as 52476; health mode is `fastapi`.- mDNS publisher: `peach.local` is published on `192.168.50.162` as HTTP, but an actual LAN client could not resolve it. Use `http://192.168.50.162/` until the client/router multicast path is fixed; no firewall/router change was made.- Stash: `127.0.0.1:9999`, PID observed as 35332.- Traffic monitor: running through `RM-TrafficWatch` from `R:\peach-app\.venv`; all probe/sheets tasks use the same project environment.@@ -23,6 +23,7 @@ Runtime PIDs are observations, not configuration; always re-check them.- Migration `0002` added canonical entity/alias/external-ref/asset-relation tables and backfilled existing performer/tag/studio/creator/series projections. After the post-migration external-metadata reconciliation, the real ledger has 8,603 entities and 131,877 relations. The Stash and external-metadata importers dual-write canonical relations while retaining flattened UI projections.- Passive `/api/providers` health discovery now exposes separate inference/agent capabilities without model calls, credential reads or secret values.- The OpenCode Go adapter now supports explicit public model discovery through `/api/providers/opencode-go/models`, with a five-minute in-memory cache and normalized secret-free output. It does not invoke inference or read CLI credentials.+- The first online-follow connector is a generic explicit RSS/Atom `FeedAdapter`: conditional requests, bounded response reads, normalized entries and no ledger writes. It has only isolated feed tests so far; no real feed was contacted.- Snapshot rows still contain 10,714 pre-split `R:\Resources\Intake\snapshots` paths. Runtime now performs a strict legacy-prefix rebase to `R:\peach-data\generated\snapshots`; it does not mutate the real ledger.- `R:\peach-data` now separates `database/generated/sources/state/secrets/logs/archive/inbox/tools`; the old empty root Inbox and old Resources/Tools compatibility surface are removed.- `web_contract.py` now uses an application-owned database/cache/write-lock context rather than module globals; separate app instances cannot leak databases or caches into each other.@@ -30,7 +31,7 @@ Runtime PIDs are observations, not configuration; always re-check them.- Creator/studio top lists and related-item creator/tag/studio matching now read canonical entity relations. Real-ledger timings were 0.055 s for 28 top entries and 0.055 s for 24 related items.- Creator/studio filters, canonical-name search, creator index, facets and attribution stats now also read entity relations. Real-ledger timings were 0.040 s for a 1,545-item creator filter, 0.043 s for the first 60 creators, 0.132 s for facets and 0.394 s for stats.- Snapshot availability checks use the same strict legacy-prefix resolver as `/thumb`, so the front end requests migrated previews instead of displaying false “无预览” cards.-- 39 isolated tests and tracked-script static compilation passed under Python 3.14.+- 42 isolated tests and tracked-script static compilation passed under Python 3.14.- Real migration preserved 81,873 assets and 59,697 tag links; both live database and backup passed `integrity_check` and `foreign_key_check` before later metadata writes.- Desktop 1280×720 and mobile 390×844 browser checks passed on the same application candidate before the schema-only migration; visual checks were not rerun after migration because no browser instance was connected.- Restarted production port 80 passed health, home, public OpenCode Go model discovery (26 models at verification time), canonical filtered-list/item reads, thumbnail `200` and 1 KiB `206 Partial Content` Range smoke checks.@@ -59,6 +60,6 @@ Runtime PIDs are observations, not configuration; always re-check them.## Next work-1. Add the first tracked online-follow source adapter; keep metadata scraping as a reviewable batch pipeline.+1. Add configured feed persistence under `peach-data/sources`, conditional-request state and a reviewed candidate import without automatic ledger writes.2. Add reviewed inference requests behind the OpenCode Go adapter; AI output must remain a candidate and cannot write ledger truth directly.3. Replace remaining flattened creator/studio display projections only when the front end can consume canonical DTO fields without breaking compatibility.diff --git a/docs/adr/0007-online-follow-feed-adapter.md b/docs/adr/0007-online-follow-feed-adapter.mdnew file mode 100644index 000000000..720c2cbbf--- /dev/null+++ b/docs/adr/0007-online-follow-feed-adapter.md@@ -0,0 +1,28 @@+# ADR-0007:在线追更首先复用 RSS/Atom 协议++- 状态:Accepted+- 日期:2026-08-14++## 背景++Peach 把在线追更列为正式能力,但尚无 connector。直接从站点 HTML、私有接口或浏览器状态开始,会把站点易变结构、认证、抓取和 ledger 写入耦合在一起。++## 决策++- 第一类追更 connector 复用 RSS 2.0/Atom 公开协议,由 `FeedAdapter` 统一输出稳定候选 DTO。+- 网络请求只能由显式调用触发;服务启动、health 和普通浏览均不自动联网。+- adapter 支持 ETag/Last-Modified 条件请求、15 秒超时、5 MiB 有界读取,以及 RSS enclosure/Atom enclosure 媒体候选。+- URL 只允许无内嵌凭据的绝对 HTTP(S) 地址;凭据不得写入 URL、日志或 ledger。+- adapter 只发现候选,不自动写 ledger 真相。后续必须把原始响应存入 `peach-data/sources`,再通过带 source/provenance/review 的导入边界写入。+- 无 feed 的站点以后实现独立 connector;不得把站点专用 HTML 规则塞进通用 feed adapter。++## 后果++Peach 获得可测试、低耦合的首个在线追更边界,并复用成熟协议;具体 feed 配置、调度、原始快照和 reviewed import 仍需下一阶段实现。当前没有对真实站点发起追更请求,也没有修改 ledger。++## 拒绝方案++- 服务启动时自动轮询所有来源。+- 用浏览器 Cookie 或 URL 内嵌账号密码抓取。+- 解析结果直接创建/覆盖资产。+- 为首个 connector 引入独立抓取服务或消息队列。diff --git a/src/peach/follow.py b/src/peach/follow.pynew file mode 100644index 000000000..088ac596c--- /dev/null+++ b/src/peach/follow.py@@ -0,0 +1,203 @@+"""Explicit online-follow adapters.++Adapters discover remote candidates only. They do not write ledger truth; callers must+persist raw evidence and submit normalized entries through a review boundary.+"""+from __future__ import annotations++import hashlib+import html+import re+import urllib.error+import urllib.parse+import urllib.request+import xml.etree.ElementTree as ET+from dataclasses import dataclass+from typing import Callable, Mapping, Protocol+++DEFAULT_MAX_BYTES = 5 * 1024 * 1024+++class FollowSourceError(RuntimeError):+ pass+++@dataclass(frozen=True)+class HttpResponse:+ status: int+ headers: Mapping[str, str]+ body: bytes+++@dataclass(frozen=True)+class FollowEntry:+ external_id: str+ title: str+ url: str | None+ media_url: str | None+ published: str | None+ author: str | None+ summary: str | None+++@dataclass(frozen=True)+class FollowResult:+ source_url: str+ entries: tuple[FollowEntry, ...]+ etag: str | None = None+ last_modified: str | None = None+ not_modified: bool = False+++class FollowSource(Protocol):+ def fetch(self, url: str, *, etag: str | None = None,+ last_modified: str | None = None) -> FollowResult: ...+++def _read_http(request: urllib.request.Request, timeout: float, max_bytes: int) -> HttpResponse:+ try:+ with urllib.request.urlopen(request, timeout=timeout) as response:+ return HttpResponse(+ status=response.status,+ headers=dict(response.headers.items()),+ body=response.read(max_bytes + 1),+ )+ except urllib.error.HTTPError as exc:+ if exc.code == 304:+ return HttpResponse(304, dict(exc.headers.items()), b"")+ raise+++def _local_name(tag: str) -> str:+ return tag.rsplit("}", 1)[-1].lower()+++def _children(element: ET.Element, name: str) -> list[ET.Element]:+ return [child for child in element if _local_name(child.tag) == name]+++def _child_text(element: ET.Element, *names: str) -> str | None:+ wanted = set(names)+ for child in element:+ if _local_name(child.tag) in wanted:+ value = "".join(child.itertext()).strip()+ if value:+ return value+ return None+++def _plain_text(value: str | None) -> str | None:+ if not value:+ return None+ cleaned = html.unescape(re.sub(r"<[^>]+>", " ", value))+ cleaned = re.sub(r"\s+", " ", cleaned).strip()+ return cleaned or None+++def _stable_id(*parts: str | None) -> str:+ material = "\n".join(part or "" for part in parts).encode("utf-8")+ return "sha256:" + hashlib.sha256(material).hexdigest()+++def _validate_url(raw_url: str) -> str:+ parsed = urllib.parse.urlsplit(raw_url)+ if parsed.scheme not in ("http", "https") or not parsed.hostname:+ raise FollowSourceError("follow source must be an absolute HTTP(S) URL")+ if parsed.username is not None or parsed.password is not None:+ raise FollowSourceError("credentials are not allowed in follow source URLs")+ return urllib.parse.urlunsplit(parsed._replace(fragment=""))+++class FeedAdapter:+ """RSS 2.0 and Atom discovery using mature public feed protocols."""++ def __init__(self, *, timeout: float = 15.0, max_bytes: int = DEFAULT_MAX_BYTES,+ transport: Callable[[urllib.request.Request, float, int], HttpResponse] = _read_http):+ self.timeout = timeout+ self.max_bytes = max_bytes+ self.transport = transport++ def fetch(self, url: str, *, etag: str | None = None,+ last_modified: str | None = None) -> FollowResult:+ source_url = _validate_url(url)+ headers = {+ "Accept": "application/atom+xml, application/rss+xml, application/xml;q=0.9",+ "User-Agent": "Peach/0.2 (+local self-hosted follow reader)",+ }+ if etag:+ headers["If-None-Match"] = etag+ if last_modified:+ headers["If-Modified-Since"] = last_modified+ request = urllib.request.Request(source_url, headers=headers)+ try:+ response = self.transport(request, self.timeout, self.max_bytes)+ except (OSError, urllib.error.URLError) as exc:+ raise FollowSourceError("follow source request failed") from exc+ response_headers = {key.lower(): value for key, value in response.headers.items()}+ common = {+ "source_url": source_url,+ "etag": response_headers.get("etag"),+ "last_modified": response_headers.get("last-modified"),+ }+ if response.status == 304:+ return FollowResult(entries=(), not_modified=True, **common)+ if response.status != 200:+ raise FollowSourceError(f"follow source returned HTTP {response.status}")+ if len(response.body) > self.max_bytes:+ raise FollowSourceError("follow source exceeded response size limit")+ try:+ root = ET.fromstring(response.body)+ except ET.ParseError as exc:+ raise FollowSourceError("follow source returned invalid XML") from exc+ root_name = _local_name(root.tag)+ if root_name == "rss":+ entries = self._parse_rss(root)+ elif root_name == "feed":+ entries = self._parse_atom(root)+ else:+ raise FollowSourceError("unsupported feed format")+ return FollowResult(entries=tuple(entries), **common)++ @staticmethod+ def _parse_rss(root: ET.Element) -> list[FollowEntry]:+ channel = next((node for node in root if _local_name(node.tag) == "channel"), None)+ if channel is None:+ raise FollowSourceError("RSS feed has no channel")+ entries = []+ for item in _children(channel, "item"):+ title = _child_text(item, "title") or "(untitled)"+ url = _child_text(item, "link")+ published = _child_text(item, "pubdate", "date")+ author = _child_text(item, "author", "creator")+ summary = _plain_text(_child_text(item, "description", "summary"))+ guid = _child_text(item, "guid")+ enclosure = next((node for node in item if _local_name(node.tag) == "enclosure"), None)+ media_url = enclosure.get("url") if enclosure is not None else None+ entries.append(FollowEntry(+ external_id=guid or url or _stable_id(title, published, media_url),+ title=title, url=url, media_url=media_url, published=published,+ author=author, summary=summary,+ ))+ return entries++ @staticmethod+ def _parse_atom(root: ET.Element) -> list[FollowEntry]:+ entries = []+ for item in _children(root, "entry"):+ title = _child_text(item, "title") or "(untitled)"+ links = _children(item, "link")+ alternate = next((node for node in links if node.get("rel", "alternate") == "alternate"), None)+ enclosure = next((node for node in links if node.get("rel") == "enclosure"), None)+ author_node = next((node for node in item if _local_name(node.tag) == "author"), None)+ author = _child_text(author_node, "name") if author_node is not None else None+ url = alternate.get("href") if alternate is not None else None+ media_url = enclosure.get("href") if enclosure is not None else None+ published = _child_text(item, "published", "updated")+ external_id = _child_text(item, "id") or url or _stable_id(title, published, media_url)+ entries.append(FollowEntry(+ external_id=external_id, title=title, url=url, media_url=media_url,+ published=published, author=author,+ summary=_plain_text(_child_text(item, "summary", "content")),+ ))+ return entriesdiff --git a/tests/test_follow.py b/tests/test_follow.pynew file mode 100644index 000000000..5a9d9b7f5--- /dev/null+++ b/tests/test_follow.py@@ -0,0 +1,68 @@+import unittest++from peach.follow import FeedAdapter, FollowSourceError, HttpResponse+++class FeedAdapterTests(unittest.TestCase):+ def test_rss_discovery_normalizes_entries_and_conditional_headers(self):+ calls = []+ rss = b"""<?xml version='1.0'?>+ <rss version='2.0'><channel><title>Example</title><item>+ <guid>post-1</guid><title> First post </title>+ <link>https://example.test/posts/1</link>+ <pubDate>Thu, 14 Aug 2026 08:00:00 GMT</pubDate>+ <author>Alice</author><description><b>Hello</b> world</description>+ <enclosure url='https://cdn.example.test/1.mp4' type='video/mp4'/>+ </item></channel></rss>"""++ def transport(request, timeout, max_bytes):+ calls.append((request, timeout))+ return HttpResponse(200, {"ETag": '"v1"'}, rss)++ result = FeedAdapter(transport=transport).fetch(+ "https://example.test/feed.xml#ignored", etag='"v0"',+ last_modified="Wed, 13 Aug 2026 08:00:00 GMT",+ )+ self.assertEqual(result.source_url, "https://example.test/feed.xml")+ self.assertEqual(result.etag, '"v1"')+ self.assertEqual(result.entries[0].external_id, "post-1")+ self.assertEqual(result.entries[0].summary, "Hello world")+ self.assertEqual(result.entries[0].media_url, "https://cdn.example.test/1.mp4")+ self.assertEqual(calls[0][0].get_header("If-none-match"), '"v0"')+ self.assertEqual(calls[0][0].get_header("If-modified-since"),+ "Wed, 13 Aug 2026 08:00:00 GMT")++ def test_atom_discovery_and_not_modified(self):+ atom = b"""<feed xmlns='http://www.w3.org/2005/Atom'><entry>+ <id>tag:example.test,2026:2</id><title>Second</title>+ <updated>2026-08-14T09:00:00Z</updated>+ <author><name>Bob</name></author>+ <link href='https://example.test/posts/2'/>+ <link rel='enclosure' href='https://cdn.example.test/2.mp4'/>+ <summary>Fresh</summary></entry></feed>"""+ adapter = FeedAdapter(transport=lambda *_: HttpResponse(200, {}, atom))+ result = adapter.fetch("https://example.test/atom")+ self.assertEqual(result.entries[0].author, "Bob")+ self.assertEqual(result.entries[0].url, "https://example.test/posts/2")++ cached = FeedAdapter(transport=lambda *_: HttpResponse(+ 304, {"Last-Modified": "Thu, 14 Aug 2026 09:00:00 GMT"}, b"",+ )).fetch("https://example.test/atom")+ self.assertTrue(cached.not_modified)+ self.assertEqual(cached.entries, ())++ def test_rejects_unsafe_urls_oversized_and_invalid_feeds(self):+ adapter = FeedAdapter(transport=lambda *_: HttpResponse(200, {}, b"x" * 5), max_bytes=4)+ with self.assertRaisesRegex(FollowSourceError, "size limit"):+ adapter.fetch("https://example.test/feed")+ with self.assertRaisesRegex(FollowSourceError, "credentials"):+ adapter.fetch("https://user:[email protected]/feed")+ with self.assertRaisesRegex(FollowSourceError, "absolute HTTP"):+ adapter.fetch("file:///tmp/feed.xml")+ invalid = FeedAdapter(transport=lambda *_: HttpResponse(200, {}, b"<html/>"))+ with self.assertRaisesRegex(FollowSourceError, "unsupported"):+ invalid.fetch("https://example.test/feed")+++if __name__ == "__main__":+ unittest.main()