whale-memory-core 0.11.2 → 0.15.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.
@@ -1,68 +1,69 @@
1
- // 她自己的记忆:统一读取她自己的经历、日记、自述;按相关度取回
2
- // 匹配口径和 self-experience.recall 是同一套(query-match.js):虚词不算、长查询要过比例门槛
3
- import fs from 'node:fs'
4
- import path from 'node:path'
5
- import { loadAll } from './self-experience.js'
6
- import { queryTerms, requiredOverlap, matchedTerms } from './query-match.js'
7
-
8
- function readJsonl(file) {
9
- try {
10
- return fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l) } catch { return null } }).filter(Boolean)
11
- } catch { return [] }
12
- }
13
-
14
- // 她自己的经历(自己的时间写的):走 loadAll,id 和后记都与 self-experience 一致
15
- export function loadExperiences(dir) {
16
- return loadAll(dir).map((r) => ({
17
- id: r.id,
18
- at: r.at || r.day || '',
19
- kind: r.kind || '其它',
20
- text: String(r.then.text || '').slice(0, 400),
21
- thought: String(r.then.thought || '').slice(0, 200),
22
- later: (r.later || []).map((l) => String(l.thought || '')).join(' '),
23
- origin: 'own-time',
24
- author: 'self'
25
- }))
26
- }
27
-
28
- // 她的日记(可能提到别人,默认只在主人私聊用)
29
- export function loadDiaries(dir) {
30
- return readJsonl(path.join(dir, 'autobiography.jsonl')).map((r) => ({
31
- id: 'diary_' + (r.day || '') + '_' + String(r.time || '').replace(/:/g, ''),
32
- at: r.day || '',
33
- kind: '日记',
34
- text: String(r.event || r.text || '').slice(0, 400),
35
- thought: '',
36
- origin: 'diary',
37
- author: 'self'
38
- })).filter((r) => r.text)
39
- }
40
-
41
- export function recall(dir, query, { includeDiary = false, limit = 4, minOverlap = 1, minRatio = 0.6, mode = 'strict' } = {}) {
42
- const pool = loadExperiences(dir).concat(includeDiary ? loadDiaries(dir) : [])
43
- const q = String(query || '')
44
- const parsed = queryTerms(q)
45
- const required = requiredOverlap(parsed, { mode, minOverlap, minRatio })
46
- const scored = pool.map((r) => ({ r, score: q ? matchedTerms(parsed.terms, [r.text, r.thought, r.later || ''].join(' ')).size : 0 }))
47
- .filter((x) => (q ? x.score >= required : true))
48
- .sort((a, b) => (b.score - a.score) || (String(b.r.at).localeCompare(String(a.r.at))))
49
- const out = [], seen = new Set()
50
- for (const x of scored) {
51
- if (seen.has(x.r.text)) continue
52
- seen.add(x.r.text)
53
- out.push(x.r)
54
- if (out.length >= limit) break
55
- }
56
- return out
57
- }
58
-
59
- export function renderBlock(items, { title = '【我的记忆(我自己的,不是谁告诉我的)】', maxChars = 320 } = {}) {
60
- if (!items || !items.length) return ''
61
- const lines = [title]
62
- for (const r of items) {
63
- const when = String(r.at || '').slice(5, 10)
64
- lines.push('- ' + (when ? when + ' ' : '') + String(r.text).slice(0, 70) + (r.thought ? '(当时想:' + String(r.thought).slice(0, 40) + ')' : ''))
65
- }
66
- const out = lines.join('\n')
67
- return out.length <= maxChars ? out : out.slice(0, maxChars - 1) + '…'
1
+ // 她自己的记忆:统一读取她自己的经历、日记、自述;按相关度取回
2
+ // 匹配口径和 self-experience.recall 是同一套(query-match.js):虚词不算、长查询要过比例门槛
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { loadAll } from './self-experience.js'
6
+ import { queryTerms, requiredOverlap, matchedTerms } from './query-match.js'
7
+
8
+ function readJsonl(file) {
9
+ try {
10
+ return fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l) } catch { return null } }).filter(Boolean)
11
+ } catch { return [] }
12
+ }
13
+
14
+ // 她自己的经历(自己的时间写的):走 loadAll,id 和后记都与 self-experience 一致
15
+ // 她封存了的不进这里:被问到"你自己"时不该把她不想再提的事翻出来
16
+ export function loadExperiences(dir) {
17
+ return loadAll(dir).filter((r) => !r.sealed).map((r) => ({
18
+ id: r.id,
19
+ at: r.at || r.day || '',
20
+ kind: r.kind || '其它',
21
+ text: String(r.then.text || '').slice(0, 400),
22
+ thought: String(r.then.thought || '').slice(0, 200),
23
+ later: (r.later || []).map((l) => String(l.thought || '')).join(' '),
24
+ origin: 'own-time',
25
+ author: 'self'
26
+ }))
27
+ }
28
+
29
+ // 她的日记(可能提到别人,默认只在主人私聊用)
30
+ export function loadDiaries(dir) {
31
+ return readJsonl(path.join(dir, 'autobiography.jsonl')).map((r) => ({
32
+ id: 'diary_' + (r.day || '') + '_' + String(r.time || '').replace(/:/g, ''),
33
+ at: r.day || '',
34
+ kind: '日记',
35
+ text: String(r.event || r.text || '').slice(0, 400),
36
+ thought: '',
37
+ origin: 'diary',
38
+ author: 'self'
39
+ })).filter((r) => r.text)
40
+ }
41
+
42
+ export function recall(dir, query, { includeDiary = false, limit = 4, minOverlap = 1, minRatio = 0.6, mode = 'strict' } = {}) {
43
+ const pool = loadExperiences(dir).concat(includeDiary ? loadDiaries(dir) : [])
44
+ const q = String(query || '')
45
+ const parsed = queryTerms(q)
46
+ const required = requiredOverlap(parsed, { mode, minOverlap, minRatio })
47
+ const scored = pool.map((r) => ({ r, score: q ? matchedTerms(parsed.terms, [r.text, r.thought, r.later || ''].join(' ')).size : 0 }))
48
+ .filter((x) => (q ? x.score >= required : true))
49
+ .sort((a, b) => (b.score - a.score) || (String(b.r.at).localeCompare(String(a.r.at))))
50
+ const out = [], seen = new Set()
51
+ for (const x of scored) {
52
+ if (seen.has(x.r.text)) continue
53
+ seen.add(x.r.text)
54
+ out.push(x.r)
55
+ if (out.length >= limit) break
56
+ }
57
+ return out
58
+ }
59
+
60
+ export function renderBlock(items, { title = '【我的记忆(我自己的,不是谁告诉我的)】', maxChars = 320 } = {}) {
61
+ if (!items || !items.length) return ''
62
+ const lines = [title]
63
+ for (const r of items) {
64
+ const when = String(r.at || '').slice(5, 10)
65
+ lines.push('- ' + (when ? when + ' ' : '') + String(r.text).slice(0, 70) + (r.thought ? '(当时想:' + String(r.thought).slice(0, 40) + ')' : ''))
66
+ }
67
+ const out = lines.join('\n')
68
+ return out.length <= maxChars ? out : out.slice(0, maxChars - 1) + '…'
68
69
  }
@@ -1,26 +1,27 @@
1
- export type UnfinishedChoice = 'done' | 'shelved' | 'reopen'
2
-
3
- export const CHOICES: Set<UnfinishedChoice>
4
-
5
- export interface UnfinishedEvent {
6
- id: string
7
- at: string
8
- day: string
9
- choice: UnfinishedChoice
10
- note: string
11
- }
12
-
13
- export interface UnfinishedLatest {
14
- id: string
15
- at: string
16
- day: string
17
- choice: UnfinishedChoice | ''
18
- note: string
19
- history: UnfinishedChoice[]
20
- }
21
-
22
- export function eventsFile(memDir: string): string
23
- export function append(memDir: string, opts: { id: string; choice: UnfinishedChoice; note?: string }, lockOpts?: Record<string, unknown>): UnfinishedEvent
24
- export function readAll(memDir: string): { rows: UnfinishedEvent[]; bad: number }
25
- export function latestByExp(memDir: string): Map<string, UnfinishedLatest>
1
+ export type UnfinishedChoice = 'done' | 'shelved' | 'reopen'
2
+
3
+ export const CHOICES: Set<UnfinishedChoice>
4
+
5
+ export interface UnfinishedEvent {
6
+ id: string
7
+ at: string
8
+ day: string
9
+ choice: UnfinishedChoice
10
+ note: string
11
+ }
12
+
13
+ export interface UnfinishedLatest {
14
+ id: string
15
+ at: string
16
+ day: string
17
+ choice: UnfinishedChoice | ''
18
+ note: string
19
+ history: UnfinishedChoice[]
20
+ }
21
+
22
+ export function eventsFile(memDir: string): string
23
+ export function append(memDir: string, opts: { id: string; choice: UnfinishedChoice; note?: string }, lockOpts?: Record<string, unknown>): UnfinishedEvent
24
+ export function readAll(memDir: string): { rows: UnfinishedEvent[]; bad: number }
25
+ /** until:按这一刻(毫秒时间戳)之前(含)的选择重放 */
26
+ export function latestByExp(memDir: string, opts?: { until?: number | null }): Map<string, UnfinishedLatest>
26
27
  export function countByExp(memDir: string): Map<string, number>
