whale-memory-core 0.15.0 → 0.19.1
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/README.md +14 -0
- package/bin/whale-memory-mcp.mjs +276 -0
- package/demo.mjs +44 -33
- package/index.d.ts +19 -15
- package/index.js +21 -17
- package/lib/archive.d.ts +22 -22
- package/lib/archive.js +171 -135
- package/lib/as-of.d.ts +5 -5
- package/lib/as-of.js +32 -32
- package/lib/book.d.ts +4 -4
- package/lib/book.js +75 -75
- package/lib/chapter-events.d.ts +39 -39
- package/lib/chapter-events.js +89 -89
- package/lib/detail-recall.d.ts +15 -0
- package/lib/detail-recall.js +174 -0
- package/lib/event-log.d.ts +10 -10
- package/lib/event-log.js +61 -61
- package/lib/evidence-from-experience.d.ts +8 -8
- package/lib/evidence-from-experience.js +62 -62
- package/lib/evidence-policy.js +2 -2
- package/lib/fact-timeline-contract.d.ts +73 -0
- package/lib/fact-timeline-contract.js +226 -0
- package/lib/fact-timeline-query.d.ts +29 -0
- package/lib/fact-timeline-query.js +97 -0
- package/lib/file-lock.js +1 -1
- package/lib/later-events.d.ts +21 -21
- package/lib/later-events.js +80 -80
- package/lib/link-events.d.ts +15 -15
- package/lib/link-events.js +33 -33
- package/lib/person-card.d.ts +4 -0
- package/lib/person-card.js +179 -0
- package/lib/query-match.js +55 -0
- package/lib/recall-events.d.ts +24 -24
- package/lib/recall-events.js +97 -97
- package/lib/recap.d.ts +23 -23
- package/lib/recap.js +79 -79
- package/lib/relative-window.d.ts +4 -0
- package/lib/relative-window.js +123 -0
- package/lib/seal-events.d.ts +25 -25
- package/lib/seal-events.js +82 -82
- package/lib/self-experience.d.ts +180 -175
- package/lib/self-experience.js +624 -560
- package/lib/self-memory.js +70 -68
- package/lib/self-prompt.js +8 -4
- package/lib/self-settings.js +2 -2
- package/lib/time-sense.d.ts +6 -0
- package/lib/time-sense.js +89 -0
- package/lib/unfinished-events.d.ts +26 -26
- package/lib/unfinished-events.js +105 -105
- package/lib/unsaid.d.ts +28 -28
- package/lib/unsaid.js +105 -105
- package/lib/waking.d.ts +1 -1
- package/lib/waking.js +99 -92
- package/package.json +139 -113
package/lib/self-memory.js
CHANGED
|
@@ -1,69 +1,71 @@
|
|
|
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
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
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, contentUnits, coverage, MIN_COVER } 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 units = contentUnits(q)
|
|
48
|
+
const scored = pool.map((r) => { const text = [r.text, r.thought, r.later || ''].join(' '); return { r, score: q ? matchedTerms(parsed.terms, text).size : 0, cover: q ? coverage(units, text) : 0 } })
|
|
49
|
+
// 与 self-experience 同一口径:strict 要求意思被接住至少 MIN_COVER
|
|
50
|
+
.filter((x) => (!q ? true : mode === 'loose' ? x.score >= required : x.score >= minOverlap && x.cover >= MIN_COVER))
|
|
51
|
+
.sort((a, b) => (b.score - a.score) || (String(b.r.at).localeCompare(String(a.r.at))))
|
|
52
|
+
const out = [], seen = new Set()
|
|
53
|
+
for (const x of scored) {
|
|
54
|
+
if (seen.has(x.r.text)) continue
|
|
55
|
+
seen.add(x.r.text)
|
|
56
|
+
out.push(x.r)
|
|
57
|
+
if (out.length >= limit) break
|
|
58
|
+
}
|
|
59
|
+
return out
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function renderBlock(items, { title = '【我的记忆(我自己的,不是谁告诉我的)】', maxChars = 320 } = {}) {
|
|
63
|
+
if (!items || !items.length) return ''
|
|
64
|
+
const lines = [title]
|
|
65
|
+
for (const r of items) {
|
|
66
|
+
const when = String(r.at || '').slice(5, 10)
|
|
67
|
+
lines.push('- ' + (when ? when + ' ' : '') + String(r.text).slice(0, 70) + (r.thought ? '(当时想:' + String(r.thought).slice(0, 40) + ')' : ''))
|
|
68
|
+
}
|
|
69
|
+
const out = lines.join('\n')
|
|
70
|
+
return out.length <= maxChars ? out : out.slice(0, maxChars - 1) + '…'
|
|
69
71
|
}
|
package/lib/self-prompt.js
CHANGED
|
@@ -41,8 +41,8 @@ export function load(dataDir) {
|
|
|
41
41
|
|
|
42
42
|
export function save(dataDir, text, reason = '', opts = {}) {
|
|
43
43
|
const body = clean(text)
|
|
44
|
-
if (!body) return { ok: false, error: '
|
|
45
|
-
if (body.length > MAX_CHARS) return { ok: false, error: '
|
|
44
|
+
if (!body) return { ok: false, error: 'Empty, nothing written.(空的,不写。)' }
|
|
45
|
+
if (body.length > MAX_CHARS) return { ok: false, error: 'Too long (' + body.length + '/' + MAX_CHARS + ' chars); shorten it and try again.(太长了(' + body.length + '/' + MAX_CHARS + ' 字),删一些再试。)' }
|
|
46
46
|
|
|
47
47
|
const current = load(dataDir)
|
|
48
48
|
if (current === body) return { ok: true, noop: true, reason: '和当前版本一样,没有写入。' }
|
|
@@ -83,10 +83,14 @@ export function history(dataDir, limit = 10) {
|
|
|
83
83
|
|
|
84
84
|
export function revert(dataDir, version, reason = '') {
|
|
85
85
|
try {
|
|
86
|
+
const key = String(version)
|
|
87
|
+
// 只接受 history.jsonl 里真实出现过的快照名:不把调用方给的字符串直接拼进路径
|
|
88
|
+
const known = history(dataDir, 100000).some((h) => String(h.snapshot) === key)
|
|
89
|
+
if (!known) return { ok: false, error: 'Version not found.(找不到这个版本。)' }
|
|
86
90
|
const d = base(dataDir)
|
|
87
|
-
const body = fs.readFileSync(path.join(d, VERSIONS,
|
|
91
|
+
const body = fs.readFileSync(path.join(d, VERSIONS, key + '.md'), 'utf8')
|
|
88
92
|
return save(dataDir, body, reason || ('回退到 ' + version))
|
|
89
|
-
} catch { return { ok: false, error: '
|
|
93
|
+
} catch { return { ok: false, error: 'Version not found.(找不到这个版本。)' } }
|
|
90
94
|
}
|
|
91
95
|
|
|
92
96
|
// 生效内容 = 默认段 + 她的 overlay;超总长会明确报告截断,不悄悄切
|
package/lib/self-settings.js
CHANGED
|
@@ -25,7 +25,7 @@ function readSaved(f) {
|
|
|
25
25
|
const j = JSON.parse(raw)
|
|
26
26
|
if (j && typeof j === 'object' && !Array.isArray(j)) return j
|
|
27
27
|
} catch { }
|
|
28
|
-
throw new Error('
|
|
28
|
+
throw new Error('Settings file is corrupted (' + f + '); back it up and fix it before changing settings, so her saved settings are not overwritten.(设置文件损坏(' + f + '),先备份并修好再改,避免把她改过的设置冲掉。)')
|
|
29
29
|
}
|
|
30
30
|
|
|
31
31
|
// 读的时候宽容:坏了就先按默认跑,不让宿主起不来;写的时候才严格
|
|
@@ -34,7 +34,7 @@ export function load(dataDir) {
|
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
export function save(dataDir, patch, reason = '') {
|
|
37
|
-
if (!patch || typeof patch !== 'object' || Array.isArray(patch)) throw new Error('
|
|
37
|
+
if (!patch || typeof patch !== 'object' || Array.isArray(patch)) throw new Error('Settings must be an object, e.g. {"readingPerDay": 50}.(设置要是一个对象,例如 {"readingPerDay": 50}。)')
|
|
38
38
|
const f = fileOf(dataDir)
|
|
39
39
|
fs.mkdirSync(path.dirname(f), { recursive: true })
|
|
40
40
|
const next = withFileLock(f + '.lock', () => {
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** 「刚刚 / 12 分钟前 / 今天 09:12 / 昨天 20:30 / 3 天前 / 上周三 / 2 个月前 / 2025-08-01」 */
|
|
2
|
+
export function humanTime(ts: number | string | null | undefined, options?: { now?: number }): string
|
|
3
|
+
/** 只要时长,不要时刻:「刚刚 / 12 分钟前 / 3 小时前 / 昨天 / 4 天前」 */
|
|
4
|
+
export function timeAgo(ts: number | string | null | undefined, options?: { now?: number }): string
|
|
5
|
+
/** 本地日历日差:0=今天,1=昨天,2=前天 */
|
|
6
|
+
export function dayDiff(ts: number, now?: number): number | null
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 人话时间:把时间戳说成她该听见的样子——「昨天 20:30」「上周三」「3 天前」,而不是「11-20 20:30」。
|
|
3
|
+
*
|
|
4
|
+
* 为什么要单独一层:她答「前几天那个事」时,需要的是「这属于哪一天」,而不是一个日期字符串。
|
|
5
|
+
* 纯函数,无 IO。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
function toMs(ts) {
|
|
9
|
+
const n = Number(ts);
|
|
10
|
+
if (!Number.isFinite(n) || n <= 0) return 0;
|
|
11
|
+
return n >= 1e11 ? n : n * 1000; // 秒 → 毫秒
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function pad(n) {
|
|
15
|
+
return String(n).padStart(2, '0');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function clock(d) {
|
|
19
|
+
return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 本地日历日差:0=今天,1=昨天,2=前天…… */
|
|
23
|
+
export function dayDiff(ts, now = Date.now()) {
|
|
24
|
+
const a = toMs(ts);
|
|
25
|
+
const b = toMs(now);
|
|
26
|
+
if (!a || !b) return null;
|
|
27
|
+
const da = new Date(a);
|
|
28
|
+
const db = new Date(b);
|
|
29
|
+
const startA = new Date(da.getFullYear(), da.getMonth(), da.getDate()).getTime();
|
|
30
|
+
const startB = new Date(db.getFullYear(), db.getMonth(), db.getDate()).getTime();
|
|
31
|
+
return Math.round((startB - startA) / 86400000);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const WEEK = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 「人话」时间。
|
|
38
|
+
* @param {number} ts 时间戳(秒或毫秒)
|
|
39
|
+
* @param {object} [options] {now}
|
|
40
|
+
* @returns {string} 例:刚刚 / 12 分钟前 / 今天 09:12 / 昨天 20:30 / 前天 18:40 / 3 天前 / 上周三 / 3 周前 / 2 个月前 / 2025-08-01
|
|
41
|
+
*/
|
|
42
|
+
export function humanTime(ts, { now = Date.now() } = {}) {
|
|
43
|
+
const t = toMs(ts);
|
|
44
|
+
const n = toMs(now) || Date.now();
|
|
45
|
+
if (!t) return '';
|
|
46
|
+
const diff = n - t;
|
|
47
|
+
if (diff < 0) return clock(new Date(t)); // 未来的时间:只给时刻,不编「之后」
|
|
48
|
+
const minutes = diff / 60000;
|
|
49
|
+
if (minutes < 1) return '刚刚';
|
|
50
|
+
if (minutes < 60) return `${Math.floor(minutes)} 分钟前`;
|
|
51
|
+
|
|
52
|
+
const days = dayDiff(t, n);
|
|
53
|
+
const d = new Date(t);
|
|
54
|
+
if (days === 0) return `今天 ${clock(d)}`;
|
|
55
|
+
if (days === 1) return `昨天 ${clock(d)}`;
|
|
56
|
+
if (days === 2) return `前天 ${clock(d)}`;
|
|
57
|
+
if (days != null && days >= 3 && days <= 6) return `${days} 天前`;
|
|
58
|
+
const current = new Date(n);
|
|
59
|
+
if (days >= 7 && days <= 13) {
|
|
60
|
+
const daysSinceMonday = (current.getDay() + 6) % 7;
|
|
61
|
+
return days <= daysSinceMonday + 7 ? '上' + WEEK[d.getDay()] : `${days} 天前`;
|
|
62
|
+
}
|
|
63
|
+
if (days != null && days >= 14 && days <= 29) return `${Math.round(days / 7)} 周前`;
|
|
64
|
+
if (days != null && days >= 30 && days <= 364) {
|
|
65
|
+
const months = (current.getFullYear() - d.getFullYear()) * 12 + current.getMonth() - d.getMonth();
|
|
66
|
+
if (months === 0) return `${Math.round(days / 7)} 周前`;
|
|
67
|
+
return months === 1 ? '上个月' : `${months} 个月前`;
|
|
68
|
+
}
|
|
69
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 「多久以前」的短说法:刚刚 / 12 分钟前 / 3 小时前 / 昨天 / 4 天前 / 2 个月前 */
|
|
73
|
+
export function timeAgo(ts, { now = Date.now() } = {}) {
|
|
74
|
+
const t = toMs(ts);
|
|
75
|
+
const n = toMs(now) || Date.now();
|
|
76
|
+
if (!t) return '';
|
|
77
|
+
const diff = Math.max(0, n - t);
|
|
78
|
+
const minutes = diff / 60000;
|
|
79
|
+
if (minutes < 1) return '刚刚';
|
|
80
|
+
if (minutes < 60) return `${Math.floor(minutes)} 分钟前`;
|
|
81
|
+
const hours = minutes / 60;
|
|
82
|
+
if (hours < 24 && dayDiff(t, n) === 0) return `${Math.floor(hours)} 小时前`;
|
|
83
|
+
const days = dayDiff(t, n);
|
|
84
|
+
if (days === 1) return '昨天';
|
|
85
|
+
if (days === 2) return '前天';
|
|
86
|
+
if (days != null && days < 30) return `${days} 天前`;
|
|
87
|
+
if (days != null && days < 365) return `${Math.max(1, Math.round(days / 30))} 个月前`;
|
|
88
|
+
return '很久以前';
|
|
89
|
+
}
|
|
@@ -1,27 +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
|
-
/** until:按这一刻(毫秒时间戳)之前(含)的选择重放 */
|
|
26
|
-
export function latestByExp(memDir: string, opts?: { until?: number | null }): 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>
|
|
27
27
|
export function countByExp(memDir: string): Map<string, number>
|
package/lib/unfinished-events.js
CHANGED
|
@@ -1,106 +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
|
-
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
|
|
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 cannot be empty(id 不能为空)')
|
|
46
|
+
if (!CHOICES.has(choice)) throw new Error('choice must be done / shelved / reopen(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 cannot be empty(id 不能为空)')
|
|
56
|
+
if (!CHOICES.has(choice)) throw new Error('choice must be done / shelved / reopen(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
|
|
106
106
|
}
|
package/lib/unsaid.d.ts
CHANGED
|
@@ -1,28 +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 }
|
|
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 }
|