@kpeace/dsh-prompt-notes 0.0.0-stage → 0.3.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/src/routes.js ADDED
@@ -0,0 +1,208 @@
1
+ /**
2
+ * HTTP 路由:面板(客户端半体)读写便签、读取系统注入内容的唯一通道。
3
+ *
4
+ * GET /dsh-prompt-notes/state?session=&cwd= → 全量状态(相对该会话/工作目录的观察者)
5
+ * GET /dsh-prompt-notes/preview?session=&cwd= → 该观察者的 system prompt 里实际注入的便签文本
6
+ * GET /dsh-prompt-notes/system?session=&cwd= → 系统自带注入内容(真实 assemble 结果 / skills / MCP)
7
+ * POST /dsh-prompt-notes/notes → 新建
8
+ * PUT /dsh-prompt-notes/notes/:id → 部分更新
9
+ * DELETE /dsh-prompt-notes/notes/:id → 删除(进回收站,不是真删)
10
+ * POST /dsh-prompt-notes/notes/:id/restore → 从回收站捡回来
11
+ * PUT /dsh-prompt-notes/paused → {paused:boolean} 总开关
12
+ * GET /dsh-prompt-notes/export?ids=a,b → 导出一组(缺省全部)便签的分享文件
13
+ * POST /dsh-prompt-notes/import/preview → {bundle,strategy} 只算「会发生什么」,不写
14
+ * POST /dsh-prompt-notes/import → {bundle,strategy} 真的导入,回全量状态
15
+ *
16
+ * 导入是两步:先 preview 看「新建 / 重命名 / 覆盖 / 跳过」和将被执行的 MCP 命令,再确认。
17
+ *
18
+ * 所有写接口都回「写完之后的全量状态」,客户端直接替换,不用自己合并。
19
+ *
20
+ * 写接口的防护:本机服务上的 POST 可以被任意网页用 <form> 跨站发起,
21
+ * 而这些便签最终会进模型的 system prompt(MCP 便签甚至会启动本地进程)——
22
+ * 等于给别人一个远程改提示词/执行命令的口子。所以写请求必须带自定义头
23
+ * (跨站请求带自定义头会触发预检,而本路由不答 CORS,浏览器直接拦掉),
24
+ * 并且显式拒绝 Sec-Fetch-Site: cross-site。读请求不受此限(同样没有 CORS 头,跨站读不到)。
25
+ */
26
+ import { isAbsolute } from 'node:path'
27
+ import { LIMITS, describeNotes, displayTitle, planInjection, renderSection } from './notes.js'
28
+ import { createNote, deleteNote, restoreNote, updateNote } from './mutations.js'
29
+ import { applyImport, packBundle, parseBundle, planImport } from './share.js'
30
+
31
+ export const ROUTE_PREFIX = '/dsh-prompt-notes/'
32
+ export const GUARD_HEADER = 'x-dsh-prompt-notes'
33
+ const MAX_BODY_BYTES = 256 * 1024
34
+ const SESSION_ID = /^[A-Za-z0-9_.:-]{1,128}$/
35
+
36
+ function sendJson(res, status, payload) {
37
+ const body = JSON.stringify(payload)
38
+ res.writeHead(status, {
39
+ 'content-type': 'application/json; charset=utf-8',
40
+ 'cache-control': 'no-store',
41
+ 'content-length': Buffer.byteLength(body),
42
+ })
43
+ res.end(body)
44
+ }
45
+
46
+ function readJsonBody(req) {
47
+ return new Promise((resolve, reject) => {
48
+ const chunks = []
49
+ let size = 0
50
+ req.on('data', (chunk) => {
51
+ size += chunk.length
52
+ if (size > MAX_BODY_BYTES) {
53
+ reject(new Error('request body too large'))
54
+ req.destroy()
55
+ return
56
+ }
57
+ chunks.push(chunk)
58
+ })
59
+ req.on('end', () => {
60
+ const text = Buffer.concat(chunks).toString('utf8').trim()
61
+ if (!text) return resolve(undefined)
62
+ try { resolve(JSON.parse(text)) } catch { reject(new Error('invalid JSON')) }
63
+ })
64
+ req.on('error', reject)
65
+ })
66
+ }
67
+
68
+ /**
69
+ * @param {{ store, maxChars: number, order: number, file: string,
70
+ * host?: { resolveViewer?, liveSessionIds?, system?, mcpRuntime?, mcpAllowed? } }} deps
71
+ * host 是 index.js 提供的、需要 cordis 服务的能力;单测可以不传(退化成「只看 query 里的观察者」)。
72
+ */
73
+ export function createHandler({ store, maxChars, order, file, host = {} }) {
74
+ const viewerFrom = (url) => {
75
+ const s = url.searchParams.get('session') ?? ''
76
+ const c = url.searchParams.get('cwd') ?? ''
77
+ const query = {
78
+ sessionId: SESSION_ID.test(s) ? s : undefined,
79
+ cwd: c && isAbsolute(c) && c.length <= LIMITS.target ? c : undefined,
80
+ }
81
+ return host.resolveViewer ? host.resolveViewer(query) : { sessionId: query.sessionId, cwd: query.cwd }
82
+ }
83
+
84
+ const buildState = (viewer) => {
85
+ const doc = store.snapshot()
86
+ const plan = planInjection(doc.notes, maxChars, { paused: doc.paused, viewer })
87
+ const runtime = host.mcpRuntime ? host.mcpRuntime() : {}
88
+ return {
89
+ revision: store.revision,
90
+ paused: doc.paused,
91
+ viewer: { sessionId: viewer.sessionId ?? null, cwd: viewer.cwd ?? null },
92
+ notes: describeNotes(doc.notes, plan, { paused: doc.paused, viewer, runtime }),
93
+ budget: { used: plan.used, max: plan.max },
94
+ limits: LIMITS,
95
+ sectionOrder: order,
96
+ file,
97
+ mcpAllowed: host.mcpAllowed !== false,
98
+ liveSessions: host.liveSessionIds ? host.liveSessionIds() : [],
99
+ }
100
+ }
101
+
102
+ const guardWrite = (req, res) => {
103
+ if (req.headers[GUARD_HEADER] !== '1' || req.headers['sec-fetch-site'] === 'cross-site') {
104
+ sendJson(res, 403, { error: 'forbidden' })
105
+ return false
106
+ }
107
+ return true
108
+ }
109
+
110
+ const handle = async (req, res) => {
111
+ const method = (req.method ?? 'GET').toUpperCase()
112
+ const url = new URL(req.url ?? '/', 'http://localhost')
113
+ if (!url.pathname.startsWith(ROUTE_PREFIX)) return sendJson(res, 404, { error: 'not found' })
114
+ const path = url.pathname.slice(ROUTE_PREFIX.length - 1) // 保留前导 /
115
+
116
+ if (method === 'GET' || method === 'HEAD') {
117
+ const viewer = viewerFrom(url)
118
+ if (path === '/state') return sendJson(res, 200, buildState(viewer))
119
+ if (path === '/export') {
120
+ const ids = (url.searchParams.get('ids') ?? '').split(',').map((x) => x.trim()).filter(Boolean)
121
+ return sendJson(res, 200, packBundle(store.snapshot().notes, { ids }))
122
+ }
123
+ if (path === '/preview') {
124
+ const doc = store.snapshot()
125
+ const plan = planInjection(doc.notes, maxChars, { paused: doc.paused, viewer })
126
+ const text = renderSection(plan.injected)
127
+ return sendJson(res, 200, { text, chars: text.length, count: plan.injected.length, paused: doc.paused })
128
+ }
129
+ if (path === '/system') {
130
+ if (!host.system) return sendJson(res, 200, { session: { id: viewer.sessionId ?? null, cwd: viewer.cwd ?? null, found: false }, sections: [], contexts: [], skills: [], mcp: [], tools: { count: 0, mcpCount: 0 }, errors: ['system linkage unavailable'] })
131
+ return sendJson(res, 200, await host.system({ sessionId: viewer.sessionId, cwd: viewer.cwd }))
132
+ }
133
+ return sendJson(res, 404, { error: 'not found' })
134
+ }
135
+
136
+ if (!guardWrite(req, res)) return
137
+ // 写接口回的状态也要相对调用者的观察者,所以写请求同样带 ?session=&cwd=
138
+ const viewer = viewerFrom(url)
139
+
140
+ if (path === '/notes' && method === 'POST') {
141
+ const result = await createNote(store, await readJsonBody(req))
142
+ if (!result.ok) return sendJson(res, result.status, { error: result.error })
143
+ return sendJson(res, 201, buildState(viewer))
144
+ }
145
+
146
+ if ((path === '/import/preview' || path === '/import') && method === 'POST') {
147
+ const body = await readJsonBody(req)
148
+ const parsed = parseBundle(body && body.bundle)
149
+ if (!parsed.ok) return sendJson(res, 400, { error: parsed.error })
150
+ const plan = planImport(store.snapshot().notes, parsed.notes, body && body.strategy)
151
+ if (path === '/import/preview') {
152
+ // 预览只说「会发生什么」:动作 + 名字 + 将被执行的命令 + 被丢弃的条目
153
+ return sendJson(res, 200, {
154
+ counts: plan.counts,
155
+ warnings: plan.warnings,
156
+ dropped: parsed.dropped,
157
+ actions: plan.actions.map((a) => ({
158
+ action: a.action,
159
+ kind: a.note ? a.note.kind : undefined,
160
+ title: a.note ? displayTitle(a.note) : a.title,
161
+ name: a.note && a.note.mcp ? a.note.mcp.name : a.note && a.note.skill ? a.note.skill.name : undefined,
162
+ reason: a.reason,
163
+ })),
164
+ })
165
+ }
166
+ const result = await applyImport(store, plan)
167
+ return sendJson(res, 200, { ...buildState(viewer), imported: result, counts: plan.counts, warnings: plan.warnings })
168
+ }
169
+
170
+ if (path === '/paused' && method === 'PUT') {
171
+ const body = await readJsonBody(req)
172
+ if (!body || typeof body.paused !== 'boolean') return sendJson(res, 400, { error: 'body must be {"paused": boolean}' })
173
+ await store.mutate((doc) => { doc.paused = body.paused })
174
+ return sendJson(res, 200, buildState(viewer))
175
+ }
176
+
177
+ const restore = /^\/notes\/([A-Za-z0-9-]{1,64})\/restore$/.exec(path)
178
+ if (restore && method === 'POST') {
179
+ const result = await restoreNote(store, restore[1])
180
+ if (!result.ok) return sendJson(res, result.status, { error: result.error })
181
+ return sendJson(res, 200, buildState(viewer))
182
+ }
183
+
184
+ const m = /^\/notes\/([A-Za-z0-9-]{1,64})$/.exec(path)
185
+ if (m) {
186
+ const id = m[1]
187
+ if (method === 'PUT') {
188
+ const result = await updateNote(store, id, await readJsonBody(req))
189
+ if (!result.ok) return sendJson(res, result.status, { error: result.error })
190
+ return sendJson(res, 200, buildState(viewer))
191
+ }
192
+ if (method === 'DELETE') {
193
+ await deleteNote(store, id)
194
+ return sendJson(res, 200, buildState(viewer))
195
+ }
196
+ }
197
+
198
+ res.writeHead(405, { allow: 'GET, HEAD, POST, PUT, DELETE' })
199
+ res.end()
200
+ }
201
+
202
+ return (req, res) => {
203
+ handle(req, res).catch((error) => {
204
+ if (!res.headersSent) sendJson(res, 400, { error: String(error?.message ?? error) })
205
+ else res.end()
206
+ })
207
+ }
208
+ }
package/src/share.js ADDED
@@ -0,0 +1,231 @@
1
+ /**
2
+ * 分享:把便签导成一份 JSON,再从 JSON 导入回来(单张 / 一组 / 全部)。
3
+ *
4
+ * 这里的每一条规则都是为了「导入别人的东西不会悄悄改变我的环境」:
5
+ * 1. 导入的 MCP 便签**一律未钉住**——钉上等于在本机执行一条命令;
6
+ * 预览里必须把将要执行的命令原样显示出来,让用户自己决定要不要钉。
7
+ * 2. 文件带 `format` / `version`;不认识的格式、超大的文件、逐条坏掉的便签,
8
+ * 都只报告、不半途写入(导入是「先预览、后确认」两步)。
9
+ * 3. 冲突(同 id / 同技能名 / 同 MCP 名)默认**重命名**:一个文件丢进别人的便签簿,
10
+ * 最安全的默认不是覆盖他已有的东西。
11
+ * 4. 导入的每一条都要过 parseNoteInput —— 和面板手写、助手创建同一个校验口径。
12
+ */
13
+ import { LIMITS, SKILL_NAME, MCP_NAME, parseNoteInput } from './notes.js'
14
+
15
+ export const SHARE_FORMAT = 'dsh-prompt-notes'
16
+ export const SHARE_VERSION = 1
17
+ export const SHARE_LIMITS = Object.freeze({
18
+ /** 一份导入文件最多这么大(字符数,含 JSON 结构)。 */
19
+ bytes: 200 * 1024,
20
+ /** 一份导入文件最多这么多条。 */
21
+ notes: LIMITS.notes,
22
+ })
23
+ /** 冲突策略。默认重命名。 */
24
+ export const STRATEGIES = Object.freeze(['rename', 'skip', 'overwrite'])
25
+
26
+ const pick = (note) => ({
27
+ id: note.id,
28
+ kind: note.kind,
29
+ scope: note.scope,
30
+ target: note.target,
31
+ title: note.title,
32
+ body: note.body,
33
+ tags: note.tags,
34
+ color: note.color,
35
+ enabled: note.enabled,
36
+ ...(note.skill ? { skill: note.skill } : {}),
37
+ ...(note.mcp ? { mcp: note.mcp } : {}),
38
+ })
39
+
40
+ /**
41
+ * 导出:把若干张便签包成一份可分享的文件。
42
+ * @param {object[]} notes 全部便签
43
+ * @param {{ ids?: string[] }} [opts] 只导出这些 id(缺省 = 全部)
44
+ */
45
+ export function packBundle(notes, opts = {}) {
46
+ const wanted = Array.isArray(opts.ids) && opts.ids.length ? new Set(opts.ids) : null
47
+ const picked = notes.filter((n) => !wanted || wanted.has(n.id))
48
+ return {
49
+ format: SHARE_FORMAT,
50
+ version: SHARE_VERSION,
51
+ exportedAt: new Date().toISOString(),
52
+ notes: picked.map(pick),
53
+ }
54
+ }
55
+
56
+ /**
57
+ * 解析导入文件:检查格式 / 版本 / 体积 / 条数,再逐条校验。
58
+ * 坏的条目单条丢弃并报告,不因为一条坏就整份失败。
59
+ * @returns {{ ok: true, notes: object[], dropped: object[] } | { ok: false, error: string }}
60
+ */
61
+ export function parseBundle(raw) {
62
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return { ok: false, error: '导入内容必须是一个 JSON 对象' }
63
+ if (raw.format !== SHARE_FORMAT) return { ok: false, error: `不是便签文件(format 应为 "${SHARE_FORMAT}")` }
64
+ const version = Number(raw.version)
65
+ if (!Number.isFinite(version) || version < 1 || version > SHARE_VERSION) return { ok: false, error: `不支持的版本 ${raw.version}` }
66
+ if (!Array.isArray(raw.notes)) return { ok: false, error: 'notes 必须是数组' }
67
+ if (raw.notes.length > SHARE_LIMITS.notes) return { ok: false, error: `一次最多导入 ${SHARE_LIMITS.notes} 条` }
68
+ let bytes = 0
69
+ try { bytes = JSON.stringify(raw).length } catch { return { ok: false, error: '导入内容无法序列化' } }
70
+ if (bytes > SHARE_LIMITS.bytes) return { ok: false, error: `文件太大(${Math.round(bytes / 1024)}KB > ${Math.round(SHARE_LIMITS.bytes / 1024)}KB)` }
71
+
72
+ const notes = []
73
+ const dropped = []
74
+ for (const [index, item] of raw.notes.entries()) {
75
+ if (!item || typeof item !== 'object' || Array.isArray(item)) { dropped.push({ index, reason: '不是对象' }); continue }
76
+ const { id: sourceId, createdAt, updatedAt, ...fields } = item
77
+ const parsed = parseNoteInput(fields)
78
+ if (!parsed.ok) { dropped.push({ index, reason: parsed.error }); continue }
79
+ // 导入的 MCP 一律未钉住:钉上等于在本机执行一条命令,只能由人决定。
80
+ const value = parsed.value.kind === 'mcp' ? { ...parsed.value, enabled: false } : parsed.value
81
+ notes.push({ ...value, sourceId: typeof sourceId === 'string' ? sourceId : undefined })
82
+ }
83
+ return { ok: true, notes, dropped }
84
+ }
85
+
86
+ /** 名字冲突时找一个没被占用的后缀:go-review → go-review-2 → go-review-3 …(砍到长度上限仍不合法就放弃) */
87
+ function freeName(base, isTaken, max) {
88
+ const clip = (s) => (s.length > max ? s.slice(0, max) : s)
89
+ if (!isTaken(clip(base))) return clip(base)
90
+ for (let i = 2; i < 100; i++) {
91
+ const candidate = clip(`${base}-${i}`)
92
+ if (!isTaken(candidate)) return candidate
93
+ }
94
+ return null
95
+ }
96
+
97
+ /**
98
+ * 算出「这份文件导入进来会发生什么」。不写盘——预览和真正导入用的是同一个函数,
99
+ * 所以预览里看到的动作就是点下去之后会做的事。
100
+ *
101
+ * @param {object[]} existing 现有便签
102
+ * @param {object[]} incoming parseBundle 的结果
103
+ * @param {'rename'|'skip'|'overwrite'} strategy
104
+ * @returns {{ actions: object[], counts: object, warnings: string[] }}
105
+ */
106
+ export function planImport(existing, incoming, strategy = 'rename') {
107
+ const mode = STRATEGIES.includes(strategy) ? strategy : 'rename'
108
+ const byId = new Map(existing.map((n) => [n.id, n]))
109
+ // skill 名只在同一个 scope+target 里唯一,MCP 名全局唯一 —— 用两个复合键的集合表达
110
+ const usedSkill = new Set(existing.filter((n) => n.kind === 'skill' && n.skill).map((n) => `${n.skill.name}|${n.scope}|${n.target}`))
111
+ const usedMcp = new Set(existing.filter((n) => n.kind === 'mcp' && n.mcp).map((n) => n.mcp.name))
112
+ // 同一份文件里也可能自己撞自己:新占用的名字立刻进集合,下一条就能看到
113
+ const takenSkill = (name, scope, target) => usedSkill.has(`${name}|${scope}|${target}`)
114
+ const takenMcp = (name) => usedMcp.has(name)
115
+ const remember = (n) => {
116
+ if (n.skill) usedSkill.add(`${n.skill.name}|${n.scope}|${n.target}`)
117
+ if (n.mcp) usedMcp.add(n.mcp.name)
118
+ }
119
+
120
+ const actions = []
121
+ const warnings = []
122
+ const counts = { create: 0, rename: 0, overwrite: 0, skip: 0 }
123
+
124
+ for (const note of incoming) {
125
+ const idHit = note.sourceId && byId.has(note.sourceId) ? byId.get(note.sourceId) : null
126
+ const nameHit = note.kind === 'mcp'
127
+ ? (note.mcp && takenMcp(note.mcp.name) ? 'name' : null)
128
+ : note.kind === 'skill'
129
+ ? (note.skill && takenSkill(note.skill.name, note.scope, note.target) ? 'name' : null)
130
+ : null
131
+
132
+ const note_mcp = note.kind === 'mcp' ? note.mcp : null
133
+ if (note_mcp) {
134
+ // 预览里要给出「钉上之后会执行的完整一行命令」,而不是只给命令名
135
+ const line = [note_mcp.command, ...(Array.isArray(note_mcp.args) ? note_mcp.args : [])].filter(Boolean).join(' ') || note_mcp.url
136
+ warnings.push(`MCP "${note_mcp.name}" 导入后是未钉住的;钉上会执行:${line}`)
137
+ }
138
+
139
+ const push = (action, extra) => {
140
+ counts[action]++
141
+ actions.push({ index: actions.length, action, ...extra })
142
+ }
143
+
144
+ // 1) 同 id
145
+ if (idHit) {
146
+ if (mode === 'skip') { push('skip', { reason: '同 id 已存在', title: idHit.title }); continue }
147
+ if (mode === 'overwrite') {
148
+ push('overwrite', { replaceId: idHit.id, note: { ...note, id: idHit.id, createdAt: idHit.createdAt } })
149
+ continue
150
+ }
151
+ // rename:id 换成新的,然后照常处理名字冲突
152
+ const entry = { ...note, id: undefined }
153
+ if (nameHit) {
154
+ const renamed = renameFor(entry, takenSkill, takenMcp)
155
+ if (!renamed) { push('skip', { reason: '找不到可用的新名字' }); continue }
156
+ remember(renamed)
157
+ push('rename', { note: renamed, reason: '同 id 已存在' })
158
+ continue
159
+ }
160
+ push('rename', { note: entry, reason: '同 id 已存在,另存一份' })
161
+ continue
162
+ }
163
+
164
+ // 2) 名字冲突(mcp 名全局唯一;skill 名在 scope+target 内唯一)
165
+ if (nameHit) {
166
+ if (mode === 'skip') { push('skip', { reason: '名字已被占用' }); continue }
167
+ if (mode === 'overwrite') {
168
+ const victim = note.kind === 'mcp'
169
+ ? existing.find((n) => n.kind === 'mcp' && n.mcp && n.mcp.name === note.mcp.name)
170
+ : existing.find((n) => n.kind === 'skill' && n.skill && n.skill.name === note.skill.name && n.scope === note.scope && n.target === note.target)
171
+ push('overwrite', { replaceId: victim.id, note: { ...note, id: victim.id, createdAt: victim.createdAt } })
172
+ continue
173
+ }
174
+ const renamed = renameFor(note, takenSkill, takenMcp)
175
+ if (!renamed) { push('skip', { reason: '找不到可用的新名字' }); continue }
176
+ remember(renamed)
177
+ push('rename', { note: renamed, reason: '名字已被占用' })
178
+ continue
179
+ }
180
+
181
+ // 3) 干净的新便签
182
+ const entry = { ...note }
183
+ remember(entry)
184
+ push('create', { note: entry })
185
+ }
186
+
187
+ return { actions, counts, warnings }
188
+ }
189
+
190
+ /** 按 kind 把名字改成没被占用的那个。名字有长度上限,用 SKILL_NAME / MCP_NAME 再校验一次。 */
191
+ function renameFor(note, takenSkill, takenMcp) {
192
+ if (note.kind === 'skill' && note.skill) {
193
+ const next = freeName(note.skill.name, (n) => takenSkill(n, note.scope, note.target), 64)
194
+ if (!next || !SKILL_NAME.test(next)) return null
195
+ return { ...note, skill: { ...note.skill, name: next } }
196
+ }
197
+ if (note.kind === 'mcp' && note.mcp) {
198
+ const next = freeName(note.mcp.name, takenMcp, 32)
199
+ if (!next || !MCP_NAME.test(next)) return null
200
+ return { ...note, mcp: { ...note.mcp, name: next } }
201
+ }
202
+ // 提示词没有名字可改:同 id 的情况已经另起了新 id,这里只可能是不该发生的情况
203
+ return { ...note }
204
+ }
205
+
206
+ /**
207
+ * 执行计划:一次 mutate 写完全部动作(中间不会有半份状态)。
208
+ * @returns {Promise<{added:number, replaced:number, skipped:number}>}
209
+ */
210
+ export async function applyImport(store, plan, now = new Date().toISOString()) {
211
+ let added = 0
212
+ let replaced = 0
213
+ let skipped = 0
214
+ await store.mutate((doc) => {
215
+ for (const action of plan.actions) {
216
+ if (action.action === 'skip') { skipped++; continue }
217
+ if (action.action === 'overwrite' && action.replaceId) {
218
+ const idx = doc.notes.findIndex((n) => n.id === action.replaceId)
219
+ if (idx < 0) { skipped++; continue }
220
+ doc.notes[idx] = { ...doc.notes[idx], ...action.note, id: action.replaceId, updatedAt: now }
221
+ replaced++
222
+ continue
223
+ }
224
+ if (doc.notes.length >= LIMITS.notes) { skipped++; continue }
225
+ // 不带 id:由 store 的清洗环节分配(它同时会重建 allowlist 过的字段)
226
+ doc.notes.push({ ...action.note, createdAt: now, updatedAt: now })
227
+ added++
228
+ }
229
+ })
230
+ return { added, replaced, skipped }
231
+ }
package/src/store.js ADDED
@@ -0,0 +1,214 @@
1
+ /**
2
+ * 便签存储:一个 JSON 文件,同步读、原子写。
3
+ *
4
+ * 为什么同步读:system prompt 的 section provider 必须在「组装那一刻」同步拿到答案。
5
+ * 所以内存里始终有一份快照;读取时最多做一次廉价的 stat,发现文件被外部改过就重读。
6
+ *
7
+ * TODO(prompt-notes): 互通分享。这个文件(version 2)就是预期的交换格式;还缺:
8
+ * - 导出/导入单张或一组便签(导入时对 id、skill 名、MCP 名冲突的处理策略);
9
+ * - 导入来的 MCP 便签必须默认「未钉住」并明确提示将执行的命令,不能静默启用;
10
+ * - 来源与签名字段(谁分享的、是否被篡改),避免同事的提示词被悄悄替换。
11
+ * 误删恢复:删除不是真删——被删的便签进文件的 `trash` 区(最近 50 条、30 天),
12
+ * 面板上可以撤销;超出上限或过期的在每次写盘前清掉。MCP 便签进 trash 时进程也随之撤掉。
13
+ *
14
+ * 为什么放 DSH_HOME 而不是某个 profile 目录:提示词是个人/团队的偏好,不属于某个项目,
15
+ * 也不该因为换了 profile 就丢;以后做「互通分享」时,这个文件本身就是交换格式。
16
+ */
17
+ import { copyFileSync, readFileSync, statSync } from 'node:fs'
18
+ import { mkdir, rename, writeFile } from 'node:fs/promises'
19
+ import { homedir } from 'node:os'
20
+ import { dirname, join } from 'node:path'
21
+ import { randomUUID } from 'node:crypto'
22
+ import { LIMITS, parseNoteInput } from './notes.js'
23
+
24
+ /** v2:新增 kind / scope / target / skill / mcp。v1 的便签读入时自动补成 prompt + global。 */
25
+ const FILE_VERSION = 3
26
+ /** 文件超过这个大小就当坏文件(200 条 × 20k 字 = 4MB 上限的两倍留给 JSON 开销)。 */
27
+ const MAX_FILE_BYTES = 8 * 1024 * 1024
28
+ /** 回收站上限:条数与天数。超过就先丢最旧的——它只是「撤销」,不是归档。 */
29
+ const TRASH_MAX = 50
30
+ const TRASH_DAYS = 30
31
+ /** 外部改动的探测间隔:太勤没意义,太懒又会让手改看起来「没生效」。 */
32
+ const STAT_INTERVAL_MS = 1000
33
+
34
+ export function resolveDataFile(configured, env = process.env) {
35
+ if (typeof configured === 'string' && configured.trim()) return configured.trim()
36
+ const home = env.DSH_HOME?.trim()
37
+ if (home) return join(home, 'prompt-notes', 'notes.json')
38
+ return join(env.HOME?.trim() || homedir(), '.dsh', 'prompt-notes', 'notes.json')
39
+ }
40
+
41
+ function emptyDoc() {
42
+ return { version: FILE_VERSION, paused: false, notes: [], trash: [] }
43
+ }
44
+
45
+ /** v1 用主题 token 当颜色名;升级时映射到纸色(由 parseNoteInput 兜底校验)。 */
46
+ const LEGACY_PAPER = { brand: 'yellow', success: 'green', warn: 'pink', error: 'pink', idle: 'lilac' }
47
+
48
+ /**
49
+ * 把磁盘上读到的东西洗成合法文档:未知字段丢弃,永不抛。
50
+ * 非法的条目(手改写坏了的)不进文档,但会被计入 dropped,由调用方留备份——
51
+ * 否则下一次保存会悄悄把它们从文件里抹掉。
52
+ * @returns {{ doc: object, dropped: number }}
53
+ */
54
+ function sanitizeDoc(raw) {
55
+ const doc = emptyDoc()
56
+ let dropped = 0
57
+ if (!raw || typeof raw !== 'object') return { doc, dropped }
58
+ doc.paused = raw.paused === true
59
+ const ids = new Set()
60
+ for (const n of Array.isArray(raw.notes) ? raw.notes : []) {
61
+ if (!n || typeof n !== 'object') { dropped++; continue }
62
+ const input = { ...n, kind: n.kind ?? 'prompt', scope: n.scope ?? 'global', enabled: n.enabled === true }
63
+ if (input.color in LEGACY_PAPER) input.color = LEGACY_PAPER[input.color]
64
+ delete input.id
65
+ const parsed = parseNoteInput(input)
66
+ if (!parsed.ok) { dropped++; continue }
67
+ const id = typeof n.id === 'string' && n.id && !ids.has(n.id) ? n.id : randomUUID()
68
+ ids.add(id)
69
+ const now = new Date().toISOString()
70
+ doc.notes.push({
71
+ id,
72
+ ...parsed.value,
73
+ createdAt: typeof n.createdAt === 'string' ? n.createdAt : now,
74
+ updatedAt: typeof n.updatedAt === 'string' ? n.updatedAt : now,
75
+ })
76
+ if (doc.notes.length >= LIMITS.notes) break
77
+ }
78
+ // 回收站:每条自带删除时间;坏的条目直接丢(它只是便利功能,不值得为它留备份)
79
+ for (const item of Array.isArray(raw.trash) ? raw.trash : []) {
80
+ if (!item || typeof item !== 'object' || !item.note || typeof item.note !== 'object') continue
81
+ const input = { ...item.note, kind: item.note.kind ?? 'prompt', scope: item.note.scope ?? 'global', enabled: item.note.enabled === true }
82
+ if (input.color in LEGACY_PAPER) input.color = LEGACY_PAPER[input.color]
83
+ const id = typeof input.id === 'string' ? input.id : ''
84
+ delete input.id
85
+ const parsed = parseNoteInput(input)
86
+ if (!parsed.ok || !id) continue
87
+ doc.trash.push({ deletedAt: typeof item.deletedAt === 'string' ? item.deletedAt : new Date().toISOString(), note: { id, ...parsed.value } })
88
+ }
89
+ pruneTrash(doc)
90
+ return { doc, dropped }
91
+ }
92
+
93
+ /** 回收站只留最近 TRASH_MAX 条、TRASH_DAYS 天内的。写盘前调用,读盘后也调用。 */
94
+ export function pruneTrash(doc, now = Date.now()) {
95
+ const cutoff = now - TRASH_DAYS * 24 * 60 * 60 * 1000
96
+ const kept = []
97
+ for (const item of Array.isArray(doc.trash) ? doc.trash : []) {
98
+ const at = Date.parse(item.deletedAt)
99
+ if (!Number.isFinite(at) || at < cutoff) continue
100
+ kept.push(item)
101
+ if (kept.length >= TRASH_MAX) break
102
+ }
103
+ doc.trash = kept
104
+ return doc
105
+ }
106
+
107
+ export class NoteStore {
108
+ /** @param {string} file 数据文件的绝对路径 */
109
+ constructor(file, warn = () => {}) {
110
+ this.file = file
111
+ this.warn = warn
112
+ this.doc = emptyDoc()
113
+ this.signature = ''
114
+ this.checkedAt = 0
115
+ this.chain = Promise.resolve()
116
+ this.listeners = new Set()
117
+ this.#load()
118
+ }
119
+
120
+ #stat() {
121
+ try {
122
+ const st = statSync(this.file)
123
+ return { sig: `${st.mtimeMs}:${st.size}`, size: st.size }
124
+ } catch {
125
+ return { sig: 'missing', size: 0 }
126
+ }
127
+ }
128
+
129
+ #backup(tag, why) {
130
+ this.warn(`${why}; a copy was kept as ${this.file}.${tag}-<time>`)
131
+ try { copyFileSync(this.file, `${this.file}.${tag}-${Date.now()}`) } catch { /* 备份失败不阻断功能 */ }
132
+ }
133
+
134
+ #load() {
135
+ const { sig, size } = this.#stat()
136
+ this.signature = sig
137
+ this.checkedAt = Date.now()
138
+ if (sig === 'missing') { this.doc = emptyDoc(); return }
139
+ try {
140
+ if (size > MAX_FILE_BYTES) throw new Error(`file too large (${size} bytes)`)
141
+ const { doc, dropped } = sanitizeDoc(JSON.parse(readFileSync(this.file, 'utf8')))
142
+ this.doc = doc
143
+ if (dropped > 0) this.#backup('invalid', `${dropped} invalid note(s) were skipped`)
144
+ } catch (error) {
145
+ // 坏文件:留一份备份再当空处理,下一次保存才不会悄悄把用户手里唯一的一份内容盖掉。
146
+ this.#backup('corrupt', `notes file unreadable (${String(error)}), starting empty`)
147
+ this.doc = emptyDoc()
148
+ }
149
+ }
150
+
151
+ /** 订阅「内容变了」(含外部手改)。返回取消订阅函数。 */
152
+ subscribe(fn) {
153
+ this.listeners.add(fn)
154
+ return () => this.listeners.delete(fn)
155
+ }
156
+
157
+ #emit() {
158
+ for (const fn of this.listeners) {
159
+ try { fn() } catch (error) { this.warn(`listener failed: ${String(error)}`) }
160
+ }
161
+ }
162
+
163
+ /** 主动探测外部改动(供定时器调用);有变化则重读并通知订阅者。 */
164
+ poll() {
165
+ const { sig } = this.#stat()
166
+ this.checkedAt = Date.now()
167
+ if (sig === this.signature) return false
168
+ this.#load()
169
+ this.#emit()
170
+ return true
171
+ }
172
+
173
+ /** 同步读取当前快照(必要时先感知外部改动)。 */
174
+ snapshot() {
175
+ if (Date.now() - this.checkedAt >= STAT_INTERVAL_MS) this.poll()
176
+ return this.doc
177
+ }
178
+
179
+ get revision() {
180
+ return this.signature
181
+ }
182
+
183
+ /**
184
+ * 串行地「重读 → 修改 → 原子写」。重读是为了不覆盖外部手改。
185
+ * fn 收到文档的深拷贝,返回要给调用方的结果;抛错则不写盘。
186
+ */
187
+ mutate(fn) {
188
+ const run = async () => {
189
+ this.#load()
190
+ const draft = structuredClone(this.doc)
191
+ const result = fn(draft)
192
+ const next = sanitizeDoc(draft).doc
193
+ await this.#write(next)
194
+ this.doc = next
195
+ this.#emit()
196
+ return result
197
+ }
198
+ const task = this.chain.then(run, run)
199
+ this.chain = task.catch(() => {})
200
+ return task
201
+ }
202
+
203
+ async #write(doc) {
204
+ const body = `${JSON.stringify(doc, null, 2)}\n`
205
+ const tmp = `${this.file}.${process.pid}.${Date.now()}.tmp`
206
+ await mkdir(dirname(this.file), { recursive: true })
207
+ await writeFile(tmp, body, 'utf8')
208
+ await rename(tmp, this.file)
209
+ this.signature = this.#stat().sig
210
+ this.checkedAt = Date.now()
211
+ }
212
+ }
213
+
214
+ export { sanitizeDoc, emptyDoc }