You're reading this. The skill predicted it. A workflow that turns every post into a calibrated experiment—score, blind-predict, retro, evolve. The future doesn't reward effort, it rewards those who see the pattern first. 1M followers in a month — not luck, system.
Python
feat(perf-data): add WeChat Channels adapter (#47)
NEYMAR946db8b2189a4e6
diff --git a/.gitignore b/.gitignoreindex ee9d8e1..02e1cab 100644--- a/.gitignore+++ b/.gitignore@@ -47,6 +47,7 @@ content.db.auth/.auth-xhs/.auth-linkedin/+.auth-wechat-channels/.debug/# Editor / IDEdiff --git a/adapters/perf-data/wechat-channels/.gitattributes b/adapters/perf-data/wechat-channels/.gitattributesnew file mode 100644index 0000000..1bbd695--- /dev/null+++ b/adapters/perf-data/wechat-channels/.gitattributes@@ -0,0 +1,2 @@+*.sh text eol=lf+*.py text eol=lfdiff --git a/adapters/perf-data/wechat-channels/README.md b/adapters/perf-data/wechat-channels/README.mdnew file mode 100644index 0000000..9892deb--- /dev/null+++ b/adapters/perf-data/wechat-channels/README.md@@ -0,0 +1,57 @@+# Adapter: wechat-channels(视频号助手)++用于抓取自己账号在视频号助手后台的作品运营数据。++## 原理++- Playwright 持久化 Chromium 登录态+- 被动监听 `channels.weixin.qq.com/platform/` 页面自行发出的 JSON+- 不逆向签名,不读取微信客户端文件+- 登录态保存在内容项目的 `.auth-wechat-channels/`++## 安装与登录++```powershell+cd <内容项目>+.\.venv\Scripts\python.exe -m pip install -r <adapter>\requirements.txt+.\.venv\Scripts\python.exe -m playwright install chromium+.\.venv\Scripts\python.exe <adapter>\review.py login+```++扫码登录后验证:++```powershell+.\.venv\Scripts\python.exe <adapter>\review.py list+```++## 抓取单条作品++```powershell+.\.venv\Scripts\python.exe <adapter>\review.py post <post_id> [script.txt]+```++运行时只在内存中处理页面自行发出的 JSON。adapter 不把原始响应、请求体、+完整后台 URL、后台页面文本或截图写入磁盘;诊断信息只在终端输出计数和错误原因。++## 当前限制++- 第一版优先实现作品列表和播放/点赞/爱心/评论/分享数据。+- 已支持从“互动管理 → 评论”自动抓评论文本、点赞数和作者回复。+- 默认按点赞和时间排序,报告最多写入 Top 20;接口有分页时自动翻页。+- 如果指定的 post_id 不在最近作品列表中,会以非 0 状态退出,避免生成 0 值 report.md 污染复盘。+- `run.sh` 会在每次抓取前删除目标目录内的旧 `report.md`;抓取失败时不会把陈旧报告误报为成功。++## TOS / 风险边界++- 仅用于用户自己登录后可见的视频号助手后台数据。+- 不抓取他人作品,不绕过登录,不逆向签名,不自动发布内容。+- 不持久化原始响应、请求体、signed media URL、内部用户名/ID、cookie、secret、后台截图或页面文本。+- `report.md` 仍含用户自己的运营数据和评论文本,应保存在私有内容项目中;对外分享前须审阅和脱敏。+- 请低频手动触发,用于个人内容复盘和 NotebookLM/cheat-on-content 分析。++## 本地验证++```bash+python -m unittest discover -s adapters/perf-data/wechat-channels -p 'test_*.py' -v+bash adapters/perf-data/wechat-channels/test_run_contract.sh+```diff --git a/adapters/perf-data/wechat-channels/crawler.py b/adapters/perf-data/wechat-channels/crawler.pynew file mode 100644index 0000000..79e645f--- /dev/null+++ b/adapters/perf-data/wechat-channels/crawler.py@@ -0,0 +1,518 @@+"""视频号助手创作者后台抓取。++使用 Playwright 持久化登录态,被动监听后台页面自行发出的 JSON 请求。+不伪造签名,不读取微信客户端数据。+"""+from __future__ import annotations++import asyncio+import json+import re+import sys+import time+from typing import Any++from playwright.async_api import BrowserContext, Page, Response, async_playwright++from paths import auth_dir++PLATFORM_HOME = "https://channels.weixin.qq.com/platform/"+CONTENT_URLS = (+ "https://channels.weixin.qq.com/platform/post/list",+ "https://channels.weixin.qq.com/platform/content",+ PLATFORM_HOME,+)+++class Session:+ def __init__(self, ctx: BrowserContext, pw: Any) -> None:+ self.ctx = ctx+ self.pw = pw++ @classmethod+ async def open(cls, headless: bool = False) -> "Session":+ pw = await async_playwright().start()+ auth = auth_dir()+ auth.mkdir(parents=True, exist_ok=True)+ ctx = await pw.chromium.launch_persistent_context(+ user_data_dir=str(auth),+ headless=headless,+ viewport={"width": 1440, "height": 900},+ args=["--disable-blink-features=AutomationControlled"],+ )+ return cls(ctx, pw)++ async def close(self) -> None:+ try:+ await self.ctx.close()+ finally:+ await self.pw.stop()+++async def _logged_in(page: Page) -> bool:+ if "login" in page.url.lower():+ return False+ try:+ body = await page.locator("body").inner_text(timeout=3000)+ except Exception:+ return False+ login_markers = ("扫码登录", "微信扫码", "登录视频号助手")+ account_markers = ("内容管理", "互动管理", "收入与服务", "视频号ID")+ return not any(x in body for x in login_markers) and any(x in body for x in account_markers)+++async def ensure_login(timeout_s: int = 300) -> bool:+ sess = await Session.open()+ try:+ page = sess.ctx.pages[0] if sess.ctx.pages else await sess.ctx.new_page()+ await page.goto(PLATFORM_HOME, wait_until="domcontentloaded", timeout=60000)+ print(f"[登录] 请在弹出的窗口扫码登录视频号助手,最多等待 {timeout_s} 秒。")+ for i in range(timeout_s):+ if await _logged_in(page):+ print(f"[登录] ✓ 已检测到视频号助手登录态(用时 {i}s)")+ await asyncio.sleep(2)+ return True+ await asyncio.sleep(1)+ print("[登录] 超时,未检测到登录态。")+ return False+ finally:+ await sess.close()+++def _first(obj: dict, *keys: str, default: Any = None) -> Any:+ for key in keys:+ if key in obj and obj[key] not in (None, ""):+ return obj[key]+ return default+++def _walk(value: Any):+ if isinstance(value, dict):+ yield value+ for child in value.values():+ yield from _walk(child)+ elif isinstance(value, list):+ for child in value:+ yield from _walk(child)+++def _looks_like_post(obj: dict) -> bool:+ keys = set(obj)+ has_id = bool(keys & {"object_id", "objectId", "feed_id", "feedId", "post_id", "postId", "id"})+ has_metrics = bool(+ keys+ & {+ "read_count",+ "readCount",+ "play_count",+ "playCount",+ "like_count",+ "likeCount",+ "comment_count",+ "commentCount",+ "forward_count",+ "forwardCount",+ }+ )+ return has_id and has_metrics+++def _text_from_desc(value: Any) -> str:+ if isinstance(value, str):+ return value.strip()+ if not isinstance(value, dict):+ return ""+ for key in ("description", "title", "content"):+ text = value.get(key)+ if isinstance(text, str) and text.strip():+ return text.strip()+ short_title = value.get("shortTitle")+ if isinstance(short_title, list):+ labels = [+ item.get("shortTitle", "").strip()+ for item in short_title+ if isinstance(item, dict) and isinstance(item.get("shortTitle"), str)+ ]+ if labels:+ return " ".join(labels)+ return ""+++def _normalize_post(obj: dict) -> dict:+ post_id = str(+ _first(obj, "object_id", "objectId", "feed_id", "feedId", "post_id", "postId", "id", default="")+ )+ title = ""+ for key in ("title", "description", "content"):+ value = obj.get(key)+ if isinstance(value, str) and value.strip():+ title = value.strip()+ break+ if not title:+ title = _text_from_desc(obj.get("desc"))+ create_time = _first(+ obj,+ "create_time",+ "createTime",+ "publish_time",+ "publishTime",+ "post_time",+ "postTime",+ default=0,+ )+ return {+ "post_id": post_id,+ "title": title,+ "create_time": create_time,+ "view_count": _first(obj, "read_count", "readCount", "play_count", "playCount", "view_count", default=0),+ "like_count": _first(obj, "like_count", "likeCount", "like_num", "likeNum", default=0),+ "favorite_count": _first(+ obj, "favorite_count", "favoriteCount", "fav_count", "favCount", "collect_count", default=0+ ),+ "comment_count": _first(obj, "comment_count", "commentCount", "comment_num", default=0),+ "share_count": _first(+ obj, "forward_count", "forwardCount", "share_count", "shareCount", "export_count", default=0+ ),+ "full_play_rate": _first(obj, "fullPlayRate", "full_play_rate", default=None),+ "avg_play_time_sec": _first(obj, "avgPlayTimeSec", "avg_play_time_sec", default=None),+ "follow_count": _first(obj, "followCount", "follow_count", default=0),+ "fast_flip_rate": _first(obj, "fastFlipRate", "fast_flip_rate", default=None),+ "yesterday_view_count": _first(obj, "yesterdayReadCount", "yesterday_read_count", default=0),+ "comments": obj.get("commentList") if isinstance(obj.get("commentList"), list) else [],+ }+++def _dedupe_posts(items: list[dict]) -> list[dict]:+ seen: set[str] = set()+ result: list[dict] = []+ for item in items:+ post_id = item.get("post_id")+ if not post_id or post_id in seen:+ continue+ seen.add(post_id)+ result.append(item)+ return result+++async def _capture_json(+ response: Response,+ captured: list[dict],+ *,+ include_request_metadata: bool = False,+) -> None:+ content_type = (response.headers.get("content-type") or "").lower()+ if "json" not in content_type and not any(k in response.url.lower() for k in ("post", "feed", "finder", "data")):+ return+ try:+ data = await response.json()+ except Exception:+ return+ packet = {"data": data}+ if include_request_metadata:+ # Needed only in memory to paginate the selected post's comments.+ # These values are never written to disk or included in report.md.+ packet.update({"url": response.url, "post_data": response.request.post_data})+ captured.append(packet)+++async def _click_text(page: Page, label: str) -> bool:+ for frame in page.frames:+ try:+ locator = frame.get_by_text(label, exact=True)+ if await locator.count():+ await locator.first.click(timeout=5000)+ return True+ except Exception:+ continue+ return False+++async def fetch_recent_posts(sess: Session, limit: int = 50) -> list[dict]:+ captured: list[dict] = []+ page = await sess.ctx.new_page()++ async def on_response(response: Response) -> None:+ await _capture_json(response, captured)++ page.on("response", on_response)+ try:+ await page.goto(PLATFORM_HOME, wait_until="domcontentloaded", timeout=60000)+ await asyncio.sleep(5)++ # The content app is loaded dynamically after expanding the sidebar.+ # Click across all frames because Tencent occasionally mounts it in an iframe.+ if not await _click_text(page, "内容管理"):+ print("[诊断] 未找到“内容管理”入口。")+ await asyncio.sleep(4)++ # Content Management may open its own route before rendering the submenu.+ clicked_video = await _click_text(page, "视频")+ if not clicked_video:+ for url in CONTENT_URLS[:-1]:+ try:+ await page.goto(url, wait_until="domcontentloaded", timeout=60000)+ await asyncio.sleep(4)+ if await _click_text(page, "视频"):+ clicked_video = True+ break+ except Exception:+ continue+ await asyncio.sleep(8)++ for _ in range(5):+ await page.mouse.wheel(0, 1400)+ await asyncio.sleep(2)++ posts: list[dict] = []+ for packet in captured:+ for obj in _walk(packet["data"]):+ if _looks_like_post(obj):+ posts.append(_normalize_post(obj))+ posts = _dedupe_posts(posts)++ if not posts:+ print(f"[诊断] 暂未解析到作品;本次在内存中检查了 {len(captured)} 个 JSON 响应,未写入原始数据。")+ return posts[:limit]+ finally:+ await page.close()+++async def capture_comment_management(sess: Session, title_hint: str = "") -> dict:+ captured: list[dict] = []+ page = await sess.ctx.new_page()++ async def on_response(response: Response) -> None:+ await _capture_json(response, captured)++ page.on("response", on_response)+ try:+ await page.goto(PLATFORM_HOME, wait_until="domcontentloaded", timeout=60000)+ await asyncio.sleep(5)+ if not await _click_text(page, "互动管理"):+ print("[诊断] 未找到“互动管理”入口。")+ await asyncio.sleep(4)+ if not await _click_text(page, "评论"):+ print("[诊断] 未找到“评论”子菜单。")+ await asyncio.sleep(10)++ clicked_post = False+ if title_hint:+ for frame in page.frames:+ try:+ candidates = frame.get_by_text(re.compile(re.escape(title_hint[:12])))+ if await candidates.count():+ await candidates.first.click(timeout=5000)+ clicked_post = True+ break+ except Exception:+ continue+ if not clicked_post:+ # Calibration fallback: click the second visible video row. The first+ # row may have zero comments; selecting another row triggers the+ # comment detail endpoint needed for field discovery.+ await page.mouse.click(480, 435)+ await asyncio.sleep(10)++ for _ in range(8):+ for frame in page.frames:+ try:+ await frame.locator("body").first.evaluate("el => el.scrollBy(0, 1200)")+ except Exception:+ continue+ await page.mouse.wheel(0, 1200)+ await asyncio.sleep(2)++ print(f"[评论诊断] 本次在内存中检查了 {len(captured)} 个 JSON 响应,未写入原始数据。")+ return {"captured_count": len(captured)}+ finally:+ await page.close()+++def _normalize_comment(obj: dict, parent_id: str = "") -> dict:+ text = str(_first(obj, "commentContent", "content", "text", default="")).strip()+ text = text.replace("/:strong", "👍").replace("/:heart", "❤️")+ return {+ "comment_id": str(_first(obj, "commentId", "comment_id", "id", default="")),+ "text": text,+ "create_time": _first(obj, "commentCreatetime", "createTime", "create_time", default=0),+ "like_count": _first(obj, "commentLikeCount", "likeCount", "like_count", default=0),+ "parent_id": parent_id,+ "is_reply": bool(parent_id or obj.get("replyCommentId")),+ }+++def _comments_from_payload(payload: dict) -> list[dict]:+ data = payload.get("data") if isinstance(payload, dict) else None+ if isinstance(data, dict) and isinstance(data.get("data"), dict):+ data = data["data"]+ if not isinstance(data, dict):+ return []+ roots = data.get("comment")+ if not isinstance(roots, list):+ return []+ comments: list[dict] = []++ def add(item: dict, parent_id: str = "") -> None:+ normalized = _normalize_comment(item, parent_id=parent_id)+ if normalized["comment_id"] and normalized["text"]:+ comments.append(normalized)+ replies = item.get("levelTwoComment")+ if isinstance(replies, list):+ for reply in replies:+ if isinstance(reply, dict):+ add(reply, normalized["comment_id"])++ for root in roots:+ if isinstance(root, dict):+ add(root)+ return comments+++def _dedupe_comments(comments: list[dict]) -> list[dict]:+ by_id: dict[str, dict] = {}+ for comment in comments:+ comment_id = comment.get("comment_id")+ if comment_id:+ by_id[comment_id] = comment+ return sorted(+ by_id.values(),+ key=lambda item: (int(item.get("like_count") or 0), int(item.get("create_time") or 0)),+ reverse=True,+ )+++async def fetch_comments_creator(+ sess: Session,+ post_id: str,+ title_hint: str = "",+ max_pages: int = 20,+) -> list[dict]:+ captured: list[dict] = []+ page = await sess.ctx.new_page()++ async def on_response(response: Response) -> None:+ await _capture_json(response, captured, include_request_metadata=True)++ page.on("response", on_response)+ try:+ await page.goto(PLATFORM_HOME, wait_until="domcontentloaded", timeout=60000)+ await asyncio.sleep(5)+ await _click_text(page, "互动管理")+ await asyncio.sleep(3)+ await _click_text(page, "评论")+ await asyncio.sleep(8)++ clicked = False+ hint = re.sub(r"\s+", " ", title_hint).strip()[:12]+ for _ in range(30):+ if hint:+ for frame in page.frames:+ try:+ locator = frame.get_by_text(re.compile(re.escape(hint)))+ if await locator.count():+ await locator.first.click(timeout=5000)+ clicked = True+ break+ except Exception:+ continue+ if clicked:+ break+ # Scroll every likely list container to load older posts.+ for frame in page.frames:+ try:+ await frame.locator("div").evaluate_all(+ "els => els.forEach(el => { if (el.scrollHeight > el.clientHeight + 100) el.scrollTop += 900; })"+ )+ except Exception:+ continue+ await asyncio.sleep(2)++ if not clicked:+ print(f"[评论] 未在评论管理列表中定位作品:{title_hint[:30]}")+ return []+ await asyncio.sleep(8)++ packet = next(+ (+ item+ for item in reversed(captured)+ if "comment/comment_list" in item.get("url", "")+ and isinstance(item.get("post_data"), str)+ ),+ None,+ )+ if not packet:+ print("[评论] 点选作品后未捕获 comment_list 接口。")+ return []++ try:+ request_body = json.loads(packet["post_data"])+ except (TypeError, json.JSONDecodeError):+ request_body = {}+ # Refuse accidental cross-post data: the request must match the target.+ if request_body.get("exportId") != post_id:+ print("[评论] 捕获到的作品 ID 与目标不一致,停止以避免串评论。")+ return []++ all_comments = _comments_from_payload(packet["data"])+ page_data = packet["data"].get("data") or {}+ page_count = 1+ while page_count < max_pages and int(page_data.get("downContinueFlag") or 0):+ request_body["lastBuff"] = page_data.get("lastBuff") or ""+ request_body["timestamp"] = str(int(time.time() * 1000))+ response = await sess.ctx.request.post(+ packet["url"],+ data=request_body,+ headers={"content-type": "application/json"},+ )+ if not response.ok:+ break+ payload = await response.json()+ all_comments.extend(_comments_from_payload(payload))+ page_data = payload.get("data") or {}+ page_count += 1++ comments = _dedupe_comments(all_comments)+ print(f"[评论] 抓到 {len(comments)} 条({page_count} 页)")+ return comments+ finally:+ await page.close()+++async def fetch_post(sess: Session, post_id: str) -> dict:+ posts = await fetch_recent_posts(sess, limit=200)+ for post in posts:+ if post["post_id"] == post_id:+ return post+ raise LookupError(+ f"未在视频号助手最近 200 条作品中找到 post_id={post_id}。"+ "为避免把未知作品误记为 0 播放,本次不生成 report.md。"+ )+++async def fetch_all(post_id: str) -> dict:+ sess = await Session.open()+ try:+ post = await fetch_post(sess, post_id)+ comments = [+ normalized+ for item in post.get("comments") or []+ if isinstance(item, dict)+ for normalized in (_normalize_comment(item),)+ if normalized["comment_id"] and normalized["text"]+ ]+ if int(post.get("comment_count") or 0) > 0:+ fetched = await fetch_comments_creator(sess, post_id, title_hint=post.get("title") or "")+ if fetched:+ comments = fetched+ return {"post": post, "comments": comments}+ finally:+ await sess.close()+++if __name__ == "__main__":+ try:+ asyncio.run(ensure_login())+ except LookupError as exc:+ print(f"[错误] {exc}", file=sys.stderr)+ raise SystemExit(3) from excdiff --git a/adapters/perf-data/wechat-channels/paths.py b/adapters/perf-data/wechat-channels/paths.pynew file mode 100644index 0000000..e2a7146--- /dev/null+++ b/adapters/perf-data/wechat-channels/paths.py@@ -0,0 +1,24 @@+from __future__ import annotations++import os+from pathlib import Path+from typing import Mapping+++def runtime_project_root(+ env: Mapping[str, str] | None = None,+ cwd: Path | None = None,+) -> Path:+ active_env = env if env is not None else os.environ+ if active_env.get("CHEAT_PROJECT_ROOT"):+ return Path(active_env["CHEAT_PROJECT_ROOT"]).expanduser().resolve()+ return (cwd or Path.cwd()).expanduser().resolve()+++def auth_dir() -> Path:+ return runtime_project_root() / ".auth-wechat-channels"+++def videos_dir() -> Path:+ override = os.environ.get("CHEAT_VIDEOS_DIR")+ return Path(override).expanduser().resolve() if override else runtime_project_root() / "videos"diff --git a/adapters/perf-data/wechat-channels/renderer.py b/adapters/perf-data/wechat-channels/renderer.pynew file mode 100644index 0000000..280287c--- /dev/null+++ b/adapters/perf-data/wechat-channels/renderer.py@@ -0,0 +1,97 @@+from __future__ import annotations++import datetime as dt+from pathlib import Path+++def _fmt_time(value) -> str:+ if not value:+ return "未知"+ try:+ ts = int(value)+ if ts > 1_000_000_000_000:+ ts //= 1000+ return dt.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M")+ except (TypeError, ValueError, OSError):+ return str(value)+++def _fmt_num(value) -> str:+ try:+ n = int(value or 0)+ except (TypeError, ValueError):+ return str(value)+ return f"{n / 10000:.1f}w" if n >= 10000 else str(n)+++def _ratio(num, denom) -> str:+ try:+ a, b = int(num or 0), int(denom or 0)+ return "-" if b <= 0 else f"{a / b * 100:.2f}%"+ except (TypeError, ValueError):+ return "-"+++def _percent(value) -> str:+ try:+ n = float(value)+ except (TypeError, ValueError):+ return "-"+ if n <= 1:+ n *= 100+ return f"{n:.2f}%"+++def slugify(text: str, max_len: int = 30) -> str:+ bad = '<>:"/\\|?*\n\r\t'+ return ("".join("_" if ch in bad else ch for ch in text).strip()[:max_len] or "untitled")+++def output_dir_for(post: dict, root: Path) -> Path:+ date = _fmt_time(post.get("create_time"))[:10].replace("未知", "nodate")+ return root / f"{date}_{slugify(post.get('title') or post['post_id'])}"+++def render_report(post: dict, script: str, comments: list[dict]) -> str:+ title = post.get("title") or "(无标题)"+ views = post.get("view_count") or 0+ lines = [+ f"# {title}",+ "",+ f"- 视频号作品 ID:`{post['post_id']}`",+ f"- 发布时间:{_fmt_time(post.get('create_time'))}",+ f"- 抓取时间:{dt.datetime.now().strftime('%Y-%m-%d %H:%M')}",+ "",+ "## 数据快照",+ "",+ f"- 播放/浏览:{_fmt_num(views)}",+ f"- 点赞:{_fmt_num(post.get('like_count'))}(赞播比 {_ratio(post.get('like_count'), views)})",+ f"- 爱心/收藏:{_fmt_num(post.get('favorite_count'))}(藏播比 {_ratio(post.get('favorite_count'), views)})",+ f"- 评论:{_fmt_num(post.get('comment_count'))}(评播比 {_ratio(post.get('comment_count'), views)})",+ f"- 分享/转发:{_fmt_num(post.get('share_count'))}(分播比 {_ratio(post.get('share_count'), views)})",+ ]+ if post.get("full_play_rate") is not None:+ lines.append(f"- 完播率:{_percent(post.get('full_play_rate'))}")+ if post.get("avg_play_time_sec") is not None:+ lines.append(f"- 平均播放时长:{float(post.get('avg_play_time_sec')):.1f} 秒")+ if post.get("fast_flip_rate") is not None:+ lines.append(f"- 快速划走率:{_percent(post.get('fast_flip_rate'))}")+ if post.get("follow_count"):+ lines.append(f"- 带来关注:{_fmt_num(post.get('follow_count'))}")+ if post.get("yesterday_view_count"):+ lines.append(f"- 昨日新增播放:{_fmt_num(post.get('yesterday_view_count'))}")+ lines.append("")+ lines.extend(["## 原始稿子", "", script.strip() or "(未提供)", "", "## 评论", ""])+ if comments:+ for comment in comments[:20]:+ if not isinstance(comment, dict):+ continue+ text = comment.get("text") or comment.get("content") or comment.get("comment") or ""+ likes = comment.get("like_count") or comment.get("likeCount") or 0+ reply = "(回复)" if comment.get("is_reply") else ""+ if text:+ lines.append(f"- [👍{likes}] {reply}{str(text).replace(chr(10), ' ').strip()}")+ else:+ lines.append("(作品列表接口未返回评论文本;需要在评论管理页进一步捕获。)")+ lines.append("")+ return "\n".join(lines)diff --git a/adapters/perf-data/wechat-channels/requirements.txt b/adapters/perf-data/wechat-channels/requirements.txtnew file mode 100644index 0000000..86a8fae--- /dev/null+++ b/adapters/perf-data/wechat-channels/requirements.txt@@ -0,0 +1 @@+playwright>=1.44diff --git a/adapters/perf-data/wechat-channels/review.py b/adapters/perf-data/wechat-channels/review.pynew file mode 100644index 0000000..7c0da51--- /dev/null+++ b/adapters/perf-data/wechat-channels/review.py@@ -0,0 +1,76 @@+from __future__ import annotations++import asyncio+import os+import sys+from pathlib import Path++import crawler+import renderer+from paths import videos_dir+++async def list_posts() -> list[dict]:+ sess = await crawler.Session.open()+ try:+ return await crawler.fetch_recent_posts(sess, limit=50)+ finally:+ await sess.close()+++async def run_with_id(post_id: str, script_path: str | None = None) -> None:+ script = ""+ if script_path:+ path = Path(script_path).expanduser()+ if path.is_file():+ script = path.read_text(encoding="utf-8", errors="ignore")++ result = await crawler.fetch_all(post_id)+ post = result["post"]+ root = videos_dir()+ root.mkdir(parents=True, exist_ok=True)+ output_override = os.environ.get("CHEAT_OUTPUT_DIR")+ out_dir = Path(output_override).expanduser().resolve() if output_override else renderer.output_dir_for(post, root)+ out_dir.mkdir(parents=True, exist_ok=True)+ if script:+ (out_dir / "script.txt").write_text(script, encoding="utf-8")+ report = out_dir / "report.md"+ report.write_text(renderer.render_report(post, script, result["comments"]), encoding="utf-8")+ print(f"✓ {report}")+++def main() -> None:+ command = sys.argv[1] if len(sys.argv) > 1 else "list"+ if command == "login":+ asyncio.run(crawler.ensure_login())+ elif command == "list":+ posts = asyncio.run(list_posts())+ for i, post in enumerate(posts):+ title = (post.get("title") or "").replace("\n", " ")[:50]+ print(+ f"[{i}] {post['post_id']} {renderer._fmt_time(post.get('create_time'))} "+ f"播放{renderer._fmt_num(post.get('view_count'))} {title}"+ )+ elif command == "capture-comments":+ async def _capture() -> None:+ sess = await crawler.Session.open()+ try:+ hint = sys.argv[2] if len(sys.argv) > 2 else ""+ await crawler.capture_comment_management(sess, title_hint=hint)+ finally:+ await sess.close()+ asyncio.run(_capture())+ elif command in ("post", "video"):+ if len(sys.argv) < 3:+ raise SystemExit("Usage: review.py post <post_id> [script_path]")+ asyncio.run(run_with_id(sys.argv[2], sys.argv[3] if len(sys.argv) > 3 else None))+ else:+ raise SystemExit("Usage: review.py login|list|capture-comments|post <post_id> [script_path]")+++if __name__ == "__main__":+ try:+ main()+ except LookupError as exc:+ print(f"[错误] {exc}", file=sys.stderr)+ raise SystemExit(3) from excdiff --git a/adapters/perf-data/wechat-channels/run.sh b/adapters/perf-data/wechat-channels/run.shnew file mode 100755index 0000000..bfeb8de--- /dev/null+++ b/adapters/perf-data/wechat-channels/run.sh@@ -0,0 +1,82 @@+#!/usr/bin/env bash+set -euo pipefail++POST_ID="${1:-}"+VIDEO_FOLDER="${2:-}"+SCRIPT_PATH="${3:-}"++if [[ -z "$POST_ID" || -z "$VIDEO_FOLDER" ]]; then+ echo "Usage: bash run.sh <post_id> <video_folder> [script_path]" >&2+ exit 3+fi++ADAPTER_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"+mkdir -p "$VIDEO_FOLDER"+VIDEO_FOLDER_REAL="$( cd "$VIDEO_FOLDER" && pwd )"++find_project_root() {+ local dir+ dir="$( dirname "$VIDEO_FOLDER_REAL" )"+ while [[ "$dir" != "/" && -n "$dir" ]]; do+ if [[ -f "$dir/.cheat-state.json" ]]; then+ printf '%s\n' "$dir"+ return 0+ fi+ dir="$( dirname "$dir" )"+ done+ return 1+}++if ! PROJECT_ROOT="$(find_project_root)"; then+ echo "Could not find .cheat-state.json above $VIDEO_FOLDER" >&2+ exit 3+fi++REPORT_PATH="$VIDEO_FOLDER_REAL/report.md"+rm -f "$REPORT_PATH"+cleanup_report_on_failure() {+ local status=$?+ if [[ "$status" -ne 0 ]]; then+ rm -f "$REPORT_PATH"+ fi+}+trap cleanup_report_on_failure EXIT++if [[ -n "${CHEAT_PYTHON:-}" ]]; then+ PYTHON="$CHEAT_PYTHON"+elif [[ -x "$PROJECT_ROOT/.venv/Scripts/python.exe" ]]; then+ PYTHON="$PROJECT_ROOT/.venv/Scripts/python.exe"+elif [[ -x "$PROJECT_ROOT/.venv/bin/python" ]]; then+ PYTHON="$PROJECT_ROOT/.venv/bin/python"+elif command -v python3 >/dev/null 2>&1; then+ PYTHON="python3"+elif command -v python >/dev/null 2>&1; then+ PYTHON="python"+else+ echo "python not found" >&2+ exit 2+fi++if ! "$PYTHON" -c "import playwright" 2>/dev/null; then+ echo "playwright not installed in project venv" >&2+ exit 2+fi+if [[ ! -d "$PROJECT_ROOT/.auth-wechat-channels" ]]; then+ echo "视频号助手未登录,请先运行: $PYTHON \"$ADAPTER_DIR/review.py\" login" >&2+ exit 1+fi++cd "$PROJECT_ROOT"+export CHEAT_PROJECT_ROOT="$PROJECT_ROOT"+export CHEAT_VIDEOS_DIR="$( dirname "$VIDEO_FOLDER_REAL" )"+export CHEAT_OUTPUT_DIR="$VIDEO_FOLDER_REAL"+export PYTHONUTF8=1++if [[ -n "$SCRIPT_PATH" && -f "$SCRIPT_PATH" ]]; then+ "$PYTHON" "$ADAPTER_DIR/review.py" post "$POST_ID" "$SCRIPT_PATH"+else+ "$PYTHON" "$ADAPTER_DIR/review.py" post "$POST_ID"+fi++[[ -f "$REPORT_PATH" ]] || exit 3+echo "report.md written to $REPORT_PATH"diff --git a/adapters/perf-data/wechat-channels/test_adapter.py b/adapters/perf-data/wechat-channels/test_adapter.pynew file mode 100644index 0000000..2ebdbae--- /dev/null+++ b/adapters/perf-data/wechat-channels/test_adapter.py@@ -0,0 +1,60 @@+from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path+++ADAPTER_DIR = Path(__file__).resolve().parent+sys.path.insert(0, str(ADAPTER_DIR))++import paths # noqa: E402+import renderer # noqa: E402+++class PrivacyBoundaryTests(unittest.TestCase):+ def test_report_excludes_raw_and_comment_identity_fields(self) -> None:+ post = {+ "post_id": "own-post-123",+ "title": "自己的作品",+ "view_count": 10,+ "raw": {"signed_url": "https://media.example/video?signature=secret"},+ }+ comments = [+ {+ "comment_id": "internal-comment-id",+ "nickname": "internal-user-name",+ "text": "有帮助",+ "like_count": 2,+ }+ ]++ report = renderer.render_report(post, "稿子", comments)++ self.assertIn("有帮助", report)+ self.assertNotIn("internal-comment-id", report)+ self.assertNotIn("internal-user-name", report)+ self.assertNotIn("signature=secret", report)++ def test_crawler_does_not_persist_raw_browser_artifacts(self) -> None:+ source = (ADAPTER_DIR / "crawler.py").read_text(encoding="utf-8")++ self.assertNotIn(".write_text(", source)+ self.assertNotIn(".screenshot(", source)+ self.assertNotIn("debug_dir", source)+++class RuntimePathTests(unittest.TestCase):+ def test_explicit_project_root_wins_over_cwd(self) -> None:+ with tempfile.TemporaryDirectory() as project, tempfile.TemporaryDirectory() as cwd:+ result = paths.runtime_project_root(+ env={"CHEAT_PROJECT_ROOT": project},+ cwd=Path(cwd),+ )++ self.assertEqual(result, Path(project).resolve())+++if __name__ == "__main__":+ unittest.main()diff --git a/adapters/perf-data/wechat-channels/test_run_contract.sh b/adapters/perf-data/wechat-channels/test_run_contract.shnew file mode 100755index 0000000..d5c6920--- /dev/null+++ b/adapters/perf-data/wechat-channels/test_run_contract.sh@@ -0,0 +1,54 @@+#!/usr/bin/env bash+set -euo pipefail++ADAPTER_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"+TMP_ROOT="$(mktemp -d)"+trap 'rm -rf "$TMP_ROOT"' EXIT++PROJECT="$TMP_ROOT/project"+VIDEO_FOLDER="$PROJECT/videos/example"+FAKE_PYTHON="$TMP_ROOT/fake-python"++mkdir -p "$PROJECT/.auth-wechat-channels" "$VIDEO_FOLDER"+printf '{}\n' > "$PROJECT/.cheat-state.json"+printf 'stale report\n' > "$VIDEO_FOLDER/report.md"++cat > "$FAKE_PYTHON" <<'FAKE'+#!/usr/bin/env bash+if [[ "${1:-}" == "-c" ]]; then+ exit "${FAKE_IMPORT_STATUS:-0}"+fi+exit 7+FAKE+chmod +x "$FAKE_PYTHON"++set +e+CHEAT_PYTHON="$FAKE_PYTHON" bash "$ADAPTER_DIR/run.sh" example "$VIDEO_FOLDER" >/dev/null 2>&1+status=$?+set -e++if [[ "$status" -ne 7 ]]; then+ echo "expected crawler exit 7, got $status" >&2+ exit 1+fi+if [[ -e "$VIDEO_FOLDER/report.md" ]]; then+ echo "stale report survived a failed crawler run" >&2+ exit 1+fi++printf 'stale report\n' > "$VIDEO_FOLDER/report.md"+set +e+FAKE_IMPORT_STATUS=9 CHEAT_PYTHON="$FAKE_PYTHON" bash "$ADAPTER_DIR/run.sh" example "$VIDEO_FOLDER" >/dev/null 2>&1+status=$?+set -e++if [[ "$status" -ne 2 ]]; then+ echo "expected dependency exit 2, got $status" >&2+ exit 1+fi+if [[ -e "$VIDEO_FOLDER/report.md" ]]; then+ echo "stale report survived dependency validation failure" >&2+ exit 1+fi++echo "run.sh failure contract: ok"diff --git a/skills/cheat-init/SKILL.md b/skills/cheat-init/SKILL.mdindex ab319ce..f207a6b 100644--- a/skills/cheat-init/SKILL.md+++ b/skills/cheat-init/SKILL.md@@ -142,11 +142,12 @@ allowed-tools: Bash(*), Read, Write, Edit, Glob, WebFetch, Skill> c) YouTube — 装 youtube-data-api adapter(需 API key)> d) B 站 — bilibili-stat adapter> e) LinkedIn — 装 linkedin-session adapter(Playwright + 登录 LinkedIn,抓单帖分析)-> f) 其他 / 多平台 — 走 manual paste 模式"+> f) 微信视频号 — 装 wechat-channels adapter(Playwright + 扫码登录视频号助手,仅抓自己账号后台数据)+> g) 其他 / 多平台 — 走 manual paste 模式"-如选 a/b/c/d/e → 询问 Q2.2;如选 f → 跳到 Q2.3 manual。+如选 a/b/c/d/e/f → 询问 Q2.2;如选 g → 跳到 Q2.3 manual。-**Q2.2: adapter 安装时机**(仅 Q2.1=a/b/c/d/e)+**Q2.2: adapter 安装时机**(仅 Q2.1=a/b/c/d/e/f)> "现在装 adapter 自动抓取,还是先手动告诉我?> - 现在装 — 引导你装 Playwright + 扫码 → 抓回最近 N 条数据@@ -267,17 +268,17 @@ c) 不找 → state 标 `benchmark_status: none`,用通用 v0 起步0. **`.gitignore`(安全 — 必须第一步创建)**```"先创建 .gitignore,把账号凭证挡在版本控制外——这是第一件事。- .auth/ / .auth-xhs/ / .auth-linkedin/ 存的是抖音 / 小红书 / LinkedIn 的登录态(等同账号密码),+ .auth/ / .auth-xhs/ / .auth-linkedin/ / .auth-wechat-channels/ 存的是各平台登录态(等同账号密码),.cheat-secrets.json 存 API key / cookie——一旦被 commit 或云同步就等于泄露账号。注意:predictions/ videos/ scripts/ 这些**不**忽略——原则 #1/#3 依赖git history 作为预测的不可变档案,必须入库。"```- 复制 `cheat-on-content/templates/gitignore.template` → `<user-repo>/.gitignore`- 如 `<user-repo>/.gitignore` **已存在** → 不覆盖;逐行检查并**追加缺失行**,至少确保- `.auth/`、`.auth-xhs/`、`.auth-linkedin/`、`.cheat-secrets.json` 四行存在+ `.auth/`、`.auth-xhs/`、`.auth-linkedin/`、`.auth-wechat-channels/`、`.cheat-secrets.json` 五行存在- 即使用户项目当前**还不是 git 仓库**也照常创建——它会在用户 `git init` 的那一刻立即生效- 创建后提醒一句:如果项目已经 `git init` 过且可能误加过 `.auth/`,让用户跑- `git rm -r --cached .auth .auth-xhs .auth-linkedin .cheat-secrets.json` 把已暂存的凭证移出+ `git rm -r --cached .auth .auth-xhs .auth-linkedin .auth-wechat-channels .cheat-secrets.json` 把已暂存的凭证移出1. **`.cheat-state.json`**```@@ -304,7 +305,7 @@ c) 不找 → state 标 `benchmark_status: none`,用通用 v0 起步"data_layer": "markdown","hooks_installed": <查 Q5 映射表,写 bool true/false>,"enabled_trend_sources": ["manual-paste"],- "enabled_perf_adapters": <Q2.1=a→[\"douyin-session\"];b→[\"xhs-explore\"];c→[\"youtube-data-api\"];d→[\"bilibili-stat\"];e→[\"linkedin-session\"];其他→[]>,+ "enabled_perf_adapters": <Q2.1=a→[\"douyin-session\"];b→[\"xhs-explore\"];c→[\"youtube-data-api\"];d→[\"bilibili-stat\"];e→[\"linkedin-session\"];f→[\"wechat-channels\"];其他→[]>,"last_bump_at": null,"last_bump_self_audited": false,"last_published_at": null,diff --git a/skills/cheat-retro/SKILL.md b/skills/cheat-retro/SKILL.mdindex a46e9f4..4f0fce3 100644--- a/skills/cheat-retro/SKILL.md+++ b/skills/cheat-retro/SKILL.md@@ -96,6 +96,7 @@ allowed-tools: Bash(*), Read, Edit, Write, Glob, Grep, Skill| `douyin` | `adapters/perf-data/douyin-session/` | `bash <adapters-dir>/douyin-session/run.sh <aweme_id> <video_folder>` || `xhs` | `adapters/perf-data/xhs-explore/` | `bash <adapters-dir>/xhs-explore/run.sh <note_id> <video_folder>` || `linkedin` | `adapters/perf-data/linkedin-session/` | `bash <adapters-dir>/linkedin-session/run.sh <activity_id> <video_folder>` |+| `wechat_channels` | `adapters/perf-data/wechat-channels/` | `bash <adapters-dir>/wechat-channels/run.sh <post_id> <video_folder>` || `youtube` | `adapters/perf-data/youtube-data-api/`(planned — batch 3, not yet available) | 调 YouTube Data API(需 API key) || `bilibili` | `adapters/perf-data/bilibili-stat/` | `bash <adapters-dir>/bilibili-stat/run.sh <bvid> <video_folder>` || 其他 | 无 adapter | 优雅降级到 Path A |@@ -120,6 +121,12 @@ allowed-tools: Bash(*), Read, Edit, Write, Glob, Grep, Skill- **只能抓你本人发的帖子**(LinkedIn 单帖分析仅作者可见);LinkedIn 界面 日/英 随机切换,`extract.py` 的 `POST_METRICS` 已存双语标签,万一某项为 None 看 `.cheat-cache/linkedin-session-debug/post_<id>.txt` 把新标签补进去- **评论只给数、不给正文**(分析页限制)→ report.md 标注 → **降级要求用户 manual 粘 top 评论**(评论是真信号,不能省)+**wechat-channels 的特殊处理**:+- 仅抓用户自己登录后可见的视频号助手后台数据;调用前确认内容项目存在 `.auth-wechat-channels/`+- 不存在登录态时,提示先运行 `python <adapter>/review.py login` 并扫码;登录态只保存在内容项目本地+- adapter 输出 `report.md`,但不落盘原始响应、请求体、完整后台 URL、后台截图、页面文本、评论者昵称或内部用户 ID+- 找不到目标作品或 adapter 失败时,非 0 退出并降级 manual;不得把旧 report.md 当作本次成功+**bilibili-stat 的特殊处理**:- 视频 URL(`https://www.bilibili.com/video/<BV号>` 或 b23.tv 短链)或直接给 BV 号 → adapter 自动提取 BV 号- **无需登录**:B站视频数据(view)与评论(reply)都是公开接口、免 wbi 签名,adapter 是纯 httpx,没有 `crawler.py login` 步骤、不碰 `.auth/`diff --git a/templates/gitignore.template b/templates/gitignore.templateindex 3911572..ae78b9e 100644--- a/templates/gitignore.template+++ b/templates/gitignore.template@@ -9,10 +9,12 @@# .auth/ = 抖音 Playwright 登录态(含 sessionid)# .auth-xhs/ = 小红书 Playwright 登录态(含 web_session 等)# .auth-linkedin/ = LinkedIn Playwright 登录态(含 li_at)+# .auth-wechat-channels/ = 视频号助手 Playwright 登录态# .cheat-secrets.json = API key / cookie.auth/.auth-xhs/.auth-linkedin/+.auth-wechat-channels/.cheat-secrets.json# ── 本地缓存与生成物 ──