Skip to content

feat(kb): site adapters — WeChat, Bilibili, YouTube (K-F)#284

Merged
oratis merged 8 commits into
mainfrom
feat/kb-adapters
Jul 24, 2026
Merged

feat(kb): site adapters — WeChat, Bilibili, YouTube (K-F)#284
oratis merged 8 commits into
mainfrom
feat/kb-adapters

Conversation

@oratis

@oratis oratis commented Jul 23, 2026

Copy link
Copy Markdown
Owner

Part of the knowledge-base v2.0 stack (plan: #278, handoff: #281). Stacked on #283 (K-E) — merge order: #278 → … → #283 → this.

差距

通用 readability 路径够不到的三类高频来源:公众号(验证页 + 懒加载图)、B 站(正文即视频,元数据在 API)、YouTube(字幕在 InnerTube,且经常拿不到)。

做了什么

src/kb/ingest/adapters/,三个 IngestAdapter 插进 K-E 预留的接缝:

  • wechat#js_content 取正文、#js_name 取公众号名、var ct 兜底发布时间;图片 data-src 已由转换器处理。命中验证页明确报错并给出路(手机打开分享链接 → 复制正文 → kb_add 粘贴),绝不静默存空页。
  • bilibili — 元数据走公开 x/web-interface/viewb23.tv 先经守护 fetch 解短链。字幕需 SESSDATA(用户可自愿填在 kb/feeds.jsonsessdata 字段,K-H 的 store 会保留该字段),没有就降级并在原因里写明开启方式。
  • youtube — oEmbed 作为可靠性地板 + 一次 InnerTube player POST 拿简介/字幕轨;captionTracks → &fmt=json3,人工轨优先于 ASR;PO Token / 200 空体 / 云 IP 限流全部走降级。

字幕分层(照交接文档写死):内建 API → yt-dlp → 仅元数据+简介。 yt-dlp 只用 --dump-single-json 发现字幕 URL(没装就跳过),实际下载仍走守护 fetch。字幕拿不到不是失败:frontmatter 记 transcript: unavailable (<原因>),工具返回值提示可用 kb_add 自行补贴文稿。

配套改动

  • fetchFollowingSafeRedirects 增加可选 SafeFetchInit(method/headers/body)——适配器的 API POST 和 cookie 都走同一条 SSRF 守护路径,不另起 fetch。
  • ingest 共享类型抽到 types.ts,打破 adapters ↔ index 的循环导入。
  • 最小正文长度门槛只作用于通用路径:合法降级的视频条目(仅元数据)可以很短,必须成功。
  • 测试接缝:IngestContext.ytDlpDumpJson 可注入,测试永不 spawn 进程、永不打网络。

测了什么

19 例全离线固件:三个 adapter 的 match 边界、公众号验证页报错、B 站无/有 SESSDATA 两条路、b23 短链解析、view API 错误、YouTube 人工轨优先、InnerTube 空体 → yt-dlp → 纯元数据的完整降级链、字幕两种载荷解析、ingestUrl 端到端路由。

npm run typecheck 干净;npm test 1249 pass / 0 fail。

🤖 Generated with Claude Code

oratis and others added 7 commits July 23, 2026 14:12
Design of record for three KB capabilities on top of v1.0 (#235-#242):

- K1 paste any link (web / 公众号 / B站 / YouTube) -> Markdown source
- K2 a watchlist -> daily fetched, classified, summarized brief
- K3 [[slug]] parsed into a real link graph; index.md becomes a ranked
  map-of-content; memory stores [[kb:slug]] links instead of content

Review of the shipped v1.0 code found five gaps this plan closes, one of
them a confirmed bug: both TF-IDF tokenizers (kb/search.ts:45 and
memory/vector.ts:212) split on whitespace, so a whole CJK run collapses
into a single token and Chinese content only matches an exact
whole-string query. Also: normalizeSlug strips non-ASCII so every Chinese
title falls back to entry-<timestamp>; web_fetch is lossy plain text with
no metadata and no store; [[slug]] is documented in SCHEMA.md but nothing
parses it; and there is no KB scheduler at all.

Includes the pro/con debate for each decision (self-built extractor vs
deps vs remote reader, immutable sources vs re-ingest, autonomous ingest
as a prompt-injection path, consent, ASCII vs CJK slugs, brief storage,
and RSSHub for feeds without one) and a nine-PR ship order.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Three foundation fixes the rest of the KB v2 work stands on
(docs/PLAN_KNOWLEDGE_BASE_v2.0.md K-B). All three are things that would
have corrupted or lost data once link ingest starts pouring Chinese
content in, so they land before the firehose.

1. CJK search was broken. Both TF-IDF tokenizers (kb/search.ts,
   memory/vector.ts) carried the same three lines: lowercase, strip
   non-word chars, split on whitespace. Chinese has no whitespace, so a
   whole clause survived as ONE token:

     doc   "这篇公众号文章讲的是知识库的设计" -> one token
     query "知识库"                          -> one token
     intersection = empty  ->  zero hits

   i.e. CJK content was only findable by an exact whole-clause query.
   Replaced by a shared src/tokenize.ts that emits character bigrams for
   CJK runs (plus the run itself, so an exact phrase still ranks
   highest), segments at latin/CJK boundaries so "gpt模型" indexes as
   "gpt" + CJK bigrams, and now keeps kana and CJK Ext-A, which the old
   character class dropped entirely. Latin tokenization is unchanged.

2. Chinese titles produced throwaway slugs. normalizeSlug strips every
   non-[a-z0-9] char, so a CJK title normalized to "" and addSource fell
   back to entry-<Date.now()> — opaque, unstable, un-dedupable. New
   kb/slug.ts mints <date>-<sha256/8> for titles with no usable latin,
   keeping slugs ASCII on purpose (macOS NFD vs git NFC filenames, URLs,
   git paths) with the real title in frontmatter. canonicalUrl() drops
   utm_*/known tracking params so the same article shared twice
   canonicalizes — and hashes — identically.

3. Entries can now carry arbitrary frontmatter via KbEntry.extra,
   round-tripped on read/write. This is where ingest provenance goes
   (url/site/author/published/hash/via) without the store knowing about
   any of it, and it means keys a future version adds survive a
   round-trip through an older one. Values are whitespace-collapsed on
   write so a newline can't forge frontmatter lines on the next read.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…d MOC

v1.0 told Lisa to cross-link wiki pages with [[slug]] (SCHEMA.md) and
recorded each page's sources: in frontmatter — but nothing ever read
either one. The KB was a pile of files with decorative links.

src/kb/links.ts builds the graph from three edge sources ([[slug]],
[[slug|alias]], [[kb:slug]] in bodies; a wiki page's sources:
frontmatter) and derives what you can't get from search: backlinks,
hubs, orphans, and links pointing at pages that don't exist yet.

index.md is now a ranked map of content rather than a flat listing.
It is injected into EVERY system prompt and hard-capped there
(prompt.ts:165), so with a flat list the truncation lands at an
arbitrary point once the KB grows and whatever fell below the line stops
existing as far as Lisa is concerned. Ordering wiki pages by
(1 + backlinks) x recency means the cut always eats the least-connected
tail. Orphans and broken links are listed as the tending to-do list, and
every truncation says how much it dropped instead of trailing off.

Sources are now listed by TITLE ONLY. Layer 1 is raw captured material —
after link ingest lands that means whole web pages — and index.md is
always-on prompt text, so an excerpt there is a direct "any page on the
internet -> Lisa's system prompt" path. This is a stronger form of the
containment the plan assigned to K-I (it covers every source, not just
origin: web), and it costs nothing: a title is all a map needs, and the
body is one kb_read away. Wiki gists stay — Lisa wrote those herself.

Also: kb/index.json (the machine-readable graph, for the web UI and
tools), a kb_links tool (links to / linked from / shares tags with), and
kb_read now takes a bare slug or a [[wikilink]] with the layer optional,
and appends the pages that link to what you just read.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
K-A/K-B/K-C are open as #278/#279/#280. This is the pickup document for
whoever continues: the branch stack and how not to break it, the APIs the
first three PRs landed, a file-by-file spec for each remaining PR, the
repo conventions that are easy to trip over (LISA_HOME must be set before
import, the tool-subset triple, the giant template literals in
lisa-client.ts), and the eight decisions that are already settled so they
don't get re-litigated.

Two things it corrects against the plan: the index-side injection
containment assigned to K-I already shipped in K-C, and in a stronger
form (every source is title-only in index.md, not just origin: web), so
K-I is down to the watchlist restriction and the kb_read fence.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…rvative autolink (K-D)

Closes the "memory stores links, not content" loop from the v2.0 plan (user
need ③). Four pieces:

- prompt.ts inlines page titles for [[kb:slug]] pointers found in MEMORY.md /
  USER.md at assembly time ([[kb:oauth]] → [[kb:oauth]](OAuth 与 PKCE)), so a
  pointer is meaningful without a kb_read. Titles come from the already-
  generated kb/index.json behind a stat-fingerprint cache — the prompt builds
  every turn, so no full-KB read on this path. Unresolvable links are kept
  verbatim: a dangling pointer is a "write this page" signal, not noise.
- memory tool description now steers knowledge OUT of memory (4KB cap) and
  into the KB with a [[kb:slug]] pointer.
- The idle tending prompt closes the loop from the other side: after
  distilling a wiki page, back-link it from any related memory entry.
- kb/autolink.ts: conservative title → [[link]] pass applied on kb_write.
  Whole-word title matches only, first occurrence, longest-first, never in
  code / existing links, short titles skipped — a wrong edge pollutes the
  (backlinks × recency) hub ranking the always-on index sorts by, so misses
  are preferred over false links. Emits [[slug|Title]] when the slug differs
  so CJK prose keeps reading as prose.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…K-E)

kb_ingest(url) turns a link into a searchable, citeable source entry (v2.0
user need ②). New src/kb/ingest/, all zero-dependency (D1: what the user
reads never leaves the machine):

- html-to-md.ts: lenient HTML tree parser + markdown serializer (headings,
  nested lists, fenced/inline code, blockquotes, tables, links, lazy-loaded
  images, emphasis). Prose is markdown-escaped BEFORE syntax is added, so page
  text can't forge emphasis/links/wikilinks into the KB; code bodies can't
  terminate their own fence; javascript: hrefs are dropped.
- readability.ts: small Readability — score candidates by text mass, <p>
  count, link density, class/id hints; fall back to <body> when unsure
  (noise is recoverable by distillation, clipped content is not).
- provenance.ts: og:* / JSON-LD Article / <title> / rel=canonical / lang →
  frontmatter (url · site · author · published · lang · hash · via).
- dedupe.ts: kb/.ingested.json (hash → slug), rebuilt from the sources'
  own hash: frontmatter when missing/corrupt. Same URL returns the existing
  entry (D2, immutable sources); force re-ingests + records supersedes:.
- index.ts: ingestUrl orchestration with an adapter seam for K-F. ALL
  fetching goes through web_fetch's fetchFollowingSafeRedirects (per-hop
  private-host validation) plus an up-front assertAllowedUrl — no second
  fetch path, no second SSRF surface.

