@itradingai/aiwiki 0.2.10 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,201 +1,235 @@
1
- ![AIWiki 宣传图](https://raw.githubusercontent.com/iTradingAI/aiwiki/refs/heads/main/docs/assets/aiwiki-hero.png)
1
+ ![AIWiki 宣传图](https://raw.githubusercontent.com/iTradingAI/aiwiki/main/docs/assets/aiwiki-hero.png)
2
2
 
3
3
  # AIWiki
4
4
 
5
- AIWiki 是一个开源的 Agent-first AI 知识库 CLI。你把文章链接、网页正文或本地文本交给宿主 Agent,宿主 Agent 负责读取内容,AIWiki 负责把结果稳定写进本地知识库,并生成适合 Obsidian 审阅的资料卡、主题、大纲和处理记录。
5
+ AIWiki 是一个开源的 Agent-first 本地 LLM-wiki CLI
6
6
 
7
- 对外只有一个 AIWiki,公开页面不做软件分层。商业服务放在部署、陪跑和团队集成里,不放在软件版本层。
7
+ 你把文章链接、网页正文或本地文本交给宿主 Agent;宿主 Agent 负责读取和理解内容;AIWiki 负责把结果稳定写进本地 Markdown 知识库,并生成可追踪、可查询、可持续整理的 Wiki 条目。
8
+
9
+ 一句话说:AIWiki 不是网页抓取器,而是宿主 Agent 的本地 LLM-wiki 后端。
8
10
 
9
11
  ## 它解决什么
10
12
 
11
- - 收藏了很多链接,但最后都散在聊天记录里
12
- - 想用 AI 总结内容,却很难继续写作或复用
13
- - 想做选题、资料卡和大纲,但每次都得重新整理
14
- - 想让 Agent 帮忙收资料,但缺一个稳定的本地入库出口
13
+ - 链接和资料散在聊天记录里,后续很难复用。
14
+ - AI 总结过一次内容,但没有沉淀成可查询的知识条目。
15
+ - 想把资料卡、选题、大纲、Wiki 条目放进同一个本地知识库。
16
+ - 想让 Agent 负责理解内容,让 CLI 负责稳定落盘和追踪。
17
+
18
+ ## 工作流
19
+
20
+ ### Ingest:把资料写入本地 Wiki
21
+
22
+ ```text
23
+ 用户给 URL / 正文 / 文件
24
+ -> 宿主 Agent 读取内容并尽量生成 analysis / wiki_entry
25
+ -> aiwiki ingest-agent --stdin
26
+ -> AIWiki 写入 Raw / Source Card / Wiki Entry / Claim / Topic / Outline / Run Log
27
+ ```
28
+
29
+ ### Query:从 Wiki 调度知识
30
+
31
+ ```bash
32
+ aiwiki context "AI Agent 出海机会"
33
+ ```
34
+
35
+ `context` 返回 JSON,主要给宿主 Agent 用。第一版是本地关键词检索,不是向量检索。
36
+
37
+ ### Lint:检查知识库结构
15
38
 
16
- ## 它会生成什么
39
+ ```bash
40
+ aiwiki lint
41
+ ```
17
42
 
18
- - 原文记录
19
- - Source Card 资料卡
20
- - Claim 建议
21
- - 创意素材
22
- - 选题候选
23
- - 草稿大纲
24
- - 处理摘要
25
- - Obsidian 审阅入口
43
+ `lint` 会检查缺失链接、重复来源、fallback Wiki 条目、enriched 条目缺字段等问题,并写入 `dashboards/Lint Report.md`。
26
44
 
27
- ## 直接发给 AI 帮你安装
45
+ ## 快速开始
28
46
 
29
- 如果你希望让 Codex、Claude Code、QClaw、OpenClaw 等 AI 直接帮你完成安装和配置,可以把下面这段话原样发给它,记得改成你自己的知识库路径:
47
+ ### 第一步:安装 AIWiki CLI
48
+
49
+ 让 AI 帮你安装时,可以把下面这段交给当前 Agent,改成自己的知识库路径:
30
50
 
31
51
  ```text
32
52
  请帮我安装并配置 AIWiki。
33
53
  安装命令:npm install -g @itradingai/aiwiki@latest
34
54
  我的知识库路径:F:\knowledges
35
55
 
36
- 要求:
37
- 1. 先检查本机 Node.js 是否满足 >=20。
38
- 2. 如果还没安装 AIWiki,就安装最新版 `@itradingai/aiwiki`。
39
- 3. 执行 `aiwiki setup --path "我的知识库路径" --yes`,帮我完成知识库初始化。
40
- 4. 执行 `aiwiki agent list` 检查当前环境支持哪些宿主 Agent。
41
- 5. 优先为当前 AI/Agent 安装 AIWiki 对接;如果能自动安装,就执行 `aiwiki agent install` 或对应的 `--agent` 命令。
42
- 6. 如果当前 Agent 不支持自动安装,就执行 `aiwiki prompt agent`,然后把生成的对接协议整理好,告诉我应该粘贴到哪里。
43
- 7. 完成后,再执行 `aiwiki doctor` 和 `aiwiki status`,确认安装和配置是否正常。
44
- 8. 最后告诉我:
45
- - 实际执行了哪些命令
46
- - 知识库路径是什么
47
- - Agent 对接是否完成
48
- - 如果还差手动步骤,明确告诉我下一步怎么做
56
+ 请检查 Node.js >=20,执行 aiwiki setup --path "我的知识库路径" --yes,
57
+ 然后运行 aiwiki agent list / aiwiki agent install 完成宿主 Agent 对接。
58
+ 最后执行 aiwiki doctor aiwiki status,告诉我实际执行了哪些命令和还差什么手动步骤。
49
59
  ```
50
60
 
51
- ## 手动安装
61
+ 手动安装:
52
62
 
53
63
  ```bash
54
64
  npx @itradingai/aiwiki@latest setup
55
65
  aiwiki agent list
56
66
  aiwiki agent install
57
- aiwiki prompt agent
58
67
  ```
59
68
 
60
- 然后把 `入库 <url>` 发给宿主 Agent
61
-
62
- ## 让宿主 Agent 直接安装 AIWiki
63
-
64
- 初始化知识库后,先扫一遍本机支持的宿主 Agent:
69
+ ### 第二步:接入宿主 Agent
65
70
 
66
71
  ```bash
67
72
  aiwiki agent list
73
+ aiwiki agent install
68
74
  ```
69
75
 
70
- 再启动安装向导:
76
+ 也可以直接输出通用协议:
71
77
 
72
78
  ```bash
73
- aiwiki agent install
79
+ aiwiki prompt agent
74
80
  ```
75
81
 
76
- 也可以直接指定目标:
82
+ ### 第三步:第一次入库
77
83
 
78
- ```bash
79
- aiwiki agent install --agent codex --yes
80
- aiwiki agent install --agent qclaw --yes
81
- aiwiki agent install --agent openclaw --yes
82
- aiwiki agent install --agent claude --yes
84
+ 对宿主 Agent 发送:
85
+
86
+ ```text
87
+ 入库 https://example.com/article
83
88
  ```
84
89
 
85
- 如果当前宿主 Agent 暂不支持自动安装,可以输出通用对接协议:
90
+ 宿主 Agent 读取正文后调用 `aiwiki ingest-agent --stdin`。用户不需要手动保存 payload,也不需要每次输入 `--path`。
86
91
 
87
- ```bash
88
- aiwiki prompt agent
92
+ ### 第四步:从知识库提问
93
+
94
+ 对宿主 Agent 说:
95
+
96
+ ```text
97
+ 从 AIWiki 里帮我了解 xxx
89
98
  ```
90
99
 
91
- 把输出内容安装成宿主 Agent 的 skill,或者粘贴到宿主 Agent 的项目说明里。
100
+ 宿主 Agent 应优先调用:
101
+
102
+ ```bash
103
+ aiwiki context "xxx"
104
+ ```
92
105
 
93
- ## 日常入库
106
+ ## AIWiki 会生成什么
94
107
 
95
- 完成 setup 和 Agent 安装后,对宿主 Agent 发送:
108
+ 成功入库会生成:
96
109
 
97
110
  ```text
98
- 入库 https://mp.weixin.qq.com/s/5i9UJdBOhCB2a1EVp0lVXQ
111
+ 02-raw/articles/
112
+ 03-sources/article-cards/
113
+ 04-claims/_suggestions/
114
+ 05-wiki/source-knowledge/
115
+ 06-assets/_suggestions/
116
+ 07-topics/ready/
117
+ 08-outputs/outlines/
118
+ 09-runs/<run-id>/
99
119
  ```
100
120
 
101
- 宿主 Agent 读取网页后,通过 `aiwiki ingest-agent --stdin` 把结构化内容交给 AIWiki CLI。用户不需要手动保存 payload,也不需要每次输入 `--path`。
121
+ 其中 `05-wiki/source-knowledge/<slug>.md` 是默认 Wiki Entry。
102
122
 
103
- 典型流程:
123
+ ### Agent-Enriched Wiki Entry
104
124
 
105
- ```text
106
- 用户发送链接 -> 宿主 Agent 读取内容 -> Agent 调用 AIWiki -> AIWiki 写入本地知识库 -> Obsidian 审阅和沉淀
125
+ 如果宿主 Agent 在 payload 中提供了 `analysis` 或 `wiki_entry`,AIWiki 会把这些总结、核心观点、知识点、概念、选题等内容写入 Wiki Entry。
126
+
127
+ frontmatter 会标记:
128
+
129
+ ```yaml
130
+ generation_mode: "agent_enriched"
131
+ quality: "enriched"
132
+ generated_by: "host_agent"
133
+ llm_enriched: true
134
+ ```
135
+
136
+ ### Deterministic Fallback Wiki Entry
137
+
138
+ 如果宿主 Agent 只提供原文,AIWiki 仍会创建 Wiki Entry,但它只是可追溯脚手架,包含标题、来源、正文预览、反链和待补全区。
139
+
140
+ frontmatter 会标记:
141
+
142
+ ```yaml
143
+ generation_mode: "deterministic_fallback"
144
+ quality: "scaffold"
145
+ generated_by: "aiwiki_cli"
146
+ llm_enriched: false
107
147
  ```
108
148
 
149
+ AIWiki CLI 本身不调用 LLM,所以不会在没有 Agent 分析字段时承诺高质量提炼。
150
+
109
151
  ## 设计边界
110
152
 
111
- AIWiki 不是通用网页抓取器。网页读取主要交给宿主 Agent,AIWiki 专注于把 Agent 已经读到的内容写成稳定、可追踪、可复用的本地知识资产。
153
+ AIWiki 做:
112
154
 
113
- AIWiki 生成的 Markdown 和 frontmatter 默认面向 Obsidian + Dataview 审阅;如果你不装 Dataview,普通 Markdown、Properties、Backlinks、Search 和 Graph View 也能用。
155
+ - 接收宿主 Agent payload。
156
+ - 写入本地 Markdown。
157
+ - 生成 frontmatter、wikilink、处理记录。
158
+ - 生成 Wiki Entry 容器。
159
+ - 支持 `context` 和 `lint`。
114
160
 
115
- 当前范围:
161
+ AIWiki 不做:
116
162
 
117
- - 只写入当前配置的知识库
118
- - 单次处理一条输入
119
- - 宿主 Agent 读取网页、附件或正文
120
- - CLI 写入本地文件和 Obsidian 友好的结构
121
- - 生成资料卡、素材建议、主题候选、草稿大纲、处理摘要
163
+ - 通用网页抓取。
164
+ - 微信公众号读取。
165
+ - 伪造浏览器头。
166
+ - 浏览器插件。
167
+ - CLI 内置 LLM。
168
+ - 自动高质量总结。
169
+ - 默认人工审核流程。
170
+ - 企业级 RBAC。
171
+ - 多知识库。
172
+ - 批量采集 / 定时采集 / RSS。
122
173
 
123
- 当前不包含:
174
+ ## Obsidian / Dataview
124
175
 
125
- - CLI 内置通用网页抓取
126
- - 跨主题自动路由
127
- - 批处理
128
- - 定时或指定采集
129
- - 长流程状态机
130
- - 技术支持流程
176
+ AIWiki 生成的是标准 Markdown 和 frontmatter,不强依赖 Obsidian。
131
177
 
132
- ## 示例展示
178
+ Obsidian 是推荐查看界面;Dataview 只是可选 dashboard 增强。AIWiki 不会自动安装 Dataview,也不会修改 `.obsidian`。
133
179
 
134
- 想先看一次完整跑完会生成什么,可以看:
180
+ Review Queue 可以保留为回看入口,但不是 AIWiki 的主流程。
135
181
 
136
- - [docs/SHOWCASE.md](docs/SHOWCASE.md)
182
+ ## 常见问题
183
+
184
+ ### AIWiki 会自己抓网页吗?
185
+
186
+ 不会。网页读取由宿主 Agent 完成,AIWiki 负责把 Agent 已经读到的内容写入本地知识库。
187
+
188
+ ### 为什么会生成 05-wiki?
189
+
190
+ 因为 AIWiki 的目标不是只保存资料,而是让资料进入可查询、可维护的 Wiki 知识层。
191
+
192
+ ### 05-wiki 是否代表我的观点?
193
+
194
+ 不一定。外部资料生成的 Wiki 条目默认代表“外部资料的结构化整理”,不代表你的个人观点。
195
+
196
+ ### 什么内容才代表我的观点?
197
+
198
+ 后续 `source_role=output` 会用于标记用户已发布文章、演讲稿、公众号文章等个人输出。本阶段外部资料默认是 `source_role: input`、`represents_user_view: false`。
199
+
200
+ ### Dataview 必须安装吗?
201
+
202
+ 不必须。没有 Dataview,也可以用普通 Markdown、Properties、Backlinks、Search 和 Graph View。
203
+
204
+ ### Review Queue 还需要吗?
205
+
206
+ 不是必需流程。它只适合低置信度、来源缺失、内容冲突、个人观点把关等回看场景。
137
207
 
138
208
  ## 文档
139
209
 
140
210
  - [docs/USAGE.md](docs/USAGE.md)
141
211
  - [docs/AGENT_HANDOFF.md](docs/AGENT_HANDOFF.md)
142
- - [docs/OBSIDIAN_DATAVIEW_PLAN.md](docs/OBSIDIAN_DATAVIEW_PLAN.md)
143
212
  - [docs/FAQ.md](docs/FAQ.md)
213
+ - [docs/SHOWCASE.md](docs/SHOWCASE.md)
144
214
  - [docs/ROADMAP.md](docs/ROADMAP.md)
145
215
  - [docs/RELEASE.md](docs/RELEASE.md)
146
216
  - [CONTRIBUTING.md](CONTRIBUTING.md)
147
217
  - [SECURITY.md](SECURITY.md)
148
- - [docs/architecture.svg](docs/architecture.svg)
149
-
150
- ## 参与与反馈
151
-
152
- 如果你想提 bug、提需求,或者反馈宿主 Agent 对接问题,直接看:
153
-
154
- - [CONTRIBUTING.md](CONTRIBUTING.md)
155
- - [.github/ISSUE_TEMPLATE/bug_report.md](.github/ISSUE_TEMPLATE/bug_report.md)
156
- - [.github/ISSUE_TEMPLATE/feature_request.md](.github/ISSUE_TEMPLATE/feature_request.md)
157
- - [.github/ISSUE_TEMPLATE/agent_integration.md](.github/ISSUE_TEMPLATE/agent_integration.md)
158
-
159
- ## 联系与交流
160
-
161
- 项目专题介绍:[maxking.cc](https://maxking.cc/aiwiki)
162
-
163
- <table>
164
- <tr>
165
- <td align="center" width="50%">
166
- <img src="https://raw.githubusercontent.com/iTradingAI/aiwiki/refs/heads/main/docs/assets/join-group.png" alt="扫码进群交流" width="360">
167
- <br>
168
- <strong>扫码进群</strong>
169
- </td>
170
- <td align="center" width="50%">
171
- <img src="https://raw.githubusercontent.com/iTradingAI/aiwiki/refs/heads/main/docs/assets/wechat-official-account.png" alt="扫码关注公众号" width="360">
172
- <br>
173
- <strong>关注公众号</strong>
174
- </td>
175
- </tr>
176
- </table>
177
218
 
178
219
  ## 本地开发
179
220
 
180
221
  ```bash
181
222
  npm install
182
223
  npm run build
224
+ npm test
183
225
  npm link
184
226
  aiwiki setup --path "F:\knowledge_data\aiwiki-test" --yes
185
- aiwiki prompt agent
186
227
  aiwiki doctor
228
+ aiwiki ingest-agent --payload tests/fixtures/agent_payload.url.valid.json --path "F:\knowledge_data\aiwiki-test"
229
+ aiwiki context "AI Agent" --path "F:\knowledge_data\aiwiki-test"
230
+ aiwiki lint --path "F:\knowledge_data\aiwiki-test"
187
231
  ```
188
232
 
189
- ## 最新动态
190
-
191
- - `2026-05-13`:更新了本地 Markdown 导入的命名规则,明确优先使用文件标题或文件名生成外部文件名,不优先从正文反推标题,并调整了 README 中的入口顺序和手动安装说明。
192
- - `2026-05-12`:公开前口径收口,统一 README、npm 元数据和公开文档入口。
193
- - `2026-05-09`:完成 npm 公开发布准备,补齐发布前的 README 与交付信息,并让 CLI 版本号与 `package.json` / 发布包保持一致,便于安装、排查与版本确认。
194
- - `2026-05-08`:完成中文化体验收口,包括默认生成中文 prompt、中文状态输出、中文目标描述,以及 README 和使用文档的中文本地化。
195
- - `2026-05-08`:强化 Obsidian 工作流,把 Review Queue、Claims Review 等审阅队列提升为一等入口,方便在知识库里持续审阅和回看入库内容。
196
- - `2026-05-07`:新增 Codex skill 安装能力,并补上 Agent 协议安装引导,让宿主 Agent 在正式入库前更容易完成对接。
197
- - `2026-05-07`:持续打磨初始化体验,修复 setup 提示问题,避免静默套用默认值,并把首次使用流程改成交互式引导。
198
-
199
233
  ## License
200
234
 
201
235
  MIT. See [LICENSE](LICENSE).
package/dist/src/app.js CHANGED
@@ -4,7 +4,9 @@ import path from "node:path";
4
4
  import { createInterface } from "node:readline/promises";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { flagBool, flagString, parseArgs } from "./args.js";
7
+ import { buildContext } from "./context.js";
7
8
  import { deriveFileTitle, ingestFile, ingestPayload } from "./ingest.js";
9
+ import { lintWorkspace, renderLintReport, writeLintReport } from "./lint.js";
8
10
  import { CliError, writeLine } from "./output.js";
9
11
  import { confirmInit, directorySummary, doctor, exists, initWorkspace, promptForSetup, promptForInitPath, readConfig, resolveWorkspace, setDefaultWorkspace, statusSummary } from "./workspace.js";
10
12
  export async function runCli(argv, streams = { stdout: process.stdout, stderr: process.stderr }) {
@@ -124,6 +126,23 @@ export async function runCli(argv, streams = { stdout: process.stdout, stderr: p
124
126
  writeLine(streams.stdout, `最近处理: ${summary.lastRunId ?? "无"}`);
125
127
  return 0;
126
128
  }
129
+ if (command === "context") {
130
+ const root = await resolveWorkspace(flagString(args, "path"));
131
+ const query = args.positional.slice(1).join(" ").trim();
132
+ if (!query) {
133
+ throw new CliError("请提供查询主题。");
134
+ }
135
+ writeLine(streams.stdout, JSON.stringify(await buildContext(root, query), null, 2));
136
+ return 0;
137
+ }
138
+ if (command === "lint") {
139
+ const root = await resolveWorkspace(flagString(args, "path"));
140
+ const report = await lintWorkspace(root);
141
+ const reportPath = await writeLintReport(root, report);
142
+ writeLine(streams.stdout, renderLintReport(report));
143
+ writeLine(streams.stdout, `report: ${reportPath}`);
144
+ return 0;
145
+ }
127
146
  if (command === "ingest-agent") {
128
147
  const root = await resolveWorkspace(flagString(args, "path"));
129
148
  const payloadPath = flagString(args, "payload");
@@ -203,6 +222,8 @@ function printHelp(stream) {
203
222
  writeLine(stream, " aiwiki prompt agent");
204
223
  writeLine(stream, " aiwiki doctor");
205
224
  writeLine(stream, " aiwiki status");
225
+ writeLine(stream, " aiwiki context <query>");
226
+ writeLine(stream, " aiwiki lint");
206
227
  writeLine(stream, " aiwiki ingest-agent --stdin");
207
228
  writeLine(stream, " aiwiki ingest-file --file <file>");
208
229
  writeLine(stream, " aiwiki init --path <path> --yes --set-default");
@@ -360,10 +381,13 @@ function printAgentPrompt(stream) {
360
381
  writeLine(stream, "");
361
382
  writeLine(stream, "如果当前会话被用户明确设定为 AIWiki 入库助手,则用户只发送 URL 也默认触发入库。普通会话中不要把所有 URL 都自动入库。");
362
383
  writeLine(stream, "");
363
- writeLine(stream, "流程:读取网页正文;生成 aiwiki.agent_payload.v1;通过 stdin 调用 `aiwiki ingest-agent --stdin`;读取 CLI 输出;只向用户汇报 ingested、recorded、fit_score、fit_level、summary、run_dirprocessing_summary、source_card、dashboard、review_queue。");
364
- writeLine(stream, "回复措辞:成功时说“已加入 Obsidian 审阅队列”,并给出资料卡、处理记录、Obsidian 入口和待审队列。Dataview 是可选增强,不要替用户安装插件或修改 .obsidian。");
384
+ writeLine(stream, "流程:读取网页正文;尽量生成 analysis/wiki_entry;生成 aiwiki.agent_payload.v1;通过 stdin 调用 `aiwiki ingest-agent --stdin`;读取 CLI 输出;向用户汇报 ingested、summary、wiki_entrywiki_entry_quality、source_card、processing_summary。");
385
+ writeLine(stream, "回复措辞:成功时说“AIWiki 已完成入库,并生成 Wiki 条目。” 如果 wiki_entry_quality=scaffold,说明该条目只是可追溯脚手架,仍需宿主 Agent 后续补全。Dataview 是可选增强,不要替用户安装插件或修改 .obsidian。");
386
+ writeLine(stream, "");
387
+ writeLine(stream, "查询:当用户要求从 AIWiki 里了解某个主题时,调用 `aiwiki context <主题>`。");
388
+ writeLine(stream, "整理:当用户要求检查或整理知识库时,调用 `aiwiki lint`。");
365
389
  writeLine(stream, "");
366
- writeLine(stream, "禁止:让用户保存 payload;让用户每次输入 --path;声称 AIWiki CLI 负责网页抓取。");
390
+ writeLine(stream, "禁止:让用户保存 payload;让用户每次输入 --path;声称 AIWiki CLI 负责网页抓取;声称 AIWiki CLI 会在没有 Agent 分析字段时自动高质量总结。");
367
391
  }
368
392
  function doctorStatusText(status) {
369
393
  if (status === "ok") {
@@ -389,6 +413,15 @@ function printIngestResult(stream, result) {
389
413
  writeLine(stream, `run_dir: ${result.runDir}`);
390
414
  writeLine(stream, `files: ${result.generatedFiles.length}`);
391
415
  writeLine(stream, `processing_summary: ${result.agentReport.keyFiles.processingSummary}`);
416
+ if (result.agentReport.keyFiles.wikiEntry) {
417
+ writeLine(stream, `wiki_entry: ${result.agentReport.keyFiles.wikiEntry}`);
418
+ }
419
+ if (result.agentReport.wikiEntryGenerationMode) {
420
+ writeLine(stream, `wiki_entry_generation_mode: ${result.agentReport.wikiEntryGenerationMode}`);
421
+ }
422
+ if (result.agentReport.wikiEntryQuality) {
423
+ writeLine(stream, `wiki_entry_quality: ${result.agentReport.wikiEntryQuality}`);
424
+ }
392
425
  if (result.agentReport.keyFiles.sourceCard) {
393
426
  writeLine(stream, `source_card: ${result.agentReport.keyFiles.sourceCard}`);
394
427
  }
@@ -0,0 +1,123 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { frontmatterArray, frontmatterString, parseMarkdown } from "./frontmatter.js";
4
+ import { relativePath } from "./paths.js";
5
+ import { exists } from "./workspace.js";
6
+ const GROUPS = [
7
+ { key: "wiki_entries", dir: "05-wiki", weight: 6 },
8
+ { key: "topics", dir: "07-topics/ready", weight: 5 },
9
+ { key: "source_cards", dir: "03-sources/article-cards", weight: 4 },
10
+ { key: "claims", dir: "04-claims/_suggestions", weight: 3 },
11
+ { key: "outlines", dir: "08-outputs/outlines", weight: 2 },
12
+ { key: "raw_refs", dir: "02-raw/articles", weight: 1 }
13
+ ];
14
+ export async function buildContext(rootPath, query, now = new Date().toISOString()) {
15
+ const root = path.resolve(rootPath);
16
+ const tokens = tokenize(query);
17
+ const result = {
18
+ schema_version: "aiwiki.context.v1",
19
+ query,
20
+ generated_at: now,
21
+ matches: {
22
+ wiki_entries: [],
23
+ source_cards: [],
24
+ claims: [],
25
+ topics: [],
26
+ outlines: [],
27
+ raw_refs: []
28
+ },
29
+ suggested_answer_structure: ["主题概览", "核心观点", "已有资料依据", "可复用判断", "下一步建议"],
30
+ warnings: []
31
+ };
32
+ if (!tokens.length) {
33
+ result.warnings.push("query is empty after tokenization");
34
+ return result;
35
+ }
36
+ for (const group of GROUPS.filter((item) => item.key !== "raw_refs")) {
37
+ const dir = path.join(root, group.dir);
38
+ if (!(await exists(dir))) {
39
+ continue;
40
+ }
41
+ const matches = await searchDir(root, dir, tokens, group.weight);
42
+ result.matches[group.key].push(...matches.slice(0, 10));
43
+ }
44
+ if (!result.matches.wiki_entries.length) {
45
+ result.warnings.push("未命中 Wiki Entry,结果可能来自资料卡、选题或原文引用。");
46
+ const rawGroup = GROUPS.find((item) => item.key === "raw_refs");
47
+ if (rawGroup) {
48
+ const rawDir = path.join(root, rawGroup.dir);
49
+ if (await exists(rawDir)) {
50
+ result.matches.raw_refs.push(...(await searchDir(root, rawDir, tokens, rawGroup.weight)).slice(0, 10));
51
+ }
52
+ }
53
+ }
54
+ return result;
55
+ }
56
+ async function searchDir(root, dir, tokens, weight) {
57
+ const files = await listMarkdownFiles(dir);
58
+ const matches = [];
59
+ for (const file of files) {
60
+ const text = await fs.readFile(file, "utf8");
61
+ const parsed = parseMarkdown(text);
62
+ const rel = relativePath(root, file);
63
+ const title = frontmatterString(parsed.frontmatter, "title") ?? path.basename(file, ".md");
64
+ const haystack = [
65
+ rel,
66
+ title,
67
+ frontmatterString(parsed.frontmatter, "source_url") ?? "",
68
+ frontmatterArray(parsed.frontmatter, "topics").join(" "),
69
+ frontmatterArray(parsed.frontmatter, "tags").join(" "),
70
+ parsed.body
71
+ ].join("\n").toLowerCase();
72
+ const hits = tokens.filter((token) => haystack.includes(token.toLowerCase())).length;
73
+ if (!hits) {
74
+ continue;
75
+ }
76
+ const generationMode = frontmatterString(parsed.frontmatter, "generation_mode");
77
+ const quality = frontmatterString(parsed.frontmatter, "quality");
78
+ const warnings = generationMode === "deterministic_fallback"
79
+ ? ["该 Wiki Entry 是 deterministic fallback,仅包含来源、正文预览和待补全区。"]
80
+ : [];
81
+ matches.push({
82
+ title,
83
+ path: rel,
84
+ summary: frontmatterString(parsed.frontmatter, "summary") ?? summarize(parsed.body, quality),
85
+ score: Number(((hits / tokens.length) * weight).toFixed(2)),
86
+ topics: frontmatterArray(parsed.frontmatter, "topics"),
87
+ source_url: frontmatterString(parsed.frontmatter, "source_url") ?? "",
88
+ generation_mode: generationMode,
89
+ quality,
90
+ warnings
91
+ });
92
+ }
93
+ return matches.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
94
+ }
95
+ async function listMarkdownFiles(dir) {
96
+ const entries = await fs.readdir(dir, { withFileTypes: true });
97
+ const files = [];
98
+ for (const entry of entries) {
99
+ const target = path.join(dir, entry.name);
100
+ if (entry.isDirectory()) {
101
+ files.push(...await listMarkdownFiles(target));
102
+ }
103
+ else if (entry.isFile() && entry.name.toLowerCase().endsWith(".md")) {
104
+ files.push(target);
105
+ }
106
+ }
107
+ return files;
108
+ }
109
+ function tokenize(value) {
110
+ const compact = value.trim();
111
+ if (!compact) {
112
+ return [];
113
+ }
114
+ const asciiTokens = compact.split(/[^\p{L}\p{N}]+/u).filter((token) => token.length >= 2);
115
+ return Array.from(new Set([compact, ...asciiTokens]));
116
+ }
117
+ function summarize(body, quality) {
118
+ const compact = body.replace(/\s+/g, " ").trim();
119
+ if (quality === "scaffold") {
120
+ return "仅有正文预览,未生成高质量摘要。";
121
+ }
122
+ return compact.length > 180 ? `${compact.slice(0, 180)}...` : compact;
123
+ }
@@ -0,0 +1,55 @@
1
+ export function parseMarkdown(text) {
2
+ if (!text.startsWith("---")) {
3
+ return { frontmatter: {}, body: text };
4
+ }
5
+ const end = text.indexOf("\n---", 3);
6
+ if (end === -1) {
7
+ return { frontmatter: {}, body: text };
8
+ }
9
+ const rawFrontmatter = text.slice(3, end).trim();
10
+ const body = text.slice(end).replace(/^\n---\r?\n?/, "");
11
+ return { frontmatter: parseFrontmatter(rawFrontmatter), body };
12
+ }
13
+ export function parseFrontmatter(text) {
14
+ const result = {};
15
+ for (const line of text.split(/\r?\n/)) {
16
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line.trim());
17
+ if (!match) {
18
+ continue;
19
+ }
20
+ result[match[1]] = parseScalar(match[2]);
21
+ }
22
+ return result;
23
+ }
24
+ export function frontmatterString(value, key) {
25
+ const item = value[key];
26
+ return typeof item === "string" ? item : undefined;
27
+ }
28
+ export function frontmatterBoolean(value, key) {
29
+ const item = value[key];
30
+ return typeof item === "boolean" ? item : undefined;
31
+ }
32
+ export function frontmatterArray(value, key) {
33
+ const item = value[key];
34
+ return Array.isArray(item) ? item : [];
35
+ }
36
+ function parseScalar(value) {
37
+ const trimmed = value.trim();
38
+ if (trimmed === "true") {
39
+ return true;
40
+ }
41
+ if (trimmed === "false") {
42
+ return false;
43
+ }
44
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
45
+ return trimmed
46
+ .slice(1, -1)
47
+ .split(",")
48
+ .map((item) => unquote(item.trim()))
49
+ .filter(Boolean);
50
+ }
51
+ return unquote(trimmed);
52
+ }
53
+ function unquote(value) {
54
+ return value.replace(/^["']|["']$/g, "");
55
+ }