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.
Files changed (54) hide show
  1. package/README.md +14 -0
  2. package/bin/whale-memory-mcp.mjs +276 -0
  3. package/demo.mjs +44 -33
  4. package/index.d.ts +19 -15
  5. package/index.js +21 -17
  6. package/lib/archive.d.ts +22 -22
  7. package/lib/archive.js +171 -135
  8. package/lib/as-of.d.ts +5 -5
  9. package/lib/as-of.js +32 -32
  10. package/lib/book.d.ts +4 -4
  11. package/lib/book.js +75 -75
  12. package/lib/chapter-events.d.ts +39 -39
  13. package/lib/chapter-events.js +89 -89
  14. package/lib/detail-recall.d.ts +15 -0
  15. package/lib/detail-recall.js +174 -0
  16. package/lib/event-log.d.ts +10 -10
  17. package/lib/event-log.js +61 -61
  18. package/lib/evidence-from-experience.d.ts +8 -8
  19. package/lib/evidence-from-experience.js +62 -62
  20. package/lib/evidence-policy.js +2 -2
  21. package/lib/fact-timeline-contract.d.ts +73 -0
  22. package/lib/fact-timeline-contract.js +226 -0
  23. package/lib/fact-timeline-query.d.ts +29 -0
  24. package/lib/fact-timeline-query.js +97 -0
  25. package/lib/file-lock.js +1 -1
  26. package/lib/later-events.d.ts +21 -21
  27. package/lib/later-events.js +80 -80
  28. package/lib/link-events.d.ts +15 -15
  29. package/lib/link-events.js +33 -33
  30. package/lib/person-card.d.ts +4 -0
  31. package/lib/person-card.js +179 -0
  32. package/lib/query-match.js +55 -0
  33. package/lib/recall-events.d.ts +24 -24
  34. package/lib/recall-events.js +97 -97
  35. package/lib/recap.d.ts +23 -23
  36. package/lib/recap.js +79 -79
  37. package/lib/relative-window.d.ts +4 -0
  38. package/lib/relative-window.js +123 -0
  39. package/lib/seal-events.d.ts +25 -25
  40. package/lib/seal-events.js +82 -82
  41. package/lib/self-experience.d.ts +180 -175
  42. package/lib/self-experience.js +624 -560
  43. package/lib/self-memory.js +70 -68
  44. package/lib/self-prompt.js +8 -4
  45. package/lib/self-settings.js +2 -2
  46. package/lib/time-sense.d.ts +6 -0
  47. package/lib/time-sense.js +89 -0
  48. package/lib/unfinished-events.d.ts +26 -26
  49. package/lib/unfinished-events.js +105 -105
  50. package/lib/unsaid.d.ts +28 -28
  51. package/lib/unsaid.js +105 -105
  52. package/lib/waking.d.ts +1 -1
  53. package/lib/waking.js +99 -92
  54. package/package.json +139 -113
@@ -1,98 +1,98 @@
1
- // 想起是事件:只追加,不改经历正文
2
- // 一行一个 { id, at, query, chatKey?, backfilled? }
3
- // 参数是记忆目录本身(<data>/plugin-data/biomimetic-memory),与 self-experience 一致
4
- import fs from 'node:fs'
5
- import path from 'node:path'
6
- import { withFileLock } from './file-lock.js'
7
- import { before } from './as-of.js'
8
-
9
- const FILE = 'recall-events.jsonl'
10
-
11
- export function eventsFile(memDir) {
12
- return path.join(memDir, FILE)
13
- }
14
-
15
- function ensureDir(memDir) {
16
- fs.mkdirSync(memDir, { recursive: true })
17
- }
18
-
19
-
20
-
21
- export function append(memDir, { id, query = '', chatKey = '', backfilled = false } = {}, opts = {}) {
22
- if (!String(id || '').trim()) throw new Error('id 不能为空')
23
- const row = {
24
- id: String(id),
25
- at: new Date().toISOString(),
26
- query: String(query || '').slice(0, 200),
27
- chatKey: String(chatKey || '').slice(0, 120)
28
- }
29
- if (backfilled) row.backfilled = true
30
-
31
- ensureDir(memDir)
32
- return withFileLock(eventsFile(memDir) + '.lock', () => {
33
- const file = eventsFile(memDir)
34
- let prefix = ''
35
- try {
36
- const st = fs.statSync(file)
37
- if (st.size) {
38
- const fd = fs.openSync(file, 'r')
39
- const buf = Buffer.alloc(1)
40
- fs.readSync(fd, buf, 0, 1, st.size - 1)
41
- fs.closeSync(fd)
42
- if (buf[0] !== 10) prefix = '\n'
43
- }
44
- } catch { }
45
- fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
46
- return row
47
- }, opts)
48
- }
49
-
50
- export function readAll(memDir) {
51
- let raw = ''
52
- try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
53
- const rows = []
54
- let bad = 0
55
- for (const line of raw.split('\n')) {
56
- if (!line.trim()) continue
57
- try {
58
- const r = JSON.parse(line)
59
- if (r && r.id) rows.push(r)
60
- else bad += 1
61
- } catch { bad += 1 }
62
- }
63
- return { rows, bad }
64
- }
65
-
66
- // 进程内缓存:同一进程里连续 recall 不再重复解析整个事件文件
67
- const memo = new Map()
68
-
69
- // until:只数这一刻之前(含)的想起;截断查询不走缓存
70
- export function countByExp(memDir, { until = null } = {}) {
71
- const file = eventsFile(memDir)
72
- let stamp = ''
73
- try { const st = fs.statSync(file); stamp = st.mtimeMs + ':' + st.size } catch { }
74
- const hit = until === null ? memo.get(memDir) : null
75
- if (hit && hit.stamp === stamp) return hit.map
76
-
77
- const { rows } = readAll(memDir)
78
- const map = new Map()
79
- for (const r of rows) {
80
- if (!before(r, until)) continue
81
- const cur = map.get(r.id) || { count: 0, lastAt: '' }
82
- cur.count += 1
83
- if (String(r.at || '') > cur.lastAt) cur.lastAt = String(r.at || '')
84
- map.set(r.id, cur)
85
- }
86
- if (until === null) memo.set(memDir, { stamp, map })
87
- return map
88
- }
89
-
90
- export function list(memDir, { id = '', limit = 20 } = {}) {
91
- const { rows } = readAll(memDir)
92
- return rows
93
- .filter((r) => !id || r.id === id)
94
- .slice(-limit)
95
- .reverse()
96
- }
97
-
1
+ // 想起是事件:只追加,不改经历正文
2
+ // 一行一个 { id, at, query, chatKey?, backfilled? }
3
+ // 参数是记忆目录本身(<data>/plugin-data/biomimetic-memory),与 self-experience 一致
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+ import { withFileLock } from './file-lock.js'
7
+ import { before } from './as-of.js'
8
+
9
+ const FILE = 'recall-events.jsonl'
10
+
11
+ export function eventsFile(memDir) {
12
+ return path.join(memDir, FILE)
13
+ }
14
+
15
+ function ensureDir(memDir) {
16
+ fs.mkdirSync(memDir, { recursive: true })
17
+ }
18
+
19
+
20
+
21
+ export function append(memDir, { id, query = '', chatKey = '', backfilled = false } = {}, opts = {}) {
22
+ if (!String(id || '').trim()) throw new Error('id cannot be empty(id 不能为空)')
23
+ const row = {
24
+ id: String(id),
25
+ at: new Date().toISOString(),
26
+ query: String(query || '').slice(0, 200),
27
+ chatKey: String(chatKey || '').slice(0, 120)
28
+ }
29
+ if (backfilled) row.backfilled = true
30
+
31
+ ensureDir(memDir)
32
+ return withFileLock(eventsFile(memDir) + '.lock', () => {
33
+ const file = eventsFile(memDir)
34
+ let prefix = ''
35
+ try {
36
+ const st = fs.statSync(file)
37
+ if (st.size) {
38
+ const fd = fs.openSync(file, 'r')
39
+ const buf = Buffer.alloc(1)
40
+ fs.readSync(fd, buf, 0, 1, st.size - 1)
41
+ fs.closeSync(fd)
42
+ if (buf[0] !== 10) prefix = '\n'
43
+ }
44
+ } catch { }
45
+ fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
46
+ return row
47
+ }, opts)
48
+ }
49
+
50
+ export function readAll(memDir) {
51
+ let raw = ''
52
+ try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
53
+ const rows = []
54
+ let bad = 0
55
+ for (const line of raw.split('\n')) {
56
+ if (!line.trim()) continue
57
+ try {
58
+ const r = JSON.parse(line)
59
+ if (r && r.id) rows.push(r)
60
+ else bad += 1
61
+ } catch { bad += 1 }
62
+ }
63
+ return { rows, bad }
64
+ }
65
+
66
+ // 进程内缓存:同一进程里连续 recall 不再重复解析整个事件文件
67
+ const memo = new Map()
68
+
69
+ // until:只数这一刻之前(含)的想起;截断查询不走缓存
70
+ export function countByExp(memDir, { until = null } = {}) {
71
+ const file = eventsFile(memDir)
72
+ let stamp = ''
73
+ try { const st = fs.statSync(file); stamp = st.mtimeMs + ':' + st.size } catch { }
74
+ const hit = until === null ? memo.get(memDir) : null
75
+ if (hit && hit.stamp === stamp) return hit.map
76
+
77
+ const { rows } = readAll(memDir)
78
+ const map = new Map()
79
+ for (const r of rows) {
80
+ if (!before(r, until)) continue
81
+ const cur = map.get(r.id) || { count: 0, lastAt: '' }
82
+ cur.count += 1
83
+ if (String(r.at || '') > cur.lastAt) cur.lastAt = String(r.at || '')
84
+ map.set(r.id, cur)
85
+ }
86
+ if (until === null) memo.set(memDir, { stamp, map })
87
+ return map
88
+ }
89
+
90
+ export function list(memDir, { id = '', limit = 20 } = {}) {
91
+ const { rows } = readAll(memDir)
92
+ return rows
93
+ .filter((r) => !id || r.id === id)
94
+ .slice(-limit)
95
+ .reverse()
96
+ }
97
+
98
98
  export const internals = { FILE }
package/lib/recap.d.ts CHANGED
@@ -1,23 +1,23 @@
1
- import type { AsOf } from './self-experience.js'
2
-
3
- export interface RecapItem {
4
- id: string
5
- day: string
6
- text: string
7
- }
8
-
9
- export interface Recap {
10
- from: string
11
- to: string
12
- days: number
13
- written: Array<RecapItem & { kind: string; feeling: string[]; refs: string[] }>
14
- revised: Array<RecapItem & { thought: string; feeling: string[]; at: string; laterDay: string }>
15
- feelingShifts: Array<RecapItem & { then: string[]; now: string[]; laterDay: string }>
16
- settled: Array<RecapItem & { unfinished: string; choice: 'done' | 'shelved'; stateDay: string }>
17
- reopened: Array<RecapItem & { unfinished: string; choice: 'reopen'; stateDay: string }>
18
- stillOpen: Array<RecapItem & { unfinished: string }>
19
- }
20
-
21
- /** 只整理事实,不调模型、不下结论;她封存了的不列 */
22
- export function recap(dir: string, opts?: { days?: number; asOf?: AsOf; now?: Date }): Recap
23
- export function renderRecap(recap: Recap): string
1
+ import type { AsOf } from './self-experience.js'
2
+
3
+ export interface RecapItem {
4
+ id: string
5
+ day: string
6
+ text: string
7
+ }
8
+
9
+ export interface Recap {
10
+ from: string
11
+ to: string
12
+ days: number
13
+ written: Array<RecapItem & { kind: string; feeling: string[]; refs: string[] }>
14
+ revised: Array<RecapItem & { thought: string; feeling: string[]; at: string; laterDay: string }>
15
+ feelingShifts: Array<RecapItem & { then: string[]; now: string[]; laterDay: string }>
16
+ settled: Array<RecapItem & { unfinished: string; choice: 'done' | 'shelved'; stateDay: string }>
17
+ reopened: Array<RecapItem & { unfinished: string; choice: 'reopen'; stateDay: string }>
18
+ stillOpen: Array<RecapItem & { unfinished: string }>
19
+ }
20
+
21
+ /** 只整理事实,不调模型、不下结论;她封存了的不列 */
22
+ export function recap(dir: string, opts?: { days?: number; asOf?: AsOf; now?: Date }): Recap
23
+ export function renderRecap(recap: Recap): string
package/lib/recap.js CHANGED
@@ -1,79 +1,79 @@
1
- // 回顾材料:把这几天发生过的整理出来,给她写回想用
2
- // 只列事实——写下了什么、改过什么想法、感觉怎么变的、哪些事想通或放下了、哪些还没弄完
3
- // 不调模型、不下结论、不替她归纳;她封存了的不列。要不要写回想、从哪几件事想到的,由她定
4
- import { loadAll } from './self-experience.js'
5
- import { parseAsOf, dayOf } from './as-of.js'
6
-
7
- const snippet = (s, n = 40) => { const c = [...String(s || '')]; return c.length > n ? c.slice(0, n).join('') + '…' : c.join('') }
8
-
9
- // days:往回看几天(1–366);asOf:以那一刻为"今天"往回看(只看那时的她)
10
- export function recap(dir, { days = 7, asOf = null, now = new Date() } = {}) {
11
- if (!Number.isInteger(days) || days < 1 || days > 366) throw new Error('days 要是 1 到 366 之间的整数。')
12
- const cut = parseAsOf(asOf)
13
- const end = cut === null ? now.getTime() : cut
14
- // 按自然日:含"今天"在内往回 days 天,从那天本地零点算起
15
- const e = new Date(end)
16
- const start = new Date(e.getFullYear(), e.getMonth(), e.getDate() - (days - 1)).getTime() - 1
17
- const within = (at) => { const t = Date.parse(String(at || '')); return Number.isFinite(t) && t > start && t <= end }
18
- const rows = loadAll(dir, { asOf: cut === null ? null : asOf }).filter((r) => !r.sealed)
19
- const head = (r) => ({ id: r.id, day: r.day, text: snippet(r.then.text) })
20
-
21
- const written = rows.filter((r) => within(r.at)).map((r) => ({ ...head(r), kind: r.kind, feeling: r.then.feeling || [], refs: r.then.refs || [] }))
22
- const revised = []
23
- const feelingShifts = []
24
- for (const r of rows) {
25
- const inRange = (r.later || []).filter((l) => within(l.at))
26
- for (const l of inRange) revised.push({ ...head(r), thought: String(l.thought || ''), feeling: l.feeling || [], at: l.at, laterDay: l.day || String(l.at || '').slice(0, 10) })
27
- const felt = [...inRange].reverse().find((l) => Array.isArray(l.feeling) && l.feeling.length)
28
- if (felt) feelingShifts.push({ ...head(r), then: r.then.feeling || [], now: felt.feeling, laterDay: felt.day || String(felt.at || '').slice(0, 10) })
29
- }
30
- const settled = []
31
- const reopened = []
32
- for (const r of rows) {
33
- const st = r.unfinishedState
34
- if (!st || !within(st.at)) continue
35
- const item = { ...head(r), unfinished: r.then.unfinished, choice: st.choice, stateDay: st.day }
36
- if (st.choice === 'reopen') reopened.push(item)
37
- else settled.push(item)
38
- }
39
- const stillOpen = rows
40
- .filter((r) => r.then.unfinished && !(r.unfinishedState && (r.unfinishedState.choice === 'done' || r.unfinishedState.choice === 'shelved')))
41
- .slice(-5)
42
- .map((r) => ({ ...head(r), unfinished: r.then.unfinished }))
43
-
44
- return { from: dayOf(start + 1), to: dayOf(end), days, written, revised, feelingShifts, settled, reopened, stillOpen }
45
- }
46
-
47
- const at = (x) => (x.day || '') + '「' + x.text + '」(' + x.id + ')'
48
-
49
- export function renderRecap(rc) {
50
- const lines = ['【这几天(' + rc.from + ' ~ ' + rc.to + ')】']
51
- const empty = !rc.written.length && !rc.revised.length && !rc.settled.length && !rc.reopened.length
52
- if (empty) lines.push('这几天没有新写下的,也没有改过想法。')
53
- if (rc.written.length) {
54
- lines.push('写下了 ' + rc.written.length + ' 件:')
55
- for (const x of rc.written) lines.push('- ' + at(x) + (x.feeling.length ? ' 当时的感觉:' + x.feeling.join('、') : '') + (x.kind === '回想' ? '(这是一条回想)' : ''))
56
- }
57
- if (rc.revised.length) {
58
- lines.push('回头想过的:')
59
- for (const x of rc.revised) lines.push('- ' + at(x) + ' → ' + x.laterDay + ' 写了「' + snippet(x.thought, 60) + '」')
60
- }
61
- if (rc.feelingShifts.length) {
62
- lines.push('感觉变了的:')
63
- for (const x of rc.feelingShifts) lines.push('- ' + at(x) + ':当时 ' + (x.then.length ? x.then.join('、') : '没写') + ' → ' + x.laterDay + ' ' + x.now.join('、'))
64
- }
65
- if (rc.settled.length) {
66
- lines.push('有了决定的:')
67
- for (const x of rc.settled) lines.push('- 「' + x.unfinished + '」' + (x.choice === 'done' ? '想通了' : '先放下了') + '(' + x.stateDay + ',' + x.id + ')')
68
- }
69
- if (rc.reopened.length) {
70
- lines.push('又拾起来的:')
71
- for (const x of rc.reopened) lines.push('- 「' + x.unfinished + '」(' + x.stateDay + ',' + x.id + ')')
72
- }
73
- if (rc.stillOpen.length) {
74
- lines.push('还没弄完的:')
75
- for (const x of rc.stillOpen) lines.push('- 「' + x.unfinished + '」(' + x.id + ')')
76
- }
77
- lines.push('(这些是记录,不是结论。想写一条回想,就用 write --kind 回想 --refs 带上你想到的那几条 id;不想写也可以。)')
78
- return lines.join('\n')
79
- }
1
+ // 回顾材料:把这几天发生过的整理出来,给她写回想用
2
+ // 只列事实——写下了什么、改过什么想法、感觉怎么变的、哪些事想通或放下了、哪些还没弄完
3
+ // 不调模型、不下结论、不替她归纳;她封存了的不列。要不要写回想、从哪几件事想到的,由她定
4
+ import { loadAll } from './self-experience.js'
5
+ import { parseAsOf, dayOf } from './as-of.js'
6
+
7
+ const snippet = (s, n = 40) => { const c = [...String(s || '')]; return c.length > n ? c.slice(0, n).join('') + '…' : c.join('') }
8
+
9
+ // days:往回看几天(1–366);asOf:以那一刻为"今天"往回看(只看那时的她)
10
+ export function recap(dir, { days = 7, asOf = null, now = new Date() } = {}) {
11
+ if (!Number.isInteger(days) || days < 1 || days > 366) throw new Error('days must be an integer from 1 to 366.(days 要是 1 到 366 之间的整数。)')
12
+ const cut = parseAsOf(asOf)
13
+ const end = cut === null ? now.getTime() : cut
14
+ // 按自然日:含"今天"在内往回 days 天,从那天本地零点算起
15
+ const e = new Date(end)
16
+ const start = new Date(e.getFullYear(), e.getMonth(), e.getDate() - (days - 1)).getTime() - 1
17
+ const within = (at) => { const t = Date.parse(String(at || '')); return Number.isFinite(t) && t > start && t <= end }
18
+ const rows = loadAll(dir, { asOf: cut === null ? null : asOf }).filter((r) => !r.sealed)
19
+ const head = (r) => ({ id: r.id, day: r.day, text: snippet(r.then.text) })
20
+
21
+ const written = rows.filter((r) => within(r.at)).map((r) => ({ ...head(r), kind: r.kind, feeling: r.then.feeling || [], refs: r.then.refs || [] }))
22
+ const revised = []
23
+ const feelingShifts = []
24
+ for (const r of rows) {
25
+ const inRange = (r.later || []).filter((l) => within(l.at))
26
+ for (const l of inRange) revised.push({ ...head(r), thought: String(l.thought || ''), feeling: l.feeling || [], at: l.at, laterDay: l.day || String(l.at || '').slice(0, 10) })
27
+ const felt = [...inRange].reverse().find((l) => Array.isArray(l.feeling) && l.feeling.length)
28
+ if (felt) feelingShifts.push({ ...head(r), then: r.then.feeling || [], now: felt.feeling, laterDay: felt.day || String(felt.at || '').slice(0, 10) })
29
+ }
30
+ const settled = []
31
+ const reopened = []
32
+ for (const r of rows) {
33
+ const st = r.unfinishedState
34
+ if (!st || !within(st.at)) continue
35
+ const item = { ...head(r), unfinished: r.then.unfinished, choice: st.choice, stateDay: st.day }
36
+ if (st.choice === 'reopen') reopened.push(item)
37
+ else settled.push(item)
38
+ }
39
+ const stillOpen = rows
40
+ .filter((r) => r.then.unfinished && !(r.unfinishedState && (r.unfinishedState.choice === 'done' || r.unfinishedState.choice === 'shelved')))
41
+ .slice(-5)
42
+ .map((r) => ({ ...head(r), unfinished: r.then.unfinished }))
43
+
44
+ return { from: dayOf(start + 1), to: dayOf(end), days, written, revised, feelingShifts, settled, reopened, stillOpen }
45
+ }
46
+
47
+ const at = (x) => (x.day || '') + '「' + x.text + '」(' + x.id + ')'
48
+
49
+ export function renderRecap(rc) {
50
+ const lines = ['【这几天(' + rc.from + ' ~ ' + rc.to + ')】']
51
+ const empty = !rc.written.length && !rc.revised.length && !rc.settled.length && !rc.reopened.length
52
+ if (empty) lines.push('这几天没有新写下的,也没有改过想法。')
53
+ if (rc.written.length) {
54
+ lines.push('写下了 ' + rc.written.length + ' 件:')
55
+ for (const x of rc.written) lines.push('- ' + at(x) + (x.feeling.length ? ' 当时的感觉:' + x.feeling.join('、') : '') + (x.kind === '回想' ? '(这是一条回想)' : ''))
56
+ }
57
+ if (rc.revised.length) {
58
+ lines.push('回头想过的:')
59
+ for (const x of rc.revised) lines.push('- ' + at(x) + ' → ' + x.laterDay + ' 写了「' + snippet(x.thought, 60) + '」')
60
+ }
61
+ if (rc.feelingShifts.length) {
62
+ lines.push('感觉变了的:')
63
+ for (const x of rc.feelingShifts) lines.push('- ' + at(x) + ':当时 ' + (x.then.length ? x.then.join('、') : '没写') + ' → ' + x.laterDay + ' ' + x.now.join('、'))
64
+ }
65
+ if (rc.settled.length) {
66
+ lines.push('有了决定的:')
67
+ for (const x of rc.settled) lines.push('- 「' + x.unfinished + '」' + (x.choice === 'done' ? '想通了' : '先放下了') + '(' + x.stateDay + ',' + x.id + ')')
68
+ }
69
+ if (rc.reopened.length) {
70
+ lines.push('又拾起来的:')
71
+ for (const x of rc.reopened) lines.push('- 「' + x.unfinished + '」(' + x.stateDay + ',' + x.id + ')')
72
+ }
73
+ if (rc.stillOpen.length) {
74
+ lines.push('还没弄完的:')
75
+ for (const x of rc.stillOpen) lines.push('- 「' + x.unfinished + '」(' + x.id + ')')
76
+ }
77
+ lines.push('(这些是记录,不是结论。想写一条回想,就用 write --kind 回想 --refs 带上你想到的那几条 id;不想写也可以。)')
78
+ return lines.join('\n')
79
+ }
@@ -0,0 +1,4 @@
1
+ /** 把「前几天 / 上周三 / 上个月 / 两周前 / 昨天晚上」翻成 [from, to);翻不出来返回 null */
2
+ export function parseRelativeWindow(text: string, options?: { now?: number }): { from: number; to: number; label: string; kind: string } | null
3
+ /** 时间是否落在窗口内;窗口为 null 时一律算在内 */
4
+ export function inWindow(ts: number | string | null | undefined, window: { from: number; to: number } | null): boolean
@@ -0,0 +1,123 @@
1
+ /**
2
+ * 把口语里的时间说法翻成时间窗口:「前几天」「上周三」「上个月」「昨天晚上」。
3
+ *
4
+ * 为什么要它:她问「前几天那个事」时,字面匹配找不到任何东西——那句话里没有具体日期。
5
+ * 先翻成 [from, to),再去检索,才可能命中。
6
+ *
7
+ * 纯函数,无 IO。拿不准就返回 null(宁可不过滤,也不乱过滤)。
8
+ */
9
+
10
+ const DAY = 86400000;
11
+
12
+ function toMs(ts) {
13
+ const n = Number(ts);
14
+ if (!Number.isFinite(n) || n <= 0) return 0;
15
+ return n >= 1e11 ? n : n * 1000;
16
+ }
17
+
18
+ function localDay(ms, offset = 0, hour = 0) {
19
+ const d = new Date(ms);
20
+ return new Date(d.getFullYear(), d.getMonth(), d.getDate() + offset, hour).getTime();
21
+ }
22
+
23
+ function startOfWeek(ms) {
24
+ const d = new Date(ms);
25
+ const offset = (d.getDay() + 6) % 7; // 周一为一周开始
26
+ return localDay(ms, -offset);
27
+ }
28
+
29
+ function startOfMonth(ms) {
30
+ const d = new Date(ms);
31
+ return new Date(d.getFullYear(), d.getMonth(), 1).getTime();
32
+ }
33
+
34
+ const CN_NUM = { 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9, 十: 10 };
35
+ function cnNumber(text) {
36
+ if (/^\d+$/.test(text)) return Number(text);
37
+ if (text === '十') return 10;
38
+ if (/^十[一二三四五六七八九]$/.test(text)) return 10 + CN_NUM[text[1]];
39
+ if (/^[一二两三四五六七八九]十$/.test(text)) return CN_NUM[text[0]] * 10;
40
+ if (/^[一二两三四五六七八九]十[一二三四五六七八九]$/.test(text)) return CN_NUM[text[0]] * 10 + CN_NUM[text[2]];
41
+ return CN_NUM[text] || 0;
42
+ }
43
+
44
+ /**
45
+ * 解析口语时间窗口。
46
+ * @param {string} text 她收到的那句话
47
+ * @param {object} [options] {now}
48
+ * @returns {{from:number,to:number,label:string,kind:string}|null}
49
+ */
50
+ export function parseRelativeWindow(text, { now = Date.now() } = {}) {
51
+ const q = String(text || '');
52
+ const n = toMs(now) || Date.now();
53
+ if (!q.trim()) return null;
54
+ const today = localDay(n);
55
+
56
+ // 数量要先于「前天」匹配,否则「三天前天气」会在量词边界处被截断。
57
+ const quantity = /([0-9]+|[一二两三四五六七八九十]+)\s*(天|日|个?周|个?星期|个?礼拜)(?:以|之)?前/.exec(q);
58
+ if (quantity) {
59
+ const k = cnNumber(quantity[1]);
60
+ const days = quantity[2] === '天' || quantity[2] === '日';
61
+ if (!k || k > (days ? 60 : 12)) return null;
62
+ const from = days ? localDay(today, -k) : localDay(startOfWeek(n), -7 * k);
63
+ return { from, to: localDay(from, days ? 1 : 7), label: days ? `${k} 天前` : `${k} 周前`, kind: days ? 'n-days' : 'n-weeks' };
64
+ }
65
+
66
+ if (/前几天|前两天|几天前|前些天|前阵子|这些天|这几天|这两天|近几天/.test(q)) {
67
+ return { from: localDay(today, -4), to: localDay(today, 1), label: '前几天', kind: 'fuzzy-days' };
68
+ }
69
+
70
+ const day = /(大前天|前天|昨天|今天|昨晚|今晚|今早)(?:的?\s*(上午|早上|中午|下午|傍晚|晚上|夜里|半夜))?/.exec(q);
71
+ if (day) {
72
+ const label = { 昨晚: '昨天', 今晚: '今天', 今早: '今天' }[day[1]] || day[1];
73
+ const offset = { 大前天: -3, 前天: -2, 昨天: -1, 今天: 0 }[label];
74
+ const base = localDay(today, offset);
75
+ const part = { 昨晚: '晚上', 今晚: '晚上', 今早: '早上' }[day[1]] || day[2];
76
+ if (!part) return { from: base, to: localDay(base, 1), label, kind: 'day' };
77
+ const [start, end] = { 上午: [6, 12], 早上: [6, 11], 中午: [11, 13], 下午: [13, 17], 傍晚: [17, 19], 晚上: [18, 22], 夜里: [22, 24], 半夜: [23, 26] }[part];
78
+ return { from: localDay(base, 0, start), to: localDay(base, 0, end), label: label + part, kind: 'part-of-day' };
79
+ }
80
+ if (/刚刚|刚才/.test(q)) {
81
+ return { from: n - 3600000, to: n + 60000, label: '刚刚', kind: 'recent' };
82
+ }
83
+
84
+ // 无「上/这/本」等限定词时,只有紧跟星期几才足以定位。
85
+ const week = /(?:(上上|下下|上|下|这|本)个?|(?<![每隔个0-9一二两三四五六七八九十])(?=(?:周|星期|礼拜)[一二三四五六日天]))(?:周|星期|礼拜)(?!末|年|围|堂|杰伦)([一二三四五六日天])?((?:以|之)前)?/.exec(q);
86
+ if (week) {
87
+ const which = week[1] || '这';
88
+ if (which.startsWith('下')) return null;
89
+ const shift = which === '上上' ? -14 : which === '上' ? -7 : 0;
90
+ const weekday = week[2];
91
+ const offset = weekday ? { 一: 0, 二: 1, 三: 2, 四: 3, 五: 4, 六: 5, 日: 6, 天: 6 }[weekday] : 0;
92
+ const from = localDay(startOfWeek(n), shift + offset);
93
+ const label = which + '周' + (weekday || '');
94
+ if (week[3]) return { from: 0, to: from, label: label + week[3], kind: 'older' };
95
+ return { from, to: localDay(from, weekday ? 1 : 7), label, kind: weekday ? 'weekday' : 'week' };
96
+ }
97
+
98
+ const month = /(上上|上|这|本)个?月(?!亮|光|饼|份)((?:以|之)前)?/.exec(q);
99
+ if (month) {
100
+ const d = new Date(n);
101
+ const shift = month[1] === '上上' ? -2 : month[1] === '上' ? -1 : 0;
102
+ const from = new Date(d.getFullYear(), d.getMonth() + shift, 1).getTime();
103
+ const label = month[1] + '个月';
104
+ if (month[2]) return { from: 0, to: from, label: label + month[2], kind: 'older' };
105
+ return { from, to: new Date(d.getFullYear(), d.getMonth() + shift + 1, 1).getTime(), label, kind: 'month' };
106
+ }
107
+
108
+ if (/最近|近期/.test(q)) {
109
+ return { from: localDay(today, -3), to: localDay(today, 1), label: '最近', kind: 'recent' };
110
+ }
111
+ if (/更早/.test(q)) {
112
+ return { from: startOfMonth(n) - 90 * DAY, to: startOfMonth(n), label: '上个月以前', kind: 'older' };
113
+ }
114
+ return null;
115
+ }
116
+
117
+ /** 是否落在窗口里。窗口为 null 时一律算在内(不过滤)。 */
118
+ export function inWindow(ts, window) {
119
+ if (!window) return true;
120
+ const t = toMs(ts);
121
+ if (!t) return false;
122
+ return t >= window.from && t < window.to;
123
+ }
@@ -1,25 +1,25 @@
1
- export type SealAction = 'seal' | 'unseal'
2
-
3
- export const ACTIONS: Set<SealAction>
4
-
5
- export interface SealEvent {
6
- id: string
7
- at: string
8
- day: string
9
- action: SealAction
10
- note: string
11
- }
12
-
13
- export interface SealedInfo {
14
- at: string
15
- day: string
16
- note: string
17
- }
18
-
19
- export function eventsFile(memDir: string): string
20
- /** 同一把锁里重读 → 判断 → 追加;已是这个状态就 noop,不写第二条 */
21
- export function decide(memDir: string, opts: { id: string; action: SealAction; note?: string }, lockOpts?: Record<string, unknown>): { row: SealEvent | null; noop: boolean }
22
- export function readAll(memDir: string): { rows: SealEvent[]; bad: number }
23
- /** 现在(或截至 until)仍封存着的经历 */
24
- export function sealedByExp(memDir: string, opts?: { until?: number | null }): Map<string, SealedInfo>
25
- export const internals: { FILE: string }
1
+ export type SealAction = 'seal' | 'unseal'
2
+
3
+ export const ACTIONS: Set<SealAction>
4
+
5
+ export interface SealEvent {
6
+ id: string
7
+ at: string
8
+ day: string
9
+ action: SealAction
10
+ note: string
11
+ }
12
+
13
+ export interface SealedInfo {
14
+ at: string
15
+ day: string
16
+ note: string
17
+ }
18
+
19
+ export function eventsFile(memDir: string): string
20
+ /** 同一把锁里重读 → 判断 → 追加;已是这个状态就 noop,不写第二条 */
21
+ export function decide(memDir: string, opts: { id: string; action: SealAction; note?: string }, lockOpts?: Record<string, unknown>): { row: SealEvent | null; noop: boolean }
22
+ export function readAll(memDir: string): { rows: SealEvent[]; bad: number }
23
+ /** 现在(或截至 until)仍封存着的经历 */
24
+ export function sealedByExp(memDir: string, opts?: { until?: number | null }): Map<string, SealedInfo>
25
+ export const internals: { FILE: string }