dsh-learn-space 0.0.0-stage → 1.1.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/index.js ADDED
@@ -0,0 +1,1226 @@
1
+ /**
2
+ * 学习空间 Host 半边:
3
+ * - webServer: /api/learning-space/* 给面板供数据(解析 curriculum 下的 markdown)
4
+ * - tools: learn_guide / learn_status / learn_update(AI 教学时读方法、写进度)
5
+ */
6
+ import { readFile, writeFile, mkdir, readdir, stat, rm } from 'node:fs/promises'
7
+ import { fileURLToPath } from 'node:url'
8
+ import path from 'node:path'
9
+ import { randomUUID as cryptoRandomUUID } from 'node:crypto'
10
+ import { annotateQuiz, appendQuizLog, parseQuizLog } from './quiz.js'
11
+
12
+ export const inject = ['tools', 'webServer', 'sessionController', 'sessionTitle', 'sessions']
13
+
14
+ const CLASS_STATUS = { done: 'done', doing: 'doing', warn: 'warn', todo: 'todo' }
15
+
16
+ function parseFrontmatter(text) {
17
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)
18
+ const fm = {}
19
+ if (m) {
20
+ for (const line of m[1].split(/\r?\n/)) {
21
+ const kv = /^(topic|goal):\s*(.*)$/.exec(line)
22
+ if (kv) fm[kv[1]] = kv[2]
23
+ }
24
+ }
25
+ return fm
26
+ }
27
+
28
+ /** 解析 plan.md:mermaid 节点/边 + checkbox 状态 */
29
+ function parsePlan(text) {
30
+ const fm = parseFrontmatter(text)
31
+ const nodes = []
32
+ const edges = []
33
+ const order = []
34
+ const mermaid = /```mermaid([\s\S]*?)```/.exec(text)
35
+ // id + 标签(兼容带引号 A["x"] 与不带引号 A[x],标签内可含 : / 等字符)+ :::class
36
+ const idDef = s => {
37
+ const def = /^\s*([^\[\]:"'\s]+)\s*(?:\["([^"]*)"\]|\[([^\]]*)\])?\s*(?:::+(\w+))?\s*$/.exec(s)
38
+ if (!def) return null
39
+ const label = def[2] !== undefined ? def[2] : def[3] !== undefined ? def[3].trim() : undefined
40
+ return { id: def[1].trim(), label: label || undefined, cls: def[4] }
41
+ }
42
+ const pushNode = (id, label, cls) => {
43
+ if (!id) return
44
+ let n = nodes.find(x => x.id === id)
45
+ if (!n) { n = { id, label: label || id, status: 'todo' }; nodes.push(n) }
46
+ if (label) n.label = label
47
+ if (cls && CLASS_STATUS[cls]) n.status = cls
48
+ }
49
+ if (mermaid) {
50
+ for (const raw of mermaid[1].split(/\r?\n/)) {
51
+ const line = raw.trim()
52
+ if (line.includes('-->')) {
53
+ const parts = line.split('-->').map(idDef).filter(Boolean)
54
+ for (const p of parts) pushNode(p.id, p.label, p.cls)
55
+ for (let i = 0; i + 1 < parts.length; i++) edges.push([parts[i].id, parts[i + 1].id])
56
+ } else {
57
+ const def = /^\s*([^\[\]:"']+?)\s*\["([^"]*)"\]\s*(?:::+(\w+))?/.exec(line)
58
+ if (def) pushNode(def[1].trim(), def[2], def[3])
59
+ }
60
+ }
61
+ }
62
+ // checkbox 顺序与状态(以 checkbox 为准,覆盖 mermaid class)
63
+ // 宽松匹配:AI 常写「id + 标签 + 注释」「标签(注释)」「标签<br/>换行」三种风格,
64
+ // 按 标签全等 / 行首 id / 归一化前缀(去 <br/>、空白、全半角标点后比前缀)三级回退映射回节点
65
+ const norm = s => String(s).replace(/<br\s*\/?>/gi, ' ').replace(/[\s\u3000()()::、,,。.\-—_]/g, '')
66
+ const cbStatus = {}
67
+ for (const m of text.matchAll(/^- \[([ x~!])\] (.+)$/gm)) {
68
+ const st = m[1] === 'x' ? 'done' : m[1] === '~' ? 'doing' : m[1] === '!' ? 'warn' : 'todo'
69
+ order.push(m[2])
70
+ cbStatus[m[2]] = st
71
+ }
72
+ for (const n of nodes) {
73
+ let st, key
74
+ if (cbStatus[n.label] !== undefined) { st = cbStatus[n.label]; key = n.label }
75
+ else {
76
+ // 行首 id:checkbox 以「<id> 」「<id>:」「<id>:」开头
77
+ const idKey = Object.keys(cbStatus).find(k =>
78
+ new RegExp(`^${n.id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[\\s::]`).test(k))
79
+ if (idKey) { st = cbStatus[idKey]; key = idKey }
80
+ else if (n.label) {
81
+ // 归一化前缀:标签或 checkbox 任一方为另一方前缀(后缀注释/截断兼容);取最长匹配降低歧义
82
+ const nl = norm(n.label)
83
+ const cands = Object.keys(cbStatus)
84
+ .filter(k => { const nk = norm(k); return nk !== '' && nl !== '' && (nk.startsWith(nl) || nl.startsWith(nk)) })
85
+ .sort((a, b) => norm(b).length - norm(a).length)
86
+ if (cands.length) { st = cbStatus[cands[0]]; key = cands[0] }
87
+ }
88
+ }
89
+ if (st !== undefined) n.status = st
90
+ // 匹配到的 checkbox 原文:导出报告提取节点的学习内容描述(标签后的括号注释等)
91
+ if (key !== undefined) n.checkbox = key
92
+ }
93
+ const counts = { done: 0, doing: 0, warn: 0, todo: 0 }
94
+ for (const n of nodes) counts[n.status] = (counts[n.status] || 0) + 1
95
+ // mermaid 块原文透传(面板完整渲染 / 导出报告用);无块为空串,旧字段零改动
96
+ return { topic: fm.topic || '', goal: fm.goal || '', nodes, edges, order, counts,
97
+ planMermaid: mermaid ? mermaid[1].trim() : '' }
98
+ }
99
+
100
+ function mistakeItems(text) {
101
+ const out = []
102
+ for (const m of text.matchAll(/^- \*\*(.+?)\*\*/gm)) out.push(m[1])
103
+ return out
104
+ }
105
+
106
+ async function listTopics(root) {
107
+ const dir = path.join(root, 'curriculum')
108
+ let entries = []
109
+ try { entries = await readdir(dir, { withFileTypes: true }) } catch { return [] }
110
+ const topics = []
111
+ for (const e of entries) {
112
+ if (!e.isDirectory() || e.name.startsWith('_')) continue
113
+ try {
114
+ const plan = parsePlan(await readFile(path.join(dir, e.name, 'plan.md'), 'utf8'))
115
+ let mistakes = []
116
+ try {
117
+ mistakes = mistakeItems(await readFile(path.join(dir, e.name, 'mistakes.md'), 'utf8'))
118
+ } catch { /* 无错题本 */ }
119
+ let notes = []
120
+ try { notes = (await readdir(path.join(dir, e.name, 'notes'))).filter(f => f.endsWith('.md')) } catch { /* 无笔记 */ }
121
+ // 两阶段会话状态:读侧推导(旧 {sessionId} → phase2 存量),sessionId 保留为镜像字段
122
+ const sessionState = await readSessionState(path.join(dir, e.name))
123
+ const planReady = sessionState.phase === 1 && plan.nodes.length >= 2 && !isSkeletonPlan(plan.nodes)
124
+ let studyLog = []
125
+ try { studyLog = parseStudyLog(await readFile(path.join(dir, e.name, 'study-log.md'), 'utf8')) } catch { /* 无学习记录 */ }
126
+ // 材料列表(materials/<topic>/ 下文件名 + 大小);无目录时为空数组,既有字段零改动
127
+ const materials = []
128
+ try {
129
+ const mdir = path.join(root, 'materials', e.name)
130
+ for (const f of await readdir(mdir)) {
131
+ try { materials.push({ name: f, size: (await stat(path.join(mdir, f))).size }) } catch { /* 文件刚被删 */ }
132
+ }
133
+ } catch { /* 无 materials 目录 */ }
134
+ topics.push({ name: e.name, goal: plan.goal, nodes: plan.nodes, edges: plan.edges,
135
+ order: plan.order, counts: plan.counts, planMermaid: plan.planMermaid,
136
+ mistakes, notes, sessionId: sessionState.phase2SessionId ?? sessionState.phase1SessionId,
137
+ phase: sessionState.phase, phase1SessionId: sessionState.phase1SessionId,
138
+ phase2SessionId: sessionState.phase2SessionId, webSearch: sessionState.webSearch,
139
+ planReady, studyLog: studyLog.slice().reverse().slice(0, 50), materials })
140
+ } catch { /* 无 plan.md 的目录跳过 */ }
141
+ }
142
+ return topics
143
+ }
144
+
145
+ /** 取 content 块数组里的 text 块拼接 */
146
+ function textOf(content) {
147
+ if (!Array.isArray(content)) return ''
148
+ return content.filter(b => b && b.type === 'text' && typeof b.text === 'string')
149
+ .map(b => b.text).join('').trim()
150
+ }
151
+
152
+ /**
153
+ * 会话历史记录是 { type:'event', event } 包装(宿主 SessionEventsPage.records),
154
+ * 取事件本体后才能用 type/seq 分支。
155
+ */
156
+ function unwrapRecord(record) {
157
+ if (!record || typeof record !== 'object') return null
158
+ return record.type === 'event' && record.event ? record.event : record
159
+ }
160
+
161
+ /**
162
+ * 把会话事件流映射为面板用的精简消息数组(client 不接触原始事件)。
163
+ * tool/result 不新增消息条目,只更新更早 seq 的 tool 行;它的状态变化单独放进
164
+ * toolUpdates 回传,否则会被 afterSeq 增量裁剪丢掉。
165
+ */
166
+ function mapEvents(records) {
167
+ const messages = []
168
+ const toolUpdates = []
169
+ let lastStart = -1
170
+ let lastEnd = -1
171
+ let cursor = 0
172
+ for (const record of records || []) {
173
+ const ev = unwrapRecord(record)
174
+ if (!ev) continue
175
+ const seq = ev.seq
176
+ if (typeof seq === 'number' && seq > cursor) cursor = seq
177
+ if (ev.type === 'user/message') {
178
+ const src = ev.data && ev.data.source
179
+ // 宿主按 source.kind === 'user' 取真人消息;agent.inject() 的上下文不能混进对话
180
+ if (!src || src.kind !== 'user') continue
181
+ const text = textOf(ev.data && ev.data.content)
182
+ if (text) messages.push({ seq, role: 'user', text })
183
+ } else if (ev.type === 'assistant/message') {
184
+ const text = textOf(ev.data && ev.data.message && ev.data.message.content)
185
+ if (text) messages.push({ seq, role: 'assistant', text })
186
+ } else if (ev.type === 'tool/call') {
187
+ const d = ev.data || {}
188
+ const m = { seq, role: 'tool', toolName: d.name, callId: d.callId, state: 'running' }
189
+ // ask_user_question:把问题内容带上面板渲染成提示卡片(作答仍走完整会话)
190
+ if (d.name === 'ask_user_question' && typeof d.arguments === 'string') {
191
+ try {
192
+ const parsed = JSON.parse(d.arguments)
193
+ if (Array.isArray(parsed.questions) && parsed.questions.length) m.ask = parsed.questions
194
+ } catch { /* 参数不是合法 JSON 就退回普通工具行 */ }
195
+ }
196
+ messages.push(m)
197
+ } else if (ev.type === 'tool/result') {
198
+ const d = ev.data || {}
199
+ const msg = d.message || {}
200
+ // tool/result 顶层没有 callId:调用标识在 message.toolCallId 或 message.source.callId
201
+ const callId = d.callId || msg.toolCallId || (msg.source && msg.source.callId)
202
+ if (!callId) continue
203
+ const state = d.error || msg.isError ? 'error' : 'done'
204
+ for (let i = messages.length - 1; i >= 0; i--) {
205
+ const m = messages[i]
206
+ if (m.role === 'tool' && m.callId === callId) {
207
+ m.state = state
208
+ break
209
+ }
210
+ }
211
+ if (typeof seq === 'number') toolUpdates.push({ seq, callId, state })
212
+ } else if (ev.type === 'turn/start') {
213
+ if (typeof seq === 'number' && seq > lastStart) lastStart = seq
214
+ } else if (ev.type === 'turn/end') {
215
+ if (typeof seq === 'number' && seq > lastEnd) lastEnd = seq
216
+ }
217
+ }
218
+ return { messages, cursor, running: lastStart > lastEnd, toolUpdates }
219
+ }
220
+
221
+ /** topic 只允许单段目录名,字符白名单与 /topic/create 对齐 */
222
+ function validTopic(topic) {
223
+ return typeof topic === 'string' && topic.length > 0 &&
224
+ !/[\\/:*?"<>|]/.test(topic) && !topic.includes('..')
225
+ }
226
+
227
+ /** 宿主 Remote 错误:会话不存在(冷会话也读不到持久化时) */
228
+ function isSessionNotFound(err) {
229
+ for (let e = err, depth = 0; e && depth < 4; depth++) {
230
+ const code = typeof e.code === 'string' ? e.code : ''
231
+ if (/not[-_]?found/i.test(code)) return true
232
+ e = e.cause
233
+ }
234
+ return false
235
+ }
236
+
237
+ async function readBody(req) {
238
+ const chunks = []
239
+ for await (const chunk of req) chunks.push(chunk)
240
+ const raw = Buffer.concat(chunks).toString('utf8') || '{}'
241
+ try {
242
+ return JSON.parse(raw)
243
+ } catch {
244
+ const err = new Error('invalid body')
245
+ err.status = 400
246
+ throw err
247
+ }
248
+ }
249
+
250
+ /** 读原始请求体(上传用):Content-Length 预检 + 读取累计硬顶,超限 413 并断开 */
251
+ async function readRawBody(req, cap) {
252
+ const len = Number(req.headers['content-length'] || 0)
253
+ if (len > cap) { const e = new Error('payload too large'); e.status = 413; throw e }
254
+ const chunks = []
255
+ let total = 0
256
+ for await (const chunk of req) {
257
+ total += chunk.length
258
+ if (total > cap) {
259
+ try { req.destroy() } catch { /* 已断开 */ }
260
+ const e = new Error('payload too large'); e.status = 413; throw e
261
+ }
262
+ chunks.push(chunk)
263
+ }
264
+ return Buffer.concat(chunks)
265
+ }
266
+
267
+ /**
268
+ * 手工解析 multipart/form-data(零依赖):
269
+ * Buffer.indexOf 按 '--boundary' 字节级切段(二进制安全),头区按 utf8 解码取
270
+ * Content-Disposition 的 name / filename(filename*= 优先,RFC 5987)。
271
+ * 文本字段转字符串,文件字段保留 Buffer。解析不出任何 part → 400。
272
+ */
273
+ function parseMultipart(buffer, contentType) {
274
+ const bm = /boundary=(?:"([^"]+)"|([^\s;]+))/i.exec(String(contentType || ''))
275
+ if (!bm) { const e = new Error('missing multipart boundary'); e.status = 400; throw e }
276
+ const boundary = bm[1] || bm[2]
277
+ const delim = Buffer.from('--' + boundary)
278
+ // 行首 boundary(前面必是 \r\n;首个除外)——避免文件内容里恰好出现 boundary 字面量而截断
279
+ const lineDelim = Buffer.concat([Buffer.from('\r\n'), delim])
280
+ const fields = {}
281
+ const files = []
282
+ let pos = buffer.indexOf(delim)
283
+ if (pos === -1) { const e = new Error('invalid multipart body'); e.status = 400; throw e }
284
+ while (pos !== -1) {
285
+ // part 起点:分隔符行后的 \r\n;结尾分隔符是 --boundary--
286
+ let start = pos + delim.length
287
+ if (buffer.slice(start, start + 2).toString('latin1') === '--') break
288
+ start += 2
289
+ const headEnd = buffer.indexOf('\r\n\r\n', start)
290
+ if (headEnd === -1) break
291
+ const next = buffer.indexOf(lineDelim, headEnd)
292
+ if (next === -1) break
293
+ const head = buffer.slice(start, headEnd).toString('utf8')
294
+ // part 体区到 \r\n--boundary 为止(不含该 \r\n)
295
+ const data = buffer.slice(headEnd + 4, next)
296
+ const cd = /content-disposition:([^\r\n]*)/i.exec(head)
297
+ if (cd) {
298
+ const disp = cd[1]
299
+ const nameM = /name="((?:[^"\\]|\\.)*)"/i.exec(disp)
300
+ const name = nameM ? nameM[1].replace(/\\(.)/g, '$1') : ''
301
+ // filename*=UTF-8''...(RFC 5987,百分号解码)优先于普通 filename
302
+ let filename = ''
303
+ const starM = /filename\*=(?:utf-8|UTF-8)''([^;\r\n]+)/i.exec(disp)
304
+ if (starM) {
305
+ try { filename = decodeURIComponent(starM[1].trim()) } catch { filename = starM[1].trim() }
306
+ } else {
307
+ const fileM = /filename="((?:[^"\\]|\\.)*)"/i.exec(disp)
308
+ if (fileM) filename = fileM[1].replace(/\\(.)/g, '$1')
309
+ }
310
+ if (filename) files.push({ name: name || 'file', filename, data })
311
+ else if (name) fields[name] = data.toString('utf8')
312
+ }
313
+ pos = next + 2
314
+ }
315
+ if (!Object.keys(fields).length && !files.length) {
316
+ const e = new Error('invalid multipart body: no parts'); e.status = 400; throw e
317
+ }
318
+ return { fields, files }
319
+ }
320
+
321
+ /** 材料扩展名白名单(小写比较) */
322
+ const MATERIAL_EXTS = new Set(['pdf', 'md', 'txt', 'docx', 'pptx', 'xlsx', 'csv', 'json', 'epub', 'png', 'jpg', 'jpeg', 'gif', 'webp', 'zip'])
323
+ const MAX_FILE_SIZE = 20 * 1024 * 1024 // 单文件 20MB
324
+ const MAX_TOPIC_TOTAL = 200 * 1024 * 1024 // 课程总量 200MB
325
+ const MAX_UPLOAD_BODY = 25 * 1024 * 1024 // 请求级硬顶 25MB
326
+
327
+ /** 材料文件名清洗:去 Windows 非法字符与首尾空白/点;空名拒绝 */
328
+ function cleanMaterialName(filename) {
329
+ let n = String(filename || '').replace(/[\\/:*?"<>|]/g, '').trim().replace(/^[. ]+|[. ]+$/g, '')
330
+ if (!n || n === '.' || n === '..') { const e = new Error('文件名为空或不合法'); e.status = 400; throw e }
331
+ return n
332
+ }
333
+
334
+ /** 同名冲突:name-1.ext、name-2.ext 依序找空位,不覆盖 */
335
+ async function dedupeName(dir, name) {
336
+ const dot = name.lastIndexOf('.')
337
+ const stem = dot > 0 ? name.slice(0, dot) : name
338
+ const ext = dot > 0 ? name.slice(dot) : ''
339
+ let candidate = name
340
+ for (let i = 1; ; i++) {
341
+ try { await stat(path.join(dir, candidate)); candidate = `${stem}-${i}${ext}` }
342
+ catch { return candidate }
343
+ }
344
+ }
345
+
346
+ async function journalLines(root, limit = 8) {
347
+ const dir = path.join(root, 'journal')
348
+ let files = []
349
+ try { files = (await readdir(dir)).filter(f => f.endsWith('.md')).sort().reverse() } catch { return [] }
350
+ const lines = []
351
+ for (const f of files) {
352
+ const text = await readFile(path.join(dir, f), 'utf8')
353
+ for (const m of text.matchAll(/^- (\d{4}-\d{2}-\d{2}[^\n]*)$/gm)) lines.push(m[1])
354
+ if (lines.length >= limit) break
355
+ }
356
+ return lines.slice(0, limit)
357
+ }
358
+
359
+ // ── session.json 两阶段状态(读侧推导 + 写侧镜像) ──────────────
360
+
361
+ /**
362
+ * 读课程会话状态并做内存推导(迁移不落盘):
363
+ * 旧 {sessionId}(无 phase 字段)→ 视为 { phase:2, phase2SessionId:sessionId },
364
+ * 存量课程直接进阶段二续学;webSearch 缺省 true(对齐 learn_guide 现有「上网检索核实」)。
365
+ * 无 session.json 返回初始空态(phase 1、双空)。
366
+ */
367
+ async function readSessionState(topicDir) {
368
+ let raw = null
369
+ try { raw = JSON.parse(await readFile(path.join(topicDir, 'session.json'), 'utf8')) } catch { /* 未绑定 */ }
370
+ if (!raw) return { phase: 1, phase1SessionId: null, phase2SessionId: null, webSearch: true }
371
+ if (raw.phase == null && raw.sessionId) {
372
+ return { phase: 2, phase1SessionId: null, phase2SessionId: raw.sessionId, webSearch: raw.webSearch !== false }
373
+ }
374
+ const phase1SessionId = raw.phase1SessionId ?? null
375
+ const phase2SessionId = raw.phase2SessionId ?? null
376
+ let phase = raw.phase
377
+ if (phase !== 1 && phase !== 2) phase = phase2SessionId ? 2 : 1
378
+ return { phase, phase1SessionId, phase2SessionId, webSearch: raw.webSearch !== false }
379
+ }
380
+
381
+ /** 写侧始终带镜像 sessionId = phase2SessionId ?? phase1SessionId:回滚到旧插件仍能路由到会话 */
382
+ async function writeSessionState(topicDir, state) {
383
+ const doc = {
384
+ phase: state.phase === 2 ? 2 : 1,
385
+ phase1SessionId: state.phase1SessionId ?? null,
386
+ phase2SessionId: state.phase2SessionId ?? null,
387
+ webSearch: state.webSearch !== false,
388
+ sessionId: state.phase2SessionId ?? state.phase1SessionId ?? null,
389
+ }
390
+ await writeFile(path.join(topicDir, 'session.json'), JSON.stringify(doc, null, 2), 'utf8')
391
+ return doc
392
+ }
393
+
394
+ // ── 模型选择持久化(项目根 .learning-space.json) ──────────────
395
+
396
+ /** 读模型选择:无文件 / 坏 JSON / 形状不合法 → null(= 跟随宿主默认,与现状一致) */
397
+ async function readModelSelection(root) {
398
+ let raw = null
399
+ try { raw = JSON.parse(await readFile(path.join(root, '.learning-space.json'), 'utf8')) }
400
+ catch { /* 无文件或坏 JSON:按 null 处理,可 warn 但不必打扰 */ }
401
+ const m = raw && raw.model
402
+ if (!m || typeof m !== 'object' || typeof m.provider !== 'string' || !m.provider ||
403
+ typeof m.model !== 'string' || !m.model) return null
404
+ const sel = { provider: m.provider, model: m.model }
405
+ if (typeof m.reasoningEffort === 'string' && m.reasoningEffort) sel.reasoningEffort = m.reasoningEffort
406
+ return sel
407
+ }
408
+
409
+ /** 写模型选择:sel 为 null 时写 {model:null}(读侧与无文件等价) */
410
+ async function writeModelSelection(root, sel) {
411
+ await writeFile(path.join(root, '.learning-space.json'),
412
+ JSON.stringify({ model: sel ?? null }, null, 2), 'utf8')
413
+ }
414
+
415
+ /** 立即应用的目标会话:phase2 优先,无则 phase1,都未绑定返回 null */
416
+ async function modelApplyTarget(root, topic) {
417
+ const state = await readSessionState(path.join(root, 'curriculum', topic))
418
+ if (state.phase2SessionId) return { phase: 2, sessionId: state.phase2SessionId }
419
+ if (state.phase1SessionId) return { phase: 1, sessionId: state.phase1SessionId }
420
+ return null
421
+ }
422
+
423
+ /** 缺省 phase 推导:显式 1|2 优先,否则有 phase2SessionId → 2,再退 state.phase */
424
+ function resolvePhase(state, phase) {
425
+ if (phase === 1 || phase === 2) return phase
426
+ if (state.phase2SessionId) return 2
427
+ return state.phase === 2 ? 2 : 1
428
+ }
429
+
430
+ /** 按 phase 取对应会话 id */
431
+ function phaseSessionId(state, phase) {
432
+ return phase === 1 ? state.phase1SessionId : phase === 2 ? state.phase2SessionId : null
433
+ }
434
+
435
+ // ── 两段 seed 指令(联网话术同一处三元拼接,保证两段一致) ──────────
436
+
437
+ /** 阶段一 seed:只摸底 + 生成 plan.md,不开教 */
438
+ function seedPhase1(topic, goal, webSearch) {
439
+ return `我开始了课程《${topic}》的摸底与学习计划生成${goal ? `(目标:${goal})` : ''}。请先调用 learn_guide 获取完整教学方法,然后**只执行教学流程的前三步**:
440
+ 1. 确认资料来源:用户上传的材料在 materials/${topic}/ 目录下。${webSearch ? '资料不足时允许用网络搜索核实补充。' : '只允许使用用户上传的材料,禁止联网检索。'}
441
+ 2. 出题定位:按 quiz 教学方法出摸底题,定位我的当前水平。
442
+ 3. 生成学习计划:综合目标和摸底结果,用 learn_update 的 save 把完整的 curriculum/${topic}/plan.md 重写(必须保持 frontmatter(topic/goal) + mermaid 依赖图(classDef done/doing/warn/todo + 节点:::类名) + 「## 学习顺序」checkbox 的格式)。
443
+
444
+ **本阶段不要开始正式教学,不要讲解任何节点的内容。** 计划写入 plan.md 后,明确告诉我:「学习计划已生成,请在学习空间面板点击开始学习」。`
445
+ }
446
+
447
+ /** 阶段二 seed:按 plan.md 逐节点教学,每节点确认后必须写 study_log */
448
+ function seedPhase2(topic, goal, webSearch) {
449
+ return `我开始课程《${topic}》的正式学习${goal ? `(目标:${goal})` : ''}。请先调用 learn_guide 获取教学方法,再调用 learn_status 查看进度,然后严格按 curriculum/${topic}/plan.md 的「学习顺序」教学:从第一个未确认(\`[ ]\`/\`[!]\`)节点开始,已确认的跳过。
450
+ 每教完一个节点,依次:①向我确认掌握情况后才进入下一节点;②用 learn_update 的 save 更新 plan.md 中该节点的 checkbox 状态;③**必须**用 learn_update 的 study_log 把本节点摘要(知识点要点 + 我的掌握情况)写入学习记录;④发现我答错的题用 record_mistake 记错题。
451
+ 资料来源:materials/${topic}/ 目录下的用户材料${webSearch ? ',可辅以网络搜索核实。' : ',禁止联网检索。'}`
452
+ }
453
+
454
+ // ── 计划成型检测 + 学习记录解析 ──────────────────
455
+
456
+ const SKELETON_LABELS = ['无条件真理', '目标']
457
+ /** 骨架 plan 签名:恰好两节点且标签为骨架对(/topic/create 与 init_topic 写入的初始骨架) */
458
+ function isSkeletonPlan(nodes) {
459
+ return nodes.length === 2 && nodes.every(n => SKELETON_LABELS.includes(n.label))
460
+ }
461
+
462
+ /** study-log.md → 条目数组(文件顺序,最早在前);条目 = `## 日期 · 节点` + 要点/掌握行 */
463
+ function parseStudyLog(text) {
464
+ const entries = []
465
+ for (const b of String(text || '').split(/(?=^## )/m)) {
466
+ const head = /^## (\d{4}-\d{2}-\d{2}) · (.+?)\s*$/m.exec(b)
467
+ if (!head) continue
468
+ const pick = re => { const m = re.exec(b); return m ? m[1].trim() : '' }
469
+ entries.push({ date: head[1], node: head[2], summary: pick(/^- 要点:(.*)$/m), mastery: pick(/^- 掌握:(.*)$/m) })
470
+ }
471
+ return entries
472
+ }
473
+
474
+ /** 限制相对路径只在允许的根内,防逃逸 */
475
+ function safeJoin(root, rel, allowedBases) {
476
+ const norm = rel.replace(/\\/g, '/')
477
+ const base = allowedBases.find(b => norm === b || norm.startsWith(b + '/'))
478
+ if (!base || norm.includes('..')) throw new Error(`路径越界或不被允许: ${rel}(只允许 ${allowedBases.join(', ')} 下)`)
479
+ return path.join(root, norm)
480
+ }
481
+
482
+ // ── 导出报告(自包含 HTML)─────────────────────────
483
+
484
+ /** 笔记文件名匹配:notes 目录文件列表 + 节点名 → 匹配的文件名(精确/清洗/归一化三级) */
485
+ function matchNoteFile(files, node) {
486
+ const stem = n => n.replace(/\.md$/i, '')
487
+ const norm = s => s.replace(/[\s\u3000()()::、,,。.\-—_/\\]/g, '')
488
+ return files.find(f =>
489
+ stem(f) === node
490
+ || stem(f) === node.replace(/[\\/:*?"<>|]/g, '-')
491
+ || norm(stem(f)) === norm(node)) || null
492
+ }
493
+
494
+ /** 报告展示用标签清洗:<br/> 换行标记 → 「 · 」(源数据不动) */
495
+ const reportLabel = s => String(s || '').replace(/<br\s*\/?>/gi, ' · ').replace(/\s{2,}/g, ' ').trim()
496
+
497
+ /** 节点在计划中的学习内容描述:mermaid 标签 <br/> 后的子描述 + checkbox 超出标签的注释 */
498
+ function nodePlanDesc(n) {
499
+ const punct = /[\s ()()::、,,。.\-—_/]/
500
+ const norm = s => String(s).replace(new RegExp(punct.source, 'g'), '')
501
+ // 纯进度注释(「(2026-11-19 已确认)」之类)不是学习内容,过滤
502
+ const statusOnly = /^[((]?\s*(\d{4}-\d{2}-\d{2}\s*)?(摸底)?(已确认|待学|待修复|进行中|未学|已掌握|基本掌握|需复习)\s*[))]?$/
503
+ const parts = []
504
+ const label = String(n.label || '')
505
+ const br = /<br\s*\/?>/i.exec(label)
506
+ if (br) {
507
+ const tail = label.slice(br.index + br[0].length).replace(/<br\s*\/?>/gi, ';').trim()
508
+ if (tail) parts.push(tail)
509
+ }
510
+ const cb = String(n.checkbox || '')
511
+ if (cb) {
512
+ // checkbox 可能带「<id> 」前缀;标签取 <br/> 前的主标题做前缀比对。
513
+ // 全半角标点/空白差异(mermaid 用 : checkbox 用 :)按归一化前缀定位,再映射回原文取注释
514
+ const head = (br ? label.slice(0, br.index) : label).trim()
515
+ const idPrefix = new RegExp(`^${String(n.id).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[\\s::]+`)
516
+ const body = cb.replace(idPrefix, '').trim()
517
+ const normHead = norm(head)
518
+ // idx[i] = 归一化第 i 个字符在原文中的下一位置,用于把前缀长度映射回原文切出注释
519
+ const idx = []
520
+ let normBody = ''
521
+ for (let i = 0; i < body.length; i++) {
522
+ if (!punct.test(body[i])) { normBody += body[i]; idx.push(i + 1) }
523
+ }
524
+ if (normHead && normBody.length > normHead.length && normBody.startsWith(normHead)) {
525
+ const tail = body.slice(idx[normHead.length - 1]).trim()
526
+ const inner = tail.replace(/^[((]\s*/, '').replace(/\s*[))]$/, '')
527
+ // 与 <br/> 子描述归一化后互为子串的视为重复(「终止」vs「终止条件」),只留更长的
528
+ const nt = norm(inner)
529
+ const dup = parts.findIndex(p => { const np = norm(p); return np && nt && (np.includes(nt) || nt.includes(np)) })
530
+ if (tail && !statusOnly.test(inner)) {
531
+ if (dup >= 0) { if (nt.length > norm(parts[dup]).length) parts[dup] = tail }
532
+ else parts.push(tail)
533
+ }
534
+ }
535
+ }
536
+ return parts.join(';')
537
+ }
538
+
539
+ /** 插件自身目录(定位 assets/,不依赖 cwd) */
540
+ const PLUGIN_DIR = path.dirname(fileURLToPath(import.meta.url))
541
+
542
+ /** HTML 转义:& < > " ' 五字符 */
543
+ function escapeHtml(s) {
544
+ return String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;')
545
+ .replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;')
546
+ }
547
+
548
+ /** mermaid 源码进 <script>/HTML 前的双保险:先 HTML 转义,再拆 </script 字面量 */
549
+ function escapeMermaidSrc(s) {
550
+ return escapeHtml(s).replace(/<\/script/gi, '&lt;\\/script')
551
+ }
552
+
553
+ /** 内嵌 JS(mermaid.min.js 全文)安全放进 <script>:拆掉闭合标签字面量 */
554
+ function embedJs(code) {
555
+ return String(code).replace(/<\/script/gi, '<\\/script')
556
+ }
557
+
558
+ const REPORT_STATUS_LABEL = { done: '已确认', doing: '进行中', warn: '待修复', todo: '未学' }
559
+ const REPORT_STATUS_COLOR = { done: '#3E6B4F', doing: '#3D5A80', warn: '#B5432E', todo: '#6E6A60' }
560
+
561
+ /**
562
+ * 自包含 HTML 报告(方案 A):mermaid.min.js 全文内嵌,浏览器打开时 startOnLoad 渲染。
563
+ * mermaidJs 为 null 时降级:不嵌脚本,.mermaid 块直接显示源码文本 + 顶部提示。
564
+ */
565
+ /** 导出报告用极简 markdown → HTML:代码块/标题/列表/加粗/行内码;无法识别的行按段落(先整体转义防注入) */
566
+ function mdToHtmlHost(text) {
567
+ const esc = escapeHtml
568
+ const lines = String(text || '').split(/\r?\n/)
569
+ const out = []
570
+ let code = null
571
+ let list = null
572
+ const inline = s => s
573
+ .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
574
+ .replace(/`([^`]+)`/g, '<code>$1</code>')
575
+ const flushList = () => { if (list && list.length) { out.push(`<ul>${list.map(li => `<li>${inline(li)}</li>`).join('')}</ul>`); list = null } }
576
+ for (const raw of lines) {
577
+ if (/^\s*```/.test(raw)) {
578
+ if (code) { out.push(`<pre><code>${esc(code.join('\n'))}</code></pre>`); code = null } else { flushList(); code = [] }
579
+ continue
580
+ }
581
+ if (code) { code.push(raw); continue }
582
+ const hm = /^(#{1,4})\s+(.*)$/.exec(raw)
583
+ if (hm) { flushList(); out.push(`<h4>${inline(esc(hm[2]))}</h4>`); continue }
584
+ if (/^\s*[-*]\s+/.test(raw)) { list = list || []; list.push(esc(raw.replace(/^\s*[-*]\s+/, ''))); continue }
585
+ flushList()
586
+ if (raw.trim()) out.push(`<p>${inline(esc(raw))}</p>`)
587
+ }
588
+ if (code) out.push(`<pre><code>${esc(code.join('\n'))}</code></pre>`)
589
+ flushList()
590
+ return out.join('\n')
591
+ }
592
+
593
+ function buildReportHtml(topicsData, { all, mermaidJs }) {
594
+ const esc = escapeHtml
595
+ const date = new Date().toISOString().slice(0, 10)
596
+ const title = all ? `学习报告 · 全部课程(${date})` : `学习报告 · ${topicsData[0] ? topicsData[0].name : ''}(${date})`
597
+ const sections = topicsData.map(t => {
598
+ const { name, goal, counts, nodes, planMermaid, quizRecords, mistakes, journal } = t
599
+ const total = nodes.length
600
+ const doneCount = counts.done || 0
601
+ const pct = total ? Math.round((doneCount / total) * 100) : 0
602
+ const badges = ['done', 'doing', 'warn', 'todo'].filter(s => counts[s])
603
+ .map(s => `<span class="badge" style="background:${REPORT_STATUS_COLOR[s]}">${REPORT_STATUS_LABEL[s]} ${counts[s]}</span>`).join('')
604
+ const nodeRows = nodes.map(n =>
605
+ `<tr><td>${esc(reportLabel(n.label))}</td><td><span class="badge" style="background:${REPORT_STATUS_COLOR[n.status] || REPORT_STATUS_COLOR.todo}">${REPORT_STATUS_LABEL[n.status] || n.status}</span></td></tr>`).join('')
606
+ const quizRows = quizRecords.length ? quizRecords.map(r =>
607
+ `<tr><td>${esc(r.date)}</td><td>第 ${esc(r.index)} / ${esc(r.total)} 题</td><td>${r.correct ? '✅ 答对' : '❌ 答错'}</td><td>${esc(r.stem)}</td><td>答 ${esc(r.answer)}</td><td>${esc(r.feedback)}</td></tr>`).join('')
608
+ : '<tr><td colspan="6" class="muted">暂无答题记录</td></tr>'
609
+ const mistakeItemsHtml = mistakes.length
610
+ ? `<ul>${mistakes.map(m => `<li>${esc(m)}</li>`).join('')}</ul>`
611
+ : '<p class="muted">暂无错题</p>'
612
+ const journalHtml = journal.length
613
+ ? `<ul>${journal.map(l => `<li>${esc(l)}</li>`).join('')}</ul>`
614
+ : '<p class="muted">暂无日志</p>'
615
+ const studyLog = t.studyLog || []
616
+ const studyRows = studyLog.length ? studyLog.map(e =>
617
+ `<tr><td>${esc(e.date)}</td><td>${esc(e.node)}</td><td>${esc(e.mastery || '—')}</td><td>${esc(e.summary)}</td></tr>`).join('')
618
+ : '<tr><td colspan="4" class="muted">暂无学习记录</td></tr>'
619
+ const nodeNotes = t.nodeNotes || []
620
+ const notesHtml = nodeNotes.length
621
+ ? nodeNotes.map(nn => {
622
+ const body = nn.content
623
+ ? mdToHtmlHost(nn.content)
624
+ : nn.desc
625
+ ? `<p>${esc(nn.desc)}</p><p class="muted">以上为该节点计划中的学习内容,教学笔记将在学习确认后写入。</p>`
626
+ : '<p class="muted">暂无教学笔记(学到这里时 AI 会写入 notes/&lt;节点&gt;.md)</p>'
627
+ return `<details class="note"${nn.content ? ' open' : ''}><summary><span class="badge" style="background:${REPORT_STATUS_COLOR[nn.status] || REPORT_STATUS_COLOR.todo}">${REPORT_STATUS_LABEL[nn.status] || nn.status || ''}</span> ${esc(reportLabel(nn.label))}</summary><div class="note-body">${body}</div></details>`
628
+ }).join('\n')
629
+ : '<p class="muted">暂无教学笔记(学到的节点会由 AI 写入 notes 后出现在这里)</p>'
630
+ return `<section>
631
+ <h2>${esc(name)}</h2>
632
+ <p class="goal">${esc(goal || '(未设置目标)')}</p>
633
+ <div class="meta">${esc(doneCount)} / ${esc(total)} 已确认(${esc(pct)}%) ${badges}</div>
634
+ <div class="bar"><div class="bar-fill" style="width:${esc(pct)}%"></div></div>
635
+ <h3>依赖图</h3>
636
+ <div class="graph-wrap">${planMermaid
637
+ ? `<div class="mermaid${mermaidJs ? '' : ' raw'}">${escapeMermaidSrc(planMermaid)}</div>`
638
+ : '<p class="muted">plan.md 中无 mermaid 图</p>'}</div>
639
+ <h3>节点状态</h3>
640
+ <table><thead><tr><th>节点</th><th>状态</th></tr></thead><tbody>${nodeRows || '<tr><td colspan="2" class="muted">无节点</td></tr>'}</tbody></table>
641
+ <h3>节点学习内容</h3>
642
+ <div class="notes">${notesHtml}</div>
643
+ <h3>学习记录</h3>
644
+ <table><thead><tr><th>日期</th><th>节点</th><th>掌握</th><th>要点</th></tr></thead><tbody>${studyRows}</tbody></table>
645
+ <h3>答题历史</h3>
646
+ <table><thead><tr><th>日期</th><th>序号</th><th>结果</th><th>题面</th><th>作答</th><th>反馈</th></tr></thead><tbody>${quizRows}</tbody></table>
647
+ <h3>错题</h3>${mistakeItemsHtml}
648
+ <h3>学习日志</h3>${journalHtml}
649
+ </section>`
650
+ }).join('\n')
651
+ const mermaidBoot = mermaidJs
652
+ ? `<script>${embedJs(mermaidJs)}</script>
653
+ <script>
654
+ mermaid.initialize({ startOnLoad: true, theme: 'neutral', securityLevel: 'loose' })
655
+ </script>`
656
+ : `<p class="warn">mermaid 资产缺失,依赖图以源码文本显示。</p>`
657
+ return `<!DOCTYPE html>
658
+ <html lang="zh-CN">
659
+ <head>
660
+ <meta charset="utf-8">
661
+ <meta name="viewport" content="width=device-width, initial-scale=1">
662
+ <title>${esc(title)}</title>
663
+ <style>
664
+ body { font-family: -apple-system, "Segoe UI", "Microsoft YaHei", sans-serif; margin: 0 auto;
665
+ max-width: 960px; padding: 24px 20px; color: #2c2c2c; background: #faf9f6; line-height: 1.7; }
666
+ h1 { font-size: 24px; } h2 { font-size: 18px; border-bottom: 2px solid #3d5a80; padding-bottom: 6px; }
667
+ h3 { font-size: 14px; color: #6e6a60; letter-spacing: 2px; margin-bottom: 6px; }
668
+ section { background: #fff; border: 1px solid #e4e0d8; border-radius: 10px; padding: 18px 22px; margin-bottom: 20px; }
669
+ .goal { color: #6e6a60; margin: 4px 0 10px; }
670
+ .meta { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font-size: 13px; }
671
+ .badge { display: inline-block; color: #faf7f0; font-size: 12px; border-radius: 10px; padding: 1px 10px; }
672
+ .bar { height: 6px; border-radius: 3px; background: #e4e0d8; margin: 10px 0 16px; overflow: hidden; }
673
+ .bar-fill { height: 100%; background: #3e6b4f; }
674
+ .graph-wrap { border: 1px solid #e4e0d8; border-radius: 8px; padding: 10px; overflow-x: auto; margin-bottom: 14px; }
675
+ .mermaid { display: flex; justify-content: center; }
676
+ .mermaid.raw { white-space: pre; font-family: Consolas, monospace; font-size: 12px; text-align: left; }
677
+ .mermaid svg { max-width: 100%; }
678
+ table { border-collapse: collapse; width: 100%; font-size: 13px; margin-bottom: 14px; }
679
+ th, td { border: 1px solid #e4e0d8; padding: 5px 9px; text-align: left; word-break: break-word; }
680
+ th { background: #f1eee7; }
681
+ .notes details.note { border: 1px solid #e4e0d8; border-radius: 8px; padding: 8px 12px; margin-bottom: 8px; }
682
+ .notes summary { cursor: pointer; font-weight: 600; font-size: 13px; }
683
+ .notes .note-body { border-top: 1px dashed #e4e0d8; margin-top: 8px; padding-top: 8px; font-size: 13px; }
684
+ .notes .note-body pre { background: #f1eee7; border-radius: 6px; padding: 8px 10px; overflow-x: auto; font-size: 12px; }
685
+ .notes .note-body code { background: #f1eee7; border-radius: 3px; padding: 0 4px; }
686
+ ul { padding-left: 20px; } li { margin: 3px 0; font-size: 13px; }
687
+ .muted { color: #9a968c; font-size: 13px; }
688
+ .warn { background: #fdf3e7; border: 1px solid #e8c89a; border-radius: 8px; padding: 8px 12px; font-size: 13px; }
689
+ footer { color: #9a968c; font-size: 12px; text-align: center; margin-top: 12px; }
690
+ </style>
691
+ </head>
692
+ <body>
693
+ <h1>${esc(title)}</h1>
694
+ ${all && topicsData.length > 1 ? `<p class="muted">共 ${esc(topicsData.length)} 门课程</p>` : ''}
695
+ ${mermaidBoot}
696
+ ${sections}
697
+ <footer>由学习空间面板导出 · ${esc(date)}</footer>
698
+ </body>
699
+ </html>`
700
+ }
701
+
702
+ /** 导出用:课程名进文件名的清洗 */
703
+ function cleanFilename(s) {
704
+ return String(s || '').replace(/[\\/:*?"<>|\s]+/g, '_').slice(0, 50) || 'report'
705
+ }
706
+
707
+ /** 收集一门课程的导出数据(plan/mistakes 已在 listTopics 读过,补 quiz 记录、study-log、节点教学笔记与该课日志) */
708
+ async function collectTopicForExport(root, t) {
709
+ const quizRecords = await parseQuizLog(root, t.name).catch(() => [])
710
+ const allJournal = await journalLines(root, 100).catch(() => [])
711
+ const journal = allJournal.filter(l => l.includes(`· ${t.name} ·`))
712
+ let studyLog = []
713
+ try { studyLog = parseStudyLog(await readFile(path.join(root, 'curriculum', t.name, 'study-log.md'), 'utf8')) } catch { /* 无学习记录 */ }
714
+ // 节点教学内容:全部节点按顺序列出;有 notes/<节点>.md 的带笔记全文,
715
+ // 没有的带计划里的学习内容描述(mermaid <br/> 子描述 + checkbox 注释)
716
+ let noteFiles = []
717
+ try { noteFiles = await readdir(path.join(root, 'curriculum', t.name, 'notes')) } catch { /* 无 notes 目录 */ }
718
+ const nodeNotes = []
719
+ for (const n of t.nodes) {
720
+ const label = n.label || n.id
721
+ let content = ''
722
+ const f = matchNoteFile(noteFiles, label)
723
+ if (f) {
724
+ try { content = await readFile(path.join(root, 'curriculum', t.name, 'notes', f), 'utf8') } catch { /* 读失败按无笔记 */ }
725
+ // 笔记头部 frontmatter(node/deps/date)是元数据,报告只呈现正文
726
+ content = content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '')
727
+ }
728
+ nodeNotes.push({ label, status: n.status, desc: nodePlanDesc(n), content: content.trim() ? content : '' })
729
+ }
730
+ return { name: t.name, goal: t.goal, counts: t.counts, nodes: t.nodes,
731
+ planMermaid: t.planMermaid, quizRecords, mistakes: t.mistakes, journal,
732
+ studyLog: studyLog.slice().reverse(), nodeNotes }
733
+ }
734
+
735
+ const toolOutput = {
736
+ schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string' } }, required: ['text'] },
737
+ render: (_args, result) => [{ type: 'text', text: result.text }],
738
+ }
739
+
740
+ export function apply(ctx, config) {
741
+ const root = (config && config.root) || process.cwd()
742
+
743
+ ctx.effect(() => ctx.webServer.register({
744
+ kind: 'prefix',
745
+ path: '/api/learning-space',
746
+ handler: async (req, res) => {
747
+ const url = new URL(req.url ?? '/', 'http://x')
748
+ const send = (status, body) => {
749
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
750
+ res.end(JSON.stringify(body))
751
+ }
752
+ try {
753
+ // 路由分派:multipart 只允许上传路由,其余路由收到 multipart 直接 415(readBody 只吃 JSON)
754
+ const ct = (req.headers['content-type'] || '').toLowerCase()
755
+ const isMultipart = ct.startsWith('multipart/')
756
+ const isUpload = req.method === 'POST' && url.pathname === '/api/learning-space/materials/upload'
757
+ if (isMultipart && !isUpload) { send(415, { ok: false, error: '该接口只接受 JSON 请求' }); return }
758
+ if (!isMultipart && isUpload) { send(415, { ok: false, error: '上传接口要求 multipart/form-data 请求' }); return }
759
+
760
+ // 材料上传:multipart 落盘 materials/<topic>/(二进制安全手工解析)
761
+ if (isUpload) {
762
+ const raw = await readRawBody(req, MAX_UPLOAD_BODY)
763
+ const { fields, files } = parseMultipart(raw, req.headers['content-type'])
764
+ const topic = fields.topic
765
+ if (!validTopic(topic)) { send(400, { ok: false, error: '课程名不合法' }); return }
766
+ try { await readFile(path.join(root, 'curriculum', topic, 'plan.md'), 'utf8') }
767
+ catch { send(404, { ok: false, error: `课程「${topic}」不存在` }); return }
768
+ if (!files.length) { send(400, { ok: false, error: '缺少文件字段 file' }); return }
769
+ // 先全量校验(扩展名 / 单文件大小 / 课程总量),任一违规则整个请求拒绝,不落半批
770
+ const mdir = path.join(root, 'materials', topic)
771
+ let existing = 0
772
+ try {
773
+ for (const f of await readdir(mdir)) {
774
+ try { existing += (await stat(path.join(mdir, f))).size } catch { /* 忽略 */ }
775
+ }
776
+ } catch { /* 目录尚不存在 */ }
777
+ let incoming = 0
778
+ for (const f of files) {
779
+ const clean = cleanMaterialName(f.filename)
780
+ const dot = clean.lastIndexOf('.')
781
+ const ext = dot > 0 ? clean.slice(dot + 1).toLowerCase() : ''
782
+ if (!MATERIAL_EXTS.has(ext)) {
783
+ send(400, { ok: false, error: `文件类型不允许: .${ext || clean}` }); return
784
+ }
785
+ if (f.data.length > MAX_FILE_SIZE) {
786
+ send(413, { ok: false, error: `文件「${clean}」超过单文件 20MB 上限` }); return
787
+ }
788
+ incoming += f.data.length
789
+ }
790
+ if (existing + incoming > MAX_TOPIC_TOTAL) {
791
+ send(413, { ok: false, error: '课程材料总大小超过 200MB' }); return
792
+ }
793
+ // 全量校验通过后统一写盘;同名冲突加序号
794
+ await mkdir(mdir, { recursive: true })
795
+ const saved = []
796
+ for (const f of files) {
797
+ const clean = cleanMaterialName(f.filename)
798
+ const finalName = await dedupeName(mdir, clean)
799
+ await writeFile(path.join(mdir, finalName), f.data)
800
+ saved.push({ name: finalName, size: f.data.length })
801
+ }
802
+ send(200, { ok: true, files: saved })
803
+ return
804
+ }
805
+ if (req.method === 'GET' && url.pathname === '/api/learning-space/overview') {
806
+ const [topics, journal] = await Promise.all([listTopics(root), journalLines(root)])
807
+ send(200, { ok: true, topics, journal })
808
+ return
809
+ }
810
+ // 模型设置:宿主模型目录透传 + 已保存选择;目录加载失败降级 catalog:null(保存仍可行,前端仅允许跟默认)
811
+ if (req.method === 'GET' && url.pathname === '/api/learning-space/settings/model') {
812
+ const saved = { model: await readModelSelection(root) }
813
+ let catalog = null
814
+ let error = null
815
+ try { catalog = await ctx.sessionController.modelCatalog() }
816
+ catch (err) { error = `模型目录暂不可用: ${String(err && err.message || err)}` }
817
+ send(200, { ok: true, catalog, saved, error })
818
+ return
819
+ }
820
+ // 模型设置保存:写 .learning-space.json;可选 applyToTopic 立即应用到该课程 phase2(无则 phase1)会话,
821
+ // apply 失败不使保存失败,错误文本随 applyError 返回
822
+ if (req.method === 'POST' && url.pathname === '/api/learning-space/settings/model') {
823
+ const { model, applyToTopic } = await readBody(req)
824
+ if (model !== null) {
825
+ const bad = !model || typeof model !== 'object' ||
826
+ typeof model.provider !== 'string' || !model.provider ||
827
+ typeof model.model !== 'string' || !model.model ||
828
+ (model.reasoningEffort !== undefined &&
829
+ (typeof model.reasoningEffort !== 'string' || !model.reasoningEffort))
830
+ if (bad) { send(400, { ok: false, error: 'invalid model' }); return }
831
+ }
832
+ if (applyToTopic !== undefined && !validTopic(applyToTopic)) {
833
+ send(400, { ok: false, error: 'invalid topic' }); return
834
+ }
835
+ const sel = model === null ? null
836
+ : model.reasoningEffort !== undefined
837
+ ? { provider: model.provider, model: model.model, reasoningEffort: model.reasoningEffort }
838
+ : { provider: model.provider, model: model.model }
839
+ try { await writeModelSelection(root, sel) }
840
+ catch (err) { send(500, { ok: false, error: String(err && err.message || err) }); return }
841
+ let applied = null
842
+ let applyError = null
843
+ if (applyToTopic && sel) {
844
+ try {
845
+ const target = await modelApplyTarget(root, applyToTopic)
846
+ if (target) {
847
+ await ctx.sessionController.selectModel(
848
+ { sessionId: target.sessionId, ...sel }, AbortSignal.timeout(8000))
849
+ applied = { topic: applyToTopic, phase: target.phase, sessionId: target.sessionId, selected: sel }
850
+ }
851
+ } catch (err) { applyError = String(err && err.message || err) }
852
+ }
853
+ send(200, { ok: true, saved: { model: sel }, applied, applyError })
854
+ return
855
+ }
856
+ // 开始/继续某课程的学习会话(分相):phase=1 摸底会话「摸底 · X」,phase=2 学习会话「学习 · X」
857
+ // 有绑定直接返回(幂等):冷会话由宿主 prompt/events 按需恢复,不重发 seed;
858
+ // 新建仅两入口:对应 phase 无绑定,或失效绑定显式 rebind:true(只重建该 phase 的会话)。
859
+ if (req.method === 'POST' && url.pathname === '/api/learning-space/session/start') {
860
+ const { topic, rebind, phase: phaseParam } = await readBody(req)
861
+ if (!topic || typeof topic !== 'string' || topic.includes('..') || topic.includes('/')) {
862
+ send(400, { ok: false, error: 'invalid topic' }); return
863
+ }
864
+ const topicDir = path.join(root, 'curriculum', topic)
865
+ const state = await readSessionState(topicDir)
866
+ const phase = resolvePhase(state, phaseParam)
867
+ let sessionId = phaseSessionId(state, phase)
868
+ if (!sessionId || rebind === true) {
869
+ const created = await ctx.sessionController.create({ cwd: root })
870
+ sessionId = created.sessionId
871
+ const next = { ...state }
872
+ if (phase === 1) { next.phase = 1; next.phase1SessionId = sessionId }
873
+ else { next.phase = 2; next.phase2SessionId = sessionId }
874
+ await writeSessionState(topicDir, next)
875
+ const session = ctx.sessions.get(sessionId)
876
+ if (session) {
877
+ try { ctx.sessionTitle.rename(session, phase === 1 ? `摸底 · ${topic}` : `学习 · ${topic}`) } catch { /* 标题失败不阻塞 */ }
878
+ }
879
+ // 点开始学习时,把阶段一摸底会话改名归位「摸底 · X」(旧数据可能叫「学习 · X」)
880
+ if (phase === 2 && next.phase1SessionId && next.phase1SessionId !== sessionId) {
881
+ const s1 = ctx.sessions.get(next.phase1SessionId)
882
+ if (s1) { try { ctx.sessionTitle.rename(s1, `摸底 · ${topic}`) } catch { /* 同上 */ } }
883
+ }
884
+ // 应用已保存的模型选择(无 .learning-space.json / model:null 时跳过,行为与现状一致)
885
+ const sel = await readModelSelection(root)
886
+ if (sel) {
887
+ try {
888
+ await ctx.sessionController.selectModel(
889
+ { sessionId, ...sel }, AbortSignal.timeout(8000))
890
+ } catch (err) {
891
+ // 失败不阻塞:会话退回宿主默认模型,仅记 warn
892
+ try { ctx.logger.warn(`learning-space: selectModel failed for ${sessionId}: ${String(err && err.message || err)}`) } catch { /* 无 logger */ }
893
+ }
894
+ }
895
+ // 唤醒:按 phase 注入对应 seed(联网开关取当时值,指令级生效)
896
+ let goal = ''
897
+ try { goal = parsePlan(await readFile(path.join(topicDir, 'plan.md'), 'utf8')).goal } catch { /* 无 plan */ }
898
+ const seed = phase === 1 ? seedPhase1(topic, goal, state.webSearch) : seedPhase2(topic, goal, state.webSearch)
899
+ try {
900
+ await ctx.sessionController.prompt({
901
+ sessionId,
902
+ requestId: cryptoRandomUUID(),
903
+ mode: 'queue',
904
+ content: [{ type: 'text', text: seed }],
905
+ }, AbortSignal.timeout(15000))
906
+ } catch (err) { /* 注入失败不阻塞打开会话,用户进去后 AI 仍可用工具 */ }
907
+ }
908
+ send(200, { ok: true, sessionId, phase })
909
+ return
910
+ }
911
+ // 内嵌对话窗:读会话历史消息(events 冷安全,不激活会话);按 phase 路由到对应会话
912
+ if (req.method === 'GET' && url.pathname === '/api/learning-space/session/messages') {
913
+ const topic = url.searchParams.get('topic') || ''
914
+ const afterSeqRaw = url.searchParams.get('afterSeq')
915
+ const phaseRaw = url.searchParams.get('phase')
916
+ if (!validTopic(topic)) { send(400, { ok: false, error: 'invalid topic' }); return }
917
+ let afterSeq = null
918
+ if (afterSeqRaw !== null && afterSeqRaw !== '') {
919
+ afterSeq = Number(afterSeqRaw)
920
+ if (!Number.isInteger(afterSeq) || afterSeq < 0) { send(400, { ok: false, error: 'invalid afterSeq' }); return }
921
+ }
922
+ const state = await readSessionState(path.join(root, 'curriculum', topic))
923
+ const phase = resolvePhase(state, phaseRaw === '1' ? 1 : phaseRaw === '2' ? 2 : undefined)
924
+ const sessionId = phaseSessionId(state, phase)
925
+ if (!sessionId) { send(404, { ok: false, error: 'no session' }); return }
926
+ let page
927
+ try {
928
+ page = await ctx.sessionController.events(
929
+ { address: { kind: 'session', sessionId }, maxMessages: 200 },
930
+ AbortSignal.timeout(10000),
931
+ )
932
+ } catch (err) {
933
+ if (isSessionNotFound(err)) { send(404, { ok: false, error: 'no session' }); return }
934
+ if (err && (err.name === 'TimeoutError' || err.name === 'AbortError')) { send(504, { ok: false, error: 'history read timeout' }); return }
935
+ send(500, { ok: false, error: String(err && err.message || err) }); return
936
+ }
937
+ const mapped = mapEvents(page && page.records)
938
+ // cursor 用宿主返回的日志读切点(records 的最大 seq),不要从记录自算
939
+ const cursor = page && typeof page.cursor === 'number' ? page.cursor : mapped.cursor
940
+ // quiz 配对:全量重放标注 m.quiz,闭环三元组幂等落盘(fbSeq 水位 + 文件内标记双保险);
941
+ // 阶段一摸底题若走 quiz 协议同样落盘——annotateQuiz 逻辑不动,phase 只影响会话路由
942
+ const annotated = annotateQuiz(mapped.messages)
943
+ for (const triple of annotated.triples) {
944
+ try { await appendQuizLog(root, topic, triple) } catch (err) { console.warn('[learning-space] quiz 落盘失败:', err) }
945
+ }
946
+ const messages = afterSeq === null ? annotated.messages : annotated.messages.filter(m => m.seq > afterSeq)
947
+ const toolUpdates = (afterSeq === null ? mapped.toolUpdates : mapped.toolUpdates.filter(u => u.seq > afterSeq))
948
+ .map(u => ({ callId: u.callId, state: u.state }))
949
+ send(200, {
950
+ ok: true, sessionId, cursor, running: mapped.running,
951
+ hasMore: !!(page && page.hasMore), messages, toolUpdates,
952
+ })
953
+ return
954
+ }
955
+ // 内嵌对话窗:往绑定会话发消息(不在此隐式建课);按 phase 路由到对应会话
956
+ if (req.method === 'POST' && url.pathname === '/api/learning-space/session/send') {
957
+ const { topic, text, phase: phaseParam } = await readBody(req)
958
+ if (!validTopic(topic)) { send(400, { ok: false, error: 'invalid topic' }); return }
959
+ if (!text || typeof text !== 'string') { send(400, { ok: false, error: 'empty text' }); return }
960
+ if (text.length > 8000) { send(400, { ok: false, error: 'text too long' }); return }
961
+ const state = await readSessionState(path.join(root, 'curriculum', topic))
962
+ const phase = resolvePhase(state, phaseParam)
963
+ const sessionId = phaseSessionId(state, phase)
964
+ if (!sessionId) { send(409, { ok: false, error: 'session gone, start first' }); return }
965
+ // 冷会话(DSH 重启后 ctx.sessions 里没有)也直接投递:prompt 会先恢复会话
966
+ try {
967
+ const requestId = cryptoRandomUUID()
968
+ await ctx.sessionController.prompt({
969
+ sessionId,
970
+ requestId,
971
+ mode: 'queue',
972
+ content: [{ type: 'text', text }],
973
+ }, AbortSignal.timeout(15000))
974
+ send(200, { ok: true, requestId })
975
+ } catch (err) {
976
+ if (isSessionNotFound(err)) { send(409, { ok: false, error: 'session gone, start first' }); return }
977
+ send(500, { ok: false, error: String(err && err.message || err) })
978
+ }
979
+ return
980
+ }
981
+ // 答题历史:quiz.md 按标记解析为记录数组(倒序,全量返回)
982
+ if (req.method === 'GET' && url.pathname === '/api/learning-space/quizlog') {
983
+ const topic = url.searchParams.get('topic') || ''
984
+ if (!validTopic(topic)) { send(400, { ok: false, error: 'invalid topic' }); return }
985
+ send(200, { ok: true, records: await parseQuizLog(root, topic) })
986
+ return
987
+ }
988
+ // 联网开关:只写 webSearch 字段,不动会话绑定(指令级,对下一次新会话生效)
989
+ if (req.method === 'POST' && url.pathname === '/api/learning-space/session/websearch') {
990
+ const { topic, enabled } = await readBody(req)
991
+ if (!validTopic(topic)) { send(400, { ok: false, error: 'invalid topic' }); return }
992
+ const topicDir = path.join(root, 'curriculum', topic)
993
+ const state = await readSessionState(topicDir)
994
+ const on = enabled !== false && enabled !== 'false'
995
+ await writeSessionState(topicDir, { ...state, webSearch: on })
996
+ send(200, { ok: true, webSearch: on })
997
+ return
998
+ }
999
+ // 下载 plan.md 原文(ASCII 兜底名 + RFC 5987 filename* 传中文名,写法同 /export)
1000
+ if (req.method === 'GET' && url.pathname === '/api/learning-space/export/plan') {
1001
+ const topic = url.searchParams.get('topic') || ''
1002
+ if (!validTopic(topic)) { send(400, { ok: false, error: 'invalid topic' }); return }
1003
+ let text
1004
+ try { text = await readFile(path.join(root, 'curriculum', topic, 'plan.md'), 'utf8') }
1005
+ catch { send(404, { ok: false, error: `课程「${topic}」不存在或尚无 plan.md` }); return }
1006
+ res.writeHead(200, {
1007
+ 'content-type': 'text/markdown; charset=utf-8',
1008
+ 'content-disposition': `attachment; filename="learning-plan.md"; filename*=UTF-8''${encodeURIComponent(`学习计划-${cleanFilename(topic)}.md`)}`,
1009
+ })
1010
+ res.end(text)
1011
+ return
1012
+ }
1013
+ // 下载 study-log.md 原文(同上头写法)
1014
+ if (req.method === 'GET' && url.pathname === '/api/learning-space/studylog') {
1015
+ const topic = url.searchParams.get('topic') || ''
1016
+ if (!validTopic(topic)) { send(400, { ok: false, error: 'invalid topic' }); return }
1017
+ let text
1018
+ try { text = await readFile(path.join(root, 'curriculum', topic, 'study-log.md'), 'utf8') }
1019
+ catch { send(404, { ok: false, error: `课程「${topic}」暂无学习记录` }); return }
1020
+ res.writeHead(200, {
1021
+ 'content-type': 'text/markdown; charset=utf-8',
1022
+ 'content-disposition': `attachment; filename="study-log.md"; filename*=UTF-8''${encodeURIComponent(`学习记录-${cleanFilename(topic)}.md`)}`,
1023
+ })
1024
+ res.end(text)
1025
+ return
1026
+ }
1027
+ // 面板新建课程:建骨架后即可开始学习会话
1028
+ if (req.method === 'POST' && url.pathname === '/api/learning-space/topic/create') {
1029
+ const { topic, goal } = await readBody(req)
1030
+ if (!topic || typeof topic !== 'string' || /[\\/:*?"<>|]/.test(topic) || topic.startsWith('_') || topic.length > 60) {
1031
+ send(400, { ok: false, error: '课程名不合法(1-60 字,不能含特殊字符)' }); return
1032
+ }
1033
+ const dir = path.join(root, 'curriculum', topic)
1034
+ try { await readdir(dir); send(409, { ok: false, error: `课程「${topic}」已存在` }); return } catch { /* 不存在,继续 */ }
1035
+ await mkdir(path.join(dir, 'notes'), { recursive: true })
1036
+ const plan = `---\ntopic: ${topic}\ngoal: ${goal || ''}\n---\n\n` +
1037
+ `# ${topic} · 依赖图\n\n\`\`\`mermaid\nflowchart BT\n classDef done fill:#3E6B4F,color:#FAF7F0\n classDef doing fill:#3D5A80,color:#FAF7F0\n classDef warn fill:#B5432E,color:#FAF7F0\n classDef todo fill:#FAF7F0,color:#6E6A60,stroke:#9A968C,stroke-dasharray:4 3\n\n 根节点["无条件真理"]:::todo --> 目标["目标"]:::todo\n\`\`\`\n\n## 学习顺序\n\n- [ ] 无条件真理\n- [ ] 目标\n`
1038
+ await writeFile(path.join(dir, 'plan.md'), plan, 'utf8')
1039
+ await writeFile(path.join(dir, 'mistakes.md'), '# 错题本\n', 'utf8')
1040
+ send(200, { ok: true })
1041
+ return
1042
+ }
1043
+ // 删除课程:递归删 curriculum/<topic> 与 materials/<topic>(学习会话保留在 DSH 会话列表,可手动归档)
1044
+ if (req.method === 'POST' && url.pathname === '/api/learning-space/topic/delete') {
1045
+ const { topic } = await readBody(req)
1046
+ if (!validTopic(topic)) { send(400, { ok: false, error: '课程名不合法' }); return }
1047
+ const topicDir = path.join(root, 'curriculum', topic)
1048
+ // 只删真实课程目录(必须有 plan.md),防止误删/路径逃逸
1049
+ try { await readFile(path.join(topicDir, 'plan.md'), 'utf8') }
1050
+ catch { send(404, { ok: false, error: `课程「${topic}」不存在` }); return }
1051
+ await rm(topicDir, { recursive: true, force: true })
1052
+ await rm(path.join(root, 'materials', topic), { recursive: true, force: true })
1053
+ send(200, { ok: true })
1054
+ return
1055
+ }
1056
+ // 静态资产:mermaid UMD(文件不可变,缓存一天;缺失 404 JSON 让客户端走降级)
1057
+ if (req.method === 'GET' && url.pathname === '/api/learning-space/assets/mermaid.min.js') {
1058
+ let buf
1059
+ try { buf = await readFile(path.join(PLUGIN_DIR, 'assets', 'mermaid.min.js')) }
1060
+ catch { send(404, { ok: false, error: 'mermaid asset missing' }); return }
1061
+ res.writeHead(200, {
1062
+ 'content-type': 'application/javascript; charset=utf-8',
1063
+ 'cache-control': 'public, max-age=86400',
1064
+ })
1065
+ res.end(buf)
1066
+ return
1067
+ }
1068
+ // 节点教学笔记:notes/<节点名>.md(文件名含非法字符时按清洗/归一化兜底匹配)
1069
+ if (req.method === 'GET' && url.pathname === '/api/learning-space/node-note') {
1070
+ const topic = url.searchParams.get('topic') || ''
1071
+ const node = url.searchParams.get('node') || ''
1072
+ if (!validTopic(topic) || !node || node.length > 200) { send(400, { ok: false, error: 'invalid params' }); return }
1073
+ const notesDir = path.join(root, 'curriculum', topic, 'notes')
1074
+ let files = []
1075
+ try { files = await readdir(notesDir) } catch { send(200, { ok: true, content: '' }); return }
1076
+ const target = matchNoteFile(files, node)
1077
+ if (!target) { send(200, { ok: true, content: '' }); return }
1078
+ let content = ''
1079
+ try { content = await readFile(path.join(notesDir, target), 'utf8') } catch { /* 读失败按无笔记 */ }
1080
+ send(200, { ok: true, content })
1081
+ return
1082
+ }
1083
+ // 导出自包含 HTML 报告:单课程 / 全部
1084
+ if (req.method === 'GET' && url.pathname === '/api/learning-space/export') {
1085
+ const all = url.searchParams.get('all') === '1'
1086
+ const topic = url.searchParams.get('topic') || ''
1087
+ if (!all && !validTopic(topic)) { send(400, { ok: false, error: 'invalid topic' }); return }
1088
+ const topics = await listTopics(root)
1089
+ let targets = topics
1090
+ if (!all) {
1091
+ targets = topics.filter(t => t.name === topic)
1092
+ if (!targets.length) { send(404, { ok: false, error: `课程「${topic}」不存在` }); return }
1093
+ }
1094
+ // 资产读取失败不 500:导出降级为源码文本 + 提示
1095
+ let mermaidJs = null
1096
+ try { mermaidJs = await readFile(path.join(PLUGIN_DIR, 'assets', 'mermaid.min.js'), 'utf8') } catch { /* 降级 */ }
1097
+ const topicsData = await Promise.all(targets.map(t => collectTopicForExport(root, t)))
1098
+ const html = buildReportHtml(topicsData, { all, mermaidJs })
1099
+ const filename = all ? 'learning-report-all.html' : `learning-report-${cleanFilename(topic)}.html`
1100
+ // header 值不允许非 ASCII:ASCII 兜底名 + RFC 5987 filename* 传中文名
1101
+ res.writeHead(200, {
1102
+ 'content-type': 'text/html; charset=utf-8',
1103
+ 'content-disposition': `attachment; filename="${all ? 'learning-report-all.html' : 'learning-report.html'}"; filename*=UTF-8''${encodeURIComponent(filename)}`,
1104
+ })
1105
+ res.end(html)
1106
+ return
1107
+ }
1108
+ send(404, { ok: false, error: 'not found' })
1109
+ } catch (err) {
1110
+ const status = err && typeof err.status === 'number' ? err.status : 500
1111
+ send(status, { ok: false, error: String(err && err.message || err) })
1112
+ }
1113
+ },
1114
+ }))
1115
+
1116
+ // ── 工具:学习方法 ─────────────────────────────
1117
+ ctx.effect(() => ctx.tools.register({
1118
+ name: 'learn_guide',
1119
+ description: '获取学习空间的教学方法论(teach + quiz 两个 skill 的完整内容)。当用户想学习新知识、要求辅导或讲解主题时,先调用它拿到教学方法再开始。教学流程:问目标 → 问资料来源(用户上传在 materials/<主题>/ 或上网检索核实)→ 出题定位水平 → 展示依赖图计划 → 逐节点教学并用 learn_update 记录进度。',
1120
+ parameters: { type: 'object', properties: {} },
1121
+ output: toolOutput,
1122
+ async execute() {
1123
+ const parts = []
1124
+ for (const name of ['skills/teach/SKILL.md', 'skills/quiz/SKILL.md']) {
1125
+ // 工作区自带 skills 优先(可定制),否则用插件内置副本
1126
+ let text = null
1127
+ for (const base of [root, PLUGIN_DIR]) {
1128
+ try { text = await readFile(path.join(base, name), 'utf8'); break } catch { /* 试下一处 */ }
1129
+ }
1130
+ parts.push(text ?? `(未找到 ${name})`)
1131
+ }
1132
+ return { text: parts.join('\n\n---\n\n') }
1133
+ },
1134
+ }))
1135
+
1136
+ // ── 工具:读学习状态 ───────────────────────────
1137
+ ctx.effect(() => ctx.tools.register({
1138
+ name: 'learn_status',
1139
+ description: '读取学习空间的当前状态:各课程进度(节点状态统计)、错题、最近日志。继续学习、复习错题或查看进度时调用。',
1140
+ parameters: { type: 'object', properties: {} },
1141
+ output: toolOutput,
1142
+ async execute() {
1143
+ const [topics, journal] = await Promise.all([listTopics(root), journalLines(root)])
1144
+ const lines = topics.map(t =>
1145
+ `## ${t.name}(目标:${t.goal || '未设置'})\n已确认 ${t.counts.done} / ${t.nodes.length},进行中 ${t.counts.doing},待修复 ${t.counts.warn},错题 ${t.mistakes.length} 条`)
1146
+ return { text: (lines.length ? lines.join('\n') : '还没有课程') + '\n\n最近日志:\n' + journal.join('\n') }
1147
+ },
1148
+ }))
1149
+
1150
+ // ── 工具:写学习数据 ───────────────────────────
1151
+ ctx.effect(() => ctx.tools.register({
1152
+ name: 'learn_update',
1153
+ description: '更新学习空间数据(教学课后沉淀,硬性要求每节课/每节点确认后调用)。action:init_topic=新建课程骨架(参数 topic, goal);save=写文件(参数 file 为 curriculum/ 或 journal/ 下的相对路径,content 为完整文件内容,如 curriculum/<主题>/plan.md、curriculum/<主题>/notes/<节点>.md);record_mistake=追加错题(topic, question, kind 粗心/孤立记忆/概念混淆, explanation);log=追加学习日志(topic, node, summary);study_log=阶段二每节点确认后追加学习记录(topic, node, summary, mastery 已掌握/基本掌握/需复习)。plan.md 必须保持 frontmatter(topic/goal) + mermaid DAG(classDef done/doing/warn/todo + 节点:::类名) + 「## 学习顺序」checkbox([x]已确认 [~]进行中 [!]待修复 [ ]未学)的格式,面板按此解析渲染。',
1154
+ parameters: {
1155
+ type: 'object',
1156
+ properties: {
1157
+ action: { type: 'string', enum: ['init_topic', 'save', 'record_mistake', 'log', 'study_log'] },
1158
+ topic: { type: 'string' },
1159
+ goal: { type: 'string' },
1160
+ file: { type: 'string' },
1161
+ content: { type: 'string' },
1162
+ question: { type: 'string' },
1163
+ kind: { type: 'string', enum: ['粗心', '孤立记忆', '概念混淆'] },
1164
+ explanation: { type: 'string' },
1165
+ node: { type: 'string' },
1166
+ summary: { type: 'string' },
1167
+ mastery: { type: 'string', enum: ['已掌握', '基本掌握', '需复习'] },
1168
+ },
1169
+ required: ['action'],
1170
+ },
1171
+ output: toolOutput,
1172
+ async execute(args) {
1173
+ const today = new Date().toISOString().slice(0, 10)
1174
+ try {
1175
+ if (args.action === 'init_topic') {
1176
+ if (!args.topic) throw new Error('缺少 topic')
1177
+ const dir = path.join(root, 'curriculum', args.topic)
1178
+ await mkdir(path.join(dir, 'notes'), { recursive: true })
1179
+ const plan = `---\ntopic: ${args.topic}\ngoal: ${args.goal || ''}\n---\n\n` +
1180
+ `# ${args.topic} · 依赖图\n\n\`\`\`mermaid\nflowchart BT\n classDef done fill:#3E6B4F,color:#FAF7F0\n classDef doing fill:#3D5A80,color:#FAF7F0\n classDef warn fill:#B5432E,color:#FAF7F0\n classDef todo fill:#FAF7F0,color:#6E6A60,stroke:#9A968C,stroke-dasharray:4 3\n\n 根节点["无条件真理"]:::todo --> 目标["目标"]:::todo\n\`\`\`\n\n## 学习顺序\n\n- [ ] 无条件真理\n- [ ] 目标\n`
1181
+ await writeFile(path.join(dir, 'plan.md'), plan, 'utf8')
1182
+ await writeFile(path.join(dir, 'mistakes.md'), '# 错题本\n', 'utf8')
1183
+ return { text: `已创建课程 ${args.topic}(plan.md + mistakes.md + notes/),教学时把依赖图逐节点写进 plan.md 并维护 checkbox 状态。` }
1184
+ }
1185
+ if (args.action === 'save') {
1186
+ const abs = safeJoin(root, args.file, ['curriculum', 'journal'])
1187
+ await mkdir(path.dirname(abs), { recursive: true })
1188
+ await writeFile(abs, args.content ?? '', 'utf8')
1189
+ return { text: `已写入 ${args.file}` }
1190
+ }
1191
+ if (args.action === 'record_mistake') {
1192
+ if (!args.topic || !args.question) throw new Error('缺少 topic 或 question')
1193
+ const file = path.join(root, 'curriculum', args.topic, 'mistakes.md')
1194
+ let text = '# 错题本\n'
1195
+ try { text = await readFile(file, 'utf8') } catch { /* 新建 */ }
1196
+ text += `\n- **${args.question}** · ${args.kind || '未分类'} · ${today}\n 解析:${args.explanation || ''}\n`
1197
+ await writeFile(file, text, 'utf8')
1198
+ return { text: '错题已记录' }
1199
+ }
1200
+ if (args.action === 'log') {
1201
+ if (!args.topic || !args.summary) throw new Error('缺少 topic 或 summary')
1202
+ const month = today.slice(0, 7)
1203
+ const file = path.join(root, 'journal', `${month}.md`)
1204
+ await mkdir(path.dirname(file), { recursive: true })
1205
+ let text = `# 学习日志(${month})\n`
1206
+ try { text = await readFile(file, 'utf8') } catch { /* 新建 */ }
1207
+ text += `- ${today} · ${args.topic} · ${args.node || '-'} · ${args.summary}\n`
1208
+ await writeFile(file, text, 'utf8')
1209
+ return { text: '日志已追加' }
1210
+ }
1211
+ if (args.action === 'study_log') {
1212
+ if (!args.topic || !args.node || !args.summary) throw new Error('缺少 topic / node / summary')
1213
+ const file = path.join(root, 'curriculum', args.topic, 'study-log.md')
1214
+ let text = '# 学习记录\n'
1215
+ try { text = await readFile(file, 'utf8') } catch { /* 新建 */ }
1216
+ text += `\n## ${today} · ${args.node}\n- 要点:${args.summary}\n- 掌握:${args.mastery || '未标注'}\n`
1217
+ await writeFile(file, text, 'utf8')
1218
+ return { text: '学习记录已追加' }
1219
+ }
1220
+ throw new Error(`未知 action: ${args.action}`)
1221
+ } catch (err) {
1222
+ return { text: `learn_update 失败:${String(err && err.message || err)}` }
1223
+ }
1224
+ },
1225
+ }))
1226
+ }