dsh-lifecard 0.2.0 → 0.2.2

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/lib/store.js CHANGED
@@ -10,7 +10,7 @@
10
10
  * - 快照存全文,不存 diff。
11
11
  */
12
12
 
13
- import { promises as fs } from 'node:fs'
13
+ import { promises as fs, readFileSync } from 'node:fs'
14
14
  import { createHash } from 'node:crypto'
15
15
  import path from 'node:path'
16
16
  import * as core from './core.js'
@@ -73,6 +73,11 @@ export function defaultConfig() {
73
73
  name: '我的档案',
74
74
  default_system: 'reality-interview',
75
75
  locale: 'zh',
76
+ // 三扇门各自「当前用哪张卡」。写小说、酒馆那两扇门里演谁 / 写谁,
77
+ // 不用每次都现挑;「真实人物记录」那扇门用它来决定首页先给谁。
78
+ default_cards: { real: '', tavern: '', novel: '' },
79
+ // 界面上被收起来的门(用户自己删的)。随时能装回来,数据一点没动。
80
+ hidden_doors: [],
76
81
  created_at: new Date().toISOString(),
77
82
  }
78
83
  }
@@ -376,7 +381,11 @@ export async function listDrafts(root) {
376
381
 
377
382
  /**
378
383
  * 读全部墓碑。`redactions.jsonl` 只追加、不可删除。
379
- * @returns {Promise<Array<{at: string, path?: string, id?: string, sha256?: string, reason?: string}>>}
384
+ *
385
+ * 有两种记录:撤回(缺省,或 `kind: 'withdraw'`)和恢复(`kind: 'restore'`)。
386
+ * 恢复不改写旧记录,只往后追加一条——文件是只追加的账,改旧行就等于改历史。
387
+ *
388
+ * @returns {Promise<Array<{at: string, kind?: string, path?: string, id?: string, sha256?: string, reason?: string}>>}
380
389
  */
381
390
  export async function readRedactions(root) {
382
391
  const file = path.join(root, 'redactions.jsonl')
@@ -407,17 +416,27 @@ export async function appendRedaction(root, entry) {
407
416
  }
408
417
 
409
418
  /**
410
- * 某个文件路径 + 内容是否命中墓碑。
419
+ * 某个文件路径 + 内容**最后**命中的那条墓碑。
420
+ *
421
+ * 「最后」是这里唯一要紧的事:一张卡先被删、又被恢复,账上就有两条记录,
422
+ * 该看的是后一条。以前取的是第一条命中,于是恢复永远不生效——删过的卡
423
+ * 一旦救回来,列表里还是看不见,再点删除又报「已撤回」。
411
424
  *
412
425
  * 一条墓碑至少要有一个**可比较的键**(path 或 sha256)才算数。
413
426
  * 之前没有这个下限:只写了 anchor 的残条会让三个 continue 全不触发,
414
427
  * 于是对任何文件都返回命中——`redactions.jsonl` 里手抖写进一条
415
428
  * `{anchor:"…", reason:"…"}`,全库的卡都会变成「已被撤回」。
416
429
  * anchor 只能当附加条件,不能单独承担撤回。
430
+ *
431
+ * @param {Array<object>} redactions
432
+ * @param {string} relPath
433
+ * @param {string} [content] - 文件正文;没读到就不传,纯路径的墓碑照样能命中
417
434
  */
418
- function hitsRedaction(redactions, relPath, content) {
435
+ function lastRedaction(redactions, relPath, content) {
419
436
  const hash = content === undefined ? undefined : sha256(content)
437
+ let last
420
438
  for (const r of redactions) {
439
+ if (r === null || typeof r !== 'object') continue
421
440
  const hasPath = typeof r.path === 'string' && r.path !== ''
422
441
  const hasHash = typeof r.sha256 === 'string' && r.sha256 !== ''
423
442
  // 两个键都没有:这条墓碑说不出撤回的是什么,不能命中任何东西。
@@ -425,9 +444,63 @@ function hitsRedaction(redactions, relPath, content) {
425
444
  if (hasPath && relPath !== undefined && r.path !== relPath) continue
426
445
  if (hasHash && hash !== undefined && r.sha256 !== hash) continue
427
446
  if (hasHash && hash === undefined) continue
428
- return r
447
+ last = r
429
448
  }
430
- return undefined
449
+ return last
450
+ }
451
+
452
+ /**
453
+ * 只看路径的最后一条墓碑,不算内容指纹。
454
+ *
455
+ * 只在「文件明明在、但读不出来」时用。这时候算不出内容指纹,带指纹的墓碑
456
+ * 一条都对不上,结果是这张既被撤回、又读不出的卡既不在列表里、也不在
457
+ * 「已撤回」里——用户看到的是文件凭空消失,连彻底删掉都做不到。
458
+ * 代价是:文件后来被改过也不管。但文件都读不出来了,这个差别没有意义。
459
+ */
460
+ function lastRedactionByPath(redactions, relPath) {
461
+ let last
462
+ for (const r of redactions) {
463
+ if (r === null || typeof r !== 'object') continue
464
+ if (typeof r.path !== 'string' || r.path === '' || r.path !== relPath) continue
465
+ last = r
466
+ }
467
+ return last
468
+ }
469
+
470
+ /**
471
+ * 最后一条墓碑是不是「现在还撤着」。
472
+ *
473
+ * 缺省 kind 的老记录也算撤回(墓碑机制刚上线时没有 kind 字段)。
474
+ * `restore`(恢复)和 `purge`(彻底删掉)都表示这张卡不再「撤着」:
475
+ * 恢复是回来了,彻底删是连文件都不在了,两者都不该继续占着名字。
476
+ */
477
+ function isWithdrawnRecord(record) {
478
+ if (record === undefined) return false
479
+ return record.kind === undefined || record.kind === 'withdraw'
480
+ }
481
+
482
+ export function hitsRedaction(redactions, relPath, content) {
483
+ const last = lastRedaction(redactions, relPath, content)
484
+ if (!isWithdrawnRecord(last)) return undefined
485
+ return last
486
+ }
487
+
488
+ /** 只看路径的命中判断:文件已经不在原位(读不出内容)时用。 */
489
+ export function hitsRedactionByPath(redactions, relPath) {
490
+ const last = lastRedactionByPath(redactions, relPath)
491
+ if (!isWithdrawnRecord(last)) return undefined
492
+ return last
493
+ }
494
+
495
+ /**
496
+ * 「这张卡现在撤着」的统一说法。
497
+ *
498
+ * 两条分支都从这里取(文件已经被搬进回收目录 / 文件还在原位只是账上撤了),
499
+ * 说法必须一字不差:用户看到的是同一件事,两处各写一遍早晚会漂开,
500
+ * 界面也会跟着一种说法、另一种不认。
501
+ */
502
+ export function withdrawnNotice(gone) {
503
+ return `这条记录已经被撤掉了(${gone?.reason ?? '未说明原因'}),现在不在列表里。想找回来可以恢复,它还在磁盘上。`
431
504
  }
432
505
 
433
506
  /**
@@ -486,6 +559,94 @@ export function sha256(text) {
486
559
  return createHash('sha256').update(String(text), 'utf8').digest('hex')
487
560
  }
488
561
 
562
+ // ── 收起来的卡(回收目录) ────────────────────────────────────────
563
+
564
+ /**
565
+ * 撤掉的卡不放原地,而是原样搬到 `.lifecard/redacted/<原相对路径>`。
566
+ *
567
+ * 只写墓碑、把文件留在 `people/` 有个说不通的后果:名字还被占着,
568
+ * 用户照着提示去列表里找,列表里却没有——删不掉,也重建不了同名的卡。
569
+ * 搬到回收目录以后,原位真的空出来了;想反悔照样能搬回去。
570
+ */
571
+ const REDACTED_DIR = '.lifecard/redacted'
572
+
573
+ /** 同步读墓碑。persona 注入那条同步路径也要过墓碑,不能只给它异步版本。 */
574
+ export function readRedactionsSync(root) {
575
+ let text = ''
576
+ try {
577
+ text = readFileSync(path.join(root, 'redactions.jsonl'), 'utf8')
578
+ } catch {
579
+ return []
580
+ }
581
+ const out = []
582
+ for (const line of text.split('\n')) {
583
+ const t = line.trim()
584
+ if (t === '') continue
585
+ try {
586
+ out.push(JSON.parse(t))
587
+ } catch {
588
+ // 坏行跳过,和异步版本一致
589
+ }
590
+ }
591
+ return out
592
+ }
593
+
594
+ /** 回收目录里某个原位路径下现存的候选文件名(新的在前)。 */
595
+ async function redactedCandidates(root, rel) {
596
+ const dirRel = path.posix.dirname(rel)
597
+ const dirAbs = path.join(root, REDACTED_DIR, dirRel === '.' ? '' : dirRel)
598
+ const base = path.posix.basename(rel)
599
+ let names
600
+ try {
601
+ names = await fs.readdir(dirAbs)
602
+ } catch {
603
+ return []
604
+ }
605
+ return names
606
+ .filter((name) => name === base || (name.startsWith(base + '.') && /\.card\.md\./i.test(name)))
607
+ .sort()
608
+ .reverse()
609
+ }
610
+
611
+ /**
612
+ * 把一张卡搬进回收目录,返回搬过去的位置。
613
+ *
614
+ * 同名冲突(同一张卡删过两次、或先恢复又删)不覆盖旧份:加时间戳后缀,
615
+ * 两份都留着,彻底删的时候一起清。
616
+ */
617
+ export async function moveCardToRedacted(root, relPath) {
618
+ const rel = String(relPath ?? '')
619
+ if (!rel.endsWith('.card.md')) return { ok: false, error: '这个位置不是一张卡。' }
620
+ const at = await resolveIn(root, rel)
621
+ if (!at.ok) return { ok: false, error: at.error }
622
+ const exists = await fs.stat(at.abs).then((s) => s.isFile()).catch(() => false)
623
+ if (!exists) return { ok: false, error: '磁盘上找不到这张卡。' }
624
+ const dirRel = path.posix.dirname(rel)
625
+ const dirAbs = path.join(root, REDACTED_DIR, dirRel === '.' ? '' : dirRel)
626
+ await fs.mkdir(dirAbs, { recursive: true })
627
+ const base = path.posix.basename(rel)
628
+ let name = base
629
+ const taken = await fs.access(path.join(dirAbs, name)).then(() => true).catch(() => false)
630
+ if (taken) name = `${base}.${new Date().toISOString().replace(/[:.]/g, '-')}`
631
+ const target = path.join(dirAbs, name)
632
+ await fs.rename(at.abs, target)
633
+ return {
634
+ ok: true,
635
+ path: rel,
636
+ redacted: path.posix.join(REDACTED_DIR, dirRel === '.' ? '' : dirRel, name),
637
+ }
638
+ }
639
+
640
+ /** 读出回收目录里某张卡最靠前的残份正文;没有就是 undefined。 */
641
+ async function readRedactedText(root, rel) {
642
+ const candidates = await redactedCandidates(root, rel)
643
+ if (candidates.length === 0) return undefined
644
+ const dirRel = path.posix.dirname(rel)
645
+ return fs
646
+ .readFile(path.join(root, REDACTED_DIR, dirRel === '.' ? '' : dirRel, candidates[0]), 'utf8')
647
+ .catch(() => undefined)
648
+ }
649
+
489
650
  // ── 卡片读写 ──────────────────────────────────────────────────────
490
651
 
491
652
  /**
@@ -500,7 +661,13 @@ export function cardRelPath(id, world) {
500
661
 
501
662
  /**
502
663
  * 读一张卡(已过墓碑过滤)。
503
- * @returns {Promise<{ok: boolean, path?: string, text?: string, data?: object, sections?: object[], error?: string}>}
664
+ *
665
+ * 撤掉的卡一定带 `withdrawn: true`——不管文件是已经被搬进回收目录(原位
666
+ * ENOENT),还是还在原位、只是账上记着撤掉(老式记录、手工改过文件)。
667
+ * 这两条以前一条带、一条不带,上层拿这个字段判断「要不要给恢复入口」时
668
+ * 就只认其中一种,另一种卡在界面上既看不见也删不掉。
669
+ *
670
+ * @returns {Promise<{ok: boolean, path: string, withdrawn?: boolean, text?: string, data?: object, sections?: object[], error?: string}>}
504
671
  */
505
672
  export async function readCard(root, relPath) {
506
673
  const at = await resolveIn(root, relPath)
@@ -513,7 +680,16 @@ export async function readCard(root, relPath) {
513
680
  // 「没有这个文件」和「有,但读不出来」是两件事。以前一律翻成「文件不存在」,
514
681
  // 上层于是把权限问题、同步盘没挂上当「还没有这张卡」——`card.save` 的兜底
515
682
  // 会退化成空小节,`applyProposal` 会另建一张同名的卡。
516
- if (error?.code === 'ENOENT') return { ok: false, path: relPath, error: '文件不存在' }
683
+ if (error?.code === 'ENOENT') {
684
+ // 撤掉的卡已经搬去回收目录,原位没了。这时报「文件不存在」等于告诉用户
685
+ // 这张卡凭空消失了——账上明明还记着它被撤掉。
686
+ const redactions = await readRedactions(root)
687
+ const gone = hitsRedactionByPath(redactions, relPath)
688
+ if (gone !== undefined) {
689
+ return { ok: false, path: relPath, withdrawn: true, error: withdrawnNotice(gone) }
690
+ }
691
+ return { ok: false, path: relPath, error: '文件不存在' }
692
+ }
517
693
  return {
518
694
  ok: false,
519
695
  path: relPath,
@@ -524,7 +700,11 @@ export async function readCard(root, relPath) {
524
700
  const redactions = await readRedactions(root)
525
701
  const hit = hitsRedaction(redactions, relPath, text)
526
702
  if (hit !== undefined) {
527
- return { ok: false, path: relPath, error: `这条记录已被撤回(${hit.reason ?? '未说明原因'}),不再显示` }
703
+ // 措辞要给出路。「不再显示」到此为止,用户就没法知道它其实还在磁盘上、
704
+ // 还能恢复——删掉的卡于是变成既看不见也找不回的僵局。
705
+ // 界面统一说「撤掉的」:失败路径上冒出「撤回」这种书面的词,用户会以为
706
+ // 是两个不一样的状态。
707
+ return { ok: false, path: relPath, withdrawn: true, error: withdrawnNotice(hit) }
528
708
  }
529
709
  const parsed = core.parseCard(text)
530
710
  // 解析失败要说失败。以前无论 parse 成不成一律 ok:true,于是格式坏掉的卡
@@ -687,7 +867,12 @@ export async function restoreSnapshot(root, relPath, stamp) {
687
867
 
688
868
  /**
689
869
  * 扫描整个工作区,列出所有卡(已过墓碑过滤)。
690
- * @returns {Promise<{cards: object[], worlds: object[], systems: object[], relations: object[], errors: object[]}>}
870
+ *
871
+ * `withdrawn` 是「被撤回、但文件还在磁盘上」的那些卡。它们不算 cards——
872
+ * 用户删掉的东西不该混进正常列表;但也不能像以前那样直接吞掉:列表上
873
+ * 一个字都看不见,用户就永远不知道它们还在,恢复和彻底删除都无从下手。
874
+ *
875
+ * @returns {Promise<{cards: object[], worlds: object[], systems: object[], relations: object[], errors: object[], withdrawn: object[]}>}
691
876
  */
692
877
  export async function listAll(root) {
693
878
  const redactions = await readRedactions(root)
@@ -697,6 +882,7 @@ export async function listAll(root) {
697
882
  const relations = []
698
883
  const errors = []
699
884
  const materials = []
885
+ const withdrawn = []
700
886
 
701
887
  const walk = async (relDir) => {
702
888
  const abs = path.join(root, relDir)
@@ -708,6 +894,8 @@ export async function listAll(root) {
708
894
  }
709
895
  for (const entry of entries) {
710
896
  if (entry.name.startsWith('.')) continue
897
+ // 覆盖写留下的 `.bak-<时间>`、写到一半的 `.tmp-…` 都是残骸,不是内容。
898
+ if (isBackupName(entry.name)) continue
711
899
  const rel = path.posix.join(relDir.replace(/\\/g, '/'), entry.name)
712
900
  if (entry.isDirectory()) {
713
901
  await walk(rel)
@@ -717,7 +905,14 @@ export async function listAll(root) {
717
905
  if (lower.endsWith('.card.md')) {
718
906
  const r = await readCard(root, rel)
719
907
  if (!r.ok) {
720
- if (r.error !== undefined && !r.error.startsWith('这条记录已被撤回')) errors.push({ path: rel, error: r.error })
908
+ // 先看它是不是撤回过的:读不出来(权限、同步盘没挂上)的撤回卡
909
+ // 也得出现在 withdrawn 里,否则「既看不见又删不掉」的死结照旧。
910
+ const gone = await withdrawnEntry(root, redactions, rel)
911
+ if (gone !== null) {
912
+ withdrawn.push(gone)
913
+ continue
914
+ }
915
+ if (r.error !== undefined) errors.push({ path: rel, error: r.error })
721
916
  continue
722
917
  }
723
918
  const cov = core.coverage(r.data, r.sections)
@@ -733,6 +928,8 @@ export async function listAll(root) {
733
928
  relation: r.data?.relation,
734
929
  status: r.data?.status,
735
930
  tags: Array.isArray(r.data?.tags) ? r.data.tags : [],
931
+ // 卡背面要显示一段「简介」:取自述的头一段,够长又不至于把整卡铺出来。
932
+ intro: String(core.sectionBody(r.sections, '自述') ?? '').replace(/\s+/g, ' ').trim().slice(0, 160),
736
933
  coverage: cov.percent,
737
934
  empty: cov.empty.map((e) => e.label),
738
935
  unmarkedRatio: cov.unmarkedRatio,
@@ -771,7 +968,327 @@ export async function listAll(root) {
771
968
  await walk('relations')
772
969
  await walk('materials')
773
970
 
774
- return { cards, worlds, systems, relations, errors, materials, redactions }
971
+ // 撤掉的卡现在搬去了回收目录,光扫原位不够。统一用 listWithdrawn 收口:
972
+ // 老式的(文件还在原地、只写了墓碑)和新式的(文件在回收目录)都在同一张表里。
973
+ return { cards, worlds, systems, relations, errors, materials, withdrawn: await listWithdrawn(root), redactions }
974
+ }
975
+
976
+ /**
977
+ * 拼一条「已经撤掉的」列表项:`{path, id, name, withdrawn_at}`。
978
+ *
979
+ * 名字和编号尽量从原文里取;原文读不出来就用文件名顶着——这一行
980
+ * 至少得让用户认得出是哪张卡,否则「能看见」等于没看见。
981
+ */
982
+ function withdrawnItem(rel, text, last) {
983
+ let id = ''
984
+ let name = ''
985
+ if (typeof text === 'string') {
986
+ const parsed = core.parseCard(text)
987
+ if (parsed.ok === true) {
988
+ id = String(parsed.data?.id ?? '')
989
+ name = String(parsed.data?.name ?? parsed.data?.nickname ?? '')
990
+ }
991
+ }
992
+ const base = path.posix.basename(rel).replace(/\.card\.md$/i, '')
993
+ return {
994
+ path: rel,
995
+ id: id === '' ? base : id,
996
+ name: name === '' ? base : name,
997
+ withdrawn_at: typeof last?.at === 'string' ? last.at : undefined,
998
+ }
999
+ }
1000
+
1001
+ /**
1002
+ * 原位还留着文件的老式撤掉卡:`{path, id, name, withdrawn_at}`。
1003
+ *
1004
+ * 当前不处于撤回态(最后一条是恢复/彻底删、或者内容已经换过而墓碑对不上)返回 null。
1005
+ */
1006
+ async function withdrawnEntry(root, redactions, rel) {
1007
+ const at = await resolveIn(root, rel)
1008
+ if (!at.ok) return null
1009
+ let text
1010
+ try {
1011
+ text = await fs.readFile(at.abs, 'utf8')
1012
+ } catch {
1013
+ text = undefined
1014
+ }
1015
+ const last = text === undefined
1016
+ ? lastRedactionByPath(redactions, rel)
1017
+ : lastRedaction(redactions, rel, text)
1018
+ if (!isWithdrawnRecord(last)) return null
1019
+ return withdrawnItem(rel, text, last)
1020
+ }
1021
+
1022
+ /**
1023
+ * 回收目录里的残份:`{path, id, name, withdrawn_at}`。
1024
+ *
1025
+ * 撤掉的卡已经搬走,所以「已撤掉」这一列既要从回收目录里找,也要照顾到
1026
+ * 老版本的账——那时候只写墓碑、文件留在原地。两条路都走,谁都别漏。
1027
+ */
1028
+ async function redactedEntry(root, redactions, rel, names) {
1029
+ const dirRel = path.posix.dirname(rel)
1030
+ const dirAbs = path.join(root, REDACTED_DIR, dirRel === '.' ? '' : dirRel)
1031
+ const text = await fs.readFile(path.join(dirAbs, names[0]), 'utf8').catch(() => undefined)
1032
+ const last = text === undefined
1033
+ ? lastRedactionByPath(redactions, rel)
1034
+ : lastRedaction(redactions, rel, text)
1035
+ // 账上说已经恢复/彻底删了:回收目录里这一份是没清干净的残渣,不算「正在撤着」。
1036
+ if (last !== undefined && !isWithdrawnRecord(last)) return null
1037
+ let at = typeof last?.at === 'string' ? last.at : undefined
1038
+ if (at === undefined) {
1039
+ const stat = await fs.stat(path.join(dirAbs, names[0])).catch(() => null)
1040
+ at = stat === null ? undefined : stat.mtime.toISOString()
1041
+ }
1042
+ const item = withdrawnItem(rel, text, last)
1043
+ item.withdrawn_at = at
1044
+ return item
1045
+ }
1046
+
1047
+ /**
1048
+ * 列出当前仍处于撤回态的 `.card.md`。
1049
+ *
1050
+ * 这条路存在的理由:`card.delete` 以前只写墓碑、不删文件,可界面和路由
1051
+ * 没有任何地方能把「已撤掉」的那批列出来,于是删掉的卡既不在列表里、
1052
+ * 也打不开、再点删除还报错——彻底删不掉,也恢复不了。列出来,两个动作
1053
+ * 才有地方发生。
1054
+ *
1055
+ * 只扫卡会出现的三个地方(people / self / worlds),和 listAll 一致;
1056
+ * 回收目录里同名多次的只算一条(最近那份),不然删三回就列三行。
1057
+ */
1058
+ export async function listWithdrawn(root) {
1059
+ const redactions = await readRedactions(root)
1060
+ const out = []
1061
+ const seen = new Set()
1062
+ const face = (rel) => path.posix.dirname(rel) === '.' ? '' : path.posix.dirname(rel)
1063
+ const walk = async (relDir) => {
1064
+ let entries
1065
+ try {
1066
+ entries = await fs.readdir(path.join(root, relDir), { withFileTypes: true })
1067
+ } catch {
1068
+ return
1069
+ }
1070
+ for (const entry of entries) {
1071
+ if (entry.name.startsWith('.')) continue
1072
+ const rel = path.posix.join(relDir.replace(/\\/g, '/'), entry.name)
1073
+ if (entry.isDirectory()) {
1074
+ await walk(rel)
1075
+ continue
1076
+ }
1077
+ if (!entry.name.toLowerCase().endsWith('.card.md')) continue
1078
+ const gone = await withdrawnEntry(root, redactions, rel)
1079
+ if (gone !== null && !seen.has(rel)) {
1080
+ seen.add(rel)
1081
+ out.push(gone)
1082
+ }
1083
+ }
1084
+ }
1085
+ await walk('people')
1086
+ await walk('self')
1087
+ await walk('worlds')
1088
+ // 回收目录:按目录树走一遍,同一个原位路径的多个残份归成一条。
1089
+ const walkTrash = async (relDir) => {
1090
+ let entries
1091
+ try {
1092
+ entries = await fs.readdir(path.join(root, REDACTED_DIR, relDir), { withFileTypes: true })
1093
+ } catch {
1094
+ return
1095
+ }
1096
+ for (const entry of entries) {
1097
+ const joined = relDir === '' ? entry.name : path.posix.join(relDir, entry.name)
1098
+ if (entry.isDirectory()) {
1099
+ await walkTrash(joined)
1100
+ continue
1101
+ }
1102
+ const m = /^(.*\.card\.md)(?:\..+)?$/i.exec(entry.name)
1103
+ if (m === null) continue
1104
+ const rel = path.posix.join(face(joined), m[1])
1105
+ if (seen.has(rel)) continue
1106
+ const names = await redactedCandidates(root, rel)
1107
+ if (names.length === 0) continue
1108
+ const gone = await redactedEntry(root, redactions, rel, names)
1109
+ if (gone !== null) {
1110
+ seen.add(rel)
1111
+ out.push(gone)
1112
+ }
1113
+ }
1114
+ }
1115
+ await walkTrash('')
1116
+ // 最近删的排前面:用户要恢复的多半是刚才手滑那一下。
1117
+ return out.sort((a, b) => String(b.withdrawn_at ?? '').localeCompare(String(a.withdrawn_at ?? '')))
1118
+ }
1119
+
1120
+ /**
1121
+ * 把撤掉的卡恢复回来:追加一条 `{kind:'restore', path}`,不动旧记录。
1122
+ *
1123
+ * 为什么是追加而不是删掉那条墓碑:`redactions.jsonl` 是只追加的账本,
1124
+ * 手改历史行会让「什么时候撤掉、什么时候又反悔」这件事无从追溯。
1125
+ *
1126
+ * 文件在回收目录里就搬回原位;老式的账(文件还在原地、只写了墓碑)照样能恢复。
1127
+ */
1128
+ /**
1129
+ * 「同一个地方」怎么算:卡按目录算(people/、某本世界书下的 cards/)。
1130
+ * 世界书是 `worlds/<id>/world.md`,id 由书名算出——按名字建会落到另一个目录,
1131
+ * 可它确实会和已有的那本重名,所以冲突范围是整棵 worlds/。
1132
+ */
1133
+ function conflictDir(relPath) {
1134
+ const rel = String(relPath ?? '').replace(/\\/g, '/')
1135
+ const dir = path.posix.dirname(rel)
1136
+ if (path.posix.basename(rel) === 'world.md' && dir !== 'worlds' && dir !== '.') {
1137
+ return path.posix.dirname(dir)
1138
+ }
1139
+ return dir
1140
+ }
1141
+
1142
+ /**
1143
+ * 同目录里有没有一张「名字或 id 一样」的撤掉的卡。
1144
+ *
1145
+ * 只比算出来的路径会漏:用户库里 `people/rat.card.md` 的 id 是拼音、名字是
1146
+ * 中文(「老鼠」),删掉以后按名字再建会算出另一个路径,两张同名的卡就并排
1147
+ * 出现在首页和「已经撤掉的」里,点「放回来」变成两张。所以按 name 与 id 各比一次。
1148
+ * 只在同一个目录里比:别的目录(比如另一本世界书下面)同名不算冲突。
1149
+ */
1150
+ export async function withdrawnNameHit(root, relPath, want) {
1151
+ const rel = String(relPath ?? '').replace(/\\/g, '/')
1152
+ const dir = conflictDir(rel)
1153
+ const wanted = (Array.isArray(want) ? want : [want])
1154
+ .map((v) => String(v ?? '').trim())
1155
+ .filter((v) => v !== '')
1156
+ if (wanted.length === 0) return null
1157
+ for (const one of await listWithdrawn(root)) {
1158
+ if (conflictDir(String(one.path ?? '')) !== dir) continue
1159
+ const id = String(one.id ?? '').trim()
1160
+ const name = String(one.name ?? '').trim()
1161
+ if (wanted.includes(id) || wanted.includes(name)) return one
1162
+ }
1163
+ // 世界书不在那张清单里(「已经撤掉的」只收卡),所以按账上记的路径再找一次。
1164
+ return await withdrawnWorldHit(root, await readRedactions(root), dir, wanted)
1165
+ }
1166
+
1167
+ /** 账上撤掉的路径里,所有世界书(`worlds/<id>/world.md`)的相对路径。 */
1168
+ function worldPathsFromRedactions(redactions) {
1169
+ const out = []
1170
+ for (const entry of redactions) {
1171
+ if (entry === null || typeof entry !== 'object') continue
1172
+ const rel = String(entry.path ?? '').replace(/\\/g, '/')
1173
+ if (rel !== '' && rel.toLowerCase().endsWith('world.md') && !out.includes(rel)) out.push(rel)
1174
+ }
1175
+ return out
1176
+ }
1177
+
1178
+ /** 一本撤掉的世界书叫什么:先看回收目录里那一份,再看原位还留着的那一份。 */
1179
+ async function withdrawnWorldName(root, rel) {
1180
+ const base = path.posix.basename(rel)
1181
+ const dirAbs = path.join(root, REDACTED_DIR, path.posix.dirname(rel))
1182
+ let names = []
1183
+ try {
1184
+ names = await fs.readdir(dirAbs)
1185
+ } catch {
1186
+ names = []
1187
+ }
1188
+ const tries = names
1189
+ .filter((one) => one === base || one.startsWith(base + '.'))
1190
+ .sort()
1191
+ .reverse()
1192
+ .map((one) => path.join(dirAbs, one))
1193
+ tries.push(path.join(root, rel))
1194
+ for (const abs of tries) {
1195
+ try {
1196
+ const got = core.parseCard(await fs.readFile(abs, 'utf8'))
1197
+ const name = String(got?.data?.name ?? '').trim()
1198
+ if (name !== '') return name
1199
+ } catch {
1200
+ // 读不出来就换下一份
1201
+ }
1202
+ }
1203
+ return null
1204
+ }
1205
+
1206
+ /** 同一个地方有没有一本「名字或 id 一样」的撤掉的世界书。 */
1207
+ async function withdrawnWorldHit(root, redactions, dir, wanted) {
1208
+ if (dir !== 'worlds') return null
1209
+ for (const rel of worldPathsFromRedactions(redactions)) {
1210
+ if (conflictDir(rel) !== dir) continue
1211
+ const hit = hitsRedactionByPath(redactions, rel)
1212
+ if (hit === undefined) continue
1213
+ const id = path.posix.basename(path.posix.dirname(rel))
1214
+ const name = (await withdrawnWorldName(root, rel)) ?? id
1215
+ if (wanted.includes(id) || wanted.includes(name)) {
1216
+ return { path: rel, id, name: String(name), withdrawn_at: hit.at }
1217
+ }
1218
+ }
1219
+ return null
1220
+ }
1221
+
1222
+ export async function restoreCard(root, relPath) {
1223
+ const rel = String(relPath ?? '')
1224
+ if (!rel.endsWith('.card.md')) return { ok: false, error: '这个位置不是一张卡。' }
1225
+ const at = await resolveIn(root, rel)
1226
+ if (!at.ok) return { ok: false, error: at.error }
1227
+ const exists = await fs.stat(at.abs).then((s) => s.isFile()).catch(() => false)
1228
+ // 回收目录里有残份就够了:搬回去只要 rename,不读内容也能搬。
1229
+ // 以前先看「读得出原文吗」,于是一张列在「已经撤掉的」里、但文件读不出来的卡
1230
+ // 点「放回来」会说「磁盘上找不到这张卡」——两句话互相矛盾。
1231
+ const candidates = exists ? [] : await redactedCandidates(root, rel)
1232
+ const redactions = await readRedactions(root)
1233
+ const text = exists ? await fs.readFile(at.abs, 'utf8').catch(() => undefined) : await readRedactedText(root, rel)
1234
+ if (!exists && candidates.length === 0 && text === undefined) {
1235
+ return { ok: false, error: '磁盘上找不到这张卡,恢复不了。它可能已经被彻底删掉了。' }
1236
+ }
1237
+ const last = text === undefined ? lastRedactionByPath(redactions, rel) : lastRedaction(redactions, rel, text)
1238
+ // 没有账的残份(早先版本留下的)也算撤着:能列进「已经撤掉的」,就得能放回来。
1239
+ const noRecord = last === undefined && candidates.length > 0
1240
+ if (!isWithdrawnRecord(last) && !noRecord) {
1241
+ // 没被撤掉的卡不该凭空多一条「恢复」记录:那会让下一次删除更难解释。
1242
+ return { ok: false, error: '这张卡现在没有被撤掉,不用恢复。' }
1243
+ }
1244
+ if (!exists) {
1245
+ const dirRel = path.posix.dirname(rel)
1246
+ const dirAbs = path.join(root, REDACTED_DIR, dirRel === '.' ? '' : dirRel)
1247
+ await fs.mkdir(path.dirname(at.abs), { recursive: true })
1248
+ await fs.rename(path.join(dirAbs, candidates[0]), at.abs)
1249
+ }
1250
+ await appendRedaction(root, { kind: 'restore', path: rel, reason: '用户恢复' })
1251
+ return { ok: true, path: rel, note: '已经恢复回来了,列表里又能看到它。' }
1252
+ }
1253
+
1254
+ /**
1255
+ * 彻底删掉一张撤掉的卡:真删磁盘文件(原位没有就清回收目录)。
1256
+ *
1257
+ * 只允许在**已经撤掉**的状态下做。多一道这个条件,是因为「彻底删」不可撤销:
1258
+ * 用户手滑点在列表里一张活卡上,就没法再反悔了。先撤掉(可恢复)、
1259
+ * 再从「已撤掉」里彻底删(用户已经看过一遍、确认过),是两步不同的决定。
1260
+ *
1261
+ * 删完追加一条 `{kind:'purge', path}`:不然名字永远被一条旧墓碑占着,
1262
+ * 用户清掉卡以后还是建不了同名的。
1263
+ */
1264
+ export async function purgeCard(root, relPath) {
1265
+ const rel = String(relPath ?? '')
1266
+ if (!rel.endsWith('.card.md')) return { ok: false, error: '只能彻底删掉卡片文件,别的文件不行。' }
1267
+ const at = await resolveIn(root, rel)
1268
+ if (!at.ok) return { ok: false, error: at.error }
1269
+ const exists = await fs.stat(at.abs).then((s) => s.isFile()).catch(() => false)
1270
+ const candidates = await redactedCandidates(root, rel)
1271
+ if (!exists && candidates.length === 0) {
1272
+ return { ok: false, error: '磁盘上已经没有这个文件了,不用再删。' }
1273
+ }
1274
+ const redactions = await readRedactions(root)
1275
+ const text = exists ? await fs.readFile(at.abs, 'utf8').catch(() => undefined) : await readRedactedText(root, rel)
1276
+ const last = text === undefined ? lastRedactionByPath(redactions, rel) : lastRedaction(redactions, rel, text)
1277
+ // 没有账的残份也允许清掉:否则它会永远挂在「已经撤掉的」里,点名删都删不掉。
1278
+ const noRecord = last === undefined && candidates.length > 0
1279
+ if (!isWithdrawnRecord(last) && !noRecord) {
1280
+ return { ok: false, error: '这张卡还在列表里。要彻底删掉,先从列表里删一次,再从「已经撤掉的」里彻底删。' }
1281
+ }
1282
+ if (exists) await fs.rm(at.abs, { force: true })
1283
+ const dirRel = path.posix.dirname(rel)
1284
+ const dirAbs = path.join(root, REDACTED_DIR, dirRel === '.' ? '' : dirRel)
1285
+ for (const name of candidates) await fs.rm(path.join(dirAbs, name), { force: true })
1286
+ // 历史版本也一起删。界面上三处都说「磁盘上的原文一起删,删了就真没了」,
1287
+ // 只删当前那份的话,旧版全文还躺在快照目录里,会跟着文件夹同步/备份跑到别处。
1288
+ // 目录名的扁平规则跟 readSnapshot 等地方保持一致,别另拼一套。
1289
+ await fs.rm(path.join(root, '.lifecard/snapshots', rel.replace(/[\\/]/g, '__')), { recursive: true, force: true })
1290
+ await appendRedaction(root, { kind: 'purge', path: rel, reason: '彻底删掉' })
1291
+ return { ok: true, path: rel, note: '已经彻底删掉了,磁盘上不留这个文件了。' }
775
1292
  }
776
1293
 
777
1294
  /**
@@ -871,6 +1388,11 @@ export async function deleteMaterial(root, rel) {
871
1388
  * 子目录也要读:listAll 会递归列出子目录里的材料,这里不递归的话
872
1389
  * 「列表里看得到、分析时用不到」,两边对不上。
873
1390
  */
1391
+ /** 这份文件是不是覆盖/写入时留下的残骸(`x.md.bak-1234`、`.x.md.tmp-123`)。 */
1392
+ export function isBackupName(name) {
1393
+ return /\.(bak|tmp)-/i.test(String(name ?? ''))
1394
+ }
1395
+
874
1396
  export async function readMaterials(root) {
875
1397
  const out = {}
876
1398
  const redactions = await readRedactions(root)
@@ -883,6 +1405,8 @@ export async function readMaterials(root) {
883
1405
  }
884
1406
  for (const entry of entries) {
885
1407
  if (entry.name.startsWith('.')) continue
1408
+ // 和列表同一口径:备份与临时残骸不是材料,别让旧版和现版一起进模型。
1409
+ if (isBackupName(entry.name)) continue
886
1410
  const rel = path.posix.join(relDir.replace(/\\/g, '/'), entry.name)
887
1411
  if (entry.isDirectory()) {
888
1412
  await walk(rel)
@@ -1043,7 +1567,28 @@ export async function saveProposal(root, aboutId, proposal, materials) {
1043
1567
  rejected: gate.rejected,
1044
1568
  }
1045
1569
  await fs.writeFile(abs(jsonRel), JSON.stringify(record, null, 2) + '\n', 'utf8')
1046
- return { ok: true, md: mdRel, json: jsonRel, accepted: gate.accepted.length, rejected: gate.rejected.length, gate }
1570
+ const why = rejectedReasons(gate.rejected)
1571
+ return {
1572
+ ok: true,
1573
+ md: mdRel,
1574
+ json: jsonRel,
1575
+ accepted: gate.accepted.length,
1576
+ rejected: gate.rejected.length,
1577
+ // 两种原因分开报:界面按这两个数分别说话,不再把「重复」说成「AI 编的」。
1578
+ rejectedDuplicate: why.duplicate,
1579
+ rejectedQuote: why.quote,
1580
+ gate,
1581
+ }
1582
+ }
1583
+
1584
+ /**
1585
+ * 被丢掉的那些条,为什么被丢:引文对不上,还是和前面那条重复?
1586
+ * 界面以前一律说「找不到原话」,可现在是两种原因——照旧说就成了骗人。
1587
+ */
1588
+ export function rejectedReasons(rejected) {
1589
+ const list = Array.isArray(rejected) ? rejected : []
1590
+ const duplicate = list.filter((one) => String(one?.reason ?? '').includes('重复')).length
1591
+ return { duplicate, quote: list.length - duplicate }
1047
1592
  }
1048
1593
 
1049
1594
  /** 渲染成勾选清单。**默认全部不勾**——勾选是人的动作。 */
@@ -1100,8 +1645,11 @@ export function renderProposalMarkdown({ aboutId, date, gate, proposal }) {
1100
1645
  if (gate.rejected.length > 0) {
1101
1646
  lines.push('## 已丢弃')
1102
1647
  lines.push('')
1103
- lines.push('下面这些**没有通过引文校验**(材料里找不到逐字对应),所以没进清单。')
1104
- lines.push('它们很可能是模型补出来的东西——这正是不让 AI 直接写卡的原因。')
1648
+ // 丢弃的原因现在有两种:引文对不上,或者和同一字段里另一条重复。
1649
+ // 只写「没通过引文校验」,用户看到一条明明能在材料里找到的句子被丢掉,
1650
+ // 会以为是程序坏了。
1651
+ lines.push('下面这些没进清单:**引文在材料里找不到逐字对应**的,或者**和同一字段里另一条重复**的。')
1652
+ lines.push('前者很可能是模型补出来的东西——这正是不让 AI 直接写卡的原因;后者留着只会让卡里同一件事说两遍。')
1105
1653
  lines.push('')
1106
1654
  for (const r of gate.rejected) {
1107
1655
  const what = describeValue(r.item)
@@ -1320,6 +1868,9 @@ export async function listProposals(root) {
1320
1868
  generated_at: record.generated_at,
1321
1869
  accepted: Array.isArray(record.accepted) ? record.accepted.length : 0,
1322
1870
  rejected: Array.isArray(record.rejected) ? record.rejected.length : 0,
1871
+ // 列表上那一行也要分得清「重复」和「引文对不上」。
1872
+ rejectedDuplicate: rejectedReasons(record.rejected).duplicate,
1873
+ rejectedQuote: rejectedReasons(record.rejected).quote,
1323
1874
  // 已经写进卡的条数:界面据此把「整份都采纳完了」的建议从待办里摘掉。
1324
1875
  adopted: (Array.isArray(record.accepted) ? record.accepted : [])
1325
1876
  .filter((i) => done.has(itemFingerprint(i))).length,
@@ -1359,6 +1910,15 @@ export async function applyProposal(root, jsonRel, options = {}) {
1359
1910
  const name = String(about.name ?? aboutId).trim() === '' ? aboutId : String(about.name).trim()
1360
1911
  const kind = ['real', 'fictional', 'hybrid', 'self'].includes(String(about.kind)) ? String(about.kind) : 'real'
1361
1912
  target = cardRelPath(aboutId, about.world)
1913
+ // 这个位置有一张被撤掉的卡:账上还记着它,名字也还占着。
1914
+ // 直接写会把它「复活」成一张只有提案内容的新卡,用户会觉得删了又自己回来了。
1915
+ // 按名字也要比:删掉的卡 id 可能是拼音(people/rat.card.md),只比路径会
1916
+ // 被当成「这个名字没人用」,于是采纳提案就把它悄悄复活成一张新卡。
1917
+ const blocked = hitsRedactionByPath(await readRedactions(root), target)
1918
+ const blockedBy = blocked !== undefined ? blocked : await withdrawnNameHit(root, target, [aboutId, name])
1919
+ if (blockedBy !== undefined && blockedBy !== null) {
1920
+ return { ok: false, error: '这张卡你删过一次。想重建就先到首页「已经撤掉的」里把它清掉。' }
1921
+ }
1362
1922
  const made = await writeCard(root, target, {
1363
1923
  lifecard: core.DATA_VERSION,
1364
1924
  id: aboutId,
@@ -1676,12 +2236,21 @@ export default {
1676
2236
  rememberMemoryPeople,
1677
2237
  memoryStatusOf,
1678
2238
  readRedactions,
2239
+ readRedactionsSync,
1679
2240
  appendRedaction,
2241
+ hitsRedaction,
2242
+ hitsRedactionByPath,
1680
2243
  sha256,
2244
+ moveCardToRedacted,
1681
2245
  cardRelPath,
1682
2246
  readCard,
1683
2247
  writeCard,
1684
2248
  listAll,
2249
+ isBackupName,
2250
+ listWithdrawn,
2251
+ withdrawnNameHit,
2252
+ restoreCard,
2253
+ purgeCard,
1685
2254
  appendMaterial,
1686
2255
  deleteMaterial,
1687
2256
  readMaterials,