dsh-zdiary-kit 0.0.0-stage → 0.6.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.
@@ -0,0 +1,267 @@
1
+ /**
2
+ * 配置:默认值 + 白名单 + 归一化(宿主、设置页、CLI 三处共用这一份)。
3
+ *
4
+ * 只有一个配置文件:~/.dsh/zdiary/zdiary.config.json。
5
+ * 设置页通过 keys 白名单合并 —— 加字段只改这里,不存在第二处。
6
+ *
7
+ * 多笔记本:`notebooks` 是「名字 → {path, structure}」,`active` 是当前那个的名字。
8
+ * 路径与结构都是**笔记本自己的属性**,跟着条目落盘;派生值只有两个,都不落盘、都不可写:
9
+ * · `notebook` = notebooks[active].path 解析后的绝对路径;
10
+ * · `structure` = notebooks[active].structure(当前笔记本的结构模式)。
11
+ * 磁盘上笔记本只有一个真相,就是 notebooks + active —— 没有第二个能盖过它的键。
12
+ * 老配置只有 `notebook`(或 structure 是全局键):读进来一次性迁进 `notebooks.default`,
13
+ * 之后就不再有双向合并 —— notebooks 存在时,散落的 `notebook` 顶层键只当没看见。
14
+ */
15
+ import { CFG_FILE, CFG_LOCK, defaultNotebook, expandHome, processWorkspace, resolveInWorkspace } from './paths.js';
16
+ import { fileStamp } from '../lib/file-stamp.js';
17
+ import { withFileLockSync } from '../lib/lock.js';
18
+ import { readJson, writeJson } from '../lib/json-file.js';
19
+ /** 默认笔记本的名字(老配置迁移过来的那个也叫这个) */
20
+ export const DEFAULT_NOTEBOOK_NAME = 'default';
21
+ /** 笔记本名:只接受文件名友好的字符,1-32 个 */
22
+ const NOTEBOOK_NAME_RE = /^[A-Za-z0-9_-]{1,32}$/;
23
+ /** 上限 50 个:再多就是填错了,别让配置无限长 */
24
+ const MAX_NOTEBOOKS = 50;
25
+ /** 落盘与 patch 里的派生键:notebook 纯派生、structure 有专门语义、notebooks 整体替换 —— 都不走通用合并 */
26
+ const DERIVED_KEYS = new Set(['notebook', 'structure', 'notebooks']);
27
+ /** 名字合法吗(add / use 前先问,别让非法键进 JSON) */
28
+ export function isNotebookName(name) {
29
+ return NOTEBOOK_NAME_RE.test(String(name ?? '').trim());
30
+ }
31
+ export const DEFAULTS = {
32
+ // 两个派生值:normalizeConfig 算出来,这里只是占位(不参与落盘,也不单独使用)
33
+ notebook: '',
34
+ notebooks: { [DEFAULT_NOTEBOOK_NAME]: { path: '', structure: 'flat' } },
35
+ active: DEFAULT_NOTEBOOK_NAME,
36
+ structure: 'flat',
37
+ notesDir: 'notes',
38
+ dailyDir: 'journal',
39
+ dailyGroup: 'daily',
40
+ defaultTags: [],
41
+ maxReadChars: 20_000,
42
+ memoryBudgetWords: 500,
43
+ archiveDir: 'archive',
44
+ zkVersion: '0.15.7',
45
+ zkPath: '',
46
+ };
47
+ export const CONFIG_KEYS = Object.keys(DEFAULTS);
48
+ const clamp = (n, min, max, fallback) => Number.isFinite(n) ? Math.min(max, Math.max(min, Math.trunc(n))) : fallback;
49
+ /** 子目录只接受相对路径(防止 `/` 或 `../` 把笔记写到笔记本外面) */
50
+ function relativeDir(raw, fallback) {
51
+ const s = String(raw ?? '').trim().replace(/\\/g, '/').replace(/^\/+/, '');
52
+ if (!s)
53
+ return fallback;
54
+ const parts = s.split('/').filter((p) => p && p !== '.' && p !== '..');
55
+ return parts.length ? parts.join('/') : fallback;
56
+ }
57
+ function tags(raw) {
58
+ const list = Array.isArray(raw) ? raw : String(raw ?? '').split(/[,,\s]+/);
59
+ const out = [];
60
+ for (const item of list) {
61
+ const t = String(item ?? '').trim().replace(/^#+/, '');
62
+ if (!t || /[\s#]/.test(t))
63
+ continue;
64
+ if (!out.includes(t))
65
+ out.push(t);
66
+ if (out.length >= 20)
67
+ break;
68
+ }
69
+ return out;
70
+ }
71
+ /** 结构值:只认 flat / layered,其它一律退回 fallback(structure=xyz → flat,回显里会点名) */
72
+ function structureOf(raw, fallback) {
73
+ return raw === 'layered' ? 'layered' : raw === 'flat' ? 'flat' : fallback;
74
+ }
75
+ /** 一条笔记本记录:新写法 {path, structure},老写法裸路径字符串也认(structure 继承 fallback) */
76
+ function entryOf(value, fallback) {
77
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
78
+ const v = value;
79
+ return { path: String(v.path ?? '').trim(), structure: structureOf(v.structure, fallback) };
80
+ }
81
+ return { path: String(value ?? '').trim(), structure: fallback };
82
+ }
83
+ /**
84
+ * 名字 → 记录;非法名字与非法值直接丢掉(不 throw)。
85
+ * 条目没写 structure 时沿用同名旧记录的,再退 base —— 整体替换时不悄悄改别人的结构。
86
+ */
87
+ function notebookEntries(raw, prev, base) {
88
+ const out = {};
89
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
90
+ return out;
91
+ for (const [key, value] of Object.entries(raw)) {
92
+ const name = String(key ?? '').trim();
93
+ if (!NOTEBOOK_NAME_RE.test(name))
94
+ continue;
95
+ out[name] = entryOf(value, prev[name]?.structure ?? base);
96
+ if (Object.keys(out).length >= MAX_NOTEBOOKS)
97
+ break;
98
+ }
99
+ return out;
100
+ }
101
+ /** 笔记本路径:空 = 工作区里的默认位置;相对路径按工作区解析(不是进程 cwd) */
102
+ function notebookPath(raw, workspace) {
103
+ const s = String(raw ?? '').trim();
104
+ return s ? resolveInWorkspace(expandHome(s), workspace) : defaultNotebook(workspace);
105
+ }
106
+ /**
107
+ * 任意输入 → 合法 Config(永不 throw:设置页传垃圾也只落一个安全值)。
108
+ *
109
+ * workspace 决定「空路径 / 相对路径」落在哪:工具调用传会话 cwd,其余场景默认进程工作区。
110
+ * 显式写死的绝对路径不受它影响 —— 显式配置优先。
111
+ */
112
+ export function normalizeConfig(raw, workspace = processWorkspace()) {
113
+ const src = (raw && typeof raw === 'object' ? raw : {});
114
+ // 老配置里的全局 structure:只当「条目缺省」的 fallback 用;条目自己的 structure 优先
115
+ const base = structureOf(src.structure, 'flat');
116
+ let notebooks = notebookEntries(src.notebooks, {}, base);
117
+ // 老配置只有 notebook:读进来就是 notebooks.default 的路径(一次性迁移)。
118
+ // notebooks 已存在时顶层 notebook 是历史残留 —— 一个字都不听它(磁盘上笔记本只有一个真相)。
119
+ if (Object.keys(notebooks).length === 0) {
120
+ notebooks = { [DEFAULT_NOTEBOOK_NAME]: entryOf(String(src.notebook ?? ''), base) };
121
+ }
122
+ const activeRaw = String(src.active ?? '').trim();
123
+ const active = activeRaw && NOTEBOOK_NAME_RE.test(activeRaw) && activeRaw in notebooks
124
+ ? activeRaw
125
+ : DEFAULT_NOTEBOOK_NAME in notebooks ? DEFAULT_NOTEBOOK_NAME : (Object.keys(notebooks)[0] ?? DEFAULT_NOTEBOOK_NAME);
126
+ const entry = notebooks[active] ?? { path: '', structure: 'flat' };
127
+ return {
128
+ notebook: notebookPath(entry.path, workspace),
129
+ notebooks,
130
+ active,
131
+ structure: entry.structure,
132
+ notesDir: relativeDir(src.notesDir, DEFAULTS.notesDir),
133
+ dailyDir: relativeDir(src.dailyDir, DEFAULTS.dailyDir),
134
+ dailyGroup: /^[A-Za-z0-9_-]{1,32}$/.test(String(src.dailyGroup ?? '')) ? String(src.dailyGroup) : DEFAULTS.dailyGroup,
135
+ defaultTags: tags(src.defaultTags),
136
+ maxReadChars: clamp(Number(src.maxReadChars), 1000, 200_000, DEFAULTS.maxReadChars),
137
+ memoryBudgetWords: clamp(Number(src.memoryBudgetWords), 50, 2000, DEFAULTS.memoryBudgetWords),
138
+ archiveDir: relativeDir(src.archiveDir, DEFAULTS.archiveDir),
139
+ zkVersion: /^\d+\.\d+\.\d+$/.test(String(src.zkVersion ?? '').trim().replace(/^v/i, ''))
140
+ ? String(src.zkVersion).trim().replace(/^v/i, '')
141
+ : DEFAULTS.zkVersion,
142
+ // zk 可执行文件是整台机器共享的,不跟着会话工作区漂 —— 相对路径按进程工作区解析
143
+ zkPath: String(src.zkPath ?? '').trim()
144
+ ? resolveInWorkspace(expandHome(String(src.zkPath).trim()), processWorkspace())
145
+ : '',
146
+ };
147
+ }
148
+ /** 所有已配置笔记本,保持配置里的顺序;路径规则与 cfg.notebook 一致 */
149
+ export function notebookInfos(cfg, workspace = processWorkspace()) {
150
+ return Object.entries(cfg.notebooks).map(([name, entry]) => ({
151
+ name,
152
+ path: notebookPath(entry.path, workspace),
153
+ structure: entry.structure,
154
+ active: name === cfg.active,
155
+ }));
156
+ }
157
+ /** 落盘用:去掉派生的 notebook / structure(磁盘上只有 notebooks + active 这一个真相) */
158
+ function toDisk(cfg) {
159
+ const out = { ...cfg };
160
+ delete out.notebook;
161
+ delete out.structure;
162
+ return out;
163
+ }
164
+ /**
165
+ * 配置读缓存:宿主每个 step 都会求值一次记忆注入,没有这层就是每步 readFileSync + JSON.parse。
166
+ * 失效靠文件指纹(mtime/size/ino),不是超时 —— 手改配置、设置页保存、写回迁移都能立刻生效。
167
+ * 带上 workspace:同一份配置在不同工作区解析出的笔记本绝对路径不同。
168
+ */
169
+ let configCache = null;
170
+ /**
171
+ * 读配置(每次现读,除非文件没变:设置页保存后工具下一句就看到新值)。
172
+ * workspace 只在解析「空 / 相对」笔记本路径时用到:工具传会话 cwd,其余场景用进程工作区。
173
+ */
174
+ export function config(workspace = processWorkspace()) {
175
+ const stamp = fileStamp(CFG_FILE);
176
+ if (configCache && configCache.stamp === stamp && configCache.workspace === workspace) {
177
+ return configCache.value;
178
+ }
179
+ const raw = readJson(CFG_FILE, {});
180
+ const next = normalizeConfig(raw, workspace);
181
+ // 一次性迁移:老形状(没有 notebooks / 顶层还留着 notebook 或 structure / 条目还是裸字符串)
182
+ // 读进来就写回新形状。这样以后翻默认值时,老 vault 的配置里已经有确定值(计划 §8)。
183
+ const legacy = !('notebooks' in raw)
184
+ || ('structure' in raw)
185
+ || ('notebook' in raw)
186
+ || Object.values((raw.notebooks ?? {})).some((v) => typeof v === 'string');
187
+ let writable = true;
188
+ if (Object.keys(raw).length > 0 && legacy) {
189
+ try {
190
+ writeJson(CFG_FILE, toDisk(next));
191
+ }
192
+ catch {
193
+ writable = false; /* 只读环境:下次再补 */
194
+ }
195
+ }
196
+ // 写回失败就不缓存:下次还得再试一次迁移(改了权限要能自愈)
197
+ configCache = writable ? { stamp: fileStamp(CFG_FILE), workspace, value: next } : null;
198
+ return next;
199
+ }
200
+ /**
201
+ * 切到某个笔记本(只看不改:不动磁盘、不改配置)。
202
+ * 名字不在 notebooks 里就按空路径算(= 工作区默认位置),调用方自己先校验。
203
+ */
204
+ export function selectNotebook(cfg, name, workspace = processWorkspace()) {
205
+ const notebooks = { ...cfg.notebooks };
206
+ if (!(name in notebooks))
207
+ notebooks[name] = { path: '', structure: cfg.structure };
208
+ return normalizeConfig({ ...toDisk(cfg), notebooks, active: name }, workspace);
209
+ }
210
+ /**
211
+ * 合并写入(只写白名单键),返回归一化后的完整配置。
212
+ *
213
+ * 三个派生键各有专门语义,不走通用合并:
214
+ * · `notebooks`:**整体替换**(删掉某个笔记本就是传回不含它的完整 map)。
215
+ * 同时给了别的派生键也以它为准 —— 设置页整份发回来时那些是上一次的旧值。
216
+ * · `structure`:只在没给 notebooks 时生效,改的是**当前笔记本**的结构。
217
+ * · `notebook`:纯派生,patch 里出现直接忽略(改路径用 notebooks;CLI 会拦下并提示)。
218
+ *
219
+ * 并发:读-合并-写整段持 `CFG_LOCK`,多个进程(多开 DSH / CLI / 设置页)不会丢更新。
220
+ * 给了 `expectStamp` 就先核对文件指纹 —— 设置页拿的是打开页面时的配置,
221
+ * 别人刚切过笔记本就 409,而不是把对方的 active 覆盖回去。
222
+ */
223
+ export function writeConfig(patch, workspace = processWorkspace(), opts = {}) {
224
+ return withFileLockSync(CFG_LOCK, () => {
225
+ if (opts.expectStamp && opts.expectStamp !== fileStamp(CFG_FILE))
226
+ throw new ConfigConflictError();
227
+ // 锁内重读:等锁期间别的进程可能已经写过,不能拿进程内的缓存做合并基线
228
+ const current = readConfigFresh(workspace);
229
+ const merged = { ...toDisk(current) };
230
+ for (const [k, v] of Object.entries(patch)) {
231
+ if (DERIVED_KEYS.has(k))
232
+ continue;
233
+ if (CONFIG_KEYS.includes(k))
234
+ merged[k] = v;
235
+ }
236
+ // 不是对象就当没给(垃圾输入不许把整个笔记本表清空)
237
+ const hasNotebooks = !!patch.notebooks && typeof patch.notebooks === 'object' && !Array.isArray(patch.notebooks);
238
+ const activeRaw = String(merged.active ?? current.active ?? '').trim();
239
+ const active = NOTEBOOK_NAME_RE.test(activeRaw) ? activeRaw : current.active;
240
+ const notebooks = hasNotebooks
241
+ ? notebookEntries(patch.notebooks, current.notebooks, 'flat')
242
+ : { ...current.notebooks };
243
+ if (!hasNotebooks && 'structure' in patch) {
244
+ const entry = notebooks[active] ?? { path: '', structure: 'flat' };
245
+ notebooks[active] = { ...entry, structure: structureOf(patch.structure, 'flat') };
246
+ }
247
+ const next = normalizeConfig({ ...merged, notebooks, active }, workspace);
248
+ writeJson(CFG_FILE, toDisk(next));
249
+ configCache = null;
250
+ return next;
251
+ });
252
+ }
253
+ /** 配置文件的当前指纹(设置页用它做乐观并发:GET 拿 stamp,POST 带回) */
254
+ export function configStamp() {
255
+ return fileStamp(CFG_FILE);
256
+ }
257
+ /** 设置页保存时发现配置被别处改过 —— 调用方翻成 409 + 最新配置 */
258
+ export class ConfigConflictError extends Error {
259
+ constructor() {
260
+ super('配置已被其他会话或 CLI 修改');
261
+ this.name = 'ConfigConflictError';
262
+ }
263
+ }
264
+ /** 锁内用的干净读取:不吃 configCache,合并基线必须是磁盘上的现状 */
265
+ function readConfigFresh(workspace) {
266
+ return normalizeConfig(readJson(CFG_FILE, {}), workspace);
267
+ }
@@ -0,0 +1,349 @@
1
+ /**
2
+ * dsh-zdiary-kit —— 客户端半边:DSH「设置 → 知识库(zk)」section
3
+ *
4
+ * 数据流:section ⇄ /dsh-zdiary-kit/api/*(同源 fetch)⇄ ~/.dsh/zdiary/zdiary.config.json
5
+ * 两半读同一份配置(config/store 是唯一真相)。
6
+ *
7
+ * 【结构例外】本文件必须单文件零 import:DSH web 的 __ModuleLoader__ 直接把它当普通脚本
8
+ * 加载,只提供 require("react")。所以类型也是自带的,feature.ts 也不 import 它 ——
9
+ * 两侧靠 API 路径与配置键对齐。
10
+ *
11
+ * 【禁止顶层声明】DSH 把多个插件的 client.js **拼进同一个 combo 脚本**(/plugins/??a/client.js,b/client.js)
12
+ * 再当普通脚本执行,顶层 const/let/function 落在同一个全局词法作用域里。以前这里写
13
+ * `const loader = window.__ModuleLoader__`,和同样写法的插件撞名,整个 combo 报
14
+ * "Identifier 'loader' has already been declared",本插件直接不激活。所以顶层只能是
15
+ * 表达式语句(和官方 banner 一致:window.__ModuleLoader__.load({...})),要局部变量就包 IIFE。
16
+ */
17
+ ;
18
+ window.__ModuleLoader__?.load({
19
+ id: 'dsh-zdiary-kit',
20
+ factory: (require) => {
21
+ const module = { exports: {} };
22
+ const exports = module.exports;
23
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
24
+ const React = require('react');
25
+ const h = React.createElement;
26
+ const { useCallback, useEffect, useState } = React;
27
+ const API = '/dsh-zdiary-kit/api';
28
+ const CSS = [
29
+ '.zdk{max-width:760px;color:var(--dsw-alias-label-primary);display:flex;flex-direction:column;gap:6px}',
30
+ '.zdk-title{margin:0;font-size:16px;font-weight:500;line-height:24px}',
31
+ '.zdk-intro{color:var(--dsw-alias-label-tertiary);margin:0 0 4px;font-size:13px;line-height:20px}',
32
+ '.zdk-group{margin-top:16px;font-size:13px;font-weight:600;line-height:20px}',
33
+ '.zdk-row{display:flex;justify-content:space-between;align-items:flex-start;gap:12px 20px;padding:10px 0;border-bottom:.5px solid var(--dsw-alias-border-l2);flex-wrap:wrap}',
34
+ '.zdk-row:last-child{border-bottom:none}',
35
+ '.zdk-row>div:first-child{flex:1;min-width:200px}',
36
+ '.zdk-label{font-size:13px;line-height:19px}',
37
+ '.zdk-hint{color:var(--dsw-alias-label-tertiary);margin-top:3px;font-size:11.5px;line-height:17px;white-space:pre-line}',
38
+ '.zdk-input{background:transparent;border:1px solid var(--dsw-alias-border-l2);border-radius:6px;color:var(--dsw-alias-label-primary);font-size:12.5px;height:28px;padding:0 8px;min-width:240px;outline:none}',
39
+ '.zdk-input:focus-visible{border-color:var(--dsw-alias-brand-primary)}',
40
+ '.zdk-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:14px;padding-top:12px;border-top:.5px solid var(--dsw-alias-border-l2)}',
41
+ '.zdk-btn{background:var(--dsw-alias-brand-primary);color:var(--dsw-alias-label-primary-foreground,#fff);border:none;border-radius:6px;font-size:12.5px;height:30px;padding:0 12px;cursor:pointer}',
42
+ '.zdk-btn:disabled{opacity:.5;cursor:default}',
43
+ '.zdk-btn2{background:transparent;border:1px solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-primary)}',
44
+ '.zdk-out{white-space:pre-wrap;font-family:ui-monospace,Menlo,monospace;font-size:11.5px;line-height:17px;color:var(--dsw-alias-label-secondary);background:rgba(127,127,127,.08);border-radius:8px;padding:10px 12px;max-height:280px;overflow:auto;margin-top:10px}',
45
+ '.zdk-err{color:var(--dsw-alias-state-error-primary);font-size:12px;line-height:18px;margin-top:8px;white-space:pre-line}',
46
+ '.zdk-ok{color:var(--dsw-alias-state-success-primary,#3ec46d);font-size:12px;line-height:18px;margin-top:8px;white-space:pre-line}',
47
+ ].join('');
48
+ (() => {
49
+ const tag = 'zdiary/section.css';
50
+ const old = document.getElementById(tag);
51
+ if (old)
52
+ old.remove();
53
+ const style = document.createElement('style');
54
+ style.id = tag;
55
+ style.textContent = CSS;
56
+ document.head.appendChild(style);
57
+ })();
58
+ const FIELDS = [
59
+ { group: '目录与 group', key: 'notesDir', label: '笔记子目录', hint: '普通笔记放哪(相对笔记本),默认 notes —— 所有笔记本共用' },
60
+ { group: '目录与 group', key: 'dailyDir', label: '日记子目录', hint: '日记放哪(相对笔记本),默认 journal;文件名由日期模板生成 —— 所有笔记本共用' },
61
+ { group: '目录与 group', key: 'dailyGroup', label: '日记 group 名', hint: 'zk 配置里的 [group."…"],默认 daily —— 初始化时会自动补上;所有笔记本共用' },
62
+ { group: '目录与 group', key: 'archiveDir', label: '归档目录', hint: 'supersede 之后笔记搬到这里(保留原相对路径,不删除),默认 archive;所有笔记本共用,改动后点「初始化 / 补建」' },
63
+ { group: '记忆', key: 'memoryBudgetWords', label: '注入预算(词)', hint: 'AGENTS.md + USER.md + MEMORY.md 的合计上限,默认 500(中文按 2 字 1 词)。超了先丢 MEMORY 尾部整段,并回显截断了多少' },
64
+ { group: '写入', key: 'defaultTagsText', label: '默认标签', hint: '新笔记自动追加的标签,逗号分隔,不带 #(可空)' },
65
+ { group: '写入', key: 'maxReadChars', label: 'zk_read 单次上限(字符)', hint: '默认 20000;超了会截断并明确告知模型' },
66
+ { group: 'zk', key: 'zkPath', label: 'zk 路径(可空)', hint: '空 = 自动找:配置 → $ZK_BIN → PATH → 插件内置(~/.dsh/zdiary/bin)' },
67
+ { group: 'zk', key: 'zkVersion', label: '内置 zk 版本', hint: '「安装内置 zk」下载的版本,默认 0.15.7;改完点安装即升级' },
68
+ ];
69
+ const SOURCE = { config: '设置里的路径', env: '$ZK_BIN', path: 'PATH', managed: '插件内置' };
70
+ // 分组标题直接标出作用范围:只有「笔记本」这一组跟着当前笔记本走,其余都是全局的。
71
+ const GROUP_LABELS = {
72
+ '目录与 group': '目录与 group · 全局(所有笔记本共用)',
73
+ '记忆': '记忆 · 全局(所有笔记本共用)',
74
+ '写入': '写入 · 全局(所有笔记本共用)',
75
+ 'zk': 'zk · 全局(整台机器共用)',
76
+ };
77
+ function Section() {
78
+ const [cfg, setCfg] = useState(null);
79
+ const [tagsText, setTagsText] = useState('');
80
+ const [saved, setSaved] = useState('');
81
+ const [snap, setSnap] = useState(null);
82
+ const [busy, setBusy] = useState('');
83
+ const [err, setErr] = useState('');
84
+ const [okMsg, setOkMsg] = useState('');
85
+ const [out, setOut] = useState('');
86
+ const [nbName, setNbName] = useState('');
87
+ const [nbPath, setNbPath] = useState('');
88
+ const [stamp, setStamp] = useState('');
89
+ const applySnap = useCallback((d) => {
90
+ setSnap(d);
91
+ if (typeof d.stamp === 'string' && d.stamp)
92
+ setStamp(d.stamp);
93
+ if (d.config) {
94
+ setCfg(d.config);
95
+ setTagsText((d.config.defaultTags || []).join(', '));
96
+ setSaved(JSON.stringify({ ...d.config, defaultTags: d.config.defaultTags || [] }));
97
+ }
98
+ }, []);
99
+ const load = useCallback(async () => {
100
+ setBusy('load');
101
+ setErr('');
102
+ setOkMsg('');
103
+ try {
104
+ const r = await fetch(`${API}/settings`, { headers: { accept: 'application/json' } });
105
+ const d = await r.json();
106
+ if (!d.ok)
107
+ throw new Error(d.error || '读取失败');
108
+ applySnap(d);
109
+ }
110
+ catch (e) {
111
+ setErr(String(e.message || e));
112
+ }
113
+ finally {
114
+ setBusy('');
115
+ }
116
+ }, [applySnap]);
117
+ useEffect(() => { load(); }, [load]);
118
+ const save = useCallback(async () => {
119
+ if (!cfg)
120
+ return;
121
+ // flat → layered 是单向的结构变化:明确说「只建目录不搬文件」,别让人以为笔记会被整理。
122
+ // 结构是每个笔记本自己的,逐条对比基线;新加的笔记本没有旧笔记可搬,不打扰。
123
+ let switching = false;
124
+ try {
125
+ const prev = JSON.parse(saved);
126
+ switching = Object.keys(cfg.notebooks || {}).some((n) => prev.notebooks?.[n]?.structure === 'flat' && cfg.notebooks?.[n]?.structure === 'layered');
127
+ }
128
+ catch { /* 基线坏了就当没切 */ }
129
+ if (switching && !window.confirm('切到 layered 只会新建目录与模板:\n' +
130
+ ' raw/ · inbox/ · notes/{sources,concepts,entities,patterns}/ · archive/\n' +
131
+ ' daily.md / source.md / entry.md 三套模板 · 根目录 AGENTS.md / WORKFLOW.md\n\n' +
132
+ '**不会**移动、改写或删除任何已有笔记。\n\n' +
133
+ '保存后点底部的「补建 … 的目录」才会真正建出来。继续?'))
134
+ return;
135
+ setBusy('save');
136
+ setErr('');
137
+ setOkMsg('');
138
+ try {
139
+ const body = {
140
+ config: {
141
+ ...cfg,
142
+ defaultTags: tagsText.split(/[,,]/).map((s) => s.trim()).filter(Boolean),
143
+ },
144
+ stamp,
145
+ };
146
+ const r = await fetch(`${API}/settings`, {
147
+ method: 'POST',
148
+ headers: { 'content-type': 'application/json' },
149
+ body: JSON.stringify(body),
150
+ });
151
+ const d = await r.json();
152
+ // 409:别的会话 / CLI 在页面打开期间改过配置。别拿旧表单覆盖(那会把 active 改回去):
153
+ // 直接把最新配置铺回来,让人确认后再保存一次。
154
+ if (r.status === 409) {
155
+ applySnap(d);
156
+ setErr(d.error || '配置已被其他会话修改,已刷新为最新值 —— 请确认后重新保存');
157
+ return;
158
+ }
159
+ if (!d.ok)
160
+ throw new Error(d.error || '保存失败');
161
+ applySnap(d);
162
+ setOkMsg('✓ 已保存' + (d.warn ? '\n⚠️ ' + d.warn : ''));
163
+ }
164
+ catch (e) {
165
+ setErr(String(e.message || e));
166
+ }
167
+ finally {
168
+ setBusy('');
169
+ }
170
+ }, [cfg, tagsText, saved, stamp, applySnap]);
171
+ const action = useCallback(async (name, path) => {
172
+ setBusy(name);
173
+ setErr('');
174
+ setOkMsg('');
175
+ setOut('');
176
+ try {
177
+ const r = await fetch(`${API}/${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
178
+ const d = await r.json();
179
+ if (!d.ok)
180
+ throw new Error(d.error || '操作失败');
181
+ applySnap(d);
182
+ if (name === 'install')
183
+ setOkMsg('✓ ' + (d.detail || '已安装'));
184
+ if (name === 'init') {
185
+ const res = d.result;
186
+ const r = res || {};
187
+ const parts = [r.initialized ? '已初始化' : '笔记本已存在'];
188
+ if (r.dirsCreated && r.dirsCreated.length)
189
+ parts.push(`新建目录 ${r.dirsCreated.length} 个`);
190
+ if (r.templatesWritten && r.templatesWritten.length)
191
+ parts.push('写入模板 ' + r.templatesWritten.join(' / '));
192
+ if (r.agentsWritten)
193
+ parts.push('写入 AGENTS.md');
194
+ if (r.workflowWritten)
195
+ parts.push('写入 WORKFLOW.md');
196
+ if (r.configPatched && !(r.templatesWritten && r.templatesWritten.length) && !(r.dirsCreated && r.dirsCreated.length))
197
+ parts.push('补齐 group');
198
+ setOkMsg('✓ ' + parts.join(' · '));
199
+ }
200
+ if (name === 'index')
201
+ setOkMsg('✓ 索引已重建');
202
+ }
203
+ catch (e) {
204
+ setErr(String(e.message || e));
205
+ }
206
+ finally {
207
+ setBusy('');
208
+ }
209
+ }, [applySnap]);
210
+ const selftest = useCallback(async () => {
211
+ setBusy('selftest');
212
+ setErr('');
213
+ setOkMsg('');
214
+ setOut('');
215
+ try {
216
+ const d = await fetch(`${API}/selftest`).then((x) => x.json());
217
+ setOut((d.items || []).map((it) => `${it.ok ? '✓' : '✗'} ${it.name}:${it.detail}`).join('\n') + (d.ok ? '\n\n══ 全部通过 ✓' : '\n\n══ 有 ✗,照提示修'));
218
+ if (!d.ok && d.error)
219
+ setErr(d.error);
220
+ }
221
+ catch (e) {
222
+ setErr(String(e.message || e));
223
+ }
224
+ finally {
225
+ setBusy('');
226
+ }
227
+ }, []);
228
+ const nbMap = (cfg && cfg.notebooks) || {};
229
+ const nbNames = Object.keys(nbMap);
230
+ const entryOf = (name) => nbMap[name] || { path: '', structure: 'flat' };
231
+ const patchEntry = (name, patch) => setCfg((s) => (s ? { ...s, notebooks: { ...(s.notebooks || {}), [name]: { ...entryOf(name), ...patch } } } : s));
232
+ const setNotebookPath = (name, value) => patchEntry(name, { path: value });
233
+ const setNotebookStructure = (name, value) => patchEntry(name, { structure: value });
234
+ // 删掉的是当前那个就把 active 挪到剩下的第一个 —— 否则归一化会自己挑,界面和落盘就不一致了
235
+ const removeNotebook = (name) => {
236
+ if (!window.confirm(`从配置里移除笔记本「${name}」?\n\n` +
237
+ '只删这条配置:磁盘上的目录和笔记一个字都不会动,之后还能用「新增」加回来。\n' +
238
+ '要点「保存」才会真正落盘;不保存就刷新会原样恢复。继续?'))
239
+ return;
240
+ const rest = { ...nbMap };
241
+ delete rest[name];
242
+ const first = Object.keys(rest)[0] || 'default';
243
+ setCfg((s) => (s ? { ...s, notebooks: rest, active: s.active === name ? first : s.active } : s));
244
+ };
245
+ const addNotebook = () => {
246
+ const name = String(nbName || '').trim();
247
+ if (!name)
248
+ return;
249
+ if (!/^[A-Za-z0-9_-]{1,32}$/.test(name)) {
250
+ setErr('笔记本名字只接受字母、数字、_ 与 -(1-32 字符)');
251
+ return;
252
+ }
253
+ if (nbMap[name] !== undefined) {
254
+ setErr('已经有同名笔记本:' + name);
255
+ return;
256
+ }
257
+ setErr('');
258
+ // 新笔记本结构跟当前那个一致(以前结构是全局的,这就是它的迁移语义)
259
+ setCfg((s) => (s ? {
260
+ ...s,
261
+ notebooks: {
262
+ ...(s.notebooks || {}),
263
+ [name]: { path: String(nbPath || '').trim(), structure: s.notebooks?.[s.active]?.structure || 'flat' },
264
+ },
265
+ } : s));
266
+ setNbName('');
267
+ setNbPath('');
268
+ };
269
+ if (!cfg) {
270
+ return h('div', { className: 'zdk' }, h('h3', { className: 'zdk-title' }, '知识库(zk)'), busy ? h('div', { className: 'zdk-hint' }, '读取中…') : err ? h('div', { className: 'zdk-err' }, err) : null);
271
+ }
272
+ const dirty = saved !== JSON.stringify({ ...cfg, defaultTags: tagsText.split(/[,,]/).map((s) => s.trim()).filter(Boolean) });
273
+ const input = { className: 'zdk-input', autoComplete: 'off', spellCheck: false };
274
+ const up = (key, value) => setCfg((s) => (s ? { ...s, [key]: value } : s));
275
+ const groups = [...new Set(FIELDS.map((f) => f.group))];
276
+ /** 一个字段 → 文本控件(枚举值在笔记本行的结构下拉里,不走字段清单) */
277
+ const control = (f) => {
278
+ const value = f.key === 'defaultTagsText'
279
+ ? tagsText
280
+ : String(cfg[f.key] ?? '');
281
+ const onChange = (e) => f.key === 'defaultTagsText' ? setTagsText(e.target.value) : up(f.key, e.target.value);
282
+ return h('input', { ...input, value, onChange });
283
+ };
284
+ const zk = snap?.zk;
285
+ const counts = snap?.counts;
286
+ const structure = snap?.structure;
287
+ const memory = snap?.memory;
288
+ const statusLine = !zk ? '' : !zk.found
289
+ ? 'zk 还没装:' + (zk.hint || '')
290
+ : `zk ${zk.version}(${SOURCE[zk.source || ''] || zk.source})· 笔记本 ${snap?.notebook.exists ? '就绪' : '还没初始化'}` +
291
+ (counts
292
+ ? ` · ${counts.notes} 篇笔记 / ${counts.tags} 个标签 / 断链 ${counts.brokenLinks} / 归档 ${counts.archived}(superseded ${counts.superseded})`
293
+ : '');
294
+ const memoryLine = !memory
295
+ ? ''
296
+ : `记忆 ${memory.words}/${memory.budget} 词(${memory.files.filter((f) => f.present).map((f) => f.name).join(' + ') || '三份都空'})` +
297
+ (memory.truncatedWords > 0 ? ` · 已截断 ${memory.truncatedWords} 词` : '');
298
+ // 结构以配置为准:磁盘不一致只告警,不自动建、不自动删
299
+ const structureWarn = !structure || !snap?.notebook.exists ? '' : !structure.ready
300
+ ? `结构是 ${structure.mode},但缺目录:${structure.missing.join('、')}`
301
+ : structure.agents.required && !structure.agents.present
302
+ ? '结构是 layered,但根目录缺 AGENTS.md(agent 的工作约定与注入内容)'
303
+ : '';
304
+ // 底部只留一个按钮:没建过就叫「初始化」,缺东西就叫「补建」,都带上当前笔记本名。
305
+ // 用已保存的 active 而不是 cfg.active —— 按钮执行的是服务端已落盘的那份配置。
306
+ const savedActive = snap?.config?.active || cfg.active;
307
+ const needsBuild = !!snap?.notebook.exists && !!structure &&
308
+ (!structure.ready || (structure.agents.required && !structure.agents.present));
309
+ const initLabel = !snap?.notebook.exists
310
+ ? `初始化笔记本 ${savedActive}`
311
+ : needsBuild
312
+ ? `补建 ${savedActive} 的目录`
313
+ : `初始化 / 补建 ${savedActive}`;
314
+ return h('div', { className: 'zdk' }, h('h3', { className: 'zdk-title' }, '知识库(zk)'), h('p', { className: 'zdk-intro' }, '把你的 zk 笔记本接进 DSH:agent 用 zk_* 工具搜索、读写笔记与日记,双链交给 zk 索引。' +
315
+ '没装 zk 就让插件装一个 —— 第一次调用工具时会自动建好笔记本,不需要先来这里点任何按钮。'), statusLine ? h('div', { className: 'zdk-hint' }, '📚 ' + statusLine) : null, memoryLine ? h('div', { className: 'zdk-hint' }, '🧠 ' + memoryLine) : null, structureWarn
316
+ ? h('div', { className: 'zdk-err' }, '⚠️ ' + structureWarn + ' —— 点底部「' + initLabel + '」')
317
+ : null, h('div', null, h('div', { className: 'zdk-group' }, '笔记本 · 每个笔记本自己的路径与结构'), h('div', { className: 'zdk-row' }, h('div', null, h('div', { className: 'zdk-label' }, '当前笔记本'), h('div', { className: 'zdk-hint' }, '这里是**新会话的默认值**:每个会话第一次用 zk_* 时会把当时的值固定下来,之后各走各的。' +
318
+ '改这里不会带着已经跑着的会话走 —— 要让某个会话跟过去,在那个会话里说「切到 X 库」(zk_use)。\n' +
319
+ '路径与结构是每个笔记本自己的;笔记/日记子目录、归档目录、注入预算是全局的。\n' +
320
+ '切换保存后会自动建好目标笔记本(幂等,不动已有笔记)。\n' +
321
+ '空 / 相对路径按「会话工作区」解析:agent 在哪个会话调用,就落在那个工作区。' +
322
+ (snap?.workspace ? '\n本页工作区(插件进程):' + snap.workspace : '') +
323
+ (snap?.notebook?.path ? '\n解析后:' + snap.notebook.path : ''))), h('select', {
324
+ ...input,
325
+ value: cfg.active || 'default',
326
+ onChange: (e) => setCfg((s) => (s ? { ...s, active: e.target.value } : s)),
327
+ }, ...nbNames.map((name) => h('option', { key: name, value: name }, name)))), ...nbNames.map((name, i) => h('div', { className: 'zdk-row', key: 'nb-' + name }, h('div', null, h('div', { className: 'zdk-label' }, name === cfg.active ? name + '(当前)' : name), h('div', { className: 'zdk-hint' }, (i === 0 ? 'zk 笔记本的根目录(含 .zk/)。空 = <工作区>/zdiary;相对路径按工作区解析;也可以指向任何已有 zk 笔记本。\n' : '') +
328
+ '结构跟着这个笔记本走:flat = notes/ + 日记;layered = 分层目录 + 三套模板。切到 layered 只建目录,不搬笔记')), h('div', { style: { display: 'flex', gap: '6px', alignItems: 'center' } }, h('input', {
329
+ ...input,
330
+ value: entryOf(name).path || '',
331
+ placeholder: '空 = <工作区>/zdiary',
332
+ onChange: (e) => setNotebookPath(name, e.target.value),
333
+ }), h('select', {
334
+ ...input,
335
+ style: { minWidth: '0', width: '110px' },
336
+ value: entryOf(name).structure || 'flat',
337
+ onChange: (e) => setNotebookStructure(name, e.target.value),
338
+ }, h('option', { value: 'flat' }, 'flat'), h('option', { value: 'layered' }, 'layered')), h('button', { className: 'zdk-btn zdk-btn2', onClick: () => removeNotebook(name), disabled: nbNames.length <= 1 || !!busy }, '删除')))), h('div', { className: 'zdk-row' }, h('div', null, h('div', { className: 'zdk-label' }, '新增笔记本'), h('div', { className: 'zdk-hint' }, '名字只接受字母、数字、_ 与 -(1-32 字符);路径空着就是 <工作区>/zdiary,结构跟当前笔记本一致。改完点「保存」')), h('div', { style: { display: 'flex', gap: '6px', alignItems: 'center' } }, h('input', { ...input, style: { minWidth: '0', width: '110px' }, placeholder: '名字', value: nbName, onChange: (e) => setNbName(e.target.value) }), h('input', { ...input, style: { minWidth: '0', width: '190px' }, placeholder: '路径', value: nbPath, onChange: (e) => setNbPath(e.target.value) }), h('button', { className: 'zdk-btn zdk-btn2', onClick: addNotebook, disabled: !nbName.trim() || !!busy }, '新增')))), ...groups.map((g) => h('div', { key: g }, h('div', { className: 'zdk-group' }, GROUP_LABELS[g] || g), h('div', null, FIELDS.filter((f) => f.group === g).map((f) => h('div', { className: 'zdk-row', key: f.key }, h('div', null, h('div', { className: 'zdk-label' }, f.label), h('div', { className: 'zdk-hint' }, f.hint)), control(f)))))), h('div', { className: 'zdk-actions' }, h('button', { className: 'zdk-btn', onClick: save, disabled: !!busy }, busy === 'save' ? '保存中…' : '保存'), h('button', { className: 'zdk-btn zdk-btn2', onClick: () => action('init', 'init'), disabled: !!busy }, busy === 'init' ? '处理中…' : initLabel), h('button', { className: 'zdk-btn zdk-btn2', onClick: () => action('index', 'index'), disabled: !!busy }, busy === 'index' ? '索引进…' : '重建索引'), h('button', { className: 'zdk-btn zdk-btn2', onClick: () => action('install', 'install'), disabled: !!busy }, busy === 'install' ? '下载中…' : '安装内置 zk'), h('button', { className: 'zdk-btn zdk-btn2', onClick: selftest, disabled: !!busy }, busy === 'selftest' ? '自检中…' : '自检'), h('button', { className: 'zdk-btn zdk-btn2', onClick: load, disabled: !!busy }, '刷新'), dirty ? h('span', { style: { marginLeft: '10px', color: '#ffb020', fontSize: '13px', alignSelf: 'center' } }, '● 有改动还没保存') : null), okMsg ? h('div', { className: 'zdk-ok' }, okMsg) : null, err ? h('div', { className: 'zdk-err' }, err) : null, out ? h('div', { className: 'zdk-out' }, out) : null, snap?.countsError ? h('div', { className: 'zdk-err' }, '计数失败:' + snap.countsError) : null, h('div', { className: 'zdk-hint' }, `配置:${snap?.configPath || '~/.dsh/zdiary/zdiary.config.json'}\n` +
339
+ '工具的用法:zk_search 查 → zk_read 读 → zk_new 新建 → zk_daily 写日记 → zk_link 连双链;zk_stats 看规模。'));
340
+ }
341
+ function apply(ctx) {
342
+ ctx.effect(() => ctx.slots.inject('settings.section', () => ctx.slots.register({ name: 'settings.section', id: 'zdiary', order: 8, label: () => '知识库(zk)' }, Section), 'zdiary: settings section'), 'zdiary: settings section');
343
+ }
344
+ exports.apply = apply;
345
+ exports.inject = ['slots'];
346
+ exports.Section = Section;
347
+ return module.exports;
348
+ },
349
+ });