kb_ingest is REMOTE_BLOCKED (a channel message must not make Lisa fetch an
attacker URL into the KB) but NOT autonomous-blocked — K-I scopes autonomous
use to the feeds.json domain watchlist (D3) instead of a blanket ban.

Tests are offline-fixture only: converter syntax coverage, chrome-stripping,
provenance forms, dedupe/force/ledger-rebuild, SSRF rejection before fetch,
content-type gates.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Three IngestAdapter implementations behind the K-E seam, for the sites where
generic readability extraction can't reach the content:

- wechat: article body from #js_content, account from #js_name, epoch publish
  time from inline `var ct`; lazy-loaded images already handled via data-src.
  The human-verification interstitial throws a loud, actionable error (open
  the share link on the phone, paste the text, kb_add) — never a silently
  captured blank page.
- bilibili: metadata via the public view API; b23.tv short links resolve
  through the guarded fetch. Subtitles are cookie-gated (SESSDATA, which the
  user may volunteer in kb/feeds.json) — absent that, degrade.
- youtube: oEmbed as the reliability floor + one InnerTube player POST for
  description/captions; captionTracks → &fmt=json3, manual tracks over ASR.
  Handles the documented failure modes (PO token, 200-with-empty-body,
  datacenter throttling) by degrading.

Fixed subtitle layering (handoff: do not reorder): built-in API → yt-dlp
(--dump-single-json only when installed; discovered subtitle URLs are still
fetched through the guarded path) → metadata + description. A MISSING
TRANSCRIPT IS NOT A FAILURE: the entry records `transcript: unavailable
(<reason>)` and the tool reply tells the user they can paste one via kb_add.

