@wkgeo/cli 2.0.2 → 2.0.3

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
@@ -32,6 +32,27 @@ npx -y @wkgeo/cli@latest orders list
32
32
  * 完整的给 AI 的说明书见 [`SKILL.md`](./SKILL.md);**也可以一条命令直接取出来**:
33
33
  `npx -y @wkgeo/cli@latest skill`(默认打**纯文本原文**;`--json` 时在 `data.markdown` 里)。
34
34
 
35
+ ### 0.1 建站规范(`spec` / `init`,2026-11-21)
36
+
37
+ 建站不是随便建:栏目类型、每栏目独立模板、`target_type` 兼容、首页版块跳转、图标都有硬规则。
38
+ 这份规范**随包分发**,一条命令就能拿到,也可以写进你的项目让 agent 自动读:
39
+
40
+ ```bash
41
+ npx -y @wkgeo/cli@latest spec # 规范全文(默认纯 markdown,重定向即可存成文件)
42
+ npx -y @wkgeo/cli@latest spec --agents # 只打「给 AI 的精简版」
43
+ npx -y @wkgeo/cli@latest init # 只看计划(默认 dry-run,零写盘)
44
+ npx -y @wkgeo/cli@latest init --confirm # 写进项目:AGENTS.md / CLAUDE.md / .cursorrules / Copilot 指令
45
+ ```
46
+
47
+ * **为什么要写进项目**:agent 读哪个文件是 **agent 自己**决定的(DSH/Codex 读 `AGENTS.md`、
48
+ Claude Code 读 `CLAUDE.md`、Cursor 读 `.cursorrules`、Copilot 读 `.github/copilot-instructions.md`),
49
+ CLI 控制不了它读什么,只能把文件放到它该在的位置 —— 所以 `init` 默认**四个都写**(`--agents` 可只写几个)。
50
+ * **幂等、不动你的内容**:写进去的那一段用 `<!-- wkgeo:site-spec:begin/end -->` 包着,
51
+ 再跑一次是**原地替换**;文件里已有你自己的内容时**只在末尾追加**;内容没变就一个字节都不写。
52
+ * **三处同源**:`spec` 输出、`init` 写进项目的那一段、`wkgeo-site-spec` skill 都出自同一份
53
+ `cli/spec/SITE-SPEC.md`(改规则只改那份;`node cli/scripts/gen-site-spec.mjs --check` 防漂移)。
54
+ * 规范里每条都标了**已实现 / 实现中** —— 实现中的条目不要当既有行为依赖。
55
+
35
56
  ---
36
57
 
37
58
  ## 1. 安装与分发(三条路径,主线是 npm)
package/SKILL.md CHANGED
@@ -43,6 +43,8 @@ version: 1.0.0
43
43
  * 用户问"**这个令牌能干什么 / 还剩多久 / 怎么立刻作废**" → `auth status`(账号 + scopes + 动作面)/ `auth token`(只给前 4 位 + 长度 + 到期)/ `auth revoke`(服务端吊销 + 删本地)
44
44
  * 用户说"**帮我绑自己的域名**" → CLI **没有**域名能力(域名命令已全部删除);引导到会员中心 / CMS 后台的「域名」里操作,**不要**自己编一条域名命令
45
45
  * **你自己需要这份手册**(换机器、上下文被截断、想确认某个参数)→ `skill`(把本文件原文打出来,见 §2)
46
+ * **你要建站 / 改栏目 / 做模板 / 写 `site-manifest.json`** → **先跑 `spec`**(建站规范:栏目类型、每栏目独立模板、`target_type` 兼容、首页版块跳转、图标),见 §2.1
47
+ * 用户说"**让 AI 按我们的规范建站**"/"把规矩写进项目" → `init --confirm`(把规范写进 `AGENTS.md` / `CLAUDE.md` / `.cursorrules` / Copilot 指令,agent 下次开会话自己读)
46
48
 
47
49
  **不要用**:
48
50
 
@@ -85,6 +87,25 @@ npx -y @wkgeo/cli@latest skill > SKILL.md # 直接落一份到本地,离线
85
87
  说明跑的是**被裁剪的包**或只拷了 `lib/` 的开发目录(正常 npm 安装包里一定有这份文件)。
86
88
  换官方包 `npx -y @wkgeo/cli@latest skill` 即可;这不是命令用错了。
87
89
 
90
+ ### ⭐ 建站规范:`wkgeo spec` / `wkgeo init`
91
+
92
+ ```bash
93
+ npx -y @wkgeo/cli@latest spec # 规范全文(栏目 / 模板 / 首页版块 / 图标,逐条标"已实现 / 实现中")
94
+ npx -y @wkgeo/cli@latest spec --agents # 只打"给 AI 的精简版"(= init 写进项目的那一段,逐字节相同)
95
+ npx -y @wkgeo/cli@latest spec --json # 标准信封
96
+ npx -y @wkgeo/cli@latest init # 只看计划(默认 dry-run,零写盘)
97
+ npx -y @wkgeo/cli@latest init --confirm # 写进项目:AGENTS.md / CLAUDE.md / .cursorrules / .github/copilot-instructions.md
98
+ npx -y @wkgeo/cli@latest init --confirm --agents agents,claude # 只写点名的
99
+ ```
100
+
101
+ * **三处同源**:`spec` 命令、`init` 写的约定文件、`wkgeo-site-spec` skill 全部出自同一份
102
+ `cli/spec/SITE-SPEC.md`(改规则只改那一份;生成器 `--check` 防漂移)。
103
+ * `init` **幂等**:内容用 `<!-- wkgeo:site-spec:begin/end -->` 包着 —— 已有那一段就**原地替换**,
104
+ 文件里有用户自己的内容就**只在末尾追加**(不覆盖、不重复);算出来没变就一个字节都不写。
105
+ * `init` **不猜你是哪个 agent**(env 里没有可靠特征),所以默认四个文件都写,`--agents` 可只写几个。
106
+ * 写完要让 agent **重开会话 / 重新读一次**约定文件才生效(多数 agent 只在会话开始时读)。
107
+ * `spec` 与 `skill` 同一条输出例外:**默认永远是纯 markdown**(管道里也是),只有显式 `--json` 才套信封。
108
+
88
109
  ---
89
110
 
90
111
  ## 3. 输出契约(**关键**)
@@ -118,6 +139,8 @@ npx -y @wkgeo/cli@latest skill > SKILL.md # 直接落一份到本地,离线
118
139
 
119
140
  | 命令 | 作用 | 关键参数 |
120
141
  | --- | --- | --- |
142
+ | `spec` | **建站规范全文**(栏目 / 模板 / 首页版块 / 图标,逐条标"已实现 / 实现中");默认纯 markdown,管道里也不套 JSON | `--agents`(只打精简版)、`--json` |
143
+ | `init` | 把规范的精简版写进项目:`AGENTS.md` / `CLAUDE.md` / `.cursorrules` / `.github/copilot-instructions.md`(幂等、不覆盖用户内容、默认 dry-run) | `--agents all\|none\|<名单>`、`--confirm` |
121
144
  | `login` | 授权一次(令牌存本地 30 天;**默认浏览器回调**,设备码仅兜底) | `--device`、`--no-wait`、`--device-continue`、`--no-auto-device`、`--callback-first-wait <秒>`(可选,默认关闭)、`--no-browser`、`--open-browser`、`--scope`、`--timeout <秒>` |
122
145
  | `whoami` | 当前是谁(账号标识) | `--verbose` |
123
146
  | `logout` | 退出(删本地凭据 + 服务端吊销) | `--local-only` |
@@ -86,6 +86,15 @@ import {
86
86
  } from './orders.mjs';
87
87
  import { appsListCommand, appsRevokeCommand } from './apps.mjs';
88
88
  import { skillCommand } from './skill.mjs';
89
+ /**
90
+ * ★ 2026-11-21(老板:CLI 里要把建站规范说清楚,最好还有 skill 那样的说明文档):
91
+ * `spec` = 打印随包分发的 **建站规范**(`spec/SITE-SPEC.md`,栏目 / 模板 / 首页版块 / 图标的规则);
92
+ * `init` = 把规范的精简版写进项目的 AGENTS.md / CLAUDE.md / .cursorrules / Copilot 指令
93
+ * (agent 启动时自己读,CLI 只能把文件放到位,控制不了它读什么)。
94
+ * 三处同源:spec 命令 / init 写的约定文件 / `wkgeo-site-spec` skill 都出自同一份 markdown。
95
+ */
96
+ import { specCommand } from './spec.mjs';
97
+ import { initCommand } from './init.mjs';
89
98
  /* ★ 2026-11-19 task-1250(老板:CLI 只做 CMS 内容管理,跟域名没有关系,不在那里操作):
90
99
  命令面已删除 ——
91
100
  · `domainops.mjs` :`domain search|buy|order` / `domain zone *` / `esa *`(12 条)
@@ -367,6 +376,13 @@ export const COMMANDS = [
367
376
  aiAskCommand,
368
377
  aiChatCommand,
369
378
  contextExportCommand,
379
+ /**
380
+ * `spec` / `init`:建站规范的两个出口(2026-11-21)——
381
+ * `spec` 打印全文(/ `--agents` 只打精简版),`init` 把精简版写进项目的四个约定文件。
382
+ * 与 `skill` 同属「(基础)」:不登录也能跑、纯本地。
383
+ */
384
+ specCommand,
385
+ initCommand,
370
386
  /**
371
387
  * `skill`:把随包分发的 `SKILL.md` 原文打印出来(AI 端自取手册)。
372
388
  * 放在 config 前面 —— 两者同属「(基础)」,都是"不登录也能跑"的本地命令。
@@ -571,6 +587,8 @@ export function renderHelp(name = null) {
571
587
  * 没有任何命令能把它取出来 —— AI 只能去 node_modules 里翻,等于"分发了但拿不到"。
572
588
  */
