dsh-learning-assistant 0.0.1 → 0.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.
Files changed (69) hide show
  1. package/README.md +41 -7
  2. package/assets/collect/README.md +55 -0
  3. package/assets/skills/course-inbox-sync.md +182 -0
  4. package/assets/skills/course-material-digest.md +173 -0
  5. package/assets/skills/one-to-one-tutor.md +320 -0
  6. package/assets/tools/pdf/pdf-render.ps1 +30 -0
  7. package/assets/tools/pptx-digest.py +99 -0
  8. package/assets/tools/pptx-map.py +98 -0
  9. package/assets/tools/pptx-media.py +101 -0
  10. package/assets/tools/qq-group-msg.py +258 -0
  11. package/assets/tools/qq-group-sync.py +265 -0
  12. package/docs//345/215/217/344/275/234/345/274/200/345/217/221.md +18 -10
  13. package/lib/client.js +110 -0
  14. package/lib/{index.d.mts → index.d.ts} +3 -1
  15. package/lib/index.js +392 -0
  16. package/package.json +8 -7
  17. package/src/client/settings.tsx +6 -4
  18. package/src/index.ts +36 -11
  19. package/src/practice/learn/api.mjs +393 -0
  20. package/src/practice/learn/cli.mjs +175 -0
  21. package/src/practice/learn/curriculum.mjs +292 -0
  22. package/src/practice/learn/handoff.mjs +73 -0
  23. package/src/practice/learn/jsonschema.mjs +171 -0
  24. package/src/practice/learn/mapping.mjs +90 -0
  25. package/src/practice/learn/progress.mjs +247 -0
  26. package/src/practice/learn/schema/curriculum.schema.json +88 -0
  27. package/src/practice/learn/schema/handoff.schema.json +56 -0
  28. package/src/practice/learn/schema/node-practice-map.schema.json +28 -0
  29. package/src/practice/learn/schema/progress.schema.json +66 -0
  30. package/src/practice/learn/schemas.mjs +53 -0
  31. package/src/practice/learn/store.mjs +247 -0
  32. package/src/practice/public/app.js +883 -0
  33. package/src/practice/public/index.html +19 -0
  34. package/src/practice/public/ink.js +349 -0
  35. package/src/practice/public/learn.css +20 -0
  36. package/src/practice/public/learn.js +329 -0
  37. package/src/practice/public/style.css +326 -0
  38. package/src/practice/public/vendor/katex/contrib/auto-render.min.js +1 -0
  39. package/src/practice/public/vendor/katex/fonts/KaTeX_AMS-Regular.woff2 +0 -0
  40. package/src/practice/public/vendor/katex/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  41. package/src/practice/public/vendor/katex/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  42. package/src/practice/public/vendor/katex/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
  43. package/src/practice/public/vendor/katex/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  44. package/src/practice/public/vendor/katex/fonts/KaTeX_Main-Bold.woff2 +0 -0
  45. package/src/practice/public/vendor/katex/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  46. package/src/practice/public/vendor/katex/fonts/KaTeX_Main-Italic.woff2 +0 -0
  47. package/src/practice/public/vendor/katex/fonts/KaTeX_Main-Regular.woff2 +0 -0
  48. package/src/practice/public/vendor/katex/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  49. package/src/practice/public/vendor/katex/fonts/KaTeX_Math-Italic.woff2 +0 -0
  50. package/src/practice/public/vendor/katex/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  51. package/src/practice/public/vendor/katex/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  52. package/src/practice/public/vendor/katex/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  53. package/src/practice/public/vendor/katex/fonts/KaTeX_Script-Regular.woff2 +0 -0
  54. package/src/practice/public/vendor/katex/fonts/KaTeX_Size1-Regular.woff2 +0 -0
  55. package/src/practice/public/vendor/katex/fonts/KaTeX_Size2-Regular.woff2 +0 -0
  56. package/src/practice/public/vendor/katex/fonts/KaTeX_Size3-Regular.woff2 +0 -0
  57. package/src/practice/public/vendor/katex/fonts/KaTeX_Size4-Regular.woff2 +0 -0
  58. package/src/practice/public/vendor/katex/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  59. package/src/practice/public/vendor/katex/katex.min.css +1 -0
  60. package/src/practice/public/vendor/katex/katex.min.js +1 -0
  61. package/src/practice//346/234/215/345/212/241.mjs +443 -0
  62. package/src/practice//346/240/241/351/252/214/351/242/230/347/233/256.mjs +114 -0
  63. package/src/practice//347/255/211/345/276/205/346/217/220/344/272/244.mjs +100 -0
  64. package/src/practice-service.ts +99 -0
  65. package/src/practice-tool.ts +91 -0
  66. package/src/skills.ts +156 -0
  67. package/lib/client.d.mts +0 -10
  68. package/lib/client.mjs +0 -87
  69. package/lib/index.mjs +0 -29
@@ -0,0 +1,393 @@
1
+ // 学习助手 API(挂在现有练习台服务上,路径前缀 /api/learn/*)。
2
+ //
3
+ // 设计约束(方案 §2、§6-阶段2):
4
+ // - 不新增端口、不新增服务进程:沿用 练习台\服务.mjs 的 http server 与 public\ 静态目录
5
+ // - 不改变既有 /api/library /api/practice /api/records /api/submit /api/inbox 的任何行为
6
+ // - 所有写操作都走 learn/ 下的数据层(schema 校验 + 原子写 + _history 版本备份)
7
+ import path from 'node:path';
8
+ import { selfCheckSchemas } from './schemas.mjs';
9
+ import {
10
+ DATA_ROOT, listSubjects, ensureDataRoot, readJson, exists, WORKSPACE, PRACTICE_DIR, subjectFile, loadPrefs,
11
+ } from './store.mjs';
12
+ import {
13
+ loadCurriculum, loadMeta, loadDraft, acceptCurriculum, proposeRevision, diffCurriculums,
14
+ describeDiff, validateCurriculum, archiveCurriculum, isActive,
15
+ } from './curriculum.mjs';
16
+ import { loadProgress, summarize, availableNodes, lockReason, applyVerdict, STATUSES } from './progress.mjs';
17
+ import { loadMapping, attemptsForNode, linksForNode, recordsFor, link, unlink } from './mapping.mjs';
18
+ import { listHandoffs, latestHandoff, saveHandoff } from './handoff.mjs';
19
+
20
+ const jsonBody = (body) => JSON.stringify(body);
21
+
22
+ function ok(res, code, obj) {
23
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
24
+ res.end(jsonBody(obj));
25
+ }
26
+
27
+ function fail(res, e, code = 400) {
28
+ const status = e && e.code === 'SCHEMA_INVALID' ? 400 : 400;
29
+ ok(res, e && e.status ? e.status : status, {
30
+ error: String((e && e.message) || e),
31
+ code: (e && e.code) || 'ERROR',
32
+ ...(e && e.errors ? { details: e.errors } : {}),
33
+ });
34
+ }
35
+
36
+ async function readJsonBody(req, limit = 2 * 1024 * 1024) {
37
+ const chunks = [];
38
+ let n = 0;
39
+ for await (const c of req) {
40
+ n += c.length;
41
+ if (n > limit) throw new Error('body too large');
42
+ chunks.push(c);
43
+ }
44
+ const t = Buffer.concat(chunks).toString('utf8');
45
+ if (!t.trim()) return {};
46
+ return JSON.parse(t);
47
+ }
48
+
49
+ /* ---------- 只读:课程页所需的一切 ---------- */
50
+
51
+ // 一科的完整视图:active 计划 + 待确认草案 + 进度 + 映射 + 汇总
52
+ async function subjectView(subjectId) {
53
+ const id = subjectId;
54
+ const [meta, curriculum, draft, progress, mapping] = await Promise.all([
55
+ loadMeta(id), loadCurriculum(id), loadDraft(id), loadProgress(id), loadMapping(id),
56
+ ]);
57
+ if (!curriculum) return null;
58
+ const summary = summarize(curriculum, progress);
59
+ const st = (n) => (progress && progress.nodes && progress.nodes[n] ? progress.nodes[n].status : 'not_started');
60
+ const nodes = (curriculum.nodes || []).map((n) => ({
61
+ id: n.id, title: n.title, objective: n.objective, kind: n.kind,
62
+ estimated_minutes: n.estimated_minutes,
63
+ prerequisites: n.prerequisites,
64
+ source_refs: n.source_refs,
65
+ quiz_refs: n.quiz_refs,
66
+ status: st(n.id),
67
+ last_score: progress && progress.nodes[n.id] ? progress.nodes[n.id].last_score : null,
68
+ last_studied_at: progress && progress.nodes[n.id] ? progress.nodes[n.id].last_studied_at : null,
69
+ attempts: progress && progress.nodes[n.id] ? progress.nodes[n.id].attempts : 0,
70
+ misconception_refs: progress && progress.nodes[n.id] ? progress.nodes[n.id].misconception_refs : [],
71
+ mastered_at: progress && progress.nodes[n.id] ? progress.nodes[n.id].mastered_at : null,
72
+ lock_reason: lockReason(curriculum, progress, n.id),
73
+ linked_practices: linksForNode(mapping, n.id).map((l) => ({ course: l.course, practice_id: l.practice_id })),
74
+ }));
75
+ return {
76
+ subject_id: id,
77
+ meta,
78
+ plan: {
79
+ title: curriculum.title, goal: curriculum.goal, status: curriculum.status,
80
+ active: isActive(curriculum), revision: curriculum.revision,
81
+ confirmed_at: curriculum.confirmed_at, confirmed_by: curriculum.confirmed_by,
82
+ created_at: curriculum.created_at, updated_at: curriculum.updated_at,
83
+ based_on: curriculum.based_on, change_note: curriculum.change_note,
84
+ materials: curriculum.materials, missing: curriculum.missing,
85
+ open_questions: curriculum.open_questions, fixture: !!curriculum.fixture,
86
+ },
87
+ summary,
88
+ nodes,
89
+ detached: (progress && progress._detached) || {},
90
+ draft: draft ? {
91
+ revision: draft.revision, status: draft.status, based_on: draft.based_on,
92
+ change_note: draft.change_note, proposed_by: draft.proposed_by || null,
93
+ node_count: (draft.nodes || []).length,
94
+ diff: describeDiff(diffCurriculums(curriculum, draft)),
95
+ nodes: (draft.nodes || []).map((n) => ({ id: n.id, title: n.title, kind: n.kind, prerequisites: n.prerequisites })),
96
+ } : null,
97
+ mapping,
98
+ data_root: DATA_ROOT,
99
+ };
100
+ }
101
+
102
+ /* ---------- 路由 ---------- */
103
+
104
+ /**
105
+ * 处理 /api/learn/* 。返回 true 表示已处理。
106
+ * 由 服务.mjs 在既有路由之后调用,因此不可能影响既有接口。
107
+ */
108
+ export async function handleLearnApi(req, res, u) {
109
+ const p = u.pathname;
110
+ if (!p.startsWith('/api/learn')) return false;
111
+ const q = u.searchParams;
112
+ const sub = p.slice('/api/learn'.length) || '/';
113
+
114
+ try {
115
+ /* --- 健康自检:schema 可解析 + 数据根可写 --- */
116
+ if (sub === '/health' && req.method === 'GET') {
117
+ const schemas = await selfCheckSchemas();
118
+ await ensureDataRoot();
119
+ return ok(res, 200, {
120
+ ok: schemas.every((s) => s.ok),
121
+ data_root: DATA_ROOT,
122
+ workspace: WORKSPACE,
123
+ schemas,
124
+ statuses: STATUSES,
125
+ }), true;
126
+ }
127
+
128
+ /* --- 打开来源材料(只读;路径必须落在白名单根内) --- */
129
+ if (sub === '/material' && req.method === 'GET') {
130
+ const rel = String(q.get('path') || '').trim();
131
+ const location = String(q.get('location') || '').trim();
132
+ const limit = Number(q.get('limit') || 0) || 200000;
133
+ const { resolveSourceRef, readText } = await import('./store.mjs');
134
+ const abs = resolveSourceRef(rel); // 越界/绝对路径在这里就会抛
135
+ if (!(await exists(abs))) {
136
+ return ok(res, 200, { path: rel, location, missing: true, text: null, error: '材料文件不存在(缺失,不编造内容)' }), true;
137
+ }
138
+ const text = await readText(abs);
139
+ const head = text.length > limit;
140
+ if (q.get('raw') === '1') {
141
+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
142
+ return res.end(text), true;
143
+ }
144
+ return ok(res, 200, {
145
+ path: rel, location, missing: false,
146
+ truncated: head, chars: text.length,
147
+ text: head ? text.slice(0, limit) : text,
148
+ }), true;
149
+ }
150
+
151
+ /* --- 科目列表 --- */
152
+ if (sub === '/subjects' && req.method === 'GET') {
153
+ const all = await listSubjects();
154
+ const items = [];
155
+ for (const s of all) {
156
+ if (!s.curriculum) continue;
157
+ items.push({
158
+ subject_id: s.subject_id,
159
+ title: s.curriculum.title,
160
+ goal: s.curriculum.goal,
161
+ status: s.curriculum.status,
162
+ active: isActive(s.curriculum),
163
+ revision: s.curriculum.revision,
164
+ has_draft: await exists(subjectFile(s.subject_id, 'curriculum.draft.json')),
165
+ summary: summarize(s.curriculum, s.progress),
166
+ fixture: !!s.curriculum.fixture,
167
+ });
168
+ }
169
+ return ok(res, 200, { items, data_root: DATA_ROOT }), true;
170
+ }
171
+
172
+ /* --- 单科视图 --- */
173
+ if (sub === '/subject' && req.method === 'GET') {
174
+ const id = String(q.get('subject') || '').trim();
175
+ if (!id) return ok(res, 400, { error: '缺少 subject 参数' }), true;
176
+ const v = await subjectView(id);
177
+ if (!v) return ok(res, 404, { error: `科目 ${id} 还没有课程计划` }), true;
178
+ return ok(res, 200, v), true;
179
+ }
180
+
181
+ /* --- 某节点可关联的题库练习(供人/导师建立映射,不自动绑定) --- */
182
+ if (sub === '/practices' && req.method === 'GET') {
183
+ const course = String(q.get('course') || '').trim();
184
+ if (!course) return ok(res, 400, { error: '缺少 course 参数' }), true;
185
+ const bank = path.join(PRACTICE_DIR, '_题库');
186
+ const fsp = await import('node:fs/promises');
187
+ let items = [];
188
+ try {
189
+ for (const f of await fsp.readdir(path.join(bank, course))) {
190
+ if (!f.endsWith('.json')) continue;
191
+ const pr = await readJson(path.join(bank, course, f), null);
192
+ if (!pr) continue;
193
+ items.push({ practice_id: f.replace(/\.json$/, ''), title: pr.title, topic: pr.topic, source: pr.source });
194
+ }
195
+ } catch { items = []; }
196
+ return ok(res, 200, { course, items }), true;
197
+ }
198
+
199
+ /* --- 答卷(只读,来自现有 _记录) --- */
200
+ if (sub === '/attempts' && req.method === 'GET') {
201
+ const id = String(q.get('subject') || '').trim();
202
+ const node = String(q.get('node') || '').trim();
203
+ if (!id || !node) return ok(res, 400, { error: '需要 subject 与 node' }), true;
204
+ return ok(res, 200, { items: await attemptsForNode(id, node) }), true;
205
+ }
206
+
207
+ /* --- 交接记录 --- */
208
+ if (sub === '/handoffs' && req.method === 'GET') {
209
+ const id = String(q.get('subject') || '').trim();
210
+ const node = String(q.get('node') || '').trim();
211
+ if (!id) return ok(res, 400, { error: '缺少 subject' }), true;
212
+ if (node) {
213
+ const h = await latestHandoff(id, node);
214
+ return ok(res, 200, { items: h ? [h] : [] }), true;
215
+ }
216
+ return ok(res, 200, { items: await listHandoffs(id) }), true;
217
+ }
218
+
219
+ /* --- 偏好(全局极短偏好,读写都很小) --- */
220
+ if (sub === '/prefs' && req.method === 'GET') return ok(res, 200, await loadPrefs()), true;
221
+
222
+ /* --- 重规划草案:只提议,不生效 --- */
223
+ if (sub === '/propose' && req.method === 'POST') {
224
+ const b = await readJsonBody(req);
225
+ const id = String(b.subject || '').trim();
226
+ if (!id) return ok(res, 400, { error: '缺少 subject' }), true;
227
+ const draft = await proposeRevision(id, b.changes || {}, { reason: b.reason || '', by: b.by || 'model' });
228
+ const base = await loadCurriculum(id);
229
+ return ok(res, 200, {
230
+ ok: true, applied: false,
231
+ revision: draft.revision,
232
+ note: '这是待确认草案,已写入 curriculum.draft.json;未确认前不影响生效计划。',
233
+ diff: describeDiff(diffCurriculums(base, draft)),
234
+ }), true;
235
+ }
236
+
237
+ /* --- 确认草案 → 生效 --- */
238
+ if (sub === '/accept' && req.method === 'POST') {
239
+ const b = await readJsonBody(req);
240
+ const id = String(b.subject || '').trim();
241
+ if (!id) return ok(res, 400, { error: '缺少 subject' }), true;
242
+ const { writeJsonVersioned } = await import('./store.mjs');
243
+ const fsp = await import('node:fs/promises');
244
+ const target = subjectFile(id, 'curriculum.json');
245
+ const onDisk = await readJson(target, null);
246
+ const draftFile = await loadDraft(id);
247
+ // 两种待确认形态:
248
+ // 1) 已有生效计划 + curriculum.draft.json(重规划草案)
249
+ // 2) 首份计划:curriculum.json 本身就是未确认草案(status=draft)
250
+ const draft = draftFile || (onDisk && onDisk.status === 'draft' ? onDisk : null);
251
+ if (!draft) {
252
+ // 已生效的计划被重复确认:给出明确的 409,而不是含糊的 404
253
+ if (onDisk && isActive(onDisk)) {
254
+ return ok(res, 409, {
255
+ error: `科目 ${id} revision ${onDisk.revision} 已是生效计划,无需重复确认`,
256
+ code: 'ALREADY_ACTIVE',
257
+ }), true;
258
+ }
259
+ return ok(res, 404, { error: `科目 ${id} 没有待确认草案(计划已生效或尚未建立)` }), true;
260
+ }
261
+ if (b.expected_revision != null && Number(b.expected_revision) !== draft.revision) {
262
+ return ok(res, 409, {
263
+ error: `草案已变化:页面看到 revision ${b.expected_revision},当前 ${draft.revision}。请刷新后重试。`,
264
+ code: 'REVISION_STALE', current: draft.revision,
265
+ }), true;
266
+ }
267
+ // 草案文件顶替 curriculum.json 后再走标准 accept(旧版本先进 _history)
268
+ if (draftFile) {
269
+ if (onDisk) await writeJsonVersioned(subjectFile(id, `curriculum.r${onDisk.revision}.json`), onDisk, 'curriculum-archive');
270
+ await writeJsonVersioned(target, { ...draft, status: 'draft', confirmed_at: null }, 'curriculum');
271
+ }
272
+ const active = await acceptCurriculum(id, { by: b.by || 'user', expectedRevision: null });
273
+ if (draftFile) { try { await fsp.unlink(subjectFile(id, 'curriculum.draft.json')); } catch { /* 无草案也无妨 */ } }
274
+ return ok(res, 200, { ok: true, applied: true, revision: active.revision, status: active.status }), true;
275
+ }
276
+
277
+ /* --- 建立「课程节点 ↔ 练习」映射(显式,不自动绑定) --- */
278
+ if (sub === '/link' && req.method === 'POST') {
279
+ const b = await readJsonBody(req);
280
+ const id = String(b.subject || '').trim();
281
+ const node = String(b.node || '').trim();
282
+ const practiceId = String(b.practice_id || '').trim();
283
+ const course = String(b.course || '').trim();
284
+ if (!id || !node || !practiceId || !course) {
285
+ return ok(res, 400, { error: '需要 subject / node / course / practice_id' }), true;
286
+ }
287
+ const m = await link(id, { node_id: node, practice_id: practiceId, course, note: b.note || '' });
288
+ return ok(res, 200, { ok: true, links: m.links.length }), true;
289
+ }
290
+
291
+ if (sub === '/unlink' && req.method === 'POST') {
292
+ const b = await readJsonBody(req);
293
+ const m = await unlink(String(b.subject || '').trim(), {
294
+ node_id: String(b.node || '').trim(),
295
+ practice_id: String(b.practice_id || '').trim(),
296
+ course: String(b.course || '').trim(),
297
+ });
298
+ return ok(res, 200, { ok: true, links: m.links.length }), true;
299
+ }
300
+
301
+ /* --- 归档 --- */
302
+ if (sub === '/archive' && req.method === 'POST') {
303
+ const b = await readJsonBody(req);
304
+ const id = String(b.subject || '').trim();
305
+ if (!id) return ok(res, 400, { error: '缺少 subject' }), true;
306
+ const cur = await archiveCurriculum(id, { reason: b.reason || '' });
307
+ return ok(res, 200, { ok: true, revision: cur.revision, status: cur.status }), true;
308
+ }
309
+
310
+ /* --- 导师判定(唯一能写 mastered 的入口) --- */
311
+ if (sub === '/verdict' && req.method === 'POST') {
312
+ const b = await readJsonBody(req);
313
+ const id = String(b.subject || '').trim();
314
+ const node = String(b.node || '').trim();
315
+ if (!id || !node) return ok(res, 400, { error: '需要 subject 与 node' }), true;
316
+ const cur = await loadCurriculum(id);
317
+ const prog = await applyVerdict(id, node, {
318
+ verdict: b.verdict,
319
+ evidence: b.evidence || [],
320
+ by: b.by || 'tutor',
321
+ reason: b.reason || '',
322
+ score: b.score == null ? null : b.score,
323
+ overridePrereq: b.override_prereq || null,
324
+ curriculum: cur,
325
+ });
326
+ return ok(res, 200, { ok: true, current_node_id: prog.current_node_id, node: prog.nodes[node] }), true;
327
+ }
328
+
329
+ /* --- 记录作答(不构成掌握判定;网页提交后由导师流程调用) --- */
330
+ if (sub === '/record' && req.method === 'POST') {
331
+ const b = await readJsonBody(req);
332
+ const id = String(b.subject || '').trim();
333
+ const node = String(b.node || '').trim();
334
+ if (!id || !node) return ok(res, 400, { error: '需要 subject 与 node' }), true;
335
+ const { recordScore } = await import('./progress.mjs');
336
+ const prog = await recordScore(id, node, {
337
+ score: b.score == null ? null : b.score,
338
+ attemptRef: b.attempt_ref || null,
339
+ misconceptionRefs: b.misconceptions || [],
340
+ });
341
+ return ok(res, 200, { ok: true, node: prog.nodes[node] }), true;
342
+ }
343
+
344
+ /* --- 保存交接(阶段 4) --- */
345
+ if (sub === '/handoff' && req.method === 'POST') {
346
+ const b = await readJsonBody(req);
347
+ const id = String(b.subject || '').trim();
348
+ if (!id) return ok(res, 400, { error: '缺少 subject' }), true;
349
+ const h = await saveHandoff(id, b);
350
+ return ok(res, 200, { ok: true, handoff: h }), true;
351
+ }
352
+
353
+ /* --- 建草案(供导师流程调用;不自动建课) --- */
354
+ if (sub === '/draft' && req.method === 'POST') {
355
+ const b = await readJsonBody(req);
356
+ const id = String(b.subject || '').trim();
357
+ if (!id) return ok(res, 400, { error: '缺少 subject' }), true;
358
+ const { saveDraft } = await import('./curriculum.mjs');
359
+ const cur = await loadCurriculum(id);
360
+ let saved;
361
+ if (cur) {
362
+ // 已有计划(含生效计划):一律生成待确认 revision,不覆盖
363
+ saved = await proposeRevision(id, { ...b.curriculum, nodes: b.curriculum && b.curriculum.nodes }, { reason: b.reason || '', by: b.by || 'model' });
364
+ } else {
365
+ saved = await saveDraft(id, { ...(b.curriculum || {}), change_note: b.reason || '' });
366
+ }
367
+ return ok(res, 200, { ok: true, applied: false, revision: saved.revision, status: saved.status }), true;
368
+ }
369
+
370
+ /* --- 校验一份 curriculum(不落盘,供自检/测试) --- */
371
+ if (sub === '/validate' && req.method === 'POST') {
372
+ const b = await readJsonBody(req);
373
+ await validateCurriculum(b.curriculum, { strictSources: b.strict_sources !== false });
374
+ return ok(res, 200, { ok: true }), true;
375
+ }
376
+
377
+ /* --- 差异预览(不落盘) --- */
378
+ if (sub === '/diff' && req.method === 'GET') {
379
+ const id = String(q.get('subject') || '').trim();
380
+ const base = await loadCurriculum(id);
381
+ const draft = await loadDraft(id);
382
+ if (!base || !draft) return ok(res, 404, { error: '缺少生效计划或草案' }), true;
383
+ return ok(res, 200, { diff: diffCurriculums(base, draft), text: describeDiff(diffCurriculums(base, draft)) }), true;
384
+ }
385
+
386
+ return ok(res, 404, { error: `未知的 learn 接口:${sub}` }), true;
387
+ } catch (e) {
388
+ fail(res, e);
389
+ return true;
390
+ }
391
+ }
392
+
393
+ export { recordsFor };
@@ -0,0 +1,175 @@
1
+ // 学习助手命令行:给导师流程(skill)用的唯一入口。
2
+ //
3
+ // 为什么要 CLI:导师流程需要「建草案 / 记作答 / 判掌握 / 存交接」,
4
+ // 直接手写 JSON 容易绕过 schema 与证据校验。这里把它们收成子命令,输出 JSON 供人看。
5
+ //
6
+ // 用法(在 练习台 目录下):
7
+ // node learn/cli.mjs subjects
8
+ // node learn/cli.mjs view <科目>
9
+ // node learn/cli.mjs draft <科目> <草案.json> # 新建/覆盖草案(已有生效计划时自动转为待确认 revision)
10
+ // node learn/cli.mjs accept <科目> # 用户确认后生效
11
+ // node learn/cli.mjs record <科目> <节点> <答卷ref> [得分0-1]
12
+ // node learn/cli.mjs verdict <科目> <节点> <mastered|needs_review|in_progress> <答卷ref...> [--reason 文本]
13
+ // node learn/cli.mjs link <科目> <节点> <课程> <练习id>
14
+ // node learn/cli.mjs handoff <科目> <节点> <交接.json>
15
+ // node learn/cli.mjs material <相对路径> [--location 文本]
16
+ // node learn/cli.mjs check # schema 自检
17
+ import fsp from 'node:fs/promises';
18
+ import path from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+
21
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
22
+ process.chdir(path.dirname(HERE));
23
+
24
+ const C = await import('./curriculum.mjs');
25
+ const P = await import('./progress.mjs');
26
+ const M = await import('./mapping.mjs');
27
+ const H = await import('./handoff.mjs');
28
+ const S = await import('./store.mjs');
29
+ const SC = await import('./schemas.mjs');
30
+
31
+ const argv = process.argv.slice(2);
32
+ const cmd = argv[0];
33
+ const flag = (name) => {
34
+ const i = argv.indexOf('--' + name);
35
+ return i >= 0 ? (argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : true) : null;
36
+ };
37
+ const pos = argv.slice(1).filter((a, i, arr) => !a.startsWith('--') && !(i > 0 && arr[i - 1].startsWith('--')));
38
+ const out = (o) => console.log(typeof o === 'string' ? o : JSON.stringify(o, null, 2));
39
+ const readJsonFile = async (f) => JSON.parse(await fsp.readFile(path.resolve(f), 'utf8'));
40
+
41
+ try {
42
+ switch (cmd) {
43
+ case 'check': {
44
+ const r = await SC.selfCheckSchemas();
45
+ await S.ensureDataRoot();
46
+ out({ data_root: S.DATA_ROOT, schemas: r });
47
+ process.exit(r.every((x) => x.ok) ? 0 : 1);
48
+ break;
49
+ }
50
+
51
+ case 'subjects': {
52
+ const all = await S.listSubjects();
53
+ out(all.filter((s) => s.curriculum).map((s) => ({
54
+ subject_id: s.subject_id, title: s.curriculum.title, status: s.curriculum.status,
55
+ active: C.isActive(s.curriculum), revision: s.curriculum.revision,
56
+ summary: P.summarize(s.curriculum, s.progress),
57
+ })));
58
+ break;
59
+ }
60
+
61
+ case 'view': {
62
+ const id = pos[0];
63
+ const [cur, prog, meta, draft] = await Promise.all([
64
+ C.loadCurriculum(id), P.loadProgress(id), C.loadMeta(id), C.loadDraft(id),
65
+ ]);
66
+ if (!cur) throw new Error(`科目 ${id} 没有课程计划`);
67
+ out({
68
+ meta, plan: { title: cur.title, goal: cur.goal, status: cur.status, active: C.isActive(cur), revision: cur.revision },
69
+ summary: P.summarize(cur, prog),
70
+ nodes: cur.nodes.map((n) => ({
71
+ id: n.id, title: n.title, kind: n.kind, estimated_minutes: n.estimated_minutes,
72
+ prerequisites: n.prerequisites, status: (prog && prog.nodes[n.id] ? prog.nodes[n.id].status : 'not_started'),
73
+ lock_reason: P.lockReason(cur, prog, n.id),
74
+ source_refs: n.source_refs,
75
+ })),
76
+ draft: draft ? { revision: draft.revision, based_on: draft.based_on, change_note: draft.change_note, diff: C.describeDiff(C.diffCurriculums(cur, draft)) } : null,
77
+ });
78
+ break;
79
+ }
80
+
81
+ case 'draft': {
82
+ const [id, file] = pos;
83
+ const body = await readJsonFile(file);
84
+ const cur = await C.loadCurriculum(id);
85
+ let saved;
86
+ if (cur) {
87
+ saved = await C.proposeRevision(id, body.nodes ? body : { ...body, nodes: (body.nodes || cur.nodes) }, { reason: body.change_note || '', by: 'model' });
88
+ const diff = C.diffCurriculums(cur, saved);
89
+ out({ applied: false, revision: saved.revision, note: '待确认草案,已写入 curriculum.draft.json', diff: C.describeDiff(diff) });
90
+ } else {
91
+ saved = await C.saveDraft(id, body);
92
+ out({ applied: false, revision: saved.revision, note: '首份草案,等待用户确认(确认后才生效)' });
93
+ }
94
+ break;
95
+ }
96
+
97
+ case 'accept': {
98
+ const id = pos[0];
99
+ const target = S.subjectFile(id, 'curriculum.json');
100
+ const onDisk = await S.readJson(target, null);
101
+ const draftFile = await C.loadDraft(id);
102
+ // 两种待确认形态:重规划草案(draft 文件)或首份草案(curriculum.json 本身 status=draft)
103
+ const draft = draftFile || (onDisk && onDisk.status === 'draft' ? onDisk : null);
104
+ if (!draft) throw new Error(`科目 ${id} 没有待确认草案(计划已生效或尚未建立)`);
105
+ if (draftFile) {
106
+ if (onDisk) await S.writeJsonVersioned(S.subjectFile(id, `curriculum.r${onDisk.revision}.json`), onDisk, 'curriculum-archive');
107
+ await S.writeJsonVersioned(target, { ...draft, status: 'draft', confirmed_at: null }, 'curriculum');
108
+ }
109
+ const active = await C.acceptCurriculum(id, { by: 'user' });
110
+ if (draftFile) { try { await fsp.unlink(S.subjectFile(id, 'curriculum.draft.json')); } catch { /* 无草案 */ } }
111
+ out({ ok: true, applied: true, revision: active.revision, status: active.status, confirmed_at: active.confirmed_at });
112
+ break;
113
+ }
114
+
115
+ case 'record': {
116
+ const [id, node, ref, score] = pos;
117
+ const prog = await P.recordScore(id, node, { score: score == null ? null : Number(score), attemptRef: ref || null });
118
+ out({ ok: true, node: prog.nodes[node], note: '只记成绩与尝试次数,不构成掌握判定' });
119
+ break;
120
+ }
121
+
122
+ case 'verdict': {
123
+ const [id, node, verdict, ...refs] = pos;
124
+ const cur = await C.loadCurriculum(id);
125
+ const prog = await P.applyVerdict(id, node, {
126
+ verdict, evidence: refs, by: 'tutor',
127
+ reason: typeof flag('reason') === 'string' ? flag('reason') : '',
128
+ overridePrereq: typeof flag('override') === 'string' ? flag('override') : null,
129
+ curriculum: cur,
130
+ });
131
+ out({ ok: true, node: prog.nodes[node], current_node_id: prog.current_node_id });
132
+ break;
133
+ }
134
+
135
+ case 'link': {
136
+ const [id, node, course, practiceId] = pos;
137
+ const m = await M.link(id, { node_id: node, practice_id: practiceId, course });
138
+ out({ ok: true, links: m.links.length });
139
+ break;
140
+ }
141
+
142
+ case 'handoff': {
143
+ const [id, , file] = pos;
144
+ const body = await readJsonFile(file);
145
+ const h = await H.saveHandoff(id, body);
146
+ out({ ok: true, handoff: h });
147
+ break;
148
+ }
149
+
150
+ case 'material': {
151
+ const rel = pos[0];
152
+ const abs = S.resolveSourceRef(rel);
153
+ if (!(await S.exists(abs))) {
154
+ out({ path: rel, missing: true, note: '材料缺失:不编造内容,请在计划里标注待补' });
155
+ break;
156
+ }
157
+ const text = await S.readText(abs);
158
+ const limit = Number(flag('limit') || 4000);
159
+ out({ path: rel, location: flag('location') || '', missing: false, chars: text.length, truncated: text.length > limit, text: text.slice(0, limit) });
160
+ break;
161
+ }
162
+
163
+ default:
164
+ console.log(`用法见文件头部注释。可用子命令:
165
+ check | subjects | view <科目> | draft <科目> <草案.json> | accept <科目>
166
+ record <科目> <节点> <答卷ref> [得分] | verdict <科目> <节点> <判定> <答卷ref...> [--reason 文本] [--override 理由]
167
+ link <科目> <节点> <课程> <练习id> | handoff <科目> <节点> <交接.json>
168
+ material <相对路径> [--location 文本]`);
169
+ process.exit(cmd ? 1 : 0);
170
+ }
171
+ } catch (e) {
172
+ console.error(`[失败] ${e.code ? e.code + ': ' : ''}${e.message}`);
173
+ if (e.errors) for (const x of e.errors) console.error(' - ' + x);
174
+ process.exit(1);
175
+ }