Supporting changes: fetchFollowingSafeRedirects gains an optional SafeFetchInit
(method/headers/body) so adapter API calls stay on the single SSRF-guarded
fetch path; ingest types moved to types.ts to break the adapter↔index cycle;
the min-body-length gate now applies only to the generic path so degraded
video captures can be legitimately short.

All tests offline-fixture; degradation paths asserted explicitly.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@oratis

oratis commented Jul 24, 2026

Copy link
Copy Markdown
Owner Author

Strong, well-tested adapter layer — routing every request through the single SSRF-guarded ctx.fetchImpl, the types.ts cycle break, and the "missing transcript is a degradation, not a failure" layering are all the right calls. Two things to address before merge, plus minor hardening:

1. SESSDATA cookie is replayed to every redirect hop. fetchFollowingSafeRedirects now spreads init.headers inside the per-hop loop (web_fetch.ts:103), and Bilibili sends the login cookie via that path (adapters/bilibili.ts:375-378). The per-hop guard only rejects private IPs, not host changes, so a redirect from api.bilibili.com to another public host would receive the cookie. Please scope caller-supplied headers to the initial origin (or strip cookie when the host changes across a hop).

2. Remote titles can corrupt frontmatter on read. serializeEntry whitespace-collapses extra values precisely to stop newlines forging frontmatter (store.ts:118), but the title is written raw (store.ts:106) and adapters feed it remote-controlled values (YouTube/Bilibili API titles bypass sanitization entirely; og:title/<title> keep newlines through sane()). A title with an embedded \n---\n truncates the block and drops url/hash/via/created/origin from metadata into the body. One-line fix: collapse the title like the extra values. (Store-layer asymmetry, but this PR is what makes it reachable.)

