clipsmith-xhs
MANDATORY — load references/plan.md before any browser or extraction action begins.
⚠️ NEVER WRITE YOUR OWN SCRIPT
The download logic is fully implemented. Always invoke the existing script — do NOT write a new one.
cd <clipsmith-repo>/skills/clipsmith-xhs
npx tsx scripts/run.ts \
--post_url "<url>" \
--output_dir "<bundle_dir>" \
--flat true
<url> may be a full XHS URL, an xhslink.cn short link (e.g. http://xhslink.cn/o/<id>), or an xhslink.com short link — the script resolves short links via the authenticated browser session before navigating. <bundle_dir> should be the final bundle root named <platform>-<note_id> (e.g. inbox/xhs/xhs-6a716ccf000000003303036a/). With --flat true, the script writes directly into <bundle_dir> without creating a <date>-<title>-<note_id> subfolder, so the next normalization step can run in place.
The sections below (carousel logic, DOM extraction, anti-detection) are implementation documentation for the script itself, not instructions for you to re-implement. If the script doesn't exist or can't run, report the error — never substitute with hand-written Playwright code.
Clipsmith Bundle Normalization
The downloader produces a raw post folder with post.md, downloaded images
(plus optional video) at the root, and ocr.md for post images. It does not
generate a summary by default. Convert the raw folder into a final bundle with
the shared normalizer, then validate.
In-place flow (preferred when --flat true was used):
cd <clipsmith-repo>
uv run clipsmith normalize raw xhs "<bundle_dir>" "<bundle_dir>" \
--source-url "<original_url>" \
--canonical-url "<canonical_url>" \
--title "<title>" \
--author "<author>" \
--captured-at "<iso8601_time>" \
--overwrite \
--json
uv run clipsmith validate-bundle "<bundle_dir>" --json
Staged flow (when the downloader wrote to a separate staging dir):
uv run clipsmith normalize raw xhs "<staging_dir>" "<bundle_dir>" \
--source-url "<original_url>" \
--canonical-url "<canonical_url>" \
--title "<title>" \
--author "<author>" \
--captured-at "<iso8601_time>" \
--json
uv run clipsmith validate-bundle "<bundle_dir>" --json
The normalizer keeps post.md, generates summary.md, preserves ocr.md/ocr.txt as kind: "ocr-text" when OCR ran, moves image/video files (.webp, .jpg, .jpeg, .png, .gif, .mp4, .mov, .webm) into assets/, and writes capture.json with matching assets[] entries (kind: "image" or kind: "video"). When raw_dir and bundle_dir are the same path and --overwrite is set, the normalizer reads the source files into memory first so the in-place rmtree does not lose them. The normalizer does not move comment images or other raw assets — those are out of scope for the bundle.
Do not call uv run clipsmith capture finalize until capture.json exists and validation succeeds.
Quality Evaluation
Use the committed eval profile and fixture before changing prompt, OCR, or XHS
capture behavior:
cd <clipsmith-repo>/skills/clipsmith-xhs
node scripts/eval.mjs \
--fixture xhs-skill-long-term-asset \
--profile xhs-skill-long-term-asset
npx tsx scripts/ocr.ts \
--note_dir /tmp/clipsmith-xhs-ocr-fixture \
--images_dir evals/fixtures/xhs-skill-long-term-asset/images
node scripts/eval.mjs \
--fixture xhs-skill-long-term-asset \
--profile xhs-skill-long-term-asset \
--run_ocr
The fixture is a user-owned XHS note. Keep the fixture images, post.md, and
ocr.md in sync with evals/xhs-capture-evals.json, and use
prompts/evaluate-capture.md for agent AI eval when working in the source repo.
Packaged skill installs may omit eval fixtures and baselines. The live URL can
still be used for end-to-end browser validation when XHS is reachable, but local
fixture eval must not depend on network access.
Required Constraints
- Use browser automation only.
- Do not use Xiaohongshu private APIs.
- Reuse manual-login session via unified Chrome CDP startup:
open -na "Google Chrome" --args --remote-debugging-port=9223 --user-data-dir="$HOME/.chrome-labali-no-proxy".
- Optional cleanup: pass
--close_browser_on_success true only when the CDP
Chrome is dedicated to this automation run. The browser closes after a fully
successful capture; failures and partial captures leave it open for manual
inspection.
- Prefer semantic extraction from visible page state and loaded resources.
- Download only target post assets: images plus optional post video.
- Generate
post.md for extracted text metadata.
- Run local OCR for downloaded post images by default and save
ocr.md next to
post.md. OCR failure for one image must not fail the whole post download;
preserve image files and report OCR warnings.
- Export comments only when
include_comments=true, and write comments/comments.json + comments/comments.md.
- Download comment images into
comments/images/.
- Comment export is not guaranteed to be complete — if extraction yields zero comments on a post known to have them, retain all image/video downloads, set
comments_count=0, and report the partial result without throwing.
- Do not generate
manifest.json.
- If multiple video segments are downloaded, merge them into one file and delete segment files.
- Preserve all original query parameters (especially
xsec_token, xsec_source, share_id) for page navigation — Xiaohongshu uses these tokens to render authenticated content; stripping them causes incomplete page rendering (wrong image count, missing text).
- Normalize post URL to canonical format (
https://www.xiaohongshu.com/explore/<note_id>) for output only: folder naming, post.md source field, and logs. Do not strip params before navigating.
Anti-Detection Principles
XiaoHongShu applies behavioral analysis to detect automation. Violations of these principles have caused account rate-limiting in the past — do not remove or bypass them.
Core test — apply before every browser action:
"Would a real user do this, from this state, at this moment?"
If no → skip it or slow it down. Re-navigating an already-open post, batch-extracting DOM nodes, issuing fresh HTTP requests for images the browser just loaded, using fixed delays — all fail this test.
Navigation:
- If the tab is already on the target post URL, skip
page.goto() entirely — re-navigating an already-open post is an unnatural action and a clear bot signal.
- All fixed
waitForTimeout values must be randomized (e.g., base + Math.random() * range) — deterministic delays are a bot fingerprint.
- After navigating to a post, scroll down briefly to simulate reading the text, then scroll back up before interacting with images.
Image acquisition:
- Never issue new HTTP requests for images — the browser has already downloaded them.
- Register
page.on("response") BEFORE calling page.goto() — images load during navigation; a listener registered after goto() misses the first batch entirely.
- Primary image source: DOM-scoped extraction from
.note-slider, NOT whole-page response interception. XHS pages load 10–40× more feed/recommendation images than the post itself; intercepting all xhscdn responses produces the wrong count. Correct flow:
- After page settles, press
ArrowLeft repeatedly (up to 20×) until no new image appears — this resets the carousel to slide 1 regardless of prior state.
- Read the currently visible slide image URL from
.note-slider img (the active/largest src, not all preloaded imgs) and append it to an ordered list.
- Press
ArrowRight once, wait, then read the new current slide URL. Repeat until the URL is the same as the first URL (carousel wrapped) or no change after 2 consecutive presses.
- This ordered list is the authoritative image sequence — file names (
image_01, image_02, …) must match this order.
- Fetch each URL via
fetch(url, {cache: 'force-cache'}) in page.evaluate().
- Do NOT do a bulk upfront query of all
.note-slider img elements — XHS preloads all slides into the DOM simultaneously, so a single querySelectorAll returns them in DOM order (which is not carousel order), causing the naming to be scrambled.
- Response listener (
page.on("response")) may still run as a supplemental net, but DOM extraction is the authoritative source.
- If neither path yields images, report failure — do not fall back to
page.request.get().
- Deduplicate by image hash, not just by URL — XHS CDN URLs for the same image at different quality levels share the same hash prefix before
! (e.g. sns-webpic-qc.xhscdn.com/.../HASH!nd_dft_wlteh_webp_3 and ...HASH!nd_dft_wlteh_webp_1 are the same image). Extract the hash segment and keep only the URL whose downloaded file is largest. Alternatively, after all downloads complete, remove any file whose size is less than 40% of the median file size — these are preloaded thumbnails, not content images.
- Carousel navigation:
page.keyboard.press('ArrowRight') first (most reliable); DOM selectors (.note-slider .right-arrow, [class*="rightArrow"], .swiper-button-next) as fallback.
Video:
- Before downloading, simulate user engagement through CDP in the existing XHS
tab: start or continue playback and wait 3–5 seconds for buffering. Never call
bringToFront() or otherwise steal focus from the user.
- Extract the real video URL from resources the player loaded after playback.
- Preserve and log quality evidence supplied by XHS (dimensions, bitrate, size,
frame rate, and codec), omitting signed query parameters from logs. Rank by
that evidence; use the player-loaded candidate only as the final tie-breaker.
- If no comparable quality metadata exists, describe the result as the
player-loaded rendition. Do not claim it is the highest-quality or native-4K
source merely because the output canvas is 3840×2160.
- Download the selected video URL with the authenticated browser cookies and
current post
referer, streaming to *.part before the final rename.
- Run
ffprobe on the completed *.part; rename only when it contains a video
stream and positive duration. Report measured resolution, frame rate, codecs,
duration, and bitrate.
- If multiple direct MP4 candidates are visible, keep the best evidenced
candidate rather than downloading every quality variant. Use player-loaded
status only as the final tie-breaker. Only HLS/segment downloads should
produce multiple files for later merge.
General:
- Always operate within the user's authenticated Chrome session (CDP reuse) — never launch a headless or separate browser.
- Never read
window.__INITIAL_STATE__ or manipulate the DOM in ways that go beyond what a user's own browser JS would do.
NEVER
- Never write a custom Playwright/Node.js script to perform the download — the existing
scripts/run.ts already handles all carousel navigation, image extraction, deduplication, and metadata. Writing a new script bypasses all tested logic and produces incomplete results (e.g. only 1 image instead of all slides).
- Never leave multiple video segment files in the output folder after a successful run — merge segments and delete the originals.
- Never report success if
post.md was not generated.
- Never report success based on action completion alone — verify output folder structure and required files exist.
- Never strip xsec_token or share params before navigating — XiaoHongShu uses these tokens server-side to render authenticated content; a URL without them silently produces wrong image counts and missing text, with no error.
- Never launch a new Chrome instance if CDP is already responding on port 9223 — launching a second instance creates a separate session, loses the authenticated profile, and forces re-login.
- Never take over a non-XiaoHongShu browser tab — if an existing XHS tab is found, reuse it by navigating it to the post URL; if no XHS tab exists, open a new tab. Never hijack tabs belonging to other pages (e.g., Gmail, dev tools). The correct behavior is always: XHS tab → navigate it to post URL; no XHS tab → open new tab.
- Never issue new outbound HTTP requests for post images — use response interception or browser cache reads only; falling back to
page.request.get() for images is a bot signal.
- Never use fixed (non-randomized) delays — deterministic timing is a bot fingerprint; all waits must include a random component.
- Never retry automatically after a hard risk signal (CAPTCHA, rate-limit message, account anomaly) — stop immediately, preserve all downloaded files, log the signal type and last successfully processed item, and surface the error to the user for manual intervention.
- Never treat a login modal as a hard stop — XHS shows a "登录继续查看笔记" dismissible popup on cold tab opens; content is fully accessible underneath. The script calls
dismissLoginModalIfPresent() before risk-signal checks. Do NOT confuse this modal with an actual login wall. "验证码" in page text is only a CAPTCHA signal when the login modal indicators ("手机号登录", "扫码登录") are absent.
Success Criteria
A run is successful only when all conditions hold:
- A post output folder is created under the specified local directory.
- Folder naming format:
- With
--flat true: <output_dir> is used as-is — caller-controlled. The recommended convention is <platform>-<note_id> (e.g. xhs-6a716ccf000000003303036a).
- Without
--flat: <output_dir>/<download_date>-<sanitized_title>-<note_id> (title omitted when empty); <download_date> is today's date (YYYYMMDD), not the post's publish time.
post.md is generated in the folder.
- Post image files are saved in the folder (root of the output dir during the download stage; the normalizer moves them under
assets/ during bundle finalization).
ocr.md is generated in the folder for downloaded post images.
- Post video files are saved when the post contains video.
- If multiple video files are generated, they are merged into one and segment files are removed.
- When
include_comments=true, comments are exported under comments/ with comments.json and comments.md.
- When comment images exist, they are downloaded under
comments/images/.
- URL output and logs use canonical
/explore/<note_id> form without token query.
- After normalization,
assets/ contains all image/video files and capture.json.assets[] declares each one with kind: "image" or kind: "video". validate-bundle reports 0 issues.
Comment export failure behavior:
- If extraction yields zero comments on a post known to have them: retain all downloaded files, return
comments_count=0, do not throw. Partial coverage of hierarchy/reply linking is acceptable and expected.
Operational Mode
- Default mode: guided browser flow + semantic extraction + authenticated media download + local OCR for post images.
- Optional cleanup mode:
--close_browser_on_success true closes the connected
CDP Chrome after a successful capture with failed_count=0; keep the default
false when the same browser is used for manual debugging or other tabs.
- Optional mode: add semantic comment extraction, comment image download, and write
comments/comments.json + comments/comments.md when include_comments=true.
- Startup guidance:
- check if CDP is responding:
curl -s http://localhost:9223/json/version
- if CDP is NOT responding → auto-launch Chrome immediately (no user prompt needed):
open -na "Google Chrome" --args --remote-debugging-port=9223 --user-data-dir="$HOME/.chrome-labali-no-proxy"
then wait 3 seconds and verify CDP responds before proceeding.
- if Chrome with remote debugging is already running on the CDP port, reuse it — do not launch a new instance,
- connect via CDP port,
- if an existing Xiaohongshu tab is found, reuse it — do not open a new tab or navigate away from any other active tab,
- if no Xiaohongshu tab exists, open a new tab,
- check whether login is required,
- if required, guide user to complete manual login in the same window,
- if already logged in, skip login wait.
- Input guidance:
- after startup/login check, if
post_url is missing, prompt user to input post URL interactively,
- if
output_dir is missing, prompt user to input target folder (with default). When the caller has a pre-existing bundle layout (e.g. KB inbox at inbox/<platform>/<platform>-<note_id>/), pass --output_dir <bundle_dir> --flat true so the script writes into the bundle root directly and the normalizer can finalize in place.
- If login is required:
- keep browser open,
- ask user to complete login manually,
- continue in the same session after confirmation.
- On partial download failures:
- keep successfully downloaded files and any non-empty
*.part,
- never delete the raw directory,
- return result with explicit failure count.
Resources
| When |
Must load |
Do NOT load |
| Always — at skill invocation start |
references/plan.md |
references/architecture.md |
| Extraction returns wrong count or fails |
references/architecture.md |
— |
| Video merge or comment export unclear |
references/architecture.md |
— |
See Resources table above for conditional loads.
1---2name: clipsmith-xhs3description: >-4 Download XiaoHongShu (XHS / xiaohongshu) post assets — images, video, text5 metadata — to a local folder using browser automation with manual-login6 session reuse. Use when downloading a XHS post, saving post images, exporting7 post content, or archiving a note. Trigger phrases: "download xhs",8 "xiaohongshu post", "xhs images", "save post", "xhs note",9 "xiaohongshu download".10license: MIT11allowed-tools: "Bash(npx:*), Bash(node:*), Bash(pnpm:*)"12metadata:13 source: https://skillmd.com/skills/octopusgarage/clipsmith-xhs14 pattern: pipeline15 compatibility: "macOS / Linux; requires Chrome with remote-debugging enabled (port 9223), profile ~/.chrome-labali-no-proxy, and authenticated XiaoHongShu session; Node.js ≥ 20 + tsx"16---1718# clipsmith-xhs1920> **MANDATORY — load `references/plan.md` before any browser or extraction action begins.**2122## ⚠️ NEVER WRITE YOUR OWN SCRIPT2324**The download logic is fully implemented. Always invoke the existing script — do NOT write a new one.**2526```bash27cd <clipsmith-repo>/skills/clipsmith-xhs28npx tsx scripts/run.ts \29 --post_url "<url>" \30 --output_dir "<bundle_dir>" \31 --flat true32```3334`<url>` may be a full XHS URL, an `xhslink.cn` short link (e.g. `http://xhslink.cn/o/<id>`), or an `xhslink.com` short link — the script resolves short links via the authenticated browser session before navigating. `<bundle_dir>` should be the final bundle root named `<platform>-<note_id>` (e.g. `inbox/xhs/xhs-6a716ccf000000003303036a/`). With `--flat true`, the script writes directly into `<bundle_dir>` without creating a `<date>-<title>-<note_id>` subfolder, so the next normalization step can run in place.3536The sections below (carousel logic, DOM extraction, anti-detection) are **implementation documentation for the script itself**, not instructions for you to re-implement. If the script doesn't exist or can't run, report the error — never substitute with hand-written Playwright code.3738## Clipsmith Bundle Normalization3940The downloader produces a raw post folder with `post.md`, downloaded images41(plus optional video) at the root, and `ocr.md` for post images. It does not42generate a summary by default. Convert the raw folder into a final bundle with43the shared normalizer, then validate.4445**In-place flow (preferred when `--flat true` was used):**4647```bash48cd <clipsmith-repo>49uv run clipsmith normalize raw xhs "<bundle_dir>" "<bundle_dir>" \50 --source-url "<original_url>" \51 --canonical-url "<canonical_url>" \52 --title "<title>" \53 --author "<author>" \54 --captured-at "<iso8601_time>" \55 --overwrite \56 --json57uv run clipsmith validate-bundle "<bundle_dir>" --json58```5960**Staged flow (when the downloader wrote to a separate staging dir):**6162```bash63uv run clipsmith normalize raw xhs "<staging_dir>" "<bundle_dir>" \64 --source-url "<original_url>" \65 --canonical-url "<canonical_url>" \66 --title "<title>" \67 --author "<author>" \68 --captured-at "<iso8601_time>" \69 --json70uv run clipsmith validate-bundle "<bundle_dir>" --json71```7273The normalizer keeps `post.md`, generates `summary.md`, preserves `ocr.md`/`ocr.txt` as `kind: "ocr-text"` when OCR ran, moves image/video files (`.webp`, `.jpg`, `.jpeg`, `.png`, `.gif`, `.mp4`, `.mov`, `.webm`) into `assets/`, and writes `capture.json` with matching `assets[]` entries (`kind: "image"` or `kind: "video"`). When `raw_dir` and `bundle_dir` are the same path and `--overwrite` is set, the normalizer reads the source files into memory first so the in-place rmtree does not lose them. The normalizer does not move comment images or other raw assets — those are out of scope for the bundle.7475Do not call `uv run clipsmith capture finalize` until `capture.json` exists and validation succeeds.7677## Quality Evaluation7879Use the committed eval profile and fixture before changing prompt, OCR, or XHS80capture behavior:8182```bash83cd <clipsmith-repo>/skills/clipsmith-xhs84node scripts/eval.mjs \85 --fixture xhs-skill-long-term-asset \86 --profile xhs-skill-long-term-asset87npx tsx scripts/ocr.ts \88 --note_dir /tmp/clipsmith-xhs-ocr-fixture \89 --images_dir evals/fixtures/xhs-skill-long-term-asset/images90node scripts/eval.mjs \91 --fixture xhs-skill-long-term-asset \92 --profile xhs-skill-long-term-asset \93 --run_ocr94```9596The fixture is a user-owned XHS note. Keep the fixture images, `post.md`, and97`ocr.md` in sync with `evals/xhs-capture-evals.json`, and use98`prompts/evaluate-capture.md` for agent AI eval when working in the source repo.99Packaged skill installs may omit eval fixtures and baselines. The live URL can100still be used for end-to-end browser validation when XHS is reachable, but local101fixture eval must not depend on network access.102103## Required Constraints104105- Use browser automation only.106- Do not use Xiaohongshu private APIs.107- Reuse manual-login session via unified Chrome CDP startup:108 `open -na "Google Chrome" --args --remote-debugging-port=9223 --user-data-dir="$HOME/.chrome-labali-no-proxy"`.109- Optional cleanup: pass `--close_browser_on_success true` only when the CDP110 Chrome is dedicated to this automation run. The browser closes after a fully111 successful capture; failures and partial captures leave it open for manual112 inspection.113- Prefer semantic extraction from visible page state and loaded resources.114- Download only target post assets: images plus optional post video.115- Generate `post.md` for extracted text metadata.116- Run local OCR for downloaded post images by default and save `ocr.md` next to117 `post.md`. OCR failure for one image must not fail the whole post download;118 preserve image files and report OCR warnings.119- Export comments only when `include_comments=true`, and write `comments/comments.json` + `comments/comments.md`.120- Download comment images into `comments/images/`.121- Comment export is not guaranteed to be complete — if extraction yields zero comments on a post known to have them, retain all image/video downloads, set `comments_count=0`, and report the partial result without throwing.122- Do not generate `manifest.json`.123- If multiple video segments are downloaded, merge them into one file and delete segment files.124- Preserve all original query parameters (especially `xsec_token`, `xsec_source`, `share_id`) for page navigation — Xiaohongshu uses these tokens to render authenticated content; stripping them causes incomplete page rendering (wrong image count, missing text).125- Normalize post URL to canonical format (`https://www.xiaohongshu.com/explore/<note_id>`) for output only: folder naming, `post.md` source field, and logs. Do not strip params before navigating.126127## Anti-Detection Principles128129XiaoHongShu applies behavioral analysis to detect automation. Violations of these principles have caused account rate-limiting in the past — do not remove or bypass them.130131**Core test — apply before every browser action:**132> "Would a real user do this, from this state, at this moment?"133> If no → skip it or slow it down. Re-navigating an already-open post, batch-extracting DOM nodes, issuing fresh HTTP requests for images the browser just loaded, using fixed delays — all fail this test.134135**Navigation:**136- If the tab is already on the target post URL, skip `page.goto()` entirely — re-navigating an already-open post is an unnatural action and a clear bot signal.137- All fixed `waitForTimeout` values must be randomized (e.g., `base + Math.random() * range`) — deterministic delays are a bot fingerprint.138- After navigating to a post, scroll down briefly to simulate reading the text, then scroll back up before interacting with images.139140**Image acquisition:**141- Never issue new HTTP requests for images — the browser has already downloaded them.142- **Register `page.on("response")` BEFORE calling `page.goto()`** — images load during navigation; a listener registered after `goto()` misses the first batch entirely.143- **Primary image source: DOM-scoped extraction from `.note-slider`**, NOT whole-page response interception. XHS pages load 10–40× more feed/recommendation images than the post itself; intercepting all xhscdn responses produces the wrong count. Correct flow:144 1. After page settles, press `ArrowLeft` repeatedly (up to 20×) until no new image appears — this resets the carousel to slide 1 regardless of prior state.145 2. Read the **currently visible** slide image URL from `.note-slider img` (the active/largest `src`, not all preloaded imgs) and append it to an ordered list.146 3. Press `ArrowRight` once, wait, then read the new current slide URL. Repeat until the URL is the same as the first URL (carousel wrapped) or no change after 2 consecutive presses.147 4. This ordered list is the authoritative image sequence — file names (`image_01`, `image_02`, …) must match this order.148 5. Fetch each URL via `fetch(url, {cache: 'force-cache'})` in `page.evaluate()`.149 - **Do NOT do a bulk upfront query of all `.note-slider img` elements** — XHS preloads all slides into the DOM simultaneously, so a single querySelectorAll returns them in DOM order (which is not carousel order), causing the naming to be scrambled.150- Response listener (`page.on("response")`) may still run as a supplemental net, but DOM extraction is the authoritative source.151- If neither path yields images, report failure — do not fall back to `page.request.get()`.152- **Deduplicate by image hash, not just by URL** — XHS CDN URLs for the same image at different quality levels share the same hash prefix before `!` (e.g. `sns-webpic-qc.xhscdn.com/.../HASH!nd_dft_wlteh_webp_3` and `...HASH!nd_dft_wlteh_webp_1` are the same image). Extract the hash segment and keep only the URL whose downloaded file is largest. Alternatively, after all downloads complete, remove any file whose size is less than 40% of the median file size — these are preloaded thumbnails, not content images.153- Carousel navigation: `page.keyboard.press('ArrowRight')` first (most reliable); DOM selectors (`.note-slider .right-arrow`, `[class*="rightArrow"]`, `.swiper-button-next`) as fallback.154155**Video:**156- Before downloading, simulate user engagement through CDP in the existing XHS157 tab: start or continue playback and wait 3–5 seconds for buffering. Never call158 `bringToFront()` or otherwise steal focus from the user.159- Extract the real video URL from resources the player loaded after playback.160- Preserve and log quality evidence supplied by XHS (dimensions, bitrate, size,161 frame rate, and codec), omitting signed query parameters from logs. Rank by162 that evidence; use the player-loaded candidate only as the final tie-breaker.163- If no comparable quality metadata exists, describe the result as the164 player-loaded rendition. Do not claim it is the highest-quality or native-4K165 source merely because the output canvas is 3840×2160.166- Download the selected video URL with the authenticated browser cookies and167 current post `referer`, streaming to `*.part` before the final rename.168- Run `ffprobe` on the completed `*.part`; rename only when it contains a video169 stream and positive duration. Report measured resolution, frame rate, codecs,170 duration, and bitrate.171- If multiple direct MP4 candidates are visible, keep the best evidenced172 candidate rather than downloading every quality variant. Use player-loaded173 status only as the final tie-breaker. Only HLS/segment downloads should174 produce multiple files for later merge.175176**General:**177- Always operate within the user's authenticated Chrome session (CDP reuse) — never launch a headless or separate browser.178- Never read `window.__INITIAL_STATE__` or manipulate the DOM in ways that go beyond what a user's own browser JS would do.179180## NEVER181182- **Never write a custom Playwright/Node.js script to perform the download** — the existing `scripts/run.ts` already handles all carousel navigation, image extraction, deduplication, and metadata. Writing a new script bypasses all tested logic and produces incomplete results (e.g. only 1 image instead of all slides).183- Never leave multiple video segment files in the output folder after a successful run — merge segments and delete the originals.184- Never report success if `post.md` was not generated.185- Never report success based on action completion alone — verify output folder structure and required files exist.186- **Never strip xsec_token or share params before navigating** — XiaoHongShu uses these tokens server-side to render authenticated content; a URL without them silently produces wrong image counts and missing text, with no error.187- **Never launch a new Chrome instance if CDP is already responding on port 9223** — launching a second instance creates a separate session, loses the authenticated profile, and forces re-login.188- **Never take over a non-XiaoHongShu browser tab** — if an existing XHS tab is found, reuse it by navigating it to the post URL; if no XHS tab exists, open a new tab. Never hijack tabs belonging to other pages (e.g., Gmail, dev tools). The correct behavior is always: XHS tab → navigate it to post URL; no XHS tab → open new tab.189- **Never issue new outbound HTTP requests for post images** — use response interception or browser cache reads only; falling back to `page.request.get()` for images is a bot signal.190- **Never use fixed (non-randomized) delays** — deterministic timing is a bot fingerprint; all waits must include a random component.191- **Never retry automatically after a hard risk signal** (CAPTCHA, rate-limit message, account anomaly) — stop immediately, preserve all downloaded files, log the signal type and last successfully processed item, and surface the error to the user for manual intervention.192- **Never treat a login modal as a hard stop** — XHS shows a "登录继续查看笔记" dismissible popup on cold tab opens; content is fully accessible underneath. The script calls `dismissLoginModalIfPresent()` before risk-signal checks. Do NOT confuse this modal with an actual login wall. "验证码" in page text is only a CAPTCHA signal when the login modal indicators ("手机号登录", "扫码登录") are absent.193194## Success Criteria195196A run is successful only when all conditions hold:1971981. A post output folder is created under the specified local directory.1992. Folder naming format:200 - With `--flat true`: `<output_dir>` is used as-is — caller-controlled. The recommended convention is `<platform>-<note_id>` (e.g. `xhs-6a716ccf000000003303036a`).201 - Without `--flat`: `<output_dir>/<download_date>-<sanitized_title>-<note_id>` (title omitted when empty); `<download_date>` is today's date (YYYYMMDD), not the post's publish time.2023. `post.md` is generated in the folder.2034. Post image files are saved in the folder (root of the output dir during the download stage; the normalizer moves them under `assets/` during bundle finalization).2045. `ocr.md` is generated in the folder for downloaded post images.2056. Post video files are saved when the post contains video.2067. If multiple video files are generated, they are merged into one and segment files are removed.2078. When `include_comments=true`, comments are exported under `comments/` with `comments.json` and `comments.md`.2089. When comment images exist, they are downloaded under `comments/images/`.20910. URL output and logs use canonical `/explore/<note_id>` form without token query.21011. After normalization, `assets/` contains all image/video files and `capture.json.assets[]` declares each one with `kind: "image"` or `kind: "video"`. `validate-bundle` reports 0 issues.211212Comment export failure behavior:213- If extraction yields zero comments on a post known to have them: retain all downloaded files, return `comments_count=0`, do not throw. Partial coverage of hierarchy/reply linking is acceptable and expected.214215## Operational Mode216217- Default mode: guided browser flow + semantic extraction + authenticated media download + local OCR for post images.218- Optional cleanup mode: `--close_browser_on_success true` closes the connected219 CDP Chrome after a successful capture with `failed_count=0`; keep the default220 `false` when the same browser is used for manual debugging or other tabs.221- Optional mode: add semantic comment extraction, comment image download, and write `comments/comments.json` + `comments/comments.md` when `include_comments=true`.222- Startup guidance:223 - check if CDP is responding: `curl -s http://localhost:9223/json/version`224 - if CDP is NOT responding → **auto-launch Chrome immediately** (no user prompt needed):225 `open -na "Google Chrome" --args --remote-debugging-port=9223 --user-data-dir="$HOME/.chrome-labali-no-proxy"`226 then wait 3 seconds and verify CDP responds before proceeding.227 - if Chrome with remote debugging is already running on the CDP port, reuse it — do not launch a new instance,228 - connect via CDP port,229 - if an existing Xiaohongshu tab is found, reuse it — do not open a new tab or navigate away from any other active tab,230 - if no Xiaohongshu tab exists, open a new tab,231 - check whether login is required,232 - if required, guide user to complete manual login in the same window,233 - if already logged in, skip login wait.234- Input guidance:235 - after startup/login check, if `post_url` is missing, prompt user to input post URL interactively,236 - if `output_dir` is missing, prompt user to input target folder (with default). When the caller has a pre-existing bundle layout (e.g. KB inbox at `inbox/<platform>/<platform>-<note_id>/`), pass `--output_dir <bundle_dir> --flat true` so the script writes into the bundle root directly and the normalizer can finalize in place.237- If login is required:238 - keep browser open,239 - ask user to complete login manually,240 - continue in the same session after confirmation.241- On partial download failures:242 - keep successfully downloaded files and any non-empty `*.part`,243 - never delete the raw directory,244 - return result with explicit failure count.245246## Resources247248| When | Must load | Do NOT load |249|------|-----------|-------------|250| Always — at skill invocation start | `references/plan.md` | `references/architecture.md` |251| Extraction returns wrong count or fails | `references/architecture.md` | — |252| Video merge or comment export unclear | `references/architecture.md` | — |253254See Resources table above for conditional loads.