@@ -1,103 +1,106 @@
1
- // 「这件没弄完的事」后来怎么样了:想通 / 先放下 / 再接着想
2
- // 一行一个 { id, at, day, choice, note? },只追加;不改 then.unfinished,也不冒充后记
3
- import fs from 'node:fs'
4
- import path from 'node:path'
5
- import { withFileLock } from './file-lock.js'
6
-
7
- const FILE = 'unfinished-events.jsonl'
8
- export const CHOICES = new Set(['done', 'shelved', 'reopen'])
9
-
10
- export function eventsFile(memDir) {
11
- return path.join(memDir, FILE)
12
- }
13
-
14
- function makeRow({ id, choice, note }) {
15
- const now = new Date()
16
- return {
17
- id: String(id),
18
- at: now.toISOString(),
19
- day: now.toLocaleDateString('sv-SE'),
20
- choice,
21
- note: String(note || '').slice(0, 200)
22
- }
23
- }
24
-
25
- // 调用前必须已经持有锁;append 和 decide 共用这一层,避免同一次选择被锁外读到两次
26
- function appendUnlocked(memDir, row) {
27
- const file = eventsFile(memDir)
28
- let prefix = ''
29
- try {
30
- const st = fs.statSync(file)
31
- if (st.size) {
32
- const fd = fs.openSync(file, 'r')
33
- const buf = Buffer.alloc(1)
34
- fs.readSync(fd, buf, 0, 1, st.size - 1)
35
- fs.closeSync(fd)
36
- if (buf[0] !== 10) prefix = '\n'
37
- }
38
- } catch { }
39
- fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
40
- return row
41
- }
42
-
43
- export function append(memDir, { id, choice, note = '' } = {}, opts = {}) {
44
- if (!String(id || '').trim()) throw new Error('id 不能为空')
45
- if (!CHOICES.has(choice)) throw new Error('choice 只能是 done / shelved / reopen')
46
- const row = makeRow({ id, choice, note })
47
- fs.mkdirSync(memDir, { recursive: true })
48
- return withFileLock(eventsFile(memDir) + '.lock', () => appendUnlocked(memDir, row), opts)
49
- }
50
-
51
- // 在同一个锁里「重读最近状态 → 判断 → 追加」:
52
- // 两个进程同时提交同一选择,第二个会看到第一个的结果并返回 noop,不会写出第二条
53
- export function decide(memDir, { id, choice, note = '' } = {}, opts = {}) {
54
- if (!String(id || '').trim()) throw new Error('id 不能为空')
55
- if (!CHOICES.has(choice)) throw new Error('choice 只能是 done / shelved / reopen')
56
- fs.mkdirSync(memDir, { recursive: true })
57
- return withFileLock(eventsFile(memDir) + '.lock', () => {
58
- const rows = readAll(memDir).rows.filter((r) => r.id === String(id))
59
- const last = rows[rows.length - 1] || null
60
- if (last && last.choice === choice) return { row: last, noop: true }
61
- if (choice === 'reopen' && !last) return { row: null, noop: true }
62
- return { row: appendUnlocked(memDir, makeRow({ id, choice, note })), noop: false }
63
- }, opts)
64
- }
65
-
66
- export function readAll(memDir) {
67
- let raw = ''
68
- try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
69
- const rows = []
70
- let bad = 0
71
- for (const line of raw.split('\n')) {
72
- if (!line.trim()) continue
73
- try {
74
- const r = JSON.parse(line)
75
- if (r && r.id && CHOICES.has(r.choice)) rows.push(r)
76
- else bad += 1
77
- } catch { bad += 1 }
78
- }
79
- return { rows, bad }
80
- }
81
-
82
- // 每个经历 id 的最新状态,附带完整的选择历史(渲染"中间放下过"要用)
83
- export function latestByExp(memDir) {
84
- const { rows } = readAll(memDir)
85
- const map = new Map()
86
- for (const r of rows) {
87
- const cur = map.get(r.id) || { id: r.id, at: '', day: '', choice: '', note: '', history: [] }
88
- cur.at = r.at
89
- cur.day = r.day
90
- cur.choice = r.choice
91
- cur.note = r.note || ''
92
- cur.history.push(r.choice)
93
- map.set(r.id, cur)
94
- }
95
- return map
96
- }
97
-
98
- export function countByExp(memDir) {
99
- const { rows } = readAll(memDir)
100
- const map = new Map()
101
- for (const r of rows) map.set(r.id, (map.get(r.id) || 0) + 1)
102
- return map
1
+ // 「这件没弄完的事」后来怎么样了:想通 / 先放下 / 再接着想
2
+ // 一行一个 { id, at, day, choice, note? },只追加;不改 then.unfinished,也不冒充后记
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { withFileLock } from './file-lock.js'
6
+ import { before } from './as-of.js'
7
+
8
+ const FILE = 'unfinished-events.jsonl'
9
+ export const CHOICES = new Set(['done', 'shelved', 'reopen'])
10
+
11
+ export function eventsFile(memDir) {
12
+ return path.join(memDir, FILE)
13
+ }
14
+
15
+ function makeRow({ id, choice, note }) {
16
+ const now = new Date()
17
+ return {
18
+ id: String(id),
19
+ at: now.toISOString(),
20
+ day: now.toLocaleDateString('sv-SE'),
21
+ choice,
22
+ note: String(note || '').slice(0, 200)
23
+ }
24
+ }
25
+
26
+ // 调用前必须已经持有锁;append 和 decide 共用这一层,避免同一次选择被锁外读到两次
27
+ function appendUnlocked(memDir, row) {
28
+ const file = eventsFile(memDir)
29
+ let prefix = ''
30
+ try {
31
+ const st = fs.statSync(file)
32
+ if (st.size) {
33
+ const fd = fs.openSync(file, 'r')
34
+ const buf = Buffer.alloc(1)
35
+ fs.readSync(fd, buf, 0, 1, st.size - 1)
36
+ fs.closeSync(fd)
37
+ if (buf[0] !== 10) prefix = '\n'
38
+ }
39
+ } catch { }
40
+ fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
41
+ return row
42
+ }
43
+
44
+ export function append(memDir, { id, choice, note = '' } = {}, opts = {}) {
45
+ if (!String(id || '').trim()) throw new Error('id 不能为空')
46
+ if (!CHOICES.has(choice)) throw new Error('choice 只能是 done / shelved / reopen')
47
+ const row = makeRow({ id, choice, note })
48
+ fs.mkdirSync(memDir, { recursive: true })
49
+ return withFileLock(eventsFile(memDir) + '.lock', () => appendUnlocked(memDir, row), opts)
50
+ }
51
+
52
+ // 在同一个锁里「重读最近状态 → 判断 → 追加」:
53
+ // 两个进程同时提交同一选择,第二个会看到第一个的结果并返回 noop,不会写出第二条
54
+ export function decide(memDir, { id, choice, note = '' } = {}, opts = {}) {
55
+ if (!String(id || '').trim()) throw new Error('id 不能为空')
56
+ if (!CHOICES.has(choice)) throw new Error('choice 只能是 done / shelved / reopen')
57
+ fs.mkdirSync(memDir, { recursive: true })
58
+ return withFileLock(eventsFile(memDir) + '.lock', () => {
59
+ const rows = readAll(memDir).rows.filter((r) => r.id === String(id))
60
+ const last = rows[rows.length - 1] || null
61
+ if (last && last.choice === choice) return { row: last, noop: true }
62
+ if (choice === 'reopen' && !last) return { row: null, noop: true }
63
+ return { row: appendUnlocked(memDir, makeRow({ id, choice, note })), noop: false }
64
+ }, opts)
65
+ }
66
+
67
+ export function readAll(memDir) {
68
+ let raw = ''
69
+ try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
70
+ const rows = []
71
+ let bad = 0
72
+ for (const line of raw.split('\n')) {
73
+ if (!line.trim()) continue
74
+ try {
75
+ const r = JSON.parse(line)
76
+ if (r && r.id && CHOICES.has(r.choice)) rows.push(r)
77
+ else bad += 1
78
+ } catch { bad += 1 }
79
+ }
80
+ return { rows, bad }
81
+ }
82
+
83
+ // 每个经历 id 的最新状态,附带完整的选择历史(渲染"中间放下过"要用)
84
+ // until:按这一刻之前(含)的选择重放,「翻回那天的自己」用
85
+ export function latestByExp(memDir, { until = null } = {}) {
86
+ const { rows } = readAll(memDir)
87
+ const map = new Map()
88
+ for (const r of rows) {
89
+ if (!before(r, until)) continue
90
+ const cur = map.get(r.id) || { id: r.id, at: '', day: '', choice: '', note: '', history: [] }
91
+ cur.at = r.at
92
+ cur.day = r.day
93
+ cur.choice = r.choice
94
+ cur.note = r.note || ''
95
+ cur.history.push(r.choice)
96
+ map.set(r.id, cur)
97
+ }
98
+ return map
99
+ }
100
+
101
+ export function countByExp(memDir) {
102
+ const { rows } = readAll(memDir)
103
+ const map = new Map()
104
+ for (const r of rows) map.set(r.id, (map.get(r.id) || 0) + 1)
105
+ return map
103
106
  }
@@ -0,0 +1,28 @@
1
+ export type UnsaidKind = 'draft' | 'question' | 'held'
2
+ export type UnsaidStatus = 'open' | 'spoken' | 'discarded'
3
+
4
+ export const KINDS: Set<UnsaidKind>
5
+ export const LIMITS: { text: number; reason: number }
6
+
7
+ export interface UnsaidItem {
8
+ id: string
9
+ day: string
10
+ kind: UnsaidKind
11
+ text: string
12
+ reason: string
13
+ status: 'open' | 'spoken'
14
+ spokenDay?: string
15
+ }
16
+
17
+ type Fail = { ok: false; error: string }
18
+
19
+ /** 只在认得出的一对一会话里可用;同 kind 同原文还开着时重复提交是 noop */
20
+ export function leaveUnsaid(dir: string, opts: { chatKey: string; kind?: UnsaidKind; text: string; reason?: string }): { ok: true; id: string; day?: string; noop: boolean } | Fail
21
+ /** 默认只给开着的;all=true 连说出口的也给。丢掉的从不给 */
22
+ export function listUnsaid(dir: string, opts: { chatKey: string; all?: boolean }): { ok: true; items: UnsaidItem[] } | Fail
23
+ export function markUnsaidSpoken(dir: string, opts: { chatKey: string; id: string }): { ok: true; id: string; status: 'spoken'; noop: boolean } | Fail
24
+ export function discardUnsaid(dir: string, opts: { chatKey: string; id: string }): { ok: true; id: string; status: 'discarded'; noop: boolean } | Fail
25
+ /** 坏行数,只给数字 */
26
+ export function badLines(dir: string): number
27
+ export function eventsFile(dir: string): string
28
+ export const internals: { FILE: string }
package/lib/unsaid.js ADDED
@@ -0,0 +1,105 @@
1
+ // 没说出口的抽屉:打了没发的(draft)、想问没问的(question)、忍住了的(held)
2
+ // unsaid-events.jsonl 只追加:留下时一行 {id, at, day, kind, text, reason, status:'open'};
3
+ // 后来说出口了 / 不想要了,各追加一行 {id, at, day, status:'spoken'|'discarded'}。原文从不删除
4
+ //
5
+ // 这个抽屉永不自动打开:recall、醒来块、read、memory、recap、book 都不读这个文件。
6
+ // 只有 listUnsaid 给她看,而且只在认得出的一对一会话里;丢掉(discarded)的,她自己也看不到了。
7
+ // 为了不让原文从"原始接口"漏出去,这里不导出任何返回原始行的函数
8
+ import { createLog, stamp } from './event-log.js'
9
+ import { isPrivateKey } from './waking.js'
10
+
11
+ export const KINDS = new Set(['draft', 'question', 'held'])
12
+ const STATUSES = new Set(['open', 'spoken', 'discarded'])
13
+ export const LIMITS = { text: 1000, reason: 200 }
14
+
15
+ const log = createLog('unsaid-events.jsonl', {
16
+ valid: (r) => Boolean(r.id && STATUSES.has(r.status) && (r.status !== 'open' || (KINDS.has(r.kind) && r.text)))
17
+ })
18
+ export const eventsFile = log.eventsFile
19
+ export const internals = { FILE: log.FILE }
20
+
21
+ // 坏行数(给 doctor 用);只给数字,不给内容
22
+ export const badLines = (dir) => log.readAll(dir).bad
23
+
24
+ function gate(chatKey) {
25
+ if (!isPrivateKey(chatKey)) throw new Error('这个抽屉只在一对一的私聊里打开;群聊和认不出的会话一律不给。')
26
+ }
27
+
28
+ // 重放:每条留下的话现在是什么状态
29
+ function replay(rows) {
30
+ const map = new Map()
31
+ for (const r of rows) {
32
+ if (r.status === 'open') {
33
+ if (!map.has(r.id)) map.set(r.id, { id: r.id, at: r.at, day: r.day, kind: r.kind, text: r.text, reason: r.reason || '', status: 'open', history: [] })
34
+ continue
35
+ }
36
+ const item = map.get(r.id)
37
+ if (!item) continue
38
+ item.status = r.status
39
+ item.history.push({ status: r.status, at: r.at, day: r.day })
40
+ }
41
+ return map
42
+ }
43
+
44
+ const fail = (e) => ({ ok: false, error: String(e && e.message ? e.message : e) })
45
+ const tooLong = (name, v, max) => {
46
+ const s = String(v || '')
47
+ if ([...s].length > max) throw new Error(`${name} 太长(${[...s].length}/${max} 字)。`)
48
+ return s
49
+ }
50
+
51
+ // 留下一句没说出口的话。同一句(同 kind、同原文)还开着时,重复提交是 noop
52
+ export function leaveUnsaid(dir, { chatKey, kind = 'draft', text, reason = '' } = {}) {
53
+ try {
54
+ gate(chatKey)
55
+ if (!KINDS.has(kind)) throw new Error('kind 只能是 draft(打了没发)/ question(想问没问)/ held(忍住了)。')
56
+ const t = tooLong('text', String(text || '').trim(), LIMITS.text)
57
+ if (!t) throw new Error('text 不能是空的。')
58
+ const why = tooLong('reason', String(reason || '').trim(), LIMITS.reason)
59
+ const res = log.decide(dir, (rows) => {
60
+ const same = [...replay(rows).values()].find((x) => x.status === 'open' && x.kind === kind && x.text === t)
61
+ if (same) return null
62
+ return { id: 'unsaid_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), ...stamp(), kind, text: t, reason: why, status: 'open' }
63
+ })
64
+ if (res.noop) {
65
+ const same = [...replay(log.readAll(dir).rows).values()].find((x) => x.status === 'open' && x.kind === kind && x.text === t)
66
+ return { ok: true, id: same ? same.id : '', noop: true }
67
+ }
68
+ return { ok: true, id: res.row.id, day: res.row.day, noop: false }
69
+ } catch (e) { return fail(e) }
70
+ }
71
+
72
+ // 打开抽屉:默认只给还开着的;all=true 时连说出口了的也给(带上哪天说的)。丢掉的从不给
73
+ export function listUnsaid(dir, { chatKey, all = false } = {}) {
74
+ try {
75
+ gate(chatKey)
76
+ const items = [...replay(log.readAll(dir).rows).values()]
77
+ .filter((x) => x.status === 'open' || (all && x.status === 'spoken'))
78
+ .map((x) => {
79
+ const spoken = x.history.filter((h) => h.status === 'spoken').pop()
80
+ return { id: x.id, day: x.day, kind: x.kind, text: x.text, reason: x.reason, status: x.status, ...(spoken ? { spokenDay: spoken.day } : {}) }
81
+ })
82
+ return { ok: true, items }
83
+ } catch (e) { return fail(e) }
84
+ }
85
+
86
+ function mark(dir, { chatKey, id }, status) {
87
+ try {
88
+ gate(chatKey)
89
+ if (!String(id || '').trim()) throw new Error('需要 id')
90
+ const res = log.decide(dir, (rows) => {
91
+ const item = replay(rows).get(String(id))
92
+ if (!item) throw new Error('抽屉里没有这一条:' + id)
93
+ if (item.status === status) return null
94
+ if (item.status === 'discarded') throw new Error('这一条已经丢掉了。')
95
+ return { id: String(id), ...stamp(), status }
96
+ })
97
+ return { ok: true, id: String(id), status, noop: res.noop }
98
+ } catch (e) { return fail(e) }
99
+ }
100
+
101
+ // 后来说出口了:原文还在,状态变成 spoken;重复标记不写第二条
102
+ export const markUnsaidSpoken = (dir, opts = {}) => mark(dir, opts, 'spoken')
103
+
104
+ // 不想要了:原文不删,但之后她自己也看不到;重复丢不写第二条
105
+ export const discardUnsaid = (dir, opts = {}) => mark(dir, opts, 'discarded')