Minor: WeChat reads the response body unbounded before parsing — apply the same MAX_HTML_BYTES cap genericFetch uses. Note the string-based isPrivateHost doesn't stop DNS-rebinding; not new, but worth tracking for the cloud edition given adapters now fetch URLs taken from API responses.

Nice test coverage on the degradation chain and the verification-page hard error.

Verdict: RISKY — fix the SESSDATA cookie replay and the title→frontmatter corruption before this merges in the stack.

@oratis
oratis changed the base branch from feat/kb-ingest to main July 24, 2026 08:18
# Conflicts:
#	src/kb/ingest/html-to-md.test.ts
#	src/kb/ingest/html-to-md.ts
#	src/kb/ingest/index.ts
#	src/kb/links.test.ts
#	src/kb/links.ts
#	src/kb/store.test.ts
#	src/kb/store.ts
#	src/kb/tool.ts
@oratis

oratis commented Jul 24, 2026

Copy link
Copy Markdown
Owner Author

Reconciled onto main + landed the review fixes: (1) SESSDATA cookie replayfetchFollowingSafeRedirects now scopes caller-supplied headers/body/method to the initial origin, so a cross-origin redirect can't replay the Bilibili login cookie (or re-POST) to another host; (2) re-applied the ingest bounded-read/OOM fix through the merge (adapters keep genericFetch as the default path). Title→frontmatter is fixed at root in store.ts (#279). typecheck + 282 KB/tools tests green. Merging.

@oratis
oratis merged commit d438173 into main Jul 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant