Peach: Local-first video metadata scraper and media manager.
feat: add canonical entities and resilient media paths
Peach local maintenancee0d64fb42e0a
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 8ee1d3cc2..6e284f822 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -16,6 +16,7 @@ This is durable operating knowledge, not a per-session transcript.- Tests must create temporary SQLite databases and temporary media files.- Before real migration: SQLite backup, asset/tag counts, `PRAGMA integrity_check`, migration version check, then service smoke test.- Formal migrations `0000` and `0001` were applied to the real ledger on 2026-08-14. The verified pre-migration recovery point is `R:\peach-data\archive\ledger.pre-migrate-20260814-152821.db`; do not delete it until later migrations have their own verified recovery point.+- `0002_canonical_entities` exists and passes isolated tests but is still pending on the real ledger. Before applying it, create a new SQLite backup and repeat counts/integrity/version checks; never silently auto-apply it during Web startup.- Media and runtime data remain under `R:\media` and `R:\peach-data`; they are not repository assets.## Operations@@ -27,6 +28,8 @@ This is durable operating knowledge, not a per-session transcript.- FFmpeg/ffprobe resolve from explicit environment overrides, then `R:\peach-data\tools\ffmpeg\bin`, then `PATH`. No active code may fall back to the Stash private directory.- Long-running inventory helpers are under `scripts/`; their scheduled tasks use `R:\peach-app\.venv\Scripts\python.exe`. They use absolute data paths and may be interrupted/restarted where their own locking contract allows it.- Check ports 80, 8900 and 9999 before starting or switching services.+- 115/PikPak playback depends on CloudDrive mounts `B:`/`A:`. A running CloudDrive process does not prove the mounts exist; check the drive roots and one known media path. Restart CloudDrive only after proving no copy task and no active I/O.+- Ledger snapshot paths written before the project/data split are rebased by an exact configured legacy prefix. Do not add basename searches or arbitrary path fallbacks.- Report verification separately: static/unit/API, desktop browser, 390×844 browser, and whether production was actually restarted.## Architectural truth@@ -34,6 +37,7 @@ This is durable operating knowledge, not a per-session transcript.- Ledger owns truth and behavior.- Stash is a replaceable adapter; do not add new direct GraphQL helpers or private Stash FFmpeg paths.- All Stash calls use `StashClient`. Imports persist the stable Scene ID and provenance in `media_binding`; do not regress to `stash_scene_id` as the only external reference.+- Canonical performer/studio/tag/creator truth belongs in `entity`, `entity_external_ref` and `asset_entity`. Flattened `asset_tag` rows are a temporary compatibility projection, not the target model.- 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.- AI provider layers are not equivalent: inference APIs and local coding/agent runtimes remain separate.diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 50b9bf652..6f2bff6af 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -4,12 +4,12 @@ Last verified: 2026-08-14## Runtime-- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, PID observed as 57976; health mode is `fastapi`.-- mDNS publisher: `peach.local` registered on `192.168.50.162` as HTTP. Same-host Windows discovery does not loop back reliably; confirmation from another LAN device remains required.+- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, PID observed as 54728; 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.- Runtime Python: 3.14.7. The removed system Python 3.12 invalidated the old venv, which was rebuilt and reverified before production start.-- Real ledger migrations: `0000` and `0001` applied; `peach migrate status` reports zero pending migrations.+- Real ledger migrations: `0000` and `0001` applied. Code migration `0002_canonical_entities` is tested but deliberately pending on the real ledger until a fresh backup/maintenance window.- Pre-migration backup: `R:\peach-data\archive\ledger.pre-migrate-20260814-152821.db`.Runtime PIDs are observations, not configuration; always re-check them.@@ -20,16 +20,20 @@ Runtime PIDs are observations, not configuration; always re-check them.- The old `BaseHTTPRequestHandler`, dynamic legacy loader and automatic schema repair path are deleted. Default contract reads are read-only; activity/play/feedback writes are explicit.- FFmpeg/ffprobe are Peach-managed under `R:\peach-data\tools\ffmpeg`; resolver order is environment, managed bundle, then PATH. Active code has no Stash private binary fallback.- Stash transport is centralized in `StashClient`; ledger imports now write stable `media_binding` external IDs and explicit tag/performer provenance. The new importer was verified only against an isolated database and was not run on the real ledger.+- Migration `0002` adds canonical entity/alias/external-ref/asset-relation tables and backfills existing performer/tag/studio/creator projections. The Stash importer dual-writes canonical relations while retaining current flattened tags for UI compatibility; isolated tests only.+- Passive `/api/providers` health discovery now exposes separate inference/agent capabilities without model calls, credential reads or secret values.+- 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.-- 24 isolated tests passed under Python 3.14, including HTTP/HTTPS mDNS publication and TLS argument boundaries.+- 29 isolated tests passed under Python 3.14, including canonical migration/import, provider registry, snapshot rebasing, HTTP/HTTPS mDNS publication and TLS argument boundaries.- Real migration preserved 81,873 assets and 59,697 tag links; both live database and backup passed `integrity_check` and `foreign_key_check`.- 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, 24,980-item all-source list, 2,552-item local list and one-byte `206 Partial Content` Range smoke checks.- After deleting the legacy server, restarted production also passed real `stats`, `tops` and `facets` aggregate contract checks.- Optional SSL is supported with an explicit certificate/key pair. Production remains HTTP until a trusted local certificate is supplied.+- CloudDrive had remained running while its `A:`/`B:` mounts disappeared. After confirming zero copy tasks and no I/O, CloudDrive was restarted and both mounts returned. Asset 4289 (`669.mp4`) then passed `video/mp4`, 1 KiB `206 Range`, thumbnail and generated-poster API checks.## Next work-1. Replace flattened `演员:` tags with canonical performer/entity relations while keeping a compatibility projection for the current UI.+1. Back up the real ledger, apply `0002`, verify counts/integrity, then restart and smoke-test production.2. Split `web_contract.py` globals into explicit repository/application objects before enabling multiple workers.3. Implement the first real online-source and AI provider adapters behind the existing boundaries.diff --git a/docs/adr/0003-ai-provider-boundaries.md b/docs/adr/0003-ai-provider-boundaries.mdindex eb4a0012b..d5902032b 100644--- a/docs/adr/0003-ai-provider-boundaries.md+++ b/docs/adr/0003-ai-provider-boundaries.md@@ -14,6 +14,7 @@ Codex/Claude Code 是带线程、工具和权限的 agent runtime;OpenCode Go- Codex 通过正式 SDK/app-server 的本地 stdio adapter 接入,由 Codex 自管 ChatGPT 登录;不得抽取登录 token 作为通用 OpenAI API 凭据。- Claude 正式发布默认使用 API key/云 provider。调用用户本机已登录 `claude` 的订阅 adapter 只标为 personal-local experimental;Peach 不实现 Claude.ai 登录、不读取或保存 OAuth 凭据。- 第一阶段只提交接口、配置与无副作用 health 边界,不发送真实模型请求。+- 第一阶段 registry 与受认证的 `/api/providers` health 已实现;它只检查本机命令可用性并返回公开 capability,不联网、不读取凭据、不返回可执行文件路径。- AI 只能生成候选、解释与补全;写入 ledger 真相字段必须经过 provenance/confidence/review。## 凭据diff --git a/docs/adr/0005-canonical-entities-and-compatibility-projection.md b/docs/adr/0005-canonical-entities-and-compatibility-projection.mdnew file mode 100644index 000000000..eaaad93d6--- /dev/null+++ b/docs/adr/0005-canonical-entities-and-compatibility-projection.md@@ -0,0 +1,27 @@+# ADR-0005:规范实体与兼容投影++- 状态:Accepted;真实迁移 Pending+- 日期:2026-08-14++## 背景++现有 ledger 把 performer 压成 `演员:` 标签,studio/creator 仅是 asset 文本列,Stash Scene 也缺少稳定的实体级外部引用。这会让改名、别名、删除同步、多来源合并和未来 profile 隔离都依赖字符串猜测。++## 决策++- `entity` 表示 performer/studio/tag/creator/series 的规范身份。+- `entity_alias` 保存来源明确的别名;`entity_external_ref` 保存 `(source, external_id)` 稳定引用。+- `asset_entity` 表示资产与实体的有类型关系,并保留 source/confidence/provenance。+- `0002` 从现有 `演员:` 标签、普通标签、studio 和 creator 文本回填关系。+- Stash importer 同时写 canonical relation 与现有扁平字段;旧 Web 继续读取兼容投影,直到查询层切换完成。+- 迁移只由 `peach migrate apply` 显式执行,不在服务启动时自动修改真实数据库。++## 被否决的方案++- 继续把 performer 永久编码为带前缀的标签。+- 一次性删除 asset 文本列和 `asset_tag`,迫使 Web 与全部脚本同步重写。+- 用名称充当跨来源稳定 ID。++## 影响++短期存在双写与兼容数据;长期可逐个查询面切换到规范实体,验证无回归后再删除旧投影。真实 ledger 应用 `0002` 前必须创建新备份并单独验收。diff --git a/migrations/0002_canonical_entities.sql b/migrations/0002_canonical_entities.sqlnew file mode 100644index 000000000..e8a168da6--- /dev/null+++ b/migrations/0002_canonical_entities.sql@@ -0,0 +1,103 @@+CREATE TABLE IF NOT EXISTS entity(+ id INTEGER PRIMARY KEY,+ kind TEXT NOT NULL CHECK(kind IN ('performer','studio','tag','creator','series')),+ canonical_name TEXT NOT NULL,+ normalized_name TEXT NOT NULL,+ metadata_json TEXT NOT NULL DEFAULT '{}',+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ UNIQUE(kind, normalized_name)+);++CREATE TABLE IF NOT EXISTS entity_alias(+ entity_id INTEGER NOT NULL REFERENCES entity(id) ON DELETE CASCADE,+ alias TEXT NOT NULL,+ normalized_alias TEXT NOT NULL,+ source TEXT NOT NULL,+ confidence REAL NOT NULL DEFAULT 1.0,+ PRIMARY KEY(entity_id, normalized_alias, source)+);++CREATE INDEX IF NOT EXISTS idx_entity_alias_normalized+ON entity_alias(normalized_alias);++CREATE TABLE IF NOT EXISTS entity_external_ref(+ entity_id INTEGER NOT NULL REFERENCES entity(id) ON DELETE CASCADE,+ provider TEXT NOT NULL,+ external_kind TEXT NOT NULL,+ external_id TEXT NOT NULL,+ metadata_json TEXT NOT NULL DEFAULT '{}',+ last_synced_at TEXT,+ PRIMARY KEY(provider, external_kind, external_id),+ UNIQUE(entity_id, provider, external_kind)+);++CREATE TABLE IF NOT EXISTS asset_entity(+ asset_id INTEGER NOT NULL REFERENCES asset(id) ON DELETE CASCADE,+ entity_id INTEGER NOT NULL REFERENCES entity(id) ON DELETE CASCADE,+ role TEXT NOT NULL,+ source TEXT NOT NULL,+ confidence REAL NOT NULL DEFAULT 1.0,+ metadata_json TEXT NOT NULL DEFAULT '{}',+ first_seen_at TEXT,+ last_seen_at TEXT,+ PRIMARY KEY(asset_id, entity_id, role, source)+);++CREATE INDEX IF NOT EXISTS idx_asset_entity_entity_role+ON asset_entity(entity_id, role);++INSERT OR IGNORE INTO entity(kind,canonical_name,normalized_name,created_at,updated_at)+SELECT 'performer', substr(tag,4), lower(trim(substr(tag,4))),+ strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')+FROM asset_tag WHERE tag LIKE '演员:%' AND trim(substr(tag,4))<>'';++INSERT OR IGNORE INTO entity(kind,canonical_name,normalized_name,created_at,updated_at)+SELECT 'tag', tag, lower(trim(tag)),+ strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')+FROM asset_tag WHERE tag NOT LIKE '演员:%' AND trim(tag)<>'';++INSERT OR IGNORE INTO entity(kind,canonical_name,normalized_name,created_at,updated_at)+SELECT 'studio', studio, lower(trim(studio)),+ strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')+FROM asset WHERE studio IS NOT NULL AND trim(studio)<>'';++INSERT OR IGNORE INTO entity(kind,canonical_name,normalized_name,created_at,updated_at)+SELECT 'creator', creator, lower(trim(creator)),+ strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')+FROM asset WHERE creator IS NOT NULL AND trim(creator)<>'';++INSERT OR IGNORE INTO entity(kind,canonical_name,normalized_name,created_at,updated_at)+SELECT 'series', series, lower(trim(series)),+ strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')+FROM asset WHERE series IS NOT NULL AND trim(series)<>'';++INSERT OR IGNORE INTO asset_entity(asset_id,entity_id,role,source,confidence)+SELECT t.asset_id,e.id,'performer',COALESCE(t.source,'legacy:asset_tag'),COALESCE(t.confidence,1.0)+FROM asset_tag t JOIN entity e+ ON e.kind='performer' AND e.normalized_name=lower(trim(substr(t.tag,4)))+WHERE t.tag LIKE '演员:%';++INSERT OR IGNORE INTO asset_entity(asset_id,entity_id,role,source,confidence)+SELECT t.asset_id,e.id,'tag',COALESCE(t.source,'legacy:asset_tag'),COALESCE(t.confidence,1.0)+FROM asset_tag t JOIN entity e+ ON e.kind='tag' AND e.normalized_name=lower(trim(t.tag))+WHERE t.tag NOT LIKE '演员:%';++INSERT OR IGNORE INTO asset_entity(asset_id,entity_id,role,source,confidence)+SELECT a.id,e.id,'studio','legacy:asset',0.8+FROM asset a JOIN entity e+ ON e.kind='studio' AND e.normalized_name=lower(trim(a.studio))+WHERE a.studio IS NOT NULL AND trim(a.studio)<>'';++INSERT OR IGNORE INTO asset_entity(asset_id,entity_id,role,source,confidence)+SELECT a.id,e.id,'creator','legacy:asset',0.8+FROM asset a JOIN entity e+ON e.kind='creator' AND e.normalized_name=lower(trim(a.creator))+WHERE a.creator IS NOT NULL AND trim(a.creator)<>'';++INSERT OR IGNORE INTO asset_entity(asset_id,entity_id,role,source,confidence)+SELECT a.id,e.id,'series','legacy:asset',0.8+FROM asset a JOIN entity e+ ON e.kind='series' AND e.normalized_name=lower(trim(a.series))+WHERE a.series IS NOT NULL AND trim(a.series)<>'';diff --git a/scripts/ledger.py b/scripts/ledger.pyindex adf29257f..6e9da9621 100644--- a/scripts/ledger.py+++ b/scripts/ledger.py@@ -66,6 +66,48 @@ CREATE TABLE IF NOT EXISTS media_binding(PRIMARY KEY(asset_id, backend),UNIQUE(backend, external_id));+CREATE TABLE IF NOT EXISTS entity(+ id INTEGER PRIMARY KEY,+ kind TEXT NOT NULL,+ canonical_name TEXT NOT NULL,+ normalized_name TEXT NOT NULL,+ metadata_json TEXT NOT NULL DEFAULT '{}',+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ UNIQUE(kind, normalized_name));++CREATE TABLE IF NOT EXISTS entity_alias(+ entity_id INTEGER NOT NULL REFERENCES entity(id),+ alias TEXT NOT NULL,+ normalized_alias TEXT NOT NULL,+ source TEXT NOT NULL,+ confidence REAL NOT NULL DEFAULT 1.0,+ PRIMARY KEY(entity_id, normalized_alias, source));++CREATE TABLE IF NOT EXISTS entity_external_ref(+ entity_id INTEGER NOT NULL REFERENCES entity(id),+ provider TEXT NOT NULL,+ external_kind TEXT NOT NULL,+ external_id TEXT NOT NULL,+ metadata_json TEXT NOT NULL DEFAULT '{}',+ last_synced_at TEXT,+ PRIMARY KEY(provider, external_kind, external_id),+ UNIQUE(entity_id, provider, external_kind));++CREATE TABLE IF NOT EXISTS asset_entity(+ asset_id INTEGER NOT NULL REFERENCES asset(id),+ entity_id INTEGER NOT NULL REFERENCES entity(id),+ role TEXT NOT NULL,+ source TEXT NOT NULL,+ confidence REAL NOT NULL DEFAULT 1.0,+ metadata_json TEXT NOT NULL DEFAULT '{}',+ first_seen_at TEXT,+ last_seen_at TEXT,+ PRIMARY KEY(asset_id, entity_id, role, source));++CREATE INDEX IF NOT EXISTS idx_entity_alias_normalized ON entity_alias(normalized_alias);+CREATE INDEX IF NOT EXISTS idx_asset_entity_entity_role ON asset_entity(entity_id, role);+CREATE INDEX IF NOT EXISTS ix_asset_hash ON asset(hash_kind, hash);CREATE INDEX IF NOT EXISTS ix_asset_size ON asset(size);CREATE INDEX IF NOT EXISTS ix_asset_loc ON asset(location);@@ -101,6 +143,42 @@ def ctx_from(size, w=None, h=None, dur=None):return length, orient, quality+def upsert_entity(c, *, kind, name, now, source, asset_id, role,+ external_id=None, metadata=None):+ canonical = str(name or "").strip()+ if not canonical:+ return None+ normalized = canonical.casefold()+ payload = json.dumps(metadata or {}, ensure_ascii=False)+ c.execute("""INSERT INTO entity(kind,canonical_name,normalized_name,metadata_json,created_at,updated_at)+ VALUES(?,?,?,?,?,?)+ ON CONFLICT(kind,normalized_name) DO UPDATE SET+ canonical_name=excluded.canonical_name,+ metadata_json=excluded.metadata_json,+ updated_at=excluded.updated_at""",+ (kind, canonical, normalized, payload, now, now))+ entity_id = c.execute(+ "SELECT id FROM entity WHERE kind=? AND normalized_name=?", (kind, normalized)+ ).fetchone()[0]+ c.execute("""INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence,+ metadata_json,first_seen_at,last_seen_at)+ VALUES(?,?,?,?,1.0,?,?,?)+ ON CONFLICT(asset_id,entity_id,role,source) DO UPDATE SET+ metadata_json=excluded.metadata_json,+ last_seen_at=excluded.last_seen_at""",+ (asset_id, entity_id, role, source, payload, now, now))+ if external_id is not None:+ c.execute("""INSERT INTO entity_external_ref(+ entity_id,provider,external_kind,external_id,metadata_json,last_synced_at)+ VALUES(?,'stash',?,?,?,?)+ ON CONFLICT(provider,external_kind,external_id) DO UPDATE SET+ entity_id=excluded.entity_id,+ metadata_json=excluded.metadata_json,+ last_synced_at=excluded.last_synced_at""",+ (entity_id, kind, str(external_id), payload, now))+ return entity_id++def cmd_init():c = conn(); c.executescript(SCHEMA); c.commit(); c.close()print(f"✓ 建库完成 {DB}")@@ -148,7 +226,7 @@ def cmd_stash(client=None):d = client.graphql("""{findScenes(filter:{per_page:-1}){scenes{id title rating100 o_counter play_countfiles{path size duration width height video_codec frame_rate audio_codec}- studio{name} performers{name} tags{name}}}}""")+ studio{id name} performers{id name} tags{id name}}}}""")except StashError as exc:print("Stash 错误:", exc)c.close()@@ -195,18 +273,28 @@ def cmd_stash(client=None):metadata_json=excluded.metadata_json,last_synced_at=excluded.last_synced_at""",(aid, str(s["id"]), json.dumps(provenance, ensure_ascii=False), now))+ studio = s.get("studio") or {}+ upsert_entity(c, kind="studio", name=studio.get("name"), now=now,+ source="stash:studio", asset_id=aid, role="studio",+ external_id=studio.get("id"), metadata=studio)for t in s.get("tags") or []:c.execute("""INSERT INTO asset_tag(asset_id,tag,confidence,source)VALUES(?,?,1.0,'stash:tag')ON CONFLICT(asset_id,tag) DO UPDATE SETconfidence=excluded.confidence,source=excluded.source""",(aid, t["name"])); nt += 1+ upsert_entity(c, kind="tag", name=t.get("name"), now=now,+ source="stash:tag", asset_id=aid, role="tag",+ external_id=t.get("id"), metadata=t)for p in s.get("performers") or []:c.execute("""INSERT INTO asset_tag(asset_id,tag,confidence,source)VALUES(?,?,1.0,'stash:performer')ON CONFLICT(asset_id,tag) DO UPDATE SETconfidence=excluded.confidence,source=excluded.source""",(aid, "演员:" + p["name"]))+ upsert_entity(c, kind="performer", name=p.get("name"), now=now,+ source="stash:performer", asset_id=aid, role="performer",+ external_id=p.get("id"), metadata=p)c.commit()print(f"✓ Stash: {len(scenes):,} 个场景,{nt:,} 条标签关联")c.close()diff --git a/src/peach/api.py b/src/peach/api.pyindex 7aa6ab91a..860076f4c 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -13,6 +13,7 @@ from .ffmpeg import FFmpegResolverfrom .media import FilesystemMediaService, MediaNotFound, MediaUnavailablefrom .mdns import MdnsPublisherfrom .previews import PreviewService, PreviewUnavailable+from .providers import default_registryfrom .repository import LedgerRepository@@ -40,14 +41,16 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:resolver = FFmpegResolver(settings.ffmpeg_root)media_service = FilesystemMediaService(repository, settings.allowed_media_roots, settings.snapshot_root,+ settings.legacy_snapshot_roots,)preview_service = PreviewService(repository, resolver, settings.snapshot_root, settings.poster_root,- settings.avatar_root, settings.logo_root,+ settings.avatar_root, settings.logo_root, settings.legacy_snapshot_roots,)mdns = MdnsPublisher(settings.mdns_name, settings.mdns_port, secure=settings.tls_enabled) if settings.mdns_enabled else None+ providers = default_registry()@asynccontextmanagerasync def lifespan(_app: FastAPI):@@ -77,6 +80,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:app.state.media_service = media_serviceapp.state.preview_service = preview_serviceapp.state.mdns = mdns+ app.state.providers = providers@app.middleware("http")async def no_store(request: Request, call_next):@@ -189,6 +193,13 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:response.headers["Cache-Control"] = "public, max-age=86400"return response+ @app.get("/api/providers")+ def provider_health(request: Request):+ args = _first_query_values(request)+ if not _authorized(request, settings.token, args):+ return JSONResponse({"error": "unauthorized"}, status_code=401)+ return providers.health()+@app.get("/api/{route:path}")def api_get(route: str, request: Request):args = _first_query_values(request)diff --git a/src/peach/config.py b/src/peach/config.pyindex 3bd98a431..752a3ba12 100644--- a/src/peach/config.py+++ b/src/peach/config.py@@ -31,6 +31,8 @@ class PeachSettings:tls_enabled: bool = Falseallowed_media_roots: tuple[Path, ...] = (Path(r"R:\media"), Path("B:/"), Path("A:/"))snapshot_root: Path = GENERATED_DIR / "snapshots"+ # 2026-08 仓库/数据拆分前写入 ledger 的旧路径;运行时只做受控前缀重映射。+ legacy_snapshot_roots: tuple[Path, ...] = (Path(r"R:\Resources\Intake\snapshots"),)poster_root: Path = GENERATED_DIR / "posters"avatar_root: Path = GENERATED_DIR / "avatars"logo_root: Path = GENERATED_DIR / "logos"diff --git a/src/peach/media.py b/src/peach/media.pyindex fadb5340a..6718c5901 100644--- a/src/peach/media.py+++ b/src/peach/media.py@@ -19,6 +19,23 @@ def normalized_path(path: Path | str) -> Path:return Path(os.path.abspath(os.fspath(candidate)))+def remap_managed_path(path: Path | str, current_root: Path,+ legacy_roots: Sequence[Path] = ()) -> Path:+ """将数据迁移前的受控根路径映射到当前根,不接受任意 basename 搜索。"""+ candidate = normalized_path(path)+ current = normalized_path(current_root)+ if candidate == current or current in candidate.parents:+ return candidate+ for legacy_root in legacy_roots:+ legacy = normalized_path(legacy_root)+ try:+ relative = candidate.relative_to(legacy)+ except ValueError:+ continue+ return current / relative+ return candidate++@dataclass(frozen=True)class MediaCapabilities:probe: bool = False@@ -47,10 +64,13 @@ class MediaUnavailable(RuntimeError):class FilesystemMediaService:def __init__(self, repository: LedgerRepository, allowed_roots: Sequence[Path],- snapshot_root: Path):+ snapshot_root: Path, legacy_snapshot_roots: Sequence[Path] = ()):self.repository = repositoryself.allowed_roots = tuple(normalized_path(root) for root in allowed_roots)self.snapshot_root = normalized_path(snapshot_root)+ self.legacy_snapshot_roots = tuple(+ normalized_path(root) for root in legacy_snapshot_roots+ )def file_for(self, asset_id: int, thumbnail: bool = False) -> Path:asset = self.repository.media_asset(asset_id)@@ -59,7 +79,8 @@ class FilesystemMediaService:raw = asset.snapshot_path if thumbnail else asset.pathif not raw:raise MediaUnavailable(asset_id)- path = normalized_path(raw)+ path = (remap_managed_path(raw, self.snapshot_root, self.legacy_snapshot_roots)+ if thumbnail else normalized_path(raw))roots = (self.snapshot_root,) if thumbnail else self.allowed_rootsif not any(path == root or root in path.parents for root in roots):raise MediaUnavailable(asset_id)diff --git a/src/peach/previews.py b/src/peach/previews.pyindex d650b1c38..f2da400e4 100644--- a/src/peach/previews.py+++ b/src/peach/previews.py@@ -7,6 +7,7 @@ import threadingfrom pathlib import Pathfrom .ffmpeg import FFmpegResolver+from .media import remap_managed_pathfrom .repository import LedgerRepository@@ -19,13 +20,15 @@ _GENERATE_LOCK = threading.Lock()class PreviewService:def __init__(self, repository: LedgerRepository, resolver: FFmpegResolver,- snapshot_root: Path, poster_root: Path, avatar_root: Path, logo_root: Path):+ snapshot_root: Path, poster_root: Path, avatar_root: Path, logo_root: Path,+ legacy_snapshot_roots: tuple[Path, ...] = ()):self.repository = repositoryself.resolver = resolverself.snapshot_root = snapshot_root.resolve()self.poster_root = poster_root.resolve()self.avatar_root = avatar_root.resolve()self.logo_root = logo_root.resolve()+ self.legacy_snapshot_roots = tuple(path.resolve() for path in legacy_snapshot_roots)def poster(self, asset_id: int, cell: int = 4) -> Path:cell = max(0, min(8, cell))@@ -114,7 +117,9 @@ class PreviewService:asset = self.repository.media_asset(asset_id)if asset is None or not asset.snapshot_path:raise PreviewUnavailable("snapshot unavailable")- path = Path(asset.snapshot_path).resolve()+ path = remap_managed_path(+ asset.snapshot_path, self.snapshot_root, self.legacy_snapshot_roots,+ )if not (path == self.snapshot_root or self.snapshot_root in path.parents) or not path.is_file():raise PreviewUnavailable("snapshot unavailable")return pathdiff --git a/src/peach/providers.py b/src/peach/providers.pyindex 25dfe5dd6..f989a4e0f 100644--- a/src/peach/providers.py+++ b/src/peach/providers.py@@ -1,7 +1,10 @@-"""AI Provider 只定义能力边界;阶段一不发真实模型请求。"""-from dataclasses import dataclass+"""AI Provider capability registry; health discovery never sends model requests."""+from __future__ import annotations++import shutil+from dataclasses import asdict, dataclassfrom enum import Enum-from typing import Protocol+from typing import Callable, Protocolclass ProviderKind(str, Enum):@@ -18,6 +21,92 @@ class ProviderCapabilities:cancellation: bool = False+@dataclass(frozen=True)+class ProviderStatus:+ id: str+ kind: ProviderKind+ provider: str+ auth_mode: str+ available: bool+ configured: bool | None+ experimental: bool+ capabilities: ProviderCapabilities+ note: str = ""++ def public_dict(self) -> dict:+ return {+ "id": self.id,+ "kind": self.kind.value,+ "provider": self.provider,+ "auth_mode": self.auth_mode,+ "available": self.available,+ "configured": self.configured,+ "experimental": self.experimental,+ "capabilities": asdict(self.capabilities),+ "note": self.note,+ }+++class ProviderRegistry:+ def __init__(self) -> None:+ self._providers: dict[str, ProviderStatus] = {}++ def register(self, status: ProviderStatus) -> None:+ if status.id in self._providers:+ raise ValueError(f"duplicate provider id: {status.id}")+ self._providers[status.id] = status++ def health(self) -> dict:+ providers = [self._providers[key].public_dict() for key in sorted(self._providers)]+ return {"ok": True, "providers": providers}+++def default_registry(+ executable_finder: Callable[[str], str | None] = shutil.which,+) -> ProviderRegistry:+ registry = ProviderRegistry()+ registry.register(ProviderStatus(+ id="opencode-go",+ kind=ProviderKind.INFERENCE,+ provider="opencode-go",+ auth_mode="api-key",+ available=True,+ configured=False,+ experimental=False,+ capabilities=ProviderCapabilities(streaming=True, structured_output=True),+ note="Direct HTTP adapter supported; API key is not configured in phase one.",+ ))+ registry.register(ProviderStatus(+ id="codex-local",+ kind=ProviderKind.AGENT,+ provider="codex",+ auth_mode="vendor-managed-oauth",+ available=executable_finder("codex") is not None,+ configured=None,+ experimental=False,+ capabilities=ProviderCapabilities(+ streaming=True, structured_output=True, tool_use=True,+ sessions=True, cancellation=True,+ ),+ note="Authentication remains owned by the Codex runtime.",+ ))+ registry.register(ProviderStatus(+ id="claude-code-local-personal",+ kind=ProviderKind.AGENT,+ provider="claude-code",+ auth_mode="vendor-managed-oauth",+ available=executable_finder("claude") is not None,+ configured=None,+ experimental=True,+ capabilities=ProviderCapabilities(+ streaming=True, structured_output=True, tool_use=True,+ sessions=True, cancellation=True,+ ),+ note="Personal-local experimental adapter; Peach never reads Claude credentials.",+ ))+ return registry++class InferenceProvider(Protocol):name: strdiff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 26ef55e40..7d4879ca4 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -100,6 +100,16 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.assertNotIn("path", data["items"][0])self.assertEqual(response.headers["cache-control"], "no-store")+ async def test_provider_health_is_authenticated_and_secret_free(self):+ denied = await self.client.get("/api/providers")+ self.assertEqual(denied.status_code, 401)+ response = await self.client.get("/api/providers?t=secret")+ self.assertEqual(response.status_code, 200)+ payload = response.json()+ self.assertTrue(payload["ok"])+ self.assertEqual(len(payload["providers"]), 3)+ self.assertNotIn("secret_ref", response.text)+async def test_post_writes_only_test_database(self):response = await self.client.post("/api/activity", headers={"X-Token": "secret"},diff --git a/tests/test_media.py b/tests/test_media.pyindex 812ef8c3d..3e11b9e10 100644--- a/tests/test_media.py+++ b/tests/test_media.py@@ -4,7 +4,9 @@ from pathlib import Pathfrom unittest.mock import patchfrom peach.ffmpeg import FFmpegResolver-from peach.media import FilesystemBackend, MediaEngine, StashAdapter, normalized_path+from peach.media import (+ FilesystemBackend, MediaEngine, StashAdapter, normalized_path, remap_managed_path,+)from peach.stash import StashClient@@ -70,6 +72,18 @@ class MediaEngineTests(unittest.TestCase):path = normalized_path(Path("B:/"))self.assertTrue(path.is_absolute())+ def test_legacy_snapshot_path_is_rebased_by_prefix(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ current = root / "generated" / "snapshots"+ legacy = root / "old" / "snapshots"+ raw = legacy / "cloud" / "local" / "aa" / "one.jpg"+ expected = current / "cloud" / "local" / "aa" / "one.jpg"+ self.assertEqual(remap_managed_path(raw, current, (legacy,)), expected)++ unrelated = root / "untrusted" / "one.jpg"+ self.assertEqual(remap_managed_path(unrelated, current, (legacy,)), unrelated.resolve())+if __name__ == "__main__":unittest.main()diff --git a/tests/test_migrations.py b/tests/test_migrations.pyindex 0fd182525..da2233155 100644--- a/tests/test_migrations.py+++ b/tests/test_migrations.py@@ -1,4 +1,5 @@import sqlite3+import shutilimport tempfileimport unittestfrom pathlib import Path@@ -22,7 +23,7 @@ class MigrationTests(unittest.TestCase):sqlite3.connect(self.db).close()backup = self.root / "before.db"done = upgrade(self.db, MIGRATIONS, backup)- self.assertEqual([m.version for m in done], ["0000", "0001"])+ self.assertEqual([m.version for m in done], ["0000", "0001", "0002"])self.assertTrue(backup.exists())con = sqlite3.connect(self.db)tables = {row[0] for row in con.execute(@@ -33,8 +34,9 @@ class MigrationTests(unittest.TestCase):)]con.close()self.assertTrue({"asset", "profile", "media_binding", "activity_event",- "provider_profile", "schema_migration"} <= tables)- self.assertEqual(versions, ["0000", "0001"])+ "provider_profile", "entity", "entity_alias",+ "entity_external_ref", "asset_entity", "schema_migration"} <= tables)+ self.assertEqual(versions, ["0000", "0001", "0002"])self.assertEqual(upgrade(self.db, MIGRATIONS), [])self.assertEqual(plan(self.db, MIGRATIONS)[1], [])@@ -73,6 +75,38 @@ class MigrationTests(unittest.TestCase):with self.assertRaises(RuntimeError):plan(self.db, MIGRATIONS)+ def test_entity_migration_backfills_flattened_relations(self):+ base_migrations = self.root / "base-migrations"+ base_migrations.mkdir()+ for name in ("0000_legacy_schema.sql", "0001_core_boundaries.sql"):+ shutil.copyfile(MIGRATIONS / name, base_migrations / name)+ sqlite3.connect(self.db).close()+ upgrade(self.db, base_migrations)+ con = sqlite3.connect(self.db)+ con.executescript("""+ INSERT INTO asset(id,location,path,name,medium,creator,studio,series)+ VALUES(1,'local','one.mp4','one.mp4','video','Owner A','Studio A','Series A');+ INSERT INTO asset_tag(asset_id,tag,confidence,source)+ VALUES(1,'演员:Performer A',1.0,'stash:performer'),+ (1,'Tag A',0.9,'stash:tag');+ """)+ con.close()+ upgrade(self.db, MIGRATIONS)+ con = sqlite3.connect(self.db)+ entities = set(con.execute("SELECT kind,canonical_name FROM entity"))+ relations = set(con.execute(+ "SELECT e.kind,ae.role,ae.source FROM asset_entity ae "+ "JOIN entity e ON e.id=ae.entity_id WHERE ae.asset_id=1"+ ))+ con.close()+ self.assertTrue({('performer','Performer A'),('tag','Tag A'),+ ('studio','Studio A'),('creator','Owner A'),+ ('series','Series A')} <= entities)+ self.assertTrue({('performer','performer','stash:performer'),+ ('tag','tag','stash:tag'),('studio','studio','legacy:asset'),+ ('creator','creator','legacy:asset'),+ ('series','series','legacy:asset')} <= relations)+if __name__ == "__main__":unittest.main()diff --git a/tests/test_providers.py b/tests/test_providers.pynew file mode 100644index 000000000..a673e1f44--- /dev/null+++ b/tests/test_providers.py@@ -0,0 +1,43 @@+import unittest++from peach.providers import (+ ProviderCapabilities, ProviderKind, ProviderRegistry, ProviderStatus,+ default_registry,+)+++class ProviderRegistryTests(unittest.TestCase):+ def test_default_health_is_passive_and_deterministic(self):+ registry = default_registry(lambda name: f"C:/tools/{name}.exe" if name == "codex" else None)+ health = registry.health()+ by_id = {item["id"]: item for item in health["providers"]}++ self.assertEqual(set(by_id), {+ "opencode-go", "codex-local", "claude-code-local-personal",+ })+ self.assertTrue(by_id["opencode-go"]["available"])+ self.assertTrue(by_id["codex-local"]["available"])+ self.assertFalse(by_id["claude-code-local-personal"]["available"])+ self.assertTrue(by_id["claude-code-local-personal"]["experimental"])+ for item in health["providers"]:+ self.assertEqual(set(item), {+ "id", "kind", "provider", "auth_mode", "available", "configured",+ "experimental", "capabilities", "note",+ })+ self.assertNotIn("secret_ref", item)+ self.assertNotIn("executable", item)++ def test_duplicate_provider_id_is_rejected(self):+ registry = ProviderRegistry()+ status = ProviderStatus(+ id="one", kind=ProviderKind.INFERENCE, provider="test",+ auth_mode="none", available=True, configured=True, experimental=False,+ capabilities=ProviderCapabilities(),+ )+ registry.register(status)+ with self.assertRaisesRegex(ValueError, "duplicate provider id"):+ registry.register(status)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_rm_ledger.py b/tests/test_rm_ledger.pyindex 62eb5cfde..c749d88ba 100644--- a/tests/test_rm_ledger.py+++ b/tests/test_rm_ledger.py@@ -30,9 +30,13 @@ class LedgerSchemaTests(unittest.TestCase):rm_ledger.cmd_init()con = sqlite3.connect(self.db)columns = {row[1] for row in con.execute("PRAGMA table_info(asset)")}+ tables = {row[0] for row in con.execute(+ "SELECT name FROM sqlite_schema WHERE type='table'"+ )}con.close()self.assertTrue({"studio", "feedback", "disposal", "leave_ratio", "play_seconds","feedback_at", "seek_count", "max_reached"} <= columns)+ self.assertTrue({"entity", "entity_alias", "entity_external_ref", "asset_entity"} <= tables)def test_stash_import_writes_studio_without_overwriting_creator(self):with redirect_stdout(io.StringIO()):@@ -49,9 +53,9 @@ class LedgerSchemaTests(unittest.TestCase):"files": [{"path": r"R:\media\one.mp4", "size": 10, "duration": 30,"width": 1920, "height": 1080, "video_codec": "h264","frame_rate": 30, "audio_codec": "aac"}],- "studio": {"name": "Studio A"},- "performers": [{"name": "Performer A"}],- "tags": [{"name": "Tag A"}],+ "studio": {"id": "7", "name": "Studio A"},+ "performers": [{"id": "8", "name": "Performer A"}],+ "tags": [{"id": "9", "name": "Tag A"}],}]}}client = SimpleNamespace(graphql=lambda *_args, **_kwargs: response)with redirect_stdout(io.StringIO()):@@ -69,12 +73,30 @@ class LedgerSchemaTests(unittest.TestCase):"SELECT backend,external_id,metadata_json FROM media_binding WHERE asset_id=(SELECT id FROM asset WHERE path=?)",(r"R:\media\one.mp4",),).fetchone()+ entities = set(con.execute(+ "SELECT kind,canonical_name FROM entity ORDER BY kind,canonical_name"+ ))+ external_refs = set(con.execute(+ "SELECT e.kind,r.external_id FROM entity_external_ref r "+ "JOIN entity e ON e.id=r.entity_id"+ ))+ relations = set(con.execute(+ "SELECT e.kind,ae.role,ae.source FROM asset_entity ae "+ "JOIN entity e ON e.id=ae.entity_id"+ ))con.close()self.assertEqual(row, ("Channel Owner", "Studio A", 42))self.assertEqual(tags, {("Tag A", "stash:tag"),("演员:Performer A", "stash:performer")})self.assertEqual(binding[:2], ("stash", "42"))self.assertIn('"transport": "stash-graphql"', binding[2])+ self.assertEqual(entities, {("studio", "Studio A"), ("tag", "Tag A"),+ ("performer", "Performer A")})+ self.assertEqual(external_refs, {("studio", "7"), ("performer", "8"),+ ("tag", "9")})+ self.assertEqual(relations, {("studio", "studio", "stash:studio"),+ ("performer", "performer", "stash:performer"),+ ("tag", "tag", "stash:tag")})if __name__ == "__main__":