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.
- package/LICENSE +21 -0
- package/README.md +345 -2
- package/cordis.patch.yml +18 -0
- package/dist/app/plugin.js +274 -0
- package/dist/cli.js +501 -0
- package/dist/config/paths.js +57 -0
- package/dist/config/session.js +108 -0
- package/dist/config/store.js +267 -0
- package/dist/features/settings/client.js +349 -0
- package/dist/features/settings/feature.js +310 -0
- package/dist/features/zk-tools/feature.js +1112 -0
- package/dist/lib/agents-template.js +79 -0
- package/dist/lib/dream.js +211 -0
- package/dist/lib/dsh.js +1 -0
- package/dist/lib/exec.js +66 -0
- package/dist/lib/file-stamp.js +17 -0
- package/dist/lib/frontmatter.js +74 -0
- package/dist/lib/http.js +20 -0
- package/dist/lib/install.js +69 -0
- package/dist/lib/json-file.js +19 -0
- package/dist/lib/lint.js +281 -0
- package/dist/lib/lock.js +80 -0
- package/dist/lib/memory.js +288 -0
- package/dist/lib/meta.js +16 -0
- package/dist/lib/notebook.js +227 -0
- package/dist/lib/platform.js +20 -0
- package/dist/lib/tool.js +70 -0
- package/dist/lib/workspace.js +22 -0
- package/dist/lib/zk.js +1235 -0
- package/docs/features/memory.md +67 -0
- package/docs/features/provisioning.md +48 -0
- package/docs/features/settings.md +63 -0
- package/docs/features/zk-tools.md +104 -0
- package/icon.svg +24 -0
- package/package.json +64 -4
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 根目录 AGENTS.md 模板:layered 初始化时写进 vault,已存在就不碰。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一个文件:它是「给人读的文档」,不是逻辑;放在这里也方便直接对照
|
|
5
|
+
* docs/features/memory.md 的三条口径(检索词归宿 / 中文必打 tags / 宿主不会自动加载)。
|
|
6
|
+
*
|
|
7
|
+
* 长度是设计约束:AGENTS.md 属于注入预算(默认 500 词,中文 2 字 = 1 词)且**永不截断**,
|
|
8
|
+
* 模板自己吃掉过半预算,USER / MEMORY 就没位置了 —— 所以这里只留规则,不写教程。
|
|
9
|
+
* 目标 ~175 词(195 → 160 → 175):每多 10 词,MEMORY 就少 10 词的正文,规则能紧就紧。
|
|
10
|
+
*/
|
|
11
|
+
export const AGENTS_TEMPLATE = `# 知识库工作约定
|
|
12
|
+
|
|
13
|
+
> zdiary 生成;DSH 不会自动加载,由插件每轮注入。
|
|
14
|
+
|
|
15
|
+
## 目录
|
|
16
|
+
|
|
17
|
+
raw/ 只读材料 · inbox/ 待归类 · notes/sources/ 来源
|
|
18
|
+
notes/{concepts,entities,patterns}/ 原子笔记 · archive/ 废弃(不删)
|
|
19
|
+
|
|
20
|
+
## 检索词
|
|
21
|
+
|
|
22
|
+
值得检索 → tags 或正文;不值得 → 不写。
|
|
23
|
+
中文必打 tags:全文索引不切中文,只查正文会静默查空,进而建重复笔记。
|
|
24
|
+
|
|
25
|
+
## 写之前
|
|
26
|
+
|
|
27
|
+
1. zk_query / zk_search 查重(中文查 tags)。
|
|
28
|
+
2. 一条笔记一件事,标题即结论;文件名用 zk_new 的 name 给 8–14 字短名(不给就是按标题生成的拼音长名);来源进 sources/,结论进 concepts/,zk_link 相连。
|
|
29
|
+
3. 结论过时用 zk_supersede(默认预演,带 reason):不删文件、不改旧结论。
|
|
30
|
+
4. 改已有笔记前读 WORKFLOW.md:先列清单等确认,再按三分类动手。
|
|
31
|
+
|
|
32
|
+
## 每周
|
|
33
|
+
|
|
34
|
+
把「上次做梦:YYYY-MM-DD」写进 DREAMS.md;到期或缺这行时:
|
|
35
|
+
zk_lint → zk_dream → 写 DREAMS.md → 人裁决后改 MEMORY.md。
|
|
36
|
+
MEMORY.md 每条结论附 [[来源路径]],zk_lint 核对。
|
|
37
|
+
`;
|
|
38
|
+
/**
|
|
39
|
+
* 根目录 WORKFLOW.md:只在「要动已有笔记」时才需要读,所以不注入、不计预算。
|
|
40
|
+
* 放进注入的话,AGENTS.md 一膨胀就会挤掉 MEMORY —— 这些规则低频但重要,适合按需读。
|
|
41
|
+
*/
|
|
42
|
+
export const WORKFLOW_TEMPLATE = `# 改笔记的工作流(按需读)
|
|
43
|
+
|
|
44
|
+
> 由 dsh-zdiary-kit 生成。AGENTS.md 只放每轮都要用的规则;这一页在要动已有笔记时才读。
|
|
45
|
+
> 它不进检索,也不要往里追加内容(整篇重写,git diff 可审)。
|
|
46
|
+
|
|
47
|
+
## 新信息与旧笔记冲突时,先分类
|
|
48
|
+
|
|
49
|
+
1. **temporal update** —— 事实随时间变了:改写现行结论,旧值连同日期搬进 Changelog 小节。
|
|
50
|
+
2. **context variant** —— 不同情境答案不同:原结论保留,加一节「针对 X:」写条件分支。
|
|
51
|
+
3. **contradiction** —— 同期、同情境互相冲突:一个字都不改,把两篇路径与冲突点写进 DREAMS.md,等人裁决。
|
|
52
|
+
|
|
53
|
+
判断不了就按 3 处理:flag 的成本远低于悄悄改写。
|
|
54
|
+
|
|
55
|
+
## 动笔前必须出清单
|
|
56
|
+
|
|
57
|
+
1. 用 zk_search / zk_query 找出可能受影响的笔记;
|
|
58
|
+
2. 列出「改哪几篇、每篇按哪一类改」;
|
|
59
|
+
3. 等用户确认,再逐篇改。
|
|
60
|
+
|
|
61
|
+
没有确认范围就动手 = 全库漂移。这条没有例外。
|
|
62
|
+
|
|
63
|
+
## 什么时候该新建
|
|
64
|
+
|
|
65
|
+
- 概念 / 实体以后还会遇到 → notes/concepts/ 或 notes/entities/;
|
|
66
|
+
- 一次性来源 → 只建 source 笔记;
|
|
67
|
+
- 旧结论过时 → zk_supersede(默认预演),不删文件。
|
|
68
|
+
|
|
69
|
+
## 链接
|
|
70
|
+
|
|
71
|
+
zk_link 只连真实的概念关联,不连「词面像」。同一篇首次提及时链一次即可。
|
|
72
|
+
|
|
73
|
+
## 别做的事
|
|
74
|
+
|
|
75
|
+
- 不写 raw/:它是只读原始材料,写了也搜不到,工具会直接拒绝。
|
|
76
|
+
- 不跑无范围的「更新一下 wiki」。
|
|
77
|
+
- 不手工改 status、不手工搬文件 —— 走 zk_supersede。
|
|
78
|
+
- 不手工 mv / 改文件名 —— 走 zk_rename(默认预演,会重写 [[入链]] 与 MEMORY.md 里的来源)。
|
|
79
|
+
`;
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 做梦(M3):只给材料,不写任何文件(计划 §3 D5 / D7)。
|
|
3
|
+
*
|
|
4
|
+
* 晋升 MEMORY.md、写 DREAMS.md 都是 agent 的语义活;这里只做三件机械事:
|
|
5
|
+
* · 最近 N 天新增的笔记(按机械规则挡掉不可晋升的,附原因;日记不算候选,它的未完成项单独一栏);
|
|
6
|
+
* · daily 里 `## Loose ends` 小节还没划掉的项;
|
|
7
|
+
* · 被引用最多的笔记(一次 `zk graph` 数入链)。
|
|
8
|
+
* 「rejected」是机械规则,不是相关性判断:authority=informal 与无标签两条,别再加。
|
|
9
|
+
*/
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { allNotes, graphEdges, localDate, MAX_SCAN } from './zk.js';
|
|
13
|
+
import { parseFrontmatter } from './frontmatter.js';
|
|
14
|
+
/** 每栏最多回多少条(计划 §4 M3 的 50 条上限) */
|
|
15
|
+
export const MAX_ITEMS = 50;
|
|
16
|
+
/** topCited 只取前几名:给 agent 一个「本周被反复引用」的提示,不是排行榜 */
|
|
17
|
+
export const TOP_CITED = 10;
|
|
18
|
+
/** `## Loose ends` / `## 未完成` / `## 待办` 都算(大小写不敏感,单复数都认) */
|
|
19
|
+
const LOOSE_HEADING = /^##\s+(loose ends?|未完成|待办(?:事项)?)\s*$/i;
|
|
20
|
+
/** 周节奏:AGENTS.md 的「每周」就按这个天数算。没有定时器,只在记忆注入里提醒到期 */
|
|
21
|
+
export const DREAM_INTERVAL_DAYS = 7;
|
|
22
|
+
/** DREAMS.md 的标记行:`上次做梦:2026-10-22`(列表符号 / 引用符 / 加粗都能容忍) */
|
|
23
|
+
const DREAM_STAMP = /^\s*(?:[-*+>]\s*)?(?:\*\*)?上次做梦(?:\*\*)?\s*[::]\s*(\d{4})-(\d{2})-(\d{2})\s*$/;
|
|
24
|
+
/**
|
|
25
|
+
* 读 DREAMS.md 正文里的「上次做梦」日期(YYYY-MM-DD)。
|
|
26
|
+
* 只认整齐的一行:这段值是**人/agent 写的**,被夹在句子里时宁可当没有,也不猜。
|
|
27
|
+
*/
|
|
28
|
+
export function lastDreamDate(body) {
|
|
29
|
+
for (const line of String(body ?? '').split('\n')) {
|
|
30
|
+
const m = DREAM_STAMP.exec(line);
|
|
31
|
+
if (m)
|
|
32
|
+
return `${m[1]}-${m[2]}-${m[3]}`;
|
|
33
|
+
}
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* 距上次做梦几天。按**本地日历天**算(不是毫秒差 / 86400000 再取整 ——
|
|
38
|
+
* 夏时制会给出 6.958 天,floor 成 6,于是「满 7 天」永远差一天)。
|
|
39
|
+
*/
|
|
40
|
+
export function daysSinceDream(last, now = new Date()) {
|
|
41
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(last ?? '').trim());
|
|
42
|
+
if (!m)
|
|
43
|
+
return null;
|
|
44
|
+
const at = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
|
|
45
|
+
if (Number.isNaN(at.getTime()))
|
|
46
|
+
return null;
|
|
47
|
+
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
|
48
|
+
return Math.round((today.getTime() - at.getTime()) / 86_400_000);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* 从日记正文里取 Loose ends 小节。
|
|
52
|
+
* `- [x]` 是已完成,不收;`- [ ]` 与普通列表项都收(划掉的状态比格式重要)。
|
|
53
|
+
*/
|
|
54
|
+
export function looseEndsOf(content) {
|
|
55
|
+
const out = [];
|
|
56
|
+
let inside = false;
|
|
57
|
+
for (const raw of String(content ?? '').split('\n')) {
|
|
58
|
+
const line = raw.trim();
|
|
59
|
+
if (/^#{1,2}\s/.test(line)) {
|
|
60
|
+
inside = LOOSE_HEADING.test(line);
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (!inside || !line)
|
|
64
|
+
continue;
|
|
65
|
+
if (/^-\s*\[[xX]\]/.test(line))
|
|
66
|
+
continue;
|
|
67
|
+
const item = line.replace(/^[-*+]\s+/, '').replace(/^\[[ xX]\]\s*/, '').trim();
|
|
68
|
+
if (item)
|
|
69
|
+
out.push(item);
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* 机械拒绝规则(只两条,别加语义判断):
|
|
75
|
+
* · authority=informal —— 口头/未验证来源,进长期记忆会污染结论;
|
|
76
|
+
* · 无标签 —— Z12 下中文正文召回不完整,没标签的笔记晋升后照样搜不到。
|
|
77
|
+
*/
|
|
78
|
+
export function rejectionReason(note) {
|
|
79
|
+
if (note.authority === 'informal')
|
|
80
|
+
return 'authority: informal(口头/未验证来源)';
|
|
81
|
+
if (note.tags.length === 0)
|
|
82
|
+
return '无标签(中文正文召回不完整,晋升后也搜不到)';
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
function isUnder(rel, dir) {
|
|
86
|
+
const d = dir.replace(/\/+$/, '');
|
|
87
|
+
return rel === d || rel.startsWith(d + '/');
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* 机械摘要:frontmatter 之后、第一个正文段落,压空白后最多 200 字。
|
|
91
|
+
* 为什么不用 NoteRecord.lead:zk 的 lead 是笔记首行(通常是标题行),当摘要没有信息量。
|
|
92
|
+
* 读失败就退回 lead(哪怕是标题行),不让 dream 因为一篇坏文件整批失败。
|
|
93
|
+
*/
|
|
94
|
+
function excerptOf(cfg, note) {
|
|
95
|
+
let body = '';
|
|
96
|
+
try {
|
|
97
|
+
const abs = note.absPath || path.join(cfg.notebook, note.path);
|
|
98
|
+
body = parseFrontmatter(fs.readFileSync(abs, 'utf8')).body;
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return note.lead;
|
|
102
|
+
}
|
|
103
|
+
const parts = [];
|
|
104
|
+
for (const raw of body.split('\n')) {
|
|
105
|
+
const line = raw.trim();
|
|
106
|
+
if (!line) {
|
|
107
|
+
if (parts.length)
|
|
108
|
+
break;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (/^#{1,6}\s/.test(line)) {
|
|
112
|
+
if (parts.length)
|
|
113
|
+
break;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
parts.push(line);
|
|
117
|
+
if (parts.join(' ').length >= 200)
|
|
118
|
+
break;
|
|
119
|
+
}
|
|
120
|
+
return parts.join(' ').replace(/\s+/g, ' ').trim().slice(0, 200) || note.lead;
|
|
121
|
+
}
|
|
122
|
+
export async function dreamNotebook(cfg, opts = {}, signal) {
|
|
123
|
+
const windowDays = Math.min(365, Math.max(1, Math.trunc(opts.days ?? 7)));
|
|
124
|
+
const now = opts.now ?? new Date();
|
|
125
|
+
const sinceMs = now.getTime() - windowDays * 86_400_000;
|
|
126
|
+
// 顺序跑:两个 zk 进程同时补索引会撞 SQLite 写锁(lint 里同样处理)
|
|
127
|
+
const notes = await allNotes(cfg, {}, signal);
|
|
128
|
+
const edges = await graphEdges(cfg, signal);
|
|
129
|
+
// 入链来源按目标分组:既算「被引几次」,也给 dream 一份上下文(谁在引它)
|
|
130
|
+
const inbound = new Map();
|
|
131
|
+
for (const edge of edges) {
|
|
132
|
+
if (edge.sourcePath === edge.targetPath)
|
|
133
|
+
continue;
|
|
134
|
+
const sources = inbound.get(edge.targetPath) ?? [];
|
|
135
|
+
if (!sources.includes(edge.sourcePath))
|
|
136
|
+
sources.push(edge.sourcePath);
|
|
137
|
+
inbound.set(edge.targetPath, sources);
|
|
138
|
+
}
|
|
139
|
+
const citedOf = (n) => inbound.get(n.path)?.length ?? 0;
|
|
140
|
+
const windowNotes = notes
|
|
141
|
+
.filter((n) => {
|
|
142
|
+
const at = Date.parse(n.created);
|
|
143
|
+
return Number.isFinite(at) && at >= sinceMs;
|
|
144
|
+
})
|
|
145
|
+
.sort((a, b) => Date.parse(b.created) - Date.parse(a.created));
|
|
146
|
+
const newNotes = [];
|
|
147
|
+
const rejected = [];
|
|
148
|
+
for (const note of windowNotes) {
|
|
149
|
+
// 日记不是晋升候选:它的「未完成项」走 dailyLooseEnds,报成「无标签」只会制造噪音
|
|
150
|
+
if (isUnder(note.path, cfg.dailyDir))
|
|
151
|
+
continue;
|
|
152
|
+
const reason = rejectionReason(note);
|
|
153
|
+
if (reason) {
|
|
154
|
+
rejected.push({ title: note.title, path: note.path, reason });
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
newNotes.push({
|
|
158
|
+
title: note.title,
|
|
159
|
+
path: note.path,
|
|
160
|
+
type: note.type,
|
|
161
|
+
authority: note.authority,
|
|
162
|
+
tags: note.tags,
|
|
163
|
+
created: localDate(note.created),
|
|
164
|
+
lead: excerptOf(cfg, note),
|
|
165
|
+
cited: citedOf(note),
|
|
166
|
+
citedBy: (inbound.get(note.path) ?? []).slice(0, 5),
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
const dailyLooseEnds = [];
|
|
170
|
+
let looseEndCount = 0;
|
|
171
|
+
for (const note of windowNotes) {
|
|
172
|
+
if (!isUnder(note.path, cfg.dailyDir))
|
|
173
|
+
continue;
|
|
174
|
+
let body = '';
|
|
175
|
+
try {
|
|
176
|
+
body = fs.readFileSync(path.resolve(note.absPath || path.join(cfg.notebook, note.path)), 'utf8');
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
const items = looseEndsOf(body);
|
|
182
|
+
if (!items.length)
|
|
183
|
+
continue;
|
|
184
|
+
looseEndCount += items.length;
|
|
185
|
+
if (dailyLooseEnds.length < MAX_ITEMS) {
|
|
186
|
+
dailyLooseEnds.push({ path: note.path, date: localDate(note.created), items });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const topCited = notes
|
|
190
|
+
.map((n) => ({ title: n.title, path: n.path, cited: citedOf(n) }))
|
|
191
|
+
.filter((x) => x.cited > 0)
|
|
192
|
+
.sort((a, b) => b.cited - a.cited || a.title.localeCompare(b.title))
|
|
193
|
+
.slice(0, TOP_CITED);
|
|
194
|
+
return {
|
|
195
|
+
notebook: cfg.notebook,
|
|
196
|
+
windowDays,
|
|
197
|
+
since: localDate(new Date(sinceMs).toISOString()),
|
|
198
|
+
truncated: notes.length >= MAX_SCAN,
|
|
199
|
+
counts: {
|
|
200
|
+
window: windowNotes.length,
|
|
201
|
+
daily: windowNotes.filter((n) => isUnder(n.path, cfg.dailyDir)).length,
|
|
202
|
+
candidates: newNotes.length,
|
|
203
|
+
rejected: rejected.length,
|
|
204
|
+
looseEnds: looseEndCount,
|
|
205
|
+
},
|
|
206
|
+
newNotes: newNotes.slice(0, MAX_ITEMS),
|
|
207
|
+
rejected: rejected.slice(0, MAX_ITEMS),
|
|
208
|
+
topCited,
|
|
209
|
+
dailyLooseEnds,
|
|
210
|
+
};
|
|
211
|
+
}
|
package/dist/lib/dsh.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/lib/exec.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** 起子进程(zk / tar),带超时、abort、stdin 输入;错误统一成 ZkExecError。 */
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
export class ExecError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
stderr;
|
|
8
|
+
constructor(message, code, stderr) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = 'ExecError';
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.stderr = stderr;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** 跑一个可执行文件,返回 { code, stdout, stderr };ENOENT / 超时会 throw */
|
|
16
|
+
export function run(exe, args, opts = {}) {
|
|
17
|
+
return new Promise((resolve, reject) => {
|
|
18
|
+
const child = execFile(exe, args, {
|
|
19
|
+
cwd: opts.cwd,
|
|
20
|
+
env: opts.env,
|
|
21
|
+
signal: opts.signal,
|
|
22
|
+
timeout: opts.timeoutMs ?? 60_000,
|
|
23
|
+
maxBuffer: opts.maxBuffer ?? 32 * 1024 * 1024,
|
|
24
|
+
encoding: 'utf8',
|
|
25
|
+
windowsHide: true,
|
|
26
|
+
}, (err, stdout, stderr) => {
|
|
27
|
+
const out = String(stdout ?? '');
|
|
28
|
+
const errText = String(stderr ?? '');
|
|
29
|
+
if (err) {
|
|
30
|
+
const code = typeof err.code === 'number' ? err.code : null;
|
|
31
|
+
const hint = code === null ? String(err.message ?? err) : '';
|
|
32
|
+
reject(new ExecError(hint || (errText.trim() || `exit ${code}`), code, errText));
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
resolve({ code: 0, stdout: out, stderr: errText });
|
|
36
|
+
});
|
|
37
|
+
if (opts.input !== undefined) {
|
|
38
|
+
child.stdin?.on('error', () => { });
|
|
39
|
+
child.stdin?.end(opts.input);
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
child.stdin?.end();
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
/** PATH 里找可执行文件(Windows 认 PATHEXT) */
|
|
47
|
+
export function findOnPath(name) {
|
|
48
|
+
const raw = process.env.PATH ?? '';
|
|
49
|
+
const exts = process.platform === 'win32'
|
|
50
|
+
? (process.env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean)
|
|
51
|
+
: [''];
|
|
52
|
+
for (const dir of raw.split(path.delimiter)) {
|
|
53
|
+
if (!dir)
|
|
54
|
+
continue;
|
|
55
|
+
for (const ext of exts) {
|
|
56
|
+
const candidate = path.join(dir, name + ext);
|
|
57
|
+
try {
|
|
58
|
+
const st = fs.statSync(candidate);
|
|
59
|
+
if (st.isFile())
|
|
60
|
+
return candidate;
|
|
61
|
+
}
|
|
62
|
+
catch { /* 下一个 */ }
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 文件指纹:给「读盘结果」缓存做失效判断。
|
|
3
|
+
*
|
|
4
|
+
* 为什么不用 mtimeMs:毫秒粒度挡不住「同一毫秒里连写两次」—— 测试与 agent 批量改写
|
|
5
|
+
* 都是这种节奏;bigint stat 的 mtimeNs 在主流文件系统上是纳秒级,size / ino 再兜一层。
|
|
6
|
+
* 读不到(不存在 / 无权限)统一记成 absent:文件出现或消失,指纹自然会变。
|
|
7
|
+
*/
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
export function fileStamp(file) {
|
|
10
|
+
try {
|
|
11
|
+
const st = fs.statSync(file, { bigint: true });
|
|
12
|
+
return `${st.mtimeNs}:${st.size}:${st.ino}`;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return 'absent';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 极简 frontmatter 编辑器:只认 `key: value` 标量行。
|
|
3
|
+
*
|
|
4
|
+
* 为什么自己写而不引 YAML 库:
|
|
5
|
+
* · 只需要改 `status` / `superseded-by` 这类标量,别的行(`tags: []`、`title: 带: 冒号`)必须原样保留;
|
|
6
|
+
* · 反序列化再序列化会把用户的注释、引号风格、字段顺序全部重排,一次 supersede 就变成全文件 diff。
|
|
7
|
+
* 所以这里只做「按行替换 / 追加」,没见过的语法一律不碰。
|
|
8
|
+
*/
|
|
9
|
+
const DELIM = /^---[ \t]*$/;
|
|
10
|
+
const KEY_LINE = /^([A-Za-z0-9_-]+)[ \t]*:[ \t]*(.*)$/;
|
|
11
|
+
/** 解析头部 frontmatter;没有就是空对象(body 为原文) */
|
|
12
|
+
export function parseFrontmatter(content) {
|
|
13
|
+
const text = String(content ?? '');
|
|
14
|
+
const lines = text.split('\n');
|
|
15
|
+
if (!DELIM.test(lines[0] ?? ''))
|
|
16
|
+
return { fields: {}, body: text };
|
|
17
|
+
const end = lines.findIndex((line, i) => i > 0 && DELIM.test(line));
|
|
18
|
+
if (end < 0)
|
|
19
|
+
return { fields: {}, body: text };
|
|
20
|
+
const fields = {};
|
|
21
|
+
for (const line of lines.slice(1, end)) {
|
|
22
|
+
const m = line.match(KEY_LINE);
|
|
23
|
+
if (m)
|
|
24
|
+
fields[m[1]] = stripQuotes(m[2]);
|
|
25
|
+
}
|
|
26
|
+
return { fields, body: lines.slice(end + 1).join('\n') };
|
|
27
|
+
}
|
|
28
|
+
function stripQuotes(raw) {
|
|
29
|
+
const v = raw.trim();
|
|
30
|
+
// 双引号走 JSON:这样 \" 与 \n 这类转义读回来才是原字符,而不是带反斜杠的字面量
|
|
31
|
+
if (v.length >= 2 && v.startsWith('"') && v.endsWith('"')) {
|
|
32
|
+
try {
|
|
33
|
+
return String(JSON.parse(v));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return v.slice(1, -1);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (v.length >= 2 && v.startsWith("'") && v.endsWith("'"))
|
|
40
|
+
return v.slice(1, -1);
|
|
41
|
+
return v;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* 设置若干标量字段:已有的同名行就地替换,缺的追加在结尾分隔符之前;
|
|
45
|
+
* 值为 `undefined` 表示「删掉这个字段」。没有 frontmatter 就以最小块新建。
|
|
46
|
+
*/
|
|
47
|
+
export function setFrontmatter(content, patch) {
|
|
48
|
+
const text = String(content ?? '');
|
|
49
|
+
const lines = text.split('\n');
|
|
50
|
+
const has = DELIM.test(lines[0] ?? '');
|
|
51
|
+
const end = has ? lines.findIndex((line, i) => i > 0 && DELIM.test(line)) : -1;
|
|
52
|
+
const wellFormed = has && end > 0;
|
|
53
|
+
const head = [];
|
|
54
|
+
const replaced = new Set();
|
|
55
|
+
for (const line of wellFormed ? lines.slice(1, end) : []) {
|
|
56
|
+
const m = line.match(KEY_LINE);
|
|
57
|
+
if (m && m[1] in patch) {
|
|
58
|
+
// 就地替换:字段顺序不动,一次 supersede 的 diff 才只有那一行
|
|
59
|
+
replaced.add(m[1]);
|
|
60
|
+
const value = patch[m[1]];
|
|
61
|
+
if (value !== undefined)
|
|
62
|
+
head.push(`${m[1]}: ${value}`);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
head.push(line);
|
|
66
|
+
}
|
|
67
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
68
|
+
if (!replaced.has(key) && value !== undefined)
|
|
69
|
+
head.push(`${key}: ${value}`);
|
|
70
|
+
}
|
|
71
|
+
const body = wellFormed ? lines.slice(end + 1).join('\n') : text;
|
|
72
|
+
const block = ['---', ...head, '---'].join('\n');
|
|
73
|
+
return wellFormed ? `${block}\n${body}` : `${block}\n\n${body}`;
|
|
74
|
+
}
|
package/dist/lib/http.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export function json(res, status, body) {
|
|
2
|
+
const payload = JSON.stringify(body);
|
|
3
|
+
res.statusCode = status;
|
|
4
|
+
res.setHeader('content-type', 'application/json; charset=utf-8');
|
|
5
|
+
res.setHeader('cache-control', 'no-store');
|
|
6
|
+
res.end(payload);
|
|
7
|
+
}
|
|
8
|
+
/** 读请求体(上限 1 MiB,超出直接截断 —— 设置页不会传这么大的东西) */
|
|
9
|
+
export async function readBody(req, limit = 1024 * 1024) {
|
|
10
|
+
const chunks = [];
|
|
11
|
+
let size = 0;
|
|
12
|
+
for await (const chunk of req) {
|
|
13
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
14
|
+
size += buf.length;
|
|
15
|
+
if (size > limit)
|
|
16
|
+
break;
|
|
17
|
+
chunks.push(buf);
|
|
18
|
+
}
|
|
19
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
20
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 安装内置 zk:下载官方 release → 解包到 ~/.dsh/zdiary/bin → 真跑一次 --version。
|
|
3
|
+
*
|
|
4
|
+
* 只信「跑得起来」这一条:下载完不验证能执行,就等于没装。
|
|
5
|
+
* 镜像:设 ZK_DOWNLOAD_BASE(例如 https://ghproxy.example.com/https://github.com)可换源。
|
|
6
|
+
*/
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { BIN_DIR, CACHE_DIR, expandHome } from '../config/paths.js';
|
|
10
|
+
import { run } from './exec.js';
|
|
11
|
+
import { zkAsset } from './platform.js';
|
|
12
|
+
import { managedBin, versionOf, ZkError } from './zk.js';
|
|
13
|
+
/** 给人看的一句话来源:装完要让用户知道刚才信任了谁 */
|
|
14
|
+
export function sourceLabel(mirror) {
|
|
15
|
+
return mirror ? `自定义镜像 ${mirror}` : 'github.com';
|
|
16
|
+
}
|
|
17
|
+
export async function installZk(version, signal) {
|
|
18
|
+
const target = zkAsset(version);
|
|
19
|
+
if (!target) {
|
|
20
|
+
throw new ZkError(`暂不支持自动安装(${process.platform}/${process.arch})`, '请自己装一份 zk 并把路径填进设置 →「zk 路径」:https://github.com/zk-org/zk#installation');
|
|
21
|
+
}
|
|
22
|
+
const mirror = (process.env.ZK_DOWNLOAD_BASE ?? '').replace(/\/+$/, '') || null;
|
|
23
|
+
fs.mkdirSync(BIN_DIR, { recursive: true });
|
|
24
|
+
fs.mkdirSync(CACHE_DIR, { recursive: true });
|
|
25
|
+
const tarFile = path.join(CACHE_DIR, target.asset);
|
|
26
|
+
let res;
|
|
27
|
+
try {
|
|
28
|
+
res = await fetch(target.url, { signal, redirect: 'follow' });
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
throw new ZkError('下载 zk 失败:' + String(err instanceof Error ? err.message : err), '检查网络,或用 ZK_DOWNLOAD_BASE 指定镜像;也可以自己装 zk 后填「zk 路径」');
|
|
32
|
+
}
|
|
33
|
+
if (!res.ok || !res.body) {
|
|
34
|
+
throw new ZkError(`下载 zk 失败:HTTP ${res.status}`, target.url);
|
|
35
|
+
}
|
|
36
|
+
fs.writeFileSync(tarFile, Buffer.from(await res.arrayBuffer()));
|
|
37
|
+
try {
|
|
38
|
+
await run('tar', ['-xzf', tarFile, '-C', BIN_DIR, target.bin], { signal, timeoutMs: 120_000 });
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
throw new ZkError('解包失败(需要系统 tar)', String(err instanceof Error ? err.message : err) + ' —— 也可以手动解包后把 zk 放到 ' + BIN_DIR);
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
try {
|
|
45
|
+
fs.unlinkSync(tarFile);
|
|
46
|
+
}
|
|
47
|
+
catch { /* 缓存目录里残留也无所谓 */ }
|
|
48
|
+
}
|
|
49
|
+
const bin = managedBin();
|
|
50
|
+
if (!fs.existsSync(bin))
|
|
51
|
+
throw new ZkError('解包后没找到 zk 可执行文件', bin);
|
|
52
|
+
try {
|
|
53
|
+
fs.chmodSync(bin, 0o755);
|
|
54
|
+
}
|
|
55
|
+
catch { /* Windows 不需要 */ }
|
|
56
|
+
const actual = await versionOf(bin);
|
|
57
|
+
if (!actual)
|
|
58
|
+
throw new ZkError('装好的 zk 跑不起来', bin);
|
|
59
|
+
// 镜像不给校验和(上游 release 也没有 checksums.txt),至少把「实际从哪下的」交回去
|
|
60
|
+
return { path: bin, version: actual, asset: target.asset, url: target.url, mirror };
|
|
61
|
+
}
|
|
62
|
+
/** 用户手动指的那个路径是不是真的 zk */
|
|
63
|
+
export async function verifyZkPath(p) {
|
|
64
|
+
const abs = path.resolve(expandHome(p));
|
|
65
|
+
if (!fs.existsSync(abs))
|
|
66
|
+
return { ok: false, error: '文件不存在:' + abs };
|
|
67
|
+
const version = await versionOf(abs);
|
|
68
|
+
return version ? { ok: true, version } : { ok: false, error: '跑不起来或不是 zk:' + abs };
|
|
69
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** 小工具:读 JSON(坏文件不炸宿主)、原子写 JSON。 */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
export function readJson(file, fallback) {
|
|
5
|
+
try {
|
|
6
|
+
const raw = fs.readFileSync(file, 'utf8');
|
|
7
|
+
return JSON.parse(raw);
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return fallback;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** 写临时文件再 rename:中途崩了也不会留下半个 JSON */
|
|
14
|
+
export function writeJson(file, value, mode) {
|
|
15
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
16
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
17
|
+
fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n', mode ? { mode } : undefined);
|
|
18
|
+
fs.renameSync(tmp, file);
|
|
19
|
+
}
|