@ggboy123/dsh-paper-reader 1.7.0 → 1.8.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/dist/host.js CHANGED
@@ -1,12 +1,13 @@
1
1
  // host.ts — webServer 路由:阅读器页面 + PDF 文件 + 转录数据接口 + 选中即问。
2
2
  // 壳层代码:只做 HTTP ↔ 纯函数核心(library/transcribe)的转接。
3
- import { createReadStream, existsSync, readFileSync, realpathSync } from 'node:fs';
3
+ import { createReadStream, existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
4
4
  import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
5
5
  import { randomUUID } from 'node:crypto';
6
- import { basename, join, resolve } from 'node:path';
7
- import { listPapers, listTopics, resolveDataDir, resolvePaper, resolveUploadTopic, validateEntryBoundary, validateEntryName, } from "./library.js";
8
- import { ManageError, assertInside, clearTopic, planTopicClear, deletePaper, deleteTopic, isManageError, planPaperDelete, planTopicDelete, realDataDir, renamePaper, renameTopic, resolveTopicDir, validateName, } from "./library-manage.js";
6
+ import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
7
+ import { caseVariantCollisions, existingEntryName, flatArtifactNames, isPaperDir, listPapers, listTopicTree, listTopics, paperDirAncestor, paperPdfPath, paperRefFor, resolveDataDir, resolvePaper, resolveUploadTopic, validateEntryBoundary, validateEntryName, } from "./library.js";
8
+ import { ManageError, assertInside, clearTopic, planTopicClear, deletePaper, deleteTopic, isManageError, planPaperDelete, planTopicDelete, realDataDir, renamePaper, renameTopic, resolveTopicDir, validateTopicPath, } from "./library-manage.js";
9
9
  import { readFormulaIndex, readTextBlockIndex } from "./formulas.js";
10
+ import { buildScopeContext } from "./scope.js";
10
11
  import { MAX_CHUNKS, MAX_LATEX_CHARS, MAX_TEXT_CHARS, MAX_TOTAL_CHARS, SelectionTranslateError, assembleSource, formulaStatusOf, translateSelection, } from "./translate-selection.js";
11
12
  import { MineruError, sanitizeDetail } from "./mineru.js";
12
13
  import { readTranscript, transcribePaper, ScannedPdfError, ShortTextError } from "./transcribe.js";
@@ -15,9 +16,13 @@ import { clearTranslateConfig, maskApiKey, readTranslateConfig, resolveTranslate
15
16
  import { clearTypesafeConfig, readTypesafeConfig, resolveTypesafeConfig, testTypesafeEndpoint, writeTypesafeConfig, } from "./typesafe-config.js";
16
17
  import { clearEmbedConfig, maskApiKey as maskEmbedApiKey, readEmbedConfig, resolveEmbedConfig, testEmbedEndpoint, writeEmbedConfig, } from "./embed-config.js";
17
18
  import { clearMineruConfig, mergeMineruBody, precheckMineruConfig, resolveMineruConfig, testMineruCloud, testMineruLocal, writeMineruConfig, } from "./mineru-config.js";
19
+ // preset 已随 dsh 0.2.x 迁移到 cordis.patch.yml 声明式注册(main a675b9f):
20
+ // host 不再安装 preset,会话创建也不默认套用任何 preset。
21
+ import { MigrationAborted, MigrationError, formatMigrationReport, lastMigrationLog, migrationLogDir, planMigration, rollbackMigration, runMigrationAsync, } from "./migrate.js";
18
22
  import { noteOrigin } from "./origin.js";
19
23
  import { deleteNote, isNoteError, readNotes, upsertNote } from "./notes.js";
20
24
  import { isOpenCodeEndpoint, openCodeSessionId } from "./opencode.js";
25
+ import { clearThemeConfig, readThemeConfig, themePayload, validateThemePatch, writeThemeConfig, } from "./theme-config.js";
21
26
  function json(res, status, body) {
22
27
  const buf = Buffer.from(JSON.stringify(body), 'utf8');
23
28
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': buf.length });
@@ -144,6 +149,15 @@ export function registerRoutes(ctx, config) {
144
149
  };
145
150
  /** 专题目录 → dsh 工作区(幂等,进程内缓存)。会话挂到工作区后原生 composer 才可用。 */
146
151
  const workspaceCache = new Map();
152
+ /** 删/改/清空一个专题(可能是路径)后,把**整棵子树**的工作区缓存键清掉(方案 §B2.4)。 */
153
+ const dropWorkspaceCache = (topicPath) => {
154
+ const base = join(dataDir, ...topicPath.split('/').filter(Boolean));
155
+ const prefix = base.endsWith(sep) ? base : base + sep;
156
+ for (const k of [...workspaceCache.keys()]) {
157
+ if (k === base || k.startsWith(prefix))
158
+ workspaceCache.delete(k);
159
+ }
160
+ };
147
161
  const ensureTopicWorkspace = async (topic) => {
148
162
  const dir = join(dataDir, topic);
149
163
  const cached = workspaceCache.get(dir);
@@ -265,6 +279,52 @@ export function registerRoutes(ctx, config) {
265
279
  inflight.delete(key);
266
280
  }
267
281
  };
282
+ /** 正在转录的文献(`topic\u0000name`):/migrate 的 busy 门用(评审 E3)。 */
283
+ const activeTranscribes = new Set();
284
+ /**
285
+ * 该范围(或其子树)是否有写操作在途。读路径**不阻塞**(方案 §B3.2:fail-soft),
286
+ * 只在提示里如实说「正在被修改,本次只给了 N 篇」。
287
+ *
288
+ * 修 G3(评审 G 次级):inflight 的 key 是 `paper\u0000<topic>\u0000<name>` /
289
+ * `topic\u0000<topicPath>`,旧实现拿 `scopePath`(`topic/name`,斜杠分隔)做 `k.includes(...)`
290
+ * ⇒ paper 范围**永远匹配不上**,busy 提示是死代码。现在先把 key 解析成「被操作的路径」再做
291
+ * 双向前缀判定:范围包含在途操作(自己的子树正在被改)或被在途操作包含(祖先专题正在被
292
+ * 清空/改名/迁移)。`migrate` 在途同样视为「正在被修改」(它确实在动整个库的文件)。
293
+ */
294
+ const scopeBusy = (scopePath) => {
295
+ for (const k of inflight) {
296
+ const parts = k.split('\u0000');
297
+ let subject = null;
298
+ if (parts[0] === 'migrate')
299
+ return true;
300
+ if (parts[0] === 'topic' && parts.length === 2)
301
+ subject = parts[1] ?? null;
302
+ else if (parts[0] === 'paper' && parts.length === 3)
303
+ subject = `${parts[1] ?? ''}/${parts[2] ?? ''}`;
304
+ if (!subject)
305
+ continue;
306
+ if (subject === scopePath || subject.startsWith(scopePath + '/') || scopePath.startsWith(subject + '/'))
307
+ return true;
308
+ }
309
+ return false;
310
+ };
311
+ /** 全库在飞译文(评审 E3 的 busy 门):迁移会搬走这些论文的产物,必须等它们完成。 */
312
+ const translationBusyPapers = () => {
313
+ const out = [];
314
+ for (const p of listPapers(dataDir)) {
315
+ try {
316
+ if (zhStatus(paperRefFor(dataDir, p.topic, p.name)).busy)
317
+ out.push(`${p.topic}/${p.name}`);
318
+ }
319
+ catch { /* 读不到的单篇不阻塞迁移(迁移自己会如实报 unreadable/冲突) */ }
320
+ }
321
+ return out;
322
+ };
323
+ /** 清空单元树 → 逐篇清单(评审 D:占用巡检与确认清单都必须覆盖整棵子树,不能只看根层 papers)。 */
324
+ const flattenClearPapers = (unit) => [
325
+ ...unit.papers,
326
+ ...unit.subtopics.flatMap((s) => flattenClearPapers(s)),
327
+ ];
268
328
  /** 「文献不存在」的统一出口:404 + 不含服务端绝对路径的文案(原先普通 Error 会冒泡成 500 并带路径)。 */
269
329
  const notFound = (what) => new ManageError('not-found', 404, what);
270
330
  /**
@@ -358,8 +418,11 @@ export function registerRoutes(ctx, config) {
358
418
  return;
359
419
  }
360
420
  if (sub === '/api/library' && req.method === 'GET') {
361
- const papers = listPapers(dataDir).map((p) => ({ ...p, pdfPath: join(dataDir, p.topic, p.name + '.pdf') }));
362
- json(res, 200, { dataDir, topics: listTopics(dataDir), papers });
421
+ // F-C:pdfPath 必须按**该篇实际所在布局**给(新布局论文夹 / 旧布局平铺)。
422
+ // 写死新布局会让未迁移旧库里的平铺论文 pdfPath 指向不存在的路径(直接影响用户现在正在用的库)。
423
+ const papers = listPapers(dataDir).map((p) => ({ ...p, pdfPath: paperPdfPath(dataDir, p.topic, p.name) }));
424
+ // topics 保持「一级子目录」语义(既有调用方/测试),新增 tree = 完整嵌套树(子专题 UI 用)
425
+ json(res, 200, { dataDir, topics: listTopics(dataDir), papers, tree: listTopicTree(dataDir) });
363
426
  return;
364
427
  }
365
428
  // 新建专题(目录)。校验与 upload / rename 的 to 侧同一套(validateName:边界 + 命名规范),
@@ -368,9 +431,46 @@ export function registerRoutes(ctx, config) {
368
431
  if (sub === '/api/library/topic' && req.method === 'POST') {
369
432
  const body = (await readBody(req));
370
433
  try {
371
- const name = validateName(body.name, 'topic');
434
+ // name 是**相对路径**(`A` / `A/B`):逐段词法校验 + 「已存在的祖先必须是库内真目录」。
435
+ // mkdir(recursive) 天然能一次建多级(方案 §B2.2「天然建多级」);这里挡的是父链里**已存在**的那几段
436
+ // ——符号链接 / 指向库外的段一律拒(不隐式穿越),不存在的段交给 mkdir 创建。
437
+ const name = validateTopicPath(body.name, false);
372
438
  const root = realDataDir(dataDir);
373
- const dir = join(root, name);
439
+ const segs = name.split('/');
440
+ const leaf = segs[segs.length - 1];
441
+ const parentSegs = segs.slice(0, -1);
442
+ // C1(评审 C1):已存在的祖先段若是**论文目录** → 409。论文目录不能再当专题父:
443
+ // listPapers 在论文目录处停止递归,在其下新建的专题会整体从列表/树/范围提问里消失。
444
+ const paperParent = paperDirAncestor(root, parentSegs);
445
+ if (paperParent) {
446
+ throw new ManageError('target-exists', 409, `父级是论文目录,不能在其下创建专题:${paperParent}`, { conflicts: [paperParent] });
447
+ }
448
+ // C2(评审 C2):同层已有同名**旧平铺论文**产物 → 409。建出同名目录后「文件夹优先」规则
449
+ // 会把旧平铺论文永久遮蔽(列表/树看不见、planPaperDelete 404、产物从 API 不可删)。
450
+ // 只看 topic 内部(parentSegs 非空):dataDir 根层的平铺文件不是文献,不构成遮蔽。
451
+ if (parentSegs.length > 0) {
452
+ const flat = flatArtifactNames(join(root, ...parentSegs), leaf);
453
+ if (flat.length > 0) {
454
+ throw new ManageError('target-exists', 409, `同层已有旧布局论文:${flat.join('、')}(请先迁移或改名,否则它会被同名专题遮蔽)`, { conflicts: flat });
455
+ }
456
+ }
457
+ // 评审 REV1-① / t11:目标同级已有**仅大小写不同**的条目 ⇒ 409 并点名磁盘真名。
458
+ // 不敏感盘上 mkdir 会命中既有目录别名(旧实现 return 200 = 假成功);敏感盘上会并存
459
+ // `CaseTopic` + `casetopic` 两个近同名专题。upload 已经拒这类(B4),此处对齐同一口径。
460
+ const caseClash = caseVariantCollisions(join(root, ...parentSegs), leaf);
461
+ if (caseClash.length > 0) {
462
+ throw new ManageError('target-exists', 409, `同层已有仅大小写不同的同名对象:${caseClash.join('、')}(大小写不敏感的文件系统上会互相吞掉)`, { conflicts: caseClash });
463
+ }
464
+ for (let i = 1; i < segs.length; i++) {
465
+ if (!existsSync(join(root, ...segs.slice(0, i))))
466
+ break;
467
+ resolveTopicDir(dataDir, segs.slice(0, i).join('/'));
468
+ }
469
+ const dir = join(root, ...segs);
470
+ // 目标本身已是论文目录(嵌套层)→ 409:它在列表里会被当成论文,永远不是可用的专题。
471
+ if (parentSegs.length > 0 && isPaperDir(dir)) {
472
+ throw new ManageError('target-exists', 409, `已存在同名论文:${leaf}(不能当专题)`, { conflicts: [leaf] });
473
+ }
374
474
  // 已存在 → 必须是真目录且不是符号链接(与 upload 同一条链路);不存在 → 词法层已保证不越界
375
475
  if (existsSync(dir))
376
476
  resolveTopicDir(dataDir, name);
@@ -394,10 +494,14 @@ export function registerRoutes(ctx, config) {
394
494
  json(res, 400, { error: '缺少 x-dpr-topic / x-dpr-name 头', code: 'bad-request' });
395
495
  return;
396
496
  }
397
- // 词法层:与其余 CRUD 同强度(../ / \ 隐藏名 控制字符 超长 空串)
398
- const errName = validateEntryName(topic);
399
- if (errName) {
400
- json(res, 400, { error: errName, code: 'bad-name' });
497
+ // 词法层:topic 是**相对路径**,逐段同强度校验(../ / \ 隐藏名 控制字符 超长 空串/层级上限)
498
+ let topicPath;
499
+ try {
500
+ topicPath = validateTopicPath(topic, false);
501
+ }
502
+ catch (err) {
503
+ if (!manageFail(res, err))
504
+ throw err;
401
505
  return;
402
506
  }
403
507
  if (!filename.toLowerCase().endsWith('.pdf')) {
@@ -418,7 +522,7 @@ export function registerRoutes(ctx, config) {
418
522
  // 顺序:目标目录的全部校验都在**读 body 之前**——越界目标不消费请求体、不碰盘。
419
523
  let dir;
420
524
  try {
421
- dir = resolveUploadTopic(dataDir, topic);
525
+ dir = resolveUploadTopic(dataDir, topicPath);
422
526
  }
423
527
  catch (err) {
424
528
  json(res, 400, { error: readableError(err), code: 'escape-rejected' });
@@ -427,7 +531,7 @@ export function registerRoutes(ctx, config) {
427
531
  // 我们的加严:上游放行「real 落在库内」的符号链接专题,我们一律拒(评审 §B 点名表扬)。
428
532
  try {
429
533
  if (existsSync(dir))
430
- resolveTopicDir(dataDir, topic.trim());
534
+ resolveTopicDir(dataDir, topicPath);
431
535
  else
432
536
  assertInside(realDataDir(dataDir), dir);
433
537
  }
@@ -436,6 +540,53 @@ export function registerRoutes(ctx, config) {
436
540
  return;
437
541
  throw err;
438
542
  }
543
+ // ── 写侧布局碰撞预检(评审 B/C1):**在消费请求体之前**完成(既有约定:越界/碰撞目标不读 body、不碰盘)──
544
+ // ① C1:topic 路径上任何一段(第 2 段起)已是**论文目录** ⇒ 409。论文目录不会再被递归,
545
+ // 往里上传的新论文会从列表/树/范围提问里整体消失。
546
+ // ② B1/B2:目标 `<topicDir>/<stem>/` 已存在(子专题目录 / 论文目录 / 同名文件)⇒ 409。
547
+ // 把子专题变成论文目录会让其下论文整体消失;覆盖已有论文目录会吞数据。
548
+ // ③ B2:同层已有**旧平铺论文**同名产物(`<stem>.pdf/.txt/.study.json/...`)⇒ 409。
549
+ // 「文件夹优先」规则会永久遮蔽它们(学习进度不可见、产物从 API 不可删)。
550
+ // ④ B3:仅大小写不同的同名目录 / 平铺文件 ⇒ 409,文案点名磁盘上的真实冲突对象。
551
+ try {
552
+ const root = realDataDir(dataDir);
553
+ const paperSeg = paperDirAncestor(root, topicPath.split('/'));
554
+ if (paperSeg) {
555
+ throw new ManageError('target-exists', 409, `专题路径落在论文目录里,不能上传:${paperSeg}`, { conflicts: [paperSeg] });
556
+ }
557
+ const targetPaperDir = join(dir, stem);
558
+ let targetStat = null;
559
+ try {
560
+ targetStat = lstatSync(targetPaperDir);
561
+ }
562
+ catch { /* 目标尚不存在 → 继续查同层产物 */ }
563
+ if (targetStat) {
564
+ const actual = existingEntryName(dir, stem);
565
+ if (targetStat.isSymbolicLink()) {
566
+ throw new ManageError('escape-rejected', 400, `路径越界:目标论文路径是符号链接,已拒绝:${actual}`);
567
+ }
568
+ if (targetStat.isDirectory()) {
569
+ if (isPaperDir(targetPaperDir)) {
570
+ throw new ManageError('target-exists', 409, `已存在同名论文目录:${actual}(上传会覆盖/合并它)`, { conflicts: [actual] });
571
+ }
572
+ throw new ManageError('target-exists', 409, `已存在同名子专题:${actual}(上传会把它变成论文目录,其下文献将整体消失)`, { conflicts: [actual] });
573
+ }
574
+ throw new ManageError('target-exists', 409, `已存在同名文件:${actual}(上传会覆盖它)`, { conflicts: [actual] });
575
+ }
576
+ const flat = flatArtifactNames(dir, stem);
577
+ if (flat.length > 0) {
578
+ throw new ManageError('target-exists', 409, `同层已有旧布局论文产物:${flat.join('、')}(新建论文文件夹会把它永久遮蔽,请先迁移)`, { conflicts: flat });
579
+ }
580
+ const caseVariants = caseVariantCollisions(dir, stem);
581
+ if (caseVariants.length > 0) {
582
+ throw new ManageError('target-exists', 409, `同层已有仅大小写不同的同名对象:${caseVariants.join('、')}(大小写不敏感的文件系统上会互相吞掉)`, { conflicts: caseVariants });
583
+ }
584
+ }
585
+ catch (err) {
586
+ if (libFail(res, err))
587
+ return;
588
+ throw err;
589
+ }
439
590
  const chunks = [];
440
591
  for await (const c of req)
441
592
  chunks.push(c);
@@ -445,14 +596,15 @@ export function registerRoutes(ctx, config) {
445
596
  return;
446
597
  }
447
598
  try {
448
- await mkdir(dir, { recursive: true });
449
- await writeFile(join(dir, safeName), buf);
599
+ // 新布局(方案 §B1.3 #20):先建**论文文件夹** `<topicDir>/<论文名>/`,PDF 落在里面
600
+ await mkdir(join(dir, stem), { recursive: true });
601
+ await writeFile(join(dir, stem, safeName), buf);
450
602
  }
451
603
  catch (err) {
452
604
  fsError(res, err);
453
605
  return;
454
606
  }
455
- json(res, 200, { ok: true, topic: topic.trim(), name: stem, bytes: buf.length });
607
+ json(res, 200, { ok: true, topic: topicPath, name: stem, bytes: buf.length });
456
608
  return;
457
609
  }
