Compare commits

...

92 Commits

Author SHA1 Message Date
codex-bot 12123c278f Resolve fourteen older Battlefield businesses with source evidence 2026-10-30 19:17:43 +08:00
codex-bot 4273dd77e0 Register all 32 enterprise Battlefield discovery entries 2026-10-30 19:09:13 +08:00
Zayden-Jung 3ab2f8e122 Merge pull request '汇总 AI 公司核查更新与文档上传 API' (#25) from codex/research-api-integration into main
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 7m33s
Reviewed-on: #25
2026-10-30 10:28:45 +00:00
codex-bot 15024c3908 merge: include latest company research updates from PR #23 2026-10-30 18:20:34 +08:00
codex-bot 770be83692 Backfill 2025 discovery ledger and verify public archive scope 2026-10-30 18:19:29 +08:00
codex-bot 083f532609 merge: integrate document upload API from PR #24 2026-10-30 18:17:53 +08:00
codex-bot 2b3706c90d merge: integrate company categorization and deployment fixes from PR #23 2026-10-30 18:17:53 +08:00
codex-bot 6bfeea4e7e feat: add scoped document API and resumable batch uploader 2026-10-30 18:14:33 +08:00
codex-bot f156406265 Classify Thrive services rollup and exclude Brila existing operator 2026-10-30 18:12:52 +08:00
codex-bot e65d90c78b Resolve Utopai founding history and preserve Fundraisly entity gaps 2026-10-30 18:10:35 +08:00
codex-bot 96f1417cda Add Goldfish with investor-backed founding-year evidence 2026-10-30 18:08:01 +08:00
codex-bot 347b9587c6 Reconcile Tapflow history and Atoms company-year evidence 2026-10-30 18:04:11 +08:00
codex-bot 677cd73945 Fix Peec team bounds regression assertion 2026-10-30 17:54:08 +08:00
codex-bot e075eee8a5 Separate legacy launches from unresolved Happycapy entity lineage 2026-10-30 17:41:15 +08:00
codex-bot d971362a97 Resolve four launch candidates through operator and app history evidence 2026-10-30 17:31:44 +08:00
codex-bot 0e5ccafa30 Classify remaining directory profiles using official business evidence 2026-10-30 17:21:06 +08:00
Zayden-Jung 0c2a909521 Merge pull request '汇总 README 整理与 Product Hunt 候选历史核查' (#22) from codex/readme-research-integration into main
Verify and deploy Tabularium / verify-and-deploy (push) Failing after 3m51s
Reviewed-on: #22
2026-10-30 09:17:21 +00:00
codex-bot a58a409c38 merge: combine README cleanup and Product Hunt history research 2026-10-30 17:13:48 +08:00
codex-bot c4ab5caac0 merge: integrate Product Hunt candidate history from PR #21 2026-10-30 17:13:13 +08:00
codex-bot 4cbb88181a Exclude four pre-2025 businesses from launch candidates 2026-10-30 17:10:51 +08:00
codex-bot ce87abd1cb docs: streamline README around content management and operations 2026-10-30 17:10:00 +08:00
Zayden-Jung dc7ec078e1 Merge pull request '补充行业基准适用性与收费研究,适配数据库文档' (#19) from codex/ai-research-context into main
Verify and deploy Tabularium / verify-and-deploy (push) Waiting to run
Reviewed-on: #19
2026-10-30 09:05:44 +00:00
codex-bot bba9fddef1 Add benchmark methodology and pricing research after document migration 2026-10-30 17:01:09 +08:00
Zayden-Jung 1302287205 Merge pull request '汇总研究更新、奇思妙想与文档数据库迁移(main-only CI)' (#18) from codex/docs-integration into main
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 7m37s
Reviewed-on: #18
2026-10-30 08:48:28 +00:00
codex-bot 59a1e4608b merge: preserve the latest Wabi research in the document database migration 2026-10-30 16:45:16 +08:00
codex-bot ed99743730 merge: integrate database documents, preserve all proposals and keep CI main-only 2026-10-30 16:40:53 +08:00
codex-bot 74af205b29 Add Wabi company case with attributed founding and free-service limits 2026-10-30 16:40:38 +08:00
codex-bot cffca6942b merge: retain the traffic platform proposal from PR #15 2026-10-30 16:39:03 +08:00
codex-bot bf58a27779 merge: integrate income group labels from PR #16 2026-10-30 16:39:03 +08:00
codex-bot 922835704b merge: integrate AI research sources from PR #14 2026-10-30 16:39:03 +08:00
codex-bot a80f6568ff fix: restore main-only CI policy and remove branch validation workflow 2026-10-30 16:36:20 +08:00
codex-bot 864a30356d Record bounded TechCrunch candidates and original-source checks 2026-10-30 16:35:52 +08:00
codex-bot 534795617d fix: decouple report checks from legacy snapshots and tolerate slow dependency downloads
Verify database-backed documents / verify (pull_request) Failing after 4m0s
2026-10-30 16:32:16 +08:00
codex-bot d57e9b77d7 feat: make the site database authoritative for documents and catalog
Verify database-backed documents / verify (pull_request) Failing after 6m6s
2026-10-30 16:23:54 +08:00
codex-bot 9a026a08a5 登记中文来源线索并补Agent与基础设施公司个案 2026-10-30 16:22:55 +08:00
codex-bot 62d3d498bb 复核EveryApp入表并保留原候选初筛审计 2026-10-30 16:09:43 +08:00
codex-bot 62c015fa9b 核对产品运营主体并补Lightfield转型对照 2026-10-30 16:00:13 +08:00
codex-bot ec95f3be31 明确收入图表的业务类别与统计分组层级 2026-10-30 15:51:57 +08:00
codex-bot 744e3314b8 核对七项候选年份并隔离第三方财务字段异常 2026-10-30 15:44:50 +08:00
codex-bot 79a6a8dbd7 补2025产品候选并核对成立年与Trace主体 2026-10-30 15:21:28 +08:00
codex-bot 0dcd178394 docs: explore Endor as a coding agent traffic platform 2026-10-30 15:16:35 +08:00
codex-bot dca7c81889 登记Product Hunt候选并补充Kilo公司个案 2026-10-30 15:11:59 +08:00
codex-bot f27b82b6a5 登记AI研究来源边界并列明覆盖缺项 2026-10-30 14:24:12 +08:00
Zayden-Jung 25c5e83d08 Merge pull request '新增 Smalltalk-80 现代化研究导读与源码研究入口' (#13) from codex/smalltalk-guide into main
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 6m56s
Reviewed-on: #13
2026-10-30 06:19:43 +00:00
codex-bot 798c6d17d0 docs: add modern Smalltalk-80 study guide 2026-10-30 14:17:39 +08:00
Zayden-Jung c2ea0900e6 Merge pull request '补充AI公司收入、合同与业务规模口径核查' (#12) from codex/ai-research-revenue-scope into main
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 6m30s
Reviewed-on: #12
2026-10-30 06:04:36 +00:00
codex-bot 1cc2c9f97f 补充6家AI公司合同与交易支出口径核查 2026-10-30 13:53:00 +08:00
Zayden-Jung 62bba8d320 Merge pull request '新增AI公司收入分布、证据核查与研究报告' (#11) from codex/ai-research-income into main
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 7m48s
Reviewed-on: #11
2026-10-30 05:48:56 +00:00
codex-bot 28fa155829 深化8家AI公司收入声明及合同并购口径核查 2026-10-30 06:58:06 +08:00
codex-bot db47c1da13 补全20家AI公司主营买家与交付边界 2026-10-30 06:51:40 +08:00
codex-bot 446ad80089 深化20条目录资料并保留发现来源审计 2026-10-30 06:47:02 +08:00
codex-bot b52d1e59a4 增加研究覆盖审计及分类数据直达链接 2026-10-30 06:24:56 +08:00
codex-bot c7aa6e54c6 补充Bud收购案例与Rocket转型业务边界 2026-10-30 06:08:28 +08:00
codex-bot f93e094ba2 明确核查范围并补齐公司明细关联 2026-10-30 06:02:20 +08:00
codex-bot 5ee28cef98 补充Gradium第三方语音评测及测试范围 2026-10-30 05:58:54 +08:00
codex-bot 8da38694bc 增加收入分布快照报告与公司明细直达链接 2026-10-30 05:54:51 +08:00
codex-bot 850ed8f9a7 补充Speedrun收入声明并关联公司核查记录 2026-10-30 05:48:49 +08:00
codex-bot 43bd5a86bf 补足ARR历史月份并更新企业规模与业务边界 2026-10-30 05:44:25 +08:00
codex-bot cfb9273f88 增加技术验证证据筛选并区分材料与独立测试 2026-10-30 05:41:35 +08:00
codex-bot 3e0cbf9831 补充中文AI样本及成立年和近名实体核查 2026-10-30 05:38:35 +08:00
codex-bot aa2d3fe244 补充Runable经营案例与商业模式初评 2026-10-30 05:35:30 +08:00
codex-bot 2e4dd8c6c7 补齐59条主营分类并记录3条资料缺口 2026-10-30 05:32:05 +08:00
codex-bot 1c4e2fc9b6 按官方长简介复核62条AI公司业务分类 2026-10-30 05:30:01 +08:00
codex-bot 69fa0b240f 新增支付平台收入样本与分布分析 2026-10-30 05:25:05 +08:00
Zayden-Jung 6d26a5b0c1 Merge pull request 'ci: 仅 main 分支执行 CI/CD' (#8) from codex/main-only-cicd into main
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 5m20s
Reviewed-on: #8
2026-10-29 20:34:12 +00:00
Zayden-Jung bb9ebaa052 Merge pull request '扩展 AI 公司目录覆盖与来源核查台账' (#10) from codex/ai-research-coverage into main
Verify and deploy Tabularium / verify-and-deploy (push) Has been cancelled
Reviewed-on: #10
2026-10-29 20:34:04 +00:00
codex-bot d50281a1e9 扩展 AI 公司目录覆盖并保留逐条核查台账
Verify and deploy Tabularium / verify-and-deploy (pull_request) Successful in 11m10s
2026-10-30 04:31:33 +08:00
codex-bot 3e2183798d 补充 AI 公司收入证据及声明纠错案例
Verify and deploy Tabularium / verify-and-deploy (pull_request) Successful in 13m33s
2026-10-30 03:54:22 +08:00
codex-bot 562618cd68 ci: restrict workflows to main branch 2026-10-30 03:43:53 +08:00
Zayden-Jung f550fc8955 Merge pull request '修复 AI 公司研究导入引用与平板布局' (#7) from codex/ai-research-validation into main
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 5m51s
Reviewed-on: #7
2026-10-29 19:37:04 +00:00
codex-bot 157144b3f9 Correct research review references and advance the data revision
Verify and deploy Tabularium / verify-and-deploy (pull_request) Successful in 6m46s
2026-10-30 03:35:17 +08:00
codex-bot 3cfce44a25 Align research workbench breakpoints with document navigation
Verify and deploy Tabularium / verify-and-deploy (pull_request) Waiting to run
2026-10-30 03:34:05 +08:00
Zayden-Jung e91255856c Merge pull request '新增 AI 公司研究工作台并共用文档站数据库' (#6) from codex/ai-company-research into main
Verify and deploy Tabularium / verify-and-deploy (push) Failing after 2m26s
Reviewed-on: #6
2026-10-29 19:31:59 +00:00
codex-bot 1250b674b0 Add AI company research workbench backed by the shared site database
Verify and deploy Tabularium / verify-and-deploy (pull_request) Failing after 5m57s
2026-10-30 03:25:38 +08:00
Zayden-Jung 074881b650 Merge pull request '补充 Agent 编程边界与 LangGraph / DSPy 研究草案' (#5) from codex/agent-composition into main
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 6m7s
Reviewed-on: #5
2026-10-28 14:28:52 +00:00
codex-bot 1966d7a0a7 Document agent composition boundaries and judgment object proposal
Verify and deploy Tabularium / verify-and-deploy (pull_request) Successful in 7m58s
2026-10-28 22:26:12 +08:00
Zayden-Jung 319de8a3a7 Merge pull request '按 Supabase 参考修正为横向分类下拉导航' (#4) from codex/category-menus into main
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 4m33s
Reviewed-on: #4
2026-10-28 11:55:47 +00:00
codex-bot 787491622b Replace collection select with horizontal category dropdown navigation
Verify and deploy Tabularium / verify-and-deploy (pull_request) Successful in 11m20s
2026-10-28 19:38:07 +08:00
Zayden-Jung e448acb904 Merge pull request '按分类与合集组织文档 URL,收紧导航与阅读排版' (#2) from codex/docs-navigation into main
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 5m33s
Reviewed-on: #2
2026-10-28 11:16:16 +00:00
codex-bot e286139572 Redirect legacy document URLs after authentication without prerendering aliases
Verify and deploy Tabularium / verify-and-deploy (pull_request) Successful in 5m25s
2026-10-28 19:15:31 +08:00
codex-bot c49c8348d2 Merge published comic changes and adapt navigation verification
Verify and deploy Tabularium / verify-and-deploy (pull_request) Failing after 5m28s
2026-10-28 19:02:26 +08:00
Zayden-Jung 7a9c88a05a Merge pull request '为 Endor 项目讨论增加双图漫画与共享图片压缩策略' (#3) from codex/endor-review-comic into main
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 4m34s
Reviewed-on: #3
2026-10-28 10:57:58 +00:00
codex-bot 422d6622a2 Organize document URLs by category and collection with compact navigation
Verify and deploy Tabularium / verify-and-deploy (pull_request) Has been cancelled
2026-10-28 18:38:13 +08:00
codex-bot bd932c36b2 Add a compressed illustration carousel with slide indicators
Verify and deploy Tabularium / verify-and-deploy (pull_request) Failing after 5m44s
2026-10-28 18:16:17 +08:00
codex-bot c08371647d Document reusable review capabilities and publish compressed comic 2026-10-28 18:02:37 +08:00
Zayden-Jung 8be53c1e25 Merge pull request '完善文档独立导航,精简边框并增加渐变与交互反馈' (#1) from codex/docs-ui into main
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 10m25s
Reviewed-on: #1
2026-10-28 07:35:50 +00:00
codex-bot 627c0ee887 Refine documentation UI with distinct collection navigation and borderless surfaces
Verify and deploy Tabularium / verify-and-deploy (pull_request) Has been cancelled
2026-10-28 15:31:25 +08:00
codex-bot e381deb04e Isolate document collection navigation and search
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 6m8s
2026-10-28 14:09:28 +08:00
codex-bot e0191e1aa3 Document object reference cycles and generational garbage collection
Verify and deploy Tabularium / verify-and-deploy (push) Waiting to run
2026-10-28 14:04:19 +08:00
codex-bot ef1ba88161 Add language design question collection with discussion decisions and provenance
Verify and deploy Tabularium / verify-and-deploy (push) Waiting to run
2026-10-28 14:02:12 +08:00
codex-bot 2b3b3a1ae4 Expand document collections with Pretext tutorial and simplify library navigation
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 5m47s
2026-10-28 13:42:51 +08:00
codex-bot 1f3ab5a7ee Frame Endor as an AI operating environment with object pools and agents
Verify and deploy Tabularium / verify-and-deploy (push) Successful in 4m44s
2026-10-28 03:49:10 +08:00
75 changed files with 66797 additions and 1424 deletions
+5
View File
@@ -6,4 +6,9 @@
**/*.pyc **/*.pyc
**/*.tsbuildinfo **/*.tsbuildinfo
.artifacts .artifacts
apps/docs/public/figures/**/*.webp
.env* .env*
**/*.sqlite
**/*.sqlite-*
**/*.db
+2 -1
View File
@@ -2,7 +2,6 @@ name: Verify and deploy Tabularium
on: on:
push: push:
branches: [main] branches: [main]
pull_request:
workflow_dispatch: workflow_dispatch:
concurrency: concurrency:
@@ -11,6 +10,7 @@ concurrency:
jobs: jobs:
verify-and-deploy: verify-and-deploy:
if: gitea.ref == 'refs/heads/main'
runs-on: ces-control runs-on: ces-control
timeout-minutes: 45 timeout-minutes: 45
env: env:
@@ -22,6 +22,7 @@ jobs:
with: with:
github-server-url: ${{ gitea.server_url }} github-server-url: ${{ gitea.server_url }}
persist-credentials: false persist-credentials: false
fetch-depth: 0
- name: Verify with persistent caches or reuse verified image - name: Verify with persistent caches or reuse verified image
run: python3 scripts/ci.py run: python3 scripts/ci.py
- name: Deploy latest main with health checks and rollback - name: Deploy latest main with health checks and rollback
+8
View File
@@ -11,3 +11,11 @@ __pycache__/
!.env.example !.env.example
.artifacts/ .artifacts/
# Browser raster derivatives are generated on the confirmed remote runner.
/apps/docs/public/figures/**/*.webp
# Application data and content exports belong in private persistent storage.
*.sqlite
*.sqlite-*
*.db
+2 -2
View File
@@ -1,9 +1,9 @@
# Tabularium working agreements # Tabularium working agreements
- 本仓库专门维护 Endor 文档与制图脚本。支持本地开发;CI/CD 使用现有 ces-control Runner,在 main 通过验证后自动部署。不得修改其他项目、共享 Runner 配置或清理共享 Docker 缓存。 - 本仓库专门维护 Endor 文档与制图脚本。支持本地开发;CI/CD 仅在 main 使用现有 ces-control Runner,验证通过后自动部署;工作分支与 PR 不运行 CI,确认 Runner 不构成扩大触发范围的授权。不得修改其他项目、共享 Runner 配置或清理共享 Docker 缓存。
- Web 技术栈为 TypeScript、React、Tailwind CSS、Next.js Pages Router;不要切换到 App Router。 - Web 技术栈为 TypeScript、React、Tailwind CSS、Next.js Pages Router;不要切换到 App Router。
- 使用 pnpm 管理 JavaScript workspace,使用 uv 管理 `tools/figures` 的 Python 项目,保留两套锁文件。 - 使用 pnpm 管理 JavaScript workspace,使用 uv 管理 `tools/figures` 的 Python 项目,保留两套锁文件。
- Markdown 正文放在 `content/docs`,Python 图形源码放在 `tools/figures/src/endor_figures`,可复现的 SVG 输出放在 `apps/docs/public/figures`。 - 文档正文、目录元数据与修订记录以站点现有 SQLite 数据库为唯一权威源,使用文档 API 或 docs 管理工具直接更新;不得把新正文、目录 JSON、数据库文件或日常内容快照提交到仓库。历史 Git 文档只用于显式的一次性迁移,不作为运行时种子。Python 图形源码放在 `tools/figures/src/endor_figures`,可复现的 SVG 输出放在 `apps/docs/public/figures`。
- 未确认的架构提议明确标注为草案,不能表述为现有实现。 - 未确认的架构提议明确标注为草案,不能表述为现有实现。
- 本地开发与预览只监听 `127.0.0.1`。部署容器监听 `0.0.0.0:3000`,服务器入口默认 18135,可通过独立 production.env 配置。 - 本地开发与预览只监听 `127.0.0.1`。部署容器监听 `0.0.0.0:3000`,服务器入口默认 18135,可通过独立 production.env 配置。
- 对 gitea.entroia.com 仅使用 codex-bot,提交身份为 Codex Bot <codex-bot@gitea.entroia.local>。SSH 使用隔离配置:`ssh -F /dev/null -o IdentitiesOnly=yes -i /Users/zzyang/.codex/credentials/gitea-entroia/codex_entroia_ed25519 -p 22222`。 - 对 gitea.entroia.com 仅使用 codex-bot,提交身份为 Codex Bot <codex-bot@gitea.entroia.local>。SSH 使用隔离配置:`ssh -F /dev/null -o IdentitiesOnly=yes -i /Users/zzyang/.codex/credentials/gitea-entroia/codex_entroia_ed25519 -p 22222`。
+173 -61
View File
@@ -1,104 +1,216 @@
# Endor · Tabularium # Endor · Tabularium
Endor 文档与制图 monorepo。Tabularium 取古罗马档案馆之意。支持本地开发,并由 Gitea Actions 在 ces-control 上验证与部署。 Endor 的文档站与 AI 公司研究工作台,包含文档阅读、全文搜索、研究数据展示和制图工具。使用 Next.js Pages Router、React、TypeScript 与 Tailwind CSS;JavaScript workspace 使用 pnpm,制图 Python 项目使用 uv。
## 本地开发 ## 代码与内容放在哪里
需要 Node.js 22.13+(推荐 LTS)、pnpm 11.25、Python 3.11+ 和 uv。 文档正文、目录元数据和修订记录由站点 SQLite 数据库管理,日常写作直接更新数据库,无需提交代码、构建或部署。研究业务数据仍沿用版本化 JSON 导入机制,后续单独迁移。
首次安装依赖需要访问软件包源。本地开发服务只监听 127.0.0.1。
| 内容 | 权威来源与维护方式 |
| --- | --- |
| 文档正文、分类、合集、分组、摘要、草案和推荐状态 | 数据库;通过文档 API 或服务器上的 `docs` 管理工具读写 |
| 文档旧地址与修订历史 | 数据库;改名保留别名,修改追加修订 |
| AI 公司、观测、证据、候选与核查记录 | `content/research` 中的版本化快照;服务端显式按版本导入同库后查询 |
| 页面、组件、管理工具和部署逻辑 | 本仓库,通过工作分支与 PR 评审 |
| 图形源码与静态资源 | `tools/figures` 与 `apps/docs/public`;生成步骤在远程 Runner 执行 |
以上数据库数据共用 `AUTH_CONFIG_FILE` 同目录下的 `login-state.sqlite`,该文件名沿用历史命名。生产环境挂载到容器 `/auth`,不随镜像替换。文档使用 `documents`、`document_aliases`、`document_revisions`、`document_imports` 表,研究数据使用 `research_*` 表,登录状态使用 `login_state` 表。
仓库不接收新的文档正文 Markdown、目录 JSON、数据库文件或日常正文快照。历史 Git 正文仅用于一次性迁移;运行时不读取 `content/docs` 或 `content/catalog.json`。README 维护程序使用与运维约定,研究个案、统计数量与内容更新日志在工作台和数据库文档中查看。
## 阅读与访问
首页、阅读页、目录及全文搜索按请求读取数据库,内容更新后刷新即可看到。旧文件式地址和改名前的语义地址继续跳转到当前地址,并保留查询参数。
- 文档原文:`GET /api/documents/source?slug=<文档地址>`。
- 全文搜索:`GET /api/search`。
- 研究工作台:`/docs/other-research/ai-company-research/overview`。
- 收入样本:`/docs/other-research/ai-company-research/income-snapshot`。
- 覆盖与缺项:`/docs/other-research/ai-company-research/coverage`。
正文、搜索、研究 API 与静态资料均经过站点登录认证,私有响应使用 `private, no-store`。Markdown 支持 GFM 表格,不解析原始 HTML;正文图片写入时检查压缩格式。草案标记用于展示状态,不构成单独的访问权限。
## 管理文档
部署后,管理员可在服务器上使用 `/opt/endorphin-tabularium-docs/docs`。该工具在当前容器中操作数据库,需要服务器运维权限。自动化上传使用下文的文档 API,日常读写无需登录服务器。
```sh ```sh
pnpm install --frozen-lockfile sudo /opt/endorphin-tabularium-docs/docs list
uv sync --project tools/figures --locked sudo /opt/endorphin-tabularium-docs/docs get endor/endor-purpose-draft
pnpm dev sudo /opt/endorphin-tabularium-docs/docs history 04-endor-purpose-draft
``` ```
访问 http://127.0.0.1:3000 ,先使用验证器动态码登录。首次本地使用需按下文初始化私有认证配置;缺少配置时正文关闭访问。站点无外部字体或 CDN 资源。 `save` 从标准输入接收完整 JSON。必填字段如下:
```text | 字段 | 用途 |
apps/docs/ Next.js Pages Router + React + TypeScript + Tailwind CSS | --- | --- |
content/docs/ Markdown 文档源,文件名成为 /docs/<slug> 路由 | `slug` | 语义化公开地址,不含数字章节前缀 |
tools/figures/ 独立 Python 项目,使用 drawsvg 编程制图 | `sourceSlug` | 稳定标识;修改公开地址时保持不变 |
| `title`、`content` | 标题与 Markdown 正文 |
| `category`、`collection`、`group` | 分类、合集与目录分组 |
| `description`、`draft`、`featured` | 摘要、草案状态与推荐状态 |
| `revision` | 新建传 `0`;修改传最近一次读取到的版本号 |
修改现有文档的流程:
```sh
umask 077
doc_work_dir=$(mktemp -d)
sudo /opt/endorphin-tabularium-docs/docs get endor/endor-purpose-draft > "$doc_work_dir/document.json"
# 编辑该私有 JSON 文件,保留读取到的 revision 和 sourceSlug。
sudo /opt/endorphin-tabularium-docs/docs save < "$doc_work_dir/document.json"
``` ```
## 命令 保存成功后,正文、目录和搜索通过后续请求读取新内容。发生版本冲突时重新读取并合并修改,不能仅改大 `revision` 覆盖并发编辑。调整分类或分组也走同一保存流程;`history` 使用稳定的 `sourceSlug` 查询修订。
- `pnpm dev`:本地开发,修改 Markdown 后刷新页面即可读取新内容。 ## 文档上传 API
- `pnpm figures`:运行 Python 制图,更新 `apps/docs/public/figures`。
- `pnpm lint` / `pnpm typecheck`:前端静态检查。
- `pnpm build`:构建文档站。
- `pnpm start`:在本地预览已构建站点。
- `pnpm check`:依次执行 lint、类型检查、制图与构建。
站点默认浅色,使用本地系统字体。全站搜索支持正文关键词、`⌘/Ctrl K`、方向键与 Enter;代码块提供复制与反馈。桌面提供分组导航和滚动高亮的页内目录,小屏可展开文档菜单与页内目录。首页入口、草案提示、前后篇导航均引用现有 Markdown 内容。 文档 API 直接读写同一个数据库,供自动化整理和大量文档上传使用。它只接受独立的文档 API Key,不接受网页 Cookie 或通用网页会话令牌;Key 不能用于研究、登录或其他站点 API。
参考设计截图与研究记录保存在 `design/references`;浏览器验收截图与检查说明保存在 `design/verification`。这些文件不作为站点静态资源发布。 | 方法与地址 | 用途 |
| --- | --- |
| `GET /api/documents?limit=50&offset=0` | 分页读取目录元数据;不返回全部正文 |
| `GET /api/documents/item/<slug>` | 读取单篇完整正文、目录字段和当前 revision;支持旧地址 |
| `GET /api/documents/item/<slug>?history=1&limit=50&offset=0` | 分页读取修订元数据与时间,按新到旧排列 |
| `GET /api/documents/item/<slug>?revision=1` | 读取指定修订的完整正文 |
| `POST /api/documents` | 保存一个完整文档 JSON;字段与 `docs save` 相同 |
| `POST /api/documents/batch` | 保存 `{ "documents": [...] }`,每个请求 1—100 篇 |
文档标题取首个 `# 标题`,文档排序按文件名。普通 Markdown 与 GFM 表格可用,嵌入图使用 `/figures/<name>.svg`。不解析原始 HTML。 写入使用 `Authorization: Bearer <文档 API Key>`。新建传 `revision: 0`;更新先读取当前全文,再使用读到的 revision。每篇正文最多 2,000,000 个 JavaScript 字符单位;每次请求最多 8 MiB。目录和修订分页的 `limit` 范围为 1—100,响应包含 `total` 和 `nextOffset`。
生产构建会生成文档路由;新增或修改文档后重新运行 build。开发模式按请求读取内容。 单个批量请求在同一事务提交,任意一篇格式错误、版本冲突或地址冲突都会整体回滚。成功返回文档地址、稳定标识和新修订号;版本或幂等键冲突返回 `409`,格式错误返回 `400`,超出请求大小返回 `413`。缺少、过期或撤销的 Key 返回 `401`,只读 Key 写入返回 `403`。
main 推送通过 CI 验证后自动部署;Pull Request 只验证,不部署。工作流也支持手动触发。
## Endor 概念图 建议写入时提供 `Idempotency-Key`,由 1—128 个字母、数字或 `._:-` 组成。同一个 Key、相同请求 ID 和相同输入重试时,返回原回执并标记 `replayed: true`,不追加修订;相同 ID 改换输入会冲突。回执描述原请求,不代表之后没有其他修改;需要当前内容时重新读取文档。改过正文或 revision 后,应使用新的请求 ID。
`content/docs/00-endor-concepts-draft.md` 解释全球入口、区域网关与 Runtime、分片、CDN、身份及跨区恢复的概念设计,页面为 `/docs/00-endor-concepts-draft`。 ### 创建、查看与撤销 Key
图形源码位于 `tools/figures/src/endor_figures/architecture.py`,由 `pnpm figures` 生成 `apps/docs/public/figures/endor-architecture.svg`。Python 负责可复现的节点、全连接和复制路径,正文直接显示图片,点击可放大;大图支持原尺寸查看、滚动和 Escape/空白处关闭。无需外部图标、字体或绘图服务。图中的数量是示意,身份服务/CDN 接入属于建议,所有未实现的关系均以草案说明。 管理员只需通过已验证的服务器连接进行 Key 管理:
拓扑检查:`uv run --locked --project tools/figures python -m unittest discover -s tools/figures/tests -v`。容器检查流程会运行同一检查。 ```sh
sudo /opt/endorphin-tabularium-docs/docs key-create codex-upload /auth/codex-docs-key.json read-write 90
sudo /opt/endorphin-tabularium-docs/docs key-list
sudo /opt/endorphin-tabularium-docs/docs key-revoke <key-id>
```
## 动态码登录与二维码 创建命令将完整 Key 写入认证私有目录中的指定新文件,权限 `0600`,终端仅输出 ID、权限和到期信息。文件已存在时拒绝覆盖。权限可选 `read` 或 `read-write`;有效期默认 90 天,可设 1—365 天。数据库仅保存 Key 摘要,列表不返回原文;撤销后不能继续认证。独立 Key 文件和认证 config.json 都不包含在 SQLite 整库备份中。
与 PROMPT 的参考流程一致:共享验证器的6位TOTP动态码,每30秒更新;成功登录的HttpOnly、SameSite=Lax会话有效7天。此方案是动态码单因素登录,不是密码加动态码的双因素组合。 ### 使用上传客户端
正文、SVG、文档数据与API都经过认证,仅登录入口、登录所需代码资源和最小健康检查公开。20次/5分钟的共享尝试上限与已用时间步持久保存在SQLite中,跨进程和重启继续生效。缺失或损坏配置时拒绝访问,不自动降为公开站点。 `scripts/documents-client.py` 仅使用 Python 标准库。通过 `TABULARIUM_DOCS_URL` 指定站点 origin,通过 `TABULARIUM_DOCS_KEY_FILE` 指定本机私有 Key 文件(支持创建命令输出的 JSON),不把 Key 放入命令行参数。
生产认证文件位于服务器 `/opt/endorphin-tabularium-docs/private-auth`,目录0700、文件0600,只挂载进本项目容器。部署只初始化一次,后续更新保留同一验证器密钥与会话签名密钥。生产镜像、Git、CI日志和网页不包含密钥。 客户端要求 HTTPS;尚未配置 HTTPS 时,可通过已验证的 SSH 连接建立本机端口转发,连接 `http://127.0.0.1:18136`。以下 `$DOCS_SSH_TARGET` 应事先设置为受信任的 SSH 别名或 `user@host`:
管理员通过SSH管理: ```sh
ssh -N -L 18136:127.0.0.1:18135 "$DOCS_SSH_TARGET"
```
将服务器私有目录中的 Key 文件复制到受保护的本机位置后,在另一个终端配置客户端。`$TABULARIUM_DOCS_KEY_FILE` 文件须仅本人可读写,不能提交到仓库:
```sh
export TABULARIUM_DOCS_URL=http://127.0.0.1:18136
export TABULARIUM_DOCS_KEY_FILE="$HOME/.config/tabularium/codex-docs-key.json"
python3 scripts/documents-client.py list --limit 50
python3 scripts/documents-client.py get endor/endor-purpose-draft
python3 scripts/documents-client.py get endor/endor-purpose-draft --history
python3 scripts/documents-client.py get endor/endor-purpose-draft --revision 1
```
修改流程与 CLI 相同:
```sh
umask 077
api_work_dir=$(mktemp -d)
python3 scripts/documents-client.py get endor/endor-purpose-draft > "$api_work_dir/document.json"
# 编辑正文或目录字段,保留 sourceSlug 和读取到的 revision。
python3 scripts/documents-client.py save "$api_work_dir/document.json"
```
大量文档可使用仅含 `documents` 数组的私有 JSON 文件。客户端按 100 篇和 8 MiB 请求上限自动分批,并为各批派生固定的幂等请求 ID。每批独立提交;后续批次失败时,前面的成功批次保留。客户端会打印根请求 ID 和各批进度,使用相同 ID 与未修改的输入重试可跳过已完成的批次;可通过 `--request-id` 显式指定根 ID(客户端最多 100 个字符)。若后续批次因业务冲突失败,按进度中已提交的文档数量提取尚未成功的部分,修正后使用新的根 ID 上传。
客户端只自动重试一次临时网络或 `502/503/504` 错误,保持正文和请求 ID 不变;`409` 等业务错误不会自动覆盖。它不跟随 HTTP 重定向,避免将 Bearer 凭据转发到其他地址。正文和 Key 继续保存在数据库或私有文件中,不因使用 API 而进入 Git。
## 研究数据与检查
研究工作台提供公司筛选、经营指标、原始证据、收费与交付模式、技术材料及核查记录。它区分公司披露、支付平台指标、第三方估算、融资和客户收益;未知收入不填零,材料可访问也不代表性能或商业效果已经验证。研究范围、样本限制和个案结论以工作台记录为准。
| 仓库资料 | 用途 |
| --- | --- |
| `content/research/ai-companies.seed.json` | 研究数据导入快照;更新必须更换 `version` |
| `content/research/ai-companies.sources.json` | 来源范围、用途、覆盖边界与后续缺项 |
| `content/research/ai-companies.coverage.json` | 候选池逐条筛选台账 |
| `content/research/ai-income-analysis.json` | 独立复算的统计参考快照 |
服务端以事务导入未载入的版本,保留旧研究版本与登录、文档数据;同一版本标识下内容变化会拒绝导入。页面和 `GET /api/research/ai-companies` 从数据库读取对应研究版本。回退程序可能选择旧研究版本,不能等同于撤销数据库中的正文编辑。
以下 Python 检查不触发编译或构建,可在工作分支执行:
```sh
PYTHONDONTWRITEBYTECODE=1 python3 scripts/audit-ai-research.py --check
PYTHONDONTWRITEBYTECODE=1 python3 scripts/summarize-ai-income.py --check
```
若需对照研究数据检查报告正文,先用 `docs export` 导出当前文档,再给对应脚本传入 `--document-export <导出文件>`。默认 `--check` 核对研究数据的统计与审计不变量,不将历史迁移快照当作当前正文。脚本不带参数时仅在 `.artifacts/reports` 生成候选正文,需审阅后通过 `docs save` 写入数据库。
## 备份与首次迁移
```sh
sudo /opt/endorphin-tabularium-docs/docs backup /auth/manual-backup.sqlite
sudo /opt/endorphin-tabularium-docs/docs export /auth/current-documents.json
```
路径在容器内,输出文件已存在时拒绝覆盖。`backup` 是整个共享 SQLite 数据库的一致性备份,包含登录状态、研究数据、正文、别名和修订;`export` 只保存当前正文与目录,供空库初始化或外部迁移使用,不包含完整修订历史。认证配置单独保存在 `/auth/config.json`,整库备份不包含该配置文件。备份与导出应保存在私有挂载或受控备份位置。
首次迁移由 `scripts/export-legacy-documents.py` 从固定历史版本导出正文和目录,基线与研究正文覆盖版本在脚本中明确记录。导出写入 Git 忽略目录,权限为 `0600`,不进入生产镜像:
```sh
python3 scripts/export-legacy-documents.py --output .artifacts/documents-migration.json
```
该命令用于迁移准备,不是日常写作入口;目标文件存在时拒绝覆盖。部署先备份共享数据库,再用 `import --if-empty` 向空文档表事务导入。已有文档时跳过,不覆盖后续编辑;导入失败整体回滚并中止部署。`--ref` 仅用于明确选择历史导出版本。
程序回退不会撤销数据库编辑;回退到旧文件式站点则会显示旧正文。完整数据库恢复会同时影响登录、研究和文档状态,需先停止写入、保留当前备份,再明确选择恢复点。部署脚本只回退镜像,不自动恢复数据库。
## 登录管理
站点使用共享验证器的 6 位 TOTP 动态码,每 30 秒更新。会话使用 HttpOnly、SameSite=Lax Cookie,有效期 7 天;共享尝试上限为每 5 分钟 20 次,重放与限流状态在数据库中持久保存。缺少或损坏认证配置时拒绝私有访问。
```sh ```sh
sudo /opt/endorphin-tabularium-docs/auth qr sudo /opt/endorphin-tabularium-docs/auth qr
sudo /opt/endorphin-tabularium-docs/auth verify sudo /opt/endorphin-tabularium-docs/auth verify
``` ```
`qr`只允许交互终端显示;`qr-png`用于通过SSH将PNG直接重定向到私有本地文件,不在CI中运行。二维码等同登录凭据,不放入本仓库或网页。只有明确执行 `auth rotate --confirm` 才更换密钥并使旧二维码、会话失效;重新显示或下载二维码不会轮换。 认证配置和数据库位于服务器 `/opt/endorphin-tabularium-docs/private-auth`。正常部署保留验证器与会话签名密钥。`qr` 只在交互终端显示,`qr-png` 可导出到私有文件;只有 `auth rotate --confirm` 会轮换密钥并使旧会话失效。二维码和令牌不进入仓库、网页或 CI 日志。
本地先构建CLI,再初始化独立的本地测试配置: 当前 Compose 配置默认 `AUTH_COOKIE_SECURE=false`;实际采用 HTTPS 时,应在独立的生产配置中设置为 `true`。HTTP 不加密动态码与会话传输。生产部署使用无副作用的 `verify`,不执行会消耗动态码和触发限流的 `exercise`。
```sh ## 开发、验证与发布
pnpm build
AUTH_CONFIG_FILE=/private/tmp/tabularium-auth/config.json node apps/docs/.next/standalone/apps/docs/auth-cli.cjs init
AUTH_CONFIG_FILE=/private/tmp/tabularium-auth/config.json AUTH_COOKIE_SECURE=false pnpm dev
```
当前服务器入口为HTTP,与参考项目一致使用 `AUTH_COOKIE_SECURE=false`;配置HTTPS后应在独立production.env设置 `AUTH_COOKIE_SECURE=true`。HTTP本身不加密动态码和会话传输。 代码依赖要求见 `package.json` 和锁文件;当前要求 Node.js 22.13+、pnpm 11.25.0,制图使用 Python 与 uv。构建、打包、制图及会隐式编译的检查只在已确认的 `ces-control` Runner 执行,本机不执行这些步骤。
`pnpm test:auth`运行算法、会话、重放及限流测试。容器验证使用自己的匿名测试卷完成登录/并发重放/CSRF/限流测试,并在重启后检查状态仍存在。生产部署只运行无副作用的 `verify`,不会消耗用户动态码或触发生产限流。 工作分支完成轻量检查后推送并创建 PR,由用户手动合并。**CI 仅在 main 推送或针对 main 的手动运行时执行,工作分支和 PR 不运行 CI。** 不自动合并,也不因确认 Runner 而扩大触发范围。
## CI/CD 与缓存 主线通过 `.gitea/workflows/ci-deploy.yml` 执行 `scripts/ci.py`:
`.gitea/workflows/ci-deploy.yml` 使用已有 ces-control Runner,不修改共享 Runner 配置。 1. 检查研究统计、审计与 Python 测试,生成首次迁移所需的历史导出。
2. 根据程序、研究快照、图形、锁文件和构建脚本计算内容指纹。命中 verified 镜像时复用,否则安装依赖并执行 lint、类型检查、数据库测试、图形检查与构建。
3. 使用隔离数据库卷核对完整迁移、认证、全部文档与资源,以及不重建内容更新和重启持久化;通过后标记镜像为 verified。
4. `scripts/deploy.py` 确认仍为最新 main,备份并初始化文档数据,使用 `--no-build` 部署;失败时回退上一版镜像。
1. 对实际构建输入计算 SHA-256:前端源码、Markdown、图片、Python 制图源码、依赖锁文件、Dockerfile 和构建脚本。 `pnpm check`、`pnpm typecheck`、`pnpm test:auth`、`pnpm test:research`、`pnpm test:docs`、`pnpm figures`、`pnpm build` 和 `pnpm dev` 等命令涉及编译、构建或产物生成,不在本机运行。图形源码与生成资源保持可复现,前端继续使用 Pages Router。
2. 命中 `verified-<scope>-<摘要>` 镜像时跳过依赖安装和 Next.js build,只做认证、实际路由与资源冒烟检查。
3. 输入变化时运行 lint、类型检查、制图一致性检查与构建。pnpm store、uv 和 `.next/cache` 使用持久 Docker 卷,main 与每个 PR 独立;额外保留 Next.js SWC 下载缓存。
4. 生产镜像只包含 Next.js standalone 产物;Python 留在检查容器,不进入运行镜像。镜像通过动态码认证、重放/限流、重启持久化、健康、全部文档、JS/CSS、SVG 和 404 检查后才标记为 verified。
5. 部署前检查是否仍为最新 main,使用 `--no-build` 启动,失败恢复上一版镜像。
根 README、工作流或部署配置等非构建输入变化不会触发 Next.js 重建;Markdown 正文变化会更新静态页面,仍需要一次增量构建。首次构建必须安装依赖并完整生成产物。缓存可能因基础镜像、工具链或锁文件变化而失效;不要清理共享 Docker 缓存或卷。 根 README 等非构建输入变更不要求重新构建;数据库正文和目录更新也不触发构建。保留 pnpm、uv、Next.js 与 SWC 缓存,不清理共享 Docker 缓存或卷,不修改共享 Runner 或其他项目。
默认入口为服务器的 **18135** 端口。容器监听 3000,使用独立 Compose 项目 `endorphin-tabularium-docs`。部署前先检查端口是否空闲(或属于本服务),不会停止其他服务以抢占端口。服务器配置位于 `/etc/endorphin-tabularium-docs/production.env`: ## 部署位置与仓库
```dotenv | 项目 | 位置或默认值 |
TABULARIUM_BIND=0.0.0.0 | --- | --- |
TABULARIUM_PORT=18135 | Compose 项目 | `endorphin-tabularium-docs` |
``` | 容器监听 | `0.0.0.0:3000` |
| 服务器入口 | 默认端口 `18135`,由生产配置决定 |
| 生产配置 | `/etc/endorphin-tabularium-docs/production.env` |
| 发布记录与当前版本 | `/opt/endorphin-tabularium-docs/releases/<commit>` 与 `current` |
| 健康检查 | `/api/health` |
发布记录位于 `/opt/endorphin-tabularium-docs/releases/<commit>`,`current` 指向最近成功发布。修改服务器入口配置后手动重跑 main 工作流即可,复用现有镜像。 服务入口使用 `TABULARIUM_BIND`、`TABULARIUM_PORT` 配置。部署前检查端口是否空闲或属于本服务,不停止其他服务抢占端口;本项目不自动修改防火墙、域名或反向代理。
健康检查:`/api/health`。本项目不修改 Hestia、PROMPT 或其他服务,也不自动修改防火墙、域名和反向代理。 仓库:[endorphin-tabularium-docs](https://gitea.entroia.com/Zayden-Jung/endorphin-tabularium-docs)。Git 操作仅使用 `codex-bot` 专用 SSH 身份与仓库级提交配置;Actions 检出使用 Gitea 内置任务令牌且不保存凭据。
## Git 远程
仓库:[endorphin-tabularium-docs](https://gitea.entroia.com/Zayden-Jung/endorphin-tabularium-docs)。开发者 Git 操作使用 codex-bot 专用 SSH;Actions 检出使用 Gitea 内置任务令牌,不保存检出凭据。
+1 -1
View File
@@ -5,5 +5,5 @@ import nextTs from "eslint-config-next/typescript";
export default defineConfig([ export default defineConfig([
...nextVitals, ...nextVitals,
...nextTs, ...nextTs,
globalIgnores([".next/**", "out/**", "next-env.d.ts"]), globalIgnores([".next/**", "out/**", "next-env.d.ts", "public/materials/**"]),
]); ]);
+8 -3
View File
@@ -3,12 +3,16 @@
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "NEXT_TELEMETRY_DISABLED=1 next dev --hostname 127.0.0.1", "dev": "node scripts/build-doc-images.mjs && NEXT_TELEMETRY_DISABLED=1 next dev --hostname 127.0.0.1",
"build": "NEXT_TELEMETRY_DISABLED=1 next build && node scripts/build-auth.mjs", "build": "node scripts/build-doc-images.mjs && NEXT_TELEMETRY_DISABLED=1 next build && node scripts/build-auth.mjs",
"images": "node scripts/build-doc-images.mjs",
"test:images": "node scripts/build-doc-images.mjs --check",
"start": "NEXT_TELEMETRY_DISABLED=1 next start --hostname 127.0.0.1", "start": "NEXT_TELEMETRY_DISABLED=1 next start --hostname 127.0.0.1",
"lint": "eslint . --max-warnings=0", "lint": "eslint . --max-warnings=0",
"typecheck": "NEXT_TELEMETRY_DISABLED=1 next typegen && tsc --noEmit", "typecheck": "NEXT_TELEMETRY_DISABLED=1 next typegen && tsc --noEmit",
"test:auth": "node scripts/test-auth.mjs" "test:auth": "node scripts/test-auth.mjs",
"test:research": "node scripts/test-research.mjs",
"test:docs": "node scripts/test-docs.mjs"
}, },
"dependencies": { "dependencies": {
"next": "16.4.3", "next": "16.4.3",
@@ -29,6 +33,7 @@
"eslint": "^9.39.5", "eslint": "^9.39.5",
"eslint-config-next": "16.4.3", "eslint-config-next": "16.4.3",
"postcss": "8.5.31", "postcss": "8.5.31",
"sharp": "0.35.5",
"tailwindcss": "4.3.3", "tailwindcss": "4.3.3",
"typescript": "~5.9.3" "typescript": "~5.9.3"
} }
@@ -0,0 +1,149 @@
{
"note": "Original exploratory run. Fixed order, repeated fixtures, headless DPR 1; not an official benchmark or accuracy baseline. Date: 2026-10-28 Asia/Shanghai.",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/156.0.0.0 Safari/537.36",
"iterations": 3000,
"rounds": 5,
"out": [
{
"name": "latin",
"chars": 1428,
"first": {
"calls": 62,
"units": 529
},
"second": {
"calls": 0,
"units": 0
},
"layoutCalls": 0,
"fastPath": true,
"widths": [
80,
121,
200,
319,
320,
321,
480,
800
],
"heights": [
3744,
2592,
1440,
864,
864,
864,
576,
336
],
"domHeights": [
3744,
2592,
1440,
864,
864,
864,
576,
336
],
"pretextMedianMs": 1.7000000476837158,
"domInterleavedMedianMs": 86,
"sink": 46530000
},
{
"name": "cjk",
"chars": 408,
"first": {
"calls": 53,
"units": 67
},
"second": {
"calls": 0,
"units": 0
},
"layoutCalls": 0,
"fastPath": true,
"widths": [
80,
121,
200,
319,
320,
321,
480,
800
],
"heights": [
2016,
1440,
864,
528,
504,
504,
336,
216
],
"domHeights": [
2016,
1440,
864,
528,
504,
504,
336,
216
],
"pretextMedianMs": 1.5,
"domInterleavedMedianMs": 57.80000019073486,
"sink": 26433000
},
{
"name": "pre-wrap",
"chars": 888,
"first": {
"calls": 50,
"units": 497
},
"second": {
"calls": 0,
"units": 0
},
"layoutCalls": 0,
"fastPath": false,
"widths": [
80,
121,
200,
319,
320,
321,
480,
800
],
"heights": [
2592,
1728,
864,
864,
864,
864,
576,
576
],
"domHeights": [
2592,
1728,
864,
864,
864,
864,
576,
576
],
"pretextMedianMs": 6.299999952316284,
"domInterleavedMedianMs": 93.90000009536743,
"sink": 36828000
}
]
}
@@ -0,0 +1,89 @@
// Tutorial mechanism probe, not the official performance or accuracy gate.
// Run from any directory; see README.md for runtime and Playwright setup.
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const {stripTypeScriptTypes} = require('node:module');
const assert = require('node:assert/strict');
const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const src = path.resolve(__dirname, '../../src');
const outputFlag = process.argv.indexOf('--output');
if (outputFlag !== -1 && !process.argv[outputFlag + 1]) throw new Error('--output requires a file path');
const modules = new Map();
function compile(dir) {
for (const entry of fs.readdirSync(dir,{withFileTypes:true})) {
const file = path.join(dir,entry.name);
if(entry.isDirectory()) compile(file);
else if(file.endsWith('.ts') && !file.endsWith('.test.ts')) {
modules.set('/'+path.relative(src,file).replace(/\.ts$/,'.js'),stripTypeScriptTypes(fs.readFileSync(file,'utf8'),{mode:'transform'}));
}
}
}
compile(src);
const server = http.createServer((req,res)=>{
res.setHeader('Content-Type',req.url==='/'?'text/html':'text/javascript');
if(req.url !== '/' && !modules.has(req.url)) { res.statusCode=404; res.end('Missing module'); return; }
res.end(req.url==='/'?'<html lang="en"><body></body></html>':modules.get(req.url));
});
(async()=>{
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve)});
let browser;
try {
browser = await chromium.launch({headless:true,...(process.env.CHROME_EXECUTABLE ? {executablePath:process.env.CHROME_EXECUTABLE} : {})});
const page = await browser.newPage();
await page.goto(`http://127.0.0.1:${server.address().port}/`);
const result = await page.evaluate(async()=>{
const api = await import('/layout.js');
let calls=0,units=0;
const original=OffscreenCanvasRenderingContext2D.prototype.measureText;
OffscreenCanvasRenderingContext2D.prototype.measureText=function(text){calls++;units+=text.length;return original.call(this,text)};
const font='16px "Helvetica Neue", "PingFang SC", "Geeza Pro"';
const cases=[
{name:'latin',text:'The quick brown fox jumps over the lazy dog. Accurate text layout needs cached measurements and careful line breaking. '.repeat(12)},
{name:'cjk',text:'高性能文本布局的关键,是复用字体测量结果,并正确处理中文标点和换行。'.repeat(12)},
{name:'pre-wrap',text:'A long line with\ttabs\n preserved spaces and a discretionary soft\u00adhyphen.\n'.repeat(12),options:{whiteSpace:'pre-wrap'}},
];
const out=[];
for(const c of cases){
api.clearCache();calls=0;units=0;
const p=api.prepare(c.text,font,c.options);
const first={calls,units};calls=0;units=0;
api.prepare(c.text,font,c.options);
const second={calls,units};calls=0;
const widths=[80,121,200,319,320,321,480,800];
const heights=widths.map(w=>api.layout(p,w,24).height);
const layoutCalls=calls;
const el=document.createElement('div');
Object.assign(el.style,{font,lineHeight:'24px',overflowWrap:'break-word',whiteSpace:c.options?.whiteSpace||'normal',position:'absolute'});
el.textContent=c.text;document.body.appendChild(el);
const domHeights=widths.map(w=>{el.style.width=w+'px';return el.getBoundingClientRect().height});
let sink=0;
for(let i=0;i<3000;i++)sink+=api.layout(p,widths[i%8],24).height;
const pretextMs=[],domMs=[];
for(let r=0;r<5;r++){
let t=performance.now();
for(let i=0;i<3000;i++)sink+=api.layout(p,widths[i%8],24).height;
pretextMs.push(performance.now()-t);
t=performance.now();
for(let i=0;i<3000;i++){el.style.width=widths[i%8]+'px';sink+=el.getBoundingClientRect().height;}
domMs.push(performance.now()-t);
}
el.remove();
const withSegments=api.prepareWithSegments(c.text,font,c.options);
const lineApiCounts=widths.map(w=>api.layoutWithLines(withSegments,w,24).lines.length);
const median=a=>a.sort((a,b)=>a-b)[2];
out.push({name:c.name,chars:c.text.length,first,second,layoutCalls,fastPath:p.simpleLineWalkFastPath,widths,heights,domHeights,lineApiCounts,pretextMedianMs:median(pretextMs),domInterleavedMedianMs:median(domMs),sink});
}
return {userAgent:navigator.userAgent,devicePixelRatio,language:document.documentElement.lang,font,iterations:3000,rounds:5,out};
});
for(const row of result.out){
assert.ok(row.first.calls > 0, row.name+': first preparation must measure');
assert.equal(row.second.calls,0,row.name+': repeated preparation must reuse Canvas metrics');
assert.equal(row.layoutCalls,0,row.name+': layout must not measure');
assert.deepEqual(row.heights,row.domHeights,row.name+': heights must match DOM for these fixtures');
assert.deepEqual(row.lineApiCounts,row.heights.map(h=>h/24),row.name+': line APIs must agree');
}
if(outputFlag !== -1) fs.writeFileSync(path.resolve(process.argv[outputFlag + 1]),JSON.stringify(result,null,2)+'\n');
console.log(JSON.stringify(result,null,2));
} finally {if(browser)await browser.close();server.close();}
})().catch(e=>{console.error(e);process.exitCode=1});
+151 -8
View File
@@ -18,6 +18,8 @@ import {
totp, totp,
isLoginRedirect, isLoginRedirect,
} from "../src/lib/auth"; } from "../src/lib/auth";
import { createDocumentKey, revokeDocumentKey } from "../src/lib/document-keys";
import { readDocument, saveDocument } from "../src/lib/docs";
import { consumeCode, initializeStore } from "../src/lib/auth-store"; import { consumeCode, initializeStore } from "../src/lib/auth-store";
async function main() { async function main() {
@@ -132,15 +134,15 @@ async function main() {
join(__dirname, ".next/BUILD_ID"), join(__dirname, ".next/BUILD_ID"),
"utf8", "utf8",
).trim(); ).trim();
const routes = Object.keys(
JSON.parse(
readFileSync(join(__dirname, ".next/prerender-manifest.json"), "utf8"),
).routes,
) as string[];
for (const path of [ for (const path of [
"/", "/",
"/docs/00-endor-concepts-draft", "/docs/00-endor-concepts-draft",
"/figures/endor-architecture.svg", "/figures/endor-architecture.svg",
"/figures/endor-review-gate.webp",
"/figures/endor-review-desk.webp",
"/docs/pretext/01-chapter",
"/materials/pretext/verify.cjs",
"/materials/pretext/results.chrome156.json",
`/_next/data/${buildId}/index.json`, `/_next/data/${buildId}/index.json`,
`/_next/data/${buildId}/docs/00-endor-concepts-draft.json`, `/_next/data/${buildId}/docs/00-endor-concepts-draft.json`,
]) { ]) {
@@ -155,7 +157,7 @@ async function main() {
path, path,
); );
} }
for (const path of ["/api/private", "/api/unknown"]) for (const path of ["/api/private", "/api/unknown", "/api/search", "/api/documents/source?slug=endor/endor-purpose-draft", "/api/research/ai-companies"])
assert.equal((await request(path)).status, 401, path); assert.equal((await request(path)).status, 401, path);
assert.equal( assert.equal(
( (
@@ -176,13 +178,110 @@ async function main() {
const headers = { const headers = {
Authorization: "Bearer " + signSession(config, undefined, 600), Authorization: "Bearer " + signSession(config, undefined, 600),
}; };
const researchResponse = await request("/api/research/ai-companies", { headers });
assert.equal(researchResponse.status, 200, "authenticated research API");
assert.ok(researchResponse.headers.get("cache-control")?.includes("no-store"));
const research = await researchResponse.json();
assert.equal(research.companies.length, 1023);
assert.equal(research.categories.length, 11);
assert.equal(research.evidence.length, 1310);
assert.equal(research.observations.length, 189);
assert.equal((await request("/api/research/ai-companies", { method: "POST", headers })).status, 405);
const researchPage = await request("/docs/other-research/ai-company-research/overview", { headers });
assert.equal(researchPage.status, 200);
const researchHtml = await researchPage.text();
assert.ok(researchHtml.includes('data-category="其他研究"'));
assert.ok(researchHtml.includes("AI 公司研究"));
assert.ok(researchHtml.includes("正在读取研究数据库"));
const searchResponse = await request("/api/search", { headers });
assert.equal(searchResponse.status, 200);
const searchIndex = await searchResponse.json();
assert.ok(searchIndex.some((doc: { slug: string; searchText: string }) => doc.slug === "source-studies/pretext/measurement-cache" && doc.searchText.includes("getSegmentMetrics")));
for (const doc of searchIndex as { slug: string; sourceSlug: string }[]) {
assert.ok(!doc.slug.split("/").some((part) => /^\d+-/.test(part)), doc.slug);
const legacy = await request(`/docs/${doc.sourceSlug}?from=legacy`, { headers });
assert.equal(legacy.status, 308, doc.sourceSlug);
const destination = new URL(legacy.headers.get("location")!, base);
assert.equal(destination.pathname, `/docs/${doc.slug}`);
assert.equal(destination.searchParams.get("from"), "legacy");
assert.ok(legacy.headers.get("cache-control")?.includes("no-store"));
}
const routes = ["/", ...searchIndex.map((doc: { slug: string }) => `/docs/${doc.slug}`)];
const raw = await request("/api/documents/source?slug=endor/endor-purpose-draft", { headers });
assert.equal(raw.status, 200);
assert.ok((await raw.text()).startsWith("# Endor"));
if (process.env.DOCUMENT_SMOKE_TEST) {
if (command === "exercise") await exerciseDocumentApi(request, headers);
const sourceSlug = "ci-live-document";
const previous = readDocument(sourceSlug);
if (command === "exercise") {
const first = saveDocument({ slug: "endor/ci-live-document", sourceSlug,
title: "Runtime document", category: "Endor", collection: "Endor 文档", group: "CI",
description: "Isolated smoke test", draft: true, featured: false,
content: "# Runtime document\n\nInitial body" }, previous?.revision ?? 0);
assert.equal((await request(`/docs/${first.slug}`, { headers })).status, 200);
saveDocument({ ...first, slug: "endor/ci-live-document-renamed", content: "# Runtime document\n\nUpdated without rebuilding" }, first.revision);
}
const stored = readDocument(sourceSlug);
assert.ok(stored, "Smoke document must exist after creation or restart");
assert.ok(stored.content.includes("Updated without rebuilding"), "DB content survives restart");
const live = await request(`/docs/${stored.slug}`, { headers });
assert.equal(live.status, 200);
assert.ok((await live.text()).includes("Updated without rebuilding"));
const alias = await request("/docs/endor/ci-live-document?live=1", { headers });
assert.equal(alias.status, 308);
assert.ok(alias.headers.get("location")?.includes("ci-live-document-renamed?live=1"));
const updatedIndex = await (await request("/api/search", { headers })).json();
assert.ok(updatedIndex.some((doc: { searchText: string }) => doc.searchText.includes("Updated without rebuilding")));
}
let home = ""; let home = "";
let purpose = "";
for (const route of routes) { for (const route of routes) {
const response = await request(route, { headers }); const response = await request(route, { headers });
assert.equal(response.status, 200, route); assert.equal(response.status, 200, route);
if (route === "/") home = await response.text(); const html = await response.text();
if (route === "/") home = html;
if (route === "/docs/endor/endor-purpose-draft") purpose = html;
if (route.startsWith("/docs/")) {
assert.ok(html.includes('aria-label="文档分类"'), route);
assert.ok(html.includes('data-category="语言与运行时"'), route);
assert.ok(html.includes('class="category-panel" hidden=""'), route);
assert.ok(!html.includes('class="collection-picker"'), route);
assert.ok(!html.includes("<select"), route);
assert.ok(!html.includes('class="nav-back"'), route);
const ids = [...html.matchAll(/<h[23] id="([^"]+)"/g)].map((match) => match[1]);
assert.equal(new Set(ids).size, ids.length, `Unique heading anchors: ${route}`);
for (const id of ids) assert.ok(html.includes(`href="#${id}"`), `TOC anchor: ${route}#${id}`);
}
}
assert.ok(home.includes("资料库"));
assert.ok(home.includes("/docs/source-studies/pretext/overview"));
// Inline preview and zoom dialog must both use the compressed browser asset.
assert.equal(
[...purpose.matchAll(/<img\b[^>]*\bsrc="\/figures\/endor-review-gate\.webp"/g)].length,
2,
"The comic preview and lightbox must use WebP",
);
assert.ok(purpose.includes('aria-label="上一张图片"'));
assert.ok(purpose.includes('aria-label="下一张图片"'));
assert.ok(purpose.includes('aria-label="显示第 1 张图片" aria-current="true"'));
assert.ok(purpose.includes('aria-label="显示第 2 张图片"'));
assert.equal(
[...purpose.matchAll(/<img\b[^>]*\bsrc="\/figures\/endor-review-desk\.webp"/g)].length,
0,
"The second slide should not download until selected",
);
for (const name of ["endor-review-gate", "endor-review-desk"]) {
assert.ok(!purpose.includes(`/figures/${name}.png`));
const comic = await request(`/figures/${name}.webp`, { headers });
assert.equal(comic.status, 200);
assert.match(comic.headers.get("content-type") || "", /image\/webp/);
assert.deepEqual(
Buffer.from(await comic.arrayBuffer()),
readFileSync(join(__dirname, `public/figures/${name}.webp`)),
);
assert.equal((await request(`/figures/${name}.png`, { headers })).status, 404);
} }
assert.ok(home.includes("TABULARIUM"));
const assets = new Set( const assets = new Set(
[...home.matchAll(/(?:src|href)="(\/_next\/static\/[^" ]+)"/g)].map((m) => [...home.matchAll(/(?:src|href)="(\/_next\/static\/[^" ]+)"/g)].map((m) =>
m[1].replaceAll("&amp;", "&"), m[1].replaceAll("&amp;", "&"),
@@ -191,6 +290,11 @@ async function main() {
assert.ok(assets.size); assert.ok(assets.size);
for (const path of assets) for (const path of assets)
assert.equal((await request(path, { headers })).status, 200, path); assert.equal((await request(path, { headers })).status, 200, path);
for (const name of ["verify.cjs", "results.chrome156.json"]) {
const response = await request("/materials/pretext/" + name, { headers });
assert.equal(response.status, 200, name);
assert.ok((await response.text()).length > 100);
}
for (const name of readdirSync(join(__dirname, "public/figures"))) { for (const name of readdirSync(join(__dirname, "public/figures"))) {
if (!name.endsWith(".svg")) continue; if (!name.endsWith(".svg")) continue;
const response = await request("/figures/" + name, { headers }); const response = await request("/figures/" + name, { headers });
@@ -254,3 +358,42 @@ main().catch((error) => {
); );
process.exitCode = 1; process.exitCode = 1;
}); });
async function exerciseDocumentApi(request: (path: string, init?: RequestInit) => Promise<Response>, session: Record<string, string>) {
const writer = createDocumentKey("isolated API smoke", "read-write", 1);
const reader = createDocumentKey("isolated read smoke", "read", 1);
const headers = { Authorization: "Bearer " + writer.token, "Content-Type": "application/json", "Idempotency-Key": "smoke-batch" };
const readHeaders = { Authorization: "Bearer " + reader.token, "Content-Type": "application/json" };
const make = (name: string) => ({ slug: `endor/${name}`, sourceSlug: name, title: "API smoke",
category: "Endor", collection: "Endor 文档", group: "CI", description: "Isolated API smoke",
draft: true, featured: false, content: "# API smoke", revision: 0 });
const payload = { documents: [make("ci-api-first"), make("ci-api-second")] };
try {
assert.equal((await request("/api/documents")).status, 401);
assert.equal((await request("/api/documents", { method: "POST", headers: { ...session, "Content-Type": "application/json" }, body: JSON.stringify(payload.documents[0]) })).status, 401);
assert.equal((await request("/api/research/ai-companies", { headers })).status, 401, "Document keys cannot read research");
assert.equal((await request("/api/search", { headers })).status, 401, "Document keys cannot authenticate other APIs");
assert.equal((await request("/api/documents/batch", { method: "POST", headers: readHeaders, body: JSON.stringify(payload) })).status, 403);
const saved = await request("/api/documents/batch", { method: "POST", headers, body: JSON.stringify(payload) });
assert.equal(saved.status, 200);
assert.equal((await saved.json()).documents.length, 2);
const replay = await request("/api/documents/batch", { method: "POST", headers, body: JSON.stringify(payload) });
assert.equal(replay.status, 200); assert.equal((await replay.json()).replayed, true);
const current = await request("/api/documents/item/endor/ci-api-first", { headers: readHeaders });
assert.equal(current.status, 200); assert.equal((await current.json()).revision, 1);
const page = await request("/api/documents?limit=1", { headers: readHeaders });
assert.equal(page.status, 200);
const listing = await page.json();
assert.equal(listing.documents.length, 1); assert.equal(listing.documents[0].content, undefined);
const bad = { documents: [{ ...payload.documents[0], revision: 1, content: "Must roll back" }, payload.documents[1]] };
const conflict = await request("/api/documents/batch", { method: "POST", headers: { ...headers, "Idempotency-Key": "smoke-conflict" }, body: JSON.stringify(bad) });
assert.equal(conflict.status, 409);
const unchanged = await request("/api/documents/item/endor/ci-api-first", { headers: readHeaders });
assert.equal((await unchanged.json()).content, "# API smoke");
const history = await request("/api/documents/item/endor/ci-api-first?history=1", { headers });
assert.equal(history.status, 200); assert.equal((await history.json()).total, 1);
revokeDocumentKey(writer.id);
assert.equal((await request("/api/documents", { headers })).status, 401);
} finally { revokeDocumentKey(writer.id); revokeDocumentKey(reader.id); }
console.log("Document API smoke passed: scoped keys, batch rollback, pagination, history, replay and revocation; no secrets displayed");
}
+5
View File
@@ -7,3 +7,8 @@ await build({
format: "cjs", format: "cjs",
outfile: ".next/standalone/apps/docs/auth-cli.cjs", outfile: ".next/standalone/apps/docs/auth-cli.cjs",
}); });
await build({
entryPoints: ["scripts/docs-cli.ts"], bundle: true, platform: "node", target: "node22",
format: "cjs", outfile: ".next/standalone/apps/docs/docs-cli.cjs",
});
+49
View File
@@ -0,0 +1,49 @@
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import sharp from "sharp";
const root = fileURLToPath(new URL("../../../", import.meta.url));
const sources = path.join(root, "tools/figures/assets");
const output = path.join(root, "apps/docs/public/figures");
const check = process.argv.includes("--check");
const policy = JSON.parse(await readFile(path.join(root, "content/image-policy.json"), "utf8"));
async function files(directory) {
const entries = await readdir(directory, { withFileTypes: true });
return (await Promise.all(entries.map((entry) => {
const name = path.join(directory, entry.name);
return entry.isDirectory() ? files(name) : [name];
}))).flat().sort();
}
// Originals stay outside public; both inline and lightbox images use the WebP.
for (const name of await files(path.join(root, "apps/docs/public"))) {
if (/\.(?:png|jpe?g|tiff?|bmp)$/i.test(name)) {
throw new Error(`Original raster exposed in public: ${path.relative(root, name)}. Move it to tools/figures/assets and run images.`);
}
}
await mkdir(output, { recursive: true });
for (const source of await files(sources)) {
if (!/\.(?:png|jpe?g|tiff?|bmp)$/i.test(source)) continue;
const relative = path.relative(sources, source).replace(/\.[^.]+$/, ".webp");
const destination = path.join(output, relative);
const original = await readFile(source);
const encoded = await sharp(original)
.rotate()
.resize({ width: policy.maxWidth, withoutEnlargement: true })
.webp({ quality: policy.quality, effort: 6 })
.toBuffer();
if (encoded.length > policy.maxBytes) {
throw new Error(`${relative}: ${encoded.length} bytes exceeds the ${policy.maxBytes}-byte image budget.`);
}
if (check) {
const generated = await readFile(destination);
if (!encoded.equals(generated)) throw new Error(`${relative} is stale. Regenerate browser images on the confirmed remote runner.`);
} else {
await mkdir(path.dirname(destination), { recursive: true });
await writeFile(destination, encoded);
}
console.log(`${check ? "Verified" : "Generated"} ${relative}: ${original.length} → ${encoded.length} bytes (${(100 * (1 - encoded.length / original.length)).toFixed(1)}% smaller)`);
}
+70
View File
@@ -0,0 +1,70 @@
import { readFileSync, writeFileSync, openSync, closeSync, unlinkSync } from "node:fs";
import { resolve, dirname, sep } from "node:path";
import { createDocumentKey, listDocumentKeys, revokeDocumentKey, type DocumentKeyScope } from "../src/lib/document-keys";
import { openSiteDatabase } from "../src/lib/site-database";
import { allDocuments, readDocument, saveDocument, importDocuments, documentHistory } from "../src/lib/docs";
process.umask(0o077);
const [command, argument, ...extra] = process.argv.slice(2);
try {
switch (command) {
case "key-create": {
const authFile = process.env.AUTH_CONFIG_FILE;
if (!authFile || !argument || !extra[0]) throw Error("Usage: key-create <name> <private-file> [read|read-write] [days]");
const file = resolve(extra[0]);
const directory = resolve(dirname(authFile));
if (!file.startsWith(directory + sep)) throw Error("Key output must be inside the private authentication directory");
const fd = openSync(file, "wx", 0o600);
let created: { id: string } | undefined;
try {
const key = createDocumentKey(argument, (extra[1] ?? "read-write") as DocumentKeyScope, Number(extra[2] ?? 90));
created = key;
writeFileSync(fd, JSON.stringify(key) + "\n");
console.log(JSON.stringify({ id: key.id, scope: key.scope, expiresAt: key.expiresAt, saved: file }));
} catch (error) {
if (created) revokeDocumentKey(created.id);
unlinkSync(file);
throw error;
} finally { closeSync(fd); }
break;
}
case "key-list": console.log(JSON.stringify(listDocumentKeys(), null, 2)); break;
case "key-revoke":
if (!argument) throw Error("Provide key id");
revokeDocumentKey(argument); console.log("Document key revoked"); break;
case "backup": {
if (!argument) throw Error("Provide a private backup filename");
const db = openSiteDatabase();
try { db.prepare("VACUUM INTO ?").run(argument); } finally { db.close(); }
console.log("Full site database backup created; existing files are never overwritten"); break;
}
case "list":
console.log(JSON.stringify(allDocuments().map(({ content: _, ...doc }) => { void _; return doc; }), null, 2)); break;
case "get": {
const doc = readDocument(argument ?? "");
if (!doc) throw Error("Document not found");
console.log(JSON.stringify(doc, null, 2)); break;
}
case "save": {
const { revision, ...input } = JSON.parse(readFileSync(0, "utf8"));
const doc = saveDocument(input, revision);
console.log(JSON.stringify({ slug: doc.slug, revision: doc.revision })); break;
}
case "history":
console.log(JSON.stringify(documentHistory(argument ?? ""), null, 2)); break;
case "import": {
const bundle = JSON.parse(readFileSync(0, "utf8"));
console.log(JSON.stringify({ imported: importDocuments(bundle, argument === "--if-empty") })); break;
}
case "export": {
if (!argument) throw Error("Provide a private export filename");
writeFileSync(argument, JSON.stringify({ format: "tabularium-documents-v1", documents: allDocuments() }),
{ flag: "wx", mode: 0o600 });
console.log("Document export created; existing files are never overwritten"); break;
}
default: throw Error("Usage: docs key-create <name> <private-file> [read|read-write] [days] | key-list | key-revoke <id> | backup <private-file> | list | get <slug> | save < input.json | history <sourceSlug> | import [--if-empty] < export.json | export <private-file>");
}
} catch (error) {
console.error(error instanceof Error ? error.message : "Document operation failed");
process.exitCode = 1;
}
+13
View File
@@ -0,0 +1,13 @@
import { build } from "esbuild";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawnSync } from "node:child_process";
const dir = await mkdtemp(join(tmpdir(), "tabularium-docs-tests-"));
try {
await build({ entryPoints: ["tests/docs.test.ts", "tests/documents-api.test.ts"], bundle: true,
platform: "node", target: "node22", format: "cjs", outdir: dir, outExtension: { ".js": ".cjs" } });
const result = spawnSync(process.execPath, ["--test", join(dir, "docs.test.cjs"), join(dir, "documents-api.test.cjs")], { stdio: "inherit" });
process.exitCode = result.status ?? 1;
} finally { await rm(dir, { recursive: true, force: true }); }
+14
View File
@@ -0,0 +1,14 @@
import { build } from "esbuild";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawnSync } from "node:child_process";
const dir = await mkdtemp(join(tmpdir(), "tabularium-research-tests-"));
try {
const file = join(dir, "research.test.cjs");
await build({ entryPoints: ["tests/research.test.ts"], bundle: true,
platform: "node", target: "node22", format: "cjs", outfile: file });
const result = spawnSync(process.execPath, ["--test", file], { stdio: "inherit" });
process.exitCode = result.status ?? 1;
} finally { await rm(dir, { recursive: true, force: true }); }
@@ -0,0 +1,181 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/router";
import IncomeDistribution from "./IncomeDistribution";
import {
categorySummary, evidenceUrl, technicalReviewLabels, reviewCompanyIds, type ResearchEvidence, type ResearchReview, type ResearchSnapshot,
} from "@/lib/ai-research";
const pageSize = 12;
const evidencePageSize = 30;
const revenueLabels = { self: "公司披露,待核口径", estimate: "仅第三方估算", platform: "仅支付平台记录", unknown: "暂无可用收入数字" };
const useLabels: Record<string, string> = {
platform: "支付平台记录", signal: "公司披露信号", estimate: "第三方估算", historical: "历史里程碑",
"historical-estimate": "其他时点估算", excluded: "排除收入比较", scale: "团队规模", adoption: "采用规模",
funding: "融资", technical: "第三方技术评测", crosscheck: "同一里程碑的其他资料",
};
const money = (value: number, unit = "USD") => unit === "USD"
? new Intl.NumberFormat("zh-CN", { style: "currency", currency: "USD", maximumFractionDigits: 0 }).format(value)
: `${new Intl.NumberFormat("zh-CN").format(value)} ${unit}`;
function External({ url, children }: { url: string; children: React.ReactNode }) {
const safe = evidenceUrl(url);
return safe ? <a href={safe} target="_blank" rel="noopener noreferrer">{children} ↗</a> : <span>{children}</span>;
}
function Evidence({ item, prefix = "evidence" }: { item: ResearchEvidence; prefix?: string }) {
return <li id={`${prefix}-${item.id}`} className="research-evidence">
<div><code>{item.id}</code><span className="research-tag">{item.kind}</span></div>
<strong><External url={item.url}>{item.title}</External></strong>
<p>{item.summary}</p><p className="research-muted">{item.limitation}</p>
<small>发布:{item.publishedAt ?? "未注明"} 读取:{item.accessedAt}</small>
</li>;
}
export default function AICompanyResearch() {
const router = useRouter();
const [data, setData] = useState<ResearchSnapshot | null>(null);
const [error, setError] = useState(false);
const [attempt, setAttempt] = useState(0);
const [query, setQuery] = useState("");
const [categoryChoice, setCategoryChoice] = useState<{ route: string; id: string } | null>(null);
const linkedCategory = router.query.category;
const category = categoryChoice && categoryChoice.route === router.asPath ? categoryChoice.id
: router.isReady && typeof linkedCategory === "string" && data?.categories.some((c) => c.id === linkedCategory)
? linkedCategory : "";
function setCategory(id: string) { setCategoryChoice({ route: router.asPath, id }); }
const [cohort, setCohort] = useState("");
const [income, setIncome] = useState("");
const [page, setPage] = useState(0);
const [sourcePage, setSourcePage] = useState(0);
const [depth, setDepth] = useState("");
const [teamBand, setTeamBand] = useState("");
const [technicalLevel, setTechnicalLevel] = useState("");
const [selection, setSelection] = useState<{ route: string; id: string | null } | null>(null);
const linkedCompany = router.query.company;
const selected = selection && selection.route === router.asPath ? selection.id
: router.isReady && typeof linkedCompany === "string" && data?.companies.some((c) => c.id === linkedCompany)
? linkedCompany : null;
function setSelected(id: string | null) { setSelection({ route: router.asPath, id }); }
const [tab, setTab] = useState<"companies" | "revenue" | "sources" | "reviews">("companies");
const companySection = useRef<HTMLElement>(null);
const detailSection = useRef<HTMLElement>(null);
useEffect(() => {
const controller = new AbortController();
fetch("/api/research/ai-companies", { signal: controller.signal, cache: "no-store" })
.then(async (response) => {
if (!response.ok) throw new Error("Research unavailable");
const snapshot: ResearchSnapshot = await response.json();
setData(snapshot);
}).catch(() => { if (!controller.signal.aborted) setError(true); });
return () => controller.abort();
}, [attempt]);
useEffect(() => { if (selected) detailSection.current?.focus(); }, [selected]);
const summaries = useMemo(() => data ? categorySummary(data) : [], [data]);
const filtered = useMemo(() => data?.companies.filter((c) => {
const search = `${c.name} ${c.business} ${c.location ?? ""} ${c.buyer}`.toLocaleLowerCase();
const yearMatch = !cohort || (cohort === "other" ? ![2025, 2026].includes(c.year ?? 0) : c.year === Number(cohort));
const depthMatch = !depth || (depth === "profile" ? c.profileOnly : !c.profileOnly);
const teamMatch = !teamBand || (teamBand === "unknown" ? c.team === null || (!!c.teamBound && c.team < 51)
: c.team !== null && (teamBand === "xl" ? c.team >= 51 : !c.teamBound && (teamBand === "small" ? c.team <= 5 : teamBand === "medium" ? c.team >= 6 && c.team <= 20 : c.team >= 21 && c.team <= 50)));
return (!technicalLevel || (c.technicalReview?.level ?? "unreviewed") === technicalLevel) && depthMatch && teamMatch && (!category || c.cat === category) && yearMatch && (!income || c.revenueStatus === income)
&& search.includes(query.trim().toLocaleLowerCase());
}) ?? [], [data, query, category, cohort, income, depth, teamBand, technicalLevel]);
if (error) return <div className="research-message" role="alert">研究数据库暂时不可用。<button onClick={() => { setError(false); setAttempt((n) => n + 1); }}>重新读取</button></div>;
if (!data) return <p className="research-message" role="status">正在读取研究数据库…</p>;
const categories = new Map(data.categories.map((c) => [c.id, c]));
const selectedCompany = data.companies.find((c) => c.id === selected);
const observed = data.observations.filter((o) => ["signal", "estimate"].includes(o.selection));
const disclosedCompanies = new Set(observed.map((o) => o.company)).size;
const revenueCompanies = data.companies.filter((c) => c.revenueStatus !== "unknown").length;
const selectedObservations = data.observations.filter((o) => o.company === selected);
const selectedEvidenceIds = new Set([
...(selectedCompany?.evidenceIds ?? []), ...(selectedCompany?.pricingEvidence ? [selectedCompany.pricingEvidence] : []),
...(selectedCompany?.technicalReview?.evidenceIds ?? []),
...selectedObservations.map((o) => o.evidence),
]);
const selectedEvidence = data.evidence.filter((e) => e.companyId === selected || selectedEvidenceIds.has(e.id));
const reviewCompanies = (review: ResearchReview) => {
const ids = new Set(reviewCompanyIds(data, review));
return data.companies.filter((c) => ids.has(c.id));
};
const selectedReviews = data.reviews.filter((r) => selected && reviewCompanyIds(data, r).includes(selected));
function chooseCategory(id: string) {
setCategory(id); setPage(0); setTab("companies");
companySection.current?.scrollIntoView({ behavior: "smooth", block: "start" });
}
return <div className="ai-research not-prose">
<div className="research-meta"><span>资料截至 {data.asOf}</span><span>首批研究 · 持续补全</span></div>
<div className="research-stats">
<div><strong>{data.companies.length}</strong><span>公司/产品记录</span></div>
<div><strong>{data.categories.length}</strong><span>业务类别</span></div>
<div><strong>{revenueCompanies}</strong><span>有收入线索的记录</span></div>
<div><strong>{data.evidence.length}</strong><span>证据记录</span></div>
</div>
<div className="research-scope"><p>{data.scope}</p>
{data.coverage && <p>YC 候选池 {data.coverage.candidateRecords} 条,官方页面读取 {data.coverage.profilesRead} 条;初筛匹配 {data.coverage.matchingProfiles} 条,新增 {data.coverage.newProfiles} 条目录记录。年份不符或缺失 {data.coverage.otherOrMissingYear} 条、AI 业务待确认 {data.coverage.unclearAI} 条、日期冲突 {data.coverage.dateConflicts} 条。目录基础资料尚未逐家核验收入和交付能力。</p>}
<details><summary>数据口径与覆盖限制</summary><ul>{data.limitations.map((note) => <li key={note}>{note}</li>)}</ul>
<p>来源以 YC、公司官网、投资机构名录与经营案例为主。同一披露的转载不构成独立验证。团队人数包含公司自报的 Team Size,与正式员工口径可能不同。</p>
</details>
</div>
<section aria-labelledby="research-categories-title" className="research-section">
<h2 id="research-categories-title">业务分类</h2><p className="research-muted">点击类别查看对应公司。数量反映本次采集覆盖,不是市场份额。</p>
<div className="research-categories">{summaries.map((c) => <button key={c.id} onClick={() => chooseCategory(c.id)} aria-label={`查看${c.name}的${c.count}条记录`}>
<div><span>{c.name}</span><strong>{c.count}</strong></div>
<span className="research-bar" aria-hidden="true"><i style={{ width: `${c.count / Math.max(1, ...summaries.map((s) => s.count)) * 100}%` }} /></span>
<small>{c.description}</small>
</button>)}</div>
</section>
<section ref={companySection} className="research-section" aria-labelledby="research-records-title">
<h2 id="research-records-title">研究数据</h2>
<div className="research-tabs" role="group" aria-label="研究数据视图">
{([['companies','公司与产品'],['revenue','收入观测'],['sources','原始证据'],['reviews','核查记录']] as const).map(([id,label]) =>
<button key={id} aria-pressed={tab === id} onClick={() => setTab(id)}>{label}</button>)}
</div>
{tab === "companies" && <>
<div className="research-filters">
<label className="research-query">搜索公司<input type="search" value={query} placeholder="名称、业务、地区或买家" onChange={(e) => { setQuery(e.target.value); setPage(0); }} /></label>
<label>业务类别<select value={category} onChange={(e) => { setCategory(e.target.value); setPage(0); }}><option value="">全部类别</option>{data.categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}</select></label>
<label>成立或发布<select value={cohort} onChange={(e) => { setCohort(e.target.value); setPage(0); }}><option value="">全部组别</option><option value="2025">2025 年成立</option><option value="2026">2026 年成立</option><option value="other">公开发布与转型对照</option></select></label>
<label>资料深度<select value={depth} onChange={(e) => { setDepth(e.target.value); setPage(0); }}><option value="">全部资料</option><option value="case">原有个案研究</option><option value="profile">目录基础资料</option></select></label>
<label>记录团队规模<select value={teamBand} onChange={(e) => { setTeamBand(e.target.value); setPage(0); }}><option value="">全部规模</option><option value="small">1—5 人</option><option value="medium">6—20 人</option><option value="large">21—50 人</option><option value="xl">至少 51 人</option><option value="unknown">未披露或分组不确定</option></select></label>
<label>技术验证证据<select value={technicalLevel} onChange={(e) => { setTechnicalLevel(e.target.value); setPage(0); }}><option value="">全部验证层级</option>{Object.entries(technicalReviewLabels).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></label>
<label>收入资料<select value={income} onChange={(e) => { setIncome(e.target.value); setPage(0); }}><option value="">全部状态</option><option value="self">找到公司披露</option><option value="estimate">仅第三方估算</option><option value="platform">仅支付平台记录</option><option value="unknown">暂无可用数字</option></select></label>
</div>
<p className="research-muted">技术验证层级记录我们查到了什么,不是能力强弱评分。技术专项评审与业务分类复核分别记录。</p>
<div className="research-result-count" role="status">{filtered.length} 条匹配记录<button onClick={() => { setCategory(""); setQuery(""); setCohort(""); setIncome(""); setDepth(""); setTeamBand(""); setTechnicalLevel(""); setPage(0); }}>清除筛选</button></div>
<div className="research-table-wrap"><table><caption className="sr-only">公司/产品分类与经营资料。选择名称查看指标和原始证据。</caption><thead><tr><th>公司或产品 / 地区</th><th>业务与买家</th><th>成立 / 发布组别</th><th>团队规模</th><th>交付与技术验证证据</th><th>收入资料</th></tr></thead><tbody>
{filtered.slice(page * pageSize, (page + 1) * pageSize).map((c) => <tr key={c.id} data-selected={selected === c.id || undefined}>
<td><button className="research-company-name" aria-expanded={selected === c.id} aria-controls="research-company-detail" onClick={() => setSelected(c.id)}>{c.name}</button><small>{c.location ?? "地区未注明"}</small></td>
<td><span className="research-tag">{categories.get(c.cat)?.name}</span>{c.profileOnly && <small>目录基础资料 · 分类依据见明细</small>}<p>{c.business}</p><small>买家:{c.buyer}</small></td>
<td>{c.cohort}</td><td>{c.team !== null && c.teamBound}{c.team ?? "未披露"}{c.team !== null && " 人"}</td><td>{c.stage}<small>{technicalReviewLabels[c.technicalReview?.level ?? "unreviewed"]}</small></td><td>{c.profileOnly ? "收入尚未逐一核验" : revenueLabels[c.revenueStatus]}</td>
</tr>)}
</tbody></table></div>
{!filtered.length && <p className="research-message">没有匹配公司,请调整筛选条件。</p>}
{filtered.length > pageSize && <nav className="research-pagination" aria-label="公司数据分页"><button disabled={page === 0} onClick={() => setPage((n) => n - 1)}>上一页</button><span>{page + 1} / {Math.ceil(filtered.length / pageSize)}</span><button disabled={(page + 1) * pageSize >= filtered.length} onClick={() => setPage((n) => n + 1)}>下一页</button></nav>}
</>}
{tab === "revenue" && <>
<IncomeDistribution data={data} onSelect={setSelected} />
<h3>公司披露与估算的历史里程碑</h3>
<p className="research-notice">这一组包含 {disclosedCompanies} 家公司的披露或估算信号,多为异时点历史里程碑,ARR 与年化收入口径仍待核对,暂不计算其同期领域均值。币种未确认的记录仅显示原值,不绘制美元长度条。上面的平台MRR统计与这一组分开。</p>
<div className="research-revenue-chart" aria-label="不同时间的公开收入里程碑,线性长度,非同行排名">{observed.map((o) => <div key={o.id}>
<div><button onClick={() => setSelected(o.company)}>{o.name}</button><strong>{o.bound !== "=" && o.bound}{money(o.value, o.unit)}</strong></div>
{o.unit === "USD" && <span className="research-bar" data-estimate={o.selection === "estimate" || undefined} aria-hidden="true"><i style={{width: `${o.value / Math.max(1, ...observed.filter((v) => v.unit === "USD").map((v) => v.value)) * 100}%`}} /></span>}
<small>{o.kind} · {useLabels[o.selection]} · {o.timing}</small>
</div>)}</div>
<div className="research-table-wrap"><table><caption>当前研究数据中的收入可得性,目录项未逐一检索;未建立同期、同龄、同口径比较组</caption><thead><tr><th>业务分类</th><th>公司披露数</th><th>仅估算数</th><th>仅平台数</th><th>暂无可用数字</th><th>同期均值 / 离散度</th></tr></thead><tbody>{summaries.map((c) => <tr key={c.id}><td><button onClick={() => chooseCategory(c.id)}>{c.name}</button></td><td>{c.self}</td><td>{c.estimate}</td><td>{c.platform}</td><td>{c.unknown}</td><td>条件不足</td></tr>)}</tbody></table></div>
<p className="research-muted">离散度用于筛选值得核查的异常,还需排除公司年龄、口径和披露偏差;不能据此认定财务造假。</p>
</>}
{tab === "sources" && <><p className="research-muted">来源链接保留原始位置。相同 URL 的记录可能属于同一披露,不能按记录数计算独立证据数量。</p><ul className="research-evidence-list">{data.evidence.slice(sourcePage * evidencePageSize, (sourcePage + 1) * evidencePageSize).map((e) => <Evidence key={e.id} item={e} />)}</ul>{data.evidence.length > evidencePageSize && <nav className="research-pagination" aria-label="原始证据分页"><button disabled={sourcePage === 0} onClick={() => setSourcePage((n) => n - 1)}>上一页</button><span>{sourcePage + 1} / {Math.ceil(data.evidence.length / evidencePageSize)}</span><button disabled={(sourcePage + 1) * evidencePageSize >= data.evidence.length} onClick={() => setSourcePage((n) => n + 1)}>下一页</button></nav>}</>}
{tab === "reviews" && <ul className="research-review-list">{data.reviews.map((r) => <li key={r.id}><span className="research-tag">{r.type}</span><h3>{r.company}</h3>{r.scope === "dataset" && <small>全局数据方法核查</small>}{r.scope === "excluded-candidate" && <small>未纳入公司表的候选</small>}<p>{r.summary}</p><p>{r.handling}</p><div>{reviewCompanies(r).map((c) => <button key={c.id} className="research-company-name" onClick={() => setSelected(c.id)}>查看 {c.name} 明细</button>)}</div><div>{r.evidenceIds.map((id) => { const e=data.evidence.find((item) => item.id === id); return e ? <External key={id} url={e.url}>{id}</External> : null; })}</div></li>)}</ul>}
</section>
{selectedCompany && <section id="research-company-detail" ref={detailSection} tabIndex={-1} className="research-detail research-section" aria-label={`${selectedCompany.name}资料明细`}>
<div className="research-detail-heading"><h2>{selectedCompany.name}</h2><button onClick={() => setSelected(null)} aria-label="关闭公司明细">关闭</button></div>
<p><External url={selectedCompany.url}>资料入口</External> {selectedCompany.extraUrl && <External url={selectedCompany.extraUrl}>额外核验入口</External>}</p>
<dl className="research-company-facts"><div><dt>主营业务</dt><dd>{selectedCompany.business}</dd></div><div><dt>样本组别</dt><dd>{selectedCompany.cohort}</dd></div><div><dt>买家</dt><dd>{selectedCompany.buyer}</dd></div><div><dt>收费/交付模式</dt><dd>{selectedCompany.businessModel ?? "待进一步核验"}</dd></div><div><dt>收费方式</dt><dd>{selectedCompany.price}</dd></div><div><dt>交付证据</dt><dd>{selectedCompany.delivery}</dd></div><div><dt>团队口径</dt><dd>{selectedCompany.teamBasis ?? "本轮未核验人数"}</dd></div><div><dt>分类依据</dt><dd>{selectedCompany.classificationBasis ?? "原有个案分类;随研究复核"}</dd></div><div><dt>技术验证证据</dt><dd>{technicalReviewLabels[selectedCompany.technicalReview?.level ?? "unreviewed"]}<p>{selectedCompany.technicalReview?.summary ?? "本轮未形成专项技术评审记录;不表示公司没有技术能力。"}</p>{selectedCompany.technicalReview && <small>评审日期:{selectedCompany.technicalReview.reviewedAt}</small>}{selectedCompany.technicalReview?.testScope && <p>测试范围:{selectedCompany.technicalReview.testScope}</p>}<p>材料可访问仅确认可查看,不证明性能、可靠性或商业交付质量;不同任务不作统一能力排名。</p></dd></div><div><dt>观测主体</dt><dd>{selectedCompany.entityBasis ?? "公司或经营品牌,法律主体未逐一核验"}</dd></div><div><dt>身份与限制</dt><dd>{selectedCompany.notes}</dd></div></dl>
<h3>经营与技术观测</h3>
{!!selectedReviews.length && <details><summary>关联核查记录({selectedReviews.length})</summary><ul>{selectedReviews.map((r) => <li key={r.id}><strong>{r.type}:{r.summary}</strong><p>{r.handling}</p><div>{r.evidenceIds.map((id) => { const item = data.evidence.find((e) => e.id === id); return item ? <External key={id} url={item.url}>{id}</External> : null; })}</div></li>)}</ul></details>}
{selectedObservations.length ? <div className="research-table-wrap"><table><thead><tr><th>指标 / 归属</th><th>原始数值</th><th>数据时点</th><th>用途及限制</th><th>证据</th></tr></thead><tbody>{selectedObservations.map((o) => <tr key={o.id}><td>{o.kind}<small>{o.scope}</small></td><td>{o.bound !== "=" && o.bound}{money(o.value,o.unit)}</td><td>{o.timing}</td><td>{useLabels[o.selection] ?? o.selection}<small>{o.reason}</small></td><td><a href={`#detail-evidence-${o.evidence}`}>{o.evidence}</a></td></tr>)}</tbody></table></div> : <p>本轮尚未找到可记录的量化经营指标。收入保持未知。</p>}
<h3>原始证据</h3><ul className="research-evidence-list">{selectedEvidence.map((e) => <Evidence key={e.id} prefix="detail-evidence" item={e} />)}</ul>
</section>}
<p className="research-footnote">数据版本 {data.version}。当前为首批资料,覆盖、收入定义、财务透明度与商业模式评估将随核验补充。</p>
</div>;
}
@@ -0,0 +1,93 @@
import Link from "next/link";
import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
import type { DocLink } from "@/lib/docs";
import { collectionEntries, collectionIcon, collectionLabel, collectionTone } from "@/lib/collections";
import { Icon } from "./Icon";
export function CategoryNavigation({ docs, current }: { docs: DocLink[]; current?: string }) {
const navigation = useRef<HTMLElement>(null);
const triggers = useRef(new Map<string, HTMLButtonElement>());
const [open, setOpen] = useState<string | null>(null);
const id = useId();
const categories = [...new Set(docs.map((doc) => doc.category))];
const collections = collectionEntries(docs);
const selected = docs.find((doc) => doc.slug === current);
useEffect(() => {
function outside(event: PointerEvent) {
if (event.target instanceof Node && !navigation.current?.contains(event.target)) setOpen(null);
}
function escape(event: globalThis.KeyboardEvent) {
if (event.key !== "Escape" || !open) return;
if (navigation.current?.contains(document.activeElement)) {
event.preventDefault();
triggers.current.get(open)?.focus();
}
setOpen(null);
}
document.addEventListener("pointerdown", outside);
document.addEventListener("keydown", escape);
return () => {
document.removeEventListener("pointerdown", outside);
document.removeEventListener("keydown", escape);
};
}, [open]);
function focusItem(panel: string, last = false) {
requestAnimationFrame(() => {
const links = document.getElementById(panel)?.querySelectorAll<HTMLAnchorElement>("a");
links?.[last ? links.length - 1 : 0]?.focus();
});
}
function move(event: KeyboardEvent<HTMLDivElement>) {
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
const links = [...event.currentTarget.querySelectorAll<HTMLAnchorElement>("a")];
const index = links.indexOf(document.activeElement as HTMLAnchorElement);
if (index < 0) return;
event.preventDefault();
const next = event.key === "Home" ? 0 : event.key === "End" ? links.length - 1 :
(index + (event.key === "ArrowDown" ? 1 : -1) + links.length) % links.length;
links[next]?.focus();
}
return <nav ref={navigation} className="top-nav category-navigation" aria-label="文档分类"
onBlur={(event) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setOpen(null);
}}>
<ul>
<li><Link className="category-home" href="/" aria-current={!current ? "page" : undefined} onClick={() => setOpen(null)}>文档中心</Link></li>
{categories.map((category, index) => {
const panel = `${id}-category-${index}`;
const expanded = open === category;
return <li className="category-menu" key={category}
onPointerEnter={(event) => { if (event.pointerType === "mouse") setOpen(category); }}
onPointerLeave={(event) => { if (event.pointerType === "mouse") setOpen(null); }}>
<button ref={(element) => { if (element) triggers.current.set(category, element); else triggers.current.delete(category); }}
type="button" className="category-trigger" data-category={category}
data-active={selected?.category === category || undefined}
aria-expanded={expanded} aria-controls={panel}
onClick={() => setOpen(expanded ? null : category)}
onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
setOpen(category);
focusItem(panel, event.key === "ArrowUp");
}
}}>
{category}<Icon name="chevron" size={11} />
</button>
<div id={panel} className="category-panel" hidden={!expanded} onKeyDown={move}>
<p className="category-panel-title">{category}</p>
{collections.filter(({entry}) => entry.category === category).map(({name, entry}) => <Link
key={name} href={`/docs/${entry.slug}`} data-tone={collectionTone(name)}
aria-current={current === entry.slug ? "page" : selected?.collection === name ? "true" : undefined}
onClick={() => setOpen(null)}>
<Icon name={collectionIcon(name)} size={19} />
<span><strong>{collectionLabel(name)}</strong><small>{entry.description}</small></span>
</Link>)}
</div>
</li>;
})}
</ul>
</nav>;
}
@@ -0,0 +1,66 @@
import { useId, useState } from "react";
import { ArchitectureFigure } from "./ArchitectureFigure";
type Slide = { source: string; alt: string };
export function FigureGallery({ slides }: { slides: Slide[] }) {
const [active, setActive] = useState(0);
const viewport = useId();
const slide = slides[active];
if (!slide) return null;
function move(offset: number) {
setActive((current) => (current + offset + slides.length) % slides.length);
}
return (
<section
className="figure-gallery"
role="region"
aria-roledescription="轮播"
aria-label="文档配图"
onKeyDown={(event) => {
if ((event.target as HTMLElement).closest("dialog")) return;
if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
event.preventDefault();
move(event.key === "ArrowLeft" ? -1 : 1);
}
}}
>
<div
id={viewport}
role="group"
aria-roledescription="幻灯片"
aria-label={`第 ${active + 1} 张,共 ${slides.length} 张`}
>
<ArchitectureFigure key={slide.source} source={slide.source} alt={slide.alt} />
</div>
<div className="figure-gallery-controls">
<button type="button" className="figure-gallery-arrow" aria-label="上一张图片" aria-controls={viewport} onClick={() => move(-1)}>
<span aria-hidden="true">‹</span>
</button>
<div className="figure-gallery-dots" role="group" aria-label="选择图片">
{slides.map((item, index) => (
<button
key={item.source}
type="button"
className="figure-gallery-dot"
aria-label={`显示第 ${index + 1} 张图片`}
aria-current={index === active ? "true" : undefined}
aria-controls={viewport}
onClick={() => setActive(index)}
>
<span aria-hidden="true" />
</button>
))}
</div>
<button type="button" className="figure-gallery-arrow" aria-label="下一张图片" aria-controls={viewport} onClick={() => move(1)}>
<span aria-hidden="true">›</span>
</button>
</div>
<p className="sr-only" role="status" aria-live="polite" aria-atomic="true">
第 {active + 1} 张,共 {slides.length} 张:{slide.alt}
</p>
</section>
);
}
+20
View File
@@ -0,0 +1,20 @@
import type { CSSProperties } from "react";
// One stroke style for controls and navigation; labels carry the meaning.
export function Icon({ name, size = 18, style }: {
name: "search" | "arrow" | "book" | "code" | "menu" | "close" | "layers" | "nodes" | "chevron";
size?: number; style?: CSSProperties;
}) {
const paths = {
layers: <><path d="m12 3 9 5-9 5-9-5 9-5Zm-9 9 9 5 9-5M3 16l9 5 9-5" /></>,
nodes: <><circle cx="5" cy="6" r="2" /><circle cx="19" cy="6" r="2" /><circle cx="12" cy="19" r="2" /><path d="M7 6h10M6 8l5 9m7-9-5 9" /></>,
chevron: <path d="m9 5 7 7-7 7" />,
search: <><circle cx="10.5" cy="10.5" r="6.5" /><path d="m16 16 4 4" /></>,
arrow: <path d="M5 12h14m-6-6 6 6-6 6" />,
book: <><path d="M12 5c-3-2-6-2-9-1v15c3-1 6-1 9 1 3-2 6-2 9-1V4c-3-1-6-1-9 1Z" /><path d="M12 5v15" /></>,
code: <path d="m8 7-5 5 5 5m8-10 5 5-5 5M14 4l-4 16" />,
menu: <path d="M4 6h16M4 12h16M4 18h16" />,
close: <path d="m6 6 12 12M6 18 18 6" />,
};
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" style={style}>{paths[name]}</svg>;
}
@@ -0,0 +1,87 @@
import { useMemo, useState } from "react";
import type { ResearchSnapshot } from "@/lib/ai-research";
import { groupIncome, platformIncomeSample } from "@/lib/research-statistics";
const usd = (value: number | null) => value === null ? "—" : new Intl.NumberFormat("zh-CN", {
style: "currency", currency: "USD", maximumFractionDigits: 0,
}).format(value);
const percent = (value: number | null) => value === null ? "—" : `${(value * 100).toFixed(1)}%`;
export default function IncomeDistribution({ data, onSelect }: {
data: ResearchSnapshot; onSelect: (id: string) => void;
}) {
const [dateWindow, setDateWindow] = useState("7");
const [year, setYear] = useState("");
const [annualize, setAnnualize] = useState(false);
const [splitModels, setSplitModels] = useState(true);
const [logScale, setLogScale] = useState(true);
const sample = useMemo(() => platformIncomeSample(data, {
windowDays: dateWindow === "all" ? null : Number(dateWindow), foundedYear: year ? Number(year) : undefined, annualize,
}), [data, dateWindow, year, annualize]);
const groups = useMemo(() => groupIncome(sample.points, splitModels).sort((a, b) =>
a.category.localeCompare(b.category) || a.provider.localeCompare(b.provider) || a.model.localeCompare(b.model)), [sample.points, splitModels]);
const categoryGroups = [...new Set(groups.map((group) => group.category))].map((category) => ({
category, rows: groups.filter((group) => group.category === category),
}));
const categories = new Map(data.categories.map((category) => [category.id, category.name]));
const metric = annualize ? "MRR×12参考年化" : "平台MRR";
const values = sample.points.map((point) => point.value);
const minValue = Math.min(...values);
const maxValue = Math.max(1, ...values);
const axisMin = logScale && minValue > 0 && Number.isFinite(minValue) ? 10 ** Math.floor(Math.log10(minValue)) : 0;
const axisMax = Math.max(axisMin * 10, 10 ** Math.ceil(Math.log10(maxValue)));
const scale = logScale ? (value: number) => Math.log10(value + 1) : (value: number) => value;
const left = 250, right = 865;
const x = (value: number) => left + (scale(value) - scale(axisMin)) / (scale(axisMax) - scale(axisMin)) * (right - left);
const ticks = logScale ? [0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000]
.filter((value) => value >= axisMin && value <= axisMax) : [0, .25, .5, .75, 1].map((fraction) => fraction * axisMax);
return <section className="research-distribution" aria-labelledby="income-distribution-title">
<h3 id="income-distribution-title">收入分布与均值敏感性</h3>
<p>单独比较支付平台显示的 USD MRR。每个点是一个产品或业务,法律主体与支付账户的独立性尚未全部核实;这不是行业总体或公司财报样本。</p>
<div className="research-filters">
<label>最后同步日期窗口<select value={dateWindow} onChange={(event) => setDateWindow(event.target.value)}><option value="7">截止日前 7 天内</option><option value="30">截止日前 30 天内</option><option value="90">截止日前 90 天内</option><option value="all">全部已知日期(混合历史)</option></select></label>
<label>资料中的创立年<select value={year} onChange={(event) => setYear(event.target.value)}><option value="">2025 与 2026</option><option value="2025">2025</option><option value="2026">2026</option></select></label>
<label>显示单位<select value={annualize ? "annualized" : "mrr"} onChange={(event) => setAnnualize(event.target.value === "annualized")}><option value="mrr">MRR(美元/月)</option><option value="annualized">MRR×12参考年化(美元/年)</option></select></label>
</div>
<div className="income-options"><label><input type="checkbox" checked={splitModels} onChange={(event) => setSplitModels(event.target.checked)} /> 按收费与交付模式细分</label><label><input type="checkbox" checked={logScale} onChange={(event) => setLogScale(event.target.checked)} /> 对数横轴</label></div>
<p>{splitModels ? "分组:业务类别 × 支付平台 × 收费与交付模式。同一类别下的多行是不同统计组,各自计算均值和中位数。" : "分组:业务类别 × 支付平台。同一平台内的收费模式已合并,不同支付平台仍分别统计。"}</p>
<p className="research-notice">资料截至 {data.asOf},纳入 {sample.points.length} 个产品,另有 {sample.excluded.length} 个 MRR 观测未纳入。{annualize ? "乘12只改变显示单位,不证明全年收入、续约或ARR;CV与相对敏感性不变。" : "MRR不等于近30日收款;平台数据连接也不等于财务审计。"}{dateWindow === "all" && " 当前包含不同时间的历史观测,不能称为同期对照。"}</p>
{sample.points.length ? <>
<figure>
<div className="research-table-wrap"><svg className="income-distribution-chart" viewBox={`0 0 900 ${groups.length * 70 + 65}`} role="group" aria-label={`${metric}分布,${logScale ? "对数" : "线性"}横轴;圆点为产品,竖线为均值,菱形为中位数`}>
{ticks.map((tick) => <g key={tick}><line x1={x(tick)} x2={x(tick)} y1={15} y2={groups.length * 70 + 10} stroke="#dfe6e0" /><text x={x(tick)} y={groups.length * 70 + 35} textAnchor="middle" fontSize="11" fill="#637066">{usd(tick)}</text></g>)}
{groups.map((group, index) => {
const y = index * 70 + 40;
const firstInCategory = index === 0 || groups[index - 1].category !== group.category;
const categoryRowCount = categoryGroups.find((entry) => entry.category === group.category)!.rows.length;
return <g key={group.key} role="group" aria-label={`${categories.get(group.category)},${group.provider},${group.model},${group.stats.n}个产品`}>
{firstInCategory && <>
{index > 0 && <line x1={8} x2={right} y1={y - 34} y2={y - 34} stroke="#dfe6e0" />}
<text x={8} y={y - 8} fontSize="12" fontWeight="600" fill="#202724">{categories.get(group.category)}({categoryRowCount}组)</text>
{categoryRowCount > 1 && <line x1={10} x2={10} y1={y + 3} y2={y + (categoryRowCount - 1) * 70 + 12} stroke="#95b4a6" strokeWidth={2} />}
</>}
<text x={20} y={y + 10} fontSize="10" fill="#637066">{group.provider} · {group.model} · n={group.stats.n}</text>
{group.stats.n < 3 && <text x={20} y={y + 26} fontSize="9" fill="#637066">{group.stats.n === 1 ? "仅1个产品,无法判断组内离散度" : "仅2个产品,不代表领域典型收入"}</text>}
<line x1={x(group.stats.min)} x2={x(group.stats.max)} y1={y} y2={y} stroke="#95b4a6" strokeWidth={2} />
<line x1={x(group.stats.mean)} x2={x(group.stats.mean)} y1={y - 17} y2={y + 17} stroke="#b17725" strokeWidth={3}><title>样本均值 {usd(group.stats.mean)}</title></line>
<path d={`M${x(group.stats.median)},${y - 7} l7,7 l-7,7 l-7,-7 Z`} fill="#8a78ad"><title>样本中位数 {usd(group.stats.median)}</title></path>
{group.points.map((point, position) => <g key={point.company.id} role="button" tabIndex={0} aria-label={`查看${point.company.name},${metric} ${usd(point.value)}`} onClick={() => onSelect(point.company.id)} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); onSelect(point.company.id); } }}>
<title>{point.company.name} · {usd(point.value)} · 数据日期 {point.observation.observedAt}{point.observation.connectionExpired ? " · 连接提示过期" : ""}</title>
<circle cx={x(point.value)} cy={y + ((position % 5) - 2) * 4} r={10} fill="transparent" />
<circle cx={x(point.value)} cy={y + ((position % 5) - 2) * 4} r={4.5} fill="#27745b" stroke="white" />
</g>)}
</g>;
})}
</svg></div>
<figcaption>圆点:产品观测 竖线:样本均值 菱形:样本中位数。业务类别标题下各行按支付平台{splitModels && "及收费与交付模式"}分别统计;n为该组产品数。点击点或下表产品名可看原始证据。</figcaption>
</figure>
<div className="research-table-wrap"><table><caption>{metric}样本统计;每行是类别下的一个统计组,CV使用样本标准差</caption><thead><tr><th scope="col">业务类别</th><th scope="col">支付平台 / 收费模式</th><th scope="col">n</th><th scope="col">均值</th><th scope="col">中位数</th><th scope="col">均值/中位数</th><th scope="col">CV</th><th scope="col">去除最大值后的均值 / 下降幅度</th><th scope="col">产品与限制</th></tr></thead>{categoryGroups.map(({ category, rows }) => <tbody key={category}>{rows.map((group, index) => <tr key={group.key}>
{index === 0 && <th scope="rowgroup" rowSpan={rows.length}>{categories.get(category)}<small>{rows.length}个统计组</small></th>}
<td>{group.provider}<small>{group.model}</small></td><td>{group.stats.n}</td><td>{usd(group.stats.mean)}</td><td>{usd(group.stats.median)}</td><td>{group.stats.meanMedianRatio?.toFixed(2) ?? "—"}</td><td>{group.stats.cv?.toFixed(2) ?? "—"}</td><td>{usd(group.stats.meanWithoutLargest)}<small>{percent(group.stats.largestRemovalDrop)}</small></td>
<td>{group.points.map((point) => <span key={point.company.id}><button className="research-company-name" onClick={() => onSelect(point.company.id)}>{point.company.name}</button>{" "}</span>)}<small>{group.stats.n < 3 ? "样本少于3,不能据此判断领域典型收入。" : "自选的小样本,须结合产品年龄、成本与留存评估。"}</small></td>
</tr>)}</tbody>)}</table></div>
</> : <p className="research-message">当前窗口和创立年份没有符合条件的 MRR 记录。</p>}
<details><summary>统计规则与解释</summary><p>每个产品只取符合条件的最新一条平台 MRR;币种为美元,要求有效数据日期、确定数值及支付来源。公司 ARR、估算、融资、目标和近30日收入均不进入这里。未知值不补零。</p><p>CV=样本标准差÷均值,标准差分母为 n−1;n=1 不算 CV。n=2 时均值必然等于中位数,不能据此认为均值有代表性。较大的均值/中位数差距、CV或移除最大值的变化,仅提示进一步核查样本构成。</p><p>支付商与平台的退款、试用、年付、币种及指标计算可能不同(<a href="https://trustmrr.com/faq" target="_blank" rel="noopener noreferrer">平台方法说明</a>)。不能将 MRR 与收款差异、单个高值或高离散度直接解释为财务造假。比较商业模式还需要毛利、获客成本、留存、人工交付和客户集中度。</p></details>
{sample.excluded.length > 0 && <details><summary>未纳入的 MRR 记录({sample.excluded.length})</summary><ul>{sample.excluded.map(({ observation, reason }) => <li key={observation.id}><button onClick={() => onSelect(observation.company)}>{observation.name}</button>:{usd(observation.value)} / 月,{observation.observedAt ?? "日期未知"};{reason}</li>)}</ul></details>}
</section>;
}
+58 -54
View File
@@ -1,7 +1,10 @@
import Link from "next/link"; import Link from "next/link";
import { CategoryNavigation } from "./CategoryNavigation";
import { Icon } from "@/components/Icon";
import { useEffect, useRef, useState, type ReactNode } from "react"; import { useEffect, useRef, useState, type ReactNode } from "react";
import type { DocLink } from "@/lib/docs"; import type { DocLink } from "@/lib/docs";
import { sectionFor } from "@/lib/navigation"; import { collectionEntries, collectionIcon, collectionLabel, collectionTone } from "@/lib/collections";
export function Brand() { export function Brand() {
return ( return (
@@ -12,10 +15,9 @@ export function Brand() {
<i /> <i />
</span> </span>
<span> <span>
Endor <span className="brand-divider">/</span>{" "}
<strong>Tabularium</strong> <strong>Tabularium</strong>
</span> </span>
<span className="docs-badge">文档</span> <span className="docs-badge">Docs</span>
</Link> </Link>
); );
} }
@@ -28,44 +30,36 @@ export function Navigation({
current?: string; current?: string;
onNavigate?: () => void; onNavigate?: () => void;
}) { }) {
const groups = [...new Set(docs.map((d) => sectionFor(d.slug).group))]; const collection = docs.find((d) => d.slug === current)?.collection;
const scopedDocs = docs.filter((d) => d.collection === collection);
const groups = [...new Set(scopedDocs.map((d) => d.group))];
const collections = collectionEntries(docs);
return ( return (
<nav aria-label="文档导航"> <nav aria-label="文档导航">
<Link {collection ? <>
onClick={onNavigate} <Link className="collection-identity" href={`/docs/${collections.find((c) => c.name === collection)!.entry.slug}`} onClick={onNavigate}>
className={`nav-home ${!current ? "selected" : ""}`} <Icon name={collectionIcon(collection)} size={22} /><span>{collectionLabel(collection)}</span>
href="/" </Link>
> </> : <div className="collection-identity"><Icon name="book" size={22} /><span>文档中心</span></div>}
▦ <span>文档概览</span> {!current && collections.map(({ name, entry }) => <Link
</Link> onClick={onNavigate} className="collection-nav-link" href={`/docs/${entry.slug}`} key={name}
><Icon name={collectionIcon(name)} size={18} /><span>{collectionLabel(name)}</span><Icon name="chevron" size={13} /></Link>)}
{groups.map((group) => ( {groups.map((group) => (
<div className="nav-group" key={group}> <div className="nav-group" key={group}>
<p>{group}</p> <p>{group === collection ? "章节目录" : group}</p>
{docs {scopedDocs.filter((d) => d.group === group).map((d) => (
.filter((d) => sectionFor(d.slug).group === group) <Link onClick={onNavigate} aria-current={d.slug === current ? "page" : undefined}
.map((d) => ( className="nav-item" href={`/docs/${d.slug}`} key={d.slug}>
<Link <span>{d.slug.endsWith("/overview") ? "概览" : d.title.replace("(草案)", "").replace(/^\d+\s*·\s*/, "")}</span>
onClick={onNavigate} {d.draft && <span className="tiny-dot" aria-label="草案" />}
aria-current={d.slug === current ? "page" : undefined} </Link>
className="nav-item" ))}
href={`/docs/${d.slug}`}
key={d.slug}
>
{d.title}
{sectionFor(d.slug).label.includes("草案") && (
<span className="tiny-dot" aria-label="草案" />
)}
</Link>
))}
</div> </div>
))} ))}
<div className="nav-note">
<span className="status-dot" /> 与代码一起演进
<p>文字、设计与图形的共同档案。</p>
</div>
</nav> </nav>
); );
} }
export function Shell({ export function Shell({
docs, docs,
current, current,
@@ -79,18 +73,34 @@ export function Shell({
const input = useRef<HTMLInputElement>(null); const input = useRef<HTMLInputElement>(null);
const trigger = useRef<HTMLButtonElement>(null); const trigger = useRef<HTMLButtonElement>(null);
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const [searchDocs, setSearchDocs] = useState(docs);
const [searchLoaded, setSearchLoaded] = useState(false);
const [searchStatus, setSearchStatus] = useState("");
const [selected, setSelected] = useState(0); const [selected, setSelected] = useState(0);
const [menu, setMenu] = useState(false); const [menu, setMenu] = useState(false);
const results = docs.filter((d) => const collection = docs.find((d) => d.slug === current)?.collection;
`${d.title} ${d.searchText}` const results = searchDocs.filter((d) =>
(!collection || d.collection === collection) &&
`${d.title} ${d.description} ${d.searchText ?? ""}`
.toLocaleLowerCase() .toLocaleLowerCase()
.includes(query.trim().toLocaleLowerCase()), .includes(query.trim().toLocaleLowerCase()),
); );
function openSearch() { async function openSearch() {
setQuery(""); setQuery("");
setSelected(0); setSelected(0);
dialog.current?.showModal(); dialog.current?.showModal();
input.current?.focus(); input.current?.focus();
if (searchLoaded) return;
setSearchStatus("正在加载全文索引…");
try {
const response = await fetch("/api/search");
if (!response.ok) throw new Error("Search unavailable");
setSearchDocs(await response.json());
setSearchLoaded(true);
setSearchStatus("");
} catch {
setSearchStatus("全文搜索暂时不可用,当前仅搜索标题和摘要。关闭后重新打开可重试。");
}
} }
function closeSearch() { function closeSearch() {
dialog.current?.close(); dialog.current?.close();
@@ -100,35 +110,28 @@ export function Shell({
function keyboard(e: KeyboardEvent) { function keyboard(e: KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
e.preventDefault(); e.preventDefault();
dialog.current?.showModal(); trigger.current?.click();
input.current?.focus();
} }
} }
document.addEventListener("keydown", keyboard); document.addEventListener("keydown", keyboard);
return () => document.removeEventListener("keydown", keyboard); return () => document.removeEventListener("keydown", keyboard);
}, []); }, []);
return ( return (
<> <div className="docs-shell" data-tone={collectionTone(collection)}>
<a className="skip-link" href="#content"> <a className="skip-link" href="#content">
跳到正文 跳到正文
</a> </a>
<header className="site-header"> <header className="site-header">
<Brand /> <Brand />
<nav className="top-nav" aria-label="主导航"> <CategoryNavigation docs={docs} current={current} />
<Link href="/">文档概览</Link>
<Link href="/docs/00-endor-concepts-draft">架构设计</Link>
<a href="https://gitea.entroia.com/Zayden-Jung/endorphin-tabularium-docs">
仓库 ↗
</a>
</nav>
<button <button
ref={trigger} ref={trigger}
className="search-trigger" className="search-trigger"
aria-label="搜索文档" aria-label="搜索文档"
onClick={openSearch} onClick={openSearch}
> >
<span aria-hidden="true">⌕</span> <Icon name="search" />
<span>搜索文档…</span> <span>{collection ? `搜索${collectionLabel(collection)}…` : "搜索全部文档…"}</span>
<kbd>⌘ K</kbd> <kbd>⌘ K</kbd>
</button> </button>
<button <button
@@ -154,7 +157,7 @@ export function Shell({
aria-expanded={menu} aria-expanded={menu}
aria-controls="mobile-navigation" aria-controls="mobile-navigation"
> >
☰ <span>文档目录</span> <Icon name={menu ? "close" : "menu"} size={16} /> <span>{collection ? collectionLabel(collection) : "全部文档"}</span>
<span>{menu ? "−" : "+"}</span> <span>{menu ? "−" : "+"}</span>
</button> </button>
</div> </div>
@@ -178,11 +181,11 @@ export function Shell({
onClose={() => trigger.current?.focus()} onClose={() => trigger.current?.focus()}
> >
<div className="search-input-row"> <div className="search-input-row">
<span aria-hidden="true">⌕</span> <Icon name="search" />
<input <input
ref={input} ref={input}
value={query} value={query}
placeholder="搜索文档、命令或概念…" placeholder={collection ? `搜索${collectionLabel(collection)}的内容…` : "搜索全部文档、命令或概念…"}
aria-label="搜索文档内容" aria-label="搜索文档内容"
aria-controls="search-results" aria-controls="search-results"
onChange={(e) => { onChange={(e) => {
@@ -214,6 +217,7 @@ export function Shell({
Esc Esc
</button> </button>
</div> </div>
{searchStatus && <p className="search-status" role="status">{searchStatus}</p>}
<div id="search-results" className="search-results"> <div id="search-results" className="search-results">
<p className="eyebrow" role="status"> <p className="eyebrow" role="status">
{query ? `${results.length} 篇匹配文档` : "浏览文档"} {query ? `${results.length} 篇匹配文档` : "浏览文档"}
@@ -228,16 +232,16 @@ export function Shell({
key={d.slug} key={d.slug}
href={`/docs/${d.slug}`} href={`/docs/${d.slug}`}
> >
<span>{sectionFor(d.slug).group}</span> <span>{d.group}</span>
<strong> <strong>
{d.title} <span aria-hidden="true">↗</span> {d.title} <span aria-hidden="true">↗</span>
</strong> </strong>
<small>{sectionFor(d.slug).description}</small> <small>{d.description}</small>
</Link> </Link>
))} ))}
{!results.length && ( {!results.length && (
<p className="empty-search"> <p className="empty-search">
没有找到相关文档。试试「节点」「SVG」或「pnpm」。 没有找到相关内容,请尝试其他关键词。
</p> </p>
)} )}
</div> </div>
@@ -245,6 +249,6 @@ export function Shell({
↑ ↓ 选择 <span>Enter 打开 · Esc 关闭</span> ↑ ↓ 选择 <span>Enter 打开 · Esc 关闭</span>
</div> </div>
</dialog> </dialog>
</> </div>
); );
} }
+87
View File
@@ -0,0 +1,87 @@
import seed from "../../../../content/research/ai-companies.seed.json";
import { createHash } from "node:crypto";
import { openSiteDatabase } from "./site-database";
import { validateResearch, type ResearchSnapshot } from "./ai-research";
// Each release selects an immutable research revision. New revisions are added
// transactionally, preserving both earlier research and all authentication rows.
export function readResearchSnapshot(snapshot = seed as ResearchSnapshot): ResearchSnapshot {
validateResearch(snapshot);
const digest = createHash("sha256").update(JSON.stringify(snapshot)).digest("hex");
const db = openSiteDatabase();
try {
db.exec(`
CREATE TABLE IF NOT EXISTS research_datasets (
id TEXT PRIMARY KEY, as_of TEXT NOT NULL, metadata TEXT NOT NULL, content_hash TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS research_categories (
dataset_id TEXT NOT NULL REFERENCES research_datasets(id),
id TEXT NOT NULL, payload TEXT NOT NULL, PRIMARY KEY(dataset_id,id)
);
CREATE TABLE IF NOT EXISTS research_companies (
dataset_id TEXT NOT NULL, id TEXT NOT NULL, category_id TEXT NOT NULL,
name TEXT NOT NULL, founded_year INTEGER, team_size INTEGER,
revenue_status TEXT NOT NULL, payload TEXT NOT NULL,
PRIMARY KEY(dataset_id,id),
FOREIGN KEY(dataset_id,category_id) REFERENCES research_categories(dataset_id,id)
);
CREATE TABLE IF NOT EXISTS research_evidence (
dataset_id TEXT NOT NULL REFERENCES research_datasets(id),
id TEXT NOT NULL, url TEXT NOT NULL, payload TEXT NOT NULL,
PRIMARY KEY(dataset_id,id)
);
CREATE TABLE IF NOT EXISTS research_observations (
dataset_id TEXT NOT NULL, id TEXT NOT NULL, company_id TEXT NOT NULL,
evidence_id TEXT NOT NULL, kind TEXT NOT NULL, amount REAL NOT NULL,
unit TEXT NOT NULL, record_use TEXT NOT NULL, payload TEXT NOT NULL,
PRIMARY KEY(dataset_id,id),
FOREIGN KEY(dataset_id,company_id) REFERENCES research_companies(dataset_id,id),
FOREIGN KEY(dataset_id,evidence_id) REFERENCES research_evidence(dataset_id,id)
);
CREATE TABLE IF NOT EXISTS research_reviews (
dataset_id TEXT NOT NULL REFERENCES research_datasets(id),
id TEXT NOT NULL, payload TEXT NOT NULL, PRIMARY KEY(dataset_id,id)
);
`);
// The database transaction also serializes first requests from two workers.
db.exec("BEGIN IMMEDIATE");
try {
const exists = db.prepare("SELECT content_hash FROM research_datasets WHERE id=?")
.get(snapshot.version) as { content_hash: string } | undefined;
if (exists && exists.content_hash !== digest)
throw new Error("Research data changed without a new revision identifier");
if (!exists) {
const { categories, companies, observations, evidence, reviews, ...metadata } = snapshot;
db.prepare("INSERT INTO research_datasets VALUES (?,?,?,?)")
.run(snapshot.version, snapshot.asOf, JSON.stringify(metadata), digest);
const insertCategory = db.prepare("INSERT INTO research_categories VALUES (?,?,?)");
for (const row of categories) insertCategory.run(snapshot.version, row.id, JSON.stringify(row));
const insertCompany = db.prepare("INSERT INTO research_companies VALUES (?,?,?,?,?,?,?,?)");
for (const row of companies) insertCompany.run(snapshot.version, row.id, row.cat,
row.name, row.year, row.team, row.revenueStatus, JSON.stringify(row));
const insertEvidence = db.prepare("INSERT INTO research_evidence VALUES (?,?,?,?)");
for (const row of evidence) insertEvidence.run(snapshot.version, row.id, row.url, JSON.stringify(row));
const insertObservation = db.prepare("INSERT INTO research_observations VALUES (?,?,?,?,?,?,?,?,?)");
for (const row of observations) insertObservation.run(snapshot.version, row.id, row.company,
row.evidence, row.kind, row.value, row.unit, row.selection, JSON.stringify(row));
const insertReview = db.prepare("INSERT INTO research_reviews VALUES (?,?,?)");
for (const row of reviews) insertReview.run(snapshot.version, row.id, JSON.stringify(row));
}
db.exec("COMMIT");
} catch (error) {
db.exec("ROLLBACK");
throw error;
}
const meta = db.prepare("SELECT metadata FROM research_datasets WHERE id=?").get(snapshot.version) as { metadata: string };
// All displayed records come from the site database, not the seed arrays.
const rows = (table: string) => (db.prepare(
`SELECT payload FROM ${table} WHERE dataset_id=? ORDER BY id`,
).all(snapshot.version) as { payload: string }[]).map((r) => JSON.parse(r.payload));
const stored: ResearchSnapshot = { ...JSON.parse(meta.metadata),
categories: rows("research_categories"), companies: rows("research_companies"),
observations: rows("research_observations"), evidence: rows("research_evidence"),
reviews: rows("research_reviews") };
validateResearch(stored);
return stored;
} finally { db.close(); }
}
+180
View File
@@ -0,0 +1,180 @@
export type ResearchCategory = { id: string; name: string; description: string };
export const technicalReviewLabels = {
unreviewed: "技术证据尚未专项评审",
description: "已读技术自述",
"public-artifact": "公开代码/模型材料可访问",
"independent-test": "有第三方独立评测记录",
};
export type ResearchCompany = {
id: string; name: string; url: string; cat: string; year: number | null;
team: number | null; teamBound?: ">" | "≥"; location: string | null; business: string; buyer: string;
delivery: string; notes: string; cohort: string; teamBasis: string | null;
price: string; stage: string; sourceType: string; evidenceIds: string[];
revenueStatus: "self" | "estimate" | "platform" | "unknown";
extraUrl?: string; pricingEvidence?: string;
businessModel?: string; entityBasis?: string;
profileOnly?: boolean; classificationBasis?: string; directoryTags?: string[];
directoryOrigin?: "yc-2025-2026";
technicalReview?: {
level: "description" | "public-artifact" | "independent-test";
reviewedAt: string; summary: string; evidenceIds: string[]; testScope?: string;
};
};
export type ResearchObservation = {
id: string; company: string; name: string; kind: string; value: number;
unit: string; timing: string; evidence: string; scope: string;
selection: string; reason: string; bound: string; comparisonGroup: string | null;
metric?: "mrr" | "arr" | "revenue-30d" | "annualized-revenue";
observedAt?: string; provider?: string; connectionExpired?: boolean; origin?: "payment-platform";
};
export type ResearchEvidence = {
id: string; companyId: string | null; title: string; url: string;
publishedAt: string | null; accessedAt: string; kind: string;
summary: string; limitation: string;
};
export type ResearchReview = {
id: string; type: string; company: string; summary: string;
evidenceIds: string[]; handling: string;
scope?: "companies" | "dataset" | "excluded-candidate"; companyIds?: string[];
};
export type ResearchCoverage = {
source: string; accessedAt: string; candidateRecords: number; profilesRead: number;
matchingProfiles: number; existingProfiles: number; newProfiles: number;
otherOrMissingYear: number; unclearAI: number; dateConflicts: number; failedProfiles: number;
discoverySha256: string;
};
export type ResearchCandidateBatch = {
id: string; sourceId: string; url: string; accessedAt: string; scope: string; complete: boolean;
records: {
id: string; name: string; url: string | null; categoryId: string;
kind: "product" | "company" | "promotion"; profileStatus: "readable" | "unavailable" | "archive-only";
status: "pending-year" | "linked" | "existing-outside-cohort" | "outside-cohort" | "promotion";
companyId?: string; evidenceIds?: string[]; note: string;
}[];
};
export type ResearchSnapshot = {
version: string; asOf: string; scope: string; limitations: string[];
categories: ResearchCategory[]; companies: ResearchCompany[];
observations: ResearchObservation[]; evidence: ResearchEvidence[];
reviews: ResearchReview[]; coverage?: ResearchCoverage; candidateBatches?: ResearchCandidateBatch[];
directoryRechecks?: {
ycId: number; originalStatus: "ai-unclear" | "year-outside-or-missing" | "date-conflict";
companyId: string; reviewedAt: string; evidenceIds: string[]; reason: string;
}[];
};
export function evidenceUrl(value: string): string | undefined {
try {
const url = new URL(value);
return ["https:", "http:"].includes(url.protocol) ? url.href : undefined;
} catch { return undefined; }
}
export function validateResearch(snapshot: ResearchSnapshot) {
const unique = (values: string[], label: string) => {
if (new Set(values).size !== values.length || values.some((v) => !v))
throw new Error(`Duplicate or missing research ${label}`);
return new Set(values);
};
if (!snapshot.version || !/^\d{4}-\d{2}-\d{2}$/.test(snapshot.asOf))
throw new Error("Invalid research dataset metadata");
const categories = unique(snapshot.categories.map((c) => c.id), "categories");
const companies = unique(snapshot.companies.map((c) => c.id), "companies");
const evidence = unique(snapshot.evidence.map((e) => e.id), "evidence");
unique(snapshot.observations.map((o) => o.id), "observations");
unique(snapshot.reviews.map((r) => r.id), "reviews");
for (const c of snapshot.companies) {
const technical = c.technicalReview;
if (technical && (!["description", "public-artifact", "independent-test"].includes(technical.level) ||
!/^\d{4}-\d{2}-\d{2}$/.test(technical.reviewedAt) ||
Number.isNaN(Date.parse(technical.reviewedAt)) ||
new Date(technical.reviewedAt).toISOString().slice(0, 10) !== technical.reviewedAt ||
technical.reviewedAt > snapshot.asOf || !technical.summary.trim() ||
!technical.evidenceIds.length || technical.evidenceIds.some((id) => !evidence.has(id)) ||
(technical.level === "independent-test" && !technical.testScope?.trim())))
throw new Error(`Invalid technical review: ${c.id}`);
if (c.profileOnly && (c.revenueStatus !== "unknown" || !c.classificationBasis))
throw new Error(`Invalid profile-only research record: ${c.id}`);
if (c.directoryOrigin && (c.directoryOrigin !== "yc-2025-2026" || !/^YC\d+$/.test(c.id)))
throw new Error(`Invalid research directory origin: ${c.id}`);
if (!categories.has(c.cat) || !evidenceUrl(c.url) ||
c.evidenceIds.some((id) => !evidence.has(id)) ||
(c.pricingEvidence && !evidence.has(c.pricingEvidence)))
throw new Error(`Invalid research company reference: ${c.id}`);
}
for (const e of snapshot.evidence) {
if (!evidenceUrl(e.url) || (e.companyId && !companies.has(e.companyId)))
throw new Error(`Invalid research evidence: ${e.id}`);
}
for (const o of snapshot.observations) {
if (!companies.has(o.company) || !evidence.has(o.evidence) ||
!Number.isFinite(o.value))
throw new Error(`Invalid research observation: ${o.id}`);
}
unique((snapshot.candidateBatches ?? []).map((b) => b.id), "candidate batches");
unique((snapshot.candidateBatches ?? []).flatMap((b) => b.records.map((r) => r.id)), "candidates");
for (const batch of snapshot.candidateBatches ?? []) {
if (!/^S\d{2}$/.test(batch.sourceId) || !evidenceUrl(batch.url) || !batch.scope.trim() ||
typeof batch.complete !== "boolean" || !/^\d{4}-\d{2}-\d{2}$/.test(batch.accessedAt) ||
Number.isNaN(Date.parse(batch.accessedAt)) ||
new Date(batch.accessedAt).toISOString().slice(0, 10) !== batch.accessedAt ||
batch.accessedAt > snapshot.asOf)
throw new Error(`Invalid research candidate batch: ${batch.id}`);
for (const row of batch.records) {
const linked = ["linked", "existing-outside-cohort"].includes(row.status);
if (!row.name.trim() || !row.note.trim() || !categories.has(row.categoryId) ||
!["product", "company", "promotion"].includes(row.kind) ||
!["readable", "unavailable", "archive-only"].includes(row.profileStatus) ||
!["pending-year", "linked", "existing-outside-cohort", "outside-cohort", "promotion"].includes(row.status) ||
(row.kind !== "promotion" && (!row.url || !evidenceUrl(row.url))) ||
(row.url !== null && !evidenceUrl(row.url)) ||
linked !== !!row.companyId || (row.companyId && !companies.has(row.companyId)) ||
(row.kind === "promotion") !== (row.status === "promotion") ||
(row.evidenceIds ?? []).some((id) => !evidence.has(id)) ||
(row.status === "outside-cohort" && !row.evidenceIds?.length))
throw new Error(`Invalid research candidate: ${row.id}`);
}
}
const coverage = snapshot.coverage;
unique((snapshot.directoryRechecks ?? []).map((row) => String(row.ycId)), "directory rechecks");
for (const row of snapshot.directoryRechecks ?? []) {
if (!Number.isSafeInteger(row.ycId) || row.ycId <= 0 || !companies.has(row.companyId) ||
!["ai-unclear", "year-outside-or-missing", "date-conflict"].includes(row.originalStatus) ||
!/^\d{4}-\d{2}-\d{2}$/.test(row.reviewedAt) || Number.isNaN(Date.parse(row.reviewedAt)) ||
new Date(row.reviewedAt).toISOString().slice(0, 10) !== row.reviewedAt || row.reviewedAt > snapshot.asOf ||
!row.reason.trim() || !row.evidenceIds.length || row.evidenceIds.some((id) => !evidence.has(id)))
throw new Error(`Invalid directory recheck: ${row.ycId}`);
}
if (coverage && (coverage.profilesRead + coverage.failedProfiles !== coverage.candidateRecords ||
coverage.matchingProfiles !== coverage.existingProfiles + coverage.newProfiles ||
coverage.matchingProfiles + coverage.otherOrMissingYear + coverage.unclearAI + coverage.dateConflicts !== coverage.profilesRead ||
snapshot.companies.filter((c) => c.profileOnly || c.directoryOrigin === "yc-2025-2026").length !== coverage.newProfiles || !evidenceUrl(coverage.source)))
throw new Error("Invalid research coverage accounting");
for (const r of snapshot.reviews)
if (r.evidenceIds.some((id) => !evidence.has(id)) ||
(r.companyIds && (new Set(r.companyIds).size !== r.companyIds.length ||
r.companyIds.some((id) => !companies.has(id)))) ||
(r.scope && !["companies", "dataset", "excluded-candidate"].includes(r.scope)) ||
(r.scope === "companies" && !r.companyIds?.length) ||
(r.scope && r.scope !== "companies" && !!r.companyIds?.length))
throw new Error(`Invalid research review: ${r.id}`);
}
/** Explicit reviewed associations take priority; older revisions use evidence ownership. */
export function reviewCompanyIds(snapshot: ResearchSnapshot, review: ResearchReview): string[] {
if (review.companyIds) return review.companyIds;
const evidenceIds = new Set(review.evidenceIds);
return [...new Set(snapshot.evidence.flatMap((e) =>
e.companyId && evidenceIds.has(e.id) ? [e.companyId] : []))];
}
export function categorySummary(snapshot: ResearchSnapshot) {
return snapshot.categories.map((category) => {
const companies = snapshot.companies.filter((c) => c.cat === category.id);
return { ...category, count: companies.length,
self: companies.filter((c) => c.revenueStatus === "self").length,
platform: companies.filter((c) => c.revenueStatus === "platform").length,
estimate: companies.filter((c) => c.revenueStatus === "estimate").length,
unknown: companies.filter((c) => c.revenueStatus === "unknown").length };
});
}
+2 -8
View File
@@ -1,14 +1,8 @@
import { chmodSync } from "node:fs";
import { dirname, join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { authId, matchingStep, type AuthConfig } from "./auth"; import { authId, matchingStep, type AuthConfig } from "./auth";
import { openSiteDatabase } from "./site-database";
function database() { function database() {
const configFile = process.env.AUTH_CONFIG_FILE; const db = openSiteDatabase();
if (!configFile) throw new Error("Authentication is not configured");
const file = join(dirname(configFile), "login-state.sqlite");
const db = new DatabaseSync(file);
chmodSync(file, 0o600);
db.exec(`PRAGMA busy_timeout=5000; db.exec(`PRAGMA busy_timeout=5000;
CREATE TABLE IF NOT EXISTS login_state ( CREATE TABLE IF NOT EXISTS login_state (
id TEXT PRIMARY KEY, window_start INTEGER NOT NULL, id TEXT PRIMARY KEY, window_start INTEGER NOT NULL,
+24
View File
@@ -0,0 +1,24 @@
import type { DocLink } from "@/lib/docs";
export function collectionLabel(name: string) {
return name.replace(/ 文档$| 源码教程$|问题集$/g, "");
}
export function collectionTone(name?: string) {
if (name?.includes("Pretext")) return "blue";
if (name?.includes("语言设计")) return "violet";
if (name?.includes("垃圾回收")) return "amber";
return "green";
}
export function collectionIcon(name?: string): "book" | "code" | "layers" | "nodes" {
if (name?.includes("Pretext")) return "code";
if (name?.includes("语言设计")) return "layers";
if (name?.includes("垃圾回收")) return "nodes";
return "book";
}
export function collectionEntries(docs: DocLink[]) {
return [...new Set(docs.map((doc) => doc.collection))].map((name) => {
const items = docs.filter((doc) => doc.collection === name);
const entry = items.find((doc) => doc.slug.endsWith("/overview")) ?? items[0];
return { name, entry, count: items.length };
});
}
+229 -19
View File
@@ -1,27 +1,237 @@
import fs from "node:fs/promises"; import { randomUUID, createHash } from "node:crypto";
import path from "node:path"; import { openSiteDatabase } from "./site-database";
const directory = path.resolve(process.cwd(), "../../content/docs"); export type DocLink = {
const validSlug = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; slug: string; sourceSlug: string; category: string; title: string; searchText?: string;
group: string; collection: string; description: string; draft: boolean; featured: boolean;
export type DocLink = { slug: string; title: string; searchText: string }; revision: number;
};
export type Doc = DocLink & { content: string }; export type Doc = DocLink & { content: string };
export type DocInput = Omit<Doc, "revision" | "searchText">;
export type DocumentExport = { format: "tabularium-documents-v1"; documents: Doc[] };
export class DocumentValidationError extends Error {}
export class DocumentConflictError extends Error {}
export type DocumentReceipt = Pick<Doc, "slug" | "sourceSlug" | "revision">;
export const validSlug = /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\/[a-z0-9]+(?:-[a-z0-9]+)*)*$/;
function database() {
const db = openSiteDatabase();
db.exec(`
CREATE TABLE IF NOT EXISTS documents (
id TEXT PRIMARY KEY, slug TEXT NOT NULL UNIQUE, source_slug TEXT NOT NULL UNIQUE,
revision INTEGER NOT NULL, payload TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS document_aliases (
alias TEXT PRIMARY KEY, document_id TEXT NOT NULL REFERENCES documents(id)
);
CREATE TABLE IF NOT EXISTS document_revisions (
document_id TEXT NOT NULL REFERENCES documents(id), revision INTEGER NOT NULL,
payload TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY(document_id, revision)
);
CREATE TABLE IF NOT EXISTS document_write_requests (
namespace TEXT NOT NULL, request_id TEXT NOT NULL, digest TEXT NOT NULL,
response TEXT NOT NULL, PRIMARY KEY(namespace, request_id)
);
CREATE TABLE IF NOT EXISTS document_imports (
digest TEXT PRIMARY KEY, document_count INTEGER NOT NULL, created_at TEXT NOT NULL
);
`);
return db;
}
export function validateDocument(input: DocInput): void {
if (!input || typeof input !== "object") throw new DocumentValidationError("Invalid document");
for (const key of ["slug", "sourceSlug"] as const)
if (typeof input[key] !== "string" || !validSlug.test(input[key])) throw new DocumentValidationError(`Invalid ${key}`);
if (input.slug.split("/").some((part) => /^\d+-/.test(part))) throw new DocumentValidationError("Use a semantic public slug");
for (const key of ["title", "category", "collection", "group"] as const)
if (typeof input[key] !== "string" || !input[key].trim()) throw new DocumentValidationError(`Missing ${key}`);
if (typeof input.content !== "string" || typeof input.description !== "string" ||
typeof input.draft !== "boolean" || typeof input.featured !== "boolean") throw new DocumentValidationError("Invalid document fields");
if (input.content.length > 2_000_000) throw new DocumentValidationError("Document exceeds content limit");
const images = [
...input.content.matchAll(/!\[[^\]]*\]\(<?([^\s)>]+)/g),
...input.content.matchAll(/<img\b[^>]*\bsrc=["']([^"']+)/gi),
];
if (images.some(([, source]) => /\.(?:png|jpe?g|tiff?|bmp)(?:[?#]|$)/i.test(source)))
throw new DocumentValidationError("Use compressed WebP images instead of original rasters");
}
function write(db: ReturnType<typeof database>, input: DocInput, expectedRevision: number): Doc {
validateDocument(input);
const existing = db.prepare("SELECT id, revision FROM documents WHERE source_slug=?")
.get(input.sourceSlug) as { id: string; revision: number } | undefined;
if ((existing?.revision ?? 0) !== expectedRevision) throw new DocumentConflictError("Document revision conflict");
const id = existing?.id ?? randomUUID();
const doc: Doc = { slug: input.slug, sourceSlug: input.sourceSlug, category: input.category,
title: input.title, group: input.group, collection: input.collection, description: input.description,
draft: input.draft, featured: input.featured, content: input.content, revision: expectedRevision + 1 };
const payload = JSON.stringify(doc);
// Reserve both canonical and historical names before updating any rows.
for (const alias of new Set([doc.slug, doc.sourceSlug])) {
const prior = db.prepare("SELECT document_id FROM document_aliases WHERE alias=?")
.get(alias) as { document_id: string } | undefined;
if (prior && prior.document_id !== id) throw new DocumentConflictError(`Document alias collision: ${alias}`);
}
db.prepare(`INSERT INTO documents VALUES (?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET
slug=excluded.slug, revision=excluded.revision, payload=excluded.payload`)
.run(id, doc.slug, doc.sourceSlug, doc.revision, payload);
for (const alias of new Set([doc.slug, doc.sourceSlug]))
db.prepare("INSERT OR IGNORE INTO document_aliases VALUES (?,?)").run(alias, id);
db.prepare("INSERT INTO document_revisions VALUES (?,?,?,?)")
.run(id, doc.revision, payload, new Date().toISOString());
return doc;
}
export function saveDocument(input: DocInput, expectedRevision: number): Doc {
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) throw new DocumentValidationError("Provide expected revision");
const db = database();
try {
db.exec("BEGIN IMMEDIATE");
try { const doc = write(db, input, expectedRevision); db.exec("COMMIT"); return doc; }
catch (error) { db.exec("ROLLBACK"); throw error; }
} finally { db.close(); }
}
export function readDocument(slug: string): Doc | null {
if (!validSlug.test(slug)) return null;
const db = database();
try {
const row = db.prepare(`SELECT d.payload FROM documents d JOIN document_aliases a
ON a.document_id=d.id WHERE a.alias=?`).get(slug) as { payload: string } | undefined;
return row ? JSON.parse(row.payload) as Doc : null;
} finally { db.close(); }
}
export function allDocuments(): Doc[] {
const db = database();
try {
return (db.prepare("SELECT payload FROM documents ORDER BY source_slug").all() as { payload: string }[])
.map((row) => JSON.parse(row.payload) as Doc);
} finally { db.close(); }
}
export async function readDoc(slug: string): Promise<Doc> { export async function readDoc(slug: string): Promise<Doc> {
if (!validSlug.test(slug)) throw new Error("Invalid document slug"); const doc = readDocument(slug);
const content = await fs.readFile(path.join(directory, `${slug}.md`), "utf8"); if (!doc) throw Error("Document not found");
const title = content.match(/^# (.+)$/m)?.[1]?.trim() ?? slug; return doc;
return { slug, title, content, searchText: content };
} }
export async function listDocs(): Promise<DocLink[]> { export async function listDocs(): Promise<DocLink[]> {
const files = (await fs.readdir(directory)) return allDocuments().map(({ content: _, ...doc }) => { void _; return doc; });
.filter((file) => file.endsWith(".md") && validSlug.test(file.slice(0, -3))) }
.sort();
return Promise.all( // Explicit, atomic bootstrap only. Runtime reads never import repository data.
files.map(async (file) => { export function importDocuments(bundle: DocumentExport, onlyIfEmpty = false): number {
const { slug, title, searchText } = await readDoc(file.slice(0, -3)); if (bundle?.format !== "tabularium-documents-v1" || !Array.isArray(bundle.documents) || !bundle.documents.length)
return { slug, title, searchText }; throw Error("Invalid or empty document export");
}), bundle.documents.forEach(validateDocument);
); const digest = createHash("sha256").update(JSON.stringify(bundle)).digest("hex");
const db = database();
try {
db.exec("BEGIN IMMEDIATE");
try {
const imported = db.prepare("SELECT digest FROM document_imports WHERE digest=?").get(digest);
if (imported) { db.exec("COMMIT"); return 0; }
const count = (db.prepare("SELECT COUNT(*) AS n FROM documents").get() as { n: number }).n;
if (count) {
if (!onlyIfEmpty) throw Error("Bootstrap requires an empty document database");
db.exec("COMMIT"); return 0;
}
for (const doc of bundle.documents) write(db, doc, 0);
db.prepare("INSERT INTO document_imports VALUES (?,?,?)").run(digest, bundle.documents.length, new Date().toISOString());
db.exec("COMMIT"); return bundle.documents.length;
} catch (error) { db.exec("ROLLBACK"); throw error; }
} finally { db.close(); }
}
export function documentHistory(sourceSlug: string): Doc[] {
const db = database();
try {
return (db.prepare(`SELECT r.payload FROM document_revisions r JOIN documents d
ON r.document_id=d.id WHERE d.source_slug=? ORDER BY r.revision`).all(sourceSlug) as { payload: string }[])
.map((row) => JSON.parse(row.payload) as Doc);
} finally { db.close(); }
}
// API batches commit entirely or not at all; receipts make lost-response retries safe.
export function saveDocumentBatch(documents: Doc[], request?: { namespace: string; id: string }) {
if (!Array.isArray(documents) || !documents.length || documents.length > 100)
throw new DocumentValidationError("Provide 1 to 100 documents");
const seen = new Set<string>();
for (const doc of documents) {
validateDocument(doc);
if (!Number.isSafeInteger(doc.revision) || doc.revision < 0)
throw new DocumentValidationError("Provide expected revision");
if (seen.has(doc.sourceSlug)) throw new DocumentValidationError("Duplicate sourceSlug in batch");
seen.add(doc.sourceSlug);
}
if (request && (!request.namespace || !/^[A-Za-z0-9._:-]{1,128}$/.test(request.id)))
throw new DocumentValidationError("Invalid Idempotency-Key");
const digest = createHash("sha256").update(JSON.stringify(documents)).digest("hex");
const db = database();
try {
db.exec("BEGIN IMMEDIATE");
try {
if (request) {
const prior = db.prepare("SELECT digest,response FROM document_write_requests WHERE namespace=? AND request_id=?")
.get(request.namespace, request.id) as { digest: string; response: string } | undefined;
if (prior) {
if (prior.digest !== digest) throw new DocumentConflictError("Idempotency-Key was used with different content");
db.exec("COMMIT");
return { documents: JSON.parse(prior.response) as DocumentReceipt[], replayed: true };
}
}
const receipts = documents.map((input) => {
const { slug, sourceSlug, revision } = write(db, input, input.revision);
return { slug, sourceSlug, revision };
});
if (request) db.prepare("INSERT INTO document_write_requests VALUES (?,?,?,?)")
.run(request.namespace, request.id, digest, JSON.stringify(receipts));
db.exec("COMMIT");
return { documents: receipts, replayed: false };
} catch (error) { db.exec("ROLLBACK"); throw error; }
} finally { db.close(); }
}
export function documentPage(limit = 50, offset = 0) {
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0)
throw new DocumentValidationError("Invalid pagination");
const db = database();
try {
db.exec("BEGIN");
const total = (db.prepare("SELECT COUNT(*) AS n FROM documents").get() as { n: number }).n;
const documents = (db.prepare("SELECT json_remove(payload,'$.content') AS payload FROM documents ORDER BY source_slug LIMIT ? OFFSET ?")
.all(limit, offset) as { payload: string }[]).map((row) => JSON.parse(row.payload) as DocLink);
db.exec("COMMIT");
return { documents, total, limit, offset, nextOffset: offset + documents.length < total ? offset + documents.length : null };
} finally { db.close(); }
}
export function documentHistoryPage(sourceSlug: string, limit = 50, offset = 0) {
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0)
throw new DocumentValidationError("Invalid pagination");
const db = database();
try {
db.exec("BEGIN");
const total = (db.prepare(`SELECT COUNT(*) AS n FROM document_revisions r JOIN documents d
ON d.id=r.document_id WHERE d.source_slug=?`).get(sourceSlug) as { n: number }).n;
const revisions = (db.prepare(`SELECT json_remove(r.payload,'$.content') AS payload, r.created_at AS createdAt
FROM document_revisions r JOIN documents d ON d.id=r.document_id
WHERE d.source_slug=? ORDER BY r.revision DESC LIMIT ? OFFSET ?`)
.all(sourceSlug, limit, offset) as { payload: string; createdAt: string }[])
.map((row) => ({ ...JSON.parse(row.payload) as DocLink, createdAt: row.createdAt }));
db.exec("COMMIT");
return { revisions, total, limit, offset, nextOffset: offset + revisions.length < total ? offset + revisions.length : null };
} finally { db.close(); }
}
export function documentRevision(sourceSlug: string, revision: number): Doc | null {
if (!Number.isSafeInteger(revision) || revision < 1) throw new DocumentValidationError("Invalid revision");
const db = database();
try {
const row = db.prepare(`SELECT r.payload FROM document_revisions r JOIN documents d
ON d.id=r.document_id WHERE d.source_slug=? AND r.revision=?`).get(sourceSlug, revision) as { payload: string } | undefined;
return row ? JSON.parse(row.payload) as Doc : null;
} finally { db.close(); }
} }
+56
View File
@@ -0,0 +1,56 @@
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { openSiteDatabase } from "./site-database";
export type DocumentKeyScope = "read" | "read-write";
export type DocumentKey = { id: string; name: string; scope: DocumentKeyScope;
createdAt: number; expiresAt: number; revokedAt: number | null; lastUsedAt: number | null };
function database() {
const db = openSiteDatabase();
db.exec(`CREATE TABLE IF NOT EXISTS document_api_keys (
id TEXT PRIMARY KEY, name TEXT NOT NULL, digest TEXT NOT NULL UNIQUE,
scope TEXT NOT NULL CHECK(scope IN ('read','read-write')), created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL, revoked_at INTEGER, last_used_at INTEGER
);`);
return db;
}
export function createDocumentKey(name: string, scope: DocumentKeyScope = "read-write", days = 90) {
if (!name.trim() || name.length > 100 || !["read", "read-write"].includes(scope) ||
!Number.isSafeInteger(days) || days < 1 || days > 365) throw Error("Invalid key name, scope or lifetime");
const id = randomUUID();
const token = "tdoc_" + randomBytes(32).toString("base64url");
const createdAt = Date.now();
const expiresAt = createdAt + days * 86400000;
const db = database();
try {
db.prepare("INSERT INTO document_api_keys(id,name,digest,scope,created_at,expires_at) VALUES (?,?,?,?,?,?)")
.run(id, name.trim(), createHash("sha256").update(token).digest("hex"), scope, createdAt, expiresAt);
return { id, token, name: name.trim(), scope, createdAt, expiresAt };
} finally { db.close(); }
}
export function authenticateDocumentKey(token: string | undefined, now = Date.now()) {
if (!token || !/^tdoc_[A-Za-z0-9_-]{43}$/.test(token)) return null;
const db = database();
try {
const row = db.prepare("SELECT id,scope,last_used_at AS lastUsedAt FROM document_api_keys WHERE digest=? AND revoked_at IS NULL AND expires_at>?")
.get(createHash("sha256").update(token).digest("hex"), now) as { id: string; scope: DocumentKeyScope; lastUsedAt: number | null } | undefined;
if (!row) return null;
if (row.lastUsedAt === null || row.lastUsedAt < now - 60000)
db.prepare("UPDATE document_api_keys SET last_used_at=? WHERE id=? AND (last_used_at IS NULL OR last_used_at<?)")
.run(now, row.id, now - 60000);
return { id: row.id, scope: row.scope };
} finally { db.close(); }
}
export function listDocumentKeys(): DocumentKey[] {
const db = database();
try {
return db.prepare(`SELECT id,name,scope,created_at AS createdAt,expires_at AS expiresAt,
revoked_at AS revokedAt,last_used_at AS lastUsedAt FROM document_api_keys ORDER BY created_at,id`).all() as DocumentKey[];
} finally { db.close(); }
}
export function revokeDocumentKey(id: string) {
const db = database();
try {
const result = db.prepare("UPDATE document_api_keys SET revoked_at=COALESCE(revoked_at,?) WHERE id=?").run(Date.now(), id);
if (!result.changes) throw Error("Document key not found");
} finally { db.close(); }
}
+51
View File
@@ -0,0 +1,51 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { authenticateDocumentKey } from "./document-keys";
import { DocumentConflictError, DocumentValidationError, validateDocument, type Doc } from "./docs";
export function authorizeDocuments(request: NextApiRequest, response: NextApiResponse, write = false) {
response.setHeader("Cache-Control", "private, no-store");
response.setHeader("X-Content-Type-Options", "nosniff");
const header = request.headers.authorization;
const token = typeof header === "string" && header.startsWith("Bearer ") ? header.slice(7) : undefined;
const key = authenticateDocumentKey(token);
if (!key) {
response.status(401).json({ error: "需要有效的文档 API Key", code: "unauthorized" });
return null;
}
if (write && key.scope !== "read-write") {
response.status(403).json({ error: "该 API Key 仅允许读取文档", code: "read_only" });
return null;
}
return key;
}
export function documentApiError(response: NextApiResponse, error: unknown) {
if (error instanceof DocumentConflictError)
return response.status(409).json({ error: error.message, code: "conflict" });
if (error instanceof DocumentValidationError)
return response.status(400).json({ error: error.message, code: "invalid_document" });
return response.status(503).json({ error: "文档数据库暂时不可用", code: "unavailable" });
}
export function parseDocument(value: unknown): Doc {
if (!value || typeof value !== "object" || Array.isArray(value)) throw new DocumentValidationError("Expected a document object");
const row = value as Record<string, unknown>;
const fields = ["slug", "sourceSlug", "title", "category", "collection", "group", "description", "draft", "featured", "content", "revision"];
if (Object.keys(row).some((key) => !fields.includes(key))) throw new DocumentValidationError("Unknown document field");
const doc = Object.fromEntries(fields.map((key) => [key, row[key]])) as Doc;
validateDocument(doc);
if (!Number.isSafeInteger(doc.revision) || doc.revision < 0) throw new DocumentValidationError("Provide expected revision");
return doc;
}
export function pagination(request: NextApiRequest) {
const number = (value: string | string[] | undefined, fallback: number) => {
if (value === undefined) return fallback;
if (typeof value !== "string" || !/^\d+$/.test(value)) throw new DocumentValidationError("Invalid pagination");
return Number(value);
};
return { limit: number(request.query.limit, 50), offset: number(request.query.offset, 0) };
}
export function idempotency(request: NextApiRequest, namespace: string) {
const id = request.headers["idempotency-key"];
if (id === undefined) return undefined;
if (typeof id !== "string" || !/^[A-Za-z0-9._:-]{1,128}$/.test(id)) throw new DocumentValidationError("Invalid Idempotency-Key");
return { namespace, id };
}
-42
View File
@@ -1,45 +1,3 @@
export type Section = {
group: string;
description: string;
label: string;
symbol: string;
};
export function sectionFor(slug: string): Section {
if (slug.includes("endor-purpose"))
return {
group: "项目讨论",
label: "讨论草案",
symbol: "○",
description: "逐步讨论 Endor 的意义:从程序入口走向用户与 AI 的对象操作。",
};
if (slug.includes("endor-concepts"))
return {
group: "架构设计",
label: "系统架构",
symbol: "◇",
description: "从全球入口、区域运行时到对象数据,了解 Endor 的系统架构。",
};
if (slug.includes("mounting"))
return {
group: "架构设计",
label: "讨论草案",
symbol: "◇",
description: "探索节点、对象与统一接入协议,记录仍在演进的设计。",
};
if (slug.includes("figures"))
return {
group: "图形档案",
label: "工具与工作流",
symbol: "⌘",
description: "从 Python 源码到可编辑 SVG,让图形与文档一起演进。",
};
return {
group: "开始使用",
label: "指南",
symbol: "↗",
description: "搭建本地工作台,添加第一篇文档,了解检查与发布流程。",
};
}
export type Heading = { id: string; text: string; level: number; line: number }; export type Heading = { id: string; text: string; level: number; line: number };
export function headingsFor(content: string): Heading[] { export function headingsFor(content: string): Heading[] {
let fenced = false; let fenced = false;
+82
View File
@@ -0,0 +1,82 @@
import type { ResearchCompany, ResearchObservation, ResearchSnapshot } from "./ai-research";
export type IncomePoint = { company: ResearchCompany; observation: ResearchObservation; value: number };
export type IncomeStats = {
n: number; mean: number; median: number; min: number; max: number;
sampleDeviation: number | null; cv: number | null; meanMedianRatio: number | null;
largestShare: number | null; meanWithoutLargest: number | null; largestRemovalDrop: number | null;
};
/** Describes the supplied sample only; missing values never become zero. */
export function describeIncome(values: number[]): IncomeStats | null {
if (!values.length || values.some((value) => !Number.isFinite(value) || value < 0)) return null;
const ordered = [...values].sort((a, b) => a - b);
const n = ordered.length;
const total = ordered.reduce((sum, value) => sum + value, 0);
const mean = total / n;
const median = n % 2 ? ordered[(n - 1) / 2] : (ordered[n / 2 - 1] + ordered[n / 2]) / 2;
const sampleDeviation = n > 1 ? Math.sqrt(ordered.reduce((sum, value) => sum + (value - mean) ** 2, 0) / (n - 1)) : null;
const max = ordered[n - 1];
const meanWithoutLargest = n > 1 ? (total - max) / (n - 1) : null;
return { n, mean, median, min: ordered[0], max, sampleDeviation,
cv: sampleDeviation !== null && mean > 0 ? sampleDeviation / mean : null,
meanMedianRatio: median > 0 ? mean / median : null,
largestShare: total > 0 ? max / total : null, meanWithoutLargest,
largestRemovalDrop: meanWithoutLargest !== null && mean > 0 ? (mean - meanWithoutLargest) / mean : null };
}
function calendarDay(value: string | undefined): number | null {
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
const time = Date.parse(`${value}T00:00:00Z`);
return Number.isFinite(time) && new Date(time).toISOString().slice(0, 10) === value ? time / 86400000 : null;
}
/** Latest dated platform MRR per product, never ARR, cash collections or estimates. */
export function platformIncomeSample(snapshot: ResearchSnapshot, options: {
windowDays: number | null; foundedYear?: number; annualize?: boolean;
}) {
const end = calendarDay(snapshot.asOf);
if (end === null || (options.windowDays !== null && (!Number.isInteger(options.windowDays) || options.windowDays < 0)))
throw new Error("Invalid income sample window");
const companies = new Map(snapshot.companies.map((company) => [company.id, company]));
const latest = new Map<string, ResearchObservation>();
const excluded: { observation: ResearchObservation; reason: string }[] = [];
const candidates = snapshot.observations.filter((o) => o.selection === "platform" && o.metric === "mrr");
for (const observation of candidates) {
const company = companies.get(observation.company);
const day = calendarDay(observation.observedAt);
let reason = "";
if (!company || ![2025, 2026].includes(company.year ?? 0)) reason = "创立年份未纳入2025—2026组";
else if (options.foundedYear && company.year !== options.foundedYear) reason = "不属于所选创立年份";
else if (observation.origin !== "payment-platform" || observation.unit !== "USD" || observation.bound !== "=" ||
observation.comparisonGroup !== "trustmrr-usd-mrr" || !observation.provider || !Number.isFinite(observation.value) || observation.value < 0)
reason = "来源、币种、指标或数值口径不满足条件";
else if (day === null) reason = "缺少有效数据日期";
else if (day > end) reason = "数据日期晚于研究截止日";
else if (options.windowDays !== null && end - day > options.windowDays) reason = "最后同步日期超出所选窗口";
if (reason) { excluded.push({ observation, reason }); continue; }
const previous = latest.get(observation.company);
if (!previous || observation.observedAt! > previous.observedAt!) {
if (previous) excluded.push({ observation: previous, reason: "同一产品的较早观测" });
latest.set(observation.company, observation);
} else excluded.push({ observation, reason: "同一产品已选较新或同日观测" });
}
const points: IncomePoint[] = [...latest.values()].map((observation) => ({
company: companies.get(observation.company)!, observation,
value: observation.value * (options.annualize ? 12 : 1),
}));
return { points, excluded };
}
export function groupIncome(points: IncomePoint[], splitModels = true) {
const groups = new Map<string, { category: string; provider: string; model: string; points: IncomePoint[] }>();
for (const point of points) {
const category = point.company.cat;
const provider = point.observation.provider!;
const model = splitModels ? point.company.businessModel ?? "收费模式未核验" : "全部收费模式";
const key = JSON.stringify([category, provider, model]);
if (!groups.has(key)) groups.set(key, { category, provider, model, points: [] });
groups.get(key)!.points.push(point);
}
return [...groups.entries()].map(([key, group]) => ({ key, ...group, stats: describeIncome(group.points.map((point) => point.value))! }));
}
+20
View File
@@ -0,0 +1,20 @@
import { chmodSync } from "node:fs";
import { dirname, join } from "node:path";
import { DatabaseSync } from "node:sqlite";
// Keep the historical filename so existing authentication state is preserved.
// Research and authentication use different tables in this same site database.
export function openSiteDatabase() {
const configFile = process.env.AUTH_CONFIG_FILE;
if (!configFile) throw new Error("Authentication is not configured");
const file = join(dirname(configFile), "login-state.sqlite");
const db = new DatabaseSync(file);
try {
chmodSync(file, 0o600);
db.exec("PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON;");
return db;
} catch (error) {
db.close();
throw error;
}
}
@@ -0,0 +1,22 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { DocumentValidationError, saveDocumentBatch } from "@/lib/docs";
import { authorizeDocuments, documentApiError, idempotency, parseDocument } from "@/lib/documents-api";
export const config = { api: { bodyParser: { sizeLimit: "8mb" } } };
export default function handler(request: NextApiRequest, response: NextApiResponse) {
try {
const key = authorizeDocuments(request, response, true);
if (!key) return;
if (request.method !== "POST") {
response.setHeader("Allow", "POST");
return response.status(405).end();
}
const body = request.body;
if (!body || typeof body !== "object" || Array.isArray(body) ||
Object.keys(body).length !== 1 || !Array.isArray(body.documents) ||
!body.documents.length || body.documents.length > 100)
throw new DocumentValidationError("Expected { documents: [...] } with 1 to 100 documents");
const documents = body.documents.map((row: unknown) => parseDocument(row));
return response.status(200).json(saveDocumentBatch(documents, idempotency(request, key.id)));
} catch (error) { return documentApiError(response, error); }
}
@@ -0,0 +1,21 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { documentPage, saveDocumentBatch } from "@/lib/docs";
import { authorizeDocuments, documentApiError, idempotency, pagination, parseDocument } from "@/lib/documents-api";
export const config = { api: { bodyParser: { sizeLimit: "8mb" } } };
export default function handler(request: NextApiRequest, response: NextApiResponse) {
try {
const key = authorizeDocuments(request, response, request.method === "POST");
if (!key) return;
if (request.method === "GET") {
const { limit, offset } = pagination(request);
return response.status(200).json(documentPage(limit, offset));
}
if (request.method === "POST") {
const result = saveDocumentBatch([parseDocument(request.body)], idempotency(request, key.id));
return response.status(200).json({ document: result.documents[0], replayed: result.replayed });
}
response.setHeader("Allow", "GET, POST");
return response.status(405).end();
} catch (error) { return documentApiError(response, error); }
}
@@ -0,0 +1,30 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { DocumentValidationError, documentHistoryPage, documentRevision, readDocument } from "@/lib/docs";
import { authorizeDocuments, documentApiError, pagination } from "@/lib/documents-api";
export default function handler(request: NextApiRequest, response: NextApiResponse) {
try {
if (!authorizeDocuments(request, response)) return;
if (request.method !== "GET") {
response.setHeader("Allow", "GET");
return response.status(405).end();
}
const slug = request.query.slug;
if (!Array.isArray(slug)) throw new DocumentValidationError("Invalid document slug");
const doc = readDocument(slug.join("/"));
if (!doc) return response.status(404).json({ error: "文档不存在", code: "not_found" });
if (request.query.revision !== undefined) {
if (request.query.history !== undefined || typeof request.query.revision !== "string" || !/^\d+$/.test(request.query.revision))
throw new DocumentValidationError("Invalid revision query");
const prior = documentRevision(doc.sourceSlug, Number(request.query.revision));
if (!prior) return response.status(404).json({ error: "修订不存在", code: "not_found" });
return response.status(200).json(prior);
}
if (request.query.history !== undefined) {
if (request.query.history !== "1") throw new DocumentValidationError("Use history=1");
const { limit, offset } = pagination(request);
return response.status(200).json(documentHistoryPage(doc.sourceSlug, limit, offset));
}
return response.status(200).json(doc);
} catch (error) { return documentApiError(response, error); }
}
@@ -0,0 +1,22 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { readDocument } from "@/lib/docs";
// The proxy protects Markdown just like the rendered document and search index.
export default function handler(request: NextApiRequest, response: NextApiResponse) {
response.setHeader("Cache-Control", "private, no-store");
if (request.method !== "GET") {
response.setHeader("Allow", "GET");
return response.status(405).end();
}
const slug = request.query.slug;
if (typeof slug !== "string") return response.status(400).json({ error: "缺少文档地址" });
try {
const doc = readDocument(slug);
if (!doc) return response.status(404).end();
response.setHeader("Content-Type", "text/plain; charset=utf-8");
response.setHeader("X-Content-Type-Options", "nosniff");
return response.status(200).send(doc.content);
} catch {
return response.status(503).json({ error: "文档数据库暂时不可用" });
}
}
@@ -0,0 +1,13 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { readResearchSnapshot } from "@/lib/ai-research-store";
// The site's existing proxy protects this endpoint with the same login session.
export default function handler(request: NextApiRequest, response: NextApiResponse) {
response.setHeader("Cache-Control", "private, no-store");
if (request.method !== "GET") {
response.setHeader("Allow", "GET");
return response.status(405).end();
}
try { return response.status(200).json(readResearchSnapshot()); }
catch { return response.status(503).json({ error: "研究数据库暂时不可用,请稍后重试" }); }
}
+17
View File
@@ -0,0 +1,17 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { allDocuments } from "@/lib/docs";
// The proxy authenticates this endpoint, including index content.
export default async function handler(request: NextApiRequest, response: NextApiResponse) {
response.setHeader("Cache-Control", "private, no-store");
if (request.method !== "GET") {
response.setHeader("Allow", "GET");
return response.status(405).end();
}
try {
const index = allDocuments().map(({ content, ...doc }) => ({ ...doc, searchText: content }));
return response.status(200).json(index);
} catch {
return response.status(503).json({ error: "文档数据库暂时不可用" });
}
}
@@ -1,9 +1,9 @@
import type { import type {
GetStaticPaths, GetServerSideProps,
GetStaticProps, InferGetServerSidePropsType,
InferGetStaticPropsType,
} from "next"; } from "next";
import Head from "next/head"; import Head from "next/head";
import dynamic from "next/dynamic";
import Link from "next/link"; import Link from "next/link";
import { import {
Children, Children,
@@ -14,23 +14,28 @@ import {
} from "react"; } from "react";
import ReactMarkdown from "react-markdown"; import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm"; import remarkGfm from "remark-gfm";
import { listDocs, readDoc, type Doc, type DocLink } from "@/lib/docs"; import { listDocs, readDocument, type Doc, type DocLink } from "@/lib/docs";
import { Shell, Navigation } from "@/components/Shell"; import { Shell, Navigation } from "@/components/Shell";
import { ArchitectureFigure } from "@/components/ArchitectureFigure"; import { ArchitectureFigure } from "@/components/ArchitectureFigure";
import { FigureGallery } from "@/components/FigureGallery";
import { CodeBlock } from "@/components/CodeBlock"; import { CodeBlock } from "@/components/CodeBlock";
import { headingsFor, sectionFor } from "@/lib/navigation"; import { collectionEntries, collectionLabel } from "@/lib/collections";
import { Icon } from "@/components/Icon";
import { headingsFor } from "@/lib/navigation";
type Props = { doc: Doc; docs: DocLink[] }; type Props = { doc: Doc; docs: DocLink[] };
export const getStaticPaths: GetStaticPaths = async () => ({ const AICompanyResearch = dynamic(() => import("@/components/AICompanyResearch"));
paths: (await listDocs()).map(({ slug }) => ({ params: { slug } })), export const getServerSideProps: GetServerSideProps<Props> = async ({ params, res, resolvedUrl }) => {
fallback: false, res.setHeader("Cache-Control", "private, no-store");
}); const slug = Array.isArray(params?.slug) ? params.slug.join("/") : params?.slug;
export const getStaticProps: GetStaticProps<Props> = async ({ params }) => {
const slug = params?.slug;
if (typeof slug !== "string") return { notFound: true }; if (typeof slug !== "string") return { notFound: true };
const docs = await listDocs(); const doc = readDocument(slug);
if (!docs.some((d) => d.slug === slug)) return { notFound: true }; if (!doc) return { notFound: true };
return { props: { doc: await readDoc(slug), docs } }; if (slug !== doc.slug) {
const query = resolvedUrl.includes("?") ? resolvedUrl.slice(resolvedUrl.indexOf("?")) : "";
return { redirect: { destination: `/docs/${doc.slug}${query}`, permanent: true } };
}
return { props: { doc, docs: await listDocs() } };
}; };
function textOf(value: ReactNode): string { function textOf(value: ReactNode): string {
return Children.toArray(value) return Children.toArray(value)
@@ -44,11 +49,13 @@ function textOf(value: ReactNode): string {
export default function DocPage({ export default function DocPage({
doc, doc,
docs, docs,
}: InferGetStaticPropsType<typeof getStaticProps>) { }: InferGetServerSidePropsType<typeof getServerSideProps>) {
const headings = headingsFor(doc.content); const headings = headingsFor(doc.content);
const [active, setActive] = useState(""); const [active, setActive] = useState("");
const section = sectionFor(doc.slug);
const index = docs.findIndex((d) => d.slug === doc.slug); const siblings = docs.filter((d) => d.collection === doc.collection);
const collectionEntry = collectionEntries(docs).find((c) => c.name === doc.collection)!.entry;
const index = siblings.findIndex((d) => d.slug === doc.slug);
useEffect(() => { useEffect(() => {
const observer = new IntersectionObserver( const observer = new IntersectionObserver(
(entries) => { (entries) => {
@@ -80,38 +87,59 @@ export default function DocPage({
<> <>
<Head> <Head>
<title>{doc.title} · Tabularium</title> <title>{doc.title} · Tabularium</title>
<meta name="description" content={section.description} /> <meta name="description" content={doc.description} />
</Head> </Head>
<Shell key={doc.slug} docs={docs} current={doc.slug}> <Shell key={doc.slug} docs={docs} current={doc.slug}>
<div className="reading-layout"> <div className={`reading-layout${doc.collection === "AI 公司研究" ? " research-layout" : ""}`}>
<aside className="sidebar"> <aside className="sidebar">
<Navigation docs={docs} current={doc.slug} /> <Navigation docs={docs} current={doc.slug} />
</aside> </aside>
<main id="content" className="reading-main"> <main id="content" className="reading-main">
<div className="breadcrumb"> <div className="breadcrumb">
<Link href="/">文档</Link> <Link href={`/docs/${collectionEntry.slug}`}>{collectionLabel(doc.collection)}</Link>
<span>/</span> <Icon name="chevron" size={12} />
<span>{section.group}</span> <span>{doc.slug === collectionEntry.slug ? "概览" : doc.group === doc.collection ? doc.title : doc.group}</span>
</div> {doc.draft && <span className="draft-badge">草案</span>}
<div className="article-meta">
<span className="eyebrow">{section.group}</span>
{section.label.includes("草案") && (
<span className="draft-badge">讨论草案</span>
)}
</div> </div>
<article className="prose prose-neutral max-w-none"> <article className="prose prose-neutral max-w-none">
<ReactMarkdown <ReactMarkdown
remarkPlugins={[remarkGfm]} remarkPlugins={[remarkGfm]}
components={{ components={{
p: ({ children, node }) => a: ({ href, children }) => {
node?.children.some( if (!href) return <a>{children}</a>;
let target = href;
if (!/^(?:[a-z]+:|\/\/|#)/i.test(href)) {
const resolved = new URL(href, `https://docs.local/docs/${doc.sourceSlug}`);
const source = decodeURIComponent(resolved.pathname).replace(/^\/docs\//, "").replace(/\.md$/, "");
const linked = docs.find((d) => d.sourceSlug === source || d.slug === source);
if (linked) target = `/docs/${linked.slug}${resolved.search}${resolved.hash}`;
}
return <a href={target}>{children}</a>;
},
p: ({ children, node }) => {
const slides = node?.children.flatMap((child) =>
child.type === "element" && child.tagName === "img" &&
typeof child.properties.src === "string" &&
child.properties.src.startsWith("/figures/endor-")
? [{ source: child.properties.src, alt: String(child.properties.alt ?? "") }]
: [],
) ?? [];
const onlyImages = node?.children.every((child) =>
(child.type === "element" && child.tagName === "img" &&
typeof child.properties.src === "string" &&
child.properties.src.startsWith("/figures/endor-")) ||
(child.type === "text" && child.value.trim() === ""),
);
if (slides.length > 1 && onlyImages) return <FigureGallery slides={slides} />;
return node?.children.some(
(child) => (child) =>
child.type === "element" && child.tagName === "img", child.type === "element" && child.tagName === "img",
) ? ( ) ? (
<div>{children}</div> <div>{children}</div>
) : ( ) : (
<p>{children}</p> <p>{children}</p>
), );
},
img: ({ src, alt }) => img: ({ src, alt }) =>
typeof src === "string" && src.startsWith("/figures/endor-") ? ( typeof src === "string" && src.startsWith("/figures/endor-") ? (
<ArchitectureFigure source={src} alt={alt ?? "Endor 架构图"} /> <ArchitectureFigure source={src} alt={alt ?? "Endor 架构图"} />
@@ -183,7 +211,7 @@ export default function DocPage({
blockquote: ({ children }) => ( blockquote: ({ children }) => (
<blockquote <blockquote
className={ className={
section.label.includes("草案") doc.draft
? "callout callout-draft" ? "callout callout-draft"
: "callout" : "callout"
} }
@@ -199,51 +227,38 @@ export default function DocPage({
{doc.content} {doc.content}
</ReactMarkdown> </ReactMarkdown>
</article> </article>
{doc.slug === "other-research/ai-company-research/overview" && <AICompanyResearch />}
<div className="article-end"> <div className="article-end">
<span>文档与源码共同维护</span>
<a <a
href={`https://gitea.entroia.com/Zayden-Jung/endorphin-tabularium-docs/src/branch/main/content/docs/${doc.slug}.md`} href={`/api/documents/source?slug=${encodeURIComponent(doc.slug)}`}
> >
查看文档源码 ↗ 查看 Markdown 原文 ↗
</a> </a>
</div> </div>
<nav className="pagination" aria-label="相邻文档"> <nav className="pagination" aria-label="相邻文档">
{index > 0 ? ( {index > 0 ? (
<Link href={`/docs/${docs[index - 1].slug}`}> <Link href={`/docs/${siblings[index - 1].slug}`}>
<small>← 上一篇</small> <small>← 上一篇</small>
<strong>{docs[index - 1].title}</strong> <strong>{siblings[index - 1].title}</strong>
</Link> </Link>
) : ( ) : (
<Link href="/"> <span />
<small>← 返回</small>
<strong>文档概览</strong>
</Link>
)} )}
{index < docs.length - 1 && ( {index < siblings.length - 1 && (
<Link <Link
className="next-page" className="next-page"
href={`/docs/${docs[index + 1].slug}`} href={`/docs/${siblings[index + 1].slug}`}
> >
<small>下一篇 →</small> <small>下一篇 →</small>
<strong>{docs[index + 1].title}</strong> <strong>{siblings[index + 1].title}</strong>
</Link> </Link>
)} )}
</nav> </nav>
<footer className="article-footer">
ENDOR / TABULARIUM <span>记录思考,连接系统。</span>
</footer>
</main> </main>
<aside className="toc"> <aside className="toc">
<p className="eyebrow">本页内容</p> <p className="eyebrow">本页内容</p>
{toc} {toc}
<div className="toc-note">
<span className="status-dot" /> {section.label}
<p>
{section.label.includes("草案")
? "这里记录正在讨论的设计,尚不代表现有实现。"
: "每一次理解,都成为下一步的起点。"}
</p>
</div>
</aside> </aside>
</div> </div>
</Shell> </Shell>
+54 -161
View File
@@ -1,168 +1,61 @@
import type { GetStaticProps, InferGetStaticPropsType } from "next"; import type { GetServerSideProps, InferGetServerSidePropsType } from "next";
import Head from "next/head"; import Head from "next/head";
import Link from "next/link"; import Link from "next/link";
import { useState } from "react";
import { listDocs, type DocLink } from "@/lib/docs"; import { listDocs, type DocLink } from "@/lib/docs";
import { Shell, Navigation } from "@/components/Shell"; import { Shell, Navigation } from "@/components/Shell";
import { CodeBlock } from "@/components/CodeBlock"; import { Icon } from "@/components/Icon";
import { sectionFor } from "@/lib/navigation"; import { collectionEntries, collectionIcon, collectionLabel, collectionTone } from "@/lib/collections";
export const getStaticProps: GetStaticProps<{ export const getServerSideProps: GetServerSideProps<{ docs: DocLink[] }> = async ({ res }) => {
docs: DocLink[]; res.setHeader("Cache-Control", "private, no-store");
}> = async () => ({ props: { docs: await listDocs() } }); return { props: { docs: await listDocs() } };
export default function Home({ };
docs, const PAGE_SIZE = 8;
}: InferGetStaticPropsType<typeof getStaticProps>) { export default function Home({ docs }: InferGetServerSidePropsType<typeof getServerSideProps>) {
return ( const [collection, setCollection] = useState("");
<> const [query, setQuery] = useState("");
<Head> const [page, setPage] = useState(0);
<title>Tabularium · Endor 文档</title> const collections = [...new Set(docs.map((doc) => doc.collection))];
<meta const filtered = docs.filter((doc) => (!collection || doc.collection === collection) &&
name="description" `${doc.title} ${doc.description}`.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()));
content="Endor 的知识档案。探索开发指南、架构设计与可复现的图形工作流。" const entries = collectionEntries(docs);
/> return <>
</Head> <Head><title>Tabularium · 资料库</title><meta name="description" content="Endor 文档、源码研究与学习资料。" /></Head>
<Shell docs={docs}> <Shell docs={docs}>
<div className="home-layout"> <div className="home-layout">
<aside className="sidebar"> <aside className="sidebar"><Navigation docs={docs} /></aside>
<Navigation docs={docs} /> <main id="content" className="home-main">
</aside> <section className="library-intro">
<main id="content" className="home-main"> <h1>文档中心</h1>
<section className="home-hero"> <p>系统设计、源码研究与学习笔记。</p>
<div className="hero-copy"> </section>
<p className="eyebrow"> <section className="featured-section" aria-labelledby="featured-title">
<span className="status-dot" /> ENDOR KNOWLEDGE ARCHIVE <h2 id="featured-title">选择一份文档</h2>
</p> <div className="featured-grid">{entries.map(({ name, entry, count }) => <Link className="featured-link" data-tone={collectionTone(name)} href={`/docs/${entry.slug}`} key={name}>
<h1> <span className="collection-art"><Icon name={collectionIcon(name)} size={26} /></span>
理解系统。 <h3>{collectionLabel(name)}</h3>
<br /> <p>{entry.description}</p>
构建下一步。 <span className="collection-entry">{count} 篇 <Icon name="arrow" size={17} /></span>
</h1> </Link>)}</div>
<p className="hero-description"> </section>
欢迎来到 <strong>Tabularium</strong>,Endor 的知识档案。 <section className="library-section" id="library" aria-labelledby="library-title">
<br className="desktop-break" /> <h2 id="library-title">全部资料</h2>
从第一篇文档到系统设计,让想法有迹可循。 <div className="library-tools">
</p> <div className="collection-filters" role="group" aria-label="资料分类">
<div className="hero-actions"> {["", ...collections].map((name) => <button key={name} aria-pressed={collection === name} onClick={() => { setCollection(name); setPage(0); }}>{name || "全部"}</button>)}
<Link
className="primary-button"
href="/docs/01-getting-started"
>
开始阅读 <span>→</span>
</Link>
<a className="text-link" href="#explore">
探索档案 <span>↓</span>
</a>
</div>
<p className="hero-footnote">
文档 · 架构 · 图形 <span>持续生长的工作台</span>
</p>
</div> </div>
<div className="archive-visual" aria-hidden="true"> <label className="library-search"><Icon name="search" /><input aria-label="筛选资料" placeholder="筛选资料…" value={query} onChange={(event) => {setQuery(event.target.value); setPage(0);}} /></label>
<div className="archive-grid" /> </div>
<div className="archive-caption">TABULARIUM / 001</div> <ul className="library-list">{filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE).map((doc) => <li key={doc.slug}>
<div className="archive-sheet sheet-back"> <Link href={`/docs/${doc.slug}`}><span className="library-row-title">{doc.title.replace("(草案)", "")}{doc.draft && <span className="draft-badge">草案</span>}</span><span className="library-row-group">{doc.group}</span><Icon name="arrow" size={16} /></Link>
<span>03 — FIGURES</span> </li>)}</ul>
<i /> {filtered.length === 0 && <p className="library-empty">没有找到相关资料。</p>}
<i /> {filtered.length > PAGE_SIZE && <nav className="library-pagination" aria-label="资料分页"><button disabled={page === 0} onClick={() => setPage(page - 1)}>上一页</button><span>{page + 1} / {Math.ceil(filtered.length / PAGE_SIZE)}</span><button disabled={(page + 1) * PAGE_SIZE >= filtered.length} onClick={() => setPage(page + 1)}>下一页</button></nav>}
<i /> </section>
</div> <footer className="site-footer"><span>Tabularium</span><a href="https://gitea.entroia.com/Zayden-Jung/endorphin-tabularium-docs">文档仓库 ↗</a></footer>
<div className="archive-sheet sheet-middle"> </main>
<span>02 — ARCHITECTURE</span> </div>
<i /> </Shell>
<i /> </>;
<i />
</div>
<div className="archive-sheet sheet-front">
<span className="sheet-label">01 / ENDOR</span>
<div className="sheet-emblem">
E<span>↗</span>
</div>
<div className="sheet-rule" />
<b>Ideas, documented.</b>
<small>知识在这里连接。</small>
</div>
<div className="archive-coordinate">
文字与图形,一起演进 <span>↗</span>
</div>
</div>
</section>
<section className="explore-section" id="explore">
<div className="section-heading">
<div>
<p className="eyebrow">EXPLORE THE ARCHIVE</p>
<h2>从这里开始探索</h2>
</div>
<span className="section-count">
{String(docs.length).padStart(2, "0")} 篇文档
</span>
</div>
<div className="doc-cards">
{docs.map((doc, index) => {
const section = sectionFor(doc.slug);
return (
<Link
className="doc-card"
key={doc.slug}
href={`/docs/${doc.slug}`}
>
<div className="card-top">
<span className={`card-icon icon-${index}`}>
{section.symbol}
</span>
<span className="card-number">0{index + 1}</span>
</div>
<p className="card-group">{section.group}</p>
<h3>
{doc.title.replace("(草案)", "")}
<span aria-hidden="true">↗</span>
</h3>
<p className="card-description">{section.description}</p>
<div className="card-bottom">
<span>{section.label}</span>
{section.label.includes("草案") && (
<span className="draft-badge">草案</span>
)}
</div>
</Link>
);
})}
</div>
</section>
<section className="quickstart">
<div>
<p className="eyebrow">LOCAL WORKSPACE</p>
<h2>一个命令,继续探索。</h2>
<p>
在本地启动文档工作台,
<br />
让文字和可复现的图形留在同一个仓库。
</p>
<Link
className="text-link"
href="/docs/01-getting-started#启动"
>
查看完整启动指南 <span>→</span>
</Link>
</div>
<CodeBlock
language="sh"
code={
"pnpm install --frozen-lockfile\nuv sync --project tools/figures --locked\npnpm dev\n"
}
/>
</section>
<footer className="site-footer">
<span>
Endor / <strong>Tabularium</strong>
</span>
<span>记录思考,连接系统。</span>
<a href="https://gitea.entroia.com/Zayden-Jung/endorphin-tabularium-docs">
在仓库中探索 ↗
</a>
</footer>
</main>
</div>
</Shell>
</>
);
} }
+9 -1
View File
@@ -1,6 +1,6 @@
import { NextResponse, type NextRequest } from "next/server"; import { NextResponse, type NextRequest } from "next/server";
import { authConfig, SESSION_COOKIE, validSession } from "./lib/auth"; import { authConfig, SESSION_COOKIE, validSession } from "./lib/auth";
import { authenticateDocumentKey } from "./lib/document-keys";
export function proxy(request: NextRequest) { export function proxy(request: NextRequest) {
const path = request.nextUrl.pathname; const path = request.nextUrl.pathname;
const headers = { const headers = {
@@ -32,6 +32,14 @@ export function proxy(request: NextRequest) {
? authorization.slice(7) ? authorization.slice(7)
: undefined; : undefined;
const token = bearer ?? request.cookies.get(SESSION_COOKIE)?.value; const token = bearer ?? request.cookies.get(SESSION_COOKIE)?.value;
// Document keys are scoped to the document API; they never authenticate other pages or APIs.
if (bearer && (path === "/api/documents" || path.startsWith("/api/documents/"))) {
try {
if (authenticateDocumentKey(bearer)) return NextResponse.next({ headers });
} catch {
return NextResponse.json({ error: "文档认证暂时不可用" }, { status: 503, headers });
}
}
if (validSession(token, config)) { if (validSession(token, config)) {
if (!["GET", "HEAD", "OPTIONS"].includes(request.method) && !bearer) { if (!["GET", "HEAD", "OPTIONS"].includes(request.method) && !bearer) {
try { try {
File diff suppressed because it is too large Load Diff
+99
View File
@@ -0,0 +1,99 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { allDocuments, documentHistory, importDocuments, readDocument, saveDocument,
type DocInput, type DocumentExport } from "../src/lib/docs";
const input: DocInput = { slug: "endor/example", sourceSlug: "00-example", title: "Example",
category: "Endor", collection: "Endor 文档", group: "讨论", description: "Example description",
draft: true, featured: false, content: "# Example\n\nOriginal body" };
function isolated(run: (directory: string) => void) {
const directory = mkdtempSync(join(tmpdir(), "tabularium-docs-"));
const previous = process.env.AUTH_CONFIG_FILE;
process.env.AUTH_CONFIG_FILE = join(directory, "config.json");
try { run(directory); } finally {
if (previous === undefined) delete process.env.AUTH_CONFIG_FILE;
else process.env.AUTH_CONFIG_FILE = previous;
rmSync(directory, { recursive: true, force: true });
}
}
function bundle(documents: DocInput[]): DocumentExport {
return { format: "tabularium-documents-v1", documents: documents.map((doc) => ({ ...doc, revision: 1 })) };
}
test("writes and metadata persist across independent connections; no repository seed", () => isolated(() => {
assert.deepEqual(allDocuments(), []);
const saved = saveDocument(input, 0);
assert.deepEqual(readDocument(input.slug), saved);
assert.deepEqual(readDocument(input.sourceSlug), saved);
const changed = saveDocument({ ...input, content: "# Revised", collection: "新合集", group: "新目录" }, 1);
assert.equal(changed.revision, 2);
assert.equal(allDocuments()[0].collection, "新合集");
assert.deepEqual(documentHistory(input.sourceSlug).map((doc) => doc.content), [input.content, "# Revised"]);
}));
test("optimistic concurrency prevents lost updates and requires explicit revision", () => isolated(() => {
saveDocument(input, 0);
assert.throws(() => saveDocument({ ...input, content: "Lost" }, 0), /conflict/);
assert.throws(() => saveDocument(input, NaN), /expected revision/);
assert.equal(readDocument(input.slug)?.content, input.content);
assert.equal(documentHistory(input.sourceSlug).length, 1);
}));
test("renames preserve aliases and alias collisions roll back document and revision", () => isolated(() => {
saveDocument(input, 0);
saveDocument({ ...input, slug: "endor/renamed" }, 1);
assert.equal(readDocument(input.slug)?.slug, "endor/renamed");
assert.throws(() => saveDocument({ ...input, sourceSlug: "another", slug: input.slug }, 0), /collision/);
assert.equal(allDocuments().length, 1);
assert.equal(readDocument("another"), null);
assert.equal(documentHistory(input.sourceSlug).length, 2);
}));
test("bootstrap is atomic and repeat imports never replace DB edits", () => isolated(() => {
const snapshot = bundle([input]);
assert.equal(importDocuments(snapshot), 1);
saveDocument({ ...input, content: "Written directly to DB" }, 1);
assert.equal(importDocuments(snapshot), 0);
assert.equal(importDocuments(bundle([{ ...input, content: "Stale release" }]), true), 0);
assert.throws(() => importDocuments(bundle([{ ...input, content: "Other" }])), /empty/);
assert.equal(readDocument(input.slug)?.content, "Written directly to DB");
}));
test("colliding bootstrap leaves no partial rows and can be retried", () => isolated(() => {
assert.throws(() => importDocuments(bundle([input, { ...input, sourceSlug: "other" }])));
assert.deepEqual(allDocuments(), []);
assert.equal(importDocuments(bundle([input])), 1);
}));
test("migration preserves unrelated authentication and research tables", () => isolated((directory) => {
const db = new DatabaseSync(join(directory, "login-state.sqlite"));
db.exec("CREATE TABLE login_state(value TEXT); INSERT INTO login_state VALUES ('preserved'); CREATE TABLE research_datasets(value TEXT); INSERT INTO research_datasets VALUES ('research');");
db.close();
importDocuments(bundle([input]));
const reopened = new DatabaseSync(join(directory, "login-state.sqlite"));
assert.equal(reopened.prepare("SELECT value FROM login_state").get()?.value, "preserved");
assert.equal(reopened.prepare("SELECT value FROM research_datasets").get()?.value, "research");
assert.deepEqual(reopened.prepare("PRAGMA foreign_key_check").all(), []);
reopened.close();
}));
test("invalid content cannot enter the database", () => isolated(() => {
for (const invalid of [ { ...input, slug: "../private" }, { ...input, slug: "endor/01-example" },
{ ...input, content: "![original](/figures/raw.png)" }, { ...input, category: "" } ])
assert.throws(() => saveDocument(invalid, 0));
assert.deepEqual(allDocuments(), []);
assert.equal(readDocument("../private"), null);
}));
test("missing database configuration fails closed", () => {
const previous = process.env.AUTH_CONFIG_FILE;
delete process.env.AUTH_CONFIG_FILE;
try { assert.throws(() => allDocuments(), /not configured/); }
finally { if (previous !== undefined) process.env.AUTH_CONFIG_FILE = previous; }
});
+136
View File
@@ -0,0 +1,136 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { mkdtempSync, rmSync, writeFileSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { NextApiRequest, NextApiResponse } from "next";
import documents from "../src/pages/api/documents/index";
import batch from "../src/pages/api/documents/batch";
import item from "../src/pages/api/documents/item/[...slug]";
import { createDocumentKey, authenticateDocumentKey, revokeDocumentKey, listDocumentKeys } from "../src/lib/document-keys";
import { allDocuments, documentHistory, readDocument, saveDocument, type Doc } from "../src/lib/docs";
import { newAuthConfig, signSession } from "../src/lib/auth";
const input: Doc = { slug: "endor/example", sourceSlug: "00-example", title: "Example", category: "Endor",
collection: "Endor 文档", group: "讨论", description: "Description", draft: true, featured: false,
content: "# Example\n\nOriginal body", revision: 0 };
type Options = { method?: string; body?: unknown; headers?: Record<string, string>;
query?: Record<string, string | string[]> };
function call(handler: (req: NextApiRequest, res: NextApiResponse) => unknown, options: Options = {}) {
let status = 200;
let body: unknown;
const headers: Record<string, string> = {};
const response = {
status(value: number) { status = value; return this; },
setHeader(name: string, value: string) { headers[name.toLowerCase()] = value; return this; },
json(value: unknown) { body = value; return this; },
end() { return this; },
};
handler({ method: options.method ?? "GET", body: options.body, headers: options.headers ?? {},
query: options.query ?? {} } as unknown as NextApiRequest, response as unknown as NextApiResponse);
return { status, body, headers };
}
function isolated(run: (context: { directory: string; headers: Record<string, string> }) => void) {
const directory = mkdtempSync(join(tmpdir(), "tabularium-doc-api-"));
const previous = process.env.AUTH_CONFIG_FILE;
process.env.AUTH_CONFIG_FILE = join(directory, "config.json");
writeFileSync(process.env.AUTH_CONFIG_FILE, JSON.stringify(newAuthConfig()), { mode: 0o600 });
try {
const key = createDocumentKey("test uploader");
run({ directory, headers: { authorization: "Bearer " + key.token } });
} finally {
if (previous === undefined) delete process.env.AUTH_CONFIG_FILE;
else process.env.AUTH_CONFIG_FILE = previous;
rmSync(directory, { recursive: true, force: true });
}
}
test("new API requires document keys, rejects browser cookies and broad web sessions", () => isolated(() => {
assert.equal(call(documents).status, 401);
assert.equal(call(documents, { headers: { authorization: "Bearer invalid" } }).status, 401);
const config = JSON.parse(readFileSync(process.env.AUTH_CONFIG_FILE!, "utf8"));
const token = signSession(config);
assert.equal(call(documents, { headers: { authorization: "Bearer " + token } }).status, 401);
assert.equal(call(documents, { headers: { cookie: "tabularium_session=" + token } }).status, 401);
assert.deepEqual(allDocuments(), []);
}));
test("key scopes, revocation, expiry and secret-free listing are persistent", () => isolated(({ directory }) => {
const key = createDocumentKey("reader", "read", 1);
const headers = { authorization: "Bearer " + key.token };
assert.equal(call(documents, { headers }).status, 200);
assert.equal(call(documents, { method: "POST", headers, body: input }).status, 403);
assert.equal(call(batch, { method: "POST", headers, body: { documents: [input] } }).status, 403);
assert.ok(!JSON.stringify(listDocumentKeys()).includes(key.token));
assert.ok(!readFileSync(join(directory, "login-state.sqlite")).includes(Buffer.from(key.token)));
assert.equal(authenticateDocumentKey(key.token, key.expiresAt), null);
revokeDocumentKey(key.id);
assert.equal(call(documents, { headers }).status, 401);
const revoked = listDocumentKeys().find((row) => row.id === key.id);
assert.ok(revoked); assert.equal(typeof revoked.revokedAt, "number");
}));
test("single save, aliases, metadata and historical content are visible without rebuilding", () => isolated(({ headers }) => {
assert.equal(call(documents, { method: "POST", headers, body: input }).status, 200);
assert.equal((call(item, { headers, query: { slug: input.slug.split("/") } }).body as Doc).revision, 1);
const changed = { ...input, revision: 1, slug: "endor/renamed", content: "# Changed", collection: "新合集" };
assert.equal(call(documents, { method: "POST", headers, body: changed }).status, 200);
assert.equal((call(item, { headers, query: { slug: input.slug.split("/") } }).body as Doc).slug, changed.slug);
assert.equal((call(item, { headers, query: { slug: [input.sourceSlug], revision: "1" } }).body as Doc).content, input.content);
const history = call(item, { headers, query: { slug: [input.sourceSlug], history: "1", limit: "1" } });
const page = history.body as { revisions: Doc[]; total: number; nextOffset: number };
assert.equal(page.total, 2);
assert.equal(page.nextOffset, 1);
assert.equal(page.revisions[0].revision, 2);
assert.equal(page.revisions[0].content, undefined);
assert.equal(call(item, { headers, query: { slug: [input.sourceSlug], revision: "99" } }).status, 404);
assert.equal(call(item, { headers, query: { slug: [input.sourceSlug], revision: "0" } }).status, 400);
}));
test("pagination returns metadata only with strict bounds", () => isolated(({ headers }) => {
const second = { ...input, slug: "endor/second", sourceSlug: "01-second" };
assert.equal(call(batch, { method: "POST", headers, body: { documents: [input, second] } }).status, 200);
const result = call(documents, { headers, query: { limit: "1" } });
const page = result.body as { documents: Doc[]; total: number; nextOffset: number };
assert.equal(page.total, 2); assert.equal(page.nextOffset, 1);
assert.equal(page.documents[0].content, undefined);
assert.equal((call(documents, { headers, query: { limit: "1", offset: "1" } }).body as typeof page).documents[0].slug, second.slug);
const invalidQueries: Record<string, string | string[]>[] = [
{ limit: "101" }, { offset: "-1" }, { limit: ["1", "2"] }, { limit: "1e2" },
];
for (const query of invalidQueries) assert.equal(call(documents, { headers, query }).status, 400);
assert.equal(result.headers["cache-control"], "private, no-store");
}));
test("late batch conflict rolls back earlier rows and their revision history", () => isolated(({ headers }) => {
saveDocument({ ...input, slug: "endor/existing", sourceSlug: "existing" }, 0);
const conflict = { ...input, slug: "endor/existing", sourceSlug: "existing", revision: 0 };
assert.equal(call(batch, { method: "POST", headers, body: { documents: [input, conflict] } }).status, 409);
assert.equal(readDocument(input.slug), null);
assert.equal(documentHistory(input.sourceSlug).length, 0);
assert.equal(documentHistory("existing").length, 1);
assert.equal(allDocuments().length, 1);
}));
test("idempotent retries return the original receipt without creating another revision", () => isolated(({ headers }) => {
const keyed = { ...headers, "idempotency-key": "upload-1" };
const first = call(documents, { method: "POST", headers: keyed, body: input });
const second = call(documents, { method: "POST", headers: keyed, body: input });
assert.equal(first.status, 200); assert.equal(second.status, 200);
assert.equal((second.body as { replayed: boolean }).replayed, true);
assert.equal(documentHistory(input.sourceSlug).length, 1);
assert.equal(call(documents, { method: "POST", headers: keyed, body: { ...input, content: "Different" } }).status, 409);
assert.equal(call(documents, { method: "POST", headers, body: input }).status, 409);
}));
test("invalid batch members, duplicate identifiers, raw images and malformed fields never write", () => isolated(({ headers }) => {
for (const body of [{ documents: [] }, { documents: [input, input] },
{ documents: [input], unexpected: true }, { documents: Array.from({ length: 101 }, () => input) }])
assert.equal(call(batch, { method: "POST", headers, body }).status, 400);
for (const body of [{ ...input, revision: undefined }, { ...input, typo: true },
{ ...input, slug: "../private" }, { ...input, content: "![raw](/figures/original.png)" }, null])
assert.equal(call(documents, { method: "POST", headers, body }).status, 400);
assert.deepEqual(allDocuments(), []);
assert.equal(call(documents, { method: "DELETE", headers }).status, 405);
assert.equal(call(item, { headers, query: { slug: ["missing"] } }).status, 404);
}));
+351
View File
@@ -0,0 +1,351 @@
import test from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import seed from "../../../content/research/ai-companies.seed.json";
import coverageAudit from "../../../content/research/ai-companies.coverage.json";
import incomeReference from "../../../content/research/ai-income-analysis.json";
import { readResearchSnapshot } from "../src/lib/ai-research-store";
import { openSiteDatabase } from "../src/lib/site-database";
import { categorySummary, evidenceUrl, reviewCompanyIds, validateResearch, type ResearchSnapshot } from "../src/lib/ai-research";
import { consumeCode, initializeStore } from "../src/lib/auth-store";
import { newAuthConfig } from "../src/lib/auth";
import { describeIncome, groupIncome, platformIncomeSample } from "../src/lib/research-statistics";
test("research revisions share the authentication database and preserve replay limits", () => {
const dir = mkdtempSync(join(tmpdir(), "site-research-"));
const previous = process.env.AUTH_CONFIG_FILE;
process.env.AUTH_CONFIG_FILE = join(dir, "config.json");
try {
initializeStore();
const config = newAuthConfig();
for (let i = 0; i < 20; i++) consumeCode(config, "invalid");
assert.equal(consumeCode(config, "invalid"), "limited");
const initial = readResearchSnapshot();
assert.equal(initial.companies.length, 1023);
assert.equal(initial.evidence.length, 1310);
assert.equal(initial.observations.length, 189);
assert.deepEqual(initial.candidateBatches, seed.candidateBatches, "candidate gaps persist in the same database metadata");
assert.deepEqual(initial.directoryRechecks, seed.directoryRechecks, "follow-up classifications persist without rewriting the discovery audit");
assert.deepEqual(readResearchSnapshot(), initial, "reopening does not duplicate records");
const db = openSiteDatabase();
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all() as { name: string }[];
assert.ok(tables.some((r) => r.name === "login_state"));
assert.ok(tables.some((r) => r.name === "research_companies"));
assert.equal(db.prepare("PRAGMA foreign_keys").get()?.foreign_keys, 1);
db.close();
const next = structuredClone(seed) as ResearchSnapshot;
next.version += "-revision-test";
next.companies[0].name = "Revised company";
assert.equal(readResearchSnapshot(next).companies[0].name, "Revised company");
assert.deepEqual(readResearchSnapshot(), initial, "old release still reads its original revision");
assert.equal(consumeCode(config, "invalid"), "limited", "research import must not reset auth limits");
const collision = structuredClone(seed) as ResearchSnapshot;
collision.companies[0].name = "Changed without revision";
assert.throws(() => readResearchSnapshot(collision), /new revision/);
assert.deepEqual(readResearchSnapshot(), initial, "failed import leaves valid revision intact");
} finally {
if (previous === undefined) delete process.env.AUTH_CONFIG_FILE;
else process.env.AUTH_CONFIG_FILE = previous;
rmSync(dir, { recursive: true, force: true });
}
});
test("research validation rejects broken evidence and unsafe source links", () => {
validateResearch(seed as ResearchSnapshot);
const invalid = structuredClone(seed) as ResearchSnapshot;
invalid.observations[0].evidence = "missing";
assert.throws(() => validateResearch(invalid), /observation/);
assert.equal(evidenceUrl("javascript:alert(1)"), undefined);
assert.equal(evidenceUrl("/local-link"), undefined);
assert.equal(evidenceUrl("https://example.com/evidence"), "https://example.com/evidence");
});
test("reviews link explicit companies without turning global or excluded cases into companies", () => {
const snapshot = structuredClone(seed) as ResearchSnapshot;
assert.equal(snapshot.reviews.filter((r) => r.scope === "companies").length, 60);
assert.equal(snapshot.reviews.filter((r) => r.scope === "dataset").length, 10);
assert.equal(snapshot.reviews.filter((r) => r.scope === "excluded-candidate").length, 30);
const review = snapshot.reviews.find((r) => r.id === "R4")!;
assert.deepEqual(reviewCompanyIds(snapshot, review), ["AI007", "AI013", "AI021", "AI034"]);
assert.deepEqual(reviewCompanyIds(snapshot, snapshot.reviews.find((r) => r.id === "CN-R-PSI")!), []);
const oldReview = structuredClone(snapshot.reviews.find((r) => r.id === "TECH-GRAD-R-SCOPE")!);
delete oldReview.scope;
delete oldReview.companyIds;
assert.deepEqual(reviewCompanyIds(snapshot, oldReview), ["AI051"], "old revisions retain evidence-owner fallback");
review.companyIds = ["unknown-company"];
assert.throws(() => validateResearch(snapshot), /research review/);
review.companyIds = ["AI007", "AI007"];
assert.throws(() => validateResearch(snapshot), /research review/);
review.companyIds = [];
assert.throws(() => validateResearch(snapshot), /research review/);
});
test("disclosure counts exclude client income, biographies, targets and duplicate milestones", () => {
const snapshot = seed as ResearchSnapshot;
const summary = categorySummary(snapshot);
assert.equal(summary.reduce((n, c) => n + c.count, 0), 1023);
assert.equal(summary.reduce((n, c) => n + c.self, 0), 26);
assert.equal(summary.reduce((n, c) => n + c.estimate, 0), 1);
assert.equal(summary.reduce((n, c) => n + c.platform, 0), 16);
assert.equal(summary.reduce((n, c) => n + c.unknown, 0), 980);
assert.equal(snapshot.companies.find((c) => c.name === "Rork")?.revenueStatus, "unknown");
assert.equal(snapshot.companies.find((c) => c.name === "Result")?.revenueStatus, "unknown");
assert.ok(snapshot.observations.filter((o) => o.selection === "signal").every((o) => o.scope === "公司整体"));
});
test("technical reviews keep accessible materials separate from tested capabilities", () => {
const snapshot = structuredClone(seed) as ResearchSnapshot;
assert.equal(snapshot.companies.filter((c) => c.technicalReview).length, 16);
assert.equal(snapshot.companies.filter((c) => c.technicalReview?.level === "public-artifact").length, 6);
assert.equal(snapshot.companies.filter((c) => c.technicalReview?.level === "independent-test").length, 1);
assert.equal(snapshot.companies.find((c) => c.id === "AI051")?.revenueStatus, "unknown");
assert.match(snapshot.companies.find((c) => c.id === "AI051")!.technicalReview!.testScope!, /Sep 2026/);
assert.ok(snapshot.observations.filter((o) => o.id.startsWith("TECH-GRAD-O-")).every((o) => o.selection === "technical" && o.comparisonGroup === null));
const company = snapshot.companies.find((c) => c.id === "AI061")!;
const review = company.technicalReview!;
review.evidenceIds = ["missing-technical-evidence"];
assert.throws(() => validateResearch(snapshot), /technical review/);
review.evidenceIds = ["TECH-NAIVE-HF"];
review.reviewedAt = "2026-02-30";
assert.throws(() => validateResearch(snapshot), /technical review/);
review.reviewedAt = "2099-01-01";
assert.throws(() => validateResearch(snapshot), /technical review/);
review.reviewedAt = snapshot.asOf;
review.level = "independent-test";
assert.throws(() => validateResearch(snapshot), /technical review/,
"an accessible artifact cannot become a test record without a stated test scope");
});
test("ambiguous ARR claims retain currency, precision and attribution limits", () => {
const snapshot = seed as ResearchSnapshot;
const variant = snapshot.observations.filter((o) => o.company === "AI066");
assert.deepEqual(variant.filter((o) => o.selection === "crosscheck").map((o) => o.value).sort(), [500000, 600000]);
assert.equal(variant.filter((o) => o.selection === "signal").length, 0);
assert.ok(variant.filter((o) => [2500000, 40000000].includes(o.value)).every((o) => o.selection === "excluded"));
const codos = snapshot.observations.find((o) => o.id === "SR-O-AI065-arr")!;
assert.equal(codos.bound, "≥");
assert.equal(codos.unit, "币种未注明");
assert.equal(codos.comparisonGroup, null);
assert.ok(snapshot.observations.filter((o) => o.id.startsWith("SR-O-")).every((o) => o.comparisonGroup === null && o.unit !== "USD"));
assert.equal(snapshot.companies.find((c) => c.id === "AI071")?.year, 2021);
const rocket = snapshot.observations.find((o) => o.id === "ROCKET-O-arr")!;
assert.equal(rocket.selection, "historical");
assert.equal(rocket.comparisonGroup, null);
assert.notEqual(rocket.scope, "公司整体");
assert.equal(snapshot.companies.find((c) => c.id === "AI070")?.revenueStatus, "unknown");
assert.equal(snapshot.observations.filter((o) => o.company === "AI070").length, 0,
"unreadable announcement summaries do not become numeric ARR");
});
// Retractions and forecasts must stay visible for review without becoming revenue signals.
test("retracted ARR and projected margins remain excluded", () => {
const snapshot = seed as ResearchSnapshot;
const cluely = snapshot.companies.find((c) => c.name === "Cluely")!;
assert.equal(cluely.revenueStatus, "unknown");
assert.ok(snapshot.reviews.some((r) => r.company === "Cluely" && r.evidenceIds.includes("E100")));
const retracted = snapshot.observations.filter((o) => o.company === cluely.id);
assert.ok(retracted.length > 0);
assert.ok(retracted.every((o) => o.selection === "excluded"));
const forecast = snapshot.observations.find((o) => o.kind === "非GAAP毛利率预期")!;
assert.equal(forecast.selection, "excluded");
const peec = snapshot.companies.find((c) => c.name === "Peec AI")!;
assert.equal(peec.team, 100);
assert.equal(peec.teamBound, "≥");
const currentTeam = snapshot.observations.find((o) => o.id === "PEEC-JOB-TEAM")!;
assert.equal(currentTeam.value, peec.team);
assert.equal(currentTeam.bound, peec.teamBound);
const historicalTeam = snapshot.observations.find((o) => o.id === "O067")!;
assert.equal(historicalTeam.value, 70);
assert.equal(historicalTeam.bound, ">");
assert.equal(snapshot.observations.filter((o) => o.company === peec.id && o.selection === "signal").length, 1);
assert.ok(snapshot.observations.some((o) => o.company === peec.id && o.selection === "historical-estimate"));
});
test("directory coverage reconciles every candidate and keeps profile-only income unknown", () => {
const snapshot = seed as ResearchSnapshot;
const coverage = snapshot.coverage!;
assert.equal(coverageAudit.records.length, coverage.candidateRecords);
assert.equal(new Set(coverageAudit.records.map((r) => r.ycId)).size, coverage.candidateRecords);
const count = (status: string) => coverageAudit.records.filter((r) => r.status === status).length;
assert.equal(count("imported"), coverage.newProfiles);
assert.equal(count("existing"), coverage.existingProfiles);
assert.equal(count("date-conflict"), coverage.dateConflicts);
assert.equal(count("year-outside-or-missing"), coverage.otherOrMissingYear);
assert.equal(count("ai-unclear"), coverage.unclearAI);
for (const row of coverageAudit.records.filter((r) => r.status === "imported")) {
const company = snapshot.companies.find((c) => c.id === `YC${row.ycId}`)!;
assert.ok(company.profileOnly || company.directoryOrigin === "yc-2025-2026");
assert.equal(company.url, row.source);
if (company.profileOnly) assert.equal(company.revenueStatus, "unknown");
assert.equal(company.year, row.foundedYear);
assert.ok([2025, 2026].includes(company.year!));
}
const invalid = structuredClone(snapshot);
invalid.coverage!.newProfiles += 1;
assert.throws(() => validateResearch(invalid), /coverage accounting/);
const promoted = snapshot.companies.find((c) => c.id === "YC30215")!;
assert.equal(promoted.profileOnly, false);
assert.equal(promoted.directoryOrigin, "yc-2025-2026");
assert.equal(promoted.revenueStatus, "self");
const lostOrigin = structuredClone(snapshot);
delete lostOrigin.companies.find((c) => c.id === promoted.id)!.directoryOrigin;
assert.throws(() => validateResearch(lostOrigin), /coverage accounting/);
});
test("income descriptions report sample dispersion and maximum-value sensitivity", () => {
const stats = describeIncome([100, 200, 300])!;
assert.equal(stats.mean, 200);
assert.equal(stats.median, 200);
assert.equal(stats.sampleDeviation, 100);
assert.equal(stats.cv, .5);
assert.equal(stats.largestShare, .5);
assert.equal(stats.meanWithoutLargest, 150);
assert.equal(stats.largestRemovalDrop, .25);
assert.equal(describeIncome([5])!.cv, null);
assert.equal(describeIncome([0, 0])!.mean, 0, "observed zero is distinct from missing");
assert.equal(describeIncome([0, 0])!.cv, null);
assert.equal(describeIncome([]), null);
assert.equal(describeIncome([100, NaN]), null);
assert.equal(describeIncome([-1]), null);
assert.ok(describeIncome([1, 2, 100])!.largestRemovalDrop! > .95);
});
test("platform samples exclude stale data and keep ARR, estimates and collections separate", () => {
const snapshot = seed as ResearchSnapshot;
const recent = platformIncomeSample(snapshot, { windowDays: 7 });
assert.equal(recent.points.length, 14);
assert.equal(recent.excluded.length, 3);
assert.ok(recent.points.every((p) => p.observation.metric === "mrr" && p.observation.selection === "platform"));
assert.deepEqual(new Set(recent.excluded.map((p) => p.observation.company)), new Set(["AI016", "MR013", "MR014"]));
assert.ok(recent.points.some((p) => p.company.name === "TrackAI" && p.observation.connectionExpired), "dated recent value is not a claim of active connection");
const older = platformIncomeSample(snapshot, { windowDays: 90 });
assert.equal(older.points.length, 15);
assert.ok(older.points.some((p) => p.company.id === "AI016"));
const scaled = platformIncomeSample(snapshot, { windowDays: 7, annualize: true });
const monthlyGroups = groupIncome(recent.points);
const annualGroups = groupIncome(scaled.points);
for (const group of monthlyGroups) {
const annual = annualGroups.find((g) => g.key === group.key)!;
assert.ok(Math.abs(annual.stats.mean - group.stats.mean * 12) < 1e-6);
if (group.stats.cv !== null) assert.ok(Math.abs(annual.stats.cv! - group.stats.cv) < 1e-10);
}
const invalid = structuredClone(snapshot);
invalid.observations = invalid.observations.filter((o) => o.company === "MR001" && o.metric === "mrr");
const first = invalid.observations[0];
invalid.observations.push({ ...first, id: "future", observedAt: "2026-11-01", value: 999999 });
invalid.observations.push({ ...first, id: "bad-date", observedAt: "2026-02-30", value: 999999 });
invalid.observations.push({ ...first, id: "currency", unit: "EUR", value: 999999 });
invalid.observations.push({ ...first, id: "older", observedAt: "2026-10-28", value: 1 });
const selected = platformIncomeSample(invalid, { windowDays: 7 });
assert.equal(selected.points.length, 1);
assert.equal(selected.points[0].observation.id, first.id, "bad newer data and older duplicate must not replace latest valid point");
assert.equal(selected.excluded.length, 4);
assert.throws(() => platformIncomeSample(snapshot, { windowDays: -1 }), /window/);
});
test("distribution statistics match independently calculated snapshot references", () => {
const snapshot = seed as ResearchSnapshot;
assert.equal(incomeReference.sourceVersion, snapshot.version);
for (const reference of incomeReference.windows) {
const sample = platformIncomeSample(snapshot, { windowDays: reference.days });
assert.deepEqual(new Set(sample.points.map((p) => p.company.id)), new Set(reference.products));
const groups = groupIncome(sample.points);
assert.equal(groups.length, reference.groups.length);
for (const expected of reference.groups) {
const actual = groups.find((g) => g.category === expected.category && g.provider === expected.provider && g.model === expected.model)!;
assert.equal(actual.stats.n, expected.n);
for (const metric of ["mean", "median", "sampleDeviation", "cv", "meanWithoutLargest", "largestRemovalDrop"] as const) {
const value = expected[metric];
if (value === null) assert.equal(actual.stats[metric], null);
else assert.ok(Math.abs(actual.stats[metric]! - value) < 1e-6, metric);
}
}
}
});
test("product launch candidates preserve unresolved years and many launches per company", () => {
const snapshot = structuredClone(seed) as ResearchSnapshot;
const batch = snapshot.candidateBatches![0];
assert.equal(batch.complete, false);
assert.equal(batch.records.length, 19);
const kilo = batch.records.filter((r) => r.companyId === "AI072");
assert.equal(kilo.length, 2, "IDE and hosted products resolve to one company");
assert.equal(snapshot.companies.filter((c) => c.id === "AI072").length, 1);
assert.ok(batch.records.some((r) => r.status === "pending-year" && !r.companyId));
assert.ok(batch.records.some((r) => r.status === "existing-outside-cohort" && r.companyId === "AI054"));
kilo[0].companyId = "missing-company";
assert.throws(() => validateResearch(snapshot), /research candidate/);
});
test("annual launch archives exclude older companies only with evidence and reuse existing records", () => {
const snapshot = structuredClone(seed) as ResearchSnapshot;
const batch = snapshot.candidateBatches!.find((b) => b.id === "PH-2025-visible-1")!;
assert.equal(batch.complete, false);
assert.equal(batch.records.length, 19);
const older = batch.records.filter((r) => r.status === "outside-cohort");
assert.equal(older.length, 16);
assert.ok(older.every((r) => !r.companyId && r.evidenceIds?.length));
assert.equal(batch.records.find((r) => r.name === "Trace")?.companyId, "YC30687");
const trace = snapshot.companies.find((c) => c.id === "YC30687")!;
assert.equal(trace.profileOnly, false);
assert.equal(trace.directoryOrigin, "yc-2025-2026");
assert.equal(trace.revenueStatus, "unknown");
assert.ok(!snapshot.observations.some((o) => o.evidence === "TRACE-HOME"), "demo metrics must not become reported results");
older[0].evidenceIds = [];
assert.throws(() => validateResearch(snapshot), /research candidate/);
older[0].evidenceIds = ["missing-proof"];
assert.throws(() => validateResearch(snapshot), /research candidate/);
});
test("unreconciled directory financials remain source reviews instead of income observations", () => {
const snapshot = seed as ResearchSnapshot;
const review = snapshot.reviews.find((r) => r.id === "PH-R-SOURCE-QUALITY")!;
assert.equal(review.scope, "dataset");
assert.ok(review.evidenceIds.includes("PH-TANA-DR"));
assert.equal(reviewCompanyIds(snapshot, review).length, 0);
assert.ok(!snapshot.observations.some((o) => o.evidence === "PH-TANA-DR"));
assert.equal(snapshot.candidateBatches!.flatMap((b) => b.records).filter((r) => r.status === "pending-year").length, 17);
});
test("product pivots and founder histories do not become new company years or current revenue", () => {
const snapshot = seed as ResearchSnapshot;
const pivot = snapshot.companies.find((c) => c.id === "AI073")!;
assert.equal(pivot.year, null, "CRM launch is not a verified company founding year");
assert.equal(pivot.revenueStatus, "unknown");
const candidate = snapshot.candidateBatches!.flatMap((b) => b.records).find((r) => r.id === "PH26-11")!;
assert.equal(candidate.status, "existing-outside-cohort");
assert.equal(candidate.companyId, pivot.id);
assert.ok(!platformIncomeSample(snapshot, { windowDays: null }).points.some((point) => point.company.id === pivot.id));
assert.ok(!snapshot.observations.some((o) => ["PH-FUNDRAISLY-ABOUT", "LF-PIVOT", "LF-HISTORY"].includes(o.evidence)), "other ventures' ARR, users and funding must not transfer");
});
test("follow-up evidence can admit an uncertain directory candidate without rewriting its original status", () => {
const snapshot = structuredClone(seed) as ResearchSnapshot;
const followup = snapshot.directoryRechecks!.find((row) => row.ycId === 36088)!;
const original = coverageAudit.records.find((row) => row.ycId === followup.ycId)!;
assert.equal(original.status, "ai-unclear");
assert.equal(followup.originalStatus, original.status);
assert.equal(snapshot.companies.find((c) => c.id === followup.companyId)?.year, 2026);
assert.equal(snapshot.candidateBatches!.flatMap((b) => b.records).find((r) => r.name === "OpenSEO")?.companyId, followup.companyId);
assert.ok(!snapshot.observations.some((o) => ["SEO-PRICE", "UP-YC", "PAZI-PRICE"].includes(o.evidence)), "pricing, other ventures' ARR and prepaid balances stay outside income observations");
followup.companyId = "missing-company";
assert.throws(() => validateResearch(snapshot), /directory recheck/);
});
test("Chinese discovery entries preserve unread articles and use separate primary evidence", () => {
const snapshot = structuredClone(seed) as ResearchSnapshot;
const batch = snapshot.candidateBatches!.find((b) => b.id === "JQ-2026-targeted-1")!;
assert.equal(batch.complete, false);
assert.equal(batch.records.length, 4);
assert.ok(batch.records.every((row) => row.kind === "company" && row.profileStatus === "unavailable"));
assert.equal(batch.records.filter((row) => row.status === "linked").length, 2);
assert.equal(batch.records.find((row) => row.name === "Utopai")?.status, "outside-cohort");
assert.ok(!snapshot.observations.some((o) => ["PS-CODE", "SG-START", "SG-APR", "SSI-HISTORY"].includes(o.evidence)), "task costs, investment, capacity and financing are not revenue");
const prism = snapshot.companies.find((c) => c.id === "AI075")!;
assert.equal(prism.team, null, "a team range or linked employees must not become exact headcount");
batch.records[0].url = null;
assert.throws(() => validateResearch(snapshot), /research candidate/);
});
-133
View File
@@ -1,133 +0,0 @@
# Endor 系统架构
Endor 的概念模型把全球访问、区域运行时和对象数据连接起来:请求从统一入口进入,在合适的区域找到 Nexus Runtime,再由它承载的 Aster VM 执行对象操作。PostgreSQL、Aerarium 和 S3 各自维护独立的分片群,在区域内保持高可用,并由统一备份系统追踪所有区域、所有存储类型的分片与恢复材料。
> **架构说明**:本文按当前讨论绘制目标架构,不表示这些组件和协议已经全部实现。图中的区域、节点、分片数量仅为示例;CDN 和身份服务的接入方式是建议方案。
## 架构总览
![Endor 架构:全球入口连接北美、亚洲及其他区域;各区两个 Traefik 与五个 Nexus Runtime 全连接,每个 Nexus 侧下方配一个 Aster VM;Aerarium 分片群分别与 PostgreSQL、S3 分片群全连接,所有分片汇入统一备份系统](/figures/endor-architecture.svg)
图中绿色/蓝色实线表示请求路径或区域内数据依赖,紫色虚线表示身份控制与公钥分发,蓝色点线表示 CDN 回源,金色虚线表示向统一备份系统采集数据。连线表示可达或依赖关系,**不表示请求向所有节点广播**。
## 本地、自部署与平台挂载
![Endor 部署与对象挂载:两组自部署通过 Nginx 或 Traefik 接入,各自包含一到两个 Nexus Runtime、配套 Aster VM 和 Aerarium、PostgreSQL、S3;自部署对象池可挂载到平台,Windows、Linux、macOS、iOS、Android 上的 Tessera 通过本地 Nexus 挂载本地和远端对象](/figures/endor-deployment.svg)
这张图将部署规模收起来,强调对象可以在哪里运行、从哪里挂载。两组自部署示例分别使用一个和两个 Nexus Runtime,每个 Nexus 都带一个 Aster VM;**每个 Nexus 在示例中配一套简单的 Aerarium、PostgreSQL 和 S3**;这用于表达小规模自部署的完整组成。Aerarium 依赖 PostgreSQL 和 S3,右侧平台则将多区域、运行时和存储分片简化为小型集群。
自部署入口可以选择 Nginx 或 Traefik。如果云服务已经提供合适的托管入口、TLS 和路由能力,就可以省去自行部署网关这一环;仍需配置服务暴露和访问权限。
紫色虚线表示**自部署 Aerarium 可以经授权挂载到 Endor 平台端**:平台获得访问源对象池的逻辑入口,源端仍保留数据归属。它不是将整个 PostgreSQL 或 S3 直接公开,也不隐含自动上传、镜像、备份或数据合并。
下方五种系统都运行 Tessera 前端,并带有本地 Nexus Runtime 和对应 Aster VM。本地对象先挂载到自带的 Nexus;本地 Nexus 也可按需挂载自部署或平台端的远程对象池,让 Tessera 通过本地运行时访问它们。蓝色线路表示可选择的远端连接,不要求所有设备同时挂载所有服务。该图延续本文的目标架构约定,不代表五个平台的运行时集成都已完成;远端身份映射、连接协议、写入权限和断线行为仍需继续定义。
## 全球入口与区域入口
客户端包括浏览器、Tessera、SDK 和 CLI。`endorphin API` 是逻辑上的全球流量入口,尚未在本文规定一个真实的域名。全球调度根据健康、延迟、项目归属和数据放置策略选择区域;不能只选择网络最近的区域而忽略对象在哪个分片。
图中展开北美和亚洲两个区域,并用“ … / etc · 其他区域”表示可以继续扩展。每个区域有自己的负载均衡入口,下面是 Traefik 网关,负责按配置进行 TLS、主机名或路径路由。图中的第二个 Traefik 标记为 **HA 副本**:多副本是生产冗余选项,单实例概念部署不要求两个网关。
### 为什么画成二分全连接
每个区域示例中有两个 Traefik 和五个 Nexus Runtime,画出全部十条边,即二分图 **K₂,₅**。网关使用独立的路由分流图标,与 Nexus 的服务器图标区分。每个网关都能把请求路由到任意一个符合条件的健康 Runtime,避免把一个网关固定绑定到一个运行时。
这是逻辑可达关系。实际转发仍需考虑服务发现、健康检查、项目和对象归属,以及有状态连接的路由策略;Runtime 之间并没有因此形成全连接网状网络。
## Nexus Runtime 与 Aster VM
此处采用 **一个 Nexus Runtime 节点配一个 Aster VM** 的概念约定。Nexus 表示对外接入与运行时承载边界,Aster VM 执行对象相关逻辑。图中每台服务器侧下方单独画出一个 VM 芯片,用点线连接到对应 Nexus;节点与 VM 采用错位排布,保持一对一归属。
请求经过区域入口和 Traefik 到达 Nexus,再定位目标分片。图中运行时下方的连接汇入分片路由层,表示节点可以按归属访问区域分片,**不是**「Runtime 1 只能访问分片 1」。对象身份、远程引用、生命周期与调用语义仍需结合[节点与对象挂载草案](/docs/02-mounting-draft)继续定义。
## 三类存储各自独立分片
PostgreSQL、Aerarium Object data pool 和 S3 是三组独立的分片群。图中每组各展开三个分片,数量可以独立增长,分片边界也可以不同;不能将一个 PG 分片、一个 Aerarium 分片和一个 S3 分片打包成固定“三件套”。
| 分片群 | 概念职责 | 分片标识示例 |
| ------------------------- | ------------------------------------------------------------ | ---------------------------- |
| PostgreSQL | 结构化元数据、对象索引及需要事务约束的状态;具体数据模型待定 | NA-PG-01、NA-PG-02、NA-PG-03 |
| Aerarium Object data pool | 对象数据的逻辑组织、对象池状态和访问层;同时依赖 PG 与 S3 | NA-AO-01、NA-AO-02、NA-AO-03 |
| S3 兼容存储 | Blob、文件、快照和适合对象存储的数据;具体格式待定 | NA-S3-01、NA-S3-02、NA-S3-03 |
### 分片群之间的全连接
每个 Aerarium 分片都能按映射访问任意一个 PostgreSQL 分片,也能访问任意一个 S3 分片。图中左右各画一组 **K₃,₃**:Aerarium ↔ PostgreSQL 有九条边,Aerarium ↔ S3 也有九条边;每区合计十八条存储关系边。
这些线表示逻辑可达关系,实际读写仍根据对象归属、分片映射、授权与健康状态选择目标。它们不表示广播,也不表示所有分片保存相同数据。PostgreSQL 和 S3 之间没有凭空增加直接全连接;两种存储通过 Aerarium 的对象模型与版本映射协作。
运行时访问先进入对象池的分片定位层,再由 Aerarium 按映射访问 PG 和 S3。因此不同层可以采用不同的分片数量和容量规划,而无需一一绑定。
### 区域内高可用
每个存储图标下面有一个小型副本图标,用点线连接,表示本区域的高可用副本。生产部署应跨独立故障域放置,具体可以是不同可用区或独立节点。
这是逻辑 HA 要求,各层的实现不同:PostgreSQL 可以使用主备复制,Aerarium 需要自己的状态协调和故障恢复设计,S3 的耐久性与副本由选定的存储系统提供。图不强制三者采用同一种同步复制机制,也不把单纯增加副本等同于已经实现故障自动切换。
## 一个统一的备份系统
备份是覆盖所有区域的总体系统,不按“北美备份亚洲、亚洲备份北美”分成两个固定系统。它统一编排各区域、各存储类型的备份采集、持久化、校验、保留与恢复。物理副本应隔离源区域的故障风险,实际存放位置由备份策略决定;图中不将该系统固定放进任何业务区域。
图中金色线路将每个区域的三类分片群接入同一备份边界,代表采集组内全部分片。统一恢复目录按“区域 + 存储类型 + 分片 ID”追踪每个分片,避免遗漏或将不同层的编号误当作同一个分片。
### 备份中的 PG、Aerarium、S3 分别是什么
| 备份内容 | 保存什么 | 恢复时的用途 |
| --------------- | -------------------------------------------------------------------- | ------------------------------------------ |
| PostgreSQL 备份 | 各 PG 分片的基础备份、WAL 与可恢复时间点等事务恢复材料 | 恢复结构化元数据与事务状态 |
| Aerarium 备份 | 各对象池分片的状态、索引、对象身份和版本映射等恢复材料,具体格式待定 | 重建对象池,并关联 PG 恢复点与 S3 对象版本 |
| S3 备份 | 各 S3 分片的实际对象版本、Blob、文件及快照 | 恢复被对象池引用的实际字节数据 |
这里展示的是**统一系统内三类不同的备份内容与采集能力**,不是每个备份槽里又放一套在线 PG + Aerarium + S3 服务。系统还要维护统一恢复清单、校验和、重试状态,以及各层的版本对应关系。
恢复某个对象或项目时,清单应能定位所需的 PG 分片恢复点、Aerarium 分片状态与 S3 对象版本。因为三类存储独立分片,恢复集合也可能涉及多个不同编号的分片;不能按固定三件套恢复,也不能只备份其中一种存储就宣称整个对象可恢复。
### “最终一定拿到数据”需要怎样的保证
设计目标是:正常访问优先本区域;本地不可用时,仍能找到异地保存的数据。需要区分两类能力:
- **异地在线副本**:已有服务能读取它;追平状态、授权和路由满足要求后,才可承担故障读取。
- **异地备份**:保留了恢复材料,需要恢复 PostgreSQL、重建 Aerarium 并校验对象版本后才能提供服务,通常更慢。
> **保证边界**:异步复制与定期备份不能无条件保证最后一笔已确认写入不会丢失。若源区在复制完成前永久丢失,未到达异地的数据仍可能丢失。当前图承诺的是“已校验恢复点可恢复”的目标,而非已实现的零数据丢失保证。
要实现更强的承诺,需要明确写入确认条件。例如必须等跨区持久化成功才返回写入成功,或者以独立耐久日志作为重放来源,并设计重试、校验、告警与恢复演练。这会增加延迟或实现成本,不能只靠一条“最终一致”虚线获得。
后续设计需要分别确定 **RPO**(可接受的数据丢失窗口)和 **RTO**(恢复服务所需时间),以及备份保留、删除传播、加密密钥和数据跨区合规策略。
## CDN 应该放在哪里
建议把 CDN 作为面向静态和可缓存内容的边缘路径,与动态 API 调度区分:
1. 客户端请求静态前端、文档或允许缓存的对象,优先命中 CDN;命中后直接返回,无需访问 Nexus。
2. 缓存未命中时,CDN 回源到指定的 S3 兼容存储,或专门的资源服务。图中仅示例回源到亚洲区域的 S3,并不把亚洲设为唯一源站。
3. 私有对象可使用短时签名 URL、受控回源或独立授权服务。缓存键、过期、权限隔离和失效策略需要单独设计。
4. 登录、写入、实时连接和个性化动态 API 默认不进入共享缓存。CDN 能代理这些流量,不代表应该缓存这些响应。
CDN 是可替换、可选的加速层,不是数据库副本,也不承担跨区灾难恢复的唯一责任。
## 身份服务是否依赖 Nexus
**建议在逻辑上独立,不把它画成依赖某个业务 Nexus 的服务。** 客户端向身份服务登录或刷新凭证;Nexus 验证访问凭证、项目归属和操作权限后才接受业务请求。
图中紫色线路表示公钥或认证配置的分发关系:使用适当的签名访问令牌方案时,Nexus 可以缓存 JWKS,在本地完成签名及必要声明校验。具体访问令牌格式尚未确定,不能把 OpenID Connect 的 ID Token 直接当作所有 API 的授权凭证。
如果采用不透明令牌、即时撤销或实时策略评估,可能需要在线内省或授权查询;这会引入身份服务的在线依赖,需要单独设计可用性和失败策略。已有令牌可离线验证也不意味着公钥轮换、过期、撤销和权限变化可以不处理。
身份服务本身仍可以使用 PostgreSQL、缓存和密钥管理等基础设施;**逻辑独立不等于没有存储依赖**。将来即使选择在通用 Nexus 基础设施上托管它,也应保留独立的故障和信任边界,避免启动、登录与业务运行时形成循环依赖。
## 继续确定的设计边界
- 全球入口如何发现项目与分片的归属,跨区域请求采用转发还是让客户端重连。
- Nexus 接入职责与 Aster VM 边界、连接亲和性和 Runtime 故障迁移。
- Aerarium 的数据格式、事务边界、对象版本和跨存储一致恢复点。
- 区域内 HA 的实际协议与跨区域 RPO/RTO、故障读取与恢复流程。
- 身份签发者、访问令牌验证与撤销机制,以及私有内容的 CDN 授权。
## 参考依据
以下资料仅用于解释通用组件的能力,不证明 Endor 已经实现本文的概念设计:
- [Traefik:服务与后端负载均衡](https://doc.traefik.io/traefik/master/routing/services/)。
- [OpenID Connect Discovery:配置发现和 JWKS URI](https://openid.net/specs/openid-connect-discovery-1_0.html)。
- [Amazon S3:同区与跨区异步复制](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication.html)。本文中的 S3 指兼容对象存储,具体部署并未指定 AWS。
-30
View File
@@ -1,30 +0,0 @@
# 开始使用
Tabularium 是 Endor 的文档工作台。文档与图形源码都保存在同一个仓库。
## 启动
在仓库根目录运行:
```sh
pnpm install --frozen-lockfile
uv sync --project tools/figures --locked
pnpm dev
```
浏览器打开 http://127.0.0.1:3000 。
## 添加文档
在 `content/docs` 下添加 Markdown 文件,例如 `04-runtime.md`。文件名使用小写字母、数字和连字符;第一个一级标题是导航标题。该文件对应 `/docs/04-runtime`。
开发模式下刷新页面读取修改;本地生产预览需要重新构建。
## 检查
```sh
pnpm check
pnpm start
```
本地开发入口只监听 127.0.0.1。main 推送会在 ces-control 上验证并自动部署,服务器入口默认 18135。相同构建输入复用已验证镜像;源码变化时复用依赖与 Next.js 缓存。Pull Request 只验证,不部署。
-25
View File
@@ -1,25 +0,0 @@
# 节点与对象挂载(草案)
> 状态:讨论草案。以下记录当前设计方向,不代表协议已经实现或接口已经定稿。
## 设计方向
每一个 Aster VM 是一个节点。实例之间可以通过统一接入协议挂载对象。
接入对象来源包含 Endor 官方配件,例如 Tessera GUI,以及通过 Endor Python、C、Go、JavaScript 等 SDK 接入的第三方程序。这两类接入采用同一套协议。
## 待确认的术语
| 概念 | 当前提议 | 状态 |
| --- | --- | --- |
| Node | 一个 Aster VM | 用户提出的模型 |
| Endpoint | 统一协议的连接端点 | 术语提议 |
| Export Root | 对外导出的顶级对象入口 | 术语提议 |
| Tessera 顶级对象 | 协议层称 root,挂载名可为 tessera | 尚未确定 |
## 后续设计问题
- 对象的导出、身份、远程引用与生命周期。
- 方法调用、属性访问和事件传播的语义。
- 授权、断连、错误与重新连接。
- 官方配件和不同语言 SDK 的共同协议边界。
-19
View File
@@ -1,19 +0,0 @@
# 图形与脚本
Python 绘图项目位于 `tools/figures`,使用 drawsvg 输出可编辑 SVG。脚本与输出都保留在 Git 中。
```sh
pnpm figures
```
下图是制图工作流的最小示例,用于验证从 Python 源码到文档图片的完整链路。
![制图工作流:Python 源码生成 SVG,再由本地文档引用](/figures/workflow.svg)
## 扩展方式
在 `tools/figures/src/endor_figures` 下保留各张图的生成逻辑,并在 CLI 中调用。输出目录通过源码位置计算,不依赖运行命令时所在的目录。
CI 会重新生成图片并检查与提交版本一致。Python 依赖保留独立缓存,不进入生产运行镜像。
图形应使用本地字体与资源,并明确标注草案状态。未来可按具体需求加入自动布局、PNG 转换或 TypeScript SVG 工具。
-273
View File
@@ -1,273 +0,0 @@
# Endor 的意义:从程序入口到对象操作
这篇文档用来逐步整理我们为什么要做 Endor。先记录一个切入点:**把对象的操作权交还给用户与 AI**。后续讨论可以在这里补充、修正,暂不把它写成一份已经定稿的项目宣言。
> **讨论草案**:以下是希望探索的系统组织方式。图中进程和对象的数量、对象关系与操作路径都是示意,不表示当前实现或性能测量。
## 一对图:我们希望改变什么
![从程序入口到对象操作的对比:上图中 OS 分出九个进程,按二、四、三个分为三组,对应三个程序;对象以进程内的随机小圆圈表示,用户通过程序入口访问。下图中 OS 只分出少量进程,承载 Endorphin 的对象关系网络,用户与 AI 用多条贝塞尔曲线直接指向选定对象;OS、进程区与 Endorphin 都位于 Endor OS 边界内](/figures/endor-purpose.svg)
### 第一张图:用户面对程序
从 OS 出发,许多进程组成不同的程序。每个程序可以对应不同数量的进程;图中分别画了两个、四个和三个。进程区里的许多小圆圈表示对象,它们散布在各进程中。
用户通常通过程序提供的界面访问能力,也可能通过 Web 或 API。这里想强调的是操作入口:用户先选择程序,再在程序提供的功能中寻找自己要做的事。图中的对象仍然存在,但通常隐藏在程序的组织和入口之后。
这是一种用于对照的简化视角,并不是说现有程序都无法开放对象或让外部系统组合能力。
### 第二张图:用户与 AI 面对对象
仍然从 OS 出发,但这次只画少量进程,用来承载 Endorphin。接下来展开的是许多相互连接的小圆圈:对象不再只作为程序内部的实现细节出现,而成为可以被引用、选择和操作的基本单位。
用户与 AI 的多条曲线分别指向部分对象,表达我们希望提供的能力:**在授权范围内,直接找到所需对象,对它们执行操作,并把不同对象的能力组合起来**。图中没有把所有对象都连向用户,因为操作权应当是有范围、可控制的。
OS、进程区与 Endorphin 被共同框在 **Endor OS** 的边界内。这是此处对整体系统的命名;是否涉及内核层面的替换、哪些职责由底层 OS 保留,尚未在这张概念图中定义。
## 为什么程序不该是唯一入口
设想我们要把一段会议录像整理成可执行的项目计划。录像在媒体库里,讨论结论写进文档,行动项录入任务工具,补充资料又放在另一个位置。用户需要把时间点、原话、负责人和截止时间反复搬运,才能让这些程序中的内容对上。
困难不只在于点击次数。任务里粘贴的会议摘要,可能无法跟随原始结论的修改;文档里的一段文字,可能没有保留它来自哪个视频片段的关系。用户知道这些内容属于同一件事,系统却往往只保存了分别属于几个程序的数据副本。
AI 参与时也会遇到这种分割。它可能通过 Web 界面、API 或工具调用取得内容,再把结果写进另一套入口。每个入口都能提供有用能力,但对象身份、关联关系和状态变化不一定在这些入口之间保持连续。一次自动化任务成功,也不等于下一次还能准确找到并更新同一对象。
Endor 想探索的是:录像、片段、结论、任务和负责人之间的关系,能否成为可以继续访问和操作的系统结构,而不是只由用户记住、再通过复制粘贴维持。
已有程序也可以用链接、共享数据库、开放 API 或其他方式解决这些问题。Endor 的意义需要通过更连贯的使用体验证明,不能只靠“现有程序彼此隔离”这个前提成立。
## 什么是用户真正想操作的对象
用户想修改的通常不是某个进程里的内存地址,而是有实际含义的东西:一篇文档、一段视频、一个任务、一组设备,或这些内容之间的联系。
在会议整理的例子里,可以先讨论以下对象与关系。这里列的是业务建模示例,不是已经确定的内置类型。
| 对象 | 用户可能希望执行的操作 | 需要保留的关系 |
| --- | --- | --- |
| 会议录像 | 查看、选择片段、引用内容 | 片段来自哪份录像 |
| 讨论结论 | 修订、核对来源、交给其他流程使用 | 依据哪些片段形成 |
| 行动任务 | 修改状态、指派负责人、调整时间 | 对应哪条结论 |
| 项目计划 | 汇集任务、查看进展、调整组织方式 | 包含哪些任务和依赖 |
一个对象能被多个入口使用,不意味着把它复制成多份互不关联的数据。我们希望同一任务可以出现在项目看板、会议记录和个人待办里,入口变化时仍能辨认它是同一个任务。需要快照或独立副本时,也应明确表达这种区别。
对象的身份、当前名称、显示位置和所属进程不能混为一谈。改名、换一个视图或迁移执行位置,是否改变对象身份,应有明确规则。对象删除、替换或不可访问时,保留的引用又如何表现,也是对象模型必须回答的问题。
这不要求把每个临时计算值都做成一个可联网访问的资源。哪些对象需要独立身份、保存和跨端引用,哪些只在一次执行中存在,需要由类型、生命周期和系统成本共同决定。
## “把操作权交还给用户”是什么意思
这里的操作权,首先是让用户能够理解并使用自己的工作对象:找到目标、保留引用、选择合适的入口,并在获准范围内发起操作。它不仅是把程序界面的按钮换成一个通用调用按钮。
- **可定位**:之后仍能找到同一对象,知道名称与引用指向什么。
- **可理解**:能够识别对象的类型、可用操作和当前状态,不必猜测某个界面动作的含义。
- **可操作**:通过明确的输入和操作契约读取、修改或调用能力,并取得可检查的结果。
- **可组合**:把一个对象或操作结果交给其他获准使用它的能力,保留必要的身份和关系。
- **可选择入口**:根据任务选择不同界面或自动化方式,不因更换入口就被迫重新建立全部数据关系。
这些是体验目标,不表示数据所有权、访问权和操作权天然相同。能查看一项任务,不一定能修改;能调用“提交”能力,也不一定能编辑它的实现或直接修改相关的全部资源。对象属于谁、用户此刻能做什么、程序允许产生什么业务效果,需要分别表达。
“交还”也不意味着消除程序提供的业务约束。例如用户调用一个约定好的提交能力,应遵守它的输入、状态和操作范围。把系统的内部存储或任意内存暴露出来,并不能自动带来清晰的对象操作权。
## 程序在 Endor 中还有什么意义
对象成为共同的操作单位后,程序仍然可以提供有价值的组织方式。项目看板擅长安排任务,视频编辑器擅长选择时间片段,专业业务界面则可以把复杂约束组织成容易理解的工作流。
区别在于,我们希望程序不必成为对象唯一的归属入口。同一任务可以由一个界面创建,由另一个界面展示,再交给 AI 协助整理;这些入口使用同一对象身份和约定好的能力,而不是各自建立一份无法关联的任务。
在这个方向上,程序可以承担几种职责:
| 职责 | 对用户的价值 |
| --- | --- |
| 视图与编辑器 | 针对当前任务选择合适的呈现和交互方式 |
| 专业工作流 | 将多个操作、检查和业务步骤组织成可靠流程 |
| 可复用逻辑 | 把一组能力实现为可引用、可调用的程序结构 |
| 与其他系统连接 | 在外部格式和接口与 Endor 对象之间建立明确映射 |
Tessera 可以作为进入对象世界的一种前端;Web 和其他专业程序也可以提供不同入口。这是希望形成的关系,不表示所有现有程序都已经能直接接入,也不表示一个通用界面可以替代全部专业工具。
## 为什么 AI 需要对象,而不只是更多工具
工具让 AI 能够采取动作,对象则让这些动作有一个可以持续引用和理解的目标。以会议整理为例,AI 不只需要“新建任务”这个工具,还需要知道这次处理的是哪次会议、哪条结论、哪些任务已经存在,以及它们之间有什么关系。
如果每次调用只得到一段文本,AI 可能需要反复从描述中重新识别目标。若结果能够保留对象身份、类型和来源关系,后续操作就有机会继续作用于同一目标,而不必每次重建上下文。
我们希望对象模型能够帮助 AI:
- 根据类型和可访问的能力理解目标,而不只依靠界面位置或名称猜测。
- 把操作结果作为后续步骤的输入,保留其来源和关联。
- 在用户、程序和 AI 之间传递同一工作对象,支持继续处理。
- 将“准备修改什么”和“实际修改了什么”组织成可以让用户检查的结果。
这些能力也可以由设计良好的 API 和工具系统提供。Endor 希望进一步让它们成为语言与运行环境中一致的组织方式,减少每个工具单独定义一套对象标识、结果格式和上下文约定的负担。是否真的减少了集成成本,需要在具体工作流里验证。
对象模型不会自动解决 AI 的理解错误,也不会因为对象有类型就保证操作正确。发现能力、理解业务意图、遵守授权和验证结果仍然是不同问题。
## Endor 语言:让对象成为可编程的共同基础
Endor 的意义不能只停留在界面上可以点击一张对象关系图。开发者、用户编写的逻辑和 AI 生成的程序,需要能够表达这些对象、关系与操作,并把它们交给运行环境执行。**Endor 语言应当是连接对象世界与可执行行为的核心部分。**
现有语言文档使用 **Endorphin** 作为语言名称;本文的“Endor 语言”指这套语言在整个项目中的角色。下面依据现有语言设计稿整理其意义,不把设计约定等同于已经完成的软件能力。
### 统一对象模型,而不只是统一调用入口
现有设计以 Object 为共同基础,把数值、文本、容器、引用、类型定义、代码、函数和运行实体纳入对象体系。类型本身也是对象,由 Object 与 Type 的关系组织实例和类型定义。
这使我们能够讨论同一个工作对象的不同层面:它是什么类型,能被什么结构引用,支持哪些操作,由什么规则管理生命周期。类型的意义也不限于检查一个函数参数是否合法,还包括对象怎样组织、使用和呈现。
“一切皆对象”不能直接推导为“一切对象都独立保存、远程暴露或永久存在”。设计稿用 atom 讨论可独立识别、保存和引用的资源单元;哪些对象需要成为这样的单元,应与具体类型和生命周期规则一起确定。
### 身份、引用与命名,让组合能够延续
用户希望反复操作同一任务,语言就需要区分任务本身与当前拿到它的名字或引用。引用应当使程序能够继续关联目标,而不只是把某次显示得到的文本复制到另一个位置。
现有设计由 workspace 管理资源归属,namespace 提供命名和组织入口。资源身份、命名路径与用户身份承担不同职责;代码引用也不自动改变资源归属或取得授权。
对项目意义而言,这种区分让“跨入口使用同一对象”有了可表达的基础。一个对象可以被不同程序引用,用户不必为了更换呈现方式就重新建立它与其他对象的关系。具体的引用失效、资源回收、命名变更和跨端行为,仍应以语言规范及系统设计逐项落实。
### 函数与类型,表达对象能够做什么
有对象身份还不够,语言还需要表达怎样操作对象。类型描述结构与能力,函数表达输入、计算和结果,使可复用逻辑能够被其他程序引用和组合。
会议整理可以被拆成选择片段、形成结论、整理行动项和建立关联等能力。这里的重点不是预先发明一套内置会议 API,而是让业务逻辑能够用可检查的类型和调用关系表达,而不只能藏在某个界面的事件处理里。
函数本身与调用结果也要区分。用户查看一个函数,不代表已经执行;函数可以被引用,也不代表调用者已经具备执行它的授权。界面、AI 与其他程序使用这些能力时,应共享明确的调用含义。
### Preflight 与 inflight,连接定义和实际执行
现有设计把程序处理分为 Preflight 与 inflight:前者负责理解声明和引用、检查名称与类型并建立关联,后者使用实际输入执行逻辑,管理调用、实例和任务的运行状态。
对于 Endor 的目标,这意味着生成或编辑一段逻辑,与实际执行它应当有清楚的边界。AI 写出一段程序,不应仅因生成了文本就被视为已经就绪或已经执行;它仍需要进入相应的检查和运行过程。
这些是语言设计中的阶段职责,不等于本文已经确认所有编译器、虚拟机和平台路径都实现了同样的语义。语言设计与当前实现之间的对应,需要分别核对。
### Agent 也是程序结构的一部分
现有设计将 agent 与 class、function 一起纳入语言资源体系,讨论工具、记忆、状态与运行控制如何在共有模型中组织。AI 因而不只是从语言外部发送指令,也可以通过语言定义和组合行为。
如果 Agent 能引用已有函数、处理类型化结果并保留与对象的关系,它就有机会成为这个对象世界的参与者。人编写的逻辑与 AI 组织的逻辑可以使用共同的资源与调用约定,便于检查、复用和交接。
语言层面的 Agent 结构并不自动授予运行权限。操作身份、委托、任务恢复时的授权检查等仍有待定义,不能从“Agent 在某个 workspace 中”推导出它能以管理员身份执行。
### 从对象类型到界面呈现
语言设计还讨论客户端根据资源或调用结果的类型选择呈现方式,并用普通函数返回可渲染值来表达界面。这让界面与业务逻辑有机会围绕同一对象模型组织,而不是在前后端之间反复重建对应的数据结构。
同一个任务对象,可以在任务列表中显示摘要,在会议记录中显示来源,在专业编辑界面中展示更多操作。不同入口需要适合各自场景的呈现,同时保留对同一对象的关联。
类型驱动呈现不意味着所有对象都自动拥有完整 UI,也不意味着跨设备共享内存或瞬时一致。呈现契约、本地副本、同步状态和失败行为仍需要具体实现。
### 语言应该承担什么,系统又应该承担什么
语言应当把对象、类型、引用和行为表达清楚,让程序可以检查、组合和执行。Nexus、Aster、Aerarium、存储与通信机制负责支撑相应运行能力;不能仅靠增加一个语法结构就宣称已经解决分布式运行、持久化或故障恢复。
对用户来说,成功的结果应当是更容易表达一件事、继续处理同一对象,并把已有能力组合成新的工作流。语言的价值需要落在这种表达与操作的连续性上,而不只在于少写了几个请求或多了一种声明形式。
语言章节会随设计继续整理。当前依据可查阅:[语言概览](https://gitea.entroia.com/Zayden-Jung/Endorphin-Document/src/branch/main/guide/01-overview.md)、[Object 与类型系统](https://gitea.entroia.com/Zayden-Jung/Endorphin-Document/src/branch/main/guide/07-top-level-types/README.md)、[资源访问与呈现](https://gitea.entroia.com/Zayden-Jung/Endorphin-Document/src/branch/main/guide/11-resource-access-and-presentation.md)和[规范状态](https://gitea.entroia.com/Zayden-Jung/Endorphin-Document/src/branch/main/appendices/specification-status.md)。这些资料记录语言设计,不能作为实现完成度的证明。
## 一个完整的使用故事:从会议录像到项目计划
下面是一条用来检验项目意义的目标工作流,不是现有功能演示。它沿用同一次会议,让对象在用户、程序与 AI 之间连续流转。
### 从分散入口开始
用户打开录像,手工记下重要时间点,把结论复制到文档,再切换到任务工具创建行动项。AI 可以协助转写和提炼,但如果交接只剩几段文本,之后仍需要人工确认每个任务来自哪里、是否重复、对应哪一次修改。
当结论变化时,用户要重新找到相关任务和文档。原有工具可以通过链接和集成改善这个过程;我们需要明确比较的是这些已经可用的做法,而不是只和纯手工操作比较。
### 在对象世界中完成同一件事
1. **找到会议**:用户在 Tessera 中打开会议录像对象,选择需要处理的片段,保留它们与原始录像的关联。
2. **交给 AI 整理**:用户要求 AI 基于这些片段形成结论和候选行动项。候选结果继续关联来源,先供用户检查,不把生成内容直接当成已确认计划。
3. **核对并形成任务**:用户修正结论、去掉无效行动项,再通过约定的程序能力建立任务与来源的关系。
4. **换一个入口继续处理**:同一任务出现在项目看板、会议记录和个人工作视图中。不同入口展示不同信息,但引用的是同一任务。
5. **继续修改**:用户调整任务或结论后,可以沿关系找到受影响的内容。哪些变化自动传播、哪些需要重新确认,由具体对象与工作流规则决定。
6. **交接工作**:另一个获准参与的人或 AI 能够继续引用这些对象,了解其来源和当前状态,而不必仅凭上一轮聊天摘要重建整个过程。
这个故事的关键不是“一次指令自动完成全部工作”,而是中途可以检查、修改、换入口并继续处理。Endor 语言应当能表达其中的对象类型、引用和业务能力,前端负责呈现和交互,运行环境则支撑实际的访问与执行。
## 用户怎样保持控制(试写,待确认)
> **本章是待讨论的体验设想,不是已确认的权限规范。** 语言设计已有 workspace 整体授权、资源编辑与程序使用的区分;下面关注用户应能看懂什么、决定什么。操作身份、Agent 委托、撤销和记录的具体机制仍需设计。
“交还操作权”最终需要体现在用户能够作出的决定上。用户应当知道自己正在查看什么、以谁的身份操作、操作会影响哪些对象,以及什么结果已经发生。仅仅让对象可以被调用,而用户看不清影响范围,并不足以实现这个目标。
### 看懂对象、身份与预期影响
在会议整理的例子里,用户应能分辨 AI 正在处理的是哪次会议、哪些片段和哪些候选结果;也应能区分“生成了一份建议”与“已经创建任务”这两种状态。
对于会改变业务状态的操作,可以探索先展示目标、主要输入和预期效果,再让用户判断是否继续。哪些操作需要确认、哪些可以在既定范围内连续执行,应根据任务与风险讨论,不在这里规定所有动作都弹窗确认。
图中让曲线指向某个对象,不表示每个对象、字段或函数都需要一份独立的用户权限表。现有语言设计以 workspace 为整体授权边界,对象定位、代码可视域、入口允许的业务效果与用户授权应各自清楚,避免在这篇意义讨论中另造一套冲突规则。
### 委托给 AI,仍能区分谁在作决定
一个值得探索的目标是:用户可以将某项工作交给 AI,同时理解这次委托的目标、允许产生的效果和停止条件。AI 能引用对象或生成代码,不应自动获得修改任意对象或管理成员的权限。
委托的具体表示、运行身份如何绑定、长期任务是否重新检查授权、用户怎样收回委托,仍未定稿。这里先记录用户需要的体验,不把某种令牌、权限语法或审批流程提前确定为方案。
### 能检查结果,也能面对失败
用户需要区分未开始、执行中、成功、部分完成和失败。若一个流程只完成了部分任务创建,系统应尽量提供足够信息,让用户判断是否继续,而不是只返回一个无法解释的失败提示。
操作记录和来源关系可以帮助检查,但记录哪些内容、保存多久、谁能查看,仍需要权衡。我们可以讨论撤销、补偿操作或恢复到某个版本的能力,不能假定每次操作都可以回滚:已经发生的外部效果可能无法收回,跨系统执行也未必具有一个统一事务。
### 部署选择与控制之间的关系
本地、自部署和平台端提供了不同的运行与数据放置选择。它们可以帮助用户决定在哪里运行对象、由谁维护服务,但部署在自己机器上并不自动解决授权、备份或错误操作问题。
如果用户希望迁出数据、替换前端或更换运行位置,系统需要有可解释的边界。哪些对象、关系和执行状态可以导出,怎样保留引用与依赖,以及离开某个服务后还能使用什么,都应继续讨论,而不是仅用“支持自部署”代替这些问题。
## Endor 的代价、边界与验证标准(试写,待确认)
> **本章提出评估问题,不是已经达成的性能、兼容性或可靠性承诺。** 我们需要用真实工作流判断对象模型带来的收益,是否值得它引入的复杂度。
### 对象共同基础也会带来成本
| 需要承担的代价 | 为什么会出现 | 应当检查什么 |
| --- | --- | --- |
| 对象身份与引用的维护 | 对象被多个入口长期使用,关系不能只存在于一次调用中 | 改名、替换、删除和迁移后,引用是否仍有可理解的行为 |
| 类型与业务语义的协调 | 多个程序要对同一对象的含义形成约定 | 类型演进与不兼容变化是否使其他入口失效 |
| 跨端状态和网络成本 | 本地与远端对象不共享同一块内存 | 延迟、断线、过期状态和部分失败是否会造成错误判断 |
| 运行环境与运维成本 | 对象的执行、保存和访问需要相应基础设施 | 小规模使用是否也必须承担不必要的部署负担 |
| 学习和集成成本 | 开发者需要理解新的语言与对象模型 | 完成同一业务是否比已有语言、API 和工具增加更多工作 |
| 共同基础的依赖风险 | 多个入口可能依赖相同运行时与对象服务 | 故障影响范围、版本兼容和退出路径是否明确 |
图里更少的进程只是组织方式的示意。实际的内存、启动时间、吞吐量、隔离性和故障影响需要分别测量;进程少不天然意味着成本低,也不证明系统更可靠。
### 哪些事情不应勉强统一
专业程序可以保留适合自己的内部结构和交互方式。对于已有明确接口、成熟工作流或特殊执行约束的系统,建立适度的连接也许比全部迁入新的对象体系更合适。
对象关系不应抹平真实边界:一个远端对象可能不可达,一个业务操作可能被拒绝,一次结果更新可能尚未传播。语言可以帮助表达和处理这些情况,不能把它们变成“看起来像本地调用,因此一定立即成功”。
Endor 也不应仅凭对象之间可连接,就宣称用户可以无损迁移全部程序、消除所有格式转换或让 AI 理解全部业务。需要保留什么、转换什么、失去什么,应在具体对象和连接机制中说明。
### 用同一条工作流验证意义
可以先用前面的会议整理故事做一个范围有限的原型,对比现有工具的正常用法与 Endor 原型。两边使用同一份材料、同样的目标和相近的辅助条件;如果现有工具已经有良好的链接与自动化能力,也应纳入比较。
| 想验证的主张 | 可以观察的结果 |
| --- | --- |
| 减少重复组织数据 | 从录像到任务,需要多少次重复录入、复制和人工重建关联 |
| 保留同一对象与来源 | 换入口或重新进入流程后,能否准确找到原任务及其依据 |
| 支持人和 AI 交接 | 人能否修正 AI 的候选结果,AI 能否在修正后继续处理正确目标 |
| 操作效果容易理解 | 用户能否判断哪些只是建议,哪些已经改变业务状态 |
| 组合能力值得复用 | 加入第二种视图或工作流时,需要新增多少适配逻辑 |
| 失败时仍可继续 | 遇到断线、拒绝访问或部分完成后,能否辨认状态并继续工作 |
这些观察需要同时记录用户体验、实现工作量与运行成本。不能只比较演示中最顺利的一次,也不能把更多后台复杂度隐藏起来,再把少几个界面步骤当成全部收益。
### 什么结果意味着需要调整方向
如果保留对象身份仍然离不开大量手工映射,换一个界面仍然要复制一套数据,或者简单任务必须先部署过多基础设施,那么当前设计还没有兑现它的意义。
如果 AI 操作对象之后更难解释结果,或开发者为了接入对象模型付出的工作远高于已有接口带来的成本,也应调整对象粒度、语言边界或集成方式。
这里先不设任意的数值门槛。第一步应是做出可重复的具体工作流,记录收益和问题,再决定哪些目标值得继续投入,哪些假设需要修改。
## 继续整理的方向
这一版先把程序入口、对象、操作权、AI 与语言之间的关系串起来。后续可以用真实工作流修订这些描述,进一步确定对象身份、执行与挂载的语义。
[系统架构](/docs/00-endor-concepts-draft)讨论部署与存储,[节点与对象挂载](/docs/02-mounting-draft)讨论运行位置和挂载边界;本文关注它们为何能给用户带来值得验证的变化。
+5
View File
@@ -0,0 +1,5 @@
{
"maxWidth": 1600,
"quality": 82,
"maxBytes": 196608
}
+129
View File
@@ -0,0 +1,129 @@
{
"updated": "2026-10-28",
"scope": "Language design questions; discussion status, not implementation status",
"chapters": [
{
"chapter": "02",
"title": "名称与作用域",
"threadId": "01a1436f-1f6a-7f21-b1cd-32ab787aac46",
"hostId": "local",
"file": "content/docs/language-design/02-questions.md",
"total": 22,
"confirmed": 13
},
{
"chapter": "03",
"title": "值与类型",
"threadId": "01a1436f-349f-71f3-a64c-115c282c9dad",
"hostId": "local",
"file": "content/docs/language-design/03-questions.md",
"total": 30,
"confirmed": 13
},
{
"chapter": "04",
"title": "存储与生命周期",
"threadId": "01a1436f-4fd8-7392-9789-d8937fec38e1",
"hostId": "local",
"file": "content/docs/language-design/04-questions.md",
"total": 20,
"confirmed": 0
},
{
"chapter": "05",
"title": "对象与成员",
"threadId": "01a1436f-61a1-7722-9914-6103691907ce",
"hostId": "local",
"file": "content/docs/language-design/05-questions.md",
"total": 18,
"confirmed": 0
},
{
"chapter": "06",
"title": "表达式与运算",
"threadId": "01a1436f-7d66-7cb0-bc59-fac88abd3362",
"hostId": "local",
"file": "content/docs/language-design/06-questions.md",
"total": 20,
"confirmed": 0
},
{
"chapter": "07",
"title": "函数与调用",
"threadId": "01a1436f-97bc-74d3-a501-650e893c73c3",
"hostId": "local",
"file": "content/docs/language-design/07-questions.md",
"total": 22,
"confirmed": 0
},
{
"chapter": "08",
"title": "控制流",
"threadId": "01a1436f-b115-76d3-800c-e7d090978ceb",
"hostId": "local",
"file": "content/docs/language-design/08-questions.md",
"total": 20,
"confirmed": 0
},
{
"chapter": "09",
"title": "集合与访问协议",
"threadId": "01a14370-5360-7550-a595-c693333a2c66",
"hostId": "local",
"file": "content/docs/language-design/09-questions.md",
"total": 22,
"confirmed": 0
},
{
"chapter": "10",
"title": "错误与资源",
"threadId": "01a14370-69b3-7090-b66f-4755f71a481a",
"hostId": "local",
"file": "content/docs/language-design/10-questions.md",
"total": 16,
"confirmed": 0
},
{
"chapter": "11",
"title": "模块与程序执行",
"threadId": "01a14370-84e7-7de3-b1eb-7707d4e62f83",
"hostId": "local",
"file": "content/docs/language-design/11-questions.md",
"total": 22,
"confirmed": 0
},
{
"chapter": "12",
"title": "并发与异步",
"threadId": "01a14370-a1d0-7ca3-951f-315ad8f13b8e",
"hostId": "local",
"file": "content/docs/language-design/12-questions.md",
"total": 21,
"confirmed": 0
},
{
"chapter": "13",
"title": "外部交互",
"threadId": "01a14370-b63f-7133-a092-78699b24473e",
"hostId": "local",
"file": "content/docs/language-design/13-questions.md",
"total": 22,
"confirmed": 0
},
{
"chapter": "14",
"title": "反射与表示",
"threadId": "01a14370-cc98-7523-8220-a1008ea9b16b",
"hostId": "local",
"file": "content/docs/language-design/14-questions.md",
"total": 16,
"confirmed": 0
}
],
"excluded": [
{
"threadId": "01a11fdf-963c-7d11-87af-65791938d536",
"reason": "Chromium navigation discussion; outside language design"
}
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+295
View File
@@ -0,0 +1,295 @@
{
"version": "2026-10-30-21",
"scopeConfirmedAt": "2026-10-30",
"acceptance": "以确认的公开来源清单为边界,逐条核对并标明缺项。",
"provenance": "S01—S12恢复自已提交用户的《AI公司研究_来源与分类模板》来源清单;S13—S16单列后续已使用的补充证据渠道,不将使用次数当作全量覆盖。",
"sources": [
{
"id": "S01",
"name": "Y Combinator",
"url": "https://www.ycombinator.com/companies",
"role": "discovery",
"status": "candidate-audit",
"hosts": [
"www.ycombinator.com"
],
"initialAccess": "官网目录可访问",
"boundary": "已读取八个2025—2026批次镜像候选池1428条,再核YC官方页面;不声称覆盖全部YC历年或未公开公司。",
"nextCheck": "当前快照三条原待分类经官网方向补证归类;继续复核规则初分、具体产品与财务缺项,不把领域粗分类当独立能力或收入验证。",
"limitation": "批次不等于成立年;不代表全部公司"
},
{
"id": "S02",
"name": "TechCrunch AI",
"url": "https://techcrunch.com/category/artificial-intelligence/",
"role": "reporting",
"status": "targeted",
"hosts": [
"techcrunch.com"
],
"initialAccess": "AI栏目可读取",
"boundary": "2026首页定向3项已登记。另已读2025年度档案入口与AI第二页,并完整登记一篇2025企业竞赛名单32项:复用1项、范围外19项、待核12项;每项均尝试原始链接,未知与不可读保留。单篇32项不等全部200参赛者、全部分页或两年全量;RSS/API普通请求受限。",
"nextCheck": "继续核本篇12项的成立、主体及AI主营,优先解决域名更名与不可读项;沿普通2025档案和AI分页扩展其余来源台账,区分参赛年、批次与公司成立年。",
"limitation": "需追溯原始披露,部分文章受访问限制",
"accessRecheckedAt": "2026-10-30"
},
{
"id": "S03",
"name": "Dealroom",
"url": "https://dealroom.co/",
"role": "discovery",
"status": "targeted",
"hosts": [
"dealroom.co",
"app.dealroom.co"
],
"initialAccess": "官网可读取",
"boundary": "已读Tana与Wabi公开公司档案:前者财务字段不一致留缺,后者2025成立字段与官方业务关联入表;尚未取得两年成立筛选结果集,两个个案不等于目录全量。",
"nextCheck": "确认公开可取得的两年成立筛选清单;逐项追溯财务原始凭证及字段口径,受权限限制保留缺项。",
"limitation": "完整档案需权限;概览及财务表不能未经勾稽直接导入ARR",
"accessRecheckedAt": "2026-10-30"
},
{
"id": "S04",
"name": "Product Hunt",
"url": "https://www.producthunt.com/",
"role": "discovery",
"status": "targeted",
"hosts": [
"www.producthunt.com",
"producthunt.com"
],
"initialAccess": "官网可读取",
"boundary": "两年公开响应各19条,共38条。当前5条关联公司、2条范围外对照、25条范围外/既有业务、4条年份待核、2条推广。旧版本、品牌与法律主体分开,Tapflow据2024原版记录排除,Happycapy仍待核;非两年全量。",
"nextCheck": "继续补两年其余分页/日期、仅图片位置及4条年份待核候选;保留Pazi日期冲突,核清品牌与主体,避免转移历史业绩。",
"limitation": "上线时间不等于成立时间",
"accessRecheckedAt": "2026-10-30"
},
{
"id": "S05",
"name": "Sacra",
"url": "https://sacra.com/",
"role": "estimation",
"status": "targeted",
"hosts": [
"sacra.com"
],
"initialAccess": "官网可读取",
"boundary": "已用于定向估算及日期口径交叉核查;无全站公司名录读取台账。",
"nextCheck": "保留估算与公司披露差异,核实历史截至日。",
"limitation": "部分付费;不能把估算当审计数"
},
{
"id": "S06",
"name": "Bessemer",
"url": "https://www.bvp.com/atlas/the-state-of-ai-2025",
"role": "context",
"status": "context",
"hosts": [
"www.bvp.com",
"bvp.com"
],
"initialAccess": "报告页面可读取",
"boundary": "主动选取20家高增长AI企业,含组合内外公司;非随机普查;已核方法与增长/毛利基准段;未取得20家逐公司底表。仅背景基准,不构成两年新公司名录。",
"nextCheck": "高增长选样和投资机构利益关系;不能把头部样本均值当各领域平均或新成立公司总体;需要公开可核底表时另补,不把缺项当已完成。",
"limitation": "投资机构选样偏差",
"accessRecheckedAt": "2026-10-30",
"methodology": {
"sample": "主动选取20家高增长AI企业,含组合内外公司;非随机普查",
"unit": "企业增长与毛利基准,按商业化后的第几年比较",
"period": "2025-08-13报告;商业化年数不等法律成立年",
"access": "已核方法与增长/毛利基准段;未取得20家逐公司底表",
"use": "用于提出留存、毛利、资本效率假设及分类线索",
"limit": "高增长选样和投资机构利益关系;不能把头部样本均值当各领域平均或新成立公司总体",
"evidenceIds": [
"CTX-BVP"
],
"checkedAt": "2026-10-30"
}
},
{
"id": "S07",
"name": "Menlo Ventures",
"url": "https://menlovc.com/perspective/2025-the-state-of-generative-ai-in-the-enterprise/",
"role": "context",
"status": "context",
"hosts": [
"menlovc.com",
"www.menlovc.com"
],
"initialAccess": "报告页面可读取",
"boundary": "495名美国企业AI采购/开发决策者,企业已主动使用AI;已核公开方法、范围及限制;受访个体与公司估算底表未取得。仅背景基准,不构成两年新公司名录。",
"nextCheck": "仅美国企业;排除芯片、推理/模型服务及既有软件内嵌AI功能,不能与包含这些项目的总量直接比较或分摊为单家公司ARR;需要公开可核底表时另补,不把缺项当已完成。",
"limitation": "口径与样本需查看方法说明",
"accessRecheckedAt": "2026-10-30",
"methodology": {
"sample": "495名美国企业AI采购/开发决策者,企业已主动使用AI",
"unit": "采购调查与自下而上的市场支出估算,非公司逐项ARR",
"period": "2025-11-07至11-25调查,市场判断截至2025-12",
"access": "已核公开方法、范围及限制;受访个体与公司估算底表未取得",
"use": "用于买家、采购方式和任务方向假设",
"limit": "仅美国企业;排除芯片、推理/模型服务及既有软件内嵌AI功能,不能与包含这些项目的总量直接比较或分摊为单家公司ARR",
"evidenceIds": [
"CTX-MENLO"
],
"checkedAt": "2026-10-30"
}
},
{
"id": "S08",
"name": "Stripe",
"url": "https://stripe.com/annual-updates/2025",
"role": "context",
"status": "context",
"hosts": [
"stripe.com",
"www.stripe.com",
"assets.stripeassets.com"
],
"initialAccess": "年度信可读取",
"boundary": "2025年开始使用Stripe的商户分组,另有Atlas注册企业分组;已读并视觉核对PDF第1、3页;未取得商户明细与完整分组计算底表。仅背景基准,不构成两年新公司名录。",
"nextCheck": "开始使用平台不等成立年,也非AI公司专属样本;交易量不等Stripe收入,门槛数量翻倍不等ARR均值翻倍;不与TrustMRR公开者样本混算;需要公开可核底表时另补,不把缺项当已完成。",
"limitation": "平台样本不能代表全部AI公司",
"accessRecheckedAt": "2026-10-30",
"methodology": {
"sample": "2025年开始使用Stripe的商户分组,另有Atlas注册企业分组",
"unit": "平台交易量、商户增长及达到收入门槛的数量;分母不同",
"period": "2025年度;2026-02-24年度信",
"access": "已读并视觉核对PDF第1、3页;未取得商户明细与完整分组计算底表",
"use": "用于支付、全球市场及首次收费速度假设",
"limit": "开始使用平台不等成立年,也非AI公司专属样本;交易量不等Stripe收入,门槛数量翻倍不等ARR均值翻倍;不与TrustMRR公开者样本混算",
"evidenceIds": [
"CTX-STRIPE"
],
"checkedAt": "2026-10-30"
}
},
{
"id": "S09",
"name": "SaaS Capital",
"url": "https://www.saas-capital.com/research/",
"role": "context",
"status": "context",
"hosts": [
"www.saas-capital.com",
"saas-capital.com"
],
"initialAccess": "研究页可读取",
"boundary": "第15次年度调查,超过1000家私营B2B SaaS公司;仅读公开摘要;完整下载需填写表单,未提交表单或取得完整底表。仅背景基准,不构成两年新公司名录。",
"nextCheck": "样本不是两年新AI公司;增长率中位数不能当ARR中位数;完整抽样与指标细节仍缺,不外推至硬件、项目服务或所有AI模式;需要公开可核底表时另补,不把缺项当已完成。",
"limitation": "不直接套用硬件与项目制业务",
"accessRecheckedAt": "2026-10-30",
"methodology": {
"sample": "第15次年度调查,超过1000家私营B2B SaaS公司",
"unit": "2025年度增长率与留存等公开摘要;非ARR金额分布",
"period": "2026报告回顾2025增长;不把报告年当公司成立年",
"access": "仅读公开摘要;完整下载需填写表单,未提交表单或取得完整底表",
"use": "用于B2B订阅软件的规模、融资和留存分层假设",
"limit": "样本不是两年新AI公司;增长率中位数不能当ARR中位数;完整抽样与指标细节仍缺,不外推至硬件、项目服务或所有AI模式",
"evidenceIds": [
"CTX-SAASCAP"
],
"checkedAt": "2026-10-30"
}
},
{
"id": "S10",
"name": "机器之心",
"url": "https://www.jiqizhixin.com/",
"role": "reporting",
"status": "targeted",
"hosts": [
"www.jiqizhixin.com",
"jiqizhixin.com",
"pro.jiqizhixin.com"
],
"initialAccess": "首页可读取",
"boundary": "已登记4篇定向检索线索;三篇直达仅登录外壳,一篇读取失败。2项经公开原始资料关联公司,SSI与Utopai经原始历史材料判为范围外,0项成立年待核;未阅读全文或穷尽两年档案。",
"nextCheck": "补公开可读文章及2025—2026档案;受限正文留缺,不以搜索摘录代全文,更名与产品发布不新增公司。",
"limitation": "全文访问受限;仅作发现时明确标识,技术和财务另追原始资料",
"accessRecheckedAt": "2026-10-30"
},
{
"id": "S11",
"name": "36氪",
"url": "https://www.36kr.com/",
"role": "reporting",
"status": "access-limited",
"hosts": [
"www.36kr.com",
"36kr.com"
],
"initialAccess": "安全检测,内容未核验",
"boundary": "2026-10-30仍返回安全检测页面,未把首页作为已读文章。",
"nextCheck": "使用可公开读取的具体文章或其他原始来源;不绕过访问保护。",
"limitation": "暂不作为已读取内容证据",
"accessRecheckedAt": "2026-10-30"
},
{
"id": "S12",
"name": "公司官网与官方博客",
"url": null,
"role": "primary",
"status": "per-company",
"hosts": [],
"initialAccess": "按公司逐一核验",
"boundary": "公司官网和官方材料逐条绑定证据;不是可预先列尽的全站候选池。",
"nextCheck": "核定价、主体、交付与收入定义,自述与独立验证分开。",
"limitation": "自述不等于独立审计"
},
{
"id": "S13",
"name": "TrustMRR",
"url": "https://trustmrr.com/",
"role": "platform",
"status": "targeted",
"hosts": [
"trustmrr.com"
],
"initialAccess": "见具体证据访问记录",
"boundary": "已采集产品与支付快照;公开者自选,不是全部商户或独立财务审计。",
"nextCheck": "核同步日、连接失效、支付平台公式及产品/法人归属。",
"limitation": "来源可读不等于声明已独立验证。"
},
{
"id": "S14",
"name": "a16z Speedrun",
"url": "https://speedrun.a16z.com/",
"role": "investor",
"status": "targeted",
"hosts": [
"speedrun.a16z.com"
],
"initialAccess": "见具体证据访问记录",
"boundary": "投资机构公司介绍定向样本,收入数字仍多来自公司。",
"nextCheck": "核币种、相对时间及管线/履历;未读取的页面保持缺项。",
"limitation": "来源可读不等于声明已独立验证。"
},
{
"id": "S15",
"name": "Artificial Analysis",
"url": "https://artificialanalysis.ai/",
"role": "technical",
"status": "targeted",
"hosts": [
"artificialanalysis.ai"
],
"initialAccess": "见具体证据访问记录",
"boundary": "第三方已发表技术评测,仅覆盖所列模型版本和任务。",
"nextCheck": "核榜单版本、测评方法及置信区间,不将排名变成企业整体能力。",
"limitation": "来源可读不等于声明已独立验证。"
},
{
"id": "S16",
"name": "其他公开补充资料",
"url": null,
"role": "supplement",
"status": "targeted",
"hosts": [],
"initialAccess": "见具体证据访问记录",
"boundary": "未归入上述来源的公开材料按原始证据链接逐条保留;不视为新增已批准的完整候选池。",
"nextCheck": "逐项核来源归属、可靠性及可读正文,不能将搜索摘要当全文。",
"limitation": "来源可读不等于声明已独立验证。"
}
]
}
+221
View File
@@ -0,0 +1,221 @@
{
"sourceVersion": "2026-10-30-battlefield-2",
"asOf": "2026-10-30",
"metric": "platform-mrr-usd",
"sampleUnit": "product-or-business",
"note": "独立Python复算参考值,仅验证样本计算;不是行业估计或财务审计。",
"windows": [
{
"days": 7,
"products": [
"MR001",
"MR002",
"MR003",
"MR004",
"MR005",
"MR006",
"MR007",
"MR008",
"MR009",
"MR010",
"MR011",
"MR012",
"MR015",
"MR016"
],
"groups": [
{
"category": "C06",
"provider": "Stripe",
"model": "软件订阅",
"products": [
"MR011",
"MR012",
"MR015",
"MR016"
],
"n": 4,
"mean": 34815.0,
"median": 36723.0,
"sampleDeviation": 16334.54845820151,
"cv": 0.46918134304758036,
"meanWithoutLargest": 28940.666666666668,
"largestRemovalDrop": 0.16872995356407675
},
{
"category": "C08",
"provider": "RevenueCat",
"model": "消费者订阅",
"products": [
"MR001"
],
"n": 1,
"mean": 53101.0,
"median": 53101,
"sampleDeviation": null,
"cv": null,
"meanWithoutLargest": null,
"largestRemovalDrop": null
},
{
"category": "C08",
"provider": "Stripe",
"model": "内容制作服务",
"products": [
"MR002"
],
"n": 1,
"mean": 62423.0,
"median": 62423,
"sampleDeviation": null,
"cv": null,
"meanWithoutLargest": null,
"largestRemovalDrop": null
},
{
"category": "C08",
"provider": "Stripe",
"model": "软件订阅",
"products": [
"MR003",
"MR004",
"MR005"
],
"n": 3,
"mean": 41693.0,
"median": 49069,
"sampleDeviation": 28111.375064197768,
"cv": 0.6742468775141575,
"meanWithoutLargest": 29849.0,
"largestRemovalDrop": 0.2840764636749574
},
{
"category": "C09",
"provider": "RevenueCat",
"model": "消费者订阅",
"products": [
"MR006",
"MR007",
"MR008",
"MR009",
"MR010"
],
"n": 5,
"mean": 25349.2,
"median": 20483,
"sampleDeviation": 11942.947278624319,
"cv": 0.4711370488466823,
"meanWithoutLargest": 20046.0,
"largestRemovalDrop": 0.20920581320120557
}
]
},
{
"days": 90,
"products": [
"MR001",
"MR002",
"MR003",
"MR004",
"MR005",
"MR006",
"MR007",
"MR008",
"MR009",
"MR010",
"MR011",
"MR012",
"MR015",
"MR016",
"AI016"
],
"groups": [
{
"category": "C06",
"provider": "Stripe",
"model": "软件订阅",
"products": [
"MR011",
"MR012",
"MR015",
"MR016",
"AI016"
],
"n": 5,
"mean": 112725.6,
"median": 40112,
"sampleDeviation": 174786.78744916618,
"cv": 1.5505509613536426,
"meanWithoutLargest": 34815.0,
"largestRemovalDrop": 0.6911526751687284
},
{
"category": "C08",
"provider": "RevenueCat",
"model": "消费者订阅",
"products": [
"MR001"
],
"n": 1,
"mean": 53101.0,
"median": 53101,
"sampleDeviation": null,
"cv": null,
"meanWithoutLargest": null,
"largestRemovalDrop": null
},
{
"category": "C08",
"provider": "Stripe",
"model": "内容制作服务",
"products": [
"MR002"
],
"n": 1,
"mean": 62423.0,
"median": 62423,
"sampleDeviation": null,
"cv": null,
"meanWithoutLargest": null,
"largestRemovalDrop": null
},
{
"category": "C08",
"provider": "Stripe",
"model": "软件订阅",
"products": [
"MR003",
"MR004",
"MR005"
],
"n": 3,
"mean": 41693.0,
"median": 49069,
"sampleDeviation": 28111.375064197768,
"cv": 0.6742468775141575,
"meanWithoutLargest": 29849.0,
"largestRemovalDrop": 0.2840764636749574
},
{
"category": "C09",
"provider": "RevenueCat",
"model": "消费者订阅",
"products": [
"MR006",
"MR007",
"MR008",
"MR009",
"MR010"
],
"n": 5,
"mean": 25349.2,
"median": 20483,
"sampleDeviation": 11942.947278624319,
"cv": 0.4711370488466823,
"meanWithoutLargest": 20046.0,
"largestRemovalDrop": 0.20920581320120557
}
]
}
]
}
@@ -0,0 +1,21 @@
# 文档 UI 验收 · 2026-10-28
参考 Supabase Database Overview 与 AI Tools 的桌面界面:共用排版,分别维护文档标识、局部目录与顶部上下文。保留 Tabularium 品牌与现有文档路径。
## 实现
- 顶部切换文档,显示当前选中项。左侧显示当前文档名称、图标、独立目录和返回入口;面包屑连接该文档入口。
- 文档中心按合集提供入口,不把所有章节铺成卡片。原有筛选、分页和全文搜索保留;阅读页搜索提示显示当前文档范围。
- 移除导航、卡片、提示、代码、表格和上下篇等区域的多数边框,以留白、浅色表面和轻渐变建立层次。不同文档使用克制的强调色。
- 入口提供 hover 浮起和箭头反馈;选中项、链接和搜索有过渡;正文及对话框有短暂进入效果。系统设置减少动态效果时关闭动画和过渡。
## 验证
- ESLint、类型检查、Next.js webpack 生产构建通过。认证单元测试 3/3 通过。
- 对最终生产构建运行原有 auth-cli verify:全部文档、搜索索引、附件、静态资源、404 和认证边界通过。
- 浏览器开发预览:1440×900 桌面检查首页、Pretext、语言设计;顶部点击切换后局部目录和搜索提示更新。搜索 nonlocal 返回本合集两篇文章,方向键与 Enter 能打开章节。
- 390×844 检查正文、顶部横向文档切换和本地目录展开;截图未见正文横向溢出。
- 下图为开发预览截图,左下角 Next.js 开发按钮不进入生产产物。生产产物已完成 HTTP 验收;额外的生产浏览器截图因原开发标签页关闭后连接失效未保存。
- 不代表远程 CI 已完成,也不代表 PR 已合并或生产环境已部署。
![桌面语言设计文档](desktop-language.jpg)
Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

+4 -2
View File
@@ -13,7 +13,9 @@
"lint": "pnpm --filter @endor/docs run lint", "lint": "pnpm --filter @endor/docs run lint",
"typecheck": "pnpm --filter @endor/docs run typecheck", "typecheck": "pnpm --filter @endor/docs run typecheck",
"figures": "uv run --locked --project tools/figures endor-figures", "figures": "uv run --locked --project tools/figures endor-figures",
"check": "pnpm run lint && pnpm run typecheck && pnpm run test:auth && pnpm run figures && pnpm run build", "check": "pnpm run lint && pnpm run typecheck && pnpm run test:auth && pnpm run test:research && pnpm run test:docs && pnpm --filter @endor/docs run images && pnpm --filter @endor/docs run test:images && pnpm run figures && pnpm run build",
"test:auth": "pnpm --filter @endor/docs run test:auth" "test:auth": "pnpm --filter @endor/docs run test:auth",
"test:research": "pnpm --filter @endor/docs run test:research",
"test:docs": "pnpm --filter @endor/docs run test:docs"
} }
} }
+4 -3
View File
@@ -59,6 +59,9 @@ importers:
postcss: postcss:
specifier: 8.5.31 specifier: 8.5.31
version: 8.5.31 version: 8.5.31
sharp:
specifier: 0.35.5
version: 0.35.5(@types/node@22.20.5)
tailwindcss: tailwindcss:
specifier: 4.3.3 specifier: 4.3.3
version: 4.3.3 version: 4.3.3
@@ -2876,8 +2879,7 @@ snapshots:
'@humanwhocodes/retry@0.4.3': {} '@humanwhocodes/retry@0.4.3': {}
'@img/colour@1.1.0': '@img/colour@1.1.0': {}
optional: true
'@img/sharp-darwin-arm64@0.35.5': '@img/sharp-darwin-arm64@0.35.5':
optionalDependencies: optionalDependencies:
@@ -5184,7 +5186,6 @@ snapshots:
'@img/sharp-win32-ia32': 0.35.5 '@img/sharp-win32-ia32': 0.35.5
'@img/sharp-win32-x64': 0.35.5 '@img/sharp-win32-x64': 0.35.5
'@types/node': 22.20.5 '@types/node': 22.20.5
optional: true
shebang-command@2.0.0: shebang-command@2.0.0:
dependencies: dependencies:
+251
View File
@@ -0,0 +1,251 @@
"""Summarize observed research coverage; does not claim an exhaustive AI census."""
import argparse
from collections import Counter
import json
from pathlib import Path
import sys
from urllib.parse import urlsplit
ROOT = Path(__file__).resolve().parents[1]
DATA = json.loads((ROOT / 'content/research/ai-companies.seed.json').read_text())
AUDIT = json.loads((ROOT / 'content/research/ai-companies.coverage.json').read_text())
SOURCES = json.loads((ROOT / 'content/research/ai-companies.sources.json').read_text())
TARGET = ROOT / '.artifacts/reports/02-coverage-and-gaps.md'
SOURCE_SLUG = 'ai-company-research/02-coverage-and-gaps'
BASE = '/docs/other-research/ai-company-research/overview'
def source_register():
sources = SOURCES['sources']
ids = {s['id'] for s in sources}
assert len(ids) == len(sources) and ids == {f'S{i:02}' for i in range(1, 17)}
assert SOURCES['scopeConfirmedAt'] <= DATA['asOf']
host_map = {}
for source in sources:
assert source['status'] in {'candidate-audit', 'targeted', 'pending', 'context', 'access-limited', 'per-company'}
assert source['boundary'] and source['nextCheck']
if source['url']:
assert urlsplit(source['url']).scheme in {'http', 'https'} and urlsplit(source['url']).netloc
for host in source['hosts']:
assert host not in host_map, f'Duplicate source host: {host}'
host_map[host] = source['id']
assigned = {key: [] for key in ids}
for evidence in DATA['evidence']:
owner = host_map.get(urlsplit(evidence['url']).netloc)
if owner is None:
owner = 'S12' if any(word in evidence['kind'] for word in ('官方', '公司自述', '公司披露')) else 'S16'
assigned[owner].append(evidence)
assert sum(len(v) for v in assigned.values()) == len(DATA['evidence'])
statuses = {'candidate-audit': '候选池逐条已读', 'targeted': '定向使用,未穷尽', 'pending': '候选台账待建',
'context': '背景研究', 'access-limited': '访问受限', 'per-company': '随公司逐条核对'}
lines = ['', '## 来源清单与验收边界', '', SOURCES['provenance'], '',
'每条证据在下表只计入一个渠道:先按所列域名归属,再将类型明确标为官方/公司自述/公司披露的剩余项计入S12,其余计入S16。公司可跨渠道出现,所以公司数不可跨行相加。零条证据表示尚未进入研究表,不表示该来源没有相关公司。背景报告不承担公司发现全集的角色。', '',
'| 来源 | 当前状态 | 证据 / 公司 / 观测数 | 已核对范围 | 剩余核查 |', '| --- | --- | --- | --- | --- |']
for source in sources:
evidence = assigned[source['id']]
evidence_ids = {e['id'] for e in evidence}
company_ids = {e['companyId'] for e in evidence if e['companyId']}
observations = sum(o['evidence'] in evidence_ids for o in DATA['observations'])
name = f"[{source['name']}]({source['url']})" if source['url'] else source['name']
lines.append(f"| {source['id']} {name} | {statuses[source['status']]} | {len(evidence)} / {len(company_ids)} / {observations} | {source['boundary']} | {source['nextCheck']} |")
lines += ['', 'Dealroom、Product Hunt、机器之心与36氪入口于2026-10-30重新访问。官网首页可读不证明已取得完整筛选结果;安全检测页面不作为文章内容。候选池之外的来源边界尚需建立可回查条目,完成前不宣布来源清单已全部覆盖。', '']
return lines
def context_methods():
evidence = {e['id']: e for e in DATA['evidence']}
rows = [s for s in SOURCES['sources'] if s.get('methodology')]
assert {s['id'] for s in rows} == {'S06', 'S07', 'S08', 'S09'}
lines = ['', '## 背景基准适用性与缺项', '',
'以下核对背景资料的方法及适用范围,不是公司名录的完整覆盖。原始方法记录与全局核查随研究版本进入同一数据库;没有把行业汇总值新增为任何公司的收入观测。', '',
'| 来源与证据 | 样本与统计单位 | 时间 | 本次读取范围 | 可用于什么 | 主要限制 |',
'| --- | --- | --- | --- | --- | --- |']
for source in rows:
m = source['methodology']
assert m['checkedAt'] <= DATA['asOf']
assert all(m.get(key) for key in ('sample', 'unit', 'period', 'access', 'use', 'limit', 'evidenceIds'))
assert all(eid in evidence and evidence[eid]['companyId'] is None for eid in m['evidenceIds'])
assert not any(o['evidence'] in m['evidenceIds'] for o in DATA['observations'])
proof = '、'.join(f"[{eid}]({evidence[eid]['url']})" for eid in m['evidenceIds'])
lines.append(f"| {source['id']} {source['name']}:{proof} | {m['sample']};{m['unit']} | {m['period']} | {m['access']} | {m['use']} | {m['limit']} |")
lines += ['', '本表的应用解释属于研究判断。选样、分母、时间或指标不同会造成表观差异;这些差异不单独证明财务造假,也不能作为给未知公司填补收入的依据。', '']
return lines
def candidate_register():
batches = DATA.get('candidateBatches', [])
companies = {c['id']: c for c in DATA['companies']}
categories = {c['id']: c['name'] for c in DATA['categories']}
known_sources = {s['id'] for s in SOURCES['sources']}
evidence = {e['id']: e for e in DATA['evidence']}
assert len({b['id'] for b in batches}) == len(batches)
all_ids = [r['id'] for b in batches for r in b['records']]
assert len(set(all_ids)) == len(all_ids)
lines = []
statuses = {'pending-year': '成立年待核', 'linked': '已关联公司',
'existing-outside-cohort': '已有关联,年份范围外',
'outside-cohort': '范围外或既有业务,不新增公司', 'promotion': '推广活动,非公司新增'}
for batch in batches:
assert batch['sourceId'] in known_sources
assert batch['accessedAt'] <= DATA['asOf']
assert any(e['url'] == batch['url'] for e in DATA['evidence'])
rows = batch['records']
counts = Counter(r['status'] for r in rows)
assert sum(counts.values()) == len(rows)
lines += ['', f"## {batch['sourceId']} 候选核对({batch['id']})", '',
f"[发现页面]({batch['url']}),读取于{batch['accessedAt']}。{batch['scope']}", '',
f"本批{len(rows)}条:{counts['linked']}条关联公司、{counts['existing-outside-cohort']}条关联范围外对照、{counts['outside-cohort']}条范围外不新增公司、{counts['pending-year']}条成立年待核、{counts['promotion']}条推广活动。完整来源覆盖标记:{'已完成' if batch['complete'] else '未完成'}。主营或产品任务的初分类不计入主公司表数量,只有已关联的公司记录进入对应公司明细。候选与缺项随研究版本保存在文档站同一SQLite的研究元数据中。", '',
'| 发现条目 | 主营或产品任务初分 | 核对状态 | 关联公司 | 核对证据 | 限制 |', '| --- | --- | --- | --- | --- | --- |']
for row in rows:
assert row['categoryId'] in categories
assert row['status'] in statuses
assert all(eid in evidence for eid in row.get('evidenceIds', []))
if row['status'] == 'outside-cohort':
assert row.get('evidenceIds') and not row.get('companyId')
name = f"[{row['name']}]({row['url']})" if row['url'] else row['name']
company = '—'
if row.get('companyId'):
assert row['companyId'] in companies
c = companies[row['companyId']]
company = f"[{c['name']}]({BASE}?company={c['id']}#research-company-detail)"
proof = '、'.join(f"[{eid}]({evidence[eid]['url']})" for eid in row.get('evidenceIds', [])) or '成立证据待补,产品页读取状态见候选记录'
category = f"[{categories[row['categoryId']]}]({BASE}?category={row['categoryId']})"
lines.append(f"| {name} | {category} | {statuses[row['status']]} | {company} | {proof} | {row['note']} |")
if batch['sourceId'] == 'S04':
lines += ['', '产品页可读只表示有可访问的资料;本批未将所有产品页完成公司、技术或财务深查。既有直接HTTP采集返回403,当前采用可读的公开页面响应,不声称取得底层全量列表;后续公开档案与未读页面继续保留缺项。', '']
else:
lines += ['', '发现条目和可读正文分开记录;登录外壳、读取失败或搜索摘录不充当已阅读全文。关联公司以列出的原始材料补证,仍保留技术、主体与收入未核事项。', '']
return lines
def directory_rechecks():
rows = DATA.get('directoryRechecks', [])
if not rows:
return []
original = {row['ycId']: row for row in AUDIT['records']}
companies = {c['id']: c for c in DATA['companies']}
evidence = {e['id']: e for e in DATA['evidence']}
assert len({row['ycId'] for row in rows}) == len(rows)
lines = ['', '## 原候选池的后续复核', '',
'原始1,428条读取快照与初筛计数保持不变;下表记录当时未入表、后续补足证据后进入公司表的项目。初筛未通过不是永久排除。后续入表不回写为当时已匹配,也不重复计入928条原始新增目录项。', '',
'| 原候选 | 原始状态 | 后续公司记录 | 复核证据 | 处理与限制 |', '| --- | --- | --- | --- | --- |']
for row in rows:
baseline = original[row['ycId']]
assert baseline['status'] == row['originalStatus']
assert row['reviewedAt'] <= DATA['asOf'] and row['reason']
assert row['originalStatus'] in {'ai-unclear', 'year-outside-or-missing', 'date-conflict'}
company = companies[row['companyId']]
assert row['evidenceIds'] and all(eid in evidence for eid in row['evidenceIds'])
proof = '、'.join(f"[{eid}]({evidence[eid]['url']})" for eid in row['evidenceIds'])
lines.append(f"| [{baseline['name']} · YC{row['ycId']}]({baseline['source']}) | {row['originalStatus']} | [{company['name']}]({BASE}?company={company['id']}#research-company-detail) | {proof} | {row['reviewedAt']}:{row['reason']} |")
lines += ['', f"已记录{len(rows)}条后续复核入表;其余未入表候选仍按原状态保留缺项,不能把这一批复核视为完成全部模糊项。", '']
return lines
def render():
cov = DATA['coverage']
companies = DATA['companies']
depth = sum(bool(c.get('profileOnly')) for c in companies)
origin = sum(bool(c.get('profileOnly')) or c.get('directoryOrigin') == 'yc-2025-2026' for c in companies)
promoted = origin - depth
reviewed = sum(bool(c.get('profileOnly')) and '人工复核' in c.get('classificationBasis', '') for c in companies)
years = Counter(c['year'] for c in companies)
income = Counter(c['revenueStatus'] for c in companies)
technical = Counter(c.get('technicalReview', {}).get('level', 'unreviewed') for c in companies)
assert cov['profilesRead'] + cov['failedProfiles'] == cov['candidateRecords']
assert cov['matchingProfiles'] == cov['existingProfiles'] + cov['newProfiles']
assert cov['matchingProfiles'] + cov['otherOrMissingYear'] + cov['unclearAI'] + cov['dateConflicts'] == cov['profilesRead']
assert origin == cov['newProfiles']
assert AUDIT['accessedAt'] == cov['accessedAt']
assert AUDIT['counts'] == cov
assert len(AUDIT['records']) == cov['profilesRead']
assert Counter(x['status'] for x in AUDIT['records']) == {
'imported': cov['newProfiles'], 'existing': cov['existingProfiles'],
'year-outside-or-missing': cov['otherOrMissingYear'],
'ai-unclear': cov['unclearAI'], 'date-conflict': cov['dateConflicts']}
assert len({x['ycId'] for x in AUDIT['records']}) == len(AUDIT['records'])
lines = ['# AI 公司资料覆盖与缺项', '',
f"截至 {DATA['asOf']},研究表含{len(companies):,}条公司或产品记录。YC候选池有逐条读取审计;其他来源为定向补充。清单尚不能作为全球AI公司普查,也不能将收入未知解释为零。", '',
'验收范围已于2026-10-30确认为:以确认的公开来源清单为边界,逐条核对并标明缺项。下方区分已逐条审计的候选池与定向补充来源;已使用某来源不代表该来源已被完整覆盖。', '',
f"[分类和数据工作台]({BASE})链接原始证据,[收入样本快照](/docs/other-research/ai-company-research/income-snapshot)展示当前可计算的MRR样本。", '',
'## 候选池与公司表的关系', '',
'| 环节 | 记录数 | 含义 |', '| --- | --- | --- |',
f"| YC批次候选 | {cov['candidateRecords']:,} | 从公开镜像发现,随后读取YC官方页面 |",
f"| 官方页面读取 | {cov['profilesRead']:,} | 此候选池读取失败{cov['failedProfiles']}条 |",
f"| 初筛匹配 | {cov['matchingProfiles']:,} | 成立年及AI相关描述通过初筛,尚非逐家商业验证 |",
f"| 与原表重合 | {cov['existingProfiles']} | URL匹配,未再次新增 |",
f"| 新增目录记录 | {cov['newProfiles']:,} | 原始入表来源,后续深化不改变发现计数 |",
f"| 年份不符或缺失 | {cov['otherOrMissingYear']} | 此轮不作为成立年匹配项 |",
f"| AI业务待确认 | {cov['unclearAI']} | 不强行把背景关键词当主营 |",
f"| 成立年与批次冲突 | {cov['dateConflicts']} | 另保留核查记录 |", '',
f"全表由{depth}条目录基础项和{len(companies)-depth}条个案或平台记录组成。候选池已匹配项之外另有{len(companies)-cov['matchingProfiles']}条记录,包含其他来源及发布/转型对照;其中已有{promoted}条原目录记录深化为个案,仍保留目录来源。两种统计边界不同。候选池数字只是该镜像快照的覆盖,Bud等后续定向补充不回填为原候选池已覆盖。", '',
'## 成立年与证据深度', '',
'| 维度 | 当前记录 | 解读 |', '| --- | --- | --- |',
f"| 记录为2025年成立 | {years[2025]} | 成立来源和精度见公司明细 |",
f"| 记录为2026年成立 | {years[2026]} | 不将产品发布日期代替成立日 |",
f"| 成立年未知或范围外 | {sum(v for k,v in years.items() if k not in (2025,2026))} | 发布/转型对照单列,不进入两年成立分组 |",
f"| 目录业务分类人工复核 | {reviewed} | 仅复核主营分类,不代表技术或财务审计 |",
f"| 其他目录基础项 | {depth-reviewed} | 规则初分或资料不足,继续待复核 |",
f"| 有团队数字 | {sum(c['team'] is not None for c in companies)} | 多为自报Team Size或Employees,时点与口径不统一 |",
f"| 专项技术证据记录 | {len(companies)-technical['unreviewed']} | 其中{technical['description']}条自述、{technical['public-artifact']}条公开材料、{technical['independent-test']}条第三方评测 |",
f"| 公司披露收入线索 | {income['self']} | 含历史、下界、币种不明及产品业务声明,不等于可比ARR |",
f"| 仅平台收入线索 | {income['platform']} | 同时有公司披露者计入上一行,不重复计数 |",
f"| 仅第三方估算 | {income['estimate']} | 不与直接披露混合 |",
f"| 暂无可用收入数字 | {income['unknown']} | 包含尚未逐家搜索的目录项,不代表没有收入 |", '',
'## 业务分类与数据入口', '',
'| 业务类别 | 记录数 |', '| --- | --- |',
]
counts = Counter(c['cat'] for c in companies)
for category in DATA['categories']:
lines.append(f"| [{category['name']}]({BASE}?category={category['id']}) | {counts[category['id']]} |")
lines += ['', '## 已使用来源的分布', '',
f"{len(DATA['evidence']):,}条证据记录对应{len({e['url'] for e in DATA['evidence']}):,}个不同URL。不同URL不自动构成独立验证;同一声明可能由公司、投资方和媒体重复转述。", '',
'| 来源 | 证据记录 | 不同URL | 用途及限制 |', '| --- | --- | --- | --- |',
]
families = [('YC官方目录', 'www.ycombinator.com', '公司自述的成立、团队与业务;英文及加速器样本偏多'),
('TrustMRR', 'trustmrr.com', '支付平台重建指标及方法;公开者存在选择偏差,非财务审计'),
('a16z Speedrun', 'speedrun.a16z.com', '投资机构中的公司介绍及收入声明;存在利益关系'),
('TechCrunch', 'techcrunch.com', '原始采访或报道;转述公司数字不等于查账'),
('Sacra', 'sacra.com', '第三方估算;与直接披露分开')]
included = set()
for name, host, note in families:
entries = [e for e in DATA['evidence'] if urlsplit(e['url']).netloc == host]
included.add(host)
lines.append(f"| {name} | {len(entries)} | {len({e['url'] for e in entries})} | {note} |")
others = [e for e in DATA['evidence'] if urlsplit(e['url']).netloc not in included]
lines.append(f"| 其他官网、评测及公开资料 | {len(others)} | {len({e['url'] for e in others})} | 按每条来源限制理解,不能统一当作独立证据 |")
lines += directory_rechecks()
lines += source_register()
lines += context_methods()
lines += candidate_register()
lines += ['', '## 尚未满足的研究条件', '',
'行业ARR比较仍缺统一业务截止日、币种、经常性定义和业务边界。现有平台MRR可描述已采集产品,不足以代表全部新公司。技术评测只覆盖所列版本与任务,不宜跨领域汇总为统一强弱分数。', '',
'下一轮优先补收入线索的日期及合同定义、非YC和非英文来源、规则初分的人工复核,以及停止服务或被收购案例。这样能减少“只见赢家”和“只见融资公司”的偏差。公开来源池之外的未披露公司仍无法证明已被穷尽。', '',
]
return '\n'.join(lines)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--check', action='store_true')
parser.add_argument('--document-export', type=Path)
args = parser.parse_args()
content = render()
if args.check:
if args.document_export is not None:
bundle = json.loads(args.document_export.read_text())
stored = next((d['content'] for d in bundle['documents'] if d['sourceSlug'] == SOURCE_SLUG), None)
if stored != content:
sys.exit('Research coverage report differs; review and regenerate')
print('Research coverage accounting verified; supplied document export compared when requested')
else:
TARGET.parent.mkdir(parents=True, exist_ok=True)
TARGET.write_text(content)
print(TARGET.relative_to(ROOT))
if __name__ == '__main__':
main()
+4
View File
@@ -6,6 +6,10 @@ uv sync --project tools/figures --locked
pnpm run lint pnpm run lint
pnpm run typecheck pnpm run typecheck
pnpm --filter @endor/docs run test:auth pnpm --filter @endor/docs run test:auth
pnpm --filter @endor/docs run test:research
pnpm --filter @endor/docs run test:docs
pnpm --filter @endor/docs run images
pnpm --filter @endor/docs run test:images
cp -R apps/docs/public/figures /tmp/expected-figures cp -R apps/docs/public/figures /tmp/expected-figures
pnpm run figures pnpm run figures
uv run --locked --project tools/figures python -m unittest discover -s tools/figures/tests -v uv run --locked --project tools/figures python -m unittest discover -s tools/figures/tests -v
+17 -2
View File
@@ -14,7 +14,8 @@ ROOT = Path(__file__).resolve().parents[1]
APP = "endorphin-tabularium-docs" APP = "endorphin-tabularium-docs"
INPUTS = ["Dockerfile", "Dockerfile.ci", ".dockerignore", ".npmrc", "package.json", INPUTS = ["Dockerfile", "Dockerfile.ci", ".dockerignore", ".npmrc", "package.json",
"pnpm-lock.yaml", "pnpm-workspace.yaml", "apps/docs", "content", "tools/figures", "pnpm-lock.yaml", "pnpm-workspace.yaml", "apps/docs", "content", "tools/figures",
"scripts/check-container.sh", "scripts/ci.py"] "scripts/check-container.sh", "scripts/ci.py", "scripts/summarize-ai-income.py",
"scripts/audit-ai-research.py", "scripts/export-legacy-documents.py"]
def run(*args: str, capture: bool = False) -> str: def run(*args: str, capture: bool = False) -> str:
@@ -35,9 +36,17 @@ def fingerprint() -> str:
def smoke_image(image: str, name: str) -> None: def smoke_image(image: str, name: str) -> None:
run("docker", "run", "-d", "--name", name, "--mount", "type=volume,dst=/auth", "-p", "127.0.0.1::3000", image) run("docker", "run", "-d", "--name", name, "--mount", "type=volume,dst=/auth", "-e", "DOCUMENT_SMOKE_TEST=1", "-p", "127.0.0.1::3000", image)
try: try:
run("docker", "exec", name, "node", "apps/docs/auth-cli.cjs", "init") run("docker", "exec", name, "node", "apps/docs/auth-cli.cjs", "init")
subprocess.run(["docker", "exec", "-i", name, "node", "apps/docs/docs-cli.cjs", "import"],
input=(ROOT / ".artifacts/documents-migration.json").read_bytes(), check=True)
run("docker", "exec", name, "node", "apps/docs/docs-cli.cjs", "export", "/auth/migrated-documents.json")
migrated = json.loads(run("docker", "exec", name, "cat", "/auth/migrated-documents.json", capture=True))
expected = json.loads((ROOT / ".artifacts/documents-migration.json").read_text())
if migrated != expected:
raise RuntimeError("Migration changed document content or catalog metadata")
run("docker", "exec", name, "node", "apps/docs/docs-cli.cjs", "backup", "/auth/smoke-backup.sqlite")
for _ in range(60): for _ in range(60):
state = json.loads(run("docker", "inspect", name, capture=True))[0]["State"] state = json.loads(run("docker", "inspect", name, capture=True))[0]["State"]
if state.get("Health", {}).get("Status") == "healthy": if state.get("Health", {}).get("Status") == "healthy":
@@ -63,6 +72,12 @@ def smoke_image(image: str, name: str) -> None:
def main() -> None: def main() -> None:
os.chdir(ROOT) os.chdir(ROOT)
migration = ROOT / ".artifacts/documents-migration.json"
migration.parent.mkdir(exist_ok=True)
migration.unlink(missing_ok=True)
run(sys.executable, "scripts/export-legacy-documents.py", "--output", str(migration))
run(sys.executable, "scripts/summarize-ai-income.py", "--check")
run(sys.executable, "scripts/audit-ai-research.py", "--check")
run(sys.executable, "-m", "unittest", "discover", "-s", "scripts", "-p", "test_*.py") run(sys.executable, "-m", "unittest", "discover", "-s", "scripts", "-p", "test_*.py")
scope = os.environ.get("CI_CACHE_SCOPE", "main") scope = os.environ.get("CI_CACHE_SCOPE", "main")
if not re.fullmatch(r"main|pr-[0-9]+", scope): if not re.fullmatch(r"main|pr-[0-9]+", scope):
+50
View File
@@ -0,0 +1,50 @@
"""Draft business labels for public company profiles, never financial verification.
Input is a directory of JSON records with a `company` object containing
one_liner and tags, as retained by the official-profile research snapshot.
Output is for review; unmatched records remain C00 rather than being forced.
This tool does not fetch sources, modify the site database or run a build.
"""
import argparse
import json
import re
from pathlib import Path
def match(pattern,text):return bool(re.search(pattern,text,re.I))
def classify(c):
short=c.get('one_liner') or '';tags=' '.join(c.get('tags') or [])
rules=[
('C10',r'\brobot(?:s|ics|ic)?\b|embodied|physical intelligence|autonomous (?:driving|vehicle)|drones?|manufacturing hardware'),
('C02',r'context compression|compression middleware|RNA intelligence|audio data for AI|synthetic data|data quality|\bGPU\b|\bGPUs\b|\bchips?\b|semiconductor|data centers?|datacenters?|inference|compute|training data|data labeling|data labelling|RL environments|reinforcement learning|model training'),
('C07',r'precision medicine|ambulance|clinic|biology|manufacturers|distributors|fabrication|people-intelligence|deskless workers|health|medical|clinical|dental|physician|hospital|veterinar|therap|radiolog|pharma|legal|law firm|lawyer|litigation|accountant|accounting|audit\b|insurance|underwrit|financ|hedge funds?|bank|wealth|investment|investing|real estate|property|properties|construction|building (?:plan|code)|engineering projects|\bCAD\b|\bEDA\b|chip design|architecture|architects|logistics|supply chain|freight|global trade|compliance|government|govtech|lobby|energy|utilities|\bfleets?\b|education|edtech|\btutor|schools?|exam prep|tax\b|recruit|hiring|human resources|procurement|retail|e-commerce|ecommerce|merchants?|industrial'),
('C03',r'AI evaluations|AI governance|voice agents|chat AI agents|harnesses|agent.{0,25}(?:infrastructure|tools|identity|identities|memory|evaluation|eval|observability|browser|payment|communication)|(?:infrastructure|tools|identity|identities|evaluation|eval|observability|browsers?|payments?).{0,25}agents?|\bMCP\b|agentmail|API.{0,20}agents?|developer.{0,15}agents?'),
('C04',r'firmware|internal apps|coding|software engineer|code\b|codebase|developer|programming|app(?:lication)? (?:builder|creation|generation)|(?:build|building|make|create|generat).{0,25}(?:apps|applications|software)|\bDevOps\b|product docs|documentation engineer|\bIDE\b|logs and fix|testing|debug'),
('C06',r'\bsales\b|marketing|customer support|customer service|call center|call centre|\bGTM\b|\bCRM\b|\bSEO\b|\bGEO\b|\bAEO\b|growth engine|outbound|telemarketing|advertis|\bads\b|contact center|customer success'),
('C08',r'\bvideo\b|\bimage\b|\bphoto\b|\bfilm\b|\bdesign\b|animation|creative|creators?|content creation|\bmusic\b|media|audio edit|voiceover'),
('C01',r'foundation models?|frontier models?|large language models?|\bLLMs?\b|voice model|speech model|world model'),
('C09',r'consumer|personal|companions?|\bstor(?:y|ies)\b|entertainment|\bgam(?:e|es|ing)\b|social network|\bphone\b|smartphone|keyboard|your digital life'),
('C05',r'\bB2B\b|enterprise|workflow|workspace|productivity|operations|\bSaaS\b|\bSOP\b|Word editor|spreadsheet|knowledge|company OS|company brain|work\b|teams?|business|employee|meeting|security|cyber|search'),
]
for label,text in [('主营简介',short),('目录标签',tags)]:
for cat,pattern in rules:
if match(pattern,text):return cat,label+'的规则初分'
return 'C00','简介不足以确定主业务,待复核'
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", required=True, type=Path)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
result = []
for path in sorted(args.input.glob("*.json")):
record = json.loads(path.read_text())
company = record["company"]
category, basis = classify(company)
result.append({"ycId": company["id"], "category": category,
"basis": basis, "status": "provisional"})
args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
if __name__ == "__main__":
main()
+16
View File
@@ -7,6 +7,7 @@ import re
import shutil import shutil
import socket import socket
import subprocess import subprocess
import time
import urllib.request import urllib.request
from ci import APP, ROOT, fingerprint, run from ci import APP, ROOT, fingerprint, run
@@ -108,6 +109,21 @@ def main() -> None:
run("docker", "run", "--rm", "--network", "none", "--mount", run("docker", "run", "--rm", "--network", "none", "--mount",
f"type=bind,src={auth_dir},dst=/auth", actual, f"type=bind,src={auth_dir},dst=/auth", actual,
"node", "apps/docs/auth-cli.cjs", "init") "node", "apps/docs/auth-cli.cjs", "init")
# Back up the entire shared database, then bootstrap documents only when empty.
# A normal release never reimports, overwrites or resets authored DB content.
migration = ROOT / ".artifacts/documents-migration.json"
if not migration.is_file():
raise RuntimeError("Verified document migration export is missing")
backup = f"/auth/before-documents-{sha}-{time.time_ns()}.sqlite"
run("docker", "run", "--rm", "--network", "none", "--mount",
f"type=bind,src={auth_dir},dst=/auth", actual,
"node", "apps/docs/docs-cli.cjs", "backup", backup)
subprocess.run(["docker", "run", "--rm", "-i", "--network", "none", "--mount",
f"type=bind,src={auth_dir},dst=/auth", actual,
"node", "apps/docs/docs-cli.cjs", "import", "--if-empty"],
input=migration.read_bytes(), check=True)
shutil.copyfile(ROOT / "scripts/docs-admin.sh", DEPLOY_ROOT / "docs")
(DEPLOY_ROOT / "docs").chmod(0o750)
shutil.copyfile(ROOT / "scripts/auth-admin.sh", DEPLOY_ROOT / "auth") shutil.copyfile(ROOT / "scripts/auth-admin.sh", DEPLOY_ROOT / "auth")
(DEPLOY_ROOT / "auth").chmod(0o750) (DEPLOY_ROOT / "auth").chmod(0o750)
current = DEPLOY_ROOT / "current" current = DEPLOY_ROOT / "current"
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
# Run on ces-control. JSON content travels through stdin, never shell arguments.
set -eu
cd /opt/endorphin-tabularium-docs/current
case "${1:-}" in
list|get|save|history|export|backup|import|key-create|key-list|key-revoke)
docker compose -p endorphin-tabularium-docs --env-file /etc/endorphin-tabularium-docs/production.env --env-file release.env -f compose.yml exec -T docs node apps/docs/docs-cli.cjs "$@" ;;
*) echo 'Usage: docs key-create <name> <private-file> [read|read-write] [days] | key-list | key-revoke <id> | list | get <slug> | save < JSON | history <sourceSlug> | export <private-file> | backup <private-file> | import < JSON' >&2; exit 1 ;;
esac
+167
View File
@@ -0,0 +1,167 @@
"""Upload documents through the database API; credentials stay in a private file."""
import argparse
import json
import os
from pathlib import Path
import stat
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
class DocumentClientError(ValueError):
pass
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
# Never forward a bearer credential to a redirected host or protocol.
return None
def server_url(value):
parsed = urllib.parse.urlsplit(value)
if (parsed.username or parsed.password or parsed.query or parsed.fragment
or parsed.path not in ('', '/') or not parsed.hostname):
raise ValueError('Provide a server origin without credentials, path, query or fragment')
if parsed.scheme != 'https' and not (
parsed.scheme == 'http' and parsed.hostname in ('localhost', '127.0.0.1', '::1')):
raise ValueError('Use HTTPS or an HTTP loopback connection through a trusted SSH tunnel')
return value.rstrip('/')
def read_token(filename):
path = Path(filename)
if stat.S_IMODE(path.stat().st_mode) & 0o077:
raise ValueError('API key file must be private (chmod 600)')
value = path.read_text().strip()
if value.startswith('{'):
value = json.loads(value)['token']
if not isinstance(value, str) or not value.startswith('tdoc_') or len(value) != 48:
raise ValueError('Invalid document API key file')
return value
def request(base, token, method, path, payload=None, request_id=None):
data = None if payload is None else json.dumps(payload, ensure_ascii=False).encode()
if data is not None and len(data) > 8 * 1024 * 1024:
raise ValueError('Request exceeds 8 MiB; split into smaller atomic batches')
headers = {'Authorization': 'Bearer ' + token, 'Accept': 'application/json'}
if data is not None:
headers['Content-Type'] = 'application/json'
headers['Idempotency-Key'] = request_id
opener = urllib.request.build_opener(NoRedirect())
for attempt in range(2):
req = urllib.request.Request(base + path, data=data, method=method, headers=headers)
try:
with opener.open(req, timeout=30) as response:
return json.load(response)
except urllib.error.HTTPError as error:
if error.code in (502, 503, 504) and attempt == 0:
error.close()
time.sleep(1)
continue
status = error.code
error.close()
explanations = {400: 'Invalid document or pagination', 401: 'Key missing, expired or revoked',
403: 'Read-only key', 404: 'Document or revision not found',
409: 'Revision or request-id conflict; read current state before retrying',
413: 'Request too large', 503: 'Database unavailable'}
raise DocumentClientError(f'HTTP {status}: ' + explanations.get(status, 'Request failed')) from None
except (urllib.error.URLError, TimeoutError):
if attempt == 0:
time.sleep(1)
continue
raise DocumentClientError('Connection failed; retry using the same request id and unchanged input') from None
def document_batches(documents, max_bytes=8 * 1024 * 1024):
if not isinstance(documents, list) or not documents:
raise DocumentClientError('Provide a nonempty documents array')
batches, chunk, size, seen = [], [], 20, set()
for document in documents:
if not isinstance(document, dict) or not isinstance(document.get('sourceSlug'), str):
raise DocumentClientError('Every document needs a sourceSlug')
if document['sourceSlug'] in seen:
raise DocumentClientError('Duplicate sourceSlug in upload')
seen.add(document['sourceSlug'])
encoded = len(json.dumps(document, ensure_ascii=False).encode()) + 2
if encoded + 20 > max_bytes:
raise DocumentClientError('A document exceeds the request limit')
if chunk and (len(chunk) == 100 or size + encoded > max_bytes):
batches.append(chunk)
chunk, size = [], 20
chunk.append(document)
size += encoded
batches.append(chunk)
return batches
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--url', default=os.environ.get('TABULARIUM_DOCS_URL'))
parser.add_argument('--key-file', default=os.environ.get('TABULARIUM_DOCS_KEY_FILE'))
sub = parser.add_subparsers(dest='command', required=True)
listing = sub.add_parser('list')
listing.add_argument('--limit', type=int, default=50)
listing.add_argument('--offset', type=int, default=0)
reading = sub.add_parser('get')
reading.add_argument('slug')
mode = reading.add_mutually_exclusive_group()
mode.add_argument('--history', action='store_true')
mode.add_argument('--revision', type=int)
reading.add_argument('--limit', type=int, default=50)
reading.add_argument('--offset', type=int, default=0)
saving = sub.add_parser('save')
saving.add_argument('file', help='Private JSON file or - for stdin; one document or {documents: [...]}')
saving.add_argument('--request-id', help='Reuse this id only with the same input when retrying')
args = parser.parse_args()
if not args.url or not args.key_file:
parser.error('Set --url and --key-file or TABULARIUM_DOCS_URL and TABULARIUM_DOCS_KEY_FILE')
try:
base = server_url(args.url)
token = read_token(args.key_file)
if args.command == 'list':
result = request(base, token, 'GET', '/api/documents?' + urllib.parse.urlencode(
{'limit': args.limit, 'offset': args.offset}))
elif args.command == 'get':
path = '/api/documents/item/' + urllib.parse.quote(args.slug, safe='/')
if args.history:
path += '?' + urllib.parse.urlencode({'history': 1, 'limit': args.limit, 'offset': args.offset})
elif args.revision is not None:
path += '?' + urllib.parse.urlencode({'revision': args.revision})
result = request(base, token, 'GET', path)
else:
payload = json.load(sys.stdin) if args.file == '-' else json.loads(Path(args.file).read_text())
request_id = args.request_id or str(uuid.uuid4())
if not request_id or len(request_id) > 100 or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._:-' for c in request_id):
raise ValueError('Invalid request id')
print('Request id: ' + request_id, file=sys.stderr)
if isinstance(payload, dict) and 'documents' in payload:
if set(payload) != {'documents'}:
raise DocumentClientError('Batch payload must contain only documents')
chunks = document_batches(payload['documents'])
receipts, replayed = [], 0
for index, chunk in enumerate(chunks, 1):
batch_id = f'{request_id}:{index}'
saved = request(base, token, 'POST', '/api/documents/batch', {'documents': chunk}, batch_id)
receipts.extend(saved['documents'])
replayed += int(saved['replayed'])
print(f'Batch {index}/{len(chunks)} committed; {len(receipts)} documents total; request id: {batch_id}', file=sys.stderr)
result = {'documents': receipts, 'batches': len(chunks), 'replayedBatches': replayed, 'requestId': request_id}
else:
result = request(base, token, 'POST', '/api/documents', payload, request_id)
print(json.dumps(result, ensure_ascii=False, indent=2))
except DocumentClientError as error:
raise SystemExit(str(error)) from None
except (ValueError, OSError, KeyError, TypeError):
# Never print exception objects that could contain credentials or document data.
raise SystemExit('Document request failed. Check the URL, private key file, JSON schema and server response; credentials omitted.') from None
if __name__ == '__main__':
main()
+50
View File
@@ -0,0 +1,50 @@
"""One-time export from an explicit historical Git revision, never a runtime seed."""
import argparse
import json
import os
from pathlib import Path
import re
import subprocess
ROOT = Path(__file__).resolve().parents[1]
BASELINE = 'cffca6942b1bc0005321e1685f38593fb0b853d5' # Integration snapshot before database migration.
RESEARCH_REVISION = '74af205b2959e1bb6a1fe9f567bc87069ac6d12c' # Final PR 14 update received during integration.
def export(ref):
commit = subprocess.check_output(['git', 'rev-parse', '--verify', ref + '^{commit}'], cwd=ROOT, text=True).strip()
def read(name, revision=commit):
return subprocess.check_output(['git', 'show', f'{revision}:{name}'], cwd=ROOT).decode()
catalog = json.loads(read('content/catalog.json'))
names = subprocess.check_output(['git', 'ls-tree', '-r', '--name-only', commit, '--', 'content/docs'], cwd=ROOT, text=True).splitlines()
documents = []
for name in sorted(n for n in names if n.endswith('.md')):
source = name.removeprefix('content/docs/').removesuffix('.md')
metadata = catalog['documents'][source]
collection = next(c for c in catalog['collections'] if not c['path'] or source.startswith(c['path'] + '/'))
revision = RESEARCH_REVISION if commit == BASELINE and source.startswith("ai-company-research/") else commit
content = read(name, revision)
title = re.search(r'^# (.+)$', content, re.M)
documents.append(dict(slug=metadata['slug'], sourceSlug=source, category=metadata['category'],
title=title[1].strip() if title else source, content=content,
group=metadata.get('group', collection['title']), collection=metadata.get('collection', collection['title']),
description=metadata.get('description', collection['description']),
draft=metadata.get('draft', False), featured=metadata.get('featured', False), revision=1))
if not documents:
raise ValueError('Refusing empty migration')
return dict(format='tabularium-documents-v1', documents=documents)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--ref', default=BASELINE)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
payload = export(args.ref)
args.output.parent.mkdir(parents=True, exist_ok=True)
descriptor = os.open(args.output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, 'w') as output:
json.dump(payload, output, ensure_ascii=False)
print(f"Exported {len(payload['documents'])} documents; source is immutable Git history")
+1 -1
View File
@@ -27,7 +27,7 @@ def verify(base: str) -> None:
assert status == 200 and json.loads(health) == {"status": "ok"} assert status == 200 and json.loads(health) == {"status": "ok"}
status, _, login = get("/login") status, _, login = get("/login")
assert status == 200 and "输入动态码" in login.decode() assert status == 200 and "输入动态码" in login.decode()
for path in ("/", "/docs/00-endor-concepts-draft", "/figures/endor-architecture.svg"): for path in ("/", "/docs/00-endor-concepts-draft", "/figures/endor-architecture.svg", "/figures/endor-review-gate.webp", "/figures/endor-review-desk.webp", "/docs/pretext/01-chapter", "/materials/pretext/verify.cjs", "/materials/pretext/results.chrome156.json"):
status, headers, _ = get(path) status, headers, _ = get(path)
assert status == 307, path assert status == 307, path
target = urllib.parse.urlparse(urllib.parse.urljoin(base, headers["Location"])) target = urllib.parse.urlparse(urllib.parse.urljoin(base, headers["Location"]))
+159
View File
@@ -0,0 +1,159 @@
"""Render a fixed research snapshot; --check performs data analysis only, no build."""
import argparse
import datetime as dt
import json
from pathlib import Path
import statistics as st
import sys
ROOT = Path(__file__).resolve().parents[1]
DATA = json.loads((ROOT / 'content/research/ai-companies.seed.json').read_text())
REFERENCE = json.loads((ROOT / 'content/research/ai-income-analysis.json').read_text())
TARGET = ROOT / '.artifacts/reports/01-income-snapshot.md'
SOURCE_SLUG = 'ai-company-research/01-income-snapshot'
BASE = '/docs/other-research/ai-company-research/overview'
COMPANIES = {c['id']: c for c in DATA['companies']}
CATEGORIES = {c['id']: c['name'] for c in DATA['categories']}
END = dt.date.fromisoformat(DATA['asOf'])
def sample(days):
latest, excluded = {}, []
for o in DATA['observations']:
if o.get('selection') != 'platform' or o.get('metric') != 'mrr':
continue
c = COMPANIES[o['company']]
day = o.get('observedAt')
try:
parsed = dt.date.fromisoformat(day)
valid_date = parsed.isoformat() == day
except (TypeError, ValueError):
valid_date = False
valid = (c['year'] in (2025, 2026) and o.get('origin') == 'payment-platform'
and o['unit'] == 'USD' and o['bound'] == '='
and o.get('comparisonGroup') == 'trustmrr-usd-mrr'
and o.get('provider') and isinstance(o['value'], (int, float))
and 0 <= o['value'] < float('inf') and valid_date
and 0 <= (END - parsed).days <= days)
if not valid:
excluded.append(o)
continue
prior = latest.get(c['id'])
if prior is None or day > prior['observedAt']:
latest[c['id']] = o
return latest, excluded
def groups(points):
result = {}
for cid, o in points.items():
c = COMPANIES[cid]
key = (c['cat'], o['provider'], c.get('businessModel', '收费模式未核验'))
result.setdefault(key, []).append(o['value'])
return result
def stats(values):
mean = st.mean(values)
sd = st.stdev(values) if len(values) > 1 else None
reduced = st.mean(sorted(values)[:-1]) if len(values) > 1 else None
return dict(n=len(values), mean=mean, median=st.median(values),
sampleDeviation=sd, cv=sd / mean if sd is not None and mean else None,
meanWithoutLargest=reduced,
largestRemovalDrop=(mean - reduced) / mean if reduced is not None and mean else None)
def verify():
assert REFERENCE['sourceVersion'] == DATA['version'], 'Reference revision mismatch'
for window in REFERENCE['windows']:
points, _ = sample(window['days'])
assert set(points) == set(window['products']), 'Sample selection mismatch'
computed = groups(points)
assert len(computed) == len(window['groups'])
for group in window['groups']:
values = computed[(group['category'], group['provider'], group['model'])]
for key, value in stats(values).items():
expected = group[key]
assert (value is None and expected is None) or (
value is not None and expected is not None
and abs(value - expected) <= 1e-8 * max(1, abs(expected))), key
def money(value):
return f'{value:,.0f}' if value is not None else '不计算'
def link(cid):
return f"[{COMPANIES[cid]['name']}]({BASE}?company={cid}#research-company-detail)"
def render():
points, excluded = sample(7)
lines = [
'# AI 公司收入样本分布快照', '',
f"截至 {DATA['asOf']},7日窗口内有 {len(points)} 个产品的美元平台MRR可纳入分组描述。创意软件订阅组的样本均值较高、CV也较大;营销软件组与消费者个人应用组的CV接近。各组只有1至5个产品,尚不足以估计行业总体或造假概率。", '',
f"这是已采集资料的固定快照。[动态工作台]({BASE})提供筛选与原始证据。窗口按最后同步日计算,不保证所有点同日,也不是{len(DATA['companies']):,}条公司/产品记录的收入普查。", '',
'## 7日窗口的分组结果', '',
'MRR单位为美元每月。CV为样本标准差除以均值;最大值剔除降幅表示移除最高收入产品后均值下降的比例。单个样本不计算离散度。', '',
'| 业务及收费模式 | 平台 | 样本数 | 均值 | 中位数 | CV | 最大值剔除降幅 |',
'| --- | --- | --- | --- | --- | --- | --- |',
]
for key, values in sorted(groups(points).items()):
cat, provider, model = key
v = stats(values)
cv = f"{v['cv']:.3f}" if v['cv'] is not None else '不计算'
drop = f"{v['largestRemovalDrop']:.1%}" if v['largestRemovalDrop'] is not None else '不计算'
lines.append(f"| {CATEGORIES[cat]} · {model} | {provider} | {v['n']} | {money(v['mean'])} | {money(v['median'])} | {cv} | {drop} |")
lines += ['',
'在至少3个样本的组内,内容创意软件订阅的均值较高,但移除最大样本后的下降也最大。营销软件与个人应用的CV仅有微小差别,不据此宣称哪个领域更稳定。两个内容类单样本组虽有更高数值,不能作为典型收入或领域排名。', '',
'均值和中位数接近只描述当前采集点,并不证明样本具有代表性。平台公开者、成立年、规模、获客渠道与收费方式均可能影响结果。', '',
'## 样本与证据入口', '',
'点击产品名称可打开公司明细,再查看平台记录及其限制。连接已过期的近期快照仍按所标日期保留,并不表示连接当前有效。', '',
'| 产品 | 成立年 | MRR美元每月 | 最后同步 | 平台 | 连接状态 |',
'| --- | --- | --- | --- | --- | --- |',
]
for cid, o in sorted(points.items()):
status = '已过期的日期快照' if o.get('connectionExpired') else '采集时未标过期'
lines.append(f"| {link(cid)} | {COMPANIES[cid]['year']} | {money(o['value'])} | {o['observedAt']} | {o['provider']} | {status} |")
fresh = stats(groups(points)[('C06', 'Stripe', '软件订阅')])
broad, _ = sample(90)
older = stats(groups(broad)[('C06', 'Stripe', '软件订阅')])
lines += ['', '## 扩大窗口后的敏感性', '',
f"营销软件订阅组从7日窗口的{fresh['n']}个产品扩大到90日窗口的{older['n']}个产品,均值从{money(fresh['mean'])}升至{money(older['mean'])}美元每月,中位数从{money(fresh['median'])}变为{money(older['median'])},CV从{fresh['cv']:.3f}升至{older['cv']:.3f}。", '',
f"新增点来自{link('AI016')}的8月历史快照,连接已过期。移除该最大值后,均值回到{money(older['meanWithoutLargest'])}美元,下降{older['largestRemovalDrop']:.1%}。这是日期与样本构成的敏感性,不能解释为行业风险变化。", '',
'## 默认窗口排除的历史记录', '',
'| 产品 | MRR美元每月 | 最后同步 | 排除原因 |',
'| --- | --- | --- | --- |',
]
for o in excluded:
lines.append(f"| {link(o['company'])} | {money(o['value'])} | {o.get('observedAt', '未知')} | 超过7日窗口,保留历史观测 |")
lines += ['', '## 对 ARR 与商业模式的含义', '',
'MRR乘12只是参考年化。公司声明的ARR、合同管线、近30日收款、一次性额度和服务交付收入仍需分开;支付平台重建指标也不等于财务审计。方法与平台限制见[TrustMRR FAQ](https://trustmrr.com/faq)。', '',
'当前更适合选择访谈对象和设计收费试验,不能据最高均值直接决定业务方向。软件订阅优先核留存与推理成本,服务交付优先核人工工时和返工,消费者应用优先核渠道成本、退款和平台抽成。', '',
f"行业ARR比较仍需补齐同一业务截止日、币种、经常性定义及业务边界。收入日期不完整或同页数值冲突的声明,继续保留在[核查工作台]({BASE}),不补成零值或精确数字。", '',
]
return '\n'.join(lines)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--check', action='store_true')
parser.add_argument('--document-export', type=Path)
args = parser.parse_args()
verify()
content = render()
if args.check:
if args.document_export is not None:
bundle = json.loads(args.document_export.read_text())
stored = next((d['content'] for d in bundle['documents'] if d['sourceSlug'] == SOURCE_SLUG), None)
if stored != content:
sys.exit('Income snapshot differs; regenerate after reviewing data changes')
print('Income reference and samples verified; supplied document export compared when requested')
else:
TARGET.parent.mkdir(parents=True, exist_ok=True)
TARGET.write_text(content)
print(TARGET.relative_to(ROOT))
if __name__ == '__main__':
main()
+2 -2
View File
@@ -1,4 +1,4 @@
"""Guard cache invalidation against stale documents and needless metadata rebuilds.""" """Guard cache invalidation against stale application code and needless metadata rebuilds."""
from pathlib import Path from pathlib import Path
import subprocess import subprocess
import tempfile import tempfile
@@ -13,7 +13,7 @@ class FingerprintTests(unittest.TestCase):
root = Path(directory) root = Path(directory)
subprocess.run(["git", "init", "-q", str(root)], check=True) subprocess.run(["git", "init", "-q", str(root)], check=True)
(root / ".gitignore").write_text(".artifacts/\n**/.next/\n") (root / ".gitignore").write_text(".artifacts/\n**/.next/\n")
doc = root / "content/docs/concept.md" doc = root / "apps/docs/src/lib/docs.ts"
doc.parent.mkdir(parents=True) doc.parent.mkdir(parents=True)
doc.write_text("# Original\n") doc.write_text("# Original\n")
package = root / "package.json" package = root / "package.json"
+85
View File
@@ -0,0 +1,85 @@
"""Lightweight client tests: no HTTP server, compilation or real credentials."""
import importlib.util
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import urllib.error
import urllib.request
spec = importlib.util.spec_from_file_location('documents_client', Path(__file__).with_name('documents-client.py'))
client = importlib.util.module_from_spec(spec)
spec.loader.exec_module(client)
class ClientTests(unittest.TestCase):
def test_only_tls_or_loopback_origins_are_accepted(self):
self.assertEqual(client.server_url('https://docs.example/'), 'https://docs.example')
self.assertEqual(client.server_url('http://127.0.0.1:18135'), 'http://127.0.0.1:18135')
for url in ['http://docs.example', 'https://user:secret@docs.example', 'file:///tmp/data',
'https://docs.example/api', 'https://docs.example/?token=secret']:
with self.assertRaises(ValueError):
client.server_url(url)
def test_key_file_permissions_and_formats(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'key.json'
token = 'tdoc_' + 'x' * 43
path.write_text(json.dumps({'token': token}))
path.chmod(0o600)
self.assertEqual(client.read_token(path), token)
path.chmod(0o644)
with self.assertRaises(ValueError):
client.read_token(path)
def test_redirects_never_forward_bearer_credentials(self):
request = urllib.request.Request('https://docs.example', headers={'Authorization': 'Bearer test-only'})
self.assertIsNone(client.NoRedirect().redirect_request(request, None, 302, '', {}, 'https://other.example'))
def test_network_retry_preserves_idempotency_and_body(self):
calls = []
class Opener:
def open(self, request, timeout):
calls.append(request)
if len(calls) == 1:
raise urllib.error.URLError('temporary network failure')
return io.BytesIO(b'{"replayed":true}')
with patch.object(client.urllib.request, 'build_opener', return_value=Opener()), patch.object(client.time, 'sleep'):
result = client.request('https://docs.example', 'test-token', 'POST', '/api/documents', {'revision': 0}, 'request-1')
self.assertTrue(result['replayed'])
self.assertEqual(calls[0].data, calls[1].data)
self.assertEqual(calls[0].get_header('Idempotency-key'), 'request-1')
self.assertEqual(calls[1].get_header('Idempotency-key'), 'request-1')
def test_large_uploads_are_split_by_count_and_bytes(self):
documents = [{'sourceSlug': str(i), 'content': 'a' * 20} for i in range(201)]
batches = client.document_batches(documents)
self.assertEqual([len(batch) for batch in batches], [100, 100, 1])
self.assertEqual([doc for batch in batches for doc in batch], documents)
bounded = client.document_batches(documents[:5], max_bytes=150)
self.assertTrue(all(len(json.dumps({'documents': batch}, ensure_ascii=False).encode()) <= 150 for batch in bounded))
def test_duplicate_identifiers_and_oversized_items_fail_before_upload(self):
with self.assertRaises(ValueError):
client.document_batches([{'sourceSlug': 'same'}, {'sourceSlug': 'same'}])
with self.assertRaises(ValueError):
client.document_batches([{'sourceSlug': 'one', 'content': 'a' * 500}], max_bytes=100)
def test_conflict_is_reported_without_printing_server_content_or_secret(self):
class Opener:
def open(self, request, timeout):
raise urllib.error.HTTPError(request.full_url, 409, 'Conflict', {}, io.BytesIO(b'{"error":"private-content"}'))
with patch.object(client.urllib.request, 'build_opener', return_value=Opener()):
with self.assertRaisesRegex(client.DocumentClientError, 'HTTP 409') as result:
client.request('https://docs.example', 'private-token', 'POST', '/api/documents', {}, 'request-1')
self.assertNotIn('private-token', str(result.exception))
self.assertNotIn('private-content', str(result.exception))
if __name__ == '__main__':
unittest.main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

@@ -0,0 +1,14 @@
Endor inspection desk comic — approved second slide
Source: built-in image_gen; physics inspection-bench variant with corrected top-row flow.
Original: exec-432e0f3d-d01d-4658-b5d5-0c63db95e472.png
The user selected this alongside the gate variant for one carousel.
The two identical machines emit raw papers. Above, a dashed integral dW boundary
encloses the backlog BEFORE one person's fixed-capacity C0 inspection desk.
Below, a dashed dW boundary encloses the one new paper being inspected. Earlier
checked outputs become structured document helpers that contribute additional
magnifiers to the Endor desk, whose capacity is C0 + k integral dW.
Store this PNG as the production master outside public. The confirmed remote
runner generates /figures/endor-review-desk.webp using content/image-policy.json.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

@@ -0,0 +1,20 @@
Endor review gate comic — approved source
Source: built-in image_gen, physics gate variant, approved by the user on 2026-10-28.
Original: exec-380f8db3-6450-4981-97df-473c13a62223.png
The PNG is the production master, not a public browser asset.
The confirmed remote runner generates the browser WebP with:
pnpm --filter @endor/docs images
Visual specification:
Two rows, white background, charcoal outlines, blue accents, identical coding
machines emitting identical raw sheets. Top: accumulated unchecked sheets inside
a dashed integral dW boundary, one person and a fixed C0 inspection gate, checked
output after the gate. Bottom: one new sheet inside a dashed dW boundary directly
inspected by a stick figure at an Endor gate. Gate capacity is C0 + k integral dW.
Checked output becomes a structured document helper, joins historical helpers,
and blue arrows from helpers feed the gate to increase inspection capability.
No dialogue or explanatory prose. Math is a conceptual metaphor, not measured data.
The bitmap master retains the approved artwork, including its mathematical
symbols. Browser optimization changes encoding and dimensions only.