dsh-mindmark 0.0.0-stage → 0.4.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/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "dsh-mindmark",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0",
4
+ "description": "Show the model your mind: mark up an answer like in Word (highlight / underline / strike / comment / rewrite / source / move) and your markup reaches DeepSeek Harness as context on the next turn.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./client": "./client.js",
10
+ "./package.json": "./package.json",
11
+ "./locale/*.json": "./locale/*.json",
12
+ "./icon": "./icon.svg"
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "client.js",
17
+ "src",
18
+ "locale",
19
+ "cordis.patch.yml",
20
+ "README.md",
21
+ "icon.svg",
22
+ "LICENSE",
23
+ "docs/demo.gif",
24
+ "CHANGELOG.md",
25
+ "README.en.md"
26
+ ],
27
+ "dsh": {
28
+ "bundle": {
29
+ "patch": "./cordis.patch.yml"
30
+ },
31
+ "client": {
32
+ "platform": "web"
33
+ }
34
+ },
35
+ "keywords": [
36
+ "dsh-plugin",
37
+ "deepseek-harness",
38
+ "annotation",
39
+ "markup",
40
+ "feedback",
41
+ "human-in-the-loop",
42
+ "intent"
43
+ ],
44
+ "license": "MIT",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/BaiKe-Zhang/dsh-mindmark.git"
48
+ },
49
+ "homepage": "https://github.com/BaiKe-Zhang/dsh-mindmark#readme",
50
+ "bugs": {
51
+ "url": "https://github.com/BaiKe-Zhang/dsh-mindmark/issues"
52
+ },
53
+ "author": "BaiKe-Zhang",
54
+ "scripts": {
55
+ "test": "node --test \"test/*.test.mjs\""
56
+ }
57
+ }
package/src/inject.js ADDED
@@ -0,0 +1,367 @@
1
+ // dsh-mindmark — the model-facing text for a batch of pending annotations.
2
+ //
3
+ // Two view modes, chosen per session by the user:
4
+ // • `brief`: only the annotated passages, each with a little context;
5
+ // • `full`: the whole captured message with inline markers (a revision view).
6
+ // Both carry the annotation ids so the model can settle them with the
7
+ // `annotations` tool (`action: resolve`).
8
+
9
+ export const STYLE_META = {
10
+ highlight: { label: '高亮', meaning: '这是用户要的:保留并强化这个方向' },
11
+ underline: { label: '下划线', meaning: '这里不够:展开、澄清或给出依据' },
12
+ strike: { label: '删除', meaning: '去掉:下一版不要再出现' },
13
+ comment: { label: '批注', meaning: '按批注内容处理,并逐条回应' },
14
+ rewrite: { label: '改写', meaning: '以用户改写后的文字为准' },
15
+ move: {
16
+ label: '移动',
17
+ meaning: '把这段挪到用户指定的位置(插入点之后;若用户选了一段目标文字,就用它替换那段文字),原处不再保留,其余内容不动',
18
+ },
19
+ reference: {
20
+ label: '依据',
21
+ meaning: '只改这一段:以用户附的材料为准,与材料冲突时听材料的,并说明改动依据了材料的哪一句',
22
+ },
23
+ }
24
+
25
+ export const TOOL_NAME = 'annotations'
26
+ export const SOURCE_KIND = 'dsh-mindmark'
27
+ export const BRIEF_CONTEXT_CHARS = 60
28
+ export const MAX_FULL_MESSAGE_CHARS = 12000
29
+ export const MATERIAL_PREVIEW_CHARS = 300
30
+
31
+ function styleLabel(style) {
32
+ return STYLE_META[style]?.label ?? '标注'
33
+ }
34
+
35
+ function flat(text) {
36
+ return typeof text === 'string' ? text.replace(/\s+/g, ' ').trim() : ''
37
+ }
38
+
39
+ function clip(text, max) {
40
+ const value = flat(text)
41
+ return value.length > max ? `${value.slice(0, max)}…` : value
42
+ }
43
+
44
+ function compareCreatedAt(left, right) {
45
+ const a = Date.parse(left?.createdAt ?? '') || 0
46
+ const b = Date.parse(right?.createdAt ?? '') || 0
47
+ return a - b
48
+ }
49
+
50
+ /** The legend every injection shares; also reused by the prompt section. */
51
+ export function legendText() {
52
+ return Object.values(STYLE_META)
53
+ .map(meta => `${meta.label}=${meta.meaning}`)
54
+ .join(';')
55
+ }
56
+
57
+ /** One annotation as a brief line pair (numbered, with its id). */
58
+ /**
59
+ * The text around an annotation. Inside a captured message the context comes
60
+ * from that message only, so nothing outside the answer (thinking, toolbars,
61
+ * other turns) leaks in; otherwise the saved page context is used.
62
+ */
63
+ export function contextOf(annotation, messages) {
64
+ const message = annotation.messageKey ? messages?.[annotation.messageKey] : undefined
65
+ const start = annotation.messageStart
66
+ const end = annotation.messageEnd
67
+ if (typeof message?.text === 'string' && Number.isInteger(start) && Number.isInteger(end) && end > start) {
68
+ const text = message.text
69
+ if (flat(text.slice(start, end)) === flat(annotation.quote)) {
70
+ return {
71
+ prefix: text.slice(Math.max(0, start - BRIEF_CONTEXT_CHARS), start),
72
+ suffix: text.slice(end, end + BRIEF_CONTEXT_CHARS),
73
+ }
74
+ }
75
+ }
76
+ return { prefix: annotation.prefix, suffix: annotation.suffix }
77
+ }
78
+
79
+ export function briefLine(annotation, index, materials, messages) {
80
+ const label = styleLabel(annotation.style)
81
+ const quote = clip(annotation.quote, 300)
82
+ const head = `${index + 1}. [#${annotation.id}] ${label}:“${quote}”`
83
+ const lines = [head]
84
+ if (annotation.style === 'comment' && annotation.note) lines.push(` 用户批注:${clip(annotation.note, 600)}`)
85
+ if (annotation.style === 'rewrite' && annotation.note) lines.push(` 改为:“${clip(annotation.note, 600)}”`)
86
+ if (annotation.style === 'move') {
87
+ lines.push(` 移到:${targetText(annotation)}`)
88
+ if (annotation.note) lines.push(` 理由:${clip(annotation.note, 600)}`)
89
+ }
90
+ const context = contextOf(annotation, messages)
91
+ const prefix = clip(context.prefix, BRIEF_CONTEXT_CHARS)
92
+ const suffix = clip(context.suffix, BRIEF_CONTEXT_CHARS)
93
+ if (prefix !== '' || suffix !== '') {
94
+ const left = prefix === '' ? '' : `…${prefix.slice(-BRIEF_CONTEXT_CHARS)}`
95
+ const right = suffix === '' ? '' : `${suffix.slice(0, BRIEF_CONTEXT_CHARS)}…`
96
+ lines.push(` 上下文:${left}【${clip(annotation.quote, 120)}】${right}`)
97
+ }
98
+ if (annotation.style === 'reference') lines.push(...materialLines(annotation, materials?.[annotation.id]))
99
+ return lines.join('\n')
100
+ }
101
+
102
+ /** A material name in 《》 unless it already starts with a title mark. */
103
+ export function bookTitle(title) {
104
+ const text = flat(title) || '未命名'
105
+ return /^[《「“"]/.test(text) ? text : `《${text}》`
106
+ }
107
+
108
+ /** Where a move goes: the insertion point, or the text it replaces. */
109
+ export function targetText(annotation) {
110
+ const before = flat(annotation.targetPrefix).slice(-40)
111
+ const after = flat(annotation.targetSuffix).slice(0, 40)
112
+ if (typeof annotation.targetQuote === 'string' && annotation.targetQuote.trim() !== '') {
113
+ const where = before === '' ? '' : `(它前面是“…${before}”)`
114
+ return `替换掉“${clip(annotation.targetQuote, 300)}”${where}`
115
+ }
116
+ if (before === '') return `开头,在“${after}…”之前`
117
+ if (after === '') return `末尾,在“…${before}”之后`
118
+ return `“…${before}”与“${after}…”之间`
119
+ }
120
+
121
+ /**
122
+ * The material of a `reference` annotation. `content` is its full text when it
123
+ * is short enough to travel whole; otherwise only the excerpt is shown and the
124
+ * model reads the rest through the tool.
125
+ */
126
+ export function materialLines(annotation, content) {
127
+ const meta = annotation.material ?? {}
128
+ const lines = []
129
+ if (meta.kind === 'url') {
130
+ lines.push(` 材料(链接):${meta.url}`)
131
+ lines.push(' 用你的联网或网页读取工具打开它;读不到就如实告诉用户,请用户改为粘贴原文,不要凭印象编造。')
132
+ } else {
133
+ const kind = meta.kind === 'file' ? '文件' : '粘贴的文本'
134
+ lines.push(` 材料${bookTitle(meta.title)}(${kind},共 ${meta.length ?? 0} 字)`)
135
+ if (typeof content === 'string') {
136
+ lines.push(' <<<材料全文')
137
+ lines.push(content.trim())
138
+ lines.push(' 材料全文>>>')
139
+ } else {
140
+ lines.push(` 开头摘录:“${clip(meta.excerpt, MATERIAL_PREVIEW_CHARS)}”`)
141
+ lines.push(` 全文较长,需要时调用 \`${TOOL_NAME}\` 工具 action=material、ids=["${annotation.id}"] 分段读取(用 offset 续读)。`)
142
+ }
143
+ }
144
+ if (annotation.note) lines.push(` 用户要求:${clip(annotation.note, 600)}`)
145
+ lines.push(' 只改被标注的这一段,其他段落保持原样。')
146
+ return lines
147
+ }
148
+
149
+ function marker(annotation, number, placed) {
150
+ const label = styleLabel(annotation.style)
151
+ const quote = flat(annotation.quote)
152
+ if (annotation.style === 'rewrite') return `[[#${number} ${label}:${quote} → ${flat(annotation.note)}]]`
153
+ if (annotation.style === 'comment') return `[[#${number} ${label}:${quote} ‖ 用户批注:${flat(annotation.note)}]]`
154
+ if (annotation.style === 'move') {
155
+ const replaces = typeof annotation.targetQuote === 'string' && annotation.targetQuote.trim() !== ''
156
+ const where = placed
157
+ ? replaces
158
+ ? `移到 [[#${number} 移入此处并替换]] 标出的位置,替换掉那里的文字`
159
+ : `移到 [[#${number} 移入此处]] 标出的位置`
160
+ : `移到${targetText(annotation)}`
161
+ const why = annotation.note ? ` ‖ 理由:${flat(annotation.note)}` : ''
162
+ return `[[#${number} ${label}:${quote} → ${where}${why}]]`
163
+ }
164
+ if (annotation.style === 'reference') return `[[#${number} ${label}:${quote} ‖ 按文末材料 #${number} 改这一段]]`
165
+ return `[[#${number} ${label}:${quote}]]`
166
+ }
167
+
168
+ /**
169
+ * Where the insertion point of a `move` lies in `text`: its stored offset when
170
+ * the surrounding text still matches, otherwise the first place the saved
171
+ * context occurs. Undefined when it cannot be found.
172
+ */
173
+ export function locateTargetPoint(text, annotation) {
174
+ return locateTarget(text, annotation)?.start
175
+ }
176
+
177
+ /**
178
+ * Where the target of a `move` lies in `text`: `{ start, end }`, with
179
+ * `end === start` for an insertion point and `end > start` for the text it
180
+ * replaces. Undefined when it cannot be found.
181
+ */
182
+ export function locateTarget(text, annotation) {
183
+ const before = typeof annotation.targetPrefix === 'string' ? annotation.targetPrefix : ''
184
+ const after = typeof annotation.targetSuffix === 'string' ? annotation.targetSuffix : ''
185
+ const middle = typeof annotation.targetQuote === 'string' ? annotation.targetQuote : ''
186
+ const offset = annotation.targetOffset
187
+ if (Number.isInteger(offset) && offset >= 0 && offset + middle.length <= text.length) {
188
+ const end = offset + middle.length
189
+ const okBefore = before === '' || text.slice(Math.max(0, offset - before.length), offset) === before
190
+ const okMiddle = text.slice(offset, end) === middle
191
+ const okAfter = after === '' || text.slice(end, end + after.length) === after
192
+ if (okBefore && okMiddle && okAfter) return { start: offset, end }
193
+ }
194
+ if (before === '' && after === '' && middle === '') return undefined
195
+ const found = text.indexOf(before + middle + after)
196
+ if (found < 0) return undefined
197
+ const start = found + before.length
198
+ return { start, end: start + middle.length }
199
+ }
200
+
201
+ /**
202
+ * Render one captured message with inline markers. Overlapping annotations
203
+ * cannot both be inlined; the later ones are returned in `leftover` for the
204
+ * brief fallback. Each inlined annotation gets a sequence number that the
205
+ * footnote maps back to its id. A move also marks its insertion point when
206
+ * that point lies outside every inlined passage.
207
+ */
208
+ export function renderFullMessage(text, annotations, startNumber = 1) {
209
+ const sorted = [...annotations]
210
+ .filter(item => Number.isInteger(item.messageStart) && Number.isInteger(item.messageEnd))
211
+ .sort((a, b) => a.messageStart - b.messageStart || a.messageEnd - b.messageEnd)
212
+ const spans = []
213
+ const leftover = []
214
+ let cursor = 0
215
+ let number = startNumber
216
+ for (const item of sorted) {
217
+ const start = Math.max(0, Math.min(item.messageStart, text.length))
218
+ const end = Math.max(start, Math.min(item.messageEnd, text.length))
219
+ const slice = text.slice(start, end)
220
+ // The offsets must still describe the quote; otherwise the capture went stale.
221
+ if (start < cursor || end <= start || flat(slice) !== flat(item.quote)) {
222
+ leftover.push(item)
223
+ continue
224
+ }
225
+ spans.push({ start, end, slice, item, number, placed: false })
226
+ number += 1
227
+ cursor = end
228
+ }
229
+ const points = []
230
+ for (const span of spans) {
231
+ if (span.item.style !== 'move') continue
232
+ const target = locateTarget(text, span.item)
233
+ if (target === undefined) continue
234
+ const { start: at, end } = target
235
+ if (end === at) {
236
+ if (at >= span.start && at <= span.end) continue
237
+ if (spans.some(other => at > other.start && at < other.end)) continue
238
+ } else if (spans.some(other => at < other.end && end > other.start)) {
239
+ continue
240
+ }
241
+ if (points.some(point => at < point.end && end > point.at)) continue
242
+ span.placed = true
243
+ points.push({ at, end, number: span.number })
244
+ }
245
+ const events = [
246
+ ...spans.map(span => ({ at: span.start, order: 1, span })),
247
+ ...points.map(point => ({ at: point.at, order: 0, point })),
248
+ ].sort((a, b) => a.at - b.at || a.order - b.order)
249
+ let out = ''
250
+ let position = 0
251
+ for (const event of events) {
252
+ if (event.span) {
253
+ const span = event.span
254
+ out += text.slice(position, span.start)
255
+ out += marker({ ...span.item, quote: span.slice }, span.number, span.placed)
256
+ position = span.end
257
+ } else if (event.point.end > event.at) {
258
+ out += text.slice(position, event.at)
259
+ out += `[[#${event.point.number} 移入此处并替换:${flat(text.slice(event.at, event.point.end))}]]`
260
+ position = event.point.end
261
+ } else {
262
+ out += text.slice(position, event.at)
263
+ out += `[[#${event.point.number} 移入此处]]`
264
+ position = event.at
265
+ }
266
+ }
267
+ out += text.slice(position)
268
+ const inlined = spans.map(span => ({ number: span.number, annotation: span.item }))
269
+ return { text: out, inlined, leftover, nextNumber: number }
270
+ }
271
+
272
+ /**
273
+ * Build the whole injection. `snapshot` is `store.snapshot(sessionId)`
274
+ * restricted to the annotations being injected; `turn` is the turn that is
275
+ * about to start. Returns '' when there is nothing to say.
276
+ */
277
+ export function buildInjection(snapshot, { turn } = {}) {
278
+ const pending = [...(snapshot?.annotations ?? [])].sort(compareCreatedAt)
279
+ if (pending.length === 0) return ''
280
+ const mode = snapshot?.mode === 'full' ? 'full' : 'brief'
281
+ const ids = pending.map(item => item.id)
282
+ const lines = []
283
+ const turnLabel = Number.isInteger(turn) ? `(第 ${turn} 轮之前)` : ''
284
+ lines.push(`## 用户对你之前回答的标注${turnLabel}`)
285
+ lines.push('')
286
+ lines.push(`用户在你之前的回答上做了 ${pending.length} 处标注,这是用户修改后希望你理解的样子。含义:${legendText()}。`)
287
+ lines.push('')
288
+
289
+ if (mode === 'full') {
290
+ const groups = new Map()
291
+ const unanchored = []
292
+ for (const item of pending) {
293
+ const message = item.messageKey !== '' ? snapshot.messages?.[item.messageKey] : undefined
294
+ if (message === undefined || typeof message.text !== 'string') {
295
+ unanchored.push(item)
296
+ continue
297
+ }
298
+ if (!groups.has(item.messageKey)) groups.set(item.messageKey, { message, items: [] })
299
+ groups.get(item.messageKey).items.push(item)
300
+ }
301
+ let number = 1
302
+ const footnotes = []
303
+ const appendix = []
304
+ for (const [, group] of groups) {
305
+ const text = group.message.text.length > MAX_FULL_MESSAGE_CHARS
306
+ ? `${group.message.text.slice(0, MAX_FULL_MESSAGE_CHARS)}\n…(后文略)`
307
+ : group.message.text
308
+ const rendered = renderFullMessage(text, group.items, number)
309
+ number = rendered.nextNumber
310
+ const where = Number.isInteger(group.message.turn) ? `第 ${group.message.turn} 轮的回答` : '你的一条回答'
311
+ lines.push(`### ${where}(修订视图,标记写作 [[#序号 类型:原文]])`)
312
+ lines.push('')
313
+ lines.push(rendered.text)
314
+ lines.push('')
315
+ for (const entry of rendered.inlined) {
316
+ footnotes.push(`#${entry.number} → id ${entry.annotation.id}(${styleLabel(entry.annotation.style)})`)
317
+ if (entry.annotation.style === 'reference') appendix.push(entry)
318
+ }
319
+ unanchored.push(...rendered.leftover)
320
+ }
321
+ if (footnotes.length > 0) {
322
+ lines.push('标记序号对应的标注 id:')
323
+ lines.push(...footnotes.map(line => `- ${line}`))
324
+ lines.push('')
325
+ }
326
+ if (appendix.length > 0) {
327
+ lines.push('### 用户附的参考材料')
328
+ lines.push('')
329
+ for (const entry of appendix) {
330
+ lines.push(`材料 #${entry.number}(对应标注 id ${entry.annotation.id}):`)
331
+ lines.push(...materialLines(entry.annotation, snapshot.materials?.[entry.annotation.id]))
332
+ lines.push('')
333
+ }
334
+ }
335
+ if (unanchored.length > 0) {
336
+ lines.push('### 其余标注(未能内嵌到完整消息里)')
337
+ lines.push('')
338
+ unanchored.sort(compareCreatedAt).forEach((item, index) => lines.push(briefLine(item, index, snapshot.materials, snapshot.messages)))
339
+ lines.push('')
340
+ }
341
+ } else {
342
+ pending.forEach((item, index) => lines.push(briefLine(item, index, snapshot.materials, snapshot.messages)))
343
+ lines.push('')
344
+ }
345
+
346
+ lines.push(
347
+ `按这些标注调整你的下一条回答。处理完后调用 \`${TOOL_NAME}\` 工具,action 传 resolve,ids 传已处理的标注 id` +
348
+ `(全部处理可省略 ids):${ids.map(id => `#${id}`).join('、')}。` +
349
+ '还需要用户确认、或打算下一轮再处理的标注,不要 resolve,它们会再次出现。' +
350
+ '如果用户要求把标注归纳成长期习惯,或者同类标注反复出现,可把它总结成一句可执行的偏好,用 action: distill 沉淀。',
351
+ )
352
+ return lines.join('\n')
353
+ }
354
+
355
+ /** The static protocol section shown while a session has pending annotations. */
356
+ export function buildProtocolSection(pendingCount) {
357
+ if (!Number.isInteger(pendingCount) || pendingCount <= 0) return ''
358
+ return [
359
+ '## 用户标注协议',
360
+ '',
361
+ '用户可以在对话里像在 Word 中一样对你的回答做标注:' + legendText() + '。',
362
+ `待处理的标注会在每一轮开始时作为一条用户上下文消息送给你(当前 ${pendingCount} 条)。` +
363
+ `处理完要调用 \`${TOOL_NAME}\` 工具(action: resolve,可带 ids)确认,否则它们会在下一轮再次出现;` +
364
+ '想看完整列表用 action: list;依据标注附的长材料用 action: material 读取;' +
365
+ '用户要求“记住这个习惯/沉淀为偏好”时用 action: distill 把一句话偏好写入长期指令。',
366
+ ].join('\n')
367
+ }
package/src/lessons.js ADDED
@@ -0,0 +1,187 @@
1
+ // dsh-mindmark — long-term lessons distilled from annotations.
2
+ //
3
+ // Lessons live in the user's global instruction file `$DSH_HOME/AGENTS.md`,
4
+ // inside one managed block, so the official agent-instructions plugin feeds
5
+ // them to every new session without any extra wiring:
6
+ //
7
+ // <!-- dsh-mindmark:start -->
8
+ // ## 用户通过标注沉淀的偏好(dsh-mindmark)
9
+ // - [2026-11-16] 解释概念时先给一个具体例子,再讲原理。
10
+ // <!-- dsh-mindmark:end -->
11
+ //
12
+ // Everything outside the block is preserved byte for byte. Writes are atomic.
13
+
14
+ import fs from 'node:fs'
15
+ import os from 'node:os'
16
+ import path from 'node:path'
17
+
18
+ export const BLOCK_START = '<!-- dsh-mindmark:start -->'
19
+ export const BLOCK_END = '<!-- dsh-mindmark:end -->'
20
+ export const BLOCK_TITLE = '## 用户通过标注沉淀的偏好(dsh-mindmark)'
21
+ export const BLOCK_INTRO = '以下是用户在批改助手回答时反复表现出的偏好,请在所有对话中遵守;与当前对话的明确指示冲突时以当前指示为准。'
22
+ export const MAX_LESSONS = 40
23
+ export const MAX_LESSON_LENGTH = 300
24
+ export const MAX_BLOCK_BYTES = 8000
25
+
26
+ /** Resolve `$DSH_HOME/AGENTS.md` (or `~/.dsh/AGENTS.md`). */
27
+ export function resolveInstructionsPath(env = process.env) {
28
+ const home =
29
+ typeof env?.DSH_HOME === 'string' && env.DSH_HOME.trim() !== ''
30
+ ? env.DSH_HOME
31
+ : path.join(os.homedir(), '.dsh')
32
+ return path.join(home, 'AGENTS.md')
33
+ }
34
+
35
+ function today() {
36
+ const d = new Date()
37
+ const pad = n => String(n).padStart(2, '0')
38
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
39
+ }
40
+
41
+ /** Collapse whitespace and clip one lesson line; '' when unusable. */
42
+ export function normalizeLesson(text) {
43
+ if (typeof text !== 'string') return ''
44
+ const flat = text.replace(/\s+/g, ' ').trim().replace(/^[-*•]\s*/, '').replace(/^\[\d{4}-\d{2}-\d{2}\]\s*/, '')
45
+ return flat.length > MAX_LESSON_LENGTH ? `${flat.slice(0, MAX_LESSON_LENGTH - 1)}…` : flat
46
+ }
47
+
48
+ /** Parse the managed block of a file body into `{ before, lessons, after }`. */
49
+ export function parseInstructions(body) {
50
+ const text = typeof body === 'string' ? body : ''
51
+ const start = text.indexOf(BLOCK_START)
52
+ const end = start < 0 ? -1 : text.indexOf(BLOCK_END, start)
53
+ if (start < 0 || end < 0) return { before: text, lessons: [], after: '' }
54
+ const inner = text.slice(start + BLOCK_START.length, end)
55
+ const lessons = []
56
+ for (const line of inner.split('\n')) {
57
+ const m = /^\s*-\s*(?:\[(\d{4}-\d{2}-\d{2})\]\s*)?(.+?)\s*$/.exec(line)
58
+ if (!m) continue
59
+ const lesson = normalizeLesson(m[2])
60
+ if (lesson !== '') lessons.push({ date: m[1] ?? '', text: lesson })
61
+ }
62
+ return { before: text.slice(0, start), lessons, after: text.slice(end + BLOCK_END.length) }
63
+ }
64
+
65
+ /** Render the managed block for a lesson list ('' when empty). */
66
+ export function renderBlock(lessons) {
67
+ if (!Array.isArray(lessons) || lessons.length === 0) return ''
68
+ const lines = [BLOCK_START, BLOCK_TITLE, '', BLOCK_INTRO, '']
69
+ for (const lesson of lessons) {
70
+ lines.push(`- ${lesson.date ? `[${lesson.date}] ` : ''}${lesson.text}`)
71
+ }
72
+ lines.push(BLOCK_END)
73
+ return lines.join('\n')
74
+ }
75
+
76
+ /** Re-assemble a file body with a new lesson list. */
77
+ export function composeInstructions(parsed, lessons) {
78
+ const block = renderBlock(lessons)
79
+ const before = parsed.before.replace(/\s+$/, '')
80
+ const after = parsed.after.replace(/^\s+|\s+$/g, '')
81
+ if (block === '') {
82
+ const joined = [before, after].filter(part => part !== '').join('\n\n')
83
+ return joined === '' ? '' : `${joined}\n`
84
+ }
85
+ return [before, block, after].filter(part => part !== '').join('\n\n') + '\n'
86
+ }
87
+
88
+ function ensureDirectory(filePath) {
89
+ fs.mkdirSync(path.dirname(filePath), { recursive: true })
90
+ }
91
+
92
+ function writeAtomic(filePath, text) {
93
+ ensureDirectory(filePath)
94
+ const temp = `${filePath}.${process.pid}.${Date.now()}.tmp`
95
+ fs.writeFileSync(temp, text, { encoding: 'utf8', mode: 0o600 })
96
+ try {
97
+ fs.renameSync(temp, filePath)
98
+ } catch (error) {
99
+ fs.copyFileSync(temp, filePath)
100
+ fs.unlinkSync(temp)
101
+ if (!fs.existsSync(filePath)) throw error
102
+ }
103
+ }
104
+
105
+ /** Read/write the managed lesson block of one instruction file. */
106
+ export class LessonStore {
107
+ constructor(filePath, { logger } = {}) {
108
+ this.filePath = filePath ?? resolveInstructionsPath()
109
+ this.logger = logger
110
+ }
111
+
112
+ read() {
113
+ let body = ''
114
+ try {
115
+ body = fs.readFileSync(this.filePath, 'utf8')
116
+ } catch (error) {
117
+ if (error?.code !== 'ENOENT') {
118
+ this.logger?.warn?.(`dsh-mindmark: cannot read ${this.filePath}: ${String(error)}`)
119
+ }
120
+ }
121
+ return parseInstructions(body)
122
+ }
123
+
124
+ /** Current lessons, oldest first. */
125
+ list() {
126
+ return this.read().lessons.map(lesson => ({ ...lesson }))
127
+ }
128
+
129
+ save(parsed, lessons) {
130
+ let kept = lessons
131
+ // Keep the block inside its byte budget by dropping the oldest lessons.
132
+ while (kept.length > MAX_LESSONS || Buffer.byteLength(renderBlock(kept)) > MAX_BLOCK_BYTES) {
133
+ kept = kept.slice(1)
134
+ }
135
+ if (kept.length === 0 && parsed.lessons.length === 0 && !fs.existsSync(this.filePath)) return kept
136
+ writeAtomic(this.filePath, composeInstructions(parsed, kept))
137
+ return kept
138
+ }
139
+
140
+ /**
141
+ * Append lessons (deduplicated, case-insensitive). Returns
142
+ * `{ added: string[], skipped: string[], lessons }`.
143
+ */
144
+ add(texts) {
145
+ const parsed = this.read()
146
+ const existing = new Set(parsed.lessons.map(lesson => lesson.text.toLowerCase()))
147
+ const added = []
148
+ const skipped = []
149
+ const next = [...parsed.lessons]
150
+ for (const raw of Array.isArray(texts) ? texts : [texts]) {
151
+ const text = normalizeLesson(raw)
152
+ if (text === '') continue
153
+ if (existing.has(text.toLowerCase())) {
154
+ skipped.push(text)
155
+ continue
156
+ }
157
+ existing.add(text.toLowerCase())
158
+ next.push({ date: today(), text })
159
+ added.push(text)
160
+ }
161
+ const lessons = added.length === 0 ? parsed.lessons : this.save(parsed, next)
162
+ return { added, skipped, lessons: lessons.map(lesson => ({ ...lesson })) }
163
+ }
164
+
165
+ /** Remove lessons by exact text or 1-based index. Returns the removed texts. */
166
+ remove(targets) {
167
+ const parsed = this.read()
168
+ const wanted = new Set()
169
+ for (const target of Array.isArray(targets) ? targets : [targets]) {
170
+ if (Number.isInteger(target) && target >= 1 && target <= parsed.lessons.length) {
171
+ wanted.add(parsed.lessons[target - 1].text.toLowerCase())
172
+ } else if (typeof target === 'string') {
173
+ const text = normalizeLesson(target)
174
+ if (/^\d+$/.test(target.trim())) {
175
+ const index = Number(target.trim())
176
+ if (index >= 1 && index <= parsed.lessons.length) wanted.add(parsed.lessons[index - 1].text.toLowerCase())
177
+ } else if (text !== '') {
178
+ wanted.add(text.toLowerCase())
179
+ }
180
+ }
181
+ }
182
+ const removed = parsed.lessons.filter(lesson => wanted.has(lesson.text.toLowerCase())).map(lesson => lesson.text)
183
+ if (removed.length === 0) return []
184
+ this.save(parsed, parsed.lessons.filter(lesson => !wanted.has(lesson.text.toLowerCase())))
185
+ return removed
186
+ }
187
+ }