dsh-zdiary-kit 0.8.3 → 0.9.0
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 +36 -7
- package/dist/cli.js +112 -11
- package/dist/config/store.js +37 -0
- package/dist/features/settings/client.js +21 -5
- package/dist/features/settings/feature.js +38 -12
- package/dist/features/zk-tools/feature.js +47 -4
- package/dist/lib/agents-template.js +3 -3
- package/dist/lib/dream.js +69 -1
- package/dist/lib/lint.js +36 -33
- package/dist/lib/memory-format.js +100 -0
- package/dist/lib/memory.js +81 -13
- package/dist/lib/notebook-config.js +188 -0
- package/dist/lib/notebook.js +324 -7
- package/docs/features/memory.md +32 -12
- package/docs/features/provisioning.md +32 -5
- package/docs/features/settings.md +9 -2
- package/docs/features/zk-tools.md +11 -2
- package/package.json +1 -1
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `.zk/config.toml` 的 group 只读解析。
|
|
3
|
+
*
|
|
4
|
+
* 为什么自己解析而不是引入 TOML 依赖:
|
|
5
|
+
* · 我们只关心 `[group."name"]` 的 `paths` / `template` 与它前面的注释;
|
|
6
|
+
* · 写回只做「替换 plugin-owned group 的 paths 行 / 组头改名」,用正则逐行改比
|
|
7
|
+
* 整份 TOML 序列化安全 —— 不会把用户的注释、顺序、自定义键重排掉。
|
|
8
|
+
*
|
|
9
|
+
* 约定:**解析不了就返回 null,绝不猜**。调用方把 null 当作「缺失 / 需要修」,
|
|
10
|
+
* 而不是按半份结果去改文件。
|
|
11
|
+
*/
|
|
12
|
+
/** `[group."name"]` / `[group.'name']` / `[group.bare]` 的组头(允许行尾注释) */
|
|
13
|
+
const GROUP_HEADER = /^\s*\[group\.(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_-]+))(?:\.(note|extra))?\]\s*(?:#.*)?$/;
|
|
14
|
+
function arrayOf(raw) {
|
|
15
|
+
const text = raw.trim();
|
|
16
|
+
if (!text.startsWith('[') || !text.endsWith(']'))
|
|
17
|
+
return null;
|
|
18
|
+
const inner = text.slice(1, -1).trim();
|
|
19
|
+
if (!inner)
|
|
20
|
+
return [];
|
|
21
|
+
const items = [];
|
|
22
|
+
let i = 0;
|
|
23
|
+
while (i < inner.length) {
|
|
24
|
+
while (i < inner.length && /[\s,]/.test(inner[i]))
|
|
25
|
+
i++;
|
|
26
|
+
if (i >= inner.length)
|
|
27
|
+
break;
|
|
28
|
+
const quote = inner[i];
|
|
29
|
+
if (quote !== '"' && quote !== "'")
|
|
30
|
+
return null;
|
|
31
|
+
i++;
|
|
32
|
+
const start = i;
|
|
33
|
+
while (i < inner.length && inner[i] !== quote) {
|
|
34
|
+
// 双引号字符串里的转义只支持 \";单引号是 TOML 字面量,没有转义
|
|
35
|
+
if (quote === '"' && inner[i] === '\\')
|
|
36
|
+
i++;
|
|
37
|
+
i++;
|
|
38
|
+
}
|
|
39
|
+
if (i >= inner.length)
|
|
40
|
+
return null;
|
|
41
|
+
items.push(inner.slice(start, i));
|
|
42
|
+
i++;
|
|
43
|
+
while (i < inner.length && inner[i] !== ',') {
|
|
44
|
+
if (!/\s/.test(inner[i]))
|
|
45
|
+
return null;
|
|
46
|
+
i++;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return items;
|
|
50
|
+
}
|
|
51
|
+
/** 值 → 单行原始值(去掉行尾注释;引号里的 # 不算注释) */
|
|
52
|
+
function valueOf(line) {
|
|
53
|
+
let quote = '';
|
|
54
|
+
for (let i = 0; i < line.length; i++) {
|
|
55
|
+
const ch = line[i];
|
|
56
|
+
if (quote) {
|
|
57
|
+
if (quote === '"' && ch === '\\') {
|
|
58
|
+
i++;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (ch === quote)
|
|
62
|
+
quote = '';
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (ch === '"' || ch === "'") {
|
|
66
|
+
quote = ch;
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (ch === '#')
|
|
70
|
+
return line.slice(0, i).trim();
|
|
71
|
+
}
|
|
72
|
+
return line.trim();
|
|
73
|
+
}
|
|
74
|
+
/** 解析整份 config.toml,返回 名字 → GroupBlock(同名重复时保留 duplicate 标记) */
|
|
75
|
+
export function parseGroupBlocks(text) {
|
|
76
|
+
const blocks = new Map();
|
|
77
|
+
const comments = [];
|
|
78
|
+
let current = null;
|
|
79
|
+
let section = null;
|
|
80
|
+
for (const line of text.split(/\r?\n/)) {
|
|
81
|
+
const header = GROUP_HEADER.exec(line);
|
|
82
|
+
if (header) {
|
|
83
|
+
const name = header[1] ?? header[2] ?? header[3] ?? '';
|
|
84
|
+
const sub = header[4];
|
|
85
|
+
if (!sub) {
|
|
86
|
+
const existing = blocks.get(name);
|
|
87
|
+
current = existing
|
|
88
|
+
? { ...existing, duplicate: true, paths: null, pathsState: 'invalid', template: null }
|
|
89
|
+
: { name, paths: null, pathsState: 'absent', template: null, comment: comments.length ? comments.join('\n') : null, header: line, duplicate: false };
|
|
90
|
+
blocks.set(name, current);
|
|
91
|
+
section = 'base';
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
// 子表必须跟在同名 base 后面;找不到就当没看见(TOML 本身也不合法)
|
|
95
|
+
current = blocks.get(name) ?? null;
|
|
96
|
+
section = current ? sub : null;
|
|
97
|
+
}
|
|
98
|
+
comments.length = 0;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (/^\s*\[/.test(line)) { // 其它 section:结束当前 group,但保留注释缓冲给下一段
|
|
102
|
+
current = null;
|
|
103
|
+
section = null;
|
|
104
|
+
comments.length = 0;
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const trimmed = line.trim();
|
|
108
|
+
if (trimmed.startsWith('#')) {
|
|
109
|
+
comments.push(trimmed);
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (!trimmed) {
|
|
113
|
+
comments.length = 0;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (!current || !section) {
|
|
117
|
+
comments.length = 0;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
// 重复 group:TOML 本身不合法,后续键一律不采信(保持 paths/template = null)
|
|
121
|
+
if (current.duplicate) {
|
|
122
|
+
comments.length = 0;
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const eq = trimmed.indexOf('=');
|
|
126
|
+
if (eq <= 0) {
|
|
127
|
+
comments.length = 0;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const key = trimmed.slice(0, eq).trim();
|
|
131
|
+
const value = valueOf(trimmed.slice(eq + 1));
|
|
132
|
+
if (section === 'base' && key === 'paths') {
|
|
133
|
+
current.paths = arrayOf(value);
|
|
134
|
+
current.pathsState = current.paths ? 'set' : 'invalid';
|
|
135
|
+
}
|
|
136
|
+
else if (section === 'note' && key === 'template') {
|
|
137
|
+
current.template = unquote(value);
|
|
138
|
+
}
|
|
139
|
+
comments.length = 0;
|
|
140
|
+
}
|
|
141
|
+
return blocks;
|
|
142
|
+
}
|
|
143
|
+
function unquote(value) {
|
|
144
|
+
if (value.length >= 2 && ((value[0] === '"' && value.endsWith('"')) || (value[0] === "'" && value.endsWith("'")))) {
|
|
145
|
+
return value.slice(1, -1);
|
|
146
|
+
}
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
/** 组头是否是 dsh-zdiary-kit 自己写的(有它才允许 `--fix` 改) */
|
|
150
|
+
export function isPluginOwned(block) {
|
|
151
|
+
return !!block.comment && block.comment.includes('dsh-zdiary-kit');
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* zk 实际用于归组的路径。没写 `paths` 等价于 `[名字]`(zk 生成的 config 注释原话:
|
|
155
|
+
* "Omitting `paths` is equivalent to providing a single path equal to the name of the group"),
|
|
156
|
+
* 所以缺键不是「没有路径」,而是按同名目录占着 —— 冲突判断必须算上它。
|
|
157
|
+
* 解析失败 / 重复组返回 null(没有可信路径,不猜)。
|
|
158
|
+
*/
|
|
159
|
+
export function effectivePaths(block) {
|
|
160
|
+
if (block.duplicate)
|
|
161
|
+
return null;
|
|
162
|
+
if (block.pathsState === 'set')
|
|
163
|
+
return block.paths;
|
|
164
|
+
return block.pathsState === 'absent' ? [block.name] : null;
|
|
165
|
+
}
|
|
166
|
+
/** 路径归一化:`./notes/` 与 `notes` 是同一个目录 */
|
|
167
|
+
export function normGroupPath(rel) {
|
|
168
|
+
const clean = rel.replace(/\\/g, '/').replace(/^\.\/+/, '').replace(/\/+/g, '/').replace(/\/+$/, '');
|
|
169
|
+
return clean === '.' ? '' : clean;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* 两条路径是不是同一个目录(`./notes/` 与 `notes` 算同一个)。
|
|
173
|
+
*
|
|
174
|
+
* 只认「完全一样」:父子目录是**合法**的 —— zk 0.15 按最具体的路径归组,
|
|
175
|
+
* `notes` 与 `notes/concepts` 共存时,子目录里的笔记走后者(真机验证过)。
|
|
176
|
+
* 只有两条路径一模一样时,zk 命中哪个 group 就只剩实现细节了(实测:先定义的那个赢)。
|
|
177
|
+
*/
|
|
178
|
+
export function sameGroupPath(a, b) {
|
|
179
|
+
return normGroupPath(a) === normGroupPath(b);
|
|
180
|
+
}
|
|
181
|
+
/** 两组 paths 是否一致(顺序无关;null 一律不一致) */
|
|
182
|
+
export function samePaths(actual, expected) {
|
|
183
|
+
if (!actual || actual.length !== expected.length)
|
|
184
|
+
return false;
|
|
185
|
+
const a = actual.map(normGroupPath).sort();
|
|
186
|
+
const b = expected.map(normGroupPath).sort();
|
|
187
|
+
return a.every((p, i) => p === b[i]);
|
|
188
|
+
}
|
package/dist/lib/notebook.js
CHANGED
|
@@ -13,6 +13,7 @@ import fs from 'node:fs';
|
|
|
13
13
|
import path from 'node:path';
|
|
14
14
|
import { ZkError, zk } from './zk.js';
|
|
15
15
|
import { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, WORKFLOW_TEMPLATE } from './agents-template.js';
|
|
16
|
+
import { effectivePaths, isPluginOwned, normGroupPath, parseGroupBlocks, sameGroupPath, samePaths } from './notebook-config.js';
|
|
16
17
|
export { AGENTS_TEMPLATE, AGENTS_TEMPLATE_FLAT, WORKFLOW_TEMPLATE } from './agents-template.js';
|
|
17
18
|
export const DAILY_TEMPLATE = `# {{format-date now "%Y-%m-%d"}}
|
|
18
19
|
|
|
@@ -123,7 +124,7 @@ export function newNoteDir(cfg, input = {}) {
|
|
|
123
124
|
const given = input.dir ? normDir(input.dir) : '';
|
|
124
125
|
if (cfg.structure !== 'layered')
|
|
125
126
|
return given || normDir(cfg.notesDir);
|
|
126
|
-
const groups =
|
|
127
|
+
const groups = expectedGroups(cfg).flatMap((group) => group.paths.map(normDir));
|
|
127
128
|
const hint = `可选目录:${groups.join(' / ')}(group 下的子目录也行);` +
|
|
128
129
|
`落在 ${cfg.notesDir}/ 根不会套模板,没有 frontmatter,文件名是随机 id`;
|
|
129
130
|
const dir = given || (input.type ? noteKindDir(cfg.notesDir, input.type) : null);
|
|
@@ -153,6 +154,10 @@ function layeredGroups(cfg) {
|
|
|
153
154
|
named('pattern', 'entry.md', 'expert'),
|
|
154
155
|
];
|
|
155
156
|
}
|
|
157
|
+
/** 当前结构期望的 group(flat 一个,layered 五个);顺序与目录一致 */
|
|
158
|
+
export function expectedGroups(cfg) {
|
|
159
|
+
return cfg.structure === 'layered' ? layeredGroups(cfg) : [dailyGroup(cfg)];
|
|
160
|
+
}
|
|
156
161
|
/** 当前结构需要的目录(相对笔记本;flat 只有笔记与日记两个) */
|
|
157
162
|
export function structureDirs(cfg) {
|
|
158
163
|
const rels = [cfg.notesDir, cfg.dailyDir];
|
|
@@ -161,6 +166,96 @@ export function structureDirs(cfg) {
|
|
|
161
166
|
}
|
|
162
167
|
return [...new Set(rels)];
|
|
163
168
|
}
|
|
169
|
+
/** 同一批 group 两两查「同一条路径」:每对只报一次 */
|
|
170
|
+
function overlapsOf(entries) {
|
|
171
|
+
const out = [];
|
|
172
|
+
for (let i = 0; i < entries.length; i++) {
|
|
173
|
+
const a = entries[i];
|
|
174
|
+
if (!a)
|
|
175
|
+
continue;
|
|
176
|
+
for (let j = i + 1; j < entries.length; j++) {
|
|
177
|
+
const b = entries[j];
|
|
178
|
+
if (!b)
|
|
179
|
+
continue;
|
|
180
|
+
const shared = (a.paths ?? []).find((x) => (b.paths ?? []).some((y) => sameGroupPath(x, y)));
|
|
181
|
+
if (shared !== undefined)
|
|
182
|
+
out.push({ a: a.name, b: b.name, path: normGroupPath(shared) });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
function groupStatuses(groups, blocks) {
|
|
188
|
+
return groups.map((group) => {
|
|
189
|
+
const block = blocks?.get(group.name) ?? null;
|
|
190
|
+
// 缺 paths 的 group 按同名目录占着(zk 语义):冲突判断必须算上,否则会追加同路径组
|
|
191
|
+
const actualPaths = block ? effectivePaths(block) : null;
|
|
192
|
+
const actualTemplate = block?.template ?? null;
|
|
193
|
+
const conflict = block ? undefined : [...(blocks?.values() ?? [])].find((candidate) => effectivePaths(candidate)?.some((actual) => group.paths.some((expected) => sameGroupPath(actual, expected))))?.name;
|
|
194
|
+
return {
|
|
195
|
+
name: group.name,
|
|
196
|
+
expectedPaths: group.paths,
|
|
197
|
+
actualPaths,
|
|
198
|
+
pathsOk: !!block && !block.duplicate && samePaths(actualPaths, group.paths),
|
|
199
|
+
present: !!block,
|
|
200
|
+
expectedTemplate: group.template,
|
|
201
|
+
actualTemplate,
|
|
202
|
+
templateOk: !!block && !block.duplicate && actualTemplate === group.template,
|
|
203
|
+
duplicate: !!block?.duplicate,
|
|
204
|
+
owned: !!block && isPluginOwned(block),
|
|
205
|
+
...(conflict ? { conflict } : {}),
|
|
206
|
+
};
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* 重叠说明(给人看的一行);level = config 是配置本身冲突、file 是 config.toml 里已经撞了。
|
|
211
|
+
* 同一对只报一次:两边都说一遍只会让设置页的告警更长。
|
|
212
|
+
* 父子目录不算冲突(zk 按最具体的路径归组),所以措辞只说「同一条路径」。
|
|
213
|
+
*/
|
|
214
|
+
export function groupOverlapNotes(st) {
|
|
215
|
+
const out = [];
|
|
216
|
+
const seen = new Set();
|
|
217
|
+
const key = (o) => [o.a, o.b].sort().join('|');
|
|
218
|
+
for (const o of st.expectedOverlaps) {
|
|
219
|
+
seen.add(key(o));
|
|
220
|
+
out.push({
|
|
221
|
+
level: 'config',
|
|
222
|
+
text: `group "${o.a}" 与 "${o.b}" 都用 ${o.path} —— 改 dailyDir / notesDir,或换结构(groups --fix 不会写)`,
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
for (const o of st.actualOverlaps) {
|
|
226
|
+
if (seen.has(key(o)))
|
|
227
|
+
continue;
|
|
228
|
+
out.push({
|
|
229
|
+
level: 'file',
|
|
230
|
+
text: `group "${o.a}" 与 "${o.b}" 的 paths 都是 ${o.path} —— 手动检查 .zk/config.toml`,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
function groupWarningsOf(groups, st) {
|
|
236
|
+
const out = [];
|
|
237
|
+
for (const group of groups) {
|
|
238
|
+
if (!group.present) {
|
|
239
|
+
out.push(group.conflict
|
|
240
|
+
? `缺 group "${group.name}":路径 ${group.expectedPaths.join('、')} 已被 group "${group.conflict}" 占用 —— 跑 zk-kit groups --fix`
|
|
241
|
+
: `缺 group "${group.name}"(期望 ${group.expectedPaths.join('、')})—— 跑 zk-kit groups --fix`);
|
|
242
|
+
}
|
|
243
|
+
else if (group.duplicate) {
|
|
244
|
+
out.push(`group "${group.name}" 重复出现,解析不了 —— 手动检查 .zk/config.toml`);
|
|
245
|
+
}
|
|
246
|
+
else if (!group.pathsOk) {
|
|
247
|
+
out.push(`group "${group.name}" ${pathsDiff(group.expectedPaths, group.actualPaths)}`);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
for (const note of groupOverlapNotes(st))
|
|
251
|
+
out.push(note.text);
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
/** 期望 / 实际 paths 的差异尾巴;actual 为 null = 解析不了(多行数组 / 未加引号的项),--fix 也不猜 */
|
|
255
|
+
function pathsDiff(expected, actual) {
|
|
256
|
+
return `期望 ${expected.join('、')},实际 ${actual?.join('、') ?? '解析不了'}` +
|
|
257
|
+
(actual === null ? '(可能是多行数组)—— 手动编辑 .zk/config.toml' : ' —— 跑 zk-kit groups --fix');
|
|
258
|
+
}
|
|
164
259
|
/** 结构一致性检查:只报告,不建目录、不改配置(设置页据此显示告警) */
|
|
165
260
|
export function structureStatus(cfg) {
|
|
166
261
|
const dirs = structureDirs(cfg);
|
|
@@ -177,6 +272,21 @@ export function structureStatus(cfg) {
|
|
|
177
272
|
.filter((rel) => !dirs.map(normDir).includes(rel))
|
|
178
273
|
.filter((rel) => fs.existsSync(path.join(cfg.notebook, rel)))
|
|
179
274
|
.sort();
|
|
275
|
+
let blocks = null;
|
|
276
|
+
try {
|
|
277
|
+
blocks = parseGroupBlocks(fs.readFileSync(path.join(cfg.notebook, '.zk', 'config.toml'), 'utf8'));
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
blocks = null;
|
|
281
|
+
}
|
|
282
|
+
const expected = expectedGroups(cfg);
|
|
283
|
+
const groups = groupStatuses(expected, blocks);
|
|
284
|
+
const expectedOverlaps = overlapsOf(expected);
|
|
285
|
+
// 重复出现的组解析不出 paths,不参与「文件里已经撞了」的判断;缺 paths 的按同名目录算(zk 语义)
|
|
286
|
+
const actualOverlaps = blocks
|
|
287
|
+
? overlapsOf([...blocks.values()].filter((block) => !block.duplicate)
|
|
288
|
+
.map((block) => ({ name: block.name, paths: effectivePaths(block) })))
|
|
289
|
+
: [];
|
|
180
290
|
return {
|
|
181
291
|
mode: cfg.structure,
|
|
182
292
|
dirs,
|
|
@@ -184,12 +294,14 @@ export function structureStatus(cfg) {
|
|
|
184
294
|
extra,
|
|
185
295
|
ready: missing.length === 0,
|
|
186
296
|
agents: { path: agentsPath, required, present: fs.existsSync(agentsPath) },
|
|
297
|
+
groups,
|
|
298
|
+
expectedOverlaps,
|
|
299
|
+
actualOverlaps,
|
|
300
|
+
groupsOk: !!blocks && groups.every((group) => group.present && group.pathsOk) &&
|
|
301
|
+
expectedOverlaps.length === 0 && actualOverlaps.length === 0,
|
|
302
|
+
groupWarnings: blocks ? groupWarningsOf(groups, { expectedOverlaps, actualOverlaps }) : [],
|
|
187
303
|
};
|
|
188
304
|
}
|
|
189
|
-
function hasGroup(configToml, group) {
|
|
190
|
-
const escaped = group.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
191
|
-
return new RegExp(`^\\[group\\."?${escaped}"?\\]`, 'm').test(configToml);
|
|
192
|
-
}
|
|
193
305
|
/** 建目录,返回真正新建的那些(相对笔记本) */
|
|
194
306
|
function ensureDirs(cfg, rels) {
|
|
195
307
|
const created = [];
|
|
@@ -255,16 +367,44 @@ export async function ensureNotebook(cfg, signal, opts = {}) {
|
|
|
255
367
|
fs.writeFileSync(workflowFile, WORKFLOW_TEMPLATE, 'utf8');
|
|
256
368
|
workflowWritten = true;
|
|
257
369
|
}
|
|
258
|
-
const groups =
|
|
370
|
+
const groups = expectedGroups(cfg);
|
|
259
371
|
let configText = fs.readFileSync(configFile, 'utf8');
|
|
372
|
+
const blocks = parseGroupBlocks(configText);
|
|
260
373
|
const groupsAdded = [];
|
|
374
|
+
const groupWarnings = [];
|
|
261
375
|
for (const group of groups) {
|
|
262
|
-
|
|
376
|
+
const block = blocks.get(group.name);
|
|
377
|
+
if (block) {
|
|
378
|
+
// 已有 group 一律不重写(用户可能改过 template / extra),只报告与配置的差异
|
|
379
|
+
if (block.duplicate) {
|
|
380
|
+
groupWarnings.push(`group "${group.name}" 重复出现,解析不了 —— 手动检查 .zk/config.toml`);
|
|
381
|
+
}
|
|
382
|
+
else if (!samePaths(effectivePaths(block), group.paths)) {
|
|
383
|
+
groupWarnings.push(`group "${group.name}" ${pathsDiff(group.paths, effectivePaths(block))}`);
|
|
384
|
+
}
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
// 新 group 的路径已经被别的 group 占着(典型:只改 dailyGroup 不改 dailyDir;缺 paths 的按同名目录也算):
|
|
388
|
+
// 再追加就是两个 group 用同一条路径,zk 命中哪个模板就只剩实现细节了 —— 只报告,不写
|
|
389
|
+
const owner = [...blocks.values()].find((candidate) => effectivePaths(candidate)?.some((actual) => group.paths.some((expected) => sameGroupPath(actual, expected))));
|
|
390
|
+
if (owner) {
|
|
391
|
+
groupWarnings.push(`group "${group.name}" 没追加:路径 ${group.paths.join('、')} 已被 group "${owner.name}" 占用` +
|
|
392
|
+
'(跑 zk-kit groups --fix)');
|
|
263
393
|
continue;
|
|
394
|
+
}
|
|
264
395
|
const prefix = configText.endsWith('\n') ? '' : '\n';
|
|
265
396
|
configText += prefix + groupSection(group);
|
|
266
397
|
fs.writeFileSync(configFile, configText, 'utf8');
|
|
267
398
|
groupsAdded.push(group.name);
|
|
399
|
+
blocks.set(group.name, {
|
|
400
|
+
name: group.name,
|
|
401
|
+
paths: group.paths.map(normGroupPath),
|
|
402
|
+
pathsState: 'set',
|
|
403
|
+
template: group.template,
|
|
404
|
+
comment: `# ${group.comment}`,
|
|
405
|
+
header: `[group."${group.name}"]`,
|
|
406
|
+
duplicate: false,
|
|
407
|
+
});
|
|
268
408
|
}
|
|
269
409
|
return {
|
|
270
410
|
notebook: cfg.notebook,
|
|
@@ -274,7 +414,184 @@ export async function ensureNotebook(cfg, signal, opts = {}) {
|
|
|
274
414
|
dirsCreated,
|
|
275
415
|
templatesWritten,
|
|
276
416
|
groupsAdded,
|
|
417
|
+
groupWarnings,
|
|
277
418
|
agentsWritten,
|
|
278
419
|
workflowWritten,
|
|
279
420
|
};
|
|
280
421
|
}
|
|
422
|
+
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
423
|
+
/** 只改组头名字(连同 .note / .extra 子表;裸键 / 引号写法都认),其它行一字不动 */
|
|
424
|
+
function renameGroup(text, from, to) {
|
|
425
|
+
const esc = escapeRe(from);
|
|
426
|
+
const re = new RegExp(`(\\[group\\.)(?:"${esc}"|'${esc}'|${esc}(?=[.\\]]))`, 'g');
|
|
427
|
+
return text.replace(re, `$1"${to}"`);
|
|
428
|
+
}
|
|
429
|
+
/** 只替换 base group 的 paths 行;多行数组 / 找不到都不猜(返回 null) */
|
|
430
|
+
function replacePaths(text, name, paths) {
|
|
431
|
+
const lines = text.split('\n');
|
|
432
|
+
const headerRe = /^\s*\[group\.(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_-]+))(?:\.(note|extra))?\]\s*(?:#.*)?$/;
|
|
433
|
+
let start = -1;
|
|
434
|
+
for (let i = 0; i < lines.length; i++) {
|
|
435
|
+
const m = headerRe.exec(lines[i]);
|
|
436
|
+
if (!m || m[4])
|
|
437
|
+
continue;
|
|
438
|
+
if ((m[1] ?? m[2] ?? m[3]) === name) {
|
|
439
|
+
start = i;
|
|
440
|
+
break;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
if (start < 0)
|
|
444
|
+
return null;
|
|
445
|
+
let end = lines.length;
|
|
446
|
+
for (let i = start + 1; i < lines.length; i++) {
|
|
447
|
+
if (/^\s*\[/.test(lines[i])) {
|
|
448
|
+
end = i;
|
|
449
|
+
break;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
const value = `[${paths.map((p) => JSON.stringify(p)).join(', ')}]`;
|
|
453
|
+
for (let i = start + 1; i < end; i++) {
|
|
454
|
+
const m = /^(\s*paths\s*=\s*)(\[[^\]]*\])(\s*(?:#.*)?)$/.exec(lines[i]);
|
|
455
|
+
if (m) {
|
|
456
|
+
lines[i] = m[1] + value + m[3];
|
|
457
|
+
return lines.join('\n');
|
|
458
|
+
}
|
|
459
|
+
if (/^\s*paths\s*=/.test(lines[i]))
|
|
460
|
+
return null; // 多行数组:不在本轮猜着改
|
|
461
|
+
}
|
|
462
|
+
lines.splice(start + 1, 0, `paths = ${value}`);
|
|
463
|
+
return lines.join('\n');
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* 显式修复 group 配置(`zk-kit groups --fix`):
|
|
467
|
+
* · 只改 dsh-zdiary-kit 自己写的 group(组头前有 `dsh-zdiary-kit` 注释);
|
|
468
|
+
* · 只改 `paths` 行,或把同路径的旧组头改名(dailyGroup 变更);
|
|
469
|
+
* · 写下去会让两个 group 用同一条路径时一律不写(父子目录不算):
|
|
470
|
+
* 期望路径自己就冲突时整轮不改,期望路径被别的 group 占着时只跳过那一个;
|
|
471
|
+
* · 用户自定义的 template / extra / 注释 / 顺序一律不动;
|
|
472
|
+
* · 写前备份 `.zk/config.toml.bak`,写临时文件后 rename。
|
|
473
|
+
*/
|
|
474
|
+
export function fixGroupConfig(cfg) {
|
|
475
|
+
const file = path.join(cfg.notebook, '.zk', 'config.toml');
|
|
476
|
+
if (!fs.existsSync(file)) {
|
|
477
|
+
throw new ZkError('还没有 .zk/config.toml —— 先跑 zk-kit init');
|
|
478
|
+
}
|
|
479
|
+
const original = fs.readFileSync(file, 'utf8');
|
|
480
|
+
let text = original;
|
|
481
|
+
const updates = [];
|
|
482
|
+
const warnings = [];
|
|
483
|
+
const groups = expectedGroups(cfg);
|
|
484
|
+
const expectedNames = new Set(groups.map((group) => group.name));
|
|
485
|
+
// 期望路径自己就撞了(典型:dailyDir 与某个 group 的路径一样):一个都不写。
|
|
486
|
+
// 写下去就是两个 group 用同一条路径,zk 命中哪个模板就只剩实现细节了 —— 这比「没改」更难查。
|
|
487
|
+
const expectedOverlaps = overlapsOf(groups);
|
|
488
|
+
if (expectedOverlaps.length > 0) {
|
|
489
|
+
for (const note of groupOverlapNotes({ expectedOverlaps, actualOverlaps: [] }))
|
|
490
|
+
warnings.push(note.text);
|
|
491
|
+
const involved = new Set(expectedOverlaps.flatMap((overlap) => [overlap.a, overlap.b]));
|
|
492
|
+
for (const group of groups) {
|
|
493
|
+
if (!involved.has(group.name))
|
|
494
|
+
continue;
|
|
495
|
+
updates.push({
|
|
496
|
+
name: group.name,
|
|
497
|
+
action: 'skip',
|
|
498
|
+
expectedPaths: group.paths,
|
|
499
|
+
reason: '配置里有两个 group 要用同一条路径,先改 dailyDir / notesDir 或换结构',
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
return { notebook: cfg.notebook, changed: false, backup: null, updates, warnings };
|
|
503
|
+
}
|
|
504
|
+
// 1. 缺失的 group:先认领同路径的旧 plugin group(改组头名),再看路径是否被占
|
|
505
|
+
for (const group of groups) {
|
|
506
|
+
const blocks = parseGroupBlocks(text);
|
|
507
|
+
if (blocks.has(group.name))
|
|
508
|
+
continue;
|
|
509
|
+
const stale = [...blocks.values()].filter((block) => isPluginOwned(block) && !expectedNames.has(block.name));
|
|
510
|
+
const same = stale.find((block) => samePaths(effectivePaths(block), group.paths));
|
|
511
|
+
if (same) {
|
|
512
|
+
text = renameGroup(text, same.name, group.name);
|
|
513
|
+
updates.push({
|
|
514
|
+
name: group.name,
|
|
515
|
+
action: 'rename',
|
|
516
|
+
from: same.name,
|
|
517
|
+
expectedPaths: group.paths,
|
|
518
|
+
actualPaths: effectivePaths(same),
|
|
519
|
+
});
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
// dailyGroup 改名 + dailyDir 同时改:认不出旧组,也不冒险追加第二个日记组
|
|
523
|
+
const staleDaily = group.template === 'daily.md' ? stale.find((block) => block.template === 'daily.md') : undefined;
|
|
524
|
+
if (staleDaily) {
|
|
525
|
+
const reason = `旧日记 group "${staleDaily.name}" 的路径是 ${effectivePaths(staleDaily)?.join('、') ?? '解析不了'},` +
|
|
526
|
+
`与期望 ${group.paths.join('、')} 不一致 —— 先手动确认改名与路径`;
|
|
527
|
+
warnings.push(reason);
|
|
528
|
+
updates.push({ name: group.name, action: 'skip', expectedPaths: group.paths, reason });
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
531
|
+
const owner = [...blocks.values()].find((block) => effectivePaths(block)?.some((actual) => group.paths.some((expected) => sameGroupPath(actual, expected))));
|
|
532
|
+
if (owner) {
|
|
533
|
+
const reason = `路径 ${group.paths.join('、')} 已被 group "${owner.name}" 占用 —— 先手动处理这个 group`;
|
|
534
|
+
warnings.push(`group "${group.name}" 没追加:${reason}`);
|
|
535
|
+
updates.push({ name: group.name, action: 'skip', expectedPaths: group.paths, reason });
|
|
536
|
+
continue;
|
|
537
|
+
}
|
|
538
|
+
const prefix = text.endsWith('\n') ? '' : '\n';
|
|
539
|
+
text += prefix + groupSection(group);
|
|
540
|
+
updates.push({ name: group.name, action: 'append', expectedPaths: group.paths });
|
|
541
|
+
}
|
|
542
|
+
// 2. 已存在的 group:只改 plugin-owned 的 paths 行
|
|
543
|
+
for (const group of groups) {
|
|
544
|
+
const current = parseGroupBlocks(text);
|
|
545
|
+
const block = current.get(group.name);
|
|
546
|
+
if (!block)
|
|
547
|
+
continue;
|
|
548
|
+
if (block.duplicate) {
|
|
549
|
+
const reason = `group "${group.name}" 重复出现,解析不了 —— 手动检查 .zk/config.toml`;
|
|
550
|
+
warnings.push(reason);
|
|
551
|
+
updates.push({ name: group.name, action: 'skip', expectedPaths: group.paths, reason });
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
const actual = effectivePaths(block);
|
|
555
|
+
if (samePaths(actual, group.paths))
|
|
556
|
+
continue;
|
|
557
|
+
if (!isPluginOwned(block)) {
|
|
558
|
+
const reason = `不是插件建的 group,paths 未改(期望 ${group.paths.join('、')},实际 ${actual?.join('、') ?? '解析不了'})`;
|
|
559
|
+
warnings.push(`group "${group.name}":${reason}`);
|
|
560
|
+
updates.push({ name: group.name, action: 'skip', expectedPaths: group.paths, actualPaths: actual, reason });
|
|
561
|
+
continue;
|
|
562
|
+
}
|
|
563
|
+
// 期望路径被别的 group 占着:不替换 —— 之前只拦了「追加」,替换同样会造出两个 group 用同一条路径。
|
|
564
|
+
// 期望内部的 group 会自己走到期望路径,不算占用;用户建的 / 上一版留下的 group 才拦。
|
|
565
|
+
const rival = [...current.values()].find((candidate) => candidate.name !== group.name &&
|
|
566
|
+
!(expectedNames.has(candidate.name) && isPluginOwned(candidate)) &&
|
|
567
|
+
effectivePaths(candidate)?.some((p) => group.paths.some((expected) => sameGroupPath(p, expected))));
|
|
568
|
+
if (rival) {
|
|
569
|
+
const reason = `路径 ${group.paths.join('、')} 已被 group "${rival.name}" 占用(${effectivePaths(rival)?.join('、') ?? '解析不了'}),paths 未改 —— 先手动处理这个 group`;
|
|
570
|
+
warnings.push(`group "${group.name}":${reason}`);
|
|
571
|
+
updates.push({ name: group.name, action: 'skip', expectedPaths: group.paths, actualPaths: actual, reason });
|
|
572
|
+
continue;
|
|
573
|
+
}
|
|
574
|
+
const next = replacePaths(text, group.name, group.paths);
|
|
575
|
+
if (next === null) {
|
|
576
|
+
const reason = 'paths 行解析不了(可能是多行数组),未改 —— 手动编辑 .zk/config.toml';
|
|
577
|
+
warnings.push(`group "${group.name}":${reason}`);
|
|
578
|
+
updates.push({ name: group.name, action: 'skip', expectedPaths: group.paths, actualPaths: actual, reason });
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
text = next;
|
|
582
|
+
updates.push({
|
|
583
|
+
name: group.name,
|
|
584
|
+
action: 'paths',
|
|
585
|
+
expectedPaths: group.paths,
|
|
586
|
+
actualPaths: actual,
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
if (text === original)
|
|
590
|
+
return { notebook: cfg.notebook, changed: false, backup: null, updates, warnings };
|
|
591
|
+
const backup = `${file}.bak`;
|
|
592
|
+
fs.copyFileSync(file, backup);
|
|
593
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
594
|
+
fs.writeFileSync(tmp, text, 'utf8');
|
|
595
|
+
fs.renameSync(tmp, file);
|
|
596
|
+
return { notebook: cfg.notebook, changed: true, backup, updates, warnings };
|
|
597
|
+
}
|