458
610
  /* ── 路由名兼容层 ─────────────────────────────────────────────────────
@@ -480,6 +632,21 @@ export function registerRoutes(ctx, config) {
480
632
  json(res, 400, { error: err, code: 'bad-name' });
481
633
  return true;
482
634
  };
635
+ /**
636
+ * 专题**路径**的入参门(方案 §B2.2):topic 升级为相对路径(`A` / `A/B`)后,**全部** topic
637
+ * 入参统一走这里——先逐段词法校验、再解析真目录,禁止保留两套并存的入参语义
638
+ * (否则会出现「同一个 topic 在 clear-plan 能过、在 clear 过不了」的不对称)。
639
+ */
640
+ const badTopicPath = (res, raw, boundaryOnly) => {
641
+ try {
642
+ return validateTopicPath(raw, boundaryOnly);
643
+ }
644
+ catch (err) {
645
+ if (!manageFail(res, err))
646
+ throw err;
647
+ return null;
648
+ }
649
+ };
483
650
  // 删除预览(dry-run):确认弹窗的文件清单必须来自这里,不许前端自己拼
484
651
  if (sub === '/api/library/paper/delete-plan' && req.method === 'GET') {
485
652
  const topic = url.searchParams.get('topic') ?? '';
@@ -514,11 +681,14 @@ export function registerRoutes(ctx, config) {
514
681
  // 别名 = /api/library/paper/delete。词法门走 badEntry(topic) + badEntryBoundary(name)。
515
682
  if ((sub === '/api/library/delete-paper' || sub === '/api/library/paper/delete') && req.method === 'POST') {
516
683
  const body = (await readBody(req));
517
- if (badEntry(res, body.topic) || badEntryBoundary(res, body.name))
684
+ if (badEntryBoundary(res, body.name))
518
685
  return;
519
686
  if (rejectWritePath(body, res))
520
687
  return;
521
- await withInflight(`${String(body.topic ?? '')}\u0000${String(body.name ?? '')}`, res, async () => {
688
+ const topicPath = badTopicPath(res, body.topic, true);
689
+ if (topicPath === null)
690
+ return;
691
+ await withInflight(`paper\u0000${topicPath}\u0000${String(body.name ?? '')}`, res, async () => {
522
692
  try {
523
693
  const plan = planPaperDelete(dataDir, body.topic, body.name);
524
694
  const ref = resolveLibraryPaper(plan.topic, plan.name);
@@ -544,11 +714,14 @@ export function registerRoutes(ctx, config) {
544
714
  if ((sub === '/api/library/rename-paper' || sub === '/api/library/paper/rename') && req.method === 'POST') {
545
715
  const body = (await readBody(req));
546
716
  const rawTo = body.newName ?? body.to;
547
- if (badEntry(res, body.topic) || badEntryBoundary(res, body.name) || badEntry(res, rawTo))
717
+ if (badEntryBoundary(res, body.name) || badEntry(res, rawTo))
548
718
  return;
549
719
  if (rejectWritePath(body, res))
550
720
  return;
551
- await withInflight(`${String(body.topic ?? '')}\u0000${String(body.name ?? '')}`, res, async () => {
721
+ const topicPath = badTopicPath(res, body.topic, true);
722
+ if (topicPath === null)
723
+ return;
724
+ await withInflight(`paper\u0000${topicPath}\u0000${String(body.name ?? '')}`, res, async () => {
552
725
  try {
553
726
  // 先校验名称/越界/存在(planPaperDelete 内部做全套检查)——不能先 resolvePaper:
554
727
  // 非法名会在那里抛出非 ManageError 的普通错误,被外层记成 500。
@@ -584,7 +757,8 @@ export function registerRoutes(ctx, config) {
584
757
  badEntry(res, rawName);
585
758
  return;
586
759
  }
587
- if (badEntryBoundary(res, rawName))
760
+ const topicPath = badTopicPath(res, rawName, true);
761
+ if (topicPath === null)
588
762
  return;
589
763
  // 词法门两段式(4 条路由都必须在文件系统操作之前过 badEntry,见 upstream V12 的结构性断言):
590
764
  // ① badEntry(上游 #4 的 validateEntryName)挡**类型 / 空值**——非字符串、空串在任何模式下都非法;
@@ -592,9 +766,9 @@ export function registerRoutes(ctx, config) {
592
766
  // 走 badEntryBoundary(分层理由见其定义:历史遗留的不规范名必须能清掉,否则是删不掉的孤儿)。
593
767
  if (rejectWritePath(body, res))
594
768
  return;
595
- await withInflight(`topic\u0000${String(rawName ?? '')}`, res, async () => {
769
+ await withInflight(`topic\u0000${topicPath}`, res, async () => {
596
770
  try {
597
- const name = rawName;
771
+ const name = topicPath;
598
772
  // confirmName 是**可选**栅栏:给了就必须一致(400 confirm-mismatch);没给也照走全部前置——
599
773
  // 空专题免确认(上游 delete-topic {topic} 契约:没有数据可毁),非空专题一律
600
774
  // 409 topic-not-empty(我们的加固,比上游「一点递归删光」保守,见 docs/reader-ux-requirements.md)。
@@ -621,7 +795,7 @@ export function registerRoutes(ctx, config) {
621
795
  if (busy > 0)
622
796
  throw new ManageError('translation-busy', 409, '该专题有正在生成译文的文献,请等待完成后再删除', {});
623
797
  const r = deleteTopic(dataDir, plan.name);
624
- workspaceCache.delete(join(dataDir, plan.name)); // 清掉指向已删目录的工作区缓存
798
+ dropWorkspaceCache(plan.name); // 清掉指向已删目录(含子树)的工作区缓存
625
799
  json(res, 200, { ...r, archivedSessionsNote: true });
626
800
  }
627
801
  catch (err) {
@@ -640,15 +814,21 @@ export function registerRoutes(ctx, config) {
640
814
  badEntry(res, rawName);
641
815
  return;
642
816
  }
643
- // from 侧同 delete-topic:badEntry 挡类型/空值,命名规范只在改名**目标**(badEntry(rawTo))上强制
817
+ // from 侧同 delete-topic:先挡类型/空值,命名规范只在改名**目标**(to)上强制
644
818
  // ——这样「历史遗留的怪名专题 → 改成规范名」这条路不被自己的校验堵死。
645
- if (badEntryBoundary(res, rawName) || badEntry(res, rawTo))
819
+ const topicPath = badTopicPath(res, rawName, true);
820
+ if (topicPath === null)
821
+ return;
822
+ // F4:`to` 是**路径**(`A/B`)——「移动到另一父」必须能走通。与 topic 创建/清空同一条门:
823
+ // 逐段命名规范类校验 + 深度/段长/总长上限 + 编码变形拒绝(绝不退回单段的 validateEntryName)。
824
+ const toPath = badTopicPath(res, rawTo, false);
825
+ if (toPath === null)
646
826
  return;
647
827
  if (rejectWritePath(body, res))
648
828
  return;
649
- await withInflight(`topic\u0000${String(rawName ?? '')}`, res, async () => {
829
+ await withInflight(`topic\u0000${topicPath}`, res, async () => {
650
830
  try {
651
- const name = String(rawName ?? '');
831
+ const name = topicPath;
652
832
  const plan = planTopicDelete(dataDir, name); // 复用同一个「存在且合法」校验
653
833
  if (!(await requireTopicSessionsClear(plan.name, res)))
654
834
  return;
@@ -667,8 +847,8 @@ export function registerRoutes(ctx, config) {
667
847
  }
668
848
  if (busy > 0)
669
849
  throw new ManageError('translation-busy', 409, '该专题有正在生成译文的文献,请等待完成后再重命名', {});
670
- const r = renameTopic(dataDir, plan.name, rawTo);
671
- workspaceCache.delete(join(dataDir, plan.name));
850
+ const r = renameTopic(dataDir, plan.name, toPath);
851
+ dropWorkspaceCache(plan.name);
672
852
  // 响应补 `topic`(上游 UI/文档读法)——我们的 RenameResult 用 from/to
673
853
  json(res, 200, { ...r, topic: r.to, detachedSessions: detached });
674
854
  }
@@ -683,20 +863,29 @@ export function registerRoutes(ctx, config) {
683
863
  // 形状与 /api/library/paper/delete-plan 对齐(files/totalBytes/notDeleted),逐篇额外给
684
864
  // sessions/translation,让 UI 在用户点确认**之前**就能提示「第 7 篇正在翻译」。
685
865
  if (sub === '/api/library/topic/clear-plan' && req.method === 'GET') {
686
- const topic = url.searchParams.get('topic') ?? '';
866
+ const rawTopic = url.searchParams.get('topic') ?? '';
687
867
  if (url.searchParams.get('path')) {
688
868
  json(res, 400, { error: '不接受 path 参数,请用 topic', code: 'escape-rejected' });
689
869
  return;
690
870
  }
871
+ // topic 类路由统一入参门(与 delete/rename/clear 同一条):逐段词法 + 编码变形 + 深度/长度上限
872
+ const topic = badTopicPath(res, rawTopic, true);
873
+ if (topic === null)
874
+ return;
691
875
  try {
692
876
  const plan = planTopicClear(dataDir, topic);
877
+ // D(评审 D2):确认框必须逐篇列出**整棵子树**的论文。旧实现只遍历根层 `plan.papers`
878
+ // ⇒ 子专题里的论文不在「将删除什么」清单里,而 `papersCount` 却包含子树(两个数字自相矛盾,
879
+ // 用户在确认框里根本看不到要删的子专题论文)。
880
+ const allPapers = flattenClearPapers(plan);
693
881
  const papers = [];
694
- for (const p of plan.papers) {
695
- const ref = resolveLibraryPaper(plan.topic, p.name);
882
+ for (const p of allPapers) {
883
+ const ref = resolveLibraryPaper(p.topic, p.name);
696
884
  const sessions = await sessionInfo(ref);
697
885
  const zh = zhStatus(ref);
698
886
  papers.push({
699
887
  name: p.name,
888
+ topic: p.topic,
700
889
  files: p.files,
701
890
  totalBytes: p.totalBytes,
702
891
  sessions: toWire(sessions),
@@ -706,10 +895,13 @@ export function registerRoutes(ctx, config) {
706
895
  json(res, 200, {
707
896
  topic: plan.topic,
708
897
  papers,
709
- papersCount: plan.papersCount,
898
+ // 与清单严格一致(清单已含子树;两者相等,任一处漂移都会让确认框说谎)
899
+ papersCount: allPapers.length,
710
900
  filesCount: plan.filesCount,
711
901
  totalBytes: plan.totalBytes,
712
902
  hidden: plan.hidden,
903
+ subtopics: plan.subtopics.map((s) => ({ topic: s.topic, papersCount: s.papersCount, filesCount: s.filesCount, totalBytes: s.totalBytes })),
904
+ subtopicsCount: plan.subtopics.length,
713
905
  trashRoot: plan.trashRoot,
714
906
  notDeleted: plan.notDeleted,
715
907
  clearEndpoint: '/api/library/topic/clear',
@@ -732,35 +924,40 @@ export function registerRoutes(ctx, config) {
732
924
  badEntry(res, rawTopic);
733
925
  return;
734
926
  }
735
- if (badEntryBoundary(res, rawTopic))
927
+ const topicPath = badTopicPath(res, rawTopic, true);
928
+ if (topicPath === null)
736
929
  return;
737
930
  if (rejectWritePath(body, res))
738
931
  return;
739
- if (body.confirmName !== rawTopic) {
932
+ if (typeof body.confirmName !== 'string' || body.confirmName.trim() !== topicPath) {
740
933
  json(res, 400, { error: '需要 confirmName 与专题名完全一致才允许清空', code: 'confirm-mismatch' });
741
934
  return;
742
935
  }
743
- await withInflight(`topic\u0000${rawTopic}`, res, async () => {
936
+ await withInflight(`topic\u0000${topicPath}`, res, async () => {
744
937
  try {
745
- const plan = planTopicClear(dataDir, rawTopic); // 存在性 404 / 越界 400 / 符号链接专题 400
938
+ const plan = planTopicClear(dataDir, topicPath); // 存在性 404 / 越界 400 / 符号链接专题 400
746
939
  if (plan.papersCount === 0) {
747
940
  throw new ManageError('bad-request', 400, '专题已为空,请用删除专题', { clearEndpoint: '/api/library/delete-topic' });
748
941
  }
749
942
  let detached = 0;
750
943
  const busyTrans = [];
751
- for (const p of plan.papers) {
752
- const ref = resolveLibraryPaper(plan.topic, p.name);
944
+ // D(评审 D1):clearTopic 删的是**整棵子树**,占用巡检也必须遍历整棵子树。
945
+ // 旧实现只遍历根层 `plan.papers` ⇒ 子专题里有活跃会话/生成中译文的论文照删不误。
946
+ for (const p of flattenClearPapers(plan)) {
947
+ // 逐篇用**它自己的**专题路径定位(子树清空时根 topic 不再是每篇的父级)
948
+ const ref = resolveLibraryPaper(p.topic, p.name);
949
+ const label = p.topic === plan.topic ? p.name : `${p.topic}/${p.name}`;
753
950
  if (!(await requireSessionClear(ref, res)))
754
951
  return; // unknown→503 / running→409(同一套 code)
755
952
  detached += (await sessionInfo(ref)).total;
756
953
  if (zhStatus(ref).busy)
757
- busyTrans.push(p.name);
954
+ busyTrans.push(label);
758
955
  }
759
956
  if (busyTrans.length > 0) {
760
957
  throw new ManageError('translation-busy', 409, `以下文献正在生成译文,请等待完成后再清空:${busyTrans.join('、')}`, { papers: busyTrans });
761
958
  }
762
959
  const r = clearTopic(dataDir, plan.topic);
763
- workspaceCache.delete(join(dataDir, plan.topic)); // 清掉指向已清空目录的工作区缓存
960
+ dropWorkspaceCache(plan.topic); // 清掉指向已清空目录(含子树)的工作区缓存
764
961
  json(res, 200, { ...r, detachedSessions: detached, archivedSessionsNote: true });
765
962
  }
766
963
  catch (err) {
@@ -770,6 +967,92 @@ export function registerRoutes(ctx, config) {
770
967
  });
771
968
  return;
772
969
  }
970
+ /* ── 布局迁移(旧平铺 → 按论文分文件夹):方案 §B1.2 的只读预检 + 显式执行 + 回滚 ──
971
+ 铁律:默认**只读**;执行必须带 confirm=migrate-library(UI/CLI 先让人核对干跑报告);
972
+ 回滚日志必须在我们的 migration-logs 目录内(不认任意路径,防被当成任意文件读写口)。 */
973
+ if (sub === '/api/library/migrate-plan' && req.method === 'GET') {
974
+ try {
975
+ const plan = planMigration(dataDir);
976
+ json(res, 200, { ok: true, plan, report: formatMigrationReport(plan) });
977
+ }
978
+ catch (err) {
979
+ if (!libFail(res, err))
980
+ throw err;
981
+ }
982
+ return;
983
+ }
984
+ if (sub === '/api/library/migrate' && req.method === 'POST') {
985
+ const body = (await readBody(req));
986
+ if (body.confirm !== 'migrate-library') {
987
+ json(res, 400, { error: '需要 confirm=migrate-library 才允许执行迁移(请先 GET /api/library/migrate-plan 人工核对报告)', code: 'confirm-mismatch' });
988
+ return;
989
+ }
990
+ await withInflight('migrate\u0000library', res, async () => {
991
+ try {
992
+ // E3(评审 E):迁移会搬动全库文件,与 delete/rename 同口径——对**在飞转录/译文**加 busy 门。
993
+ // 旧实现直接开跑:正在转录的临时产物会被当成论文产物复制/删除,正在翻译的论文也可能被搬走。
994
+ const transcribing = [...activeTranscribes].map((k) => k.split('\u0000').join('/'));
995
+ const translating = translationBusyPapers();
996
+ const busy = [...transcribing, ...translating];
997
+ if (busy.length > 0) {
998
+ throw new ManageError('busy', 409, `有文献正在转录/生成译文,请等待完成后再执行迁移:${busy.slice(0, 3).join('、')}${busy.length > 3 ? ' 等' : ''}`, { papers: busy });
999
+ }
1000
+ // E3:用异步执行体(每复制/删除一个文件让出事件循环),大库迁移期间 PDF 流 / SSE / 读接口仍可响应。
1001
+ const r = await runMigrationAsync(dataDir);
1002
+ json(res, 200, r);
1003
+ }
1004
+ catch (err) {
1005
+ if (err instanceof MigrationAborted) {
1006
+ json(res, 409, { ...err.detail, error: err.message, code: err.code });
1007
+ return;
1008
+ }
1009
+ if (err instanceof MigrationError) {
1010
+ json(res, 409, { error: err.message, code: err.code });
1011
+ return;
1012
+ }
1013
+ if (!libFail(res, err))
1014
+ throw err;
1015
+ }
1016
+ });
1017
+ return;
1018
+ }
1019
+ if (sub === '/api/library/migrate-rollback' && req.method === 'POST') {
1020
+ const body = (await readBody(req));
1021
+ if (body.confirm !== 'rollback-library') {
1022
+ json(res, 400, { error: '需要 confirm=rollback-library 才允许回滚', code: 'confirm-mismatch' });
1023
+ return;
1024
+ }
1025
+ const logDir = migrationLogDir();
1026
+ const logPath = body.logPath?.trim() || lastMigrationLog();
1027
+ if (!logPath) {
1028
+ json(res, 400, { error: '没有可用的迁移日志(请在 body 里给 logPath)', code: 'bad-request' });
1029
+ return;
1030
+ }
1031
+ // G(评审 G 次级):旧判断用裸 `startsWith`(没有路径分隔符)——`<logDir>-evil/x.jsonl` 会被
1032
+ // `<logDir>` 前缀误判通过(`/a/bc` 冒充 `/a/b` 的子路径)。用 relative 判定:必须在目录**内部**。
1033
+ const relLog = relative(resolve(logDir), resolve(logPath));
1034
+ if (!relLog || relLog === '..' || relLog.startsWith('..' + sep) || isAbsolute(relLog)) {
1035
+ json(res, 400, { error: 'logPath 必须是迁移日志目录内的文件', code: 'escape-rejected' });
1036
+ return;
1037
+ }
1038
+ await withInflight('migrate\u0000library', res, async () => {
1039
+ try {
1040
+ const r = rollbackMigration(dataDir, logPath);
1041
+ json(res, 200, r);
1042
+ }
1043
+ catch (err) {
1044
+ // E1:坏行/不可读日志是 MigrationError(带 migrate-log-* 机器码)。必须**如实**回答,
1045
+ // 不能落到 fsError 的「系统错误,请稍后重试」把行号/原因吞掉(那又成了「假成功」的变体)。
1046
+ if (err instanceof MigrationError) {
1047
+ json(res, 409, { error: err.message, code: err.code });
1048
+ return;
1049
+ }
1050
+ if (!libFail(res, err))
1051
+ throw err;
1052
+ }
1053
+ });
1054
+ return;
1055
+ }
773
1056
  // 公式索引:MinerU content_list 的 equation 块(LaTeX + bbox),供阅读器画热区/列表面板
774
1057
  if (sub === '/api/formulas' && req.method === 'GET') {
775
1058
  const ref = locate(url); // 只读路径,沿用 path/topic/name 三种定位
@@ -1121,6 +1404,34 @@ export function registerRoutes(ctx, config) {
1121
1404
  json(res, 200, { ok: true });
1122
1405
  return;
1123
1406
  }
1407
+ /* ── 阅读器深色模式配置(方案 §A2.3):设置面板卡片与阅读器 ⚙ 浮层**共用同一个后端配置** ──
1408
+ 无密钥 ⇒ GET 直接回生效值 + 实测曲线(前端据此算 CSS 变量);POST 严格校验后落盘;
1409
+ DELETE 回落默认(follow)。 */
1410
+ if (sub === '/api/theme/config' && req.method === 'GET') {
1411
+ const cfg = await readThemeConfig();
1412
+ json(res, 200, { ...themePayload(cfg), source: 'file' });
1413
+ return;
1414
+ }
1415
+ if (sub === '/api/theme/config' && req.method === 'POST') {
1416
+ const body = (await readBody(req));
1417
+ let next;
1418
+ try {
1419
+ const prev = await readThemeConfig();
1420
+ next = validateThemePatch({ ...prev, ...body });
1421
+ }
1422
+ catch (err) {
1423
+ json(res, 400, { error: err instanceof Error ? err.message : '配置非法', code: 'bad-request' });
1424
+ return;
1425
+ }
1426
+ await writeThemeConfig(next);
1427
+ json(res, 200, { ok: true, ...themePayload(next) });
1428
+ return;
1429
+ }
1430
+ if (sub === '/api/theme/config' && req.method === 'DELETE') {
1431
+ await clearThemeConfig();
1432
+ json(res, 200, { ok: true, ...themePayload(await readThemeConfig()) });
1433
+ return;
1434
+ }
1124
1435
  // ── 嵌入模型端点配置(设置面板第三张端点卡片)─────────────────────────
1125
1436
  // 与 translate/typesafe 完全同一套约定:GET 只回掩码 key;POST 预检通过才落盘;DELETE 回落。
1126
1437
  if (sub === '/api/embed/config' && req.method === 'GET') {
@@ -1302,7 +1613,17 @@ export function registerRoutes(ctx, config) {
1302
1613
  }
1303
1614
  const mineru = await resolveMineruConfig(config.mineru);
1304
1615
  const source = MINERU_SOURCES.has(body.source ?? 'auto') ? body.source : 'auto';
1305
- const t = await transcribePaper(ref, { force: body.force === true, source, mineru });
1616
+ // E3:登记在飞转录 —— /migrate 会据此 409(与 delete/rename 的 busy 门同口径),
1617
+ // 否则迁移可能复制/清理正在写的 `.tmp-*` 或半成品缓存。
1618
+ const transcribeKey = `${ref.topic}\u0000${ref.name}`;
1619
+ activeTranscribes.add(transcribeKey);
1620
+ let t;
1621
+ try {
1622
+ t = await transcribePaper(ref, { force: body.force === true, source, mineru });
1623
+ }
1624
+ finally {
1625
+ activeTranscribes.delete(transcribeKey);
1626
+ }
1306
1627
  json(res, 200, { chars: t.chars, pageCount: t.pageCount, hasPageIndex: t.pages.length > 0, source: t.source, producer: t.producer, backend: t.backend });
1307
1628
  return;
1308
1629
  }
@@ -1379,6 +1700,41 @@ export function registerRoutes(ctx, config) {
1379
1700
  await createPaperSession(sessionId, ref.topic);
1380
1701
  }
1381
1702
  catch { /* 已存在则复用 */ }
1703
+ // ── 范围(方案 §B3.1):缺省/无效一律按「当前论文」;给了非法结构则显式 400 ──
1704
+ let scope = null;
1705
+ if (body.scope !== undefined && body.scope !== null) {
1706
+ const raw = body.scope;
1707
+ if (typeof raw !== 'object') {
1708
+ json(res, 400, { error: 'scope 必须是对象', code: 'bad-request' });
1709
+ return;
1710
+ }
1711
+ if (raw.kind === 'paper') {
1712
+ const args = {};
1713
+ if (raw.topic !== undefined)
1714
+ args.topic = raw.topic;
1715
+ if (raw.name !== undefined)
1716
+ args.name = raw.name;
1717
+ if (body.topic === undefined && args.topic === undefined && args.name === undefined) {
1718
+ json(res, 400, { error: 'scope.kind=paper 需要 topic/name(或省略 scope 用当前论文)', code: 'bad-request' });
1719
+ return;
1720
+ }
1721
+ scope = { kind: 'paper', ...args };
1722
+ }
1723
+ else if (raw.kind === 'topic') {
1724
+ try {
1725
+ scope = { kind: 'topic', topic: validateTopicPath(raw.topic, false) };
1726
+ }
1727
+ catch (err) {
1728
+ if (!manageFail(res, err))
1729
+ throw err;
1730
+ return;
1731
+ }
1732
+ }
1733
+ else {
1734
+ json(res, 400, { error: "scope.kind 只能是 'paper' 或 'topic'", code: 'bad-request' });
1735
+ return;
1736
+ }
1737
+ }
1382
1738
  const hasQuote = typeof body.selectedText === 'string' && body.selectedText.trim() !== '';
1383
1739
  // 公式引用(kind='equation'):引用内容来自 MinerU 的 LaTeX,不是文本层乱码(契约 §1.3);
1384
1740
  // 非公式路径的文案必须与改造前逐字一致(回归项 A11)。
@@ -1392,6 +1748,35 @@ export function registerRoutes(ctx, config) {
1392
1748
  ? `用户在阅读器里引用了${body.page ? `第 ${body.page} 页的` : ''}一个公式(LaTeX 源,来自 MinerU 版面解析):`
1393
1749
  : `用户在阅读器里选中了一段文字${where}:`, `"""${body.selectedText.trim()}"""`);
1394
1750
  }
1751
+ // 范围块:**追加**(不传 scope 时这段完全不存在 ⇒ 既有文案逐字不变,回归项 C2)
1752
+ let scopeInfo = null;
1753
+ if (scope) {
1754
+ try {
1755
+ const ctx = buildScopeContext(dataDir, ref, scope, body.question);
1756
+ lines.push(ctx.block);
1757
+ if (scopeBusy(ctx.scopePath)) {
1758
+ lines.push(`(提示:该范围内的目录正在被修改,本次只给了 ${ctx.papers.length - ctx.omitted} 篇)`);
1759
+ }
1760
+ scopeInfo = {
1761
+ kind: scope.kind,
1762
+ path: ctx.scopePath,
1763
+ papers: ctx.papers.length - ctx.omitted,
1764
+ omitted: ctx.omitted,
1765
+ truncated: ctx.truncated,
1766
+ chars: ctx.totalChars,
1767
+ coverage: ctx.papers.map((p) => ({ path: p.path, coverage: p.coverage })),
1768
+ };
1769
+ }
1770
+ catch (err) {
1771
+ if (isManageError(err)) {
1772
+ libFail(res, err);
1773
+ return;
1774
+ }
1775
+ // 读路径 fail-soft:范围装配失败不阻断提问,降级成「只说范围、不给内容」并如实标注
1776
+ lines.push(`【提问范围】${scope.kind === 'topic' ? scope.topic : '当前论文'}(范围内容装配失败,已在无范围内容的情况下提问)`);
1777
+ scopeInfo = { kind: scope.kind, path: scope.kind === 'topic' ? scope.topic : `${ref.topic}/${ref.name}`, degraded: true };
1778
+ }
1779
+ }
1395
1780
  lines.push(`用户的问题:${body.question}`);
1396
1781
  const prompt = lines.join('\n');
1397
1782
  await sc.prompt({
@@ -1399,7 +1784,7 @@ export function registerRoutes(ctx, config) {
1399
1784
  content: [{ type: 'text', text: prompt }],
1400
1785
  requestId: randomUUID(),
1401
1786
  }, AbortSignal.timeout(30_000));
1402
- json(res, 200, { ok: true, sessionId, n });
1787
+ json(res, 200, { ok: true, sessionId, n, ...(scopeInfo ? { scope: scopeInfo } : {}) });
1403
1788
  return;
1404
1789
  }
1405
1790
  json(res, 404, { error: 'not found: ' + url.pathname });