Skip to content

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: linkedin-session adapter (LinkedIn perf-data) (#51)

Heqing Huangd07edb5ff426
diff --git a/.gitignore b/.gitignore
index 5fc697f..ee9d8e1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -46,6 +46,7 @@ content.db
# adapter 跑过留下的
.auth/
.auth-xhs/
+.auth-linkedin/
.debug/
# Editor / IDE
diff --git a/adapters/perf-data/linkedin-session/.gitattributes b/adapters/perf-data/linkedin-session/.gitattributes
new file mode 100644
index 0000000..1bbd695
--- /dev/null
+++ b/adapters/perf-data/linkedin-session/.gitattributes
@@ -0,0 +1,2 @@
+*.sh text eol=lf
+*.py text eol=lf
diff --git a/adapters/perf-data/linkedin-session/README.md b/adapters/perf-data/linkedin-session/README.md
new file mode 100644
index 0000000..d5a80d9
--- /dev/null
+++ b/adapters/perf-data/linkedin-session/README.md
@@ -0,0 +1,151 @@
+# Adapter: linkedin-session(LinkedIn 单帖分析爬取)
+
+被 `/cheat-retro` 在 `state.data_collection=adapter` + `platform=linkedin` 时自动调用。
+
+> **来源**:架构照搬 `douyin-session`(Playwright 持久化登录态 + 读渲染后 DOM)。
+> 单帖分析(impressions / reach / reactions / …)已在真实 LinkedIn 账号上端到端验证。
+
+---
+
+## 这个 adapter 是干嘛的
+
+LinkedIn 单帖分析页(`/analytics/post-summary/`)**只对帖子作者本人可见**、且数据是
+SSR/inline 进页面的——没有公开接口、没有稳定可拦的 voyager XHR,纯 HTTP / requests
+(包括 Claude 的 WebFetch)拿不到任何数据。
+
+linkedin-session 用 **Playwright + 持久化 Chromium context** 模拟真实浏览器:
+
+- 你首次登录 LinkedIn(拿到 `li_at` cookie),cookie 存在**你的内容项目根目录** `.auth-linkedin/`
+- 之后每次抓取直接复用 cookie,不用重新登录
+- 导航到单帖分析页 → 读渲染后 DOM 文本 → 按已知标签锚点解析(**不逆向、不伪造请求**)
+- 抓单帖的 10 个指标:展示 / 触达 / 反应 / 评论 / 转发 / 收藏 / 私信转发 / 社交互动 /
+ 帖子带来的主页访问 / 帖子带来的新增关注,外加帖子正文
+
+输出写到**你的内容项目** `videos/<...>/report.md`(`cheat-retro` 读这个文件 → 摘要写到 prediction 复盘段)。
+调试产物(DOM 文本 dump)写到 `.cheat-cache/linkedin-session-debug/`,避免散落在 skill 源码目录。
+
+## 一个诚实的维护说明:LinkedIn 会随机切换 日/英
+
+LinkedIn 同一账号、同一 session 内会在**日文界面**和**英文界面**之间随机切换
+(标签会从 `Impressions` 变成 `インプレッション数`)。所以 `extract.py` 的 `POST_METRICS`
+**每个指标都存两套别名**,解析时两套都试。如果你的界面是第三种语言,照着 `POST_METRICS`
+把对应标签补进去即可(多语言别名是 list,加一项不影响已有的)。
+
+## 安装(一次性)
+
+```bash
+# 1. 进你的内容项目根目录
+cd ~/my-channel
+
+# 2. 建虚拟环境(强烈建议——Playwright + Chromium 几百 MB,别污染 system Python)
+python3 -m venv .venv
+source .venv/bin/activate # Windows: .venv\Scripts\activate
+
+# 3. 装 Playwright
+pip install -r "$ADAPTER/requirements.txt"
+
+# 4. 装 Chromium(首次必须)
+playwright install chromium
+
+# 5. 首次登录 LinkedIn
+ADAPTER=$(find ~/cheat-on-content -name "linkedin-session" -type d 2>/dev/null | head -1)
+python "$ADAPTER/crawler.py" login
+# → 弹出 Chromium 窗口,登录 LinkedIn
+# → 登录成功后窗口自动关闭,cookie(li_at) 存在 当前目录/.auth-linkedin/
+```
+
+> 提示:adapter 在 `~/cheat-on-content/adapters/perf-data/linkedin-session`(克隆源码处),
+> 不在 `~/.claude/skills`(install.sh 只复制 skill,不复制 adapter)。
+
+## 用法
+
+cheat-retro 自动调用,你不需要手动跑。手动测试:
+
+```bash
+cd ~/my-channel
+source .venv/bin/activate
+
+# 抓特定帖子(给 activity_id 或整条帖子链接都行)
+python "$ADAPTER/review.py" video 7470493738918920193 <video_folder>/script.md
+
+# 输出在 当前目录/videos/<日期>_<activity_id>_<作者>/report.md
+```
+
+run.sh 是 cheat-retro 调用的 wrapper:
+
+```bash
+bash run.sh <activity_id_or_url> <video_folder> [<script_path>]
+```
+
+## 怎么拿到 activity_id
+
+LinkedIn 帖子 URL 形态:
+
+- `https://www.linkedin.com/feed/update/urn:li:activity:7470493738918920193/` → `activity_id = 7470493738918920193`
+- 分析页 `https://www.linkedin.com/analytics/post-summary/urn:li:activity:7470493738918920193/` → 同上
+
+adapter 会从整条链接里自动提取 activity_id(也接受直接给裸 id)。
+cheat-publish 登记发布时把 activity_id 存到 prediction header,cheat-retro 启动时读这个字段。
+
+## report.md 输出格式
+
+由 `renderer.py` 生成,与 douyin-session 同形。包含:
+
+- 帖子元信息(作者、发布距今、链接、抓取时间)
+- 数据快照(展示 / 触达 / 反应 / 评论 / 转发 / 收藏 / 私信转发 / 社交互动 /
+ 帖子带来的主页访问 / 帖子带来的新增关注 + 派生比率:反应率 / 评论率 / 转发率 / 社交互动率)
+- 帖子正文(从分析页 DOM 抽到时)
+- 原始稿子(cheat-retro 传入)
+- 评论(**LinkedIn 单帖分析页只给评论数、不给评论正文**——report.md 会标注,建议手动粘 top 评论)
+
+## 失败模式(按概率从高到低)
+
+| 症状 | 原因 | 处理 |
+|---|---|---|
+| `ensure_login` 超时 | cookie 过期或 LinkedIn 强制 reauth | 重新跑 `python crawler.py login` |
+| 抓取被重定向到登录页 | `li_at` 失效 | 重新跑 `python crawler.py login` |
+| `impressions` 为 None / 指标缺失 | LinkedIn 改了版式或换了第三种语言 | 看 `.cheat-cache/linkedin-session-debug/post_<id>.txt`,把新标签加进 `extract.py` 的 `POST_METRICS` |
+| 看不到分析数据 | 该帖**不是你本人**发的(单帖分析仅作者可见) | 只能抓自己的帖子 |
+| 正文没抓到 | 分析页 DOM 偶尔不含完整正文 | report.md 会标注;手动补正文 |
+| Chromium 崩溃 / 卡死 | 通常是机器内存不足 | 关其他 Chromium;`playwright install chromium --force` 重装 |
+
+**关键现实**:LinkedIn 没有给个人创作者的公开数据 API,单帖分析只能靠登录态读页面。
+版式和界面语言都可能变——这个 adapter **需要持续维护**,第一步永远是看 debug 目录里的
+`post_<id>.txt` 对照标签。
+
+## 稳定性等级
+
+★★ — Playwright + 登录态能拿到纯 HTTP 拿不到的数据,但解析依赖 DOM 文本版式 +
+界面语言(日/英随机),比走 JSON 接口的 adapter 略脆。建议每月手动跑一次验证健康。
+
+## 风险提示
+
+- **冷启动用户慎装**:Playwright + Chromium ~500MB,新人容易劝退
+- **TOS 风险**:用自己的 cookie 抓自己后台数据是个人用途;别滥用、别高频
+- **不要把 `.auth-linkedin/` 提交到 git**:cookie(`li_at`) 等同你的 LinkedIn 会话凭据,
+ 泄露 = 他人能登录你的 LinkedIn 账号
+- `.cheat-cache/linkedin-session-debug/` 也不应提交(里面是页面 DOM 文本 dump,可能含个人信息)
+
+## 文件清单
+
+```
+adapters/perf-data/linkedin-session/
+├── README.md # 本文件
+├── requirements.txt # playwright>=1.44
+├── crawler.py # 抓取核心(登录 + 单帖分析页 DOM 抓取)
+├── extract.py # 纯函数 DOM 解析(双语 日/英 标签)
+├── renderer.py # 把抓回的数据渲染成 report.md
+├── review.py # CLI 入口(login / video <activity_id> [script])
+├── paths.py # 项目根 / .auth-linkedin / debug 路径解析
+├── test_extract.py # extract.py 单元测试(合成样本,含双语)
+├── .gitattributes # *.sh / *.py eol=lf(防 Windows-CRLF 破坏脚本)
+└── run.sh # cheat-retro 调用的 wrapper
+```
+
+## 与其他 adapter 的关系
+
+- `douyin-session` — 抖音,本 adapter 的架构来源
+- `xhs-explore` — 小红书,同走 Playwright 被动路线
+- `bilibili-stat` — B 站官方 stat 公开接口,最轻
+
+如果你做多平台内容,**只装你实际用的 adapter**——不需要全装。
diff --git a/adapters/perf-data/linkedin-session/crawler.py b/adapters/perf-data/linkedin-session/crawler.py
new file mode 100644
index 0000000..1347fbd
--- /dev/null
+++ b/adapters/perf-data/linkedin-session/crawler.py
@@ -0,0 +1,140 @@
+"""LinkedIn 单帖分析抓取。
+
+登录一次后,Cookie(含 `li_at`)持久化在 .auth-linkedin/,之后直接复用。
+LinkedIn 把单帖分析(/analytics/post-summary/)SSR/inline 进页面,没有稳定可拦的
+voyager XHR,所以读渲染后 DOM 文本、按已知标签锚点解析(见 extract.py)。
+和 douyin-session 一样:一次抓取共享一个持久化 Chromium 会话。
+"""
+from __future__ import annotations
+
+import asyncio
+import re
+from typing import Any
+
+from playwright.async_api import BrowserContext, Page, async_playwright
+
+from paths import auth_dir, debug_dir
+from extract import parse_post_meta, parse_post_summary
+
+FEED = "https://www.linkedin.com/feed/"
+POST_SUMMARY = "https://www.linkedin.com/analytics/post-summary/urn:li:activity:{activity_id}/"
+
+_ACTIVITY_RE = re.compile(r"urn:li:activity:(\d+)|activity[:-](\d+)|/(\d{15,25})\b")
+
+
+def extract_activity_id(raw: str) -> str:
+ """从帖子 URL 或裸 id 提取 activity_id。
+
+ 支持:
+ - 裸 id:`7470493738918920193`
+ - 帖子链接:`https://www.linkedin.com/feed/update/urn:li:activity:7470493738918920193/`
+ - 分析链接:`https://www.linkedin.com/analytics/post-summary/urn:li:activity:7470493738918920193/`
+ 抽不出时原样返回(交给上层报错)。
+ """
+ raw = raw.strip()
+ if raw.isdigit():
+ return raw
+ m = _ACTIVITY_RE.search(raw)
+ if m:
+ return next(g for g in m.groups() if g)
+ return raw
+
+
+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_path = auth_dir()
+ auth_path.mkdir(parents=True, exist_ok=True)
+ ctx = await pw.chromium.launch_persistent_context(
+ user_data_dir=str(auth_path),
+ 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(ctx: BrowserContext) -> bool:
+ cookies = await ctx.cookies("https://www.linkedin.com")
+ return any(c["name"] == "li_at" for c in cookies)
+
+
+async def ensure_login(timeout_s: int = 300) -> bool:
+ """打开 LinkedIn,等用户登录;检测到 li_at cookie 后返回。"""
+ sess = await Session.open()
+ try:
+ page = await sess.ctx.new_page()
+ await page.goto(FEED)
+ print(f"[登录] 在弹出的 Chromium 里登录 LinkedIn。最多等 {timeout_s} 秒……")
+ for i in range(timeout_s):
+ if await _logged_in(sess.ctx):
+ print(f"[登录] ✓ 检测到 li_at(用时 {i}s)。Cookie 已存到 .auth-linkedin/")
+ await asyncio.sleep(1)
+ return True
+ await asyncio.sleep(1)
+ print("[登录] 超时未检测到登录态。")
+ return False
+ finally:
+ await sess.close()
+
+
+async def _scrape_post(page: Page, activity_id: str) -> dict:
+ await page.goto(
+ POST_SUMMARY.format(activity_id=activity_id),
+ wait_until="domcontentloaded",
+ timeout=60000,
+ )
+ await asyncio.sleep(7)
+ if "post-summary" not in page.url:
+ print(f"[post] ⚠ 可能被登出 / 重定向:{page.url}")
+ txt = await page.inner_text("body")
+ dbg = debug_dir()
+ dbg.mkdir(parents=True, exist_ok=True)
+ (dbg / f"post_{activity_id}.txt").write_text(txt, encoding="utf-8")
+
+ result = parse_post_summary(txt)
+ result["meta"] = parse_post_meta(txt)
+ result["activity_id"] = activity_id
+ if result["metrics"].get("impressions") is None:
+ print(f"[post] ⚠ {activity_id} 没抽到 impressions(结构可能变了,看 {dbg}/post_{activity_id}.txt)")
+ return result
+
+
+async def fetch_post_summary(activity_id: str, headless: bool = True) -> dict:
+ """DOM 抽取单帖分析(/analytics/post-summary/)。只能看**你自己**的帖子。"""
+ sess = await Session.open(headless=headless)
+ try:
+ if not await _logged_in(sess.ctx):
+ print("[post] 未登录。先跑:python review.py login")
+ return {}
+ page = await sess.ctx.new_page()
+ return await _scrape_post(page, activity_id)
+ finally:
+ await sess.close()
+
+
+async def fetch_all(activity_id: str, headless: bool = True) -> dict:
+ """抓单帖分析,返回 {'post': {...}}(与 review.py 的渲染入口对齐)。"""
+ print(f" → 打开单帖分析页 activity:{activity_id}")
+ post = await fetch_post_summary(activity_id, headless=headless)
+ if post:
+ m = post.get("metrics", {})
+ print(f" impressions={m.get('impressions')} reactions={m.get('reactions')} comments={m.get('comments')}")
+ return {"post": post}
+
+
+if __name__ == "__main__":
+ asyncio.run(ensure_login())
diff --git a/adapters/perf-data/linkedin-session/extract.py b/adapters/perf-data/linkedin-session/extract.py
new file mode 100644
index 0000000..a26d2fd
--- /dev/null
+++ b/adapters/perf-data/linkedin-session/extract.py
@@ -0,0 +1,113 @@
+"""从渲染后的 DOM 文本里抽取 LinkedIn 单帖分析指标。
+
+LinkedIn 把单帖分析(/analytics/post-summary/)SSR/inline 进页面——不是可拦的
+voyager XHR,所以读 `inner_text` 文本、按已知标签锚点解析。纯函数,可独立测试
+(见 test_extract.py)。
+
+LinkedIn 会在**日文 / 英文之间随机切换**界面语言(同一 session 内都可能换),
+所以每个指标都存多语言别名,两套都试。
+"""
+from __future__ import annotations
+
+import re
+
+
+def _to_int(s: str) -> int | None:
+ """'34,057' → 34057;'1.2K' → 1200;'3M' → 3000000;抽不出返回 None。"""
+ s = s.strip().replace(",", "")
+ m = re.fullmatch(r"([\d.]+)\s*([KMB]?)", s)
+ if not m:
+ return None
+ mult = {"": 1, "K": 1_000, "M": 1_000_000, "B": 1_000_000_000}[m.group(2)]
+ try:
+ return int(float(m.group(1)) * mult)
+ except ValueError:
+ return None
+
+
+# 单帖分析页(/analytics/post-summary/)。LinkedIn 在 日/英 间**随机切换**语言,
+# 所以每个指标存多语言别名。版式两段:
+# 顶部指标——值在标签上一行("before")
+# 互动明细——值在标签下一行("after")
+# (labels, key, value_position)
+POST_METRICS = [
+ (("インプレッション数", "Impressions"), "impressions", "before"),
+ (("リーチしたメンバー", "Members reached"), "reach", "before"),
+ (("この投稿からのプロフィール閲覧ユーザー", "Profile viewers from this post"), "profile_views_from_post", "before"),
+ (("この投稿で獲得したフォロワー", "Followers gained from this post"), "followers_from_post", "before"),
+ (("ソーシャルエンゲージメント", "Social engagements"), "social_engagement", "before"),
+ (("リアクション", "Reactions"), "reactions", "after"),
+ (("コメント", "Comments"), "comments", "after"),
+ (("再投稿", "Reposts"), "reposts", "after"),
+ (("保存数", "Saves"), "saves", "after"),
+ (("LinkedInでの送信数", "Sends on LinkedIn"), "sends", "after"),
+]
+
+_IMPRESSION_LABELS = ("インプレッション数", "Impressions")
+
+# 作者署名行的语言标记("…さんが投稿しました • 4日" / "… posted this • 6d")。
+_BYLINE_MARKERS = ("さんが投稿しました", "posted this")
+# 顶部指标段之前会出现的小标题("Discovery" / "調査" 等)——正文与指标的分界。
+_BODY_END_MARKERS = ("調査", "Discovery", "ディスカバリー")
+
+
+def parse_post_summary(text: str) -> dict:
+ """单帖分析 DOM 文本 → {'metrics': {...}}。支持 日/英(LinkedIn 随机切换)。
+
+ 锚在第一个指标(Impressions)后,避开正文里的数字;每个指标按 value_position
+ 取前一行 / 后一行。抽不到的指标为 None(接口/版式变更时不致整体崩)。
+ """
+ lines = [l.strip() for l in text.splitlines() if l.strip()]
+ start = 0
+ for i, l in enumerate(lines):
+ if l in _IMPRESSION_LABELS:
+ start = max(0, i - 1)
+ break
+ scan = lines[start:]
+ out = {key: None for _, key, _ in POST_METRICS}
+ for i, line in enumerate(scan):
+ for labels, key, pos in POST_METRICS:
+ if line not in labels or out[key] is not None:
+ continue
+ j = i - 1 if pos == "before" else i + 1
+ if 0 <= j < len(scan):
+ out[key] = _to_int(scan[j])
+ return {"metrics": out}
+
+
+def parse_post_meta(text: str) -> dict:
+ """从单帖分析 DOM 抽作者署名 + 相对发布时间 + 正文。
+
+ 版式(reading order):署名行("…さんが投稿しました • 4日" / "… posted this • 6d")
+ → 正文若干行 → 顶部指标小标题("Discovery"/"調査")→ 指标段。
+ 取署名行与小标题之间的行为正文;抽不到时各字段为空,不报错。
+ 返回 {'author': str, 'age': str, 'text': str}。
+ """
+ lines = [l.strip() for l in text.splitlines() if l.strip()]
+ byline_idx = None
+ for i, l in enumerate(lines):
+ if any(m in l for m in _BYLINE_MARKERS):
+ byline_idx = i
+ break
+ if byline_idx is None:
+ return {"author": "", "age": "", "text": ""}
+
+ byline = lines[byline_idx]
+ author, age = "", ""
+ if "•" in byline:
+ head, _, tail = byline.partition("•")
+ age = tail.strip()
+ author = head.strip()
+ else:
+ author = byline.strip()
+ for marker in _BYLINE_MARKERS:
+ if marker in author:
+ author = author.split(marker, 1)[0].strip()
+ break
+
+ body: list[str] = []
+ for l in lines[byline_idx + 1:]:
+ if l in _IMPRESSION_LABELS or l in _BODY_END_MARKERS:
+ break
+ body.append(l)
+ return {"author": author, "age": age, "text": "\n".join(body).strip()}
diff --git a/adapters/perf-data/linkedin-session/paths.py b/adapters/perf-data/linkedin-session/paths.py
new file mode 100644
index 0000000..dfe5a38
--- /dev/null
+++ b/adapters/perf-data/linkedin-session/paths.py
@@ -0,0 +1,41 @@
+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()
+ base_cwd = cwd if cwd is not None else Path.cwd()
+ return Path(base_cwd).expanduser().resolve()
+
+
+def auth_dir(
+ env: Mapping[str, str] | None = None,
+ cwd: Path | None = None,
+) -> Path:
+ # 独立于抖音 .auth/ 与小红书 .auth-xhs/,避免多 adapter 共用 project root 时 cookie 串味
+ return runtime_project_root(env=env, cwd=cwd) / ".auth-linkedin"
+
+
+def debug_dir(
+ env: Mapping[str, str] | None = None,
+ cwd: Path | None = None,
+) -> Path:
+ return runtime_project_root(env=env, cwd=cwd) / ".cheat-cache" / "linkedin-session-debug"
+
+
+def videos_dir(
+ 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_VIDEOS_DIR"):
+ return Path(active_env["CHEAT_VIDEOS_DIR"]).expanduser().resolve()
+ return runtime_project_root(env=env, cwd=cwd) / "videos"
diff --git a/adapters/perf-data/linkedin-session/renderer.py b/adapters/perf-data/linkedin-session/renderer.py
new file mode 100644
index 0000000..471c417
--- /dev/null
+++ b/adapters/perf-data/linkedin-session/renderer.py
@@ -0,0 +1,105 @@
+"""把抓到的 LinkedIn 单帖分析渲染成 NotebookLM 友好的 Markdown(与 douyin-session 同形)。"""
+from __future__ import annotations
+
+import datetime as dt
+from pathlib import Path
+
+
+def _fmt_num(n: int | None) -> str:
+ if n is None:
+ return "-"
+ return f"{n:,}"
+
+
+def _ratio(num: int | None, den: int | None) -> str:
+ """派生比率,分母为 0 / 缺失时显示 '-'。"""
+ if not num or not den:
+ return "-"
+ return f"{num / den * 100:.2f}%"
+
+
+def render_report(post: dict, script: str) -> str:
+ metrics = post.get("metrics", {}) if post else {}
+ meta = post.get("meta", {}) if post else {}
+ activity_id = post.get("activity_id", "") if post else ""
+
+ impressions = metrics.get("impressions")
+ reactions = metrics.get("reactions")
+ comments = metrics.get("comments")
+ reposts = metrics.get("reposts")
+
+ author = meta.get("author") or ""
+ title = author and f"{author} 的 LinkedIn 帖子" or f"LinkedIn 帖子 {activity_id}"
+
+ lines: list[str] = []
+ lines.append(f"# {title}")
+ lines.append("")
+ lines.append(f"- 帖子 activity_id:`{activity_id}`")
+ if author:
+ lines.append(f"- 作者:{author}")
+ if meta.get("age"):
+ lines.append(f"- 发布距今:{meta['age']}")
+ lines.append(f"- 链接:https://www.linkedin.com/feed/update/urn:li:activity:{activity_id}/")
+ lines.append(f"- 抓取时间:{dt.datetime.now().strftime('%Y-%m-%d %H:%M')}")
+ lines.append("")
+
+ lines.append("## 数据快照")
+ lines.append("")
+ lines.append(f"- 展示(Impressions):{_fmt_num(impressions)}")
+ lines.append(f"- 触达人数(Members reached):{_fmt_num(metrics.get('reach'))}")
+ lines.append(f"- 社交互动(Social engagements):{_fmt_num(metrics.get('social_engagement'))}")
+ lines.append(f"- 点赞 / 反应(Reactions):{_fmt_num(reactions)}")
+ lines.append(f"- 评论(Comments):{_fmt_num(comments)}")
+ lines.append(f"- 转发(Reposts):{_fmt_num(reposts)}")
+ lines.append(f"- 收藏(Saves):{_fmt_num(metrics.get('saves'))}")
+ lines.append(f"- 私信转发(Sends):{_fmt_num(metrics.get('sends'))}")
+ lines.append(f"- 帖子带来的主页访问(Profile viewers from post):{_fmt_num(metrics.get('profile_views_from_post'))}")
+ lines.append(f"- 帖子带来的新增关注(Followers from post):{_fmt_num(metrics.get('followers_from_post'))}")
+ lines.append("")
+ lines.append("派生比率(相对展示数):")
+ lines.append(f"- 反应率:{_ratio(reactions, impressions)}")
+ lines.append(f"- 评论率:{_ratio(comments, impressions)}")
+ lines.append(f"- 转发率:{_ratio(reposts, impressions)}")
+ lines.append(f"- 社交互动率:{_ratio(metrics.get('social_engagement'), impressions)}")
+ lines.append("")
+
+ lines.append("## 帖子正文")
+ lines.append("")
+ body = (meta.get("text") or "").strip()
+ lines.append(body if body else "(未抓到正文——单帖分析页有时不含完整正文,可手动补)")
+ lines.append("")
+
+ lines.append("## 原始稿子")
+ lines.append("")
+ lines.append(script.strip() if script.strip() else "(未提供)")
+ lines.append("")
+
+ lines.append("## 评论")
+ lines.append("")
+ if comments:
+ lines.append(
+ f"LinkedIn 单帖分析页只给评论**数**({comments} 条),不含评论正文。"
+ )
+ lines.append(
+ "评论文本是真信号——建议手动把 top 评论粘到这一节,供复盘分析。"
+ )
+ else:
+ lines.append("(没有评论,或未抓到评论数)")
+ lines.append("")
+
+ return "\n".join(lines)
+
+
+def slugify(text: str, max_len: int = 30) -> str:
+ """生成文件夹友好的短标题。"""
+ bad = '<>:"/\\|?*\n\r\t'
+ out = "".join("_" if ch in bad else ch for ch in text).strip()
+ return out[:max_len] or "untitled"
+
+
+def output_dir_for(post: dict, root: Path) -> Path:
+ activity_id = post.get("activity_id", "") if post else ""
+ date = dt.datetime.now().strftime("%Y-%m-%d")
+ author = (post.get("meta", {}) or {}).get("author") if post else ""
+ slug = slugify(author or activity_id or "linkedin")
+ return root / f"{date}_{activity_id}_{slug}".rstrip("_")
diff --git a/adapters/perf-data/linkedin-session/requirements.txt b/adapters/perf-data/linkedin-session/requirements.txt
new file mode 100644
index 0000000..86a8fae
--- /dev/null
+++ b/adapters/perf-data/linkedin-session/requirements.txt
@@ -0,0 +1 @@
+playwright>=1.44
diff --git a/adapters/perf-data/linkedin-session/review.py b/adapters/perf-data/linkedin-session/review.py
new file mode 100644
index 0000000..c8acec2
--- /dev/null
+++ b/adapters/perf-data/linkedin-session/review.py
@@ -0,0 +1,69 @@
+"""发完帖子后跑一次:抓 LinkedIn 单帖分析 → 生成 NotebookLM 友好的 md。
+
+用法:
+ python review.py login # 仅登录(首次,弹出浏览器)
+ python review.py video <activity_id_or_url> [script.txt] # 抓单帖分析
+
+`video` 子命令名沿用 douyin-session / bilibili-stat 的契约(/cheat-retro 统一调
+`run.sh ... video ...`);对 LinkedIn 而言"video"即一条帖子。
+"""
+from __future__ import annotations
+
+import asyncio
+import sys
+from pathlib import Path
+
+import crawler
+import renderer
+from paths import videos_dir
+
+
+def run_with_id(activity_raw: str, script_path: str | None) -> None:
+ active_videos_dir = videos_dir()
+ active_videos_dir.mkdir(parents=True, exist_ok=True)
+
+ activity_id = crawler.extract_activity_id(activity_raw)
+
+ script = ""
+ if script_path:
+ p = Path(script_path).expanduser()
+ if p.is_file():
+ script = p.read_text(encoding="utf-8", errors="ignore")
+ print(f"稿子:{p.name}({len(script)} 字符)")
+ else:
+ print(f"[警告] 找不到稿子 {p}")
+
+ print(f"[抓取] 帖子 activity:{activity_id}")
+ result = asyncio.run(crawler.fetch_all(activity_id))
+ post = result["post"]
+ if not post:
+ print("❌ 未抓到数据(多半是未登录)。先跑:python review.py login")
+ sys.exit(3)
+
+ out_dir = renderer.output_dir_for(post, active_videos_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ if script:
+ (out_dir / "script.txt").write_text(script, encoding="utf-8")
+ md = renderer.render_report(post, script)
+ report = out_dir / "report.md"
+ report.write_text(md, encoding="utf-8")
+ print(f"\n✓ {report}")
+
+
+def main() -> None:
+ if len(sys.argv) > 1 and sys.argv[1] == "login":
+ asyncio.run(crawler.ensure_login())
+ return
+ if len(sys.argv) > 1 and sys.argv[1] == "video":
+ if len(sys.argv) < 3:
+ print("用法:python review.py video <activity_id_or_url> [script.txt]")
+ sys.exit(3)
+ activity_raw = sys.argv[2]
+ script_path = sys.argv[3] if len(sys.argv) > 3 else None
+ run_with_id(activity_raw, script_path)
+ return
+ print(__doc__)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/adapters/perf-data/linkedin-session/run.sh b/adapters/perf-data/linkedin-session/run.sh
new file mode 100755
index 0000000..b787099
--- /dev/null
+++ b/adapters/perf-data/linkedin-session/run.sh
@@ -0,0 +1,121 @@
+#!/usr/bin/env bash
+#
+# linkedin-session adapter wrapper
+#
+# Called by /cheat-retro when state.data_collection=adapter and platform=linkedin.
+#
+# Usage:
+# bash run.sh <activity_id_or_url> <video_folder> [<script_path>]
+#
+# Example:
+# bash run.sh 7470493738918920193 ~/my-channel/videos/2026-05-04_7470493738918920193_post
+# bash run.sh https://www.linkedin.com/feed/update/urn:li:activity:7470493738918920193/ <folder>
+#
+# Output: writes report.md INTO the video_folder.
+# Exit codes:
+# 0 = success (report.md written)
+# 1 = login expired or required (no .auth-linkedin/)
+# 2 = adapter dependency missing (playwright not installed)
+# 3 = other failure (network, parse error, bad activity id, etc.)
+
+set -uo pipefail
+
+ACTIVITY_ID="${1:-}"
+VIDEO_FOLDER="${2:-}"
+SCRIPT_PATH="${3:-}"
+
+if [[ -z "$ACTIVITY_ID" || -z "$VIDEO_FOLDER" ]]; then
+ echo "Usage: bash run.sh <activity_id_or_url> <video_folder> [<script_path>]" >&2
+ exit 3
+fi
+
+# Resolve adapter source dir (where this script lives)
+ADAPTER_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
+
+# Find Python — prefer venv in user's project root if exists
+PYTHON=""
+PROJECT_ROOT="$( dirname "$( dirname "$( realpath "$VIDEO_FOLDER" )" )" )"
+if [[ -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 — install Python 3.10+ first" >&2
+ exit 2
+fi
+
+# Verify playwright is installed
+if ! "$PYTHON" -c "import playwright" 2>/dev/null; then
+ cat >&2 <<EOF
+❌ playwright not installed.
+
+Install in your project venv:
+ cd "$PROJECT_ROOT"
+ python3 -m venv .venv
+ source .venv/bin/activate
+ pip install -r "$ADAPTER_DIR/requirements.txt"
+ playwright install chromium
+
+Then re-run /cheat-retro.
+EOF
+ exit 2
+fi
+
+# Verify .auth-linkedin/ exists in project root (cookie persistence)
+if [[ ! -d "$PROJECT_ROOT/.auth-linkedin" ]]; then
+ cat >&2 <<EOF
+❌ Not logged in to LinkedIn.
+
+First-time login (one-shot):
+ cd "$PROJECT_ROOT"
+ source .venv/bin/activate
+ $PYTHON "$ADAPTER_DIR/review.py" login
+
+A Chromium window will pop up — log in to LinkedIn.
+Cookie (li_at) will be saved to .auth-linkedin/ for future runs.
+EOF
+ exit 1
+fi
+
+# Make sure video_folder exists
+mkdir -p "$VIDEO_FOLDER"
+
+# Resolve script path (optional)
+SCRIPT_ARG=""
+if [[ -n "$SCRIPT_PATH" && -f "$SCRIPT_PATH" ]]; then
+ SCRIPT_ARG="$SCRIPT_PATH"
+fi
+
+# Run from PROJECT_ROOT so .auth-linkedin/ is found; override videos dir to user's
+cd "$PROJECT_ROOT"
+export CHEAT_PROJECT_ROOT="$PROJECT_ROOT"
+export CHEAT_VIDEOS_DIR="$( dirname "$VIDEO_FOLDER" )" # = user's videos/
+
+echo "[linkedin-session] fetching activity=$ACTIVITY_ID into $VIDEO_FOLDER"
+if [[ -n "$SCRIPT_ARG" ]]; then
+ "$PYTHON" "$ADAPTER_DIR/review.py" video "$ACTIVITY_ID" "$SCRIPT_ARG"
+else
+ "$PYTHON" "$ADAPTER_DIR/review.py" video "$ACTIVITY_ID"
+fi
+
+# review.py writes to CHEAT_VIDEOS_DIR/<auto-named-folder>/report.md.
+# Move it into our canonical video_folder if names differ.
+LATEST_REPORT=$(find "$( dirname "$VIDEO_FOLDER" )" -name "report.md" -newer "$VIDEO_FOLDER" -type f 2>/dev/null | head -1)
+if [[ -n "$LATEST_REPORT" && "$( dirname "$LATEST_REPORT" )" != "$VIDEO_FOLDER" ]]; then
+ cp "$LATEST_REPORT" "$VIDEO_FOLDER/report.md"
+ AUTO_DIR=$( dirname "$LATEST_REPORT" )
+ if [[ -f "$AUTO_DIR/script.txt" ]]; then
+ cp "$AUTO_DIR/script.txt" "$VIDEO_FOLDER/script.txt"
+ fi
+ echo "[linkedin-session] moved auto-named output to $VIDEO_FOLDER/"
+fi
+
+if [[ ! -f "$VIDEO_FOLDER/report.md" ]]; then
+ echo "❌ report.md not produced — see review.py output above for details" >&2
+ exit 3
+fi
+
+echo "✅ report.md written to $VIDEO_FOLDER/report.md"
+exit 0
diff --git a/adapters/perf-data/linkedin-session/test_extract.py b/adapters/perf-data/linkedin-session/test_extract.py
new file mode 100644
index 0000000..40722ee
--- /dev/null
+++ b/adapters/perf-data/linkedin-session/test_extract.py
@@ -0,0 +1,136 @@
+"""extract.py 的单元测试。用合成样本(不提交真实指标)。
+
+跑:python test_extract.py
+"""
+from extract import _to_int, parse_post_meta, parse_post_summary
+
+# 合成样本:复刻真实 /analytics/post-summary/ 的 inner_text 版式(日文界面),数字是假的。
+POST_SAMPLE_JP = """Heqing Huangさんが投稿しました • 4日
+post body line one
+post body line two with a stray number 123 inside
+調査
+9,999
+インプレッション数
+800
+リーチしたメンバー
+プロフィールアクティビティ
+5
+この投稿からのプロフィール閲覧ユーザー
+2
+この投稿で獲得したフォロワー
+エンゲージメント
+30
+ソーシャルエンゲージメント
+リアクション
+20
+コメント
+6
+再投稿
+3
+保存数
+1
+LinkedInでの送信数
+0
+上位統計データ
+"""
+
+# 英文界面(LinkedIn 随机切换)。
+POST_SAMPLE_EN = """Heqing Huang posted this • 6d
+post body text with stray number 999
+Discovery
+50,000
+Impressions
+30,000
+Members reached
+Profile activity
+400
+Profile viewers from this post
+180
+Followers gained from this post
+Engagement
+300
+Social engagements
+Reactions
+100
+Comments
+25
+Reposts
+8
+Saves
+100
+Sends on LinkedIn
+67
+Top demographics
+"""
+
+
+def test_to_int():
+ assert _to_int("34,057") == 34057
+ assert _to_int("152") == 152
+ assert _to_int("1.2K") == 1200
+ assert _to_int("3M") == 3_000_000
+ assert _to_int("n/a") is None
+
+
+def test_parse_post_summary_jp():
+ m = parse_post_summary(POST_SAMPLE_JP)["metrics"]
+ assert m["impressions"] == 9999, m
+ assert m["reach"] == 800, m
+ assert m["profile_views_from_post"] == 5, m
+ assert m["followers_from_post"] == 2, m
+ assert m["social_engagement"] == 30, m
+ assert m["reactions"] == 20, m
+ assert m["comments"] == 6, m
+ assert m["reposts"] == 3, m
+ assert m["saves"] == 1, m
+ assert m["sends"] == 0, m
+
+
+def test_parse_post_summary_en():
+ m = parse_post_summary(POST_SAMPLE_EN)["metrics"]
+ assert m["impressions"] == 50000, m
+ assert m["reach"] == 30000, m
+ assert m["profile_views_from_post"] == 400, m
+ assert m["followers_from_post"] == 180, m
+ assert m["social_engagement"] == 300, m
+ assert m["reactions"] == 100, m
+ assert m["comments"] == 25, m
+ assert m["reposts"] == 8, m
+ assert m["saves"] == 100, m
+ assert m["sends"] == 67, m
+
+
+def test_parse_post_summary_missing_is_none():
+ assert parse_post_summary("no metrics here")["metrics"]["impressions"] is None
+
+
+def test_parse_post_meta_jp():
+ meta = parse_post_meta(POST_SAMPLE_JP)
+ assert meta["author"] == "Heqing Huang", meta
+ assert meta["age"] == "4日", meta
+ assert "post body line one" in meta["text"], meta
+ assert "post body line two" in meta["text"], meta
+ # 正文不应吃进指标小标题 / 指标
+ assert "調査" not in meta["text"], meta
+ assert "インプレッション数" not in meta["text"], meta
+
+
+def test_parse_post_meta_en():
+ meta = parse_post_meta(POST_SAMPLE_EN)
+ assert meta["author"] == "Heqing Huang", meta
+ assert meta["age"] == "6d", meta
+ assert "post body text" in meta["text"], meta
+ assert "Discovery" not in meta["text"], meta
+
+
+def test_parse_post_meta_missing():
+ meta = parse_post_meta("no byline at all\njust text")
+ assert meta == {"author": "", "age": "", "text": ""}, meta
+
+
+if __name__ == "__main__":
+ fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
+ for fn in fns:
+ fn()
+ print(f"✓ {fn.__name__}")
+ print(f"\n{len(fns)} passed")
diff --git a/skills/cheat-init/SKILL.md b/skills/cheat-init/SKILL.md
index a0715df..42a0e62 100644
--- a/skills/cheat-init/SKILL.md
+++ b/skills/cheat-init/SKILL.md
@@ -141,11 +141,12 @@ allowed-tools: Bash(*), Read, Write, Edit, Glob, WebFetch, Skill
> b) 小红书 — 装 xhs-explore adapter(Playwright + 扫码登录小红书创作者中心)
> c) YouTube — 装 youtube-data-api adapter(需 API key)
> d) B 站 — bilibili-stat adapter
-> e) 其他 / 多平台 — 走 manual paste 模式"
+> e) LinkedIn — 装 linkedin-session adapter(Playwright + 登录 LinkedIn,抓单帖分析)
+> f) 其他 / 多平台 — 走 manual paste 模式"
-如选 a/b/c/d → 询问 Q2.2;如选 e → 跳到 Q2.3 manual。
+如选 a/b/c/d/e → 询问 Q2.2;如选 f → 跳到 Q2.3 manual。
-**Q2.2: adapter 安装时机**(仅 Q2.1=a/b/c/d)
+**Q2.2: adapter 安装时机**(仅 Q2.1=a/b/c/d/e)
> "现在装 adapter 自动抓取,还是先手动告诉我?
> - 现在装 — 引导你装 Playwright + 扫码 → 抓回最近 N 条数据
@@ -266,17 +267,17 @@ c) 不找 → state 标 `benchmark_status: none`,用通用 v0 起步
0. **`.gitignore`(安全 — 必须第一步创建)**
```
"先创建 .gitignore,把账号凭证挡在版本控制外——这是第一件事。
- .auth/ 和 .auth-xhs/ 存的是抖音 / 小红书的登录态(等同账号密码),
+ .auth/ / .auth-xhs/ / .auth-linkedin/ 存的是抖音 / 小红书 / LinkedIn 的登录态(等同账号密码),
.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/`、`.cheat-secrets.json` 三行存在
+ `.auth/`、`.auth-xhs/`、`.auth-linkedin/`、`.cheat-secrets.json` 四行存在
- 即使用户项目当前**还不是 git 仓库**也照常创建——它会在用户 `git init` 的那一刻立即生效
- 创建后提醒一句:如果项目已经 `git init` 过且可能误加过 `.auth/`,让用户跑
- `git rm -r --cached .auth .auth-xhs .cheat-secrets.json` 把已暂存的凭证移出
+ `git rm -r --cached .auth .auth-xhs .auth-linkedin .cheat-secrets.json` 把已暂存的凭证移出
1. **`.cheat-state.json`**
```
@@ -303,7 +304,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\"];其他→[]>,
+ "enabled_perf_adapters": <Q2.1=a→[\"douyin-session\"];b→[\"xhs-explore\"];c→[\"youtube-data-api\"];d→[\"bilibili-stat\"];e→[\"linkedin-session\"];其他→[]>,
"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.md
index 61b4177..a46e9f4 100644
--- a/skills/cheat-retro/SKILL.md
+++ b/skills/cheat-retro/SKILL.md
@@ -95,6 +95,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>` |
| `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 |
@@ -113,6 +114,12 @@ allowed-tools: Bash(*), Read, Edit, Write, Glob, Grep, Skill
- 字段已校准(观看 `view_count` 等已写死);万一接口改版导致某项为 0,看 report.md 末尾 galaxy 原始 JSON,把新 key 加进 `crawler.py` 的 `_normalize_note`
- **评论可能抓不到**(xsec_token 缺失 / 评论关闭)→ report.md 标"未抓到评论" → 此时**降级要求用户 manual 粘 top 20 评论**(评论是真信号,不能省)
+**linkedin-session 的特殊处理**:
+- 帖子 URL(`https://www.linkedin.com/feed/update/urn:li:activity:<id>/`)或裸 activity_id → adapter 自动提取 activity_id
+- 调用前确认 cookie 存在(adapter 找 `.auth-linkedin/`);不存在则提示先跑 `python <adapter>/crawler.py login`
+- **只能抓你本人发的帖子**(LinkedIn 单帖分析仅作者可见);LinkedIn 界面 日/英 随机切换,`extract.py` 的 `POST_METRICS` 已存双语标签,万一某项为 None 看 `.cheat-cache/linkedin-session-debug/post_<id>.txt` 把新标签补进去
+- **评论只给数、不给正文**(分析页限制)→ report.md 标注 → **降级要求用户 manual 粘 top 评论**(评论是真信号,不能省)
+
**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.template
index 85ba1f5..3911572 100644
--- a/templates/gitignore.template
+++ b/templates/gitignore.template
@@ -8,9 +8,11 @@
# ── 凭证 / 登录态:绝不提交(提交即等于泄露账号)──
# .auth/ = 抖音 Playwright 登录态(含 sessionid)
# .auth-xhs/ = 小红书 Playwright 登录态(含 web_session 等)
+# .auth-linkedin/ = LinkedIn Playwright 登录态(含 li_at)
# .cheat-secrets.json = API key / cookie
.auth/
.auth-xhs/
+.auth-linkedin/
.cheat-secrets.json
# ── 本地缓存与生成物 ──