573
589
  out.push(' wkgeo skill # 打印给 AI 端的操作手册(随包分发)');
590
+ out.push(' wkgeo spec # 打印建站规范(栏目/模板/首页版块/图标)');
591
+ out.push(' wkgeo init --confirm # 把规范写进项目的 AGENTS.md / CLAUDE.md / .cursorrules / Copilot');
574
592
  out.push('');
575
593
  out.push('通用参数:--json(机器可读;非终端下默认开启)/ --text(强制人类可读)');
576
594
  out.push(' --base <url>(平台面)/ --cms-base <url>(CMS 面)/ --client-id <id> / --credentials <path>');
@@ -0,0 +1,111 @@
1
+ /**
2
+ * `init` 命令:把建站规范的**精简版**写进项目的四个「agent 启动即读」文件。
3
+ *
4
+ * ## 为什么是"写文件",不是"CLI 主动注入"
5
+ * agent 读什么是 **agent 自己的事**:DSH 读 `AGENTS.md`、Claude Code 读 `CLAUDE.md`、
6
+ * Cursor 读 `.cursorrules`、Copilot 读 `.github/copilot-instructions.md`。
7
+ * CLI 无法控制它读什么,能做的只有**把文件放到它该在的位置** —— 就是这条命令。
8
+ *
9
+ * ⚠️ CLI **不猜**调用者是哪个 agent:`process.env` 里没有可靠特征(`CLAUDECODE` / `CURSOR_*` /
10
+ * `DSH_*` 都可能缺失,用户也可能在任意 shell 里跑、或由别的工具当子进程调)。
11
+ * 所以默认**四个都写**,用 `--agents` 让用户自己挑。
12
+ *
13
+ * ## 幂等与"不动用户已有内容"
14
+ * * 写入内容用 `<!-- wkgeo:site-spec:begin -->` … `<!-- wkgeo:site-spec:end -->` 包起来;
15
+ * * 已有我们的标记 ⇒ **原地替换**(改规范后重跑不会重复追加);
16
+ * * 文件有内容但没有标记 ⇒ **只在末尾追加**,用户写的一个字不动;
17
+ * * 算出来一字节不差 ⇒ `unchanged`,不写盘。
18
+ *
19
+ * ## 默认 dry-run
20
+ * 与全 CLI 的写操作一致:不加 `--confirm` 只打计划(零写盘),`--confirm` 才真写。
21
+ */
22
+
23
+ import path from 'node:path';
24
+
25
+ import { readSpecMarkdown, planAgentFiles, resolveAgentFiles, writeAgentFiles } from '../site-spec.mjs';
26
+
27
+ /** 人读模式下的动作词(JSON 里仍是 created / appended / replaced / unchanged) */
28
+ const ACTION_LABEL = {
29
+ created: '将新建',
30
+ appended: '已有内容 → 追加到末尾(用户内容不动)',
31
+ replaced: '已有规范段 → 原地替换',
32
+ unchanged: '内容没变 → 跳过',
33
+ };
34
+
35
+ export const initCommand = {
36
+ name: 'init',
37
+ summary: '把建站规范写进项目的 AGENTS.md / CLAUDE.md / .cursorrules / Copilot 指令(可重复跑)',
38
+ usage: 'wkgeo init [--agents all|none|<名单>] [--confirm] [--json]',
39
+ flags: {
40
+ agents: {
41
+ type: 'string',
42
+ desc: '写哪些约定文件:all(默认)/ none / 逗号分隔(agents,claude,cursor,copilot,也认 AGENTS.md 这类文件名)',
43
+ },
44
+ 'dry-run': { type: 'boolean', desc: '只看计划不写盘(不加 --confirm 时本来就是 dry-run)' },
45
+ confirm: { type: 'boolean', desc: '真写盘(不加只打计划)' },
46
+ },
47
+ examples: [
48
+ 'wkgeo init # 只看计划(零写盘)',
49
+ 'wkgeo init --confirm # 四个约定文件都写 / 追加',
50
+ 'wkgeo init --confirm --agents agents,claude # 只写 AGENTS.md 与 CLAUDE.md',
51
+ 'wkgeo init --confirm --agents none # 一个都不写(等价于空跑)',
52
+ ],
53
+ notes: [
54
+ '写的是建站规范的**精简版**(与 `wkgeo spec --agents` 逐字节相同);全文跑 `wkgeo spec`。',
55
+ '可重复跑:自己那一段用 `<!-- wkgeo:site-spec:begin/end -->` 包着,改规范后重跑会**原地替换**,不会重复追加。',
56
+ '**不覆盖用户内容**:文件已有你自己的内容时只在末尾追加我们这一段(文件里已有我们的段则只替换那一段)。',
57
+ 'CLI 不判断你用的是哪个 agent,所以默认四个都写;用 `--agents` 可只写其中几个。',
58
+ '写完后让 agent **重新开一个会话 / 重新读一次**约定文件才会生效(多数 agent 只在会话开始时读)。',
59
+ ],
60
+ async run(ctx) {
61
+ const { out, flags } = ctx;
62
+ const dir = process.cwd();
63
+ const info = readSpecMarkdown();
64
+ const files = resolveAgentFiles(flags.agents);
65
+ const plan = planAgentFiles({ dir, markdown: info.markdown, files });
66
+
67
+ /** JSON 里不回整份 content(可能几十 KB),只给动作 + 字节数 + 路径 */
68
+ const rows = plan.map((one) => ({
69
+ path: one.path,
70
+ abs_path: one.absPath,
71
+ label: one.label,
72
+ action: one.action,
73
+ existed: one.existed,
74
+ bytes: Buffer.byteLength(one.content, 'utf8'),
75
+ }));
76
+
77
+ const dryRun = flags.confirm !== true;
78
+ const writeResult = dryRun ? { written: [], skipped: rows.filter((r) => r.action === 'unchanged').map((r) => r.path) } : writeAgentFiles(plan);
79
+ const data = {
80
+ dir,
81
+ source: info.path,
82
+ dry_run: dryRun,
83
+ files: rows,
84
+ written: writeResult.written,
85
+ skipped: writeResult.skipped,
86
+ };
87
+
88
+ if (!out.json) {
89
+ out.head(dryRun ? `建站规范 → ${dir}(dry-run,零写盘)` : `建站规范 → ${dir}`);
90
+ for (const one of rows) {
91
+ const mark = one.action === 'unchanged' ? '·' : '+';
92
+ out.line(` ${mark} ${one.path.padEnd(32)} ${ACTION_LABEL[one.action] || one.action}(${one.bytes} 字节)`);
93
+ }
94
+ out.line('');
95
+ out.info(` 规范来源:${info.path}`);
96
+ out.info(' 全文:wkgeo spec | 只要这一段:wkgeo spec --agents');
97
+ if (files.length === 0) out.warn(' --agents none:没有要写的文件(空跑)。');
98
+ else if (dryRun) out.notice('\n这是 dry-run:加 --confirm 才真写盘。');
99
+ else out.ok(`已写 ${writeResult.written.length} 个文件,跳过 ${writeResult.skipped.length} 个(内容没变)。`);
100
+ out.info(' 提示:多数 agent 只在会话开始时读约定文件,写完请重开会话(或让它重新读一次)。');
101
+ }
102
+
103
+ ctx.done(data);
104
+ return data;
105
+ },
106
+ };
107
+
108
+ /** 供单测直接拿目录解析口径(与命令层保持一致:永远用 cwd,不吃 --site 之类) */
109
+ export function resolveInitDir(cwd = process.cwd()) {
110
+ return path.resolve(String(cwd || process.cwd()));
111
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * `spec` 命令:把**随包分发**的建站规范 `spec/SITE-SPEC.md` 原文打印出来。
3
+ *
4
+ * ## 为什么是一条命令,而不是"看 README 某一节"
5
+ * 规范和代码一样会变:写在 README 里,AI 端拿到的是**它当时抓到的那一版**;写成命令,
6
+ * `npx @wkgeo/cli@latest spec` 每次都拿到**当前安装包里的那一版**(与 `wkgeo skill` 同理)。
7
+ *
8
+ * ## 三个出口同源(**这是本命令存在的核心理由**)
9
+ * * `wkgeo spec` → 全文(本命令)
10
+ * * `wkgeo spec --agents` → 只打「给 AI 的精简版」,**与 `wkgeo init` 写进项目的内容逐字节相同**
11
+ * * `wkgeo-site-spec` skill → 由 `cli/scripts/gen-site-spec.mjs` 从同一份 markdown 生成
12
+ * 三处都不另写规则;改规则只改 `cli/spec/SITE-SPEC.md`。
13
+ *
14
+ * ## 输出形态(**刻意的例外**,与 `skill` 同一套记法)
15
+ * * 默认(**包括管道/非终端**)→ 纯 markdown 原文,不套 JSON 信封 ——
16
+ * 否则 `wkgeo spec > 规范.md` 得到的是 `{"ok":true,…"markdown":"…\n…"}`,白折腾。
17
+ * * `--json` → 标准信封(给必须统一按 JSON 解析的宿主)。
18
+ *
19
+ * ## 鉴权
20
+ * 不需要登录、不发网络请求(纯本地读文件)。
21
+ */
22
+
23
+ import { SPEC_URL, extractAgentsBrief, readSpecMarkdown } from '../site-spec.mjs';
24
+
25
+ export const specCommand = {
26
+ name: 'spec',
27
+ summary: '打印建站规范(栏目 / 模板 / 首页版块 / 图标)',
28
+ usage: 'wkgeo spec [--agents] [--json]',
29
+ flags: {
30
+ agents: {
31
+ type: 'boolean',
32
+ desc: '只打印「给 AI 的精简版」那一节(= `wkgeo init` 写进 AGENTS.md / CLAUDE.md / .cursorrules / Copilot 指令的内容)',
33
+ },
34
+ },
35
+ examples: [
36
+ 'wkgeo spec # 全文',
37
+ 'wkgeo spec --agents # 只打精简版(要写进项目的那一段)',
38
+ 'wkgeo spec > SITE-SPEC.md # 存成文件(默认就是纯 markdown,不会套 JSON)',
39
+ 'wkgeo spec --json # 机器可读信封',
40
+ ],
41
+ notes: [
42
+ '默认**永远输出 markdown 原文**,即使输出到管道/非终端也不套 JSON 信封 —— 所以 `wkgeo spec > x.md` 直接得到可读文档。',
43
+ '只有显式 `wkgeo spec --json` 才输出信封:{"ok":true,"command":"spec","data":{"path":…,"markdown":…,"bytes":…,"lines":…}}。',
44
+ '本命令不需要登录、不发任何网络请求(纯本地读包内的 spec/SITE-SPEC.md)。',
45
+ '规范里的规则都标了「已实现 / 实现中」;实现中的条目别当既有行为依赖。',
46
+ ],
47
+ async run(ctx) {
48
+ const { out, flags } = ctx;
49
+ const info = readSpecMarkdown(SPEC_URL);
50
+ const agentsOnly = flags.agents === true;
51
+ const markdown = agentsOnly ? extractAgentsBrief(info.markdown) : info.markdown;
52
+ const data = {
53
+ path: info.path,
54
+ agents_only: agentsOnly,
55
+ bytes: Buffer.byteLength(markdown, 'utf8'),
56
+ lines: markdown.split('\n').length,
57
+ markdown,
58
+ };
59
+
60
+ /**
61
+ * 判断依据必须是**用户显式写的 `--json`**(`ctx.flags.json`),不能用 `out.json`:
62
+ * 后者在非终端会自动变 true(全 CLI 的通用约定),那样管道里 `wkgeo spec > x.md`
63
+ * 就会灌进一坨 JSON 信封 —— 正是这里要避免的(与 `wkgeo skill` 同一处理)。
64
+ */
65
+ if (flags.json === true) {
66
+ ctx.done(data);
67
+ return data;
68
+ }
69
+ out.plain(markdown.endsWith('\n') ? markdown : markdown + '\n');
70
+ return data;
71
+ },
72
+ };
@@ -637,6 +637,51 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
637
637
  return '';
638
638
  }
639
639
 
640
+ /**
641
+ * **这个栏目自己那一页**(老板 2026-11-21):「尽量每一个栏目制作一个模版 …… 复制一个模版绑定
642
+ * 当前的栏目,这样就方便后期修改」。
643
+ *
644
+ * 口径:
645
+ * * **清单没写 `templateFile`** 才算(写了就听清单的,上面 `resolveManifestTemplateFile` 已校验);
646
+ * * **只给新建的栏目用**(存量那行一律不碰 —— 客户自己挑过的模板页不能被一次 `content apply` 覆盖);
647
+ * * 模板里**声明了** `pages/c-<slug>.html` 才绑(判据走契约的 `templatePageBindings`)——
648
+ * base 模板 / `wkgeo template init` 出来的模板会给每个栏目做一份;
649
+ * 没做 ⇒ 空串 = 不绑(前台按类型自动选,兜底一个字没改)。
650
+ *
651
+ * @returns {Promise<string>} 要绑的模板页;`''` = 不绑
652
+ */
653
+ async function resolveOwnPerCategoryPage(cat, kind) {
654
+ const bindingContract = await loadTemplateBindingContract();
655
+ if (!bindingContract || typeof bindingContract.perCategoryPagePath !== 'function') return '';
656
+ const meta = await loadSiteTemplateMeta();
657
+ if (!meta) return '';
658
+ const own = bindingContract.perCategoryPagePath(String(cat.slug || cat.name || ''));
659
+ if (!own) return '';
660
+ const declared = new Set(
661
+ (typeof bindingContract.templatePageBindings === 'function' ? bindingContract.templatePageBindings(meta) : [])
662
+ .map(one => String((one && one.path) || '')),
663
+ );
664
+ if (!declared.has(own)) return '';
665
+ const verdict = await templateBindingVerdict(
666
+ {
667
+ key: cat.slug,
668
+ name: cat.name,
669
+ kind,
670
+ fieldsEnabled: null,
671
+ customFields: (cat.fields || []).map(one => String((one && one.key) || one || '')),
672
+ },
673
+ own,
674
+ );
675
+ if (verdict && verdict.ok === false) {
676
+ warnings.push({
677
+ path: `categories.${cat.slug}.templateFile`,
678
+ message: `模板里有 ${own},但与栏目类型不匹配,已跳过绑定(前台按类型自动选):${verdict.message}`,
679
+ });
680
+ return '';
681
+ }
682
+ return own;
683
+ }
684
+
640
685
  /* ── 栏目 ─────────────────────────────────────────────────── */
641
686
 
642
687
  /** 本次清单 `menus[]` 声明的导航 path(懒算一次;`menus[]` 是导航唯一真相) */
@@ -754,6 +799,11 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
754
799
  const kind = mapped ? mapped.kind : cat.kind;
755
800
  /** 模板绑定先过契约(计划期就定下来:不合法 ⇒ 空串 + 一条 ⚠,创建 / 更新两条分支共用) */
756
801
  const templateFile = await resolveManifestTemplateFile(cat, kind);
802
+ /**
803
+ * ★ 2026-11-21(每栏目一个模板页):**新建**栏目、且清单没指定模板页时,
804
+ * 绑它自己那一页(模板里声明了 `pages/c-<slug>.html` 才算)。存量栏目一律不碰。
805
+ */
806
+ const boundTemplate = templateFile || (existing ? '' : await resolveOwnPerCategoryPage(cat, kind));
757
807
  /** 导航归属:true / false / undefined(undefined = 本次不动,老行为) */
758
808
  const inMenu = navStateOf(cat, wantPath);
759
809
  if (inMenu === false) hidden.push(cat.name);
@@ -765,7 +815,7 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
765
815
  planned: 'create',
766
816
  action: 'create',
767
817
  label,
768
- detail: `新建栏目(${kind}${inMenu === false ? ',不进导航' : ''})${templateFile ? ` 模板 ${templateFile}` : ''}`,
818
+ detail: `新建栏目(${kind}${inMenu === false ? ',不进导航' : ''})${boundTemplate ? ` 模板 ${boundTemplate}` : ''}`,
769
819
  };
770
820
  entry.run = async (row) => {
771
821
  const payload = { name: cat.name, slug: cat.slug, kind, sort: cat.sort };
@@ -773,7 +823,7 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
773
823
  const liveParentId = cat.parent ? (state.catIdBySlug.get(cat.parent) || {}).id || '' : '';
774
824
  const effectiveParentId = liveParentId || parentId;
775
825
  if (effectiveParentId) payload.parent_id = effectiveParentId;
776
- if (templateFile) payload.template_path = templateFile;
826
+ if (boundTemplate) payload.template_path = boundTemplate;
777
827
  if (cat.description) payload.description = cat.description;
778
828
  if (cat.seoDescription) payload.seo_description = cat.seoDescription;
779
829
  if (cat.seoKeywords) payload.seo_keywords = cat.seoKeywords;
@@ -0,0 +1,302 @@
1
+ /**
2
+ * 建站规范(SITE-SPEC)读取层 —— **唯一主源 = 包内 `spec/SITE-SPEC.md`**。
3
+ *
4
+ * ## 为什么要有这一层
5
+ * 规范只有一份文件,但出口有三个:
6
+ * ① `wkgeo spec`(人 / 本地 CLI 里的 agent 主动跑);
7
+ * ② `wkgeo init` 把「给 AI 的精简版」写进项目的 AGENTS.md / CLAUDE.md / .cursorrules /
8
+ * .github/copilot-instructions.md(**agent 启动时自己读**,这才是"自动读到"的入口);
9
+ * ③ `wkgeo-site-spec` skill(DSH 本机 / 云端沙箱加载)。
10
+ * 三个出口**不能各写一份**(一定会漂移),所以:
11
+ * * ②③ 的内容都从这份 markdown 里**切出来 / 生成**;
12
+ * * 口径标记写在 markdown 里(`<!-- wkgeo:site-spec:agents:begin -->` … `end`),
13
+ * 这里只做"按标记切",不在这里复制规则文本。
14
+ *
15
+ * ## 路径解析(与 `skill.mjs` 同一个坑)
16
+ * `import.meta.url` = `<包根>/lib/site-spec.mjs` ⇒ 往上一级是包根,再进 `spec/`。
17
+ * **绝不能**用 `process.cwd()`:AI 端几乎总在别的目录里跑,npx 更是如此。
18
+ */
19
+
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import { fileURLToPath, pathToFileURL } from 'node:url';
23
+
24
+ import { CliError, EXIT, UsageError } from './errors.mjs';
25
+
26
+ /** 包根下的 `spec/SITE-SPEC.md` */
27
+ export const SPEC_URL = new URL('../spec/SITE-SPEC.md', import.meta.url);
28
+
29
+ /** 「给 AI 的精简版」在 markdown 里的起止标记(改标记 = 三处一起变,别只改一边) */
30
+ export const BRIEF_BEGIN = '<!-- wkgeo:site-spec:agents:begin -->';
31
+ export const BRIEF_END = '<!-- wkgeo:site-spec:agents:end -->';
32
+
33
+ /** 写进项目文件的那一段也用同一对标记包起来(重复跑靠它原地替换,不重复追加) */
34
+ export const BLOCK_BEGIN = '<!-- wkgeo:site-spec:begin -->';
35
+ export const BLOCK_END = '<!-- wkgeo:site-spec:end -->';
36
+
37
+ /** 沙箱任务提示词里那几行的标记(云端 AI 读不到本地文件,只能靠提示词 + 镜像里的 skill) */
38
+ export const PROMPT_BEGIN = '<!-- wkgeo:site-spec:prompt:begin -->';
39
+ export const PROMPT_END = '<!-- wkgeo:site-spec:prompt:end -->';
40
+
41
+ /**
42
+ * 四个约定文件 —— 覆盖主流 coding agent 的"启动即读"文件。
43
+ *
44
+ * ⚠️ CLI **不判断**调用者是哪个 agent(`process.env` 里没有可靠特征,用户在任意 shell 里跑、
45
+ * 或被别的工具当子进程调,都会误判)。所以默认**全写**,用 `--agents` 让用户自己挑。
46
+ */
47
+ export const AGENT_FILES = Object.freeze([
48
+ Object.freeze({
49
+ key: 'agents',
50
+ path: 'AGENTS.md',
51
+ label: 'DSH / Codex / 通用 AGENTS.md',
52
+ aliases: ['agents', 'agents.md', 'codex', 'dsh'],
53
+ }),
54
+ Object.freeze({
55
+ key: 'claude',
56
+ path: 'CLAUDE.md',
57
+ label: 'Claude Code CLAUDE.md',
58
+ aliases: ['claude', 'claude.md', 'claude-code'],
59
+ }),
60
+ Object.freeze({
61
+ key: 'cursor',
62
+ path: '.cursorrules',
63
+ label: 'Cursor .cursorrules',
64
+ aliases: ['cursor', '.cursorrules'],
65
+ }),
66
+ Object.freeze({
67
+ key: 'copilot',
68
+ path: '.github/copilot-instructions.md',
69
+ label: 'GitHub Copilot 指令文件',
70
+ aliases: ['copilot', 'github', 'copilot-instructions'],
71
+ }),
72
+ ]);
73
+
74
+ /**
75
+ * 读主源 markdown。
76
+ *
77
+ * @param {URL|string} [src] 默认包内 `spec/SITE-SPEC.md`(单测可指到别处)
78
+ * @returns {{path:string, markdown:string, bytes:number, lines:number}}
79
+ * @throws {CliError} 文件缺失 ⇒ `kind="missing_spec"`、exit 1、带中文 hint(不打堆栈)
80
+ */
81
+ export function readSpecMarkdown(src = SPEC_URL) {
82
+ const url = src instanceof URL ? src : pathToFileURL(String(src));
83
+ let filePath = String(url);
84
+ try {
85
+ filePath = fileURLToPath(url);
86
+ } catch {
87
+ /* 非 file: URL 时退回原样展示,别为展示路径把命令搞崩 */
88
+ }
89
+ try {
90
+ const markdown = fs.readFileSync(url, 'utf8');
91
+ return {
92
+ path: filePath,
93
+ markdown,
94
+ bytes: Buffer.byteLength(markdown, 'utf8'),
95
+ lines: markdown.split('\n').length,
96
+ };
97
+ } catch (e) {
98
+ const why = (e && e.code) || '读取失败';
99
+ throw new CliError(`当前安装包里没有建站规范(spec/SITE-SPEC.md):${filePath}(${why})`, {
100
+ kind: 'missing_spec',
101
+ code: (e && e.code) || null,
102
+ exitCode: EXIT.ERROR,
103
+ hint:
104
+ '这不是命令用错了:多半是开发目录里只拷了 lib/、或分发包缺了 files 白名单里的 spec/。' +
105
+ '可改用官方包 `npx -y @wkgeo/cli@latest spec`,或直接看仓库里的 cli/spec/SITE-SPEC.md',
106
+ cause: e,
107
+ });
108
+ }
109
+ }
110
+
111
+ /**
112
+ * 从全文里切出两个标记之间的正文(通用:精简版 / 沙箱提示词精要都走它)。
113
+ *
114
+ * @param {string} markdown
115
+ * @param {string} begin 起标记
116
+ * @param {string} end 止标记
117
+ * @param {string} what 报错时怎么称呼这一段(中文)
118
+ * @returns {string} 已去首尾空行、末尾带一个换行
119
+ * @throws {CliError} 标记缺失 / 顺序颠倒 / 空段 ⇒ 直接报错(宁可炸,也别写一份空规范出去)
120
+ */
121
+ export function extractSection(markdown, begin, end, what = '规范段落') {
122
+ const text = String(markdown || '');
123
+ const start = text.indexOf(begin);
124
+ const stop = text.indexOf(end);
125
+ if (start === -1 || stop === -1 || stop < start) {
126
+ throw new CliError(`建站规范里找不到${what}的标记(begin/end),无法生成`, {
127
+ kind: 'spec_marker_missing',
128
+ exitCode: EXIT.ERROR,
129
+ hint: `规范里必须有 ${begin} 与 ${end} 两行,且 begin 在 end 之前`,
130
+ });
131
+ }
132
+ const body = text
133
+ .slice(start + begin.length, stop)
134
+ .replace(/^\r?\n/, '')
135
+ .replace(/\s+$/, '');
136
+ if (!body.trim()) {
137
+ throw new CliError(`${what}的标记之间是空的,拒绝写出去`, {
138
+ kind: 'spec_marker_empty',
139
+ exitCode: EXIT.ERROR,
140
+ });
141
+ }
142
+ return body + '\n';
143
+ }
144
+
145
+ /**
146
+ * 「给 AI 的精简版」—— 写进项目四个约定文件的那一段。
147
+ *
148
+ * @param {string} markdown
149
+ * @returns {string}
150
+ */
151
+ export function extractAgentsBrief(markdown) {
152
+ return extractSection(markdown, BRIEF_BEGIN, BRIEF_END, '「给 AI 的精简版」');
153
+ }
154
+
155
+ /**
156
+ * 沙箱任务提示词里的精要(云端 AI 看不到本地文件,只能靠提示词 + 镜像里的 skill)。
157
+ *
158
+ * @param {string} markdown
159
+ * @returns {string}
160
+ */
161
+ export function extractPromptBrief(markdown) {
162
+ return extractSection(markdown, PROMPT_BEGIN, PROMPT_END, '「沙箱提示词精要」');
163
+ }
164
+
165
+ /**
166
+ * 解析 `--agents` 的取值。
167
+ *
168
+ * `all`(默认) = 四个都写;`none` = 一个都不写;
169
+ * 其它 = 逗号 / 空格分隔的点名:认 key(`agents` / `claude` / `cursor` / `copilot`)、
170
+ * 认文件名(`AGENTS.md` / `CLAUDE.md` / `.cursorrules` / `.github/copilot-instructions.md`)、
171
+ * 也认简写(`codex` / `dsh` / `github`)。
172
+ *
173
+ * @param {string|boolean|undefined} value
174
+ * @returns {Array<typeof AGENT_FILES[number]>}
175
+ * @throws {UsageError} 认不出来的名字 ⇒ 列出可用值(别静默忽略)
176
+ */
177
+ export function resolveAgentFiles(value) {
178
+ const raw = value === undefined || value === null || value === true ? 'all' : String(value).trim();
179
+ if (!raw || raw.toLowerCase() === 'all') return [...AGENT_FILES];
180
+ if (raw.toLowerCase() === 'none') return [];
181
+ const wanted = raw
182
+ .split(/[,\s]+/)
183
+ .map((one) => one.trim())
184
+ .filter(Boolean);
185
+ const out = [];
186
+ const unknown = [];
187
+ for (const name of wanted) {
188
+ const lower = name.toLowerCase().replace(/\\/g, '/');
189
+ const hit = AGENT_FILES.find(
190
+ (one) => one.key === lower || one.path.toLowerCase() === lower || one.aliases.includes(lower),
191
+ );
192
+ if (!hit) {
193
+ unknown.push(name);
194
+ continue;
195
+ }
196
+ if (!out.includes(hit)) out.push(hit);
197
+ }
198
+ if (unknown.length) {
199
+ const usable = AGENT_FILES.map((one) => `${one.key}(${one.path})`).join(' / ');
200
+ throw new UsageError(`--agents 不认识:${unknown.join(', ')}\n可用:all / none / ${usable}`);
201
+ }
202
+ return out;
203
+ }
204
+
205
+ /** 现有文件用的换行符(Windows 项目里多半是 CRLF,插入段跟着走,别混出两种) */
206
+ function eolOf(text) {
207
+ return String(text || '').includes('\r\n') ? '\r\n' : '\n';
208
+ }
209
+
210
+ /** 把块里的 `\n` 换成目标换行符 */
211
+ function withEol(block, eol) {
212
+ return eol === '\n' ? block : block.split('\n').join(eol);
213
+ }
214
+
215
+ /**
216
+ * 把「精简版」并进一份已有文件的内容 —— **纯函数**(单测直接对拍)。
217
+ *
218
+ * 四种结果:
219
+ * * `created` 文件原本不存在 / 空 ⇒ 直接就是这一段;
220
+ * * `replaced` 已有我们那一段(begin/end 都在)⇒ **原地替换**(改规范后重跑不会重复追加);
221
+ * * `appended` 文件有内容但没有我们的标记 ⇒ **只在末尾追加**,用户写的一个字不动;
222
+ * * `unchanged` 算出来的全文与原来一字节不差 ⇒ 不写盘(幂等)。
223
+ *
224
+ * @param {string|null} existing 已有内容(null = 文件不存在)
225
+ * @param {string} brief 「给 AI 的精简版」正文(末尾带换行)
226
+ * @returns {{content:string, action:'created'|'replaced'|'appended'|'unchanged'}}
227
+ */
228
+ export function upsertBriefBlock(existing, brief) {
229
+ const body = String(brief || '').replace(/\s+$/, '');
230
+ const block = `${BLOCK_BEGIN}\n${body}\n${BLOCK_END}`;
231
+ if (existing === null || existing === undefined || !String(existing).trim()) {
232
+ const content = `${block}\n`;
233
+ return { content, action: 'created' };
234
+ }
235
+ const text = String(existing);
236
+ const eol = eolOf(text);
237
+ const marker = withEol(block, eol);
238
+ const start = text.indexOf(BLOCK_BEGIN);
239
+ const end = text.indexOf(BLOCK_END, start === -1 ? 0 : start);
240
+ if (start !== -1 && end !== -1) {
241
+ const after = text.slice(end + BLOCK_END.length);
242
+ const next = text.slice(0, start) + marker + after;
243
+ return { content: next, action: next === text ? 'unchanged' : 'replaced' };
244
+ }
245
+ /* 没有我们的标记 ⇒ 追加到末尾;文件末尾没换行就先补一个,段间留一个空行 */
246
+ const base = text.endsWith('\n') ? text : text + eol;
247
+ const next = `${base}${eol}${marker}${eol}`;
248
+ return { content: next, action: 'appended' };
249
+ }
250
+
251
+ /**
252
+ * 规划「四个约定文件各要写成什么」—— **不写盘**(dry-run 与真写共用同一份计划)。
253
+ *
254
+ * @param {{dir?:string, markdown:string, files?:Array, exists?:Function, readFile?:Function}} input
255
+ * @returns {Array<{key,path,action,absPath,content,reason}>}
256
+ */
257
+ export function planAgentFiles(input = {}) {
258
+ const dir = path.resolve(String(input.dir || process.cwd()));
259
+ const files = Array.isArray(input.files) ? input.files : [...AGENT_FILES];
260
+ const brief = extractAgentsBrief(input.markdown);
261
+ const read = input.readFile || ((p) => (fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : null));
262
+ const rows = [];
263
+ for (const one of files) {
264
+ const absPath = path.join(dir, one.path.split('/').join(path.sep));
265
+ const existing = read(absPath);
266
+ const { content, action } = upsertBriefBlock(existing, brief);
267
+ rows.push({
268
+ key: one.key,
269
+ path: one.path,
270
+ label: one.label,
271
+ absPath,
272
+ action,
273
+ content,
274
+ existed: existing !== null && existing !== undefined,
275
+ });
276
+ }
277
+ return rows;
278
+ }
279
+
280
+ /**
281
+ * 落盘(只写 `action !== 'unchanged'` 的行)。
282
+ *
283
+ * @param {Array} plan `planAgentFiles()` 的结果
284
+ * @param {{mkdir?:Function, writeFile?:Function}} [io] 单测注入点
285
+ * @returns {{written:string[], skipped:string[]}}
286
+ */
287
+ export function writeAgentFiles(plan, io = {}) {
288
+ const mkdir = io.mkdir || ((p) => fs.mkdirSync(p, { recursive: true }));
289
+ const writeFile = io.writeFile || ((p, c) => fs.writeFileSync(p, c, 'utf8'));
290
+ const written = [];
291
+ const skipped = [];
292
+ for (const row of plan) {
293
+ if (row.action === 'unchanged') {
294
+ skipped.push(row.path);
295
+ continue;
296
+ }
297
+ mkdir(path.dirname(row.absPath));
298
+ writeFile(row.absPath, row.content);
299
+ written.push(row.path);
300
+ }
301
+ return { written, skipped };
302
+ }
@@ -39,6 +39,69 @@ export const DESIGN_VIEWPORTS = VIEWPORTS;
39
39
 
40
40
  const HERE = path.dirname(fileURLToPath(import.meta.url));
41
41
 
42
+ // ------------------------------------------------- 每栏目一个模板页(2026-11-21)
43
+
44
+ /**
45
+ * 模板绑定契约(唯一真源:`aliyun/fc/_shared/template-binding-contract.js`)。
46
+ * CLI 不打包它,运行时按相对路径现取(与 `manifest-apply.mjs` 同一个套路);取不到 ⇒ 本能力静默跳过。
47
+ */
48
+ let bindingContractPromise = null;
49
+ function loadBindingContract() {
50
+ if (!bindingContractPromise) {
51
+ const url = new URL('../../aliyun/fc/_shared/template-binding-contract.js', import.meta.url);
52
+ bindingContractPromise = import(url.href).then((m) => m.default || m).catch(() => null);
53
+ }
54
+ return bindingContractPromise;
55
+ }
56
+
57
+ /**
58
+ * **给每个栏目复制一份自己的模板页**(老板 2026-11-21):
59
+ * 「尽量每一个栏目制作一个模版,哪怕一样的,也复制一个模版绑定当前的栏目,这样就方便后期修改。」
60
+ *
61
+ * 命名规则 / 撞名兜底全在契约里(`perCategoryPagePath`:`pages/c-<slug>.html`,撞名 `-2`、`-3` …),
62
+ * 这里只负责**落文件**:
63
+ * * 模板里已经有这一页 ⇒ 不动(`action:'keep'`,客户改过的那份保留);
64
+ * * 没有 ⇒ 从该栏目当前用的那页复制一份(内容一模一样,换绑不改版式);
65
+ * * 同时在 `template.json.bindings[]` 声明这一页的类型,后台绑定时才校验得住。
66
+ *
67
+ * @returns {Promise<{pages: Array, bindings: Array, warnings: string[], supported: boolean}>}
68
+ */
69
+ export async function materializePerColumnPages({ outDir, columns, files, say }) {
70
+ const contract = await loadBindingContract();
71
+ if (!contract || typeof contract.planPerCategoryPages !== 'function') {
72
+ return { pages: [], bindings: [], warnings: ['没取到模板绑定契约,跳过「每栏目一个模板页」'], supported: false };
73
+ }
74
+ const plan = contract.planPerCategoryPages({ columns, files });
75
+ const pages = [];
76
+ for (const one of plan.pages) {
77
+ if (one.action === 'keep') {
78
+ pages.push({ ...one, wrote: false });
79
+ continue;
80
+ }
81
+ const srcAbs = path.join(outDir, one.sourcePath.split('/').join(path.sep));
82
+ const dstAbs = path.join(outDir, one.path.split('/').join(path.sep));
83
+ const bytes = await fsp.readFile(srcAbs);
84
+ await fsp.writeFile(dstAbs, bytes);
85
+ pages.push({ ...one, wrote: true, bytes: bytes.length });
86
+ }
87
+ /**
88
+ * 声明这些页的 `target_type`(从**来源页**的名字推断:index ⇒ list、about ⇒ single_page …)。
89
+ * 认不出来就不声明 —— 契约口径是「缺省不报错」,不硬编一个类型去拦客户。
90
+ */
91
+ const bindings = [];
92
+ for (const one of plan.pages) {
93
+ const targetType = contract.targetTypeFromPath(one.sourcePath) || '';
94
+ if (!targetType) continue;
95
+ bindings.push({ path: one.path, target_type: targetType });
96
+ }
97
+ if (typeof say === 'function' && pages.length) {
98
+ say(`每栏目一个模板页:${pages.length} 个(pages/c-<slug>.html;新复制 ${plan.stats.copy} 个、已有 ${plan.stats.kept} 个)`);
99
+ }
100
+ if (typeof say === 'function') for (const one of plan.warnings) say(` ⚠️ ${one}`);
101
+ return { pages, bindings, warnings: plan.warnings, supported: true };
102
+ }
103
+
104
+
42
105
  // ---------------------------------------------------------------- 基础文本工具
43
106
 
44
107
  const ENTITIES = {
@@ -756,6 +819,12 @@ export async function generateFromUrl({
756
819
  // key 由栏目名派生(中文名 slugify 为空 → 退到页面名),同名再 -2 去重
757
820
  let base = spec.key || slugify(spec.name) || slugify(spec.page) || "column";
758
821
  if (!/^[a-z0-9][a-z0-9-]*$/.test(base)) base = slugify(spec.page) || "column";
822
+ /**
823
+ * 首页那一栏的 key 统一成 `home`(2026-11-21):中文菜单名 slugify 之后是空 ⇒ 以前落到页面名
824
+ * `index`,跟平台预置栏目的 slug(`home`)对不上 —— 于是「每栏目一个模板页」会做成
825
+ * `pages/c-index.html`,而建站播种按栏目 slug 找的是 `pages/c-home.html`,白做一份。
826
+ */
827
+ if (base === "index") base = "home";
759
828
  let k = base;
760
829
  let i = 2;
761
830
  while (usedKeys.has(k)) k = `${base}-${i++}`;
@@ -845,6 +914,17 @@ export async function generateFromUrl({
845
914
  });
846
915
 
847
916
  const demo = columns.some((c) => c.items.length > 0);
917
+ /**
918
+ * ★ 2026-11-21(老板):**每个栏目复制一份自己的模板页** ——
919
+ * `pages/c-<slug>.html`,内容与它当前用的那页一模一样;后期只改自己那份,不影响别的栏目。
920
+ * 这些页同时进 `template.json.files[]`(打包/发布要带上)与 `bindings[]`(后台绑定要校验)。
921
+ */
922
+ const mirrorPages = await materializePerColumnPages({
923
+ outDir,
924
+ columns,
925
+ files: pagesOut.map((p) => `pages/${p.name}.html`),
926
+ say,
927
+ });
848
928
  const template = {
849
929
  _format: TEMPLATE_FORMAT,
850
930
  key,
@@ -863,7 +943,11 @@ export async function generateFromUrl({
863
943
  columns,
864
944
  requires: [],
865
945
  data: {},
866
- files: pagesOut.map((p) => `pages/${p.name}.html`).concat(['partials/header.html', 'partials/nav.html', 'partials/footer.html', 'assets/img/placeholder.svg']),
946
+ files: pagesOut
947
+ .map((p) => `pages/${p.name}.html`)
948
+ .concat(mirrorPages.pages.map((p) => p.path))
949
+ .concat(['partials/header.html', 'partials/nav.html', 'partials/footer.html', 'assets/img/placeholder.svg']),
950
+ ...(mirrorPages.bindings.length ? { bindings: mirrorPages.bindings } : {}),
867
951
  };
868
952
 
869
953
  // ---- 8) assets/base + 占位图 + template.json ----
@@ -904,6 +988,7 @@ export async function generateFromUrl({
904
988
  assetErrors: localized.errors.length,
905
989
  unmappedLinks: [...new Set(unmapped)].length,
906
990
  partials: [partHeader, partNav, partFooter].filter(Boolean).length,
991
+ perColumnPages: mirrorPages.pages.length,
907
992
  },
908
993
  pages: pagesOut,
909
994
  };
@@ -1066,6 +1151,12 @@ export async function generateFromDir({ srcDir, outDir, key, capture = true, des
1066
1151
  // key 由栏目名派生(中文名 slugify 为空 → 退到页面名),同名再 -2 去重
1067
1152
  let base = spec.key || slugify(spec.name) || slugify(spec.page) || "column";
1068
1153
  if (!/^[a-z0-9][a-z0-9-]*$/.test(base)) base = slugify(spec.page) || "column";
1154
+ /**
1155
+ * 首页那一栏的 key 统一成 `home`(2026-11-21):中文菜单名 slugify 之后是空 ⇒ 以前落到页面名
1156
+ * `index`,跟平台预置栏目的 slug(`home`)对不上 —— 于是「每栏目一个模板页」会做成
1157
+ * `pages/c-index.html`,而建站播种按栏目 slug 找的是 `pages/c-home.html`,白做一份。
1158
+ */
1159
+ if (base === "index") base = "home";
1069
1160
  let k = base;
1070
1161
  let i = 2;
1071
1162
  while (usedKeys.has(k)) k = `${base}-${i++}`;
@@ -1162,6 +1253,17 @@ export async function generateFromDir({ srcDir, outDir, key, capture = true, des
1162
1253
  };
1163
1254
  });
1164
1255
 
1256
+ /**
1257
+ * ★ 2026-11-21(老板):**每个栏目复制一份自己的模板页** —— 与 from-url 同一套规则
1258
+ * (`pages/c-<slug>.html`;内容一样,文件独立,后期只改自己那份)。
1259
+ */
1260
+ const mirrorPages = await materializePerColumnPages({
1261
+ outDir,
1262
+ columns,
1263
+ files: pagesOut.map((p) => `pages/${p.name}.html`),
1264
+ say,
1265
+ });
1266
+
1165
1267
  const template = {
1166
1268
  _format: TEMPLATE_FORMAT,
1167
1269
  key,
@@ -1180,7 +1282,11 @@ export async function generateFromDir({ srcDir, outDir, key, capture = true, des
1180
1282
  columns,
1181
1283
  requires: [],
1182
1284
  data: {},
1183
- files: pagesOut.map((p) => `pages/${p.name}.html`).concat(['partials/header.html', 'partials/nav.html', 'partials/footer.html', 'assets/img/placeholder.svg']),
1285
+ files: pagesOut
1286
+ .map((p) => `pages/${p.name}.html`)
1287
+ .concat(mirrorPages.pages.map((p) => p.path))
1288
+ .concat(['partials/header.html', 'partials/nav.html', 'partials/footer.html', 'assets/img/placeholder.svg']),
1289
+ ...(mirrorPages.bindings.length ? { bindings: mirrorPages.bindings } : {}),
1184
1290
  };
1185
1291
 
1186
1292
  const baseDir = resolveBaseDir(null, {});
@@ -1223,6 +1329,7 @@ export async function generateFromDir({ srcDir, outDir, key, capture = true, des
1223
1329
  items: columns.reduce((n, c) => n + c.items.length, 0),
1224
1330
  assets: copied.length,
1225
1331
  partials: [pH, pN, pF].filter(Boolean).length,
1332
+ perColumnPages: mirrorPages.pages.length,
1226
1333
  },
1227
1334
  pages: pagesOut,
1228
1335
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wkgeo/cli",
3
- "version": "2.0.2",
3
+ "version": "2.0.3",
4
4
  "description": "云站平台官方命令行客户端(@wkgeo/cli):授权登录一次,之后建站 / 下单 / 钱包支付 / 查余额都不用再登录(OAuth 授权码 + PKCE,公共客户端,零第三方依赖)",
5
5
  "keywords": [
6
6
  "wkgeo",
@@ -24,6 +24,7 @@
24
24
  "files": [
25
25
  "wkgeo.mjs",
26
26
  "lib",
27
+ "spec",
27
28
  "README.md",
28
29
  "SKILL.md",
29
30
  "CHANGELOG.md",
@@ -0,0 +1,198 @@
1
+ # 云站建站规范(SITE-SPEC)
2
+
3
+ > **这是唯一主源。** 下面三处都从这份文件生成 / 摘取,不另写一份:
4
+ >
5
+ > | 出口 | 谁读 | 怎么拿 |
6
+ > |---|---|---|
7
+ > | `AGENTS.md` / `CLAUDE.md` / `.cursorrules` / `.github/copilot-instructions.md` | 本地 coding agent(DSH / Codex / Claude Code / Cursor / Copilot)**启动时自动读** | `wkgeo init --confirm` 把「给 AI 的精简版」那一节写进项目(带标记、可重复跑) |
8
+ > | `wkgeo spec` | 本地 CLI 里的 agent / 人 | `wkgeo spec` 打印全文;`wkgeo spec --agents` 只打印精简版 |
9
+ > | `wkgeo-site-spec` skill | 支持 skill 的环境(DSH 本机、**云端沙箱**) | skill 文件由 `node cli/scripts/gen-site-spec.mjs` 从本文件生成 |
10
+ >
11
+ > 改规则**只改本文件**,再跑生成器;`node cli/scripts/gen-site-spec.mjs --check` 在三处不同步时 exit 1。
12
+ >
13
+ > 图例:**✅ 已实现**(命令/服务端真有这条行为,给了代码出处)| **🚧 实现中**(规则已定,代码在别的单里,写明单名)——
14
+ > 实现中的条目**不要当既有行为依赖**。
15
+
16
+ <!-- wkgeo:site-spec:agents:begin -->
17
+ ## 建站规范(wkgeo 云站 · 精简版)
18
+
19
+ 用 `wkgeo` 建站 / 改栏目 / 做模板时按这 8 条做。完整版 + 代码出处:`wkgeo spec`。
20
+
21
+ 1. **栏目类型只有三种**:`channel`(频道页)/ `list`(列表页)/ `page`(单页)。`content apply` 清单里写 `type`:单页 `single`(落库 = `page`)、列表 `list`、频道 `channel`;子栏目继承父类型;首页(`slug=home`)固定 `channel`。
22
+ 2. **每个栏目一份独立模板文件**:`pages/c-<slug>.html`(同名撞了自动 `-2` / `-3`)。内容可以从默认档复制(与 `pages/index.html` / `pages/page.html` 逐字节相同),但**文件必须独立** —— 改一个栏目只改它自己那份。默认档只作兜底,不是默认做法。*(生成侧实现中)*
23
+ 3. **绑定字段是 `cms_category.template_path`**:`wkgeo categories bind-template <栏目> pages/c-<slug>.html`(清单里写 `categories[].templateFile`)。
24
+ 4. **`target_type` 必须与栏目 kind 兼容**:`page`→`single_page|article`;`list`→`list|list+category`;`channel`→`channel|list|list+category`。不兼容就别提交 `template_path`(留空走兜底),否则渲染出半张页。
25
+ 5. **兜底(保险,不是默认做法)**:栏目没绑模板时按 kind 自动挑 —— `list`/`channel` → `pages/index.html`,`page` → `pages/page.html`,内容页 → `pages/content.html`。
26
+ 6. **首页版块已有同名栏目 ⇒ 只做跳转**:`wkgeo categories save <版块> --link-category <目标栏目ID>`,不要再建一个自己维护内容的同名版块。*(自动识别/自动设置实现中)*
27
+ 7. **图标**:必须写 iconify 名(如 `mdi:home-outline`),同一个站内**不能全一样**;不选时由系统分配不重复的默认图标。*(自动分配实现中)*
28
+ 8. **改完必须验收**:`wkgeo content check --site <站点ID>`(契约 ↔ 库 ↔ 前台)exit 0;`wkgeo preview` 逐屏看过再 `publish`。
29
+
30
+ > 实现中的几条(第 2、6、7 条的自动部分)见 `wkgeo spec` 末尾「规则状态」,别当既有行为依赖。
31
+ <!-- wkgeo:site-spec:agents:end -->
32
+
33
+ ## 0. 先认命令:规范怎么拿、怎么落到项目里
34
+
35
+ ```bash
36
+ wkgeo spec # 打印本规范全文(纯文本 markdown,重定向即可存文件)
37
+ wkgeo spec --agents # 只打印「给 AI 的精简版」那一节(= wkgeo init 写进约定文件的内容)
38
+ wkgeo spec --json # 标准信封:{ok,command:"spec",data:{path,bytes,lines,markdown}}
39
+ wkgeo init --confirm # 把精简版写进项目的四个约定文件(默认 dry-run,只打计划)
40
+ ```
41
+
42
+ `wkgeo spec` 与 `wkgeo skill` 一样:**默认输出纯 markdown,即使输出到管道也不套 JSON**(否则重定向得到一坨转义 JSON);只有显式 `--json` 才是信封。不需要登录、不发网络请求。
43
+
44
+ `wkgeo init` 写四个文件(默认全写):`AGENTS.md`(DSH / Codex / 通用)、`CLAUDE.md`(Claude Code)、`.cursorrules`(Cursor)、`.github/copilot-instructions.md`(GitHub Copilot)。
45
+
46
+ - 写入内容用 `<!-- wkgeo:site-spec:begin -->` … `<!-- wkgeo:site-spec:end -->` 包起来;
47
+ - 文件不存在 ⇒ 新建;**已有内容 ⇒ 只在文件末尾追加我们自己这一段**(用户自己写的部分一字不动);
48
+ - 已有我们这一段 ⇒ **原地替换**(改规范后重跑不会重复追加);内容没变 ⇒ 记 `unchanged`,不写盘;
49
+ - `--agents none` 一个都不写;`--agents=AGENTS.md,CLAUDE.md` 只写点名的(也认 `cursor` / `copilot` 简写)。
50
+
51
+ > ⚠️ CLI **不猜**是谁在调它。`wkgeo init` 把四份都写掉,是因为「注入」这件事不是 CLI 干的:agent 启动时自己读约定文件,CLI 只能把文件放到它该在的位置。
52
+
53
+ ## 1. 栏目(Category)
54
+
55
+ - **类型只有三种**:`channel` 频道页 / `list` 列表页 / `page` 单页。服务端判据 `COLUMN_KINDS`(`aliyun/fc/_shared/template-binding-contract.js:52`),CLI 参数 `--kind channel|list|page`(`cli/lib/commands/cms.mjs:440`)。**没有第四种**。
56
+ - **两套词表别混**(同一个东西的三个名字):
57
+
58
+ | 场景 | 怎么写 | 出处 |
59
+ |---|---|---|
60
+ | 服务端 `kind` / CLI `--kind` | `channel` / `list` / `page` | `template-binding-contract.js:52` |
61
+ | `content apply` 清单 `categories[].type` | `channel` / `list` / **`single`**(= `page`) | `cli/lib/manifest-schema.json:168-175` |
62
+ | 模板页 `target_type` | `channel` / `list` / `list+category` / `single_page` / `article` | `template-binding-contract.js:62` |
63
+
64
+ `type: "single"` 落库成 `kind: "page"`,映射由 `aliyun/fc/wkgeo-site-builder/fn/src/site-mapping-contract.mjs:149-151` **一处**决定,别在别处再写一套。
65
+ - **子栏目继承父类型**;**首页锁定频道**:`slug=home` 的 `kind` 由服务端固定为 `channel`(`wkgeo categories create` 的 notes 里有写)。
66
+ - **单页栏目自带一条只能编辑、不能新建/删除的内容**;要再加一页 = 给它加子栏目(`cli/lib/commands/cms.mjs:482`)。
67
+ - 一个栏目**是否进前台导航**由 `in_menu` 决定:首页版块 / 隐藏栏目一律 `in_menu=false`(`wkgeo categories update <栏目> --no-in-menu`)。
68
+
69
+ ## 2. 模板(Template)
70
+
71
+ ### 2.1 每个栏目一个独立 html(规范做法)
72
+
73
+ - 路径规则:**`pages/c-<slug>.html`**。`<slug>` = 栏目 slug 小写、非字母数字换成 `-`、折叠连续 `-`、去掉首尾 `-`;空 slug 用 `cat-<4位hash>`;撞名自动加 `-2` / `-3`(实现:`perCategoryPagePath()` / `planPerCategoryPages()`,`aliyun/fc/_shared/template-binding-contract.js:698-814`)。
74
+ - **内容可以从默认档复制**(`pages/index.html` / `pages/page.html`),复制出来的文件与默认档**逐字节相同**也完全可以;**但文件必须独立**。
75
+ - 为什么:老板 2026-11-21 ——「哪怕一样的,也复制一个模板绑定当前的栏目,这样就方便后期修改」。**改一个栏目 = 只改它自己那个文件**,不牵连别的栏目。
76
+ - 模板里**已经有** `pages/c-<slug>.html` ⇒ 不动它(`action:'keep'`,保留客户改过的版本);没有 ⇒ 从该栏目当前用的页面复制一份(`action:'copy'`)。
77
+ - 这条规则的**生成侧**(`wkgeo template init` 脚手架、建站时默认模板播种)**🚧 实现中**,见 §7 状态表。绑定侧的字段与命令**已实现**(见 2.2)。
78
+
79
+ ### 2.2 绑定:`cms_category.template_path`
80
+
81
+ ```bash
82
+ wkgeo categories bind-template <栏目ID|slug|path> pages/c-about.html # 绑
83
+ wkgeo categories bind-template <栏目> --clear # 解绑 → 回自动档
84
+ wkgeo categories save <栏目> --template-path pages/c-about.html # 等价写法
85
+ ```
86
+
87
+ - 落库字段就是 `cms_category.template_path`(`cli/lib/commands/cms.mjs:433`、`:462`)。
88
+ - `content apply` 清单里写 `categories[].templateFile`(如 `pages/c-about.html`);apply **先按契约试算一遍**,不合法就**不提交 `template_path`**(回落自动档)并回一条 `⚠`(`cli/lib/manifest-apply.mjs:410-417`、`:615`、`:776`)。
89
+ - 绑的文件必须是**本站模板里真实存在的 .html**,否则后端 400(`template_path` 校验)。
90
+
91
+ ### 2.3 `target_type` 对照表(唯一判据)
92
+
93
+ `target_type` 是**模板页**声明的"这一页是什么形态",必须与**栏目 kind** 兼容:
94
+
95
+ | 栏目 kind | 允许绑的 `target_type` | 常见页 |
96
+ |---|---|---|
97
+ | `page` 单页 | `single_page`、`article` | 关于我们 / 联系我们 / 服务条款 |
98
+ | `list` 列表 | `list`、`list+category` | 新闻列表 / 产品列表 |
99
+ | `channel` 频道 | `channel`、`list`、`list+category` | 首页 / 产品中心总览 |
100
+
101
+ - 判据唯一实现:`KIND_TARGETS`(`aliyun/fc/_shared/template-binding-contract.js:73-77`)。**反过来一律拒**:列表版式绑到单页栏目是最常见的错绑(渲染出空列表 + 半张页)。
102
+ - 模板页**没声明** `target_type` 时不拦,按文件名推断:`index`→`list`、`content`/`article`→`article`、`about`/`contact`/`page`/`single`…→`single_page`(`:149-152`、`:237`)。
103
+ - `single_page` / `article` 默认要求栏目有 `richtext` 字段(`DEFAULT_REQUIRED_FIELDS`,`:85-91`);缺字段也会被判不通过。
104
+
105
+ ### 2.4 兜底:栏目没绑时按 kind 自动挑(保险,不是默认做法)
106
+
107
+ | 栏目 kind | 自动档页面 |
108
+ |---|---|
109
+ | `list` | `pages/index.html` |
110
+ | `channel` | `pages/index.html` |
111
+ | `page` | `pages/page.html` |
112
+ | 内容页(content) | `pages/content.html` |
113
+
114
+ 出处:`AUTO_PAGE_BY_KIND`(`template-binding-contract.js:125-130`)。自动绑定还会按 `AUTO_PAGE_CANDIDATES`(`:136-140`)依次试第一个**通过校验**的页;一个都不合法 ⇒ 留空、由渲染期兜底,并记一条 warn。
115
+
116
+ > 兜底是**保险丝**:新站 / 老站没来得及逐栏目建页时不能白屏。**规范做法永远是 2.1 的独立文件**。
117
+
118
+ ## 3. 首页版块(Home blocks)
119
+
120
+ - 「首页版块」= 首页栏目下 `in_menu=false` 的栏目,**一块一个栏目、一块一个 id**(老板 2026-11-09 / 11-13 口径;`cli/lib/manifest-apply.mjs:656-686` 的 `inMenu` 反推规则)。
121
+ - **某个主题已经有同名栏目 ⇒ 首页版块只做跳转,不要再建一个自己维护内容的版块**:
122
+
123
+ ```bash
124
+ wkgeo categories save <首页版块栏目> --link-category <目标栏目ID>
125
+ ```
126
+
127
+ 字段 `link_category_id`、命令参数 `--link-category` 都已实现(`cli/lib/commands/cms.mjs:419`、`:445`;服务端 `aliyun/fc/_shared/content-actions.js:1541-1633`)。给了它 = 点这个版块直接跳到目标栏目**当前的** path(渲染期以 id 为准,目标栏目改路径也跟着走)。
128
+ - 只有**主题不重复**(本站确实没有对应栏目)时,首页版块才可以自己维护内容。
129
+ - 🚧 「按名字自动认出同名栏目、自动写 `link_category_id`」**实现中**(`category-icon-and-home-link`);现在需要**显式传 `--link-category`**。
130
+
131
+ ## 4. 图标(Icon)
132
+
133
+ - **只认 iconify 名**:`前缀:名字`,如 `mdi:home-outline`(正则校验在服务端 `aliyun/fc/_shared/content-actions.js:1717`);写错**不报错、只是那一位空白** ⇒ 必须用真实存在的图标名。
134
+ - 设置:`wkgeo categories save <栏目> --icon mdi:home-outline`。
135
+ - **同一个站内图标不能全一样**(是什么无所谓,全一样不对)。
136
+ - 🚧 「不选时由系统分配**不重复**的默认图标」**实现中**(`category-icon-and-home-link`);现在不传 `--icon` 时前台回落到统一兜底图标 `mdi:folder-outline`(`content-actions.js:612`)。
137
+
138
+ ## 5. 命令对照(做这几件事只走这些命令)
139
+
140
+ | 要做的事 | 命令 |
141
+ |---|---|
142
+ | 打印本规范 | `wkgeo spec`(精简版 `--agents`) |
143
+ | 把规范落到项目(自动注入给 agent) | `wkgeo init --confirm` |
144
+ | 看栏目树 / 单个栏目 | `wkgeo categories list` / `wkgeo categories get <栏目>` |
145
+ | 新建 / 改栏目(含图标、跳转、绑模板) | `wkgeo categories save [栏目] --name … --kind … --icon … --link-category … --template-path …` |
146
+ | 只绑模板 | `wkgeo categories bind-template <栏目> <文件.html>`(`--clear` 解绑) |
147
+ | 整站落库(栏目/字段/素材/内容/单页/导航) | `wkgeo content apply --file site-manifest.json`(默认 dry-run,`--confirm` 才写) |
148
+ | 按模板栏目填内容 | `wkgeo content fill --manifest manifest.json`(同上) |
149
+ | 契约 ↔ 库 ↔ 前台自检 | `wkgeo content check --site <站点ID>` |
150
+ | 拉 / 推模板文件 | `wkgeo templates pull` / `wkgeo templates push --confirm` |
151
+ | 预览 / 发布 | `wkgeo preview --site <ID>` / `wkgeo publish --site <ID> --confirm` |
152
+
153
+ ## 6. 验收(不跑不算做完)
154
+
155
+ 1. `wkgeo content apply … ` 先 **dry-run**,计划与老板对过再 `--confirm`;复跑必须全 `skipped`(幂等)。
156
+ 2. `wkgeo content check --site <ID>` **exit 0**(四种硬问题:类型不符 / 必填缺字段 / 库多出字段 / 栏目缺列)。
157
+ 3. `wkgeo preview` 逐屏看:首页 + 每个栏目列表页 + 至少一条详情页 + 每个单页。
158
+ 4. 发布后短域首页与栏目页 **HTTP 200**(`curl -sS -o /dev/null -w "%{http_code}" https://<短域>/`)。
159
+ 5. 模板线另加:`wkgeo template validate <目录>` exit 0、`template verify` 像素 ≥95%、`template score` 达标。
160
+
161
+ ## 7. 规则状态(哪些真的生效了)
162
+
163
+ | 规则 | 状态 | 证据 / 单名 |
164
+ |---|---|---|
165
+ | 栏目类型只有 `channel`/`list`/`page` | ✅ | `template-binding-contract.js:52`;`cms.mjs:440` |
166
+ | 清单 `type: single` → `kind: page` | ✅ | `site-mapping-contract.mjs:149-151` |
167
+ | 子栏目继承父类型 / 首页锁 channel | ✅ | `content-actions.js:1887-1889`(二级及以下只能继承);`cms.mjs:483`(首页锁 channel) |
168
+ | 绑定字段 `template_path` + `bind-template` / `--template-path` | ✅ | `cms.mjs:433`、`:625`;`manifest-apply.mjs:776` |
169
+ | `target_type` 与 kind 兼容校验 | ✅ | `template-binding-contract.js:73-77`、`:471-477` |
170
+ | 没绑时按 kind 自动兜底 | ✅ | `template-binding-contract.js:125-130` |
171
+ | 首页版块 `link_category_id` 跳转(字段 + 命令 + 渲染) | ✅ | `content-actions.js:1541-1633`;`cms.mjs:419` |
172
+ | 图标必须是合法 iconify 名 | ✅ | `content-actions.js:1710-1720` |
173
+ | **每个栏目一份独立 `pages/c-<slug>.html`(脚手架 / 建站播种)** | 🚧 实现中 | `per-category-template-20261121`;契约与 CLI 代码已在工作区(`template-binding-contract.js:698-814`、`cli/lib/template-gen.mjs`),未验收未发布 |
174
+ | **首页版块按同名栏目自动写 `link_category_id`** | 🚧 实现中 | `category-icon-and-home-link` |
175
+ | **不选图标时系统分配不重复的默认图标** | 🚧 实现中 | `category-icon-and-home-link`;现状统一回落 `mdi:folder-outline` |
176
+
177
+ > 实现中的三条**不要**当既有行为依赖;等对应单验收后再把 §2.1 / §3 / §4 的"实现中"字样去掉(改这一份 + 重跑生成器即可)。
178
+
179
+ ## 8. 沙箱任务提示词里的精要(自动摘取,别手改)
180
+
181
+ 云端沙箱里的 AI 拿不到本地文件,只能看到任务提示词 + 镜像/启动时放进去的 skill。
182
+ 所以这里留一段**极短**的精要,由 `cli/scripts/gen-site-spec.mjs` 摘进 `wkgeo-agent-task` 的提示词;
183
+ 与 skill 正文同源(改上面规则时这段跟着一起改)。
184
+
185
+ <!-- wkgeo:site-spec:prompt:begin -->
186
+ 【建站规范(沙箱内已放 skill:wkgeo-site-spec,开工前先加载)】
187
+ - 栏目类型只有 channel / list / page 三种;子栏目继承父类型,首页固定 channel。
188
+ - 每个栏目一份独立模板 pages/c-<slug>.html(可从默认档复制,但文件必须独立);绑定字段 template_path。
189
+ - 模板页 target_type 必须与栏目 kind 兼容:page→single_page|article;list→list|list+category;channel→channel|list|list+category。
190
+ - 首页版块已有同名栏目 ⇒ 只做跳转(link_category_id),别再建一个自己维护内容的同名版块。
191
+ - 图标用 iconify 名(如 mdi:home-outline),同一个站内不能全一样。
192
+ - 栏目没绑模板时按 kind 兜底:list/channel→pages/index.html,page→pages/page.html。
193
+ (完整规范:本地跑 `wkgeo spec`;沙箱内加载 skill `wkgeo-site-spec`)
194
+ <!-- wkgeo:site-spec:prompt:end -->
195
+
196
+ ## 9. 变更记录
197
+
198
+ - 2026-11-21:首版。三处同源(`wkgeo spec` / `wkgeo init` 写的约定文件 / `wkgeo-site-spec` skill),规则逐条标 ✅ / 🚧。