dsh-zdiary-kit 0.7.5 → 0.8.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.
@@ -0,0 +1,255 @@
1
+ /**
2
+ * 只读视图的渲染层:转义 + 极简 markdown + 页面骨架。
3
+ *
4
+ * 零依赖、无 JS、服务端拼字符串 —— Web 1.0 的意思是「浏览器只负责显示」:
5
+ * 没有 hydrate、没有 fetch、没有前端构建产物,lynx / curl / 打印都一样能看。
6
+ *
7
+ * 【安全约定】笔记正文是任意文本(里面写 <script> 很正常),所以:
8
+ * · 所有动态内容一律走 esc(),不解析原始 HTML;
9
+ * · markdown 只认下面这一小撮语法,链接只放行 http(s) / mailto / 站内相对路径;
10
+ * · 代码块先 stash 成占位符,避免里面的 ** / [ ] 被当成强调或链接。
11
+ */
12
+ import { ROUTE_BASE } from '../../lib/http.js';
13
+ const ESCAPES = {
14
+ '&': '&amp;',
15
+ '<': '&lt;',
16
+ '>': '&gt;',
17
+ '"': '&quot;',
18
+ "'": '&#39;',
19
+ };
20
+ /** HTML 文本 / 属性统一转义(属性用双引号,所以引号也必须转) */
21
+ export function esc(value) {
22
+ return String(value ?? '').replace(/[&<>"']/g, (c) => ESCAPES[c] ?? c);
23
+ }
24
+ /** 站内链接统一前缀(和 feature.ts 同源:lib/http 的 ROUTE_BASE) */
25
+ const BASE = ROUTE_BASE;
26
+ const CSS = [
27
+ 'body{margin:0 auto;max-width:860px;padding:18px 16px 40px;background:#fff;color:#111;',
28
+ 'font:16px/1.6 Georgia,"Times New Roman","Songti SC",serif}',
29
+ 'a{color:#0000cc}a:visited{color:#551a8b}a:hover{background:#ffffcc}',
30
+ 'header.site{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap}',
31
+ 'header.site .brand{font-size:20px;font-weight:bold;text-decoration:none}',
32
+ 'nav{margin:6px 0 0;font-size:14px}nav a{margin-right:12px}',
33
+ 'hr{border:0;border-top:1px solid #bbb;margin:14px 0}',
34
+ 'h1{font-size:1.6em;line-height:1.25;margin:.5em 0 .3em}',
35
+ 'h2{font-size:1.2em;margin:1.4em 0 .5em;border-bottom:1px solid #ddd;padding-bottom:2px}',
36
+ 'h3,h4,h5,h6{font-size:1.05em;margin:1.1em 0 .4em}',
37
+ 'p{white-space:pre-line;margin:.55em 0}',
38
+ 'ul,ol{margin:.4em 0 .8em;padding-left:1.6em}li{margin:.15em 0}',
39
+ 'blockquote{margin:.6em 0;padding:.2em 0 .2em 12px;border-left:3px solid #ccc;color:#333}',
40
+ 'pre{background:#f6f6f6;border:1px solid #ddd;padding:8px 10px;overflow:auto;font-size:13px;line-height:1.45}',
41
+ 'code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.92em}',
42
+ 'p code,li code{background:#f3f3f3;padding:0 3px}',
43
+ 'table{border-collapse:collapse;width:100%;margin:.5em 0}',
44
+ 'th,td{text-align:left;padding:3px 6px;border-bottom:1px solid #e5e5e5;vertical-align:top}',
45
+ 'th{font-weight:bold;border-bottom:1px solid #bbb}',
46
+ '.meta{color:#555;font-size:13px}.meta a{color:#0000cc}',
47
+ '.notice{border:1px solid #d9a300;background:#fffbe6;padding:8px 10px;margin:12px 0;font-size:14px}',
48
+ '.error{border:1px solid #c00;background:#fff2f2;padding:8px 10px;margin:12px 0;font-size:14px}',
49
+ '.tags a{margin-right:10px;white-space:nowrap}.tags .count{color:#777;font-size:12px}',
50
+ 'form.search{margin:12px 0}form.search input{font:inherit;padding:3px 6px;width:min(100%,360px);border:1px solid #999}',
51
+ 'form.search button{font:inherit;padding:3px 10px;margin-left:4px}',
52
+ '.wikilink{color:#777;border-bottom:1px dotted #999}',
53
+ 'footer{margin-top:26px;color:#666;font-size:12px}',
54
+ '.crumb{font-size:13px;color:#666}',
55
+ '@media print{body{max-width:none;font-size:12pt}nav,form.search,footer{display:none}a{color:#000;text-decoration:none}}',
56
+ ].join('');
57
+ /** 页面骨架:导航、主体、页脚。所有插值都已转义或由本模块生成。 */
58
+ export function layout({ title, notebook, body, note }) {
59
+ const generated = new Date().toISOString().replace('T', ' ').slice(0, 19) + ' UTC';
60
+ return [
61
+ '<!doctype html>',
62
+ '<html lang="zh-CN"><head>',
63
+ '<meta charset="utf-8">',
64
+ '<meta name="viewport" content="width=device-width,initial-scale=1">',
65
+ '<meta name="robots" content="noindex,nofollow">',
66
+ `<title>${esc(title)} · ${esc(notebook)}</title>`,
67
+ `<style>${CSS}</style>`,
68
+ '</head><body>',
69
+ '<header class="site">',
70
+ `<a class="brand" href="${BASE}/view">${esc(notebook)}</a>`,
71
+ '<span class="meta">只读知识库</span>',
72
+ '</header>',
73
+ '<nav>',
74
+ `<a href="${BASE}/view">首页</a>`,
75
+ `<a href="${BASE}/view?p=memory">记忆</a>`,
76
+ `<a href="${BASE}/view?p=tags">标签</a>`,
77
+ `<a href="${BASE}/feed.xml">RSS</a>`,
78
+ '</nav>',
79
+ '<hr>',
80
+ body,
81
+ '<hr>',
82
+ '<footer>',
83
+ `只读视图 · 无写接口 · 数据来自插件进程工作区 · 生成于 ${esc(generated)}`,
84
+ note ? `<br>${esc(note)}` : '',
85
+ '</footer>',
86
+ '</body></html>',
87
+ ].join('');
88
+ }
89
+ /** frontmatter 是给 zk 的元数据,页面上由标题 / 日期行展示,正文里剥掉 */
90
+ function stripFrontmatter(text) {
91
+ return text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '');
92
+ }
93
+ /**
94
+ * 只放行 http(s) / mailto / 站内相对路径;javascript:、data: 一律当成纯文本。
95
+ * `//host` 与 `\\host` / `\/host` 是协议相对链接(浏览器会把反斜杠规范成斜杠),
96
+ * 点下去就离开本地视图了,同样不算站内,直接拒绝。
97
+ */
98
+ function safeHref(href) {
99
+ const value = href.trim();
100
+ if (!value)
101
+ return false;
102
+ if (/^[\\/]{2}/.test(value))
103
+ return false;
104
+ if (/^(?:javascript|data|vbscript):/i.test(value))
105
+ return false;
106
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(value);
107
+ if (!scheme)
108
+ return true;
109
+ return /^(?:https?|mailto)$/i.test(scheme[1]);
110
+ }
111
+ /** 行内语法:代码 → 双链 → markdown 链接 → 粗体 → 斜体(全部在已转义文本上做) */
112
+ function inline(text, opts) {
113
+ const stash = [];
114
+ const keep = (html) => `\u0000${stash.push(html) - 1}\u0000`;
115
+ let out = esc(text);
116
+ out = out.replace(/`([^`\n]+)`/g, (_m, code) => keep(`<code>${code}</code>`));
117
+ out = out.replace(/\[\[([^\]\n]+)\]\]/g, (_m, inner) => {
118
+ const bar = inner.indexOf('|');
119
+ const target = (bar >= 0 ? inner.slice(0, bar) : inner).trim();
120
+ const label = (bar >= 0 ? inner.slice(bar + 1) : inner).trim() || target;
121
+ if (!target)
122
+ return keep(label);
123
+ const href = opts.linkFor?.(target) ?? null;
124
+ return keep(href
125
+ ? `<a href="${esc(href)}">${label}</a>`
126
+ : `<span class="wikilink">${label}</span>`);
127
+ });
128
+ out = out.replace(/\[([^\]\n]+)\]\(([^)\s]+)\)/g, (_m, label, href) => {
129
+ if (!safeHref(href))
130
+ return keep(label);
131
+ // href 来自已经转义过的文本,直接用;再 esc 一次会把 &amp; 变成 &amp;amp;
132
+ return keep(`<a href="${href}" rel="noopener noreferrer">${label}</a>`);
133
+ });
134
+ out = out.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>');
135
+ out = out.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>');
136
+ return out.replace(/\u0000(\d+)\u0000/g, (_m, i) => stash[Number(i)] ?? '');
137
+ }
138
+ const HR = /^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/;
139
+ const UL = /^\s*[-*+]\s+(.*)$/;
140
+ const OL = /^\s*\d+[.)]\s+(.*)$/;
141
+ const QUOTE = /^\s*>\s?(.*)$/;
142
+ const HEADING = /^(#{1,6})\s+(.*)$/;
143
+ const FENCE = /^\s*```/;
144
+ /** 独占一行的 HTML 注释:不渲染。模板首行就是 `<!-- zdiary-template: vN -->`(lint 的版本标记),
145
+ * 转义后当段落显示等于把内部约定摆到页面最上面 */
146
+ const HTML_COMMENT = /^\s*<!--[\s\S]*?-->\s*$/;
147
+ /**
148
+ * 极简 markdown:标题 / 段落 / 列表 / 引用 / 分隔线 / 围栏代码。
149
+ * 不支持的语法(表格、图片、脚注……)原样当段落显示 —— 宁可朴素,不要为了渲染引一个库。
150
+ */
151
+ export function renderMarkdown(source, opts = {}) {
152
+ const text = stripFrontmatter(String(source ?? '')).replace(/\r\n?/g, '\n');
153
+ const lines = text.split('\n');
154
+ const out = [];
155
+ const para = [];
156
+ let i = 0;
157
+ let skippedH1 = false;
158
+ const flush = () => {
159
+ if (!para.length)
160
+ return;
161
+ out.push(`<p>${para.map((line) => inline(line, opts)).join('\n')}</p>`);
162
+ para.length = 0;
163
+ };
164
+ while (i < lines.length) {
165
+ const line = lines[i] ?? '';
166
+ if (FENCE.test(line)) {
167
+ flush();
168
+ const lang = line.trim().slice(3).trim();
169
+ i += 1;
170
+ const code = [];
171
+ while (i < lines.length && !FENCE.test(lines[i] ?? ''))
172
+ code.push(lines[i++] ?? '');
173
+ i += 1;
174
+ out.push(`<pre><code${lang ? ` class="language-${esc(lang)}"` : ''}>${esc(code.join('\n'))}</code></pre>`);
175
+ continue;
176
+ }
177
+ // 整行跳过:不显示,也不 flush —— 它是不可见的元信息,不该把段落或列表从中间切开
178
+ if (HTML_COMMENT.test(line)) {
179
+ i += 1;
180
+ continue;
181
+ }
182
+ if (!line.trim()) {
183
+ flush();
184
+ i += 1;
185
+ continue;
186
+ }
187
+ const heading = HEADING.exec(line);
188
+ if (heading) {
189
+ flush();
190
+ const level = heading[1]?.length ?? 1;
191
+ if (level === 1 && opts.skipFirstH1 && !skippedH1) {
192
+ skippedH1 = true;
193
+ i += 1;
194
+ continue;
195
+ }
196
+ // 第一个标题不是 H1 时,后面的 H1 是正文小节,不能再当页面标题跳掉
197
+ skippedH1 = true;
198
+ out.push(`<h${level}>${inline(heading[2] ?? '', opts)}</h${level}>`);
199
+ i += 1;
200
+ continue;
201
+ }
202
+ if (HR.test(line)) {
203
+ flush();
204
+ out.push('<hr>');
205
+ i += 1;
206
+ continue;
207
+ }
208
+ const quote = QUOTE.exec(line);
209
+ if (quote) {
210
+ flush();
211
+ const body = [];
212
+ while (i < lines.length) {
213
+ const q = QUOTE.exec(lines[i] ?? '');
214
+ if (!q)
215
+ break;
216
+ body.push(inline(q[1] ?? '', opts));
217
+ i += 1;
218
+ }
219
+ out.push(`<blockquote>${body.join('<br>')}</blockquote>`);
220
+ continue;
221
+ }
222
+ const ul = UL.exec(line);
223
+ if (ul) {
224
+ flush();
225
+ const items = [];
226
+ while (i < lines.length) {
227
+ const m = UL.exec(lines[i] ?? '');
228
+ if (!m)
229
+ break;
230
+ items.push(`<li>${inline(m[1] ?? '', opts)}</li>`);
231
+ i += 1;
232
+ }
233
+ out.push(`<ul>${items.join('')}</ul>`);
234
+ continue;
235
+ }
236
+ const ol = OL.exec(line);
237
+ if (ol) {
238
+ flush();
239
+ const items = [];
240
+ while (i < lines.length) {
241
+ const m = OL.exec(lines[i] ?? '');
242
+ if (!m)
243
+ break;
244
+ items.push(`<li>${inline(m[1] ?? '', opts)}</li>`);
245
+ i += 1;
246
+ }
247
+ out.push(`<ol>${items.join('')}</ol>`);
248
+ continue;
249
+ }
250
+ para.push(line);
251
+ i += 1;
252
+ }
253
+ flush();
254
+ return out.join('\n');
255
+ }
@@ -127,7 +127,7 @@ window.__ModuleLoader__?.load({
127
127
  }
128
128
  catch { /* 基线坏了就当没切 */ }
129
129
  if (switching && !window.confirm('切到 layered 只会新建目录与模板:\n' +
130
- ' raw/ · inbox/ · notes/{sources,concepts,entities,patterns}/ · archive/\n' +
130
+ ' raw/ · notes/{sources,concepts,entities,patterns}/ · archive/\n' +
131
131
  ' daily.md / source.md / entry.md 三套模板 · 根目录 AGENTS.md / WORKFLOW.md\n\n' +
132
132
  '**不会**移动、改写或删除任何已有笔记。\n\n' +
133
133
  '保存后点底部的「补建 … 的目录」才会真正建出来。继续?'))
@@ -199,6 +199,8 @@ window.__ModuleLoader__?.load({
199
199
  }
200
200
  if (name === 'index')
201
201
  setOkMsg('✓ 索引已重建');
202
+ if (name === 'agents')
203
+ setOkMsg(d.result?.written === true ? '✓ 已写入 AGENTS.md 模板' : '✓ AGENTS.md 已存在,没有覆盖');
202
204
  }
203
205
  catch (e) {
204
206
  setErr(String(e.message || e));
@@ -294,13 +296,16 @@ window.__ModuleLoader__?.load({
294
296
  const memoryLine = !memory
295
297
  ? ''
296
298
  : `记忆 ${memory.words}/${memory.budget} 词(${memory.files.filter((f) => f.present).map((f) => f.name).join(' + ') || '三份都空'})` +
297
- (memory.truncatedWords > 0 ? ` · 已截断 ${memory.truncatedWords} 词` : '');
299
+ (memory.truncatedWords > 0 ? ` · 已截断 ${memory.truncatedWords} 词` : '') +
300
+ (structure && !structure.agents.present ? ' · ⚠️ 缺 AGENTS.md:约定与周提醒未启用' : '');
298
301
  // 结构以配置为准:磁盘不一致只告警,不自动建、不自动删
299
302
  const structureWarn = !structure || !snap?.notebook.exists ? '' : !structure.ready
300
303
  ? `结构是 ${structure.mode},但缺目录:${structure.missing.join('、')}`
301
304
  : structure.agents.required && !structure.agents.present
302
305
  ? '结构是 layered,但根目录缺 AGENTS.md(agent 的工作约定与注入内容)'
303
- : '';
306
+ : structure.mode === 'flat' && structure.extra.length
307
+ ? `盘上有分层目录(${structure.extra.join('、')}),但配置是 flat —— 新建笔记会落在 notes/ 根,不套模板`
308
+ : '';
304
309
  // 底部只留一个按钮:没建过就叫「初始化」,缺东西就叫「补建」,都带上当前笔记本名。
305
310
  // 用已保存的 active 而不是 cfg.active —— 按钮执行的是服务端已落盘的那份配置。
306
311
  const savedActive = snap?.config?.active || cfg.active;
@@ -335,7 +340,9 @@ window.__ModuleLoader__?.load({
335
340
  style: { minWidth: '0', width: '110px' },
336
341
  value: entryOf(name).structure || 'flat',
337
342
  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` +
343
+ }, 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), structure && snap?.notebook.exists && !structure.agents.present
344
+ ? h('button', { className: 'zdk-btn zdk-btn2', onClick: () => action('agents', 'agents'), disabled: !!busy }, busy === 'agents' ? '写入中…' : '写入 AGENTS.md 模板')
345
+ : null, 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('a', { className: 'zdk-btn zdk-btn2', href: '/dsh-zdiary-kit/view', target: '_blank', rel: 'noopener noreferrer', style: { display: 'inline-flex', alignItems: 'center', textDecoration: 'none' } }, '只读视图'), 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
346
  '工具的用法:zk_search 查 → zk_read 读 → zk_new 新建 → zk_daily 写日记 → zk_link 连双链;zk_stats 看规模。'));
340
347
  }
341
348
  function apply(ctx) {
@@ -11,14 +11,14 @@
11
11
  */
12
12
  import fs from 'node:fs';
13
13
  import path from 'node:path';
14
- import { json, readBody } from '../../lib/http.js';
14
+ import { json, readBody, ROUTE_BASE } from '../../lib/http.js';
15
15
  import { CFG_FILE, processWorkspace } from '../../config/paths.js';
16
16
  import { config, configStamp, ConfigConflictError, writeConfig } from '../../config/store.js';
17
- import { ensureNotebook, structureStatus } from '../../lib/notebook.js';
17
+ import { ensureNotebook, structureStatus, writeAgentsTemplate } from '../../lib/notebook.js';
18
18
  import { buildMemoryPayload, formatFileShares } from '../../lib/memory.js';
19
19
  import { installZk, sourceLabel } from '../../lib/install.js';
20
20
  import { hasNotebook, indexNotebook, notebookStats, resolveZk } from '../../lib/zk.js';
21
- const P = '/dsh-zdiary-kit/api';
21
+ const P = `${ROUTE_BASE}/api`;
22
22
  async function zkStatus(cfg) {
23
23
  const loc = await resolveZk(cfg);
24
24
  if (!loc) {
@@ -148,6 +148,13 @@ export function registerSettings({ route, isTrusted }) {
148
148
  if (exists && st.agents.required && !st.agents.present) {
149
149
  warn.push('layered 结构缺 AGENTS.md —— 点「初始化 / 补建」写入模板');
150
150
  }
151
+ // flat 不自动写,但「有 MEMORY 没 AGENTS」意味着约定与周提醒都没生效 —— 只提示,不擅自写
152
+ if (exists && !st.agents.present && fs.existsSync(path.join(next.notebook, 'MEMORY.md'))) {
153
+ warn.push('记忆在跑,但缺 AGENTS.md —— 约定与周提醒未启用;点「写入 AGENTS.md 模板」');
154
+ }
155
+ if (exists && st.mode === 'flat' && st.extra.length) {
156
+ warn.push(`盘上有分层目录(${st.extra.join('、')}),但配置是 flat —— 新建笔记会落在 ${next.notesDir}/ 根`);
157
+ }
151
158
  json(res, 200, { ok: true, config: next, configPath: CFG_FILE, stamp: configStamp(), warn: warn.length ? warn.join(';') : null, ...(await snapshot(next)) });
152
159
  });
153
160
  // ── 状态 ──
@@ -193,6 +200,24 @@ export function registerSettings({ route, isTrusted }) {
193
200
  json(res, 400, { ok: false, error: err instanceof Error ? err.message : String(err) });
194
201
  }
195
202
  });
203
+ // ── 写入 AGENTS.md 模板(flat 的 opt-in;已存在不覆盖)──
204
+ route(`${P}/agents`, async (req, res) => {
205
+ if (!requireTrusted(req, res))
206
+ return;
207
+ if (req.method !== 'POST') {
208
+ json(res, 405, { ok: false, error: '只支持 POST' });
209
+ return;
210
+ }
211
+ const cfg = config();
212
+ try {
213
+ const written = writeAgentsTemplate(cfg);
214
+ // 和 `/init` 一样把动作结果放进 `result`:设置页读的是 `d.result.written`
215
+ json(res, 200, { ok: true, result: { written }, ...(await snapshot(cfg)) });
216
+ }
217
+ catch (err) {
218
+ json(res, 400, { ok: false, error: err instanceof Error ? err.message : String(err) });
219
+ }
220
+ });
196
221
  // ── 安装内置 zk(官方 release → 插件 bin 目录 → 真跑一次)──
197
222
  route(`${P}/install`, async (req, res) => {
198
223
  if (!requireTrusted(req, res))
@@ -262,6 +287,9 @@ export function registerSettings({ route, isTrusted }) {
262
287
  detail: groupOk ? `group."${cfg.dailyGroup}" → ${cfg.dailyDir}/` : '配置里没有这个 group,点「初始化 / 补建」补上',
263
288
  });
264
289
  const st = structureStatus(cfg);
290
+ const drift = st.mode === 'flat' && st.extra.length
291
+ ? `;盘上有分层目录 ${st.extra.join('、')},新建笔记会落在 ${cfg.notesDir}/ 根`
292
+ : '';
265
293
  items.push({
266
294
  name: `结构(${st.mode})`,
267
295
  ok: !exists || (st.ready && (!st.agents.required || st.agents.present)),
@@ -270,8 +298,8 @@ export function registerSettings({ route, isTrusted }) {
270
298
  : st.ready
271
299
  ? st.agents.required
272
300
  ? (st.agents.present ? `${st.dirs.length} 个目录齐全 · AGENTS.md 就绪` : '目录齐全,缺 AGENTS.md —— 点「初始化 / 补建」')
273
- : `${st.dirs.length} 个目录齐全`
274
- : `缺目录:${st.missing.join('、')} —— 点「初始化 / 补建」`,
301
+ : `${st.dirs.length} 个目录齐全` + drift
302
+ : `缺目录:${st.missing.join('、')} —— 点「初始化 / 补建」` + drift,
275
303
  });
276
304
  try {
277
305
  const payload = buildMemoryPayload(cfg);