@wkgeo/cli 1.1.0 → 1.1.2

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.
Files changed (41) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +163 -25
  3. package/SKILL.md +121 -36
  4. package/lib/args.mjs +2 -2
  5. package/lib/asset-role.mjs +68 -0
  6. package/lib/cms.mjs +2 -2
  7. package/lib/commands/billing.mjs +56 -10
  8. package/lib/commands/cms.mjs +49 -13
  9. package/lib/commands/content.mjs +108 -0
  10. package/lib/commands/crawl.mjs +219 -0
  11. package/lib/commands/geo.mjs +1673 -0
  12. package/lib/commands/index.mjs +640 -541
  13. package/lib/commands/member.mjs +930 -0
  14. package/lib/commands/seo.mjs +1386 -0
  15. package/lib/commands/siteops.mjs +3 -3
  16. package/lib/commands/sites.mjs +21 -125
  17. package/lib/commands/template.mjs +1222 -6
  18. package/lib/config.mjs +16 -13
  19. package/lib/content-apply.mjs +664 -0
  20. package/lib/content-check.mjs +887 -0
  21. package/lib/content-contract.mjs +957 -0
  22. package/lib/errors.mjs +6 -0
  23. package/lib/format.mjs +5 -1
  24. package/lib/login.mjs +15 -3
  25. package/lib/manifest-apply.mjs +1499 -0
  26. package/lib/manifest-schema.json +476 -0
  27. package/lib/manifest.mjs +1082 -0
  28. package/lib/oauth-urls.mjs +1 -1
  29. package/lib/runtime.mjs +5 -1
  30. package/lib/site-create.mjs +536 -0
  31. package/lib/template-anim.mjs +1338 -0
  32. package/lib/template-animation.mjs +232 -0
  33. package/lib/template-capture.mjs +700 -0
  34. package/lib/template-gen.mjs +1204 -0
  35. package/lib/template-pack.mjs +206 -0
  36. package/lib/template-publish.mjs +733 -0
  37. package/lib/template-score.mjs +865 -0
  38. package/lib/template-validate.mjs +368 -0
  39. package/lib/template-verify.mjs +434 -0
  40. package/lib/templates-sync.mjs +616 -0
  41. package/package.json +2 -2
@@ -0,0 +1,1673 @@
1
+ /**
2
+ * `wkgeo geo` —— **本地站点产物**的 GEO(Generative Engine Optimization,生成式引擎优化)工具。
3
+ *
4
+ * 与 `seo` 组的关系(重要,别写重复实现):
5
+ * * HTML 解析 / 实体解码 / 目录遍历 / 站点清单 / robots 语法 / 字数统计**全部从 `seo.mjs` import**,
6
+ * 这里只加 GEO 特有的判定(AI 爬虫策略、llms.txt 质量、语义结构、可提取性、实体标注);
7
+ * * 与插件 `geo`(按站点 ID 读库)是两个面:这里吃目录里的静态产物,**上线前**就能跑。
8
+ *
9
+ * 五条命令:
10
+ * 1. `geo audit <dir>` 0-100 分 + issues[](severity / file / rule / message / suggestion)+ summary + grade;
11
+ * 2. `geo llms <dir> [--check]` 生成 llms.txt / llms-full.txt(分类小节 + 一句话摘要 + 链接),`--check` 只校验;
12
+ * 3. `geo robots <dir> --mode allow-ai|block-ai|show` AI 爬虫策略段(保留人工规则 + 幂等 + 默认 dry-run);
13
+ * 4. `geo brands` 品牌跟踪入口(**后台 API 未就绪**:未配置就返回 `not_configured` + 契约,不联网);
14
+ * 5. `geo report <dir> [--md]` 汇总 audit + brands 的报告(json / markdown)。
15
+ *
16
+ * 全局约定(与 `seo` 一致):
17
+ * * `--json` 走统一信封;人类输出走 `out.head/line/ok/warn`;
18
+ * * **写盘默认 dry-run**,`--confirm` 才落盘;
19
+ * * 报告类命令(audit / report)**有问题也 exit 0**,只有用法错(2)/ 无页面(1)/ 校验门禁失败(1)才非 0;
20
+ * * 零第三方依赖、**不联网**(唯一例外:`geo brands` 在配置了 `WKGEO_GEO_API` 时)。
21
+ */
22
+
23
+ import fs from 'node:fs';
24
+ import path from 'node:path';
25
+
26
+ import { CliError, UsageError } from '../errors.mjs';
27
+ import {
28
+ analyzeRobots,
29
+ charCount,
30
+ clip,
31
+ collapse,
32
+ decodeEntities,
33
+ gradeOf,
34
+ listHtmlFiles,
35
+ pageText,
36
+ pageUrl,
37
+ parsePageHtml,
38
+ readSiteMeta,
39
+ stripTags,
40
+ } from './seo.mjs';
41
+
42
+ /* ================================================================== 常量 */
43
+
44
+ /**
45
+ * 20 项 GEO 审计规则与权重(**合计 100**)。
46
+ *
47
+ * 与 `seo` 组的 13 项**不重叠**:那边是"搜索引擎收录友好",这里是"生成式引擎能不能读懂 / 摘取 / 引用"。
48
+ * `site: true` = 站点级(整目录只算一次,`total` 由检查自己给,可能 > 1);
49
+ * 其余按页算(`total` = 页数 − 该页 skip 数)。
50
+ *
51
+ * | 分组 | 规则 | 权重 |
52
+ * | --- | --- | --- |
53
+ * | AI 爬虫策略 | ai_bots_allow 10 / ai_bots_block 6 | 16 |
54
+ * | llms.txt | llms_txt 6 / llms_structure 6 / llms_full 4 | 16 |
55
+ * | 语义结构 | h1_unique 8 / heading_hierarchy 5 / faq_block 6 / extractable 5 | 24 |
56
+ * | 可提取性 | answer_description 6 / lead_paragraph 5 / body_length 4 | 15 |
57
+ * | 实体标注 | jsonld_types 8 / jsonld_required 6 | 14 |
58
+ * | 其它 | title_unique 4 / html_lang 2 / canonical 2 / og 2 / img_alt 2 / internal_links 3 | 15 |
59
+ * | **合计** | | **100** |
60
+ */
61
+ export const GEO_AUDIT_RULES = [
62
+ /* ---- AI 爬虫策略(16) ---- */
63
+ { id: 'ai_bots_allow', weight: 10, site: true, title: 'AI 爬虫显式放行(6 个 UA 在 robots.txt 里各自有 Allow)' },
64
+ { id: 'ai_bots_block', weight: 6, site: true, title: '没有对 AI 爬虫整站封禁(Disallow: /)' },
65
+ /* ---- llms.txt(16) ---- */
66
+ { id: 'llms_txt', weight: 6, site: true, title: 'llms.txt 存在' },
67
+ { id: 'llms_structure', weight: 6, site: true, title: 'llms.txt 有小节 / 链接 / 一句话摘要' },
68
+ { id: 'llms_full', weight: 4, site: true, title: 'llms-full.txt 存在(正文全文给 AI 读)' },
69
+ /* ---- 语义结构(24,按页) ---- */
70
+ { id: 'h1_unique', weight: 8, title: '每页恰好 1 个 H1' },
71
+ { id: 'heading_hierarchy', weight: 5, title: 'H2/H3 层级不跳级' },
72
+ { id: 'faq_block', weight: 6, title: '有 FAQ / 问答区块(FAQ / 常见问题 / <details> / mainEntity)' },
73
+ { id: 'extractable', weight: 5, title: '有 ul / ol / table 等可摘取结构' },
74
+ /* ---- 可提取性(15,按页) ---- */
75
+ { id: 'answer_description', weight: 6, title: 'meta description 是答案式(40-160 字符、非空话)' },
76
+ { id: 'lead_paragraph', weight: 5, title: '首段直接陈述主题(≥ 30 字符、非"欢迎访问"套话)' },
77
+ { id: 'body_length', weight: 4, title: '单页正文 ≥ 500 字符' },
78
+ /* ---- 实体标注(14) ---- */
79
+ { id: 'jsonld_types', weight: 8, site: true, title: 'JSON-LD 覆盖 Organization / Article / FAQPage / BreadcrumbList' },
80
+ { id: 'jsonld_required', weight: 6, title: 'JSON-LD 必填字段齐全(Article / FAQPage / Organization…)' },
81
+ /* ---- 其它(15) ---- */
82
+ { id: 'title_unique', weight: 4, site: true, title: '页面 title 不重复' },
83
+ { id: 'html_lang', weight: 2, title: '<html lang> 存在' },
84
+ { id: 'canonical', weight: 2, title: 'canonical 存在' },
85
+ { id: 'og', weight: 2, title: 'og:title / og:description / og:image 齐全' },
86
+ { id: 'img_alt', weight: 2, title: '图片都有 alt 属性' },
87
+ { id: 'internal_links', weight: 3, title: '内链 ≥ 3 条(页面之间互相可达)' },
88
+ ];
89
+
90
+ /** 站点级规则 id(整目录只算一次) */
91
+ const SITE_RULE_IDS = new Set(GEO_AUDIT_RULES.filter((rule) => rule.site).map((rule) => rule.id));
92
+
93
+ /**
94
+ * 要检查的 AI 爬虫(2026-10 口径)。
95
+ * `note` 只用于人类输出,说明"这家抓什么",不做任何请求。
96
+ */
97
+ export const AI_BOTS = [
98
+ { bot: 'GPTBot', note: 'OpenAI 训练/检索抓取' },
99
+ { bot: 'OAI-SearchBot', note: 'ChatGPT 搜索索引' },
100
+ { bot: 'ClaudeBot', note: 'Anthropic 抓取' },
101
+ { bot: 'PerplexityBot', note: 'Perplexity 检索' },
102
+ { bot: 'Google-Extended', note: 'Google 的 AI 训练开关(不影响搜索收录)' },
103
+ { bot: 'Bingbot', note: 'Bing / Copilot 索引' },
104
+ ];
105
+
106
+ /** 一次最多报多少条 issue(大站全量会刷屏;`--json` 里带 `truncated:true`) */
107
+ const MAX_ISSUES = 500;
108
+ /** llms.txt 里一句话摘要最多多少字符 */
109
+ const LLMS_SUMMARY_CHARS = 120;
110
+ /** llms-full.txt 里每页正文摘录最多多少字符 */
111
+ const LLMS_FULL_PAGE_CHARS = 3000;
112
+ /** 正文长度门槛(可提取性) */
113
+ const BODY_MIN_CHARS = 500;
114
+ const BODY_WARN_CHARS = 300;
115
+ /** description 的答案式长度区间 */
116
+ const DESC_MIN_CHARS = 40;
117
+ const DESC_MAX_CHARS = 160;
118
+ /** 首段最少多少字符才算"陈述了主题" */
119
+ const LEAD_MIN_CHARS = 30;
120
+ /** 内链条数门槛 */
121
+ const INTERNAL_LINKS_MIN = 3;
122
+
123
+ /** description 里典型的"空话"开头(不针对某一家,只判句式) */
124
+ const FLUFF_START = /^(欢迎|点击|了解更多|欢迎访问|本站|我们致力于|敬请)/;
125
+ const FLUFF_ANY = /lorem ipsum|欢迎访问本站|点击了解更多|致力于打造/i;
126
+
127
+ /** FAQ / 问答区块的识别信号(HTML 层) */
128
+ const FAQ_PATTERNS = [
129
+ /\bFAQ\b/i,
130
+ /常见问题/,
131
+ /问答/,
132
+ /<details\b/i,
133
+ /itemprop\s*=\s*["']?mainEntity/i,
134
+ /schema\.org\/Question/i,
135
+ ];
136
+
137
+ /** 可摘取结构(列表 / 表格 / 定义列表) */
138
+ const EXTRACTABLE_RE = /<(ul|ol|table|dl)\b/i;
139
+
140
+ /** JSON-LD 必填字段(key 为小写 @type;Article 的子类型都归到 article) */
141
+ const JSONLD_REQUIRED = {
142
+ organization: ['name', 'url'],
143
+ website: ['name', 'url'],
144
+ article: ['headline', 'datePublished', 'author'],
145
+ faqpage: ['mainEntity'],
146
+ breadcrumblist: ['itemListElement'],
147
+ product: ['name'],
148
+ person: ['name'],
149
+ };
150
+
151
+ /** Article 家族的 @type(JSON-LD 里常见写法) */
152
+ const ARTICLE_TYPES = new Set(['article', 'newsarticle', 'blogposting', 'techarticle', 'scholarlyarticle']);
153
+
154
+ /** GEO 报告要求覆盖的实体类型(`jsonld_types` 的 4 个格子) */
155
+ const GEO_ENTITY_TYPES = ['Organization', 'Article', 'FAQPage', 'BreadcrumbList'];
156
+
157
+ /** robots.txt 托管块的边界标记(幂等靠它:重跑整段替换,绝不叠加) */
158
+ const ROBOTS_BEGIN = '# >>> wkgeo:geo-ai >>>';
159
+ const ROBOTS_END = '# <<< wkgeo:geo-ai <<<';
160
+
161
+ /** `geo robots --mode` 允许的取值 */
162
+ export const GEO_ROBOTS_MODES = ['allow-ai', 'block-ai', 'show'];
163
+
164
+ /** 品牌跟踪平台状态(与后台契约一致) */
165
+ export const BRAND_STATUSES = ['none', 'listed', 'top', 'cited'];
166
+
167
+ /**
168
+ * `geo brands` 的后台契约(**只写形状,不写任何 URL / 密钥**)。
169
+ * 未配置 `WKGEO_GEO_API` 时原样返回给用户,说明"为什么没有数据"。
170
+ */
171
+ export const GEO_BRANDS_CONTRACT = {
172
+ env: 'WKGEO_GEO_API',
173
+ request: {
174
+ method: 'GET',
175
+ path: '/api/geo/brands',
176
+ query: { domain: '<站点域名>', lang: '<语言,如 zh-CN>' },
177
+ },
178
+ response: {
179
+ brands: [
180
+ {
181
+ name: '品牌名',
182
+ platforms: [
183
+ {
184
+ platform: '平台标识(如 chatgpt / perplexity)',
185
+ status: BRAND_STATUSES,
186
+ rank: '数字或 null',
187
+ citations: '数字或 null',
188
+ url: '引用链接或空串',
189
+ checkedAt: 'ISO 时间或空串',
190
+ },
191
+ ],
192
+ },
193
+ ],
194
+ },
195
+ statuses: BRAND_STATUSES,
196
+ };
197
+
198
+ /* ================================================================== robots.txt:按 UA 分组 */
199
+
200
+ /**
201
+ * robots.txt 按 `User-agent` 分组(标准语义:连续多条 `User-agent` 共享同一组规则)。
202
+ *
203
+ * `seo.mjs` 的 `analyzeRobots()` 只给**扁平指令流**,做 AI 爬虫判定必须知道"这条规则属于哪个 UA",
204
+ * 所以在它上面再分一层,**不重复实现语法解析**(坏行告警仍由 `analyzeRobots` 出)。
205
+ *
206
+ * 返回 `{ groups:[{agents:[小写UA], rules:[{name:'allow'|'disallow', value}]}], directives, sitemapLines, issues }`
207
+ */
208
+ export function parseRobotsGroups(text) {
209
+ const parsed = analyzeRobots(text);
210
+ const groups = [];
211
+ let current = { agents: [], rules: [] };
212
+ const flush = () => {
213
+ if (current.agents.length || current.rules.length) groups.push(current);
214
+ current = { agents: [], rules: [] };
215
+ };
216
+ for (const one of parsed.directives) {
217
+ if (one.name === 'user-agent') {
218
+ /** 上一组已经出现过规则 ⇒ 这是一组的开始;否则是同一组的多 UA 并列 */
219
+ if (current.rules.length) flush();
220
+ const agent = String(one.value || '').trim().toLowerCase();
221
+ if (agent) current.agents.push(agent);
222
+ continue;
223
+ }
224
+ if (one.name === 'allow' || one.name === 'disallow') {
225
+ if (!current.agents.length) current.agents.push('*');
226
+ current.rules.push({ name: one.name, value: String(one.value || '').trim() });
227
+ }
228
+ }
229
+ flush();
230
+ return { groups, directives: parsed.directives, sitemapLines: parsed.sitemapLines, issues: parsed.issues };
231
+ }
232
+
233
+ /** 这条 Allow/Disallow 是否"整站"(`/` 或 `/*`) */
234
+ function isWholeSiteRule(value) {
235
+ const v = String(value || '').trim();
236
+ return v === '/' || v === '/*';
237
+ }
238
+
239
+ /**
240
+ * 每个 AI 爬虫的实际状态。
241
+ *
242
+ * 判定口径(照 robots.txt 规范,<b>显式 UA 组覆盖 `*` 组</b>):
243
+ * * `explicit`:有该 UA 的专属组;
244
+ * * `blocked`:生效的组里有整站 `Disallow: /` 且同组没有整站 `Allow: /`;
245
+ * * `allowed`:没有被整站封禁(显式组里 `Allow: /` 或只有局部 Disallow);
246
+ * * `unlisted`:既没有专属组,`*` 组也没封它 —— 属于"没表态",不算放行。
247
+ */
248
+ export function aiBotStatuses(text) {
249
+ const parsed = parseRobotsGroups(text);
250
+ const wildcard = parsed.groups.filter((group) => group.agents.includes('*'));
251
+ const rows = AI_BOTS.map((meta) => {
252
+ const agent = meta.bot.toLowerCase();
253
+ const explicitGroups = parsed.groups.filter((group) => group.agents.includes(agent));
254
+ const explicit = explicitGroups.length > 0;
255
+ const effective = explicit ? explicitGroups : wildcard;
256
+ const rules = effective.reduce((all, group) => all.concat(group.rules), []);
257
+ const wholeAllow = rules.some((rule) => rule.name === 'allow' && isWholeSiteRule(rule.value));
258
+ const wholeDisallow = rules.some((rule) => rule.name === 'disallow' && isWholeSiteRule(rule.value));
259
+ const blocked = wholeDisallow && !wholeAllow;
260
+ const status = blocked ? 'blocked' : explicit ? 'allowed' : 'unlisted';
261
+ return {
262
+ bot: meta.bot,
263
+ note: meta.note,
264
+ explicit,
265
+ status,
266
+ matched_by: explicit ? 'explicit' : wildcard.length ? 'wildcard' : 'none',
267
+ rules: rules.map((rule) => `${rule.name}: ${rule.value}`),
268
+ };
269
+ });
270
+ const counts = { allowed: 0, blocked: 0, unlisted: 0 };
271
+ for (const row of rows) counts[row.status] = (counts[row.status] || 0) + 1;
272
+ return { robots: { exists: String(text == null ? '' : text).trim().length > 0, groups: parsed.groups.length }, bots: rows, counts, issues: parsed.issues };
273
+ }
274
+
275
+ /* ================================================================== 小工具 */
276
+
277
+ function isExternalHref(href) {
278
+ return /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(String(href || ''));
279
+ }
280
+
281
+ /** 正文第一段(`<p>`) */
282
+ function firstParagraph(html) {
283
+ const src = String(html == null ? '' : html).replace(/<!--[\s\S]*?-->/g, ' ');
284
+ const m = src.match(/<p\b[^>]*>([\s\S]*?)<\/p>/i);
285
+ return m ? collapse(decodeEntities(stripTags(m[1]))) : '';
286
+ }
287
+
288
+ /** 把 JSON-LD 的 value 展平成条目数组(支持数组与 `@graph`) */
289
+ function jsonLdEntries(value, depth = 0) {
290
+ if (!value || depth > 4) return [];
291
+ if (Array.isArray(value)) return value.flatMap((one) => jsonLdEntries(one, depth + 1));
292
+ if (typeof value !== 'object') return [];
293
+ if (Array.isArray(value['@graph'])) return value['@graph'].flatMap((one) => jsonLdEntries(one, depth + 1));
294
+ return [value];
295
+ }
296
+
297
+ /** 取 `@type`(可能是字符串或字符串数组),统一小写 */
298
+ function jsonLdTypes(entry) {
299
+ const raw = entry && entry['@type'];
300
+ const list = Array.isArray(raw) ? raw : raw ? [raw] : [];
301
+ return list.map((one) => String(one || '').trim().toLowerCase()).filter(Boolean);
302
+ }
303
+
304
+ /** 必填字段是否齐(只看"有没有值",不做深层校验:不猜) */
305
+ function missingJsonLdFields(entry, type) {
306
+ const fields = JSONLD_REQUIRED[type] || [];
307
+ const missing = [];
308
+ for (const field of fields) {
309
+ const value = entry[field];
310
+ const ok =
311
+ value !== undefined &&
312
+ value !== null &&
313
+ !(typeof value === 'string' && !value.trim()) &&
314
+ !(Array.isArray(value) && !value.length);
315
+ if (!ok) missing.push(field);
316
+ }
317
+ return missing;
318
+ }
319
+
320
+ function addIssue(list, rule, severity, file, message, suggestion) {
321
+ list.push({ severity, file, rule, message, suggestion });
322
+ }
323
+
324
+ /** 简单按行 diff(多重集口径,不做 LCS):够看"这次会动哪几行" */
325
+ function lineDiff(before, after) {
326
+ const split = (text) => String(text == null ? '' : text).replace(/\r\n/g, '\n').split('\n');
327
+ const count = (lines) => {
328
+ const map = new Map();
329
+ for (const line of lines) map.set(line, (map.get(line) || 0) + 1);
330
+ return map;
331
+ };
332
+ const a = split(before);
333
+ const b = split(after);
334
+ const left = count(a);
335
+ for (const line of b) if (left.get(line)) left.set(line, left.get(line) - 1);
336
+ const right = count(b);
337
+ for (const line of a) if (right.get(line)) right.set(line, right.get(line) - 1);
338
+
339
+ const removed = [];
340
+ for (const [line, n] of left) for (let i = 0; i < n; i += 1) removed.push(line);
341
+ const added = [];
342
+ for (const [line, n] of right) for (let i = 0; i < n; i += 1) added.push(line);
343
+ return { added, removed };
344
+ }
345
+
346
+ /* ================================================================== 单页审计 */
347
+
348
+ /**
349
+ * 一页的 13 项检查(按页规则)。
350
+ * 返回 `{ failed:Set, skipped:Set, issues[] }`:`skipped` 的规则**不计入 total**
351
+ * (例如页面完全没有 JSON-LD 时,"必填字段"这一项没有可判的对象)。
352
+ */
353
+ export function auditGeoPage(dir, rel, html) {
354
+ const page = parsePageHtml(html);
355
+ const text = pageText(html);
356
+ const bodyChars = charCount(text);
357
+ const issues = [];
358
+ const failed = new Set();
359
+ const skipped = new Set();
360
+ const fail = (rule) => failed.add(rule);
361
+
362
+ /* ---- 语义结构:H1 唯一 ---- */
363
+ const h1s = page.headings.filter((h) => h.level === 1);
364
+ if (h1s.length === 1) {
365
+ /* ok */
366
+ } else if (h1s.length === 0) {
367
+ fail('h1_unique');
368
+ addIssue(issues, 'h1_unique', 'error', rel, '没有 H1', '每页放 1 个 H1,用一句话说清"这一页讲什么"(AI 摘取的锚点)');
369
+ } else {
370
+ fail('h1_unique');
371
+ addIssue(issues, 'h1_unique', 'error', rel, `H1 有 ${h1s.length} 个(应恰好 1 个)`, '只留 1 个 H1,其余降级为 H2/H3');
372
+ }
373
+
374
+ /* ---- 语义结构:层级不跳级 ---- */
375
+ let jump = null;
376
+ for (let i = 1; i < page.headings.length; i += 1) {
377
+ const prev = page.headings[i - 1].level;
378
+ const cur = page.headings[i].level;
379
+ if (cur - prev > 1) {
380
+ jump = { from: prev, to: cur, text: page.headings[i].text };
381
+ break;
382
+ }
383
+ }
384
+ if (jump) {
385
+ fail('heading_hierarchy');
386
+ addIssue(
387
+ issues,
388
+ 'heading_hierarchy',
389
+ 'warn',
390
+ rel,
391
+ `标题层级跳级:H${jump.from} → H${jump.to}(${jump.text || '无文字'})`,
392
+ '按 H1 → H2 → H3 逐级下降;跳级会让大纲解析断掉',
393
+ );
394
+ }
395
+
396
+ /* ---- 语义结构:FAQ / 问答区块 ---- */
397
+ const faqHit = FAQ_PATTERNS.find((re) => re.test(html));
398
+ if (!faqHit) {
399
+ fail('faq_block');
400
+ addIssue(
401
+ issues,
402
+ 'faq_block',
403
+ 'warn',
404
+ rel,
405
+ '没有 FAQ / 问答区块',
406
+ '加一段「常见问题」(`<details><summary>` 或 FAQPage + mainEntity),AI 最爱直接引用问答对',
407
+ );
408
+ }
409
+
410
+ /* ---- 语义结构:可摘取结构 ---- */
411
+ if (!EXTRACTABLE_RE.test(html)) {
412
+ fail('extractable');
413
+ addIssue(issues, 'extractable', 'warn', rel, '没有 ul / ol / table 等可摘取结构', '把要点写成列表或表格,比大段文字更容易被摘取');
414
+ }
415
+
416
+ /* ---- 可提取性:description 答案式 ---- */
417
+ const desc = page.description;
418
+ const descLen = charCount(desc);
419
+ if (!desc) {
420
+ fail('answer_description');
421
+ addIssue(issues, 'answer_description', 'error', rel, '缺 meta description', '写一句 40-160 字符的"答案式"摘要:这页解决什么问题');
422
+ } else if (descLen < DESC_MIN_CHARS) {
423
+ fail('answer_description');
424
+ addIssue(
425
+ issues,
426
+ 'answer_description',
427
+ 'warn',
428
+ rel,
429
+ `description 太短(${descLen} 字符 < ${DESC_MIN_CHARS})`,
430
+ '补到 40-160 字符,直接给结论而不是"关于我们"这类标签',
431
+ );
432
+ } else if (descLen > DESC_MAX_CHARS) {
433
+ fail('answer_description');
434
+ addIssue(issues, 'answer_description', 'warn', rel, `description 过长(${descLen} 字符 > ${DESC_MAX_CHARS})`, '压到 160 字符内');
435
+ } else if (FLUFF_START.test(desc) || FLUFF_ANY.test(desc)) {
436
+ fail('answer_description');
437
+ addIssue(issues, 'answer_description', 'warn', rel, 'description 是空话("欢迎访问 / 我们致力于…")', '换成可被直接引用的事实句');
438
+ }
439
+
440
+ /* ---- 可提取性:首段直接陈述主题 ---- */
441
+ const lead = firstParagraph(html);
442
+ if (!lead) {
443
+ fail('lead_paragraph');
444
+ addIssue(issues, 'lead_paragraph', 'warn', rel, '没有正文段落(`<p>`)', 'H1 后面紧跟一段 30 字符以上的事实性首段');
445
+ } else if (charCount(lead) < LEAD_MIN_CHARS) {
446
+ fail('lead_paragraph');
447
+ addIssue(issues, 'lead_paragraph', 'warn', rel, `首段太短(${charCount(lead)} 字符 < ${LEAD_MIN_CHARS})`, '首段补到 30 字符以上,直接说主题与结论');
448
+ } else if (FLUFF_START.test(lead) || FLUFF_ANY.test(lead)) {
449
+ fail('lead_paragraph');
450
+ addIssue(issues, 'lead_paragraph', 'warn', rel, '首段是套话("欢迎访问 / 我们致力于…")', '首段第一句就陈述事实与结论');
451
+ }
452
+
453
+ /* ---- 可提取性:正文长度 ---- */
454
+ if (bodyChars < BODY_WARN_CHARS) {
455
+ fail('body_length');
456
+ addIssue(issues, 'body_length', 'error', rel, `正文仅 ${bodyChars} 字符`, `补到 ${BODY_MIN_CHARS} 字符以上:AI 需要足够上下文才敢引用`);
457
+ } else if (bodyChars < BODY_MIN_CHARS) {
458
+ fail('body_length');
459
+ addIssue(issues, 'body_length', 'warn', rel, `正文偏短(${bodyChars} < ${BODY_MIN_CHARS} 字符)`, '补事实、数据、名词解释,把一页讲透');
460
+ }
461
+
462
+ /* ---- 实体标注:JSON-LD 必填字段 ---- */
463
+ const validEntries = page.jsonld.filter((one) => one.ok).flatMap((one) => jsonLdEntries(one.value));
464
+ const recognized = validEntries
465
+ .map((entry) => {
466
+ const types = jsonLdTypes(entry);
467
+ const key = types.find((type) => (ARTICLE_TYPES.has(type) ? 'article' : JSONLD_REQUIRED[type] !== undefined));
468
+ return key ? { entry, type: ARTICLE_TYPES.has(key) ? 'article' : key, rawType: types[0] || key } : null;
469
+ })
470
+ .filter(Boolean);
471
+ if (!recognized.length) {
472
+ skipped.add('jsonld_required');
473
+ if (!validEntries.length) {
474
+ addIssue(
475
+ issues,
476
+ 'jsonld_required',
477
+ 'warn',
478
+ rel,
479
+ '没有可解析的 JSON-LD',
480
+ '至少标一个 Organization(站点级)或 Article / FAQPage / BreadcrumbList(页面级)',
481
+ );
482
+ }
483
+ } else {
484
+ for (const one of recognized) {
485
+ const missing = missingJsonLdFields(one.entry, one.type);
486
+ if (!missing.length) continue;
487
+ fail('jsonld_required');
488
+ addIssue(
489
+ issues,
490
+ 'jsonld_required',
491
+ 'warn',
492
+ rel,
493
+ `JSON-LD ${one.rawType} 缺必填字段:${missing.join(' / ')}`,
494
+ '补齐这些字段;缺字段的 JSON-LD 会被校验器判无效,等于没标',
495
+ );
496
+ break;
497
+ }
498
+ }
499
+
500
+ /* ---- 其它:lang / canonical / og / img alt / 内链 ---- */
501
+ if (!page.lang) {
502
+ fail('html_lang');
503
+ addIssue(issues, 'html_lang', 'warn', rel, '缺 <html lang>', '写 `lang="zh-CN"`(多语言站点更要写),AI 靠它判断语种');
504
+ }
505
+
506
+ if (!page.canonical) {
507
+ fail('canonical');
508
+ addIssue(issues, 'canonical', 'warn', rel, '缺 canonical', '加 `<link rel="canonical" href="<绝对地址>">`,避免同文多处被当成重复');
509
+ }
510
+
511
+ const ogMissing = ['og:title', 'og:description', 'og:image'].filter((key) => !page.og[key]);
512
+ if (ogMissing.length) {
513
+ fail('og');
514
+ addIssue(issues, 'og', 'warn', rel, `og 不全:缺 ${ogMissing.join(' / ')}`, '补齐三条 og,社媒与 AI 预览都读它');
515
+ }
516
+
517
+ const noAlt = page.images.filter((img) => img.alt === null);
518
+ if (noAlt.length) {
519
+ fail('img_alt');
520
+ addIssue(issues, 'img_alt', 'warn', rel, `${noAlt.length} 张图没有 alt 属性`, '每张图给一句描述性 alt(装饰图给 alt="")');
521
+ }
522
+
523
+ const internal = new Set();
524
+ for (const href of page.links) {
525
+ const raw = String(href || '').trim();
526
+ if (!raw || raw.startsWith('#') || isExternalHref(raw)) continue;
527
+ internal.add(raw.split('#')[0].split('?')[0]);
528
+ }
529
+ if (internal.size < INTERNAL_LINKS_MIN) {
530
+ fail('internal_links');
531
+ addIssue(
532
+ issues,
533
+ 'internal_links',
534
+ internal.size === 0 ? 'error' : 'warn',
535
+ rel,
536
+ `内链只有 ${internal.size} 条(< ${INTERNAL_LINKS_MIN})`,
537
+ '相关页面互相链:AI 顺着链接判断"这页在站里有多重要"',
538
+ );
539
+ }
540
+
541
+ return { failed, skipped, issues, stats: { body_chars: bodyChars, description_chars: descLen, headings: page.headings.length, internal_links: internal.size } };
542
+ }
543
+
544
+ /* ================================================================== 站点级检查 */
545
+
546
+ /** llms.txt 的结构统计(小节 / 链接 / 一句话摘要) */
547
+ export function inspectLlmsText(text) {
548
+ const src = String(text == null ? '' : text);
549
+ const lines = src.split(/\r?\n/);
550
+ const sections = lines.filter((line) => /^##\s+\S/.test(line)).length;
551
+ const links = [];
552
+ for (const line of lines) {
553
+ const m = line.match(/^\s*[-*]\s*\[([^\]]+)\]\(([^)\s]+)\)(.*)$/);
554
+ if (m) links.push({ title: m[1].trim(), url: m[2].trim(), tail: m[3] || '' });
555
+ }
556
+ const summaries = links.filter((one) => /^[\s::-]+[^\s::-]/.test(one.tail)).length;
557
+ return {
558
+ exists: src.trim().length > 0,
559
+ chars: charCount(src),
560
+ lines: lines.length,
561
+ sections,
562
+ links: links.map((one) => one.url),
563
+ link_count: links.length,
564
+ summaries,
565
+ has_title: lines.some((line) => /^#\s+\S/.test(line)),
566
+ };
567
+ }
568
+
569
+ /**
570
+ * 站点级检查:AI 爬虫 / llms.txt / JSON-LD 覆盖 / 标题重复。
571
+ * 返回 `{ results:{ruleId:{passed,total}}, issues[], signals{} }`。
572
+ */
573
+ export function auditGeoFiles(dir) {
574
+ const absolute = path.resolve(String(dir || '.'));
575
+ const files = listHtmlFiles(absolute);
576
+ const issues = [];
577
+ const results = {};
578
+
579
+ const readIf = (rel) => {
580
+ try {
581
+ return fs.readFileSync(path.join(absolute, rel), 'utf8');
582
+ } catch {
583
+ return null;
584
+ }
585
+ };
586
+
587
+ /* ---- AI 爬虫策略 ---- */
588
+ const robotsText = readIf('robots.txt');
589
+ const botInfo = aiBotStatuses(robotsText === null ? '' : robotsText);
590
+ results.ai_bots_allow = { passed: botInfo.counts.allowed, total: AI_BOTS.length };
591
+ results.ai_bots_block = { passed: botInfo.counts.blocked === 0 ? 1 : 0, total: 1 };
592
+
593
+ if (robotsText === null) {
594
+ addIssue(
595
+ issues,
596
+ 'ai_bots_allow',
597
+ 'warn',
598
+ 'robots.txt',
599
+ '没有 robots.txt:AI 爬虫既没被放行也没被拒绝',
600
+ '跑 `wkgeo geo robots <目录> --mode allow-ai --confirm` 生成一段显式放行策略',
601
+ );
602
+ }
603
+ for (const row of botInfo.bots) {
604
+ if (row.status === 'blocked') {
605
+ addIssue(
606
+ issues,
607
+ 'ai_bots_block',
608
+ 'error',
609
+ 'robots.txt',
610
+ `${row.bot} 被整站封禁(Disallow: /)`,
611
+ `删掉该 UA 组的 \`Disallow: /\`;要屏蔽训练只封路径,别封全站`,
612
+ );
613
+ } else if (row.status === 'unlisted') {
614
+ addIssue(
615
+ issues,
616
+ 'ai_bots_allow',
617
+ 'warn',
618
+ 'robots.txt',
619
+ `${row.bot} 没有显式策略(${row.matched_by === 'wildcard' ? '只有 * 组' : '完全没有 UA 组'})`,
620
+ `加一组 \`User-agent: ${row.bot}\` + \`Allow: /\`,明确表态比"没表态"更容易被收录`,
621
+ );
622
+ }
623
+ }
624
+ for (const one of botInfo.issues) {
625
+ addIssue(issues, 'robots_syntax', one.severity, 'robots.txt', one.message, one.suggestion);
626
+ }
627
+
628
+ /* ---- llms.txt / llms-full.txt ---- */
629
+ const llmsText = readIf('llms.txt');
630
+ const llmsFullText = readIf('llms-full.txt');
631
+ const llmsInfo = inspectLlmsText(llmsText === null ? '' : llmsText);
632
+ results.llms_txt = { passed: llmsInfo.exists ? 1 : 0, total: 1 };
633
+ results.llms_full = { passed: llmsFullText !== null && llmsFullText.trim() ? 1 : 0, total: 1 };
634
+
635
+ const structureChecks = [
636
+ { key: 'sections', ok: llmsInfo.sections >= 1, message: 'llms.txt 没有 `##` 小节', suggestion: '按栏目分节(如 `## 主要页面` / `## 博客`),AI 靠小节理解站点结构' },
637
+ { key: 'links', ok: llmsInfo.link_count >= 1, message: 'llms.txt 里没有链接', suggestion: '每条写 `- [页面标题](URL):一句话摘要`' },
638
+ { key: 'summaries', ok: llmsInfo.summaries >= 1, message: 'llms.txt 的链接没有一句话摘要', suggestion: '链接后面用 `:` 跟一句摘要(≤120 字符)' },
639
+ ];
640
+ results.llms_structure = { passed: structureChecks.filter((one) => one.ok).length, total: structureChecks.length };
641
+ for (const one of structureChecks) {
642
+ if (one.ok) continue;
643
+ addIssue(issues, 'llms_structure', 'warn', 'llms.txt', one.message, one.suggestion);
644
+ }
645
+ if (!llmsInfo.exists) {
646
+ addIssue(issues, 'llms_txt', 'warn', 'llms.txt', '没有 llms.txt', '跑 `wkgeo geo llms <目录> --confirm` 生成(含分类小节与一句话摘要)');
647
+ }
648
+ if (!results.llms_full.passed) {
649
+ addIssue(issues, 'llms_full', 'info', 'llms-full.txt', '没有 llms-full.txt', '同一条命令会一起生成,正文全文交给 AI 做长文引用');
650
+ }
651
+
652
+ /* ---- JSON-LD 覆盖(站点级 4 个格子) ---- */
653
+ const typeHits = new Map();
654
+ let pagesWithJsonLd = 0;
655
+ const titles = new Map();
656
+ for (const rel of files) {
657
+ const html = readIf(rel);
658
+ if (html === null) continue;
659
+ const page = parsePageHtml(html);
660
+ if (!page.title) {
661
+ addIssue(issues, 'title_unique', 'info', rel, '页面没有 <title>', '补标题(会参与重复判定)');
662
+ } else {
663
+ const list = titles.get(page.title) || [];
664
+ list.push(rel);
665
+ titles.set(page.title, list);
666
+ }
667
+ const entries = page.jsonld.filter((one) => one.ok).flatMap((one) => jsonLdEntries(one.value));
668
+ if (entries.length) pagesWithJsonLd += 1;
669
+ for (const entry of entries) {
670
+ for (const type of jsonLdTypes(entry)) {
671
+ const bucket = ARTICLE_TYPES.has(type) ? 'article' : type;
672
+ typeHits.set(bucket, (typeHits.get(bucket) || 0) + 1);
673
+ }
674
+ }
675
+ }
676
+ const coverage = GEO_ENTITY_TYPES.map((type) => ({
677
+ type,
678
+ present: (typeHits.get(type.toLowerCase()) || 0) > 0,
679
+ count: typeHits.get(type.toLowerCase()) || 0,
680
+ }));
681
+ results.jsonld_types = { passed: coverage.filter((one) => one.present).length, total: GEO_ENTITY_TYPES.length };
682
+ for (const one of coverage) {
683
+ if (one.present) continue;
684
+ addIssue(
685
+ issues,
686
+ 'jsonld_types',
687
+ 'warn',
688
+ 'JSON-LD',
689
+ `全站没有 ${one.type} 标注`,
690
+ one.type === 'Organization'
691
+ ? '首页标 Organization(name / url / logo),AI 用来确认"这是谁"'
692
+ : `加一页带 ${one.type} 的 JSON-LD${one.type === 'Article' ? '(headline / datePublished / author)' : one.type === 'FAQPage' ? '(mainEntity 问答对)' : '(itemListElement 面包屑)'}`,
693
+ );
694
+ }
695
+
696
+ /* ---- title 重复 ---- */
697
+ const duplicates = [...titles.entries()].filter(([, list]) => list.length > 1);
698
+ results.title_unique = { passed: duplicates.length ? 0 : 1, total: 1 };
699
+ for (const [title, list] of duplicates) {
700
+ addIssue(issues, 'title_unique', 'warn', list.join(' / '), `title 重复(${list.length} 页):${clip(title, 60)}`, '每页一个独立标题,重复会让 AI 分不清哪页答哪个问题');
701
+ }
702
+
703
+ return {
704
+ results,
705
+ issues,
706
+ signals: {
707
+ robots: { exists: robotsText !== null, groups: botInfo.robots.groups },
708
+ ai_bots: botInfo.bots,
709
+ ai_bot_counts: botInfo.counts,
710
+ llms: {
711
+ exists: llmsInfo.exists,
712
+ sections: llmsInfo.sections,
713
+ link_count: llmsInfo.link_count,
714
+ summaries: llmsInfo.summaries,
715
+ full_exists: llmsFullText !== null,
716
+ },
717
+ jsonld: { pages_with_jsonld: pagesWithJsonLd, coverage },
718
+ pages: files.length,
719
+ },
720
+ };
721
+ }
722
+
723
+ /* ================================================================== 目录审计(评分) */
724
+
725
+ /**
726
+ * 审计整个目录:**20 项加权评分(合计 100)** + 全量 issues。
727
+ * 返回 `{ dir, pages, score, grade, rules[], issues[], summary, truncated, signals }`。
728
+ *
729
+ * 报告命令:**有问题也 exit 0**;只有"目录里没有 .html"才抛 `ENOPAGES`(exit 1)。
730
+ */
731
+ export function auditGeoDirectory(dir) {
732
+ const absolute = path.resolve(String(dir || '.'));
733
+ const files = listHtmlFiles(absolute);
734
+ if (!files.length) {
735
+ throw new CliError(`目录里没有 .html 文件:${absolute}`, {
736
+ kind: 'empty',
737
+ code: 'ENOPAGES',
738
+ hint: '确认这是站点产物目录(里面有 index.html 等页面)',
739
+ exitCode: 1,
740
+ });
741
+ }
742
+
743
+ const state = new Map(GEO_AUDIT_RULES.map((rule) => [rule.id, { ...rule, passed: 0, total: 0 }]));
744
+ const issues = [];
745
+ const pageStats = [];
746
+
747
+ for (const rel of files) {
748
+ let html = '';
749
+ try {
750
+ html = fs.readFileSync(path.join(absolute, rel), 'utf8');
751
+ } catch {
752
+ html = '';
753
+ }
754
+ const result = auditGeoPage(absolute, rel, html);
755
+ pageStats.push({ file: rel, ...result.stats });
756
+ for (const rule of state.values()) {
757
+ if (SITE_RULE_IDS.has(rule.id)) continue;
758
+ if (result.skipped.has(rule.id)) continue;
759
+ rule.total += 1;
760
+ if (!result.failed.has(rule.id)) rule.passed += 1;
761
+ }
762
+ issues.push(...result.issues);
763
+ }
764
+
765
+ const site = auditGeoFiles(absolute);
766
+ for (const id of SITE_RULE_IDS) {
767
+ const rule = state.get(id);
768
+ const hit = site.results[id] || { passed: 0, total: 1 };
769
+ rule.passed = Math.min(hit.passed, hit.total);
770
+ rule.total = hit.total;
771
+ }
772
+ issues.push(...site.issues);
773
+
774
+ const rules = [...state.values()].map((rule) => ({
775
+ id: rule.id,
776
+ title: rule.title,
777
+ weight: rule.weight,
778
+ total: rule.total,
779
+ passed: rule.passed,
780
+ score: rule.total ? Math.round((rule.weight * rule.passed) / rule.total) : 0,
781
+ }));
782
+
783
+ let score = Math.round(rules.reduce((sum, rule) => sum + (rule.total ? (rule.weight * rule.passed) / rule.total : 0), 0));
784
+ score = Math.max(0, Math.min(100, score));
785
+
786
+ const severityRank = { error: 0, warn: 1, info: 2 };
787
+ issues.sort(
788
+ (a, b) =>
789
+ (severityRank[a.severity] ?? 9) - (severityRank[b.severity] ?? 9) ||
790
+ String(a.file).localeCompare(String(b.file)) ||
791
+ String(a.rule).localeCompare(String(b.rule)),
792
+ );
793
+ const truncated = issues.length > MAX_ISSUES;
794
+ const shown = truncated ? issues.slice(0, MAX_ISSUES) : issues;
795
+
796
+ const summary = { error: 0, warn: 0, info: 0, total: issues.length };
797
+ for (const one of issues) summary[one.severity] = (summary[one.severity] || 0) + 1;
798
+
799
+ return {
800
+ dir: absolute,
801
+ pages: files.length,
802
+ score,
803
+ grade: gradeOf(score),
804
+ rules,
805
+ issues: shown,
806
+ summary,
807
+ truncated,
808
+ signals: site.signals,
809
+ page_stats: pageStats,
810
+ };
811
+ }
812
+
813
+ /* ================================================================== llms.txt 生成 / 校验 */
814
+
815
+ /** 页面所属分类(一级目录名;根目录归到「主要页面」) */
816
+ function categoryOf(rel) {
817
+ const norm = String(rel || '').replace(/\\/g, '/');
818
+ const parts = norm.split('/');
819
+ if (parts.length <= 1) return '主要页面';
820
+ return parts[0] || '主要页面';
821
+ }
822
+
823
+ /**
824
+ * 生成 llms.txt / llms-full.txt 的**内容**(不写盘,写盘由命令层按 `--confirm` 决定)。
825
+ *
826
+ * llms.txt:`# 站点标题` / `> 站点描述` / 按**分类小节**(一级目录,根页面归「主要页面」)列
827
+ * `- [标题](URL):一句话摘要`(摘要取 description,没有就取正文第一段,≤120 字符)。
828
+ * llms-full.txt:站点头 + 每页 `## 标题` / `URL:` / 正文纯文本摘录(每页 ≤3000 字符)。
829
+ *
830
+ * 标题 / 描述 / 摘要都从页面与站点清单里取,**取不到就留空,不编造**。
831
+ */
832
+ export function buildGeoLlms(dir, { baseUrl = '' } = {}) {
833
+ const absolute = path.resolve(String(dir || '.'));
834
+ const files = listHtmlFiles(absolute);
835
+ if (!files.length) {
836
+ throw new CliError(`目录里没有 .html 文件:${absolute}`, {
837
+ kind: 'empty',
838
+ code: 'ENOPAGES',
839
+ hint: '确认这是站点产物目录(里面有 index.html 等页面)',
840
+ exitCode: 1,
841
+ });
842
+ }
843
+ const meta = readSiteMeta(absolute);
844
+ const base = String(baseUrl || '').replace(/\/+$/, '');
845
+ const withBase = (url) => (base ? `${base}${url}` : url);
846
+
847
+ const pages = files.map((rel) => {
848
+ let html = '';
849
+ try {
850
+ html = fs.readFileSync(path.join(absolute, rel), 'utf8');
851
+ } catch {
852
+ html = '';
853
+ }
854
+ const parsed = parsePageHtml(html);
855
+ return {
856
+ file: rel,
857
+ url: pageUrl(rel),
858
+ title: parsed.title || path.basename(rel, path.extname(rel)),
859
+ summary: clip(parsed.description || firstParagraph(html) || '', LLMS_SUMMARY_CHARS),
860
+ text: clip(pageText(html), LLMS_FULL_PAGE_CHARS),
861
+ category: categoryOf(rel),
862
+ };
863
+ });
864
+
865
+ const title = meta.name || path.basename(absolute);
866
+ const lines = [`# ${title}`];
867
+ if (meta.description) lines.push('', `> ${meta.description}`);
868
+ lines.push('', '> 站点页面索引与一句话摘要(按栏目分节);每页正文纯文本见 llms-full.txt。');
869
+
870
+ const categories = [...new Set(pages.map((one) => one.category))];
871
+ for (const category of categories) {
872
+ const subset = pages.filter((one) => one.category === category);
873
+ lines.push('', `## ${category}`);
874
+ for (const one of subset) {
875
+ const link = `[${one.title}](${withBase(one.url)})`;
876
+ lines.push(one.summary ? `- ${link}:${one.summary}` : `- ${link}`);
877
+ }
878
+ }
879
+
880
+ const full = [`# ${title}`];
881
+ if (meta.description) full.push('', `> ${meta.description}`);
882
+ for (const one of pages) {
883
+ full.push('', '---', '', `## ${one.title}`, '', `URL: ${withBase(one.url)}`);
884
+ if (one.text) full.push('', one.text);
885
+ }
886
+
887
+ const llmsTxt = `${lines.join('\n').replace(/\n{3,}/g, '\n\n').trim()}\n`;
888
+ const llmsFull = `${full.join('\n').replace(/\n{3,}/g, '\n\n').trim()}\n`;
889
+
890
+ return {
891
+ dir: absolute,
892
+ base_url: base,
893
+ site: { name: title, description: meta.description, url: meta.url, lang: meta.lang, manifest: meta.manifest.file },
894
+ notes: meta.notes,
895
+ pages,
896
+ categories,
897
+ llms_txt: { path: path.join(absolute, 'llms.txt'), chars: charCount(llmsTxt), content: llmsTxt },
898
+ llms_full: { path: path.join(absolute, 'llms-full.txt'), chars: charCount(llmsFull), content: llmsFull },
899
+ };
900
+ }
901
+
902
+ /**
903
+ * `--check`:**只校验不写盘**。
904
+ *
905
+ * 判定:llms.txt 必须存在、有小节、有链接、有摘要、覆盖所有主要页面(一级 + 二级页面);
906
+ * llms-full.txt 缺失只记 warn。`ok = 没有任何 error`(有 error 时命令层 exit 1)。
907
+ */
908
+ export function checkGeoLlms(dir, { baseUrl = '' } = {}) {
909
+ const absolute = path.resolve(String(dir || '.'));
910
+ const files = listHtmlFiles(absolute);
911
+ if (!files.length) {
912
+ throw new CliError(`目录里没有 .html 文件:${absolute}`, {
913
+ kind: 'empty',
914
+ code: 'ENOPAGES',
915
+ hint: '确认这是站点产物目录(里面有 index.html 等页面)',
916
+ exitCode: 1,
917
+ });
918
+ }
919
+ const issues = [];
920
+ const readIf = (rel) => {
921
+ try {
922
+ return fs.readFileSync(path.join(absolute, rel), 'utf8');
923
+ } catch {
924
+ return null;
925
+ }
926
+ };
927
+
928
+ const text = readIf('llms.txt');
929
+ const info = inspectLlmsText(text === null ? '' : text);
930
+ if (text === null || !info.exists) {
931
+ addIssue(issues, 'llms_missing', 'error', 'llms.txt', '没有 llms.txt', '先跑 `wkgeo geo llms <目录> --confirm` 生成,再回来 `--check`');
932
+ } else {
933
+ if (!info.has_title) addIssue(issues, 'llms_title', 'warn', 'llms.txt', 'llms.txt 没有 `# 站点标题`', '第一行写 `# <站点名>`');
934
+ if (!info.sections) addIssue(issues, 'llms_sections', 'error', 'llms.txt', 'llms.txt 没有 `##` 分类小节', '按栏目分节,AI 靠小节理解站点结构');
935
+ if (!info.link_count) addIssue(issues, 'llms_links', 'error', 'llms.txt', 'llms.txt 没有页面链接', '每条写成 `- [标题](URL):摘要`');
936
+ if (text !== null && info.link_count && !info.summaries) {
937
+ addIssue(issues, 'llms_summaries', 'warn', 'llms.txt', '链接都没有一句话摘要', '在链接后用 `:` 跟一句 ≤120 字符的摘要');
938
+ }
939
+ }
940
+
941
+ const base = String(baseUrl || '').replace(/\/+$/, '');
942
+ const targets = new Set(info.links.map((url) => String(url).replace(/^https?:\/\/[^/]+/i, '').replace(/\/$/, '/') || '/'));
943
+ const missing = [];
944
+ for (const rel of files) {
945
+ const url = pageUrl(rel);
946
+ const norm = url.replace(/\/$/, '/') || '/';
947
+ const hit = targets.has(norm) || targets.has(url) || (base && info.links.includes(`${base}${url}`));
948
+ if (!hit) missing.push(url);
949
+ }
950
+ if (info.link_count && missing.length) {
951
+ addIssue(
952
+ issues,
953
+ 'llms_coverage',
954
+ 'warn',
955
+ 'llms.txt',
956
+ `${missing.length} 个页面没进 llms.txt:${missing.slice(0, 8).join(' / ')}${missing.length > 8 ? ' …' : ''}`,
957
+ '重跑 `wkgeo geo llms <目录> --confirm`(幂等覆盖写)',
958
+ );
959
+ }
960
+
961
+ const fullText = readIf('llms-full.txt');
962
+ if (fullText === null || !fullText.trim()) {
963
+ addIssue(issues, 'llms_full_missing', 'warn', 'llms-full.txt', '没有 llms-full.txt', '同一条 `wkgeo geo llms` 命令会一起生成');
964
+ }
965
+
966
+ const summary = { error: 0, warn: 0, info: 0, total: issues.length };
967
+ for (const one of issues) summary[one.severity] = (summary[one.severity] || 0) + 1;
968
+
969
+ return {
970
+ dir: absolute,
971
+ ok: summary.error === 0,
972
+ llms_txt: { path: path.join(absolute, 'llms.txt'), exists: text !== null && info.exists, ...info },
973
+ llms_full: { path: path.join(absolute, 'llms-full.txt'), exists: fullText !== null && Boolean(fullText.trim()) },
974
+ pages: files.length,
975
+ missing_pages: missing,
976
+ issues,
977
+ summary,
978
+ };
979
+ }
980
+
981
+ /* ================================================================== robots.txt 策略段 */
982
+
983
+ /** 生成托管块(`allow-ai` / `block-ai`) */
984
+ function robotsBlock(mode) {
985
+ const action = mode === 'block-ai' ? 'Disallow' : 'Allow';
986
+ const lines = [
987
+ ROBOTS_BEGIN,
988
+ `# AI 爬虫策略(wkgeo geo robots --mode ${mode} 生成;重跑整段替换,手改请写在本段之外)`,
989
+ ];
990
+ AI_BOTS.forEach((one, index) => {
991
+ if (index > 0) lines.push('');
992
+ lines.push(`User-agent: ${one.bot}`, `${action}: /`);
993
+ });
994
+ lines.push(ROBOTS_END);
995
+ return lines.join('\n');
996
+ }
997
+
998
+ /**
999
+ * 规划 robots.txt 的改动(**纯函数,不写盘**)。
1000
+ *
1001
+ * 幂等:已存在托管块 ⇒ 整段替换(切 allow ⇄ block 也走这条);不存在 ⇒ 追加在文件末尾,
1002
+ * **原有手工规则(User-agent: * / Disallow: /cms/ / Sitemap: …)一个字节都不动**。
1003
+ *
1004
+ * 返回 `{ mode, before, after, action:'created'|'updated'|'unchanged'|'none', added[], removed[] , bots[] }`。
1005
+ */
1006
+ export function planGeoRobots({ text = '', mode }) {
1007
+ const src = String(text == null ? '' : text);
1008
+ if (!GEO_ROBOTS_MODES.includes(mode)) {
1009
+ throw new UsageError(`--mode 只能是 ${GEO_ROBOTS_MODES.join(' | ')}(收到:${mode || '(空)'})`);
1010
+ }
1011
+ if (mode === 'show') {
1012
+ return { mode, before: src, after: src, action: 'none', added: [], removed: [], diff: { added: [], removed: [] } };
1013
+ }
1014
+
1015
+ const block = robotsBlock(mode);
1016
+ const hasBlock = src.includes(ROBOTS_BEGIN) && src.includes(ROBOTS_END);
1017
+ let after;
1018
+ let action;
1019
+ if (hasBlock) {
1020
+ const begin = src.indexOf(ROBOTS_BEGIN);
1021
+ const end = src.indexOf(ROBOTS_END, begin);
1022
+ after = `${src.slice(0, begin)}${block}${src.slice(end + ROBOTS_END.length)}`;
1023
+ action = after === src ? 'unchanged' : 'updated';
1024
+ } else {
1025
+ const trimmed = src.replace(/\s+$/, '');
1026
+ after = trimmed ? `${trimmed}\n\n${block}\n` : `${block}\n`;
1027
+ action = 'created';
1028
+ }
1029
+ const diff = lineDiff(src, after);
1030
+ return { mode, before: src, after, action, added: diff.added, removed: diff.removed, diff, bots: AI_BOTS.map((one) => one.bot) };
1031
+ }
1032
+
1033
+ /** `--mode show` 的人类视图:当前 AI 相关规则(按分组给,带行号) */
1034
+ export function showGeoRobots(text) {
1035
+ const botInfo = aiBotStatuses(text);
1036
+ const parsed = parseRobotsGroups(text);
1037
+ const managed = String(text || '').includes(ROBOTS_BEGIN);
1038
+ const rules = [];
1039
+ for (const group of parsed.groups) {
1040
+ for (const agent of group.agents) {
1041
+ if (agent !== '*' && !AI_BOTS.some((one) => one.bot.toLowerCase() === agent)) continue;
1042
+ for (const rule of group.rules) rules.push({ user_agent: agent, rule: `${rule.name}: ${rule.value}` });
1043
+ }
1044
+ }
1045
+ return {
1046
+ exists: String(text == null ? '' : text).trim().length > 0,
1047
+ managed_block: managed,
1048
+ groups: parsed.groups.length,
1049
+ ai_rules: rules,
1050
+ bots: botInfo.bots,
1051
+ counts: botInfo.counts,
1052
+ };
1053
+ }
1054
+
1055
+ /* ================================================================== 品牌跟踪(后台 API) */
1056
+
1057
+ /** 读 `WKGEO_GEO_API`(**只读基址,不读任何密钥**) */
1058
+ export function brandsConfig(env = {}) {
1059
+ const base = String((env && env.WKGEO_GEO_API) || '').trim().replace(/\/+$/, '');
1060
+ return { configured: Boolean(base), base };
1061
+ }
1062
+
1063
+ /** 未配置态的返回体:`not_configured` + 契约(**不发任何请求**) */
1064
+ export function brandsNotConfigured() {
1065
+ return {
1066
+ status: 'not_configured',
1067
+ configured: false,
1068
+ brands: [],
1069
+ platforms: 0,
1070
+ contract: GEO_BRANDS_CONTRACT,
1071
+ setup: 'export WKGEO_GEO_API=<后台基址>(不给就不发请求)',
1072
+ notes: [
1073
+ '品牌跟踪的后台 API 尚未就绪:**未配置 `WKGEO_GEO_API` 时本命令不发任何网络请求、不假装有数据**。',
1074
+ '契约(base = `WKGEO_GEO_API`):`GET <base>/api/geo/brands?domain=<域>&lang=<语言>`。',
1075
+ '响应:`{brands:[{name, platforms:[{platform, status:"none|listed|top|cited", rank, citations, url, checkedAt}]}]}`。',
1076
+ 'CLI 里**不硬编码任何 URL / 密钥**;基址只从环境变量来,输出里也不打印基址。',
1077
+ ],
1078
+ };
1079
+ }
1080
+
1081
+ /** 校验 + 归一化响应(不合法就抛,不"尽力而为"造数据) */
1082
+ export function normalizeBrands(payload) {
1083
+ const list = payload && Array.isArray(payload.brands) ? payload.brands : null;
1084
+ if (!list) {
1085
+ throw new CliError('品牌接口返回的不是 {brands:[…]} 形状', {
1086
+ kind: 'validate',
1087
+ code: 'EGEOBRANDSHAPE',
1088
+ exitCode: 1,
1089
+ hint: '按契约 `{brands:[{name, platforms:[{platform,status,…}]}]}` 返回;类型不对时 CLI 不猜',
1090
+ });
1091
+ }
1092
+ const brands = [];
1093
+ let platforms = 0;
1094
+ let dropped = 0;
1095
+ for (const raw of list) {
1096
+ if (!raw || typeof raw !== 'object') {
1097
+ dropped += 1;
1098
+ continue;
1099
+ }
1100
+ const name = typeof raw.name === 'string' ? raw.name.trim() : '';
1101
+ if (!name) {
1102
+ dropped += 1;
1103
+ continue;
1104
+ }
1105
+ const rows = [];
1106
+ for (const item of Array.isArray(raw.platforms) ? raw.platforms : []) {
1107
+ if (!item || typeof item !== 'object') {
1108
+ dropped += 1;
1109
+ continue;
1110
+ }
1111
+ const platform = typeof item.platform === 'string' ? item.platform.trim() : '';
1112
+ const status = typeof item.status === 'string' ? item.status.trim().toLowerCase() : '';
1113
+ if (!platform || !BRAND_STATUSES.includes(status)) {
1114
+ dropped += 1;
1115
+ continue;
1116
+ }
1117
+ rows.push({
1118
+ platform,
1119
+ status,
1120
+ rank: Number.isFinite(item.rank) ? item.rank : null,
1121
+ citations: Number.isFinite(item.citations) ? item.citations : null,
1122
+ url: typeof item.url === 'string' ? item.url : '',
1123
+ checkedAt: typeof item.checkedAt === 'string' ? item.checkedAt : '',
1124
+ });
1125
+ }
1126
+ platforms += rows.length;
1127
+ brands.push({ name, platforms: rows });
1128
+ }
1129
+ const statusCounts = { none: 0, listed: 0, top: 0, cited: 0 };
1130
+ for (const brand of brands) for (const row of brand.platforms) statusCounts[row.status] += 1;
1131
+ return { brands, platforms, status_counts: statusCounts, dropped };
1132
+ }
1133
+
1134
+ /**
1135
+ * 调后台品牌接口(**唯一允许联网的地方**)。
1136
+ *
1137
+ * 基址只从 `WKGEO_GEO_API` 来(调用方传入),路径固定为契约里的 `/api/geo/brands`;
1138
+ * 输出里不带基址 / 任何凭据。
1139
+ */
1140
+ export async function fetchGeoBrands({ base, domain, lang = 'zh-CN', fetchImpl, timeoutMs = 15000 }) {
1141
+ const root = String(base || '').trim().replace(/\/+$/, '');
1142
+ if (!/^https?:\/\//i.test(root)) {
1143
+ throw new CliError('WKGEO_GEO_API 不是 http(s) 基址', {
1144
+ kind: 'config',
1145
+ code: 'EGEOBASECONFIG',
1146
+ exitCode: 2,
1147
+ hint: '形如 `WKGEO_GEO_API=https://<后台域名>`(不带 /api 后缀);不配置就不发请求',
1148
+ });
1149
+ }
1150
+ const url = `${root}/api/geo/brands?domain=${encodeURIComponent(String(domain || '').trim())}&lang=${encodeURIComponent(String(lang || 'zh-CN').trim())}`;
1151
+ let res;
1152
+ try {
1153
+ res = await fetchImpl(url, { method: 'GET', headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) });
1154
+ } catch (e) {
1155
+ throw new CliError(`品牌接口请求失败:${String((e && e.message) || e)}`, {
1156
+ kind: 'network',
1157
+ code: 'EGEOBRANDSNET',
1158
+ exitCode: 1,
1159
+ hint: '确认 WKGEO_GEO_API 指向的后台可达;CLI 不重试、不换地址',
1160
+ });
1161
+ }
1162
+ const text = typeof res.text === 'function' ? await res.text() : '';
1163
+ if (res.status !== 200) {
1164
+ throw new CliError(`品牌接口返回 HTTP ${res.status}`, {
1165
+ kind: 'http',
1166
+ code: 'EGEOBRANDSHTTP',
1167
+ exitCode: 1,
1168
+ hint: '看后台日志;CLI 只报状态码,不回显响应体(可能含内部信息)',
1169
+ });
1170
+ }
1171
+ let payload;
1172
+ try {
1173
+ payload = JSON.parse(text);
1174
+ } catch (e) {
1175
+ throw new CliError('品牌接口返回的不是合法 JSON', {
1176
+ kind: 'validate',
1177
+ code: 'EGEOBRANDSJSON',
1178
+ exitCode: 1,
1179
+ hint: String((e && e.message) || e),
1180
+ });
1181
+ }
1182
+ const data = normalizeBrands(payload);
1183
+ return { status: 'ok', configured: true, endpoint_path: GEO_BRANDS_CONTRACT.request.path, domain, lang, ...data };
1184
+ }
1185
+
1186
+ /* ================================================================== 报告(markdown) */
1187
+
1188
+ /** 把 audit(可选 brands)渲染成 markdown 报告 */
1189
+ export function buildGeoReport({ audit, brands, generatedAt = new Date().toISOString() }) {
1190
+ const lines = [`# GEO 报告 · ${path.basename(audit.dir) || audit.dir}`];
1191
+ lines.push('', `> 生成时间:${generatedAt} · 页面 ${audit.pages} 个 · 得分 **${audit.score}/100**(${audit.grade})`);
1192
+ lines.push(
1193
+ '',
1194
+ `> error ${audit.summary.error} / warn ${audit.summary.warn} / info ${audit.summary.info} · 目录:\`${audit.dir}\``,
1195
+ );
1196
+
1197
+ lines.push('', '## 逐项得分', '', '| 规则 | 得分 | 权重 | 通过 |', '| --- | --- | --- | --- |');
1198
+ for (const rule of audit.rules) {
1199
+ lines.push(`| ${rule.id} ${rule.title} | ${rule.score} | ${rule.weight} | ${rule.passed}/${rule.total} |`);
1200
+ }
1201
+
1202
+ const shown = audit.issues.slice(0, 20);
1203
+ lines.push('', `## 问题(共 ${audit.issues.length} 条${audit.truncated ? ',已截断' : ''})`);
1204
+ if (!shown.length) lines.push('', '无。');
1205
+ for (const issue of shown) {
1206
+ lines.push('', `- **${issue.severity}** \`${issue.file}\` · ${issue.rule} · ${issue.message}`, ` - 建议:${issue.suggestion}`);
1207
+ }
1208
+ if (audit.issues.length > shown.length) lines.push('', `… 其余 ${audit.issues.length - shown.length} 条见 \`--json\`。`);
1209
+
1210
+ lines.push('', '## AI 爬虫', '', '| 爬虫 | 显式策略 | 状态 |', '| --- | --- | --- |');
1211
+ for (const row of audit.signals.ai_bots) {
1212
+ lines.push(`| ${row.bot} | ${row.explicit ? '有专属 UA 组' : row.matched_by === 'wildcard' ? '只有 * 组' : '没有'} | ${row.status} |`);
1213
+ }
1214
+
1215
+ lines.push(
1216
+ '',
1217
+ '## llms.txt',
1218
+ '',
1219
+ `- llms.txt:${audit.signals.llms.exists ? `存在(小节 ${audit.signals.llms.sections} · 链接 ${audit.signals.llms.link_count} · 摘要 ${audit.signals.llms.summaries})` : '缺失'}`,
1220
+ `- llms-full.txt:${audit.signals.llms.full_exists ? '存在' : '缺失'}`,
1221
+ );
1222
+
1223
+ lines.push('', '## 品牌跟踪', '');
1224
+ if (!brands || brands.status === 'skipped' || brands.status === 'not_configured') {
1225
+ lines.push(
1226
+ '- 状态:`skipped`(未配置 `WKGEO_GEO_API`,本次没有发任何请求)',
1227
+ '- 契约:`GET <base>/api/geo/brands?domain=<域>&lang=<语言>` → `{brands:[{name, platforms:[{platform,status,rank,citations,url,checkedAt}]}]}`',
1228
+ );
1229
+ } else {
1230
+ lines.push(`- 状态:\`${brands.status}\` · 品牌 ${brands.brands.length} 个 · 平台记录 ${brands.platforms} 条`);
1231
+ for (const brand of brands.brands) {
1232
+ const cells = brand.platforms.map((row) => `${row.platform}=${row.status}${row.rank === null ? '' : `#${row.rank}`}`);
1233
+ lines.push(`- ${brand.name}:${cells.length ? cells.join(' · ') : '(无平台记录)'}`);
1234
+ }
1235
+ }
1236
+
1237
+ return `${lines.join('\n')}\n`;
1238
+ }
1239
+
1240
+ /* ================================================================== 写盘 / 参数 */
1241
+
1242
+ /** 写文本文件(自动建父目录);返回 `{ path, bytes, chars }` */
1243
+ function writeTextFile(file, content) {
1244
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1245
+ fs.writeFileSync(file, content, 'utf8');
1246
+ return { path: file, bytes: Buffer.byteLength(content, 'utf8'), chars: charCount(content) };
1247
+ }
1248
+
1249
+ /** 位置参数 `<目录>` → 绝对路径(不存在 / 不是目录直接 usage 错,exit 2) */
1250
+ function resolveDirArg(raw) {
1251
+ const dir = path.resolve(process.cwd(), String(raw || '.'));
1252
+ let stat = null;
1253
+ try {
1254
+ stat = fs.statSync(dir);
1255
+ } catch {
1256
+ stat = null;
1257
+ }
1258
+ if (!stat) throw new UsageError(`目录不存在:${dir}`);
1259
+ if (!stat.isDirectory()) throw new UsageError(`不是目录:${dir}`);
1260
+ return dir;
1261
+ }
1262
+
1263
+ function readTextIf(file) {
1264
+ try {
1265
+ return fs.readFileSync(file, 'utf8');
1266
+ } catch {
1267
+ return null;
1268
+ }
1269
+ }
1270
+
1271
+ /* ================================================================== geo audit */
1272
+
1273
+ export const geoAuditCommand = {
1274
+ name: 'geo audit',
1275
+ summary: '本地站点产物 GEO 体检:20 项加权评分(0-100)+ issues[](error/warn/info)+ 等级,只读',
1276
+ usage: 'wkgeo geo audit <目录> [--json]',
1277
+ args: [{ name: 'dir', required: true, desc: '站点产物目录(含 index.html 等静态页面)' }],
1278
+ flags: {},
1279
+ examples: ['wkgeo geo audit .tmp-build/seo-fixture', 'wkgeo geo audit ./dist --json'],
1280
+ notes: [
1281
+ '**20 项(权重合计 100)**:AI 爬虫 16(显式放行 10 / 无整站封禁 6)· llms 16(存在 6 / 结构 6 / full 4)· 语义结构 24(H1 唯一 8 / 层级 5 / FAQ 6 / 可摘取 5)· 可提取性 15(答案式 description 6 / 首段 5 / 正文长度 4)· 实体标注 14(类型覆盖 8 / 必填字段 6)· 其它 15(title 去重 4 / lang 2 / canonical 2 / og 2 / img alt 2 / 内链 3)。',
1282
+ '站点级 5 项(AI 爬虫 / llms / JSON-LD 覆盖 / title 去重)整目录只算一次;其余按页取「通过页数 / 总页数」。',
1283
+ '**报告命令**:有问题也 exit 0(看 `data.score` / `data.summary` / `data.issues`);只有目录不存在(exit 2)或目录里没有 .html(exit 1)才非 0。',
1284
+ '只读:不联网、不写任何文件(要补文件用 `geo llms` / `geo robots`,要出报告用 `geo report`)。',
1285
+ ],
1286
+ async run(ctx) {
1287
+ const { out } = ctx;
1288
+ const dir = resolveDirArg(ctx.positional.dir);
1289
+ const result = auditGeoDirectory(dir);
1290
+ if (!out.json) {
1291
+ out.head(`GEO 审计 ${result.dir}`);
1292
+ out.line(
1293
+ ` 页面 ${result.pages} 个 · 得分 ${result.score}/100(${result.grade}) · error ${result.summary.error} / warn ${result.summary.warn} / info ${result.summary.info}`,
1294
+ );
1295
+ out.line('');
1296
+ out.line(' 逐项:');
1297
+ for (const rule of result.rules) {
1298
+ const mark = rule.total === 0 ? '·' : rule.passed === rule.total ? '✓' : '✗';
1299
+ out.line(
1300
+ ` ${mark} ${rule.id.padEnd(19)} ${String(rule.score).padStart(3)}/${String(rule.weight).padStart(3)} ${rule.title}(${rule.passed}/${rule.total})`,
1301
+ );
1302
+ }
1303
+ out.line('');
1304
+ out.line(' AI 爬虫:');
1305
+ for (const row of result.signals.ai_bots) {
1306
+ out.line(` ${row.status === 'allowed' ? '✓' : row.status === 'blocked' ? '✗' : '·'} ${row.bot.padEnd(16)} ${row.status}${row.explicit ? '' : '(无专属 UA 组)'}`);
1307
+ }
1308
+ if (result.issues.length) {
1309
+ out.line('');
1310
+ out.line(' 问题:');
1311
+ for (const issue of result.issues.slice(0, 30)) {
1312
+ out.line(` [${issue.severity}] ${issue.file} ${issue.rule} ${issue.message}`);
1313
+ out.line(` ↳ ${issue.suggestion}`);
1314
+ }
1315
+ if (result.issues.length > 30) out.line(` … 还有 ${result.issues.length - 30} 条(--json 看全量)`);
1316
+ }
1317
+ }
1318
+ if (!out.json) out.ok(`GEO 审计完成:${result.score} 分(${result.grade})· ${result.summary.total} 条问题`);
1319
+ ctx.done(result);
1320
+ },
1321
+ };
1322
+
1323
+ /* ================================================================== geo llms */
1324
+
1325
+ export const geoLlmsCommand = {
1326
+ name: 'geo llms',
1327
+ summary: '按目录生成 llms.txt(分类小节 + 一句话摘要 + 链接)与 llms-full.txt(正文全文),--check 只校验',
1328
+ usage: 'wkgeo geo llms <目录> [--check] [--base-url <站点基址>] [--confirm] [--json]',
1329
+ args: [{ name: 'dir', required: true, desc: '站点产物目录(默认写到 <目录>/llms.txt 与 <目录>/llms-full.txt)' }],
1330
+ flags: {
1331
+ check: { type: 'boolean', desc: '只校验现有的 llms.txt / llms-full.txt,不写盘' },
1332
+ 'base-url': { type: 'string', desc: '生成绝对链接的站点基址(如 https://www.example.com;不给就写相对路径)' },
1333
+ confirm: { type: 'boolean', desc: '真的写盘(不加就是 dry-run,只打印)' },
1334
+ },
1335
+ examples: [
1336
+ 'wkgeo geo llms .tmp-build/seo-fixture',
1337
+ 'wkgeo geo llms .tmp-build/seo-fixture --check',
1338
+ 'wkgeo geo llms ./dist --base-url https://www.example.com --confirm',
1339
+ ],
1340
+ notes: [
1341
+ '**默认 dry-run**:把两份文件内容打印出来,一个字节都不写;要写必须显式 `--confirm`。',
1342
+ 'llms.txt:`# 站点标题` + `> 站点描述` + **按栏目分节**(一级目录,根页面归「主要页面」)的 `- [标题](URL):一句话摘要`;摘要取 meta description,没有就取正文第一段(≤120 字符)。',
1343
+ 'llms-full.txt:站点头 + 每页 `## 标题` / `URL:` / 正文纯文本(每页 ≤3000 字符)。',
1344
+ '**`--check` 是门禁**:llms.txt 缺失 / 没有小节 / 没有链接 ⇒ exit 1(明细在 `error.details`);缺 llms-full.txt、页面没覆盖到只是 warn。',
1345
+ '标题 / 描述 / 摘要全从页面与站点清单里取,取不到就留空,**不编造**。',
1346
+ ],
1347
+ async run(ctx) {
1348
+ const { out, flags } = ctx;
1349
+ const dir = resolveDirArg(ctx.positional.dir);
1350
+
1351
+ if (flags.check === true) {
1352
+ const result = checkGeoLlms(dir, { baseUrl: flags.baseUrl || '' });
1353
+ if (!out.json) {
1354
+ out.head(`llms.txt 校验 ${result.dir}`);
1355
+ out.line(
1356
+ ` llms.txt:${result.llms_txt.exists ? `存在(小节 ${result.llms_txt.sections} · 链接 ${result.llms_txt.link_count} · 摘要 ${result.llms_txt.summaries})` : '缺失'} · llms-full.txt:${result.llms_full.exists ? '存在' : '缺失'} · 页面 ${result.pages}`,
1357
+ );
1358
+ if (result.issues.length) {
1359
+ out.line('');
1360
+ out.line(' 问题:');
1361
+ for (const issue of result.issues) {
1362
+ out.line(` [${issue.severity}] ${issue.file} ${issue.rule} ${issue.message}`);
1363
+ out.line(` ↳ ${issue.suggestion}`);
1364
+ }
1365
+ }
1366
+ }
1367
+ if (!result.ok) {
1368
+ throw new CliError(`llms.txt 校验未通过:${result.summary.error} 个 error / ${result.summary.warn} 个 warn`, {
1369
+ kind: 'validate',
1370
+ code: 'EGEOLLMS',
1371
+ exitCode: 1,
1372
+ hint: '按上面逐条改;`--json` 的 `error.details.issues` 有完整清单',
1373
+ details: result,
1374
+ });
1375
+ }
1376
+ if (!out.json) out.ok(`llms.txt 校验通过:${result.summary.warn} 个 warn(不影响退出码)`);
1377
+ ctx.done(result);
1378
+ return;
1379
+ }
1380
+
1381
+ const result = buildGeoLlms(dir, { baseUrl: flags.baseUrl || '' });
1382
+ if (!out.json) {
1383
+ out.head(`llms.txt${flags.confirm === true ? '(写盘)' : '(dry-run,加 --confirm 才写)'} · ${result.dir}`);
1384
+ out.line(result.llms_txt.content.replace(/\n$/, ''));
1385
+ out.head(`llms-full.txt${flags.confirm === true ? '(写盘)' : '(dry-run,加 --confirm 才写)'}`);
1386
+ out.line(result.llms_full.content.replace(/\n$/, ''));
1387
+ }
1388
+ const written = [];
1389
+ if (flags.confirm === true) {
1390
+ written.push({ name: 'llms.txt', ...writeTextFile(result.llms_txt.path, result.llms_txt.content) });
1391
+ written.push({ name: 'llms-full.txt', ...writeTextFile(result.llms_full.path, result.llms_full.content) });
1392
+ if (!out.json) out.ok(`已写入 ${result.llms_txt.path} / ${result.llms_full.path}(${written[0].chars} / ${written[1].chars} 字符)`);
1393
+ } else if (!out.json) {
1394
+ out.ok('dry-run:没有写任何文件(加 --confirm 写入 llms.txt / llms-full.txt)');
1395
+ }
1396
+ ctx.done({
1397
+ dir: result.dir,
1398
+ dry_run: flags.confirm !== true,
1399
+ base_url: result.base_url,
1400
+ site: result.site,
1401
+ notes: result.notes,
1402
+ categories: result.categories,
1403
+ pages: result.pages,
1404
+ llms_txt: { path: result.llms_txt.path, chars: result.llms_txt.chars, content: result.llms_txt.content },
1405
+ llms_full: { path: result.llms_full.path, chars: result.llms_full.chars, content: result.llms_full.content },
1406
+ written,
1407
+ });
1408
+ },
1409
+ };
1410
+
1411
+ /* ================================================================== geo robots */
1412
+
1413
+ export const geoRobotsCommand = {
1414
+ name: 'geo robots',
1415
+ summary: 'AI 爬虫策略:allow-ai / block-ai 生成 robots.txt 策略段(幂等、保留人工规则),show 只看当前规则',
1416
+ usage: 'wkgeo geo robots <目录> --mode <allow-ai|block-ai|show> [--confirm] [--json]',
1417
+ args: [{ name: 'dir', required: true, desc: '站点产物目录(读 / 写 <目录>/robots.txt)' }],
1418
+ flags: {
1419
+ mode: { type: 'string', required: true, desc: `策略:${GEO_ROBOTS_MODES.join(' | ')}(allow-ai 放行 / block-ai 禁止 / show 只看)` },
1420
+ confirm: { type: 'boolean', desc: '真的写盘(不加就是 dry-run,只打印 diff)' },
1421
+ },
1422
+ examples: [
1423
+ 'wkgeo geo robots .tmp-build/seo-fixture --mode show',
1424
+ 'wkgeo geo robots .tmp-build/seo-fixture --mode allow-ai',
1425
+ 'wkgeo geo robots .tmp-build/seo-fixture --mode block-ai --confirm',
1426
+ ],
1427
+ notes: [
1428
+ '**幂等**:策略段用 `# >>> wkgeo:geo-ai >>>` … `# <<< wkgeo:geo-ai <<<` 包起来,重跑整段替换(切 allow-ai ⇄ block-ai 也是替换),不会越叠越多。',
1429
+ '**保留人工规则**:段外内容(`User-agent: *` / `Disallow: /cms/` / `Sitemap: …`)一个字节都不动;文件不存在就新建。',
1430
+ '`allow-ai` 给 6 个 AI 爬虫各写一组 `User-agent` + `Allow: /`;`block-ai` 同结构换成 `Disallow: /`(**会真的挡住 AI 收录,慎用**)。',
1431
+ '**默认 dry-run**:只打印简单 diff(`+` 新增 / `-` 删除)与改动后的完整策略段,`--confirm` 才写盘。',
1432
+ '`show` 只读:列出当前 robots.txt 里与 AI 爬虫相关的规则与每个 UA 的显式策略状态,不写盘。',
1433
+ ],
1434
+ async run(ctx) {
1435
+ const { out, flags } = ctx;
1436
+ const dir = resolveDirArg(ctx.positional.dir);
1437
+ const mode = String(flags.mode || '').trim();
1438
+ if (!GEO_ROBOTS_MODES.includes(mode)) {
1439
+ throw new UsageError(`--mode 只能是 ${GEO_ROBOTS_MODES.join(' | ')}(收到:${mode || '(空)'})`);
1440
+ }
1441
+ const file = path.join(dir, 'robots.txt');
1442
+ const before = readTextIf(file);
1443
+
1444
+ if (mode === 'show') {
1445
+ const result = { dir, path: file, ...showGeoRobots(before === null ? '' : before) };
1446
+ if (!out.json) {
1447
+ out.head(`robots.txt AI 规则 · ${file}`);
1448
+ out.line(` 文件:${result.exists ? '存在' : '不存在'} · 托管策略段:${result.managed_block ? '有' : '无'} · UA 组 ${result.groups}`);
1449
+ out.line('');
1450
+ out.line(' AI 爬虫状态:');
1451
+ for (const row of result.bots) {
1452
+ out.line(` ${row.status === 'allowed' ? '✓' : row.status === 'blocked' ? '✗' : '·'} ${row.bot.padEnd(16)} ${row.status.padEnd(9)} ${row.explicit ? '有专属 UA 组' : row.matched_by === 'wildcard' ? '只有 * 组' : '没有 UA 组'}`);
1453
+ }
1454
+ if (result.ai_rules.length) {
1455
+ out.line('');
1456
+ out.line(' 与 AI 相关的规则:');
1457
+ for (const one of result.ai_rules) out.line(` ${one.user_agent} → ${one.rule}`);
1458
+ } else if (result.exists) {
1459
+ out.line('');
1460
+ out.line(' (文件里没有任何 AI 相关规则)');
1461
+ }
1462
+ }
1463
+ if (!out.json) out.ok('只读:没有写任何文件');
1464
+ ctx.done({ ...result, dry_run: true, written: [] });
1465
+ return;
1466
+ }
1467
+
1468
+ const plan = planGeoRobots({ text: before === null ? '' : before, mode });
1469
+ if (!out.json) {
1470
+ out.head(`geo robots --mode ${mode}${flags.confirm === true ? '(写盘)' : '(dry-run,加 --confirm 才写)'} · ${file}`);
1471
+ out.line(` 改动:${plan.action === 'unchanged' ? '无(已是目标状态)' : plan.action === 'updated' ? '替换已有策略段' : '追加策略段'}`);
1472
+ if (plan.diff.removed.length) {
1473
+ out.line('');
1474
+ out.line(' 将删除:');
1475
+ for (const line of plan.diff.removed.slice(0, 40)) out.line(` - ${line}`);
1476
+ if (plan.diff.removed.length > 40) out.line(` - …(共 ${plan.diff.removed.length} 行)`);
1477
+ }
1478
+ if (plan.diff.added.length) {
1479
+ out.line('');
1480
+ out.line(' 将新增:');
1481
+ for (const line of plan.diff.added.slice(0, 40)) out.line(` + ${line}`);
1482
+ if (plan.diff.added.length > 40) out.line(` + …(共 ${plan.diff.added.length} 行)`);
1483
+ }
1484
+ out.line('');
1485
+ out.line(' 改动后的文件:');
1486
+ out.line(plan.after.replace(/\n$/, ''));
1487
+ }
1488
+ const written = [];
1489
+ if (flags.confirm === true && plan.action !== 'unchanged') {
1490
+ written.push({ name: 'robots.txt', ...writeTextFile(file, plan.after) });
1491
+ if (!out.json) out.ok(`已写入 ${file}(${written[0].chars} 字符,原有手工规则保留)`);
1492
+ } else if (!out.json && flags.confirm === true) {
1493
+ out.ok('已是目标状态:没有改文件');
1494
+ } else if (!out.json) {
1495
+ out.ok('dry-run:没有写文件(加 --confirm 写入 robots.txt)');
1496
+ }
1497
+ ctx.done({
1498
+ dir,
1499
+ path: file,
1500
+ mode,
1501
+ dry_run: flags.confirm !== true,
1502
+ action: plan.action,
1503
+ before_exists: before !== null,
1504
+ added: plan.diff.added,
1505
+ removed: plan.diff.removed,
1506
+ after: plan.after,
1507
+ bots: plan.bots,
1508
+ written,
1509
+ });
1510
+ },
1511
+ };
1512
+
1513
+ /* ================================================================== geo brands */
1514
+
1515
+ export const geoBrandsCommand = {
1516
+ name: 'geo brands',
1517
+ summary: '品牌在 AI 平台上的收录/引用跟踪(后台 API 未就绪:未配置 WKGEO_GEO_API 时返回 not_configured + 契约,不发请求)',
1518
+ usage: 'wkgeo geo brands [--domain <域>] [--lang <语言>] [--json]',
1519
+ args: [],
1520
+ flags: {
1521
+ domain: { type: 'string', desc: '要查的站点域名(配置了 WKGEO_GEO_API 时必填)' },
1522
+ lang: { type: 'string', desc: '语言(默认 zh-CN)' },
1523
+ },
1524
+ examples: ['wkgeo geo brands', 'wkgeo geo brands --domain example.com --lang zh-CN --json'],
1525
+ notes: [
1526
+ '**后台 API 尚未就绪**:未配置环境变量 `WKGEO_GEO_API` 时,本命令**不发任何请求**,返回 `status:"not_configured"` + 完整契约说明,exit 0(不是报错,是"还没接好")。',
1527
+ '配置了基址才请求:`GET <WKGEO_GEO_API>/api/geo/brands?domain=<域>&lang=<语言>`。',
1528
+ '响应契约:`{brands:[{name, platforms:[{platform, status:"none|listed|top|cited", rank, citations, url, checkedAt}]}]}`;形状不对直接报错,**不猜、不补数据**。',
1529
+ '**不硬编码任何 URL / 密钥**:基址只从环境变量来,输出里也不打印基址(只给契约路径 `/api/geo/brands`)。',
1530
+ '品牌数据只能来自后台,CLI 绝不本地伪造"看起来像真数据"的占位记录。',
1531
+ ],
1532
+ async run(ctx) {
1533
+ const { out, flags } = ctx;
1534
+ const cfg = brandsConfig(ctx.env);
1535
+
1536
+ if (!cfg.configured) {
1537
+ const result = brandsNotConfigured();
1538
+ if (!out.json) {
1539
+ out.head('品牌跟踪(品牌在 AI 平台上有没有被收录 / 引用)');
1540
+ out.line(' 状态:not_configured —— 后台 API 尚未就绪 / 未配置基址,本次没有发任何请求。');
1541
+ out.line('');
1542
+ out.line(' 契约:');
1543
+ out.line(` · 环境变量:${result.contract.env}(后台基址)`);
1544
+ out.line(` · 请求:${result.contract.request.method} <base>${result.contract.request.path}?domain=<域>&lang=<语言>`);
1545
+ out.line(' · 响应:{brands:[{name, platforms:[{platform, status:"none|listed|top|cited", rank, citations, url, checkedAt}]}]}');
1546
+ out.line('');
1547
+ for (const note of result.notes) out.line(` · ${note}`);
1548
+ }
1549
+ if (!out.json) out.notice('提示:配置 `WKGEO_GEO_API` 后重跑本命令即可接入真实数据。');
1550
+ ctx.done({ ...result, dry_run: true, written: [] });
1551
+ return;
1552
+ }
1553
+
1554
+ const domain = String(flags.domain || '').trim();
1555
+ if (!domain) {
1556
+ throw new UsageError('配置了 WKGEO_GEO_API 时必须给 --domain(CLI 不猜要查哪个域)');
1557
+ }
1558
+ const lang = String(flags.lang || 'zh-CN').trim() || 'zh-CN';
1559
+ const result = await fetchGeoBrands({
1560
+ base: cfg.base,
1561
+ domain,
1562
+ lang,
1563
+ fetchImpl: ctx.fetchImpl,
1564
+ timeoutMs: Number(flags.httpTimeout) > 0 ? Number(flags.httpTimeout) : 15000,
1565
+ });
1566
+
1567
+ if (!out.json) {
1568
+ out.head(`品牌跟踪 · ${result.domain}(${result.lang})`);
1569
+ out.line(
1570
+ ` 品牌 ${result.brands.length} 个 · 平台记录 ${result.platforms} 条 · none ${result.status_counts.none} / listed ${result.status_counts.listed} / top ${result.status_counts.top} / cited ${result.status_counts.cited}`,
1571
+ );
1572
+ if (result.dropped) out.warn(`${result.dropped} 条记录不符合契约(platform / status 不合法),已丢弃`);
1573
+ if (result.brands.length) {
1574
+ out.line('');
1575
+ out.table(
1576
+ ['品牌', '平台', '状态', '排名', '引用', '链接'],
1577
+ result.brands.flatMap((brand) =>
1578
+ brand.platforms.length
1579
+ ? brand.platforms.map((row) => [
1580
+ brand.name,
1581
+ row.platform,
1582
+ row.status,
1583
+ row.rank === null ? '-' : String(row.rank),
1584
+ row.citations === null ? '-' : String(row.citations),
1585
+ row.url || '-',
1586
+ ])
1587
+ : [[brand.name, '-', 'none', '-', '-', '-']],
1588
+ ),
1589
+ );
1590
+ }
1591
+ }
1592
+ if (!out.json) out.ok(`品牌跟踪完成:${result.brands.length} 个品牌 / ${result.platforms} 条平台记录`);
1593
+ ctx.done({ ...result, dry_run: true, written: [] });
1594
+ },
1595
+ };
1596
+
1597
+ /* ================================================================== geo report */
1598
+
1599
+ export const geoReportCommand = {
1600
+ name: 'geo report',
1601
+ summary: 'GEO 综合报告:geo audit + 品牌跟踪(未配置则 brands.status="skipped"),输出 markdown 或 json',
1602
+ usage: 'wkgeo geo report <目录> [--md] [--domain <域>] [--json]',
1603
+ args: [{ name: 'dir', required: true, desc: '站点产物目录(报告的数据源)' }],
1604
+ flags: {
1605
+ md: { type: 'boolean', desc: '强制输出 markdown 原文(可重定向成 .md;即使被"非终端自动 JSON"或 `--json` 命中,`--md` 也优先)' },
1606
+ domain: { type: 'string', desc: '品牌跟踪的域名(只在配置了 WKGEO_GEO_API 时有意义)' },
1607
+ },
1608
+ examples: ['wkgeo geo report .tmp-build/seo-fixture --md', 'wkgeo geo report ./dist --json'],
1609
+ notes: [
1610
+ '汇总两件事:`geo audit` 的 20 项评分 + issues,`geo brands` 的品牌收录(未配置 `WKGEO_GEO_API` 时 `brands.status = "skipped"`,**不发请求**)。',
1611
+ '默认终端里输出 markdown;`--md` 是显式写法,**优先级最高**(管道 / `--json` 下也只写 markdown 原文,方便 `> report.md`);要 JSON 信封就别给 `--md`(markdown 在 `data.markdown`)。',
1612
+ '**报告命令**:体检有问题也 exit 0(报告本身就是结论);目录不存在 exit 2、目录里没 .html exit 1。',
1613
+ '不写文件(要落盘自己重定向);不联网(除配置了 `WKGEO_GEO_API` 时的品牌那一段)。',
1614
+ ],
1615
+ async run(ctx) {
1616
+ const { out, flags } = ctx;
1617
+ const dir = resolveDirArg(ctx.positional.dir);
1618
+ const audit = auditGeoDirectory(dir);
1619
+
1620
+ let brands;
1621
+ const cfg = brandsConfig(ctx.env);
1622
+ const domain = String(flags.domain || '').trim();
1623
+ if (!cfg.configured) {
1624
+ brands = { status: 'skipped', reason: 'not_configured', configured: false, brands: [], platforms: 0 };
1625
+ } else if (!domain) {
1626
+ brands = { status: 'skipped', reason: 'no_domain', configured: true, brands: [], platforms: 0 };
1627
+ } else {
1628
+ try {
1629
+ brands = await fetchGeoBrands({ base: cfg.base, domain, lang: 'zh-CN', fetchImpl: ctx.fetchImpl });
1630
+ } catch (e) {
1631
+ /** 品牌段是"锦上添花":接口挂了不拖累整份报告,但**明确记下来**,不假装成功 */
1632
+ brands = { status: 'error', reason: 'request_failed', message: String((e && e.message) || e), brands: [], platforms: 0 };
1633
+ }
1634
+ }
1635
+
1636
+ const generatedAt = new Date().toISOString();
1637
+ const markdown = buildGeoReport({ audit, brands, generatedAt });
1638
+
1639
+ /**
1640
+ * `--md` **显式要 markdown 就压过"非终端自动 JSON"**:报告是要重定向成 .md 文件给人看/给
1641
+ * AI 读的,套进 JSON 信封(换行转义)等于废掉。所以三种出口互斥,绝不同时写 stdout:
1642
+ * `--md` → 只写 markdown 原文;
1643
+ * 人类终端(无 --json)→ 只写 markdown 原文 + 一句提示;
1644
+ * 其余(--json / 管道自动 JSON)→ 只写 JSON 信封(markdown 在 data.markdown 里)。
1645
+ */
1646
+ const wantMarkdown = Boolean(flags.md);
1647
+ if (wantMarkdown) {
1648
+ out.plain(markdown.endsWith('\n') ? markdown : markdown + '\n');
1649
+ return { markdown, score: audit.score, grade: audit.grade, brands };
1650
+ }
1651
+ if (!out.json) {
1652
+ out.plain(markdown);
1653
+ out.ok(`GEO 报告生成:${audit.score} 分(${audit.grade})· 品牌 ${brands.status}`);
1654
+ }
1655
+ ctx.done({
1656
+ dir: audit.dir,
1657
+ generated_at: generatedAt,
1658
+ score: audit.score,
1659
+ grade: audit.grade,
1660
+ summary: audit.summary,
1661
+ rules: audit.rules,
1662
+ issues: audit.issues,
1663
+ truncated: audit.truncated,
1664
+ signals: audit.signals,
1665
+ pages: audit.pages,
1666
+ brands,
1667
+ markdown,
1668
+ });
1669
+ },
1670
+ };
1671
+
1672
+ /** `geo` 组五条命令(注册在 `cli/lib/commands/index.mjs`) */
1673
+ export const geoCommands = [geoAuditCommand, geoLlmsCommand, geoRobotsCommand, geoBrandsCommand, geoReportCommand];