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,39 +1,39 @@
1
- export type ChapterAction = 'open' | 'rename' | 'close'
2
-
3
- export const ACTIONS: Set<ChapterAction>
4
-
5
- export interface ChapterEvent {
6
- id: string
7
- at: string
8
- day: string
9
- action: ChapterAction
10
- name?: string
11
- from?: string
12
- to?: string
13
- note?: string
14
- }
15
-
16
- export interface Chapter {
17
- id: string
18
- /** 现在(或截至 until)的名字 */
19
- name: string
20
- /** 起过的所有名字,按先后;最后一个就是 name */
21
- names: string[]
22
- from: string
23
- /** 空字符串表示"还在这段日子里" */
24
- to: string
25
- note: string
26
- openedAt: string
27
- }
28
-
29
- export function eventsFile(memDir: string): string
30
- export function readAll(memDir: string): { rows: ChapterEvent[]; bad: number }
31
- export function chapters(memDir: string, opts?: { until?: number | null }): Chapter[]
32
- /** 这一天落在哪些章节里(章节可以重叠) */
33
- export function chaptersOn(list: Chapter[], day: string): Chapter[]
34
- /** from 默认今天;同名同起点重复提交是 noop */
35
- export function open(memDir: string, opts: { name: string; from?: string; to?: string; note?: string }, lockOpts?: Record<string, unknown>): { row: ChapterEvent | null; noop: boolean }
36
- export function rename(memDir: string, opts: { id: string; name: string }, lockOpts?: Record<string, unknown>): { row: ChapterEvent | null; noop: boolean }
37
- /** to 默认今天;再 close 一次可以改结束日期 */
38
- export function close(memDir: string, opts: { id: string; to?: string }, lockOpts?: Record<string, unknown>): { row: ChapterEvent | null; noop: boolean }
39
- export const internals: { FILE: string }
1
+ export type ChapterAction = 'open' | 'rename' | 'close'
2
+
3
+ export const ACTIONS: Set<ChapterAction>
4
+
5
+ export interface ChapterEvent {
6
+ id: string
7
+ at: string
8
+ day: string
9
+ action: ChapterAction
10
+ name?: string
11
+ from?: string
12
+ to?: string
13
+ note?: string
14
+ }
15
+
16
+ export interface Chapter {
17
+ id: string
18
+ /** 现在(或截至 until)的名字 */
19
+ name: string
20
+ /** 起过的所有名字,按先后;最后一个就是 name */
21
+ names: string[]
22
+ from: string
23
+ /** 空字符串表示"还在这段日子里" */
24
+ to: string
25
+ note: string
26
+ openedAt: string
27
+ }
28
+
29
+ export function eventsFile(memDir: string): string
30
+ export function readAll(memDir: string): { rows: ChapterEvent[]; bad: number }
31
+ export function chapters(memDir: string, opts?: { until?: number | null }): Chapter[]
32
+ /** 这一天落在哪些章节里(章节可以重叠) */
33
+ export function chaptersOn(list: Chapter[], day: string): Chapter[]
34
+ /** from 默认今天;同名同起点重复提交是 noop */
35
+ export function open(memDir: string, opts: { name: string; from?: string; to?: string; note?: string }, lockOpts?: Record<string, unknown>): { row: ChapterEvent | null; noop: boolean }
36
+ export function rename(memDir: string, opts: { id: string; name: string }, lockOpts?: Record<string, unknown>): { row: ChapterEvent | null; noop: boolean }
37
+ /** to 默认今天;再 close 一次可以改结束日期 */
38
+ export function close(memDir: string, opts: { id: string; to?: string }, lockOpts?: Record<string, unknown>): { row: ChapterEvent | null; noop: boolean }
39
+ export const internals: { FILE: string }
@@ -1,89 +1,89 @@
1
- // 人生章节:她给一段日子起的名字(Conway 自传记忆模型里的"人生时期")
2
- // 一行一个 { id, at, day, action: open|rename|close, name?, from?, to?, note? },只追加
3
- // 名字是后来起的、也可以再改:改名不抹掉旧名字,翻回那天看到的是她那时的叫法
4
- // 经历按 day 落进章节:from ≤ day ≤ to(没写 to 就是"还在这段日子里");章节可以重叠
5
- import { createLog, stamp } from './event-log.js'
6
- import { before, parseAsOf } from './as-of.js'
7
-
8
- export const ACTIONS = new Set(['open', 'rename', 'close'])
9
- const log = createLog('chapter-events.jsonl', { valid: (r) => Boolean(r.id && ACTIONS.has(r.action)) })
10
- export const eventsFile = log.eventsFile
11
- export const readAll = log.readAll
12
- export const internals = { FILE: log.FILE }
13
-
14
- const LIMIT_NAME = 30
15
- const DATE = /^\d{4}-\d{2}-\d{2}$/
16
-
17
- function checkName(name) {
18
- const s = String(name || '').trim()
19
- if (!s) throw new Error('章节要有个名字,比如「在灯塔书店打工的那个月」。')
20
- if ([...s].length > LIMIT_NAME) throw new Error(`章节名太长(${[...s].length}/${LIMIT_NAME} 字)。`)
21
- return s
22
- }
23
-
24
- function checkDay(v, label) {
25
- const s = String(v || '').trim()
26
- if (!DATE.test(s)) throw new Error(`${label} 要写成 2026-11-01 这样的日期。`)
27
- parseAsOf(s) // 不存在的日期(2026-02-30)在这里报错
28
- return s
29
- }
30
-
31
- // 重放事件,得到每个章节现在(或截至 until)的样子
32
- export function chapters(memDir, { until = null } = {}) {
33
- const map = new Map()
34
- for (const r of readAll(memDir).rows) {
35
- if (!before(r, until)) continue
36
- if (r.action === 'open') map.set(r.id, { id: r.id, name: r.name, names: [r.name], from: r.from, to: r.to || '', note: r.note || '', openedAt: r.at })
37
- const c = map.get(r.id)
38
- if (!c) continue
39
- if (r.action === 'rename' && r.name !== c.name) { c.name = r.name; c.names.push(r.name) }
40
- if (r.action === 'close') c.to = r.to
41
- }
42
- return [...map.values()].sort((a, b) => a.from.localeCompare(b.from) || a.openedAt.localeCompare(b.openedAt))
43
- }
44
-
45
- export const chaptersOn = (list, day) => list.filter((c) => day >= c.from && (!c.to || day <= c.to))
46
-
47
- // 开一个章节。同名、同起点的重复提交是 noop
48
- export function open(memDir, { name, from, to = '', note = '' } = {}, opts = {}) {
49
- const n = checkName(name)
50
- const f = checkDay(from || new Date().toLocaleDateString('sv-SE'), 'from')
51
- const t = to ? checkDay(to, 'to') : ''
52
- if (t && t < f) throw new Error('结束日期不能早于开始日期。')
53
- return log.decide(memDir, (rows) => rows.some((r) => r.action === 'open' && r.name === n && r.from === f)
54
- ? null
55
- : { id: 'ch_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), ...stamp(), action: 'open', name: n, from: f, to: t, note: String(note || '').slice(0, 200) }, opts)
56
- }
57
-
58
- // 在已读出的事件里重放某一个章节(decide 的锁内用,不再重读文件)
59
- function current(rows, id) {
60
- let ch = null
61
- for (const r of rows) {
62
- if (r.id !== id) continue
63
- if (r.action === 'open') ch = { name: r.name, from: r.from, to: r.to || '' }
64
- else if (ch && r.action === 'rename') ch.name = r.name
65
- else if (ch && r.action === 'close') ch.to = r.to
66
- }
67
- return ch
68
- }
69
-
70
- // 改名:旧名字留在 names 里
71
- export function rename(memDir, { id, name } = {}, opts = {}) {
72
- const n = checkName(name)
73
- return log.decide(memDir, (rows) => {
74
- const ch = current(rows, id)
75
- if (!ch) throw new Error('找不到这个章节:' + id)
76
- return ch.name === n ? null : { id: String(id), ...stamp(), action: 'rename', name: n }
77
- }, opts)
78
- }
79
-
80
- // 这段日子结束了(再 close 一次可以改结束日期)
81
- export function close(memDir, { id, to } = {}, opts = {}) {
82
- const t = checkDay(to || new Date().toLocaleDateString('sv-SE'), 'to')
83
- return log.decide(memDir, (rows) => {
84
- const ch = current(rows, id)
85
- if (!ch) throw new Error('找不到这个章节:' + id)
86
- if (t < ch.from) throw new Error('结束日期不能早于开始日期(' + ch.from + ')。')
87
- return ch.to === t ? null : { id: String(id), ...stamp(), action: 'close', to: t }
88
- }, opts)
89
- }
1
+ // 人生章节:她给一段日子起的名字(Conway 自传记忆模型里的"人生时期")
2
+ // 一行一个 { id, at, day, action: open|rename|close, name?, from?, to?, note? },只追加
3
+ // 名字是后来起的、也可以再改:改名不抹掉旧名字,翻回那天看到的是她那时的叫法
4
+ // 经历按 day 落进章节:from ≤ day ≤ to(没写 to 就是"还在这段日子里");章节可以重叠
5
+ import { createLog, stamp } from './event-log.js'
6
+ import { before, parseAsOf } from './as-of.js'
7
+
8
+ export const ACTIONS = new Set(['open', 'rename', 'close'])
9
+ const log = createLog('chapter-events.jsonl', { valid: (r) => Boolean(r.id && ACTIONS.has(r.action)) })
10
+ export const eventsFile = log.eventsFile
11
+ export const readAll = log.readAll
12
+ export const internals = { FILE: log.FILE }
13
+
14
+ const LIMIT_NAME = 30
15
+ const DATE = /^\d{4}-\d{2}-\d{2}$/
16
+
17
+ function checkName(name) {
18
+ const s = String(name || '').trim()
19
+ if (!s) throw new Error('A chapter needs a name, e.g. "the month I worked at the lighthouse bookshop".(章节要有个名字,比如「在灯塔书店打工的那个月」。)')
20
+ if ([...s].length > LIMIT_NAME) throw new Error(`Chapter name is too long (${[...s].length}/${LIMIT_NAME} chars).(章节名太长(${[...s].length}/${LIMIT_NAME} 字)。)`)
21
+ return s
22
+ }
23
+
24
+ function checkDay(v, label) {
25
+ const s = String(v || '').trim()
26
+ if (!DATE.test(s)) throw new Error(`${label} must be a date like 2026-11-01.(${label} 要写成 2026-11-01 这样的日期。)`)
27
+ parseAsOf(s) // 不存在的日期(2026-02-30)在这里报错
28
+ return s
29
+ }
30
+
31
+ // 重放事件,得到每个章节现在(或截至 until)的样子
32
+ export function chapters(memDir, { until = null } = {}) {
33
+ const map = new Map()
34
+ for (const r of readAll(memDir).rows) {
35
+ if (!before(r, until)) continue
36
+ if (r.action === 'open') map.set(r.id, { id: r.id, name: r.name, names: [r.name], from: r.from, to: r.to || '', note: r.note || '', openedAt: r.at })
37
+ const c = map.get(r.id)
38
+ if (!c) continue
39
+ if (r.action === 'rename' && r.name !== c.name) { c.name = r.name; c.names.push(r.name) }
40
+ if (r.action === 'close') c.to = r.to
41
+ }
42
+ return [...map.values()].sort((a, b) => a.from.localeCompare(b.from) || a.openedAt.localeCompare(b.openedAt))
43
+ }
44
+
45
+ export const chaptersOn = (list, day) => list.filter((c) => day >= c.from && (!c.to || day <= c.to))
46
+
47
+ // 开一个章节。同名、同起点的重复提交是 noop
48
+ export function open(memDir, { name, from, to = '', note = '' } = {}, opts = {}) {
49
+ const n = checkName(name)
50
+ const f = checkDay(from || new Date().toLocaleDateString('sv-SE'), 'from')
51
+ const t = to ? checkDay(to, 'to') : ''
52
+ if (t && t < f) throw new Error('End date cannot be earlier than start date.(结束日期不能早于开始日期。)')
53
+ return log.decide(memDir, (rows) => rows.some((r) => r.action === 'open' && r.name === n && r.from === f)
54
+ ? null
55
+ : { id: 'ch_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), ...stamp(), action: 'open', name: n, from: f, to: t, note: String(note || '').slice(0, 200) }, opts)
56
+ }
57
+
58
+ // 在已读出的事件里重放某一个章节(decide 的锁内用,不再重读文件)
59
+ function current(rows, id) {
60
+ let ch = null
61
+ for (const r of rows) {
62
+ if (r.id !== id) continue
63
+ if (r.action === 'open') ch = { name: r.name, from: r.from, to: r.to || '' }
64
+ else if (ch && r.action === 'rename') ch.name = r.name
65
+ else if (ch && r.action === 'close') ch.to = r.to
66
+ }
67
+ return ch
68
+ }
69
+
70
+ // 改名:旧名字留在 names 里
71
+ export function rename(memDir, { id, name } = {}, opts = {}) {
72
+ const n = checkName(name)
73
+ return log.decide(memDir, (rows) => {
74
+ const ch = current(rows, id)
75
+ if (!ch) throw new Error('Chapter not found: ' + id + '(找不到这个章节:' + id + ')')
76
+ return ch.name === n ? null : { id: String(id), ...stamp(), action: 'rename', name: n }
77
+ }, opts)
78
+ }
79
+
80
+ // 这段日子结束了(再 close 一次可以改结束日期)
81
+ export function close(memDir, { id, to } = {}, opts = {}) {
82
+ const t = checkDay(to || new Date().toLocaleDateString('sv-SE'), 'to')
83
+ return log.decide(memDir, (rows) => {
84
+ const ch = current(rows, id)
85
+ if (!ch) throw new Error('Chapter not found: ' + id + '(找不到这个章节:' + id + ')')
86
+ if (t < ch.from) throw new Error('End date cannot be earlier than the start date (' + ch.from + ').(结束日期不能早于开始日期(' + ch.from + ')。)')
87
+ return ch.to === t ? null : { id: String(id), ...stamp(), action: 'close', to: t }
88
+ }, opts)
89
+ }
@@ -0,0 +1,15 @@
1
+ import type { AsOf } from './self-experience.js'
2
+
3
+ export interface DetailEvidence {
4
+ field: 'then.text' | 'then.scene' | 'then.thought' | 'then.quote' | 'then.quote.source' | 'then.feeling' | 'later.thought' | 'later.feeling'
5
+ at: string
6
+ text: string
7
+ source?: string
8
+ }
9
+ export interface DetailResult {
10
+ status: 'supported' | 'related' | 'ambiguous' | 'unmatched'
11
+ value: string | null
12
+ attribute: 'color' | 'price' | 'brand' | 'detail' | null
13
+ candidates: Array<{ id: string; day: string; match: 'phrase' | 'terms'; evidence: DetailEvidence[] }>
14
+ }
15
+ export function recallDetail(dir: string, query: string, opts?: { asOf?: AsOf }): DetailResult
@@ -0,0 +1,174 @@
1
+ import { loadAll, recall } from './self-experience.js'
2
+ import { queryTerms, matchedTerms } from './query-match.js'
3
+
4
+ // Strip only the requested attribute and conversational wrappers. The remaining
5
+ // subject keeps names, quantities, negation, and time qualifiers together.
6
+ const questions = [
7
+ ['color', /(?:的颜色|(?:是)?什么颜色)(?:的)?$/u],
8
+ ['brand', /(?:的品牌|(?:是)?什么(?:牌子|品牌))(?:的)?$/u],
9
+ ['price', /(?:的价格|多少钱)$/u],
10
+ ['detail', /(?:是什么(?:材料|品种|口味)|的(?:型号|重量|工资)|叫什么(?:名字)?|有多[重长高宽]|好吃|会不会[\p{Script=Han}]{1,6})$/u]
11
+ ]
12
+
13
+ function splitQuestion(query) {
14
+ const plain = query.trim().replace(/[??。!!]+$/u, '').trim()
15
+ .replace(/^(?:你还记得|还记得|请问)/u, '').replace(/吗$/u, '')
16
+
17
+ for (const [attribute, suffix] of questions) {
18
+ const match = suffix.exec(plain)
19
+ if (!match) continue
20
+ const topic = plain.slice(0, match.index).replace(/^[那这](?:条|支|本|个|双|件|把|台|盏|张)/u, '').trim()
21
+ if (topic.length >= 2) return { attribute, topic }
22
+ }
23
+ return { attribute: null, topic: plain }
24
+ }
25
+
26
+ // A value is offered only for a whole, explicit statement about this subject.
27
+ // Other prose, including reported speech, questions and guesses, stays evidence
28
+ // for the reader. A later note can qualify the statement even without the noun.
29
+ const statements = {
30
+ color: /^(?:的颜色是|是)((?:深|浅|淡|墨|天|米|银|金)?(?:红|橙|黄|绿|青|蓝|紫|白|黑|灰|棕|粉|银|金)色)(?:的)?[。.]?$/u,
31
+ price: /^的价格是((?:\d+(?:\.\d{1,2})?|[一二三四五六七八九十百千两零]+)元)[。.]?$/u,
32
+ brand: /^的品牌是([\p{Script=Han}A-Za-z0-9·-]{1,20})[。.]?$/u
33
+ }
34
+ const uncertainBrand = /不|没|未知|忘|可能|或|好像|大概|似乎|据说|听说|也许|应该|记得|猜|待定|待查|待确认|保密|个谜|什么|无名|无牌|无品牌|^无$|^(?:unknown|none|null|tbd)$/iu
35
+
36
+ function directValue(row, topic, attribute) {
37
+ const text = String(row.then.text || '').trim()
38
+ if (row.later.length || row.then.thought || row.then.scene || row.then.quote || !text.startsWith(topic)) return null
39
+ const value = statements[attribute]?.exec(text.slice(topic.length))?.[1]
40
+ if (!value || (attribute === 'brand' && uncertainBrand.test(value))) return null
41
+ return value
42
+ }
43
+
44
+ function excerpt(text, topic) {
45
+ const index = text.indexOf(topic)
46
+ const start = Math.max(0, index - 48)
47
+ return text.slice(start, start + Math.max(144, topic.length + 48))
48
+ }
49
+
50
+ // “我织的那条围巾”“去年冬天织的围巾”这类说法,中心词在“的”后面。
51
+ // 只在整句找不到时兜底,避免把“阿禾的工资”直接当成“工资”去全库乱找。
52
+ function headTopic(topic) {
53
+ const index = topic.lastIndexOf('的')
54
+ if (index < 0) return ''
55
+ const prefix = topic.slice(0, index)
56
+ // 只回退“我织的 / 去年冬天织的”这类带动词的定语。
57
+ // “姐姐的雨衣”“安安的相册”是限定归属,不能退成“雨衣/相册”去全库找。
58
+ if (!/[织做买画写缝编烤煮修建送借寄挑选洗修]/u.test(prefix)) return ''
59
+ // “没寄出的包裹”“没买的球鞋”是否定/未发生,不能退成“包裹/球鞋”去找已发生的那条。
60
+ if (/没|未|不|别|非|无/u.test(prefix)) return ''
61
+ // “冬青寄给我的那本画册”自带角色关系,交给 eventClues 判断;不要绕过它。
62
+ if (eventClues(topic)) return ''
63
+ let head = topic.slice(index + 1).trim()
64
+ head = head.replace(/^(?:那|这)?(?:条|支|本|个|双|件|把|台|盏|张|只|位|名)/u, '').trim()
65
+ if ([...head].length < 2 || [...head].length > 12) return ''
66
+ if (/^[的了吗呢吧啊呀么着过在里那这个些]+$/u.test(head)) return ''
67
+ return head
68
+ }
69
+
70
+ // A lender, object and action can appear apart in the same sentence. This
71
+ // retrieves a lead; their order alone cannot establish who lent what to whom.
72
+ function eventClues(topic) {
73
+ const match = /^(.{2,20}?)([借送寄买卖挑选画写做])(?:给|来|去)?(?:我|你|他|她)?的(?:那|这)?(?:条|支|本|个|双|件|把|台|盏|张)?([\p{Script=Han}]{1,16})$/u.exec(topic)
74
+ return match ? match.slice(1) : null
75
+ }
76
+
77
+ function candidate(row, topic, attribute, terms, clues) {
78
+ const fields = [
79
+ ['then.text', row.then.text, row.at], ['then.scene', row.then.scene, row.at],
80
+ ['then.thought', row.then.thought, row.at], ['then.quote', row.then.quote?.text, row.at],
81
+ ['then.quote.source', row.then.quote?.source, row.at],
82
+ ...(Array.isArray(row.then.feeling) ? row.then.feeling : []).map(feeling => ['then.feeling', feeling, row.at]),
83
+ ...row.later.flatMap(note => [
84
+ ['later.thought', note.thought, note.at],
85
+ ...(Array.isArray(note.feeling) ? note.feeling : []).map(feeling => ['later.feeling', feeling, note.at])
86
+ ])
87
+ ]
88
+ let hit = fields.find(([, text]) => typeof text === 'string' && text.includes(topic))
89
+ let anchor = topic
90
+ let match = hit ? 'phrase' : 'terms'
91
+ if (!hit && clues) {
92
+ for (const [field, text, at] of fields) {
93
+ if (typeof text !== 'string') continue
94
+ const sentence = text.split(/[。!?!?;;\n]/u).find(s => clues.every(word => s.includes(word)))
95
+ if (sentence) {
96
+ hit = [field, sentence, at]
97
+ anchor = clues[0]
98
+ match = 'terms'
99
+ break
100
+ }
101
+ }
102
+ }
103
+ if (!hit && !attribute) {
104
+ let best = 0
105
+ for (const field of fields) {
106
+ if (typeof field[1] !== 'string') continue
107
+ const matched = matchedTerms(terms, field[1])
108
+ if (matched.size <= best) continue
109
+ best = matched.size
110
+ hit = field
111
+ anchor = [...matched][0]
112
+ }
113
+ }
114
+ if (!hit) return null
115
+ const [field, text, at] = hit
116
+ const evidence = [{ field, at, text: excerpt(text, anchor) }]
117
+ if (field === 'then.quote' && row.then.quote.source) evidence[0].source = row.then.quote.source
118
+ const latest = row.later.at(-1)
119
+ if (latest?.thought && (field !== 'later.thought' || at !== latest.at || text !== latest.thought)) {
120
+ evidence.push({ field: 'later.thought', at: latest.at, text: excerpt(latest.thought, topic) })
121
+ }
122
+ return { id: row.id, day: row.day, match, evidence }
123
+ }
124
+
125
+ export function recallDetail(dir, query, { asOf = null } = {}) {
126
+ if (typeof query !== 'string' || !query.trim() || query.length > 500) {
127
+ throw new Error('Expected a question of 1 to 500 characters(请提供 1 到 500 字的问题)')
128
+ }
129
+ const { topic, attribute } = splitQuestion(query)
130
+ const result = { status: 'unmatched', value: null, attribute, candidates: [] }
131
+ if (!topic) return result
132
+ // A recognized attribute lets us look for the intact subject anywhere in the
133
+ // visible record, including a scene that the general recall index skips.
134
+ const visible = attribute
135
+ ? loadAll(dir, { asOf }).filter(row => !row.sealed).sort((a, b) => String(b.at).localeCompare(String(a.at)))
136
+ : null
137
+
138
+ const collect = (subject) => {
139
+ const rows = visible || recall(dir, subject, { asOf, limit: 3 })
140
+ const { terms } = queryTerms(subject)
141
+ const clues = attribute ? eventClues(subject) : null
142
+ const candidates = []
143
+ const leads = []
144
+ let value = null
145
+ for (const row of rows) {
146
+ const item = candidate(row, subject, attribute, terms, clues)
147
+ if (!item) continue
148
+ if (attribute && item.match === 'terms') {
149
+ if (leads.length < 3) leads.push(item)
150
+ continue
151
+ }
152
+ candidates.push(item)
153
+ if (candidates.length === 1 && attribute) value = directValue(row, subject, attribute)
154
+ if (candidates.length === 3) break
155
+ }
156
+ if (!candidates.length) candidates.push(...leads)
157
+ return { candidates, value }
158
+ }
159
+
160
+ let scan = collect(topic)
161
+ // 带定语的说法(“我织的那条围巾”)先在原句里找;找不到再退到中心词。
162
+ if (!scan.candidates.length) {
163
+ const head = headTopic(topic)
164
+ if (head && head !== topic) scan = collect(head)
165
+ }
166
+
167
+ result.candidates = scan.candidates
168
+ if (result.candidates.length > 1) result.status = 'ambiguous'
169
+ else if (result.candidates.length === 1) {
170
+ result.status = scan.value === null ? 'related' : 'supported'
171
+ result.value = scan.value
172
+ }
173
+ return result
174
+ }
@@ -1,10 +1,10 @@
1
- export interface EventLog<T> {
2
- FILE: string
3
- eventsFile(memDir: string): string
4
- readAll(memDir: string): { rows: T[]; bad: number }
5
- /** 锁内重读 → judge 决定要不要追加(返回 null 即 noop) */
6
- decide(memDir: string, judge: (rows: T[]) => T | null, opts?: Record<string, unknown>): { row: T | null; noop: boolean }
7
- }
8
-
9
- export function createLog<T = Record<string, unknown>>(fileName: string, opts?: { valid?: (row: T) => boolean }): EventLog<T>
10
- export function stamp(): { at: string; day: string }
1
+ export interface EventLog<T> {
2
+ FILE: string
3
+ eventsFile(memDir: string): string
4
+ readAll(memDir: string): { rows: T[]; bad: number }
5
+ /** 锁内重读 → judge 决定要不要追加(返回 null 即 noop) */
6
+ decide(memDir: string, judge: (rows: T[]) => T | null, opts?: Record<string, unknown>): { row: T | null; noop: boolean }
7
+ }
8
+
9
+ export function createLog<T = Record<string, unknown>>(fileName: string, opts?: { valid?: (row: T) => boolean }): EventLog<T>
10
+ export function stamp(): { at: string; day: string }
package/lib/event-log.js CHANGED
@@ -1,61 +1,61 @@
1
- // 只追加的事件文件:一行一个 JSON。新加的事件类型共用这一份读写,不再各抄一遍
2
- // - readAll:坏行跳过、计数,不阻断读取
3
- // - decide:同一把锁里「重读 → 判断 → 追加」,重复提交只记一次
4
- import fs from 'node:fs'
5
- import path from 'node:path'
6
- import { withFileLock } from './file-lock.js'
7
-
8
- export function createLog(fileName, { valid = (r) => Boolean(r) } = {}) {
9
- const eventsFile = (memDir) => path.join(memDir, fileName)
10
-
11
- function readAll(memDir) {
12
- let raw = ''
13
- try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
14
- const rows = []
15
- let bad = 0
16
- for (const line of raw.split('\n')) {
17
- if (!line.trim()) continue
18
- try {
19
- const r = JSON.parse(line)
20
- if (r && valid(r)) rows.push(r)
21
- else bad += 1
22
- } catch { bad += 1 }
23
- }
24
- return { rows, bad }
25
- }
26
-
27
- // 调用前必须已经持有锁
28
- function appendUnlocked(memDir, row) {
29
- const file = eventsFile(memDir)
30
- let prefix = ''
31
- try {
32
- const st = fs.statSync(file)
33
- if (st.size) {
34
- const fd = fs.openSync(file, 'r')
35
- const buf = Buffer.alloc(1)
36
- fs.readSync(fd, buf, 0, 1, st.size - 1)
37
- fs.closeSync(fd)
38
- if (buf[0] !== 10) prefix = '\n'
39
- }
40
- } catch { }
41
- fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
42
- return row
43
- }
44
-
45
- // judge(rows) 返回要追加的那一行,或 null 表示不用写(noop)
46
- function decide(memDir, judge, opts = {}) {
47
- fs.mkdirSync(memDir, { recursive: true })
48
- return withFileLock(eventsFile(memDir) + '.lock', () => {
49
- const row = judge(readAll(memDir).rows)
50
- if (!row) return { row: null, noop: true }
51
- return { row: appendUnlocked(memDir, row), noop: false }
52
- }, opts)
53
- }
54
-
55
- return { FILE: fileName, eventsFile, readAll, decide }
56
- }
57
-
58
- export const stamp = () => {
59
- const now = new Date()
60
- return { at: now.toISOString(), day: now.toLocaleDateString('sv-SE') }
61
- }
1
+ // 只追加的事件文件:一行一个 JSON。新加的事件类型共用这一份读写,不再各抄一遍
2
+ // - readAll:坏行跳过、计数,不阻断读取
3
+ // - decide:同一把锁里「重读 → 判断 → 追加」,重复提交只记一次
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+ import { withFileLock } from './file-lock.js'
7
+
8
+ export function createLog(fileName, { valid = (r) => Boolean(r) } = {}) {
9
+ const eventsFile = (memDir) => path.join(memDir, fileName)
10
+
11
+ function readAll(memDir) {
12
+ let raw = ''
13
+ try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
14
+ const rows = []
15
+ let bad = 0
16
+ for (const line of raw.split('\n')) {
17
+ if (!line.trim()) continue
18
+ try {
19
+ const r = JSON.parse(line)
20
+ if (r && valid(r)) rows.push(r)
21
+ else bad += 1
22
+ } catch { bad += 1 }
23
+ }
24
+ return { rows, bad }
25
+ }
26
+
27
+ // 调用前必须已经持有锁
28
+ function appendUnlocked(memDir, row) {
29
+ const file = eventsFile(memDir)
30
+ let prefix = ''
31
+ try {
32
+ const st = fs.statSync(file)
33
+ if (st.size) {
34
+ const fd = fs.openSync(file, 'r')
35
+ const buf = Buffer.alloc(1)
36
+ fs.readSync(fd, buf, 0, 1, st.size - 1)
37
+ fs.closeSync(fd)
38
+ if (buf[0] !== 10) prefix = '\n'
39
+ }
40
+ } catch { }
41
+ fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
42
+ return row
43
+ }
44
+
45
+ // judge(rows) 返回要追加的那一行,或 null 表示不用写(noop)
46
+ function decide(memDir, judge, opts = {}) {
47
+ fs.mkdirSync(memDir, { recursive: true })
48
+ return withFileLock(eventsFile(memDir) + '.lock', () => {
49
+ const row = judge(readAll(memDir).rows)
50
+ if (!row) return { row: null, noop: true }
51
+ return { row: appendUnlocked(memDir, row), noop: false }
52
+ }, opts)
53
+ }
54
+
55
+ return { FILE: fileName, eventsFile, readAll, decide }
56
+ }
57
+
58
+ export const stamp = () => {
59
+ const now = new Date()
60
+ return { at: now.toISOString(), day: now.toLocaleDateString('sv-SE') }
61
+ }
@@ -1,9 +1,9 @@
1
- import type { Fact, Verdict } from './evidence-policy.js'
2
- import type { Experience } from './self-experience.js'
3
-
4
- export function moodFacts(experiences: Experience[], opts?: { subject?: string }): Fact[]
5
- export function quoteFacts(experiences: Experience[], opts?: { subject?: string }): Fact[]
6
- /** 她对每件事的感觉:slot 为 feeling:<经历 id>;后来写了感觉的后记会取代前一条 */
7
- export function feelingFacts(experiences: Experience[], opts?: { subject?: string }): Fact[]
8
- export function factsFromExperiences(experiences: Experience[], opts?: { subject?: string }): Fact[]
1
+ import type { Fact, Verdict } from './evidence-policy.js'
2
+ import type { Experience } from './self-experience.js'
3
+
4
+ export function moodFacts(experiences: Experience[], opts?: { subject?: string }): Fact[]
5
+ export function quoteFacts(experiences: Experience[], opts?: { subject?: string }): Fact[]
6
+ /** 她对每件事的感觉:slot 为 feeling:<经历 id>;后来写了感觉的后记会取代前一条 */
7
+ export function feelingFacts(experiences: Experience[], opts?: { subject?: string }): Fact[]
8
+ export function factsFromExperiences(experiences: Experience[], opts?: { subject?: string }): Fact[]
9
9
  export function ask(experiences: Experience[], opts: { slot: string; at?: string; subject?: string }): Verdict