Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat: persist immutable follow evidence

Peach local maintenance19c77a7a103b
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index b43da85be..6792c7fa2 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -41,7 +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.
+- `FeedAdapter` is the first online-follow connector. It performs explicit bounded RSS/Atom discovery; `FeedSnapshotStore` separates immutable evidence under `sources/follow` from conditional-request cursors under `state/follow`. 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.
## Recovery
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 6a97d6bf6..bb715c340 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -23,7 +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.
+- The first online-follow connector is a generic explicit RSS/Atom `FeedAdapter`: conditional requests, bounded response reads, normalized entries and no ledger writes. `FeedSnapshotStore` persists immutable XML/normalized evidence under `sources/follow` and request cursors under `state/follow`. 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.
@@ -31,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.
-- 42 isolated tests and tracked-script static compilation passed under Python 3.14.
+- 43 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.
@@ -60,6 +60,6 @@ Runtime PIDs are observations, not configuration; always re-check them.
## Next work
-1. Add configured feed persistence under `peach-data/sources`, conditional-request state and a reviewed candidate import without automatic ledger writes.
+1. Add explicit feed configuration plus a reviewed candidate import without automatic ledger writes; only then consider a scheduler.
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.md
index 720c2cbbf..4598dad18 100644
--- a/docs/adr/0007-online-follow-feed-adapter.md
+++ b/docs/adr/0007-online-follow-feed-adapter.md
@@ -13,12 +13,12 @@ Peach 把在线追更列为正式能力,但尚无 connector。直接从站点
- 网络请求只能由显式调用触发;服务启动、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 的导入边界写入。
+- adapter 只发现候选,不自动写 ledger 真相。`FeedSnapshotStore` 把不可变原始响应与规范化旁车存入 `peach-data/sources/follow`,把条件请求游标存入 `peach-data/state/follow`;后续通过带 source/provenance/review 的导入边界写入。
- 无 feed 的站点以后实现独立 connector;不得把站点专用 HTML 规则塞进通用 feed adapter。
## 后果
-Peach 获得可测试、低耦合的首个在线追更边界,并复用成熟协议;具体 feed 配置、调度、原始快照和 reviewed import 仍需下一阶段实现。当前没有对真实站点发起追更请求,也没有修改 ledger。
+Peach 获得可测试、低耦合的首个在线追更边界,并复用成熟协议;具体 feed 配置、调度和 reviewed import 仍需下一阶段实现。当前没有对真实站点发起追更请求,也没有修改 ledger。
## 拒绝方案
diff --git a/src/peach/follow.py b/src/peach/follow.py
index 088ac596c..aca067321 100644
--- a/src/peach/follow.py
+++ b/src/peach/follow.py
@@ -7,12 +7,15 @@ from __future__ import annotations
import hashlib
import html
+import json
import re
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
-from dataclasses import dataclass
+from dataclasses import asdict, dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
from typing import Callable, Mapping, Protocol
@@ -48,6 +51,7 @@ class FollowResult:
etag: str | None = None
last_modified: str | None = None
not_modified: bool = False
+ raw_body: bytes | None = field(default=None, repr=False, compare=False)
class FollowSource(Protocol):
@@ -157,7 +161,7 @@ class FeedAdapter:
entries = self._parse_atom(root)
else:
raise FollowSourceError("unsupported feed format")
- return FollowResult(entries=tuple(entries), **common)
+ return FollowResult(entries=tuple(entries), raw_body=response.body, **common)
@staticmethod
def _parse_rss(root: ET.Element) -> list[FollowEntry]:
@@ -201,3 +205,101 @@ class FeedAdapter:
summary=_plain_text(_child_text(item, "summary", "content")),
))
return entries
+
+
+@dataclass(frozen=True)
+class FollowState:
+ source_url: str
+ etag: str | None = None
+ last_modified: str | None = None
+ checked_at: str | None = None
+ snapshot: str | None = None
+
+
+class FeedSnapshotStore:
+ """Immutable feed evidence plus small replaceable conditional-request state."""
+
+ def __init__(self, sources_root: Path, state_root: Path):
+ self.sources_root = Path(sources_root) / "follow"
+ self.state_root = Path(state_root) / "follow"
+
+ @staticmethod
+ def _source_key(source_url: str) -> str:
+ return hashlib.sha256(source_url.encode("utf-8")).hexdigest()[:20]
+
+ def load(self, source_url: str) -> FollowState:
+ source_url = _validate_url(source_url)
+ path = self.state_root / f"{self._source_key(source_url)}.json"
+ if not path.is_file():
+ return FollowState(source_url)
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+ raise FollowSourceError("follow state is unreadable") from exc
+ if not isinstance(payload, dict) or payload.get("source_url") != source_url:
+ raise FollowSourceError("follow state does not match source URL")
+ return FollowState(
+ source_url=source_url,
+ etag=payload.get("etag"),
+ last_modified=payload.get("last_modified"),
+ checked_at=payload.get("checked_at"),
+ snapshot=payload.get("snapshot"),
+ )
+
+ def persist(self, result: FollowResult, *, checked_at: datetime | None = None) -> FollowState:
+ source_url = _validate_url(result.source_url)
+ checked_at = checked_at or datetime.now(timezone.utc)
+ if checked_at.tzinfo is None:
+ raise FollowSourceError("follow check timestamp must be timezone-aware")
+ checked_text = checked_at.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
+ previous = self.load(source_url)
+ snapshot = previous.snapshot
+ if not result.not_modified:
+ if result.raw_body is None:
+ raise FollowSourceError("feed result has no raw evidence")
+ digest = hashlib.sha256(result.raw_body).hexdigest()
+ stamp = checked_at.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%S.%fZ")
+ directory = self.sources_root / self._source_key(source_url)
+ directory.mkdir(parents=True, exist_ok=True)
+ raw_path = directory / f"{stamp}-{digest[:12]}.xml"
+ metadata_path = raw_path.with_suffix(".json")
+ self._write_immutable(raw_path, result.raw_body)
+ metadata = {
+ "source_url": source_url,
+ "checked_at": checked_text,
+ "sha256": digest,
+ "entries": [asdict(entry) for entry in result.entries],
+ }
+ self._write_immutable(
+ metadata_path,
+ (json.dumps(metadata, ensure_ascii=False, indent=2) + "\n").encode("utf-8"),
+ )
+ snapshot = str(raw_path.relative_to(self.sources_root.parent))
+ state = FollowState(
+ source_url=source_url,
+ etag=result.etag or previous.etag,
+ last_modified=result.last_modified or previous.last_modified,
+ checked_at=checked_text,
+ snapshot=snapshot,
+ )
+ self.state_root.mkdir(parents=True, exist_ok=True)
+ state_path = self.state_root / f"{self._source_key(source_url)}.json"
+ self._write_state(state_path, asdict(state))
+ return state
+
+ @staticmethod
+ def _write_immutable(path: Path, payload: bytes) -> None:
+ try:
+ with path.open("xb") as handle:
+ handle.write(payload)
+ except FileExistsError:
+ if path.read_bytes() != payload:
+ raise FollowSourceError("immutable follow snapshot collision")
+
+ @staticmethod
+ def _write_state(path: Path, payload: dict) -> None:
+ temporary = path.with_suffix(path.suffix + ".tmp")
+ temporary.write_text(
+ json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8",
+ )
+ temporary.replace(path)
diff --git a/tests/test_follow.py b/tests/test_follow.py
index 5a9d9b7f5..e759f2278 100644
--- a/tests/test_follow.py
+++ b/tests/test_follow.py
@@ -1,6 +1,9 @@
import unittest
+import tempfile
+from datetime import datetime, timezone
+from pathlib import Path
-from peach.follow import FeedAdapter, FollowSourceError, HttpResponse
+from peach.follow import FeedAdapter, FeedSnapshotStore, FollowSourceError, HttpResponse
class FeedAdapterTests(unittest.TestCase):
@@ -63,6 +66,34 @@ class FeedAdapterTests(unittest.TestCase):
with self.assertRaisesRegex(FollowSourceError, "unsupported"):
invalid.fetch("https://example.test/feed")
+ def test_snapshot_store_separates_immutable_evidence_and_request_state(self):
+ rss = b"<rss><channel><item><guid>one</guid><title>One</title></item></channel></rss>"
+ fresh = FeedAdapter(transport=lambda *_: HttpResponse(
+ 200, {"ETag": '"v1"'}, rss,
+ )).fetch("https://example.test/feed")
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ store = FeedSnapshotStore(root / "sources", root / "state")
+ first = store.persist(
+ fresh, checked_at=datetime(2026, 8, 14, 8, 0, tzinfo=timezone.utc),
+ )
+ self.assertEqual(first.etag, '"v1"')
+ self.assertTrue((root / "sources" / first.snapshot).is_file())
+ source_dir = (root / "sources" / first.snapshot).parent
+ self.assertEqual(len(list(source_dir.glob("*.xml"))), 1)
+ self.assertEqual(len(list(source_dir.glob("*.json"))), 1)
+
+ cached = FeedAdapter(transport=lambda *_: HttpResponse(
+ 304, {}, b"",
+ )).fetch("https://example.test/feed")
+ second = store.persist(
+ cached, checked_at=datetime(2026, 8, 14, 9, 0, tzinfo=timezone.utc),
+ )
+ self.assertEqual(second.etag, '"v1"')
+ self.assertEqual(second.snapshot, first.snapshot)
+ self.assertEqual(len(list(source_dir.glob("*.xml"))), 1)
+ self.assertEqual(store.load("https://example.test/feed"), second)
+
if __name__ == "__main__":
unittest.main()