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
|
@@ -1,63 +1,63 @@
|
|
|
1
|
-
// 把「她的经历」桥到证据层:只抽有原文锚的东西,不推断
|
|
2
|
-
// 情绪快照 → mood fact;原文锚 → quote:<source> fact;当时/后来的感觉 → feeling:<id> fact
|
|
3
|
-
import { query } from './evidence-policy.js'
|
|
4
|
-
|
|
5
|
-
const moodOf = (r) => {
|
|
6
|
-
const state = r.then && r.then.state
|
|
7
|
-
if (!state || typeof state !== 'object') return ''
|
|
8
|
-
return String(state.mood || '')
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
export function moodFacts(experiences, { subject = 'self' } = {}) {
|
|
12
|
-
const facts = []
|
|
13
|
-
for (const r of experiences || []) {
|
|
14
|
-
const mood = moodOf(r)
|
|
15
|
-
if (!mood) continue
|
|
16
|
-
const at = (r.then.state && r.then.state.at) || r.at
|
|
17
|
-
if (!at) continue
|
|
18
|
-
facts.push({ id: 'mood:' + r.id, subject, slot: 'mood', value: mood, at, source: 'then.state' })
|
|
19
|
-
}
|
|
20
|
-
return facts
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export function quoteFacts(experiences, { subject = 'self' } = {}) {
|
|
24
|
-
const facts = []
|
|
25
|
-
for (const r of experiences || []) {
|
|
26
|
-
const q = r.then && r.then.quote
|
|
27
|
-
if (!q || !q.text) continue
|
|
28
|
-
const slot = 'quote:' + (q.source || 'unknown')
|
|
29
|
-
facts.push({ id: 'quote:' + r.id, subject, slot, value: q.text, at: r.at, source: q.source || 'then.quote' })
|
|
30
|
-
}
|
|
31
|
-
return facts
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
// 她对这一件事的感觉:当时写下的是第一条;后来某条后记写了感觉,就取代前一条(取代链可查)
|
|
35
|
-
// slot 为 feeling:<经历 id>。没写感觉的后记不算数——不替她推断"应该已经不难过了"
|
|
36
|
-
export function feelingFacts(experiences, { subject = 'self' } = {}) {
|
|
37
|
-
const facts = []
|
|
38
|
-
for (const r of experiences || []) {
|
|
39
|
-
const slot = 'feeling:' + r.id
|
|
40
|
-
let prev = ''
|
|
41
|
-
const thenFeeling = (r.then && Array.isArray(r.then.feeling)) ? r.then.feeling : []
|
|
42
|
-
if (thenFeeling.length && r.at) {
|
|
43
|
-
prev = 'feeling:' + r.id + ':then'
|
|
44
|
-
facts.push({ id: prev, subject, slot, value: thenFeeling.join('、'), at: r.at, source: 'then.feeling' })
|
|
45
|
-
}
|
|
46
|
-
for (const [i, l] of (r.later || []).entries()) {
|
|
47
|
-
if (!Array.isArray(l.feeling) || !l.feeling.length || !l.at) continue
|
|
48
|
-
const id = 'feeling:' + r.id + ':later:' + i
|
|
49
|
-
facts.push({ id, subject, slot, value: l.feeling.join('、'), at: l.at, source: 'later.feeling', ...(prev ? { supersedes: prev } : {}) })
|
|
50
|
-
prev = id
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
return facts
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export function factsFromExperiences(experiences, opts = {}) {
|
|
57
|
-
return [...moodFacts(experiences, opts), ...quoteFacts(experiences, opts), ...feelingFacts(experiences, opts)]
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// 问她某个时点是什么心情/读到过什么:没有就返回 unknown,不猜
|
|
61
|
-
export function ask(experiences, { slot, at, subject = 'self' } = {}) {
|
|
62
|
-
return query(factsFromExperiences(experiences, { subject }), { subject, slot, at })
|
|
1
|
+
// 把「她的经历」桥到证据层:只抽有原文锚的东西,不推断
|
|
2
|
+
// 情绪快照 → mood fact;原文锚 → quote:<source> fact;当时/后来的感觉 → feeling:<id> fact
|
|
3
|
+
import { query } from './evidence-policy.js'
|
|
4
|
+
|
|
5
|
+
const moodOf = (r) => {
|
|
6
|
+
const state = r.then && r.then.state
|
|
7
|
+
if (!state || typeof state !== 'object') return ''
|
|
8
|
+
return String(state.mood || '')
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function moodFacts(experiences, { subject = 'self' } = {}) {
|
|
12
|
+
const facts = []
|
|
13
|
+
for (const r of experiences || []) {
|
|
14
|
+
const mood = moodOf(r)
|
|
15
|
+
if (!mood) continue
|
|
16
|
+
const at = (r.then.state && r.then.state.at) || r.at
|
|
17
|
+
if (!at) continue
|
|
18
|
+
facts.push({ id: 'mood:' + r.id, subject, slot: 'mood', value: mood, at, source: 'then.state' })
|
|
19
|
+
}
|
|
20
|
+
return facts
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function quoteFacts(experiences, { subject = 'self' } = {}) {
|
|
24
|
+
const facts = []
|
|
25
|
+
for (const r of experiences || []) {
|
|
26
|
+
const q = r.then && r.then.quote
|
|
27
|
+
if (!q || !q.text) continue
|
|
28
|
+
const slot = 'quote:' + (q.source || 'unknown')
|
|
29
|
+
facts.push({ id: 'quote:' + r.id, subject, slot, value: q.text, at: r.at, source: q.source || 'then.quote' })
|
|
30
|
+
}
|
|
31
|
+
return facts
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// 她对这一件事的感觉:当时写下的是第一条;后来某条后记写了感觉,就取代前一条(取代链可查)
|
|
35
|
+
// slot 为 feeling:<经历 id>。没写感觉的后记不算数——不替她推断"应该已经不难过了"
|
|
36
|
+
export function feelingFacts(experiences, { subject = 'self' } = {}) {
|
|
37
|
+
const facts = []
|
|
38
|
+
for (const r of experiences || []) {
|
|
39
|
+
const slot = 'feeling:' + r.id
|
|
40
|
+
let prev = ''
|
|
41
|
+
const thenFeeling = (r.then && Array.isArray(r.then.feeling)) ? r.then.feeling : []
|
|
42
|
+
if (thenFeeling.length && r.at) {
|
|
43
|
+
prev = 'feeling:' + r.id + ':then'
|
|
44
|
+
facts.push({ id: prev, subject, slot, value: thenFeeling.join('、'), at: r.at, source: 'then.feeling' })
|
|
45
|
+
}
|
|
46
|
+
for (const [i, l] of (r.later || []).entries()) {
|
|
47
|
+
if (!Array.isArray(l.feeling) || !l.feeling.length || !l.at) continue
|
|
48
|
+
const id = 'feeling:' + r.id + ':later:' + i
|
|
49
|
+
facts.push({ id, subject, slot, value: l.feeling.join('、'), at: l.at, source: 'later.feeling', ...(prev ? { supersedes: prev } : {}) })
|
|
50
|
+
prev = id
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return facts
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function factsFromExperiences(experiences, opts = {}) {
|
|
57
|
+
return [...moodFacts(experiences, opts), ...quoteFacts(experiences, opts), ...feelingFacts(experiences, opts)]
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 问她某个时点是什么心情/读到过什么:没有就返回 unknown,不猜
|
|
61
|
+
export function ask(experiences, { slot, at, subject = 'self' } = {}) {
|
|
62
|
+
return query(factsFromExperiences(experiences, { subject }), { subject, slot, at })
|
|
63
63
|
}
|
package/lib/evidence-policy.js
CHANGED
|
@@ -103,9 +103,9 @@ export function query(facts, { subject, slot = 'default', at = new Date().toISOS
|
|
|
103
103
|
export function hasSuccessor(facts, id, at = new Date().toISOString()) {
|
|
104
104
|
const all = normalizeFacts(facts)
|
|
105
105
|
const base = all.find((f) => f.id === id)
|
|
106
|
-
if (!base) return { ok: false, reason: '
|
|
106
|
+
if (!base) return { ok: false, reason: 'Record not found(找不到这条记录)' }
|
|
107
107
|
const atT = ts(at)
|
|
108
|
-
if (atT === null) return { ok: false, reason: 'as-of
|
|
108
|
+
if (atT === null) return { ok: false, reason: 'Invalid as-of time(as-of 时间不合法)' }
|
|
109
109
|
const later = all.filter((f) => f.subject === base.subject && f.slot === base.slot && f.t > base.t && f.t <= atT)
|
|
110
110
|
return { ok: true, hasSuccessor: later.length > 0, successors: later }
|
|
111
111
|
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 事实时间线契约:给「同槽位版本链」补三样东西。
|
|
3
|
+
*
|
|
4
|
+
* - 值轴 validFrom / validUntil:这件事在世界上什么时候为真(本模块不写)
|
|
5
|
+
* - 知轴 factVersionAt / invalidatedAt:她什么时候知道、什么时候不再这么认为
|
|
6
|
+
* - 序轴 version:同一槽位里谁在谁后面(追加顺序比时钟可信)
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export type SupersedeReason = 'update' | 'correction' | 'expiry' | 'retraction' | 'dedupe' | 'unknown';
|
|
10
|
+
|
|
11
|
+
export interface FactRecordLike {
|
|
12
|
+
id?: string;
|
|
13
|
+
version?: number | string;
|
|
14
|
+
revisionOf?: string;
|
|
15
|
+
supersededById?: string;
|
|
16
|
+
factVersionAt?: number | string;
|
|
17
|
+
invalidatedAt?: number | string | null;
|
|
18
|
+
supersedeReason?: SupersedeReason | string;
|
|
19
|
+
validFrom?: number | string | null;
|
|
20
|
+
validUntil?: number | string | null;
|
|
21
|
+
lineageId?: string;
|
|
22
|
+
[key: string]: unknown;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface SuccessionPatch {
|
|
26
|
+
before: {
|
|
27
|
+
supersededById: string;
|
|
28
|
+
declinedAt: null;
|
|
29
|
+
invalidatedAt: number | null;
|
|
30
|
+
supersedeReason: SupersedeReason;
|
|
31
|
+
};
|
|
32
|
+
after: {
|
|
33
|
+
revisionOf: string;
|
|
34
|
+
version: number;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface LineageIssue {
|
|
39
|
+
code: 'I0' | 'I1' | 'I2' | 'I3' | 'I4' | 'I5';
|
|
40
|
+
id: string;
|
|
41
|
+
message: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ChainPatch {
|
|
45
|
+
id: string;
|
|
46
|
+
version: number;
|
|
47
|
+
supersedeReason: SupersedeReason | null;
|
|
48
|
+
invalidatedAt: number | null;
|
|
49
|
+
supersededById: string;
|
|
50
|
+
revisionOf?: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ChainPlan {
|
|
54
|
+
order: FactRecordLike[];
|
|
55
|
+
patches: ChainPatch[];
|
|
56
|
+
issues: LineageIssue[];
|
|
57
|
+
orderBy: 'pointer' | 'time' | 'empty';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function nextFactVersion(predecessor?: FactRecordLike | null): number;
|
|
61
|
+
export function stampSuccession(
|
|
62
|
+
before: FactRecordLike,
|
|
63
|
+
after: FactRecordLike,
|
|
64
|
+
options?: { reason?: SupersedeReason | string; at?: number }
|
|
65
|
+
): SuccessionPatch;
|
|
66
|
+
export function applySuccession<T extends FactRecordLike, U extends FactRecordLike>(
|
|
67
|
+
before: T,
|
|
68
|
+
after: U,
|
|
69
|
+
options?: { reason?: SupersedeReason | string; at?: number }
|
|
70
|
+
): { before: T; after: U; patch: SuccessionPatch };
|
|
71
|
+
export function validateLineage(records: FactRecordLike[] | null | undefined): LineageIssue[];
|
|
72
|
+
export function planChainVersions(records: FactRecordLike[] | null | undefined): ChainPlan;
|
|
73
|
+
export const SUPERSEDE_REASON_VALUES: SupersedeReason[];
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 事实时间线契约(阶段 A):给「同槽位版本链」补齐三样一直缺的东西。
|
|
3
|
+
*
|
|
4
|
+
* 设计文档 `记忆版本与时间线-设计-20261114.md` §1.2 的判断:
|
|
5
|
+
* 一个 `validUntil` 同时承担了三个轴,所以拆开——
|
|
6
|
+
* - 值轴 validFrom / validUntil:这件事在世界上什么时候为真
|
|
7
|
+
* - 知轴 factVersionAt / **invalidatedAt**:她什么时候知道、什么时候不再这么认为
|
|
8
|
+
* - 序轴 **version**:同一槽位里谁在谁后面(追加顺序永远可信,时钟不一定)
|
|
9
|
+
*
|
|
10
|
+
* 本模块只做纯计算,不读写存储:
|
|
11
|
+
* - `nextFactVersion`:新记录在链内的序号
|
|
12
|
+
* - `stampSuccession`:后继取代前驱时,两边各该补什么
|
|
13
|
+
* - `validateLineage`:把链拿出来校验,返回问题清单(对应设计的 I1–I3)
|
|
14
|
+
*
|
|
15
|
+
* 不变量(判读口径):
|
|
16
|
+
* I1 同一 lineageId 内 version 唯一、从 1 连续、不跳号
|
|
17
|
+
* I2 被取代记录的 invalidatedAt 等于后继的 factVersionAt(知轴终点接上起点)
|
|
18
|
+
* I3 后继的 revisionOf 指向前驱 id,前驱的 supersededById 指向后继 id
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const SUPERSEDE_REASONS = new Set(['update', 'correction', 'expiry', 'retraction', 'dedupe', 'unknown']);
|
|
22
|
+
|
|
23
|
+
function ms(value) {
|
|
24
|
+
const n = Number(value);
|
|
25
|
+
return Number.isFinite(n) && n > 0 ? n : 0;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 链内下一个序号:没有前驱就是 1,否则前驱序号 + 1。前驱没有序号时按 1 起算,不猜。 */
|
|
29
|
+
export function nextFactVersion(predecessor) {
|
|
30
|
+
const base = Number(predecessor?.version);
|
|
31
|
+
if (!Number.isFinite(base) || base < 1) return 1;
|
|
32
|
+
return Math.floor(base) + 1;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 后继取代前驱时两边的补丁。
|
|
37
|
+
*
|
|
38
|
+
* 只补「序轴」和「知轴终点」,不碰值轴:validFrom / validUntil 必须来自证据或人工裁决,
|
|
39
|
+
* 不能因为看到一条更晚的记录就替它编一个有效期(设计文档 §2.5 明确禁止)。
|
|
40
|
+
*/
|
|
41
|
+
export function stampSuccession(before, after, { reason = 'update', at } = {}) {
|
|
42
|
+
const beforeId = String(before?.id || '');
|
|
43
|
+
const afterId = String(after?.id || '');
|
|
44
|
+
if (!beforeId || !afterId || beforeId === afterId) throw new Error('后继取代需要两个不同的记录 id');
|
|
45
|
+
const invalidatedAt = ms(at) || ms(after?.factVersionAt) || ms(before?.factVersionAt) || null;
|
|
46
|
+
const supersedeReason = SUPERSEDE_REASONS.has(reason) ? reason : 'unknown';
|
|
47
|
+
return {
|
|
48
|
+
before: {
|
|
49
|
+
supersededById: afterId,
|
|
50
|
+
declinedAt: null,
|
|
51
|
+
// 知轴终点:她不再认为这是当前值的时刻
|
|
52
|
+
invalidatedAt,
|
|
53
|
+
supersedeReason
|
|
54
|
+
},
|
|
55
|
+
after: {
|
|
56
|
+
revisionOf: beforeId,
|
|
57
|
+
// 序轴:链内序号。前驱缺序号说明它是链头,按 1 算。
|
|
58
|
+
version: nextFactVersion({ version: Number(before?.version) || 1 })
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 把补丁写回对象(就地),返回被改动的两个对象,便于调用方决定何时落盘。 */
|
|
64
|
+
export function applySuccession(before, after, options = {}) {
|
|
65
|
+
const patch = stampSuccession(before, after, options);
|
|
66
|
+
// 链头补齐序号,否则整条链校验永远差第一格。
|
|
67
|
+
if (before && before.version == null) before.version = 1; // eslint-disable-line no-param-reassign
|
|
68
|
+
Object.assign(before, patch.before);
|
|
69
|
+
Object.assign(after, patch.after);
|
|
70
|
+
return { before, after, patch };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 校验一条链。返回 [] 表示通过;每条问题带 code / id / message,方便直接进报告。 */
|
|
74
|
+
export function validateLineage(records) {
|
|
75
|
+
const rows = (Array.isArray(records) ? records : []).filter(Boolean);
|
|
76
|
+
const issues = [];
|
|
77
|
+
if (!rows.length) return issues;
|
|
78
|
+
|
|
79
|
+
const byId = new Map();
|
|
80
|
+
for (const row of rows) {
|
|
81
|
+
const id = String(row.id || '');
|
|
82
|
+
if (!id) {
|
|
83
|
+
issues.push({ code: 'I0', id: '', message: '记录缺少 id' });
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (byId.has(id)) issues.push({ code: 'I0', id, message: '同一链里出现重复 id' });
|
|
87
|
+
// 保留第一次出现的记录继续校验,否则重复 id 会把前面的指针问题遮掉。
|
|
88
|
+
else byId.set(id, row);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// I1:序号唯一、从 1 连续
|
|
92
|
+
const versions = new Map();
|
|
93
|
+
for (const row of byId.values()) {
|
|
94
|
+
const version = Number(row.version);
|
|
95
|
+
if (!Number.isFinite(version) || version < 1 || Math.floor(version) !== version) {
|
|
96
|
+
issues.push({ code: 'I1', id: row.id, message: `version 不是正整数:${row.version}` });
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (versions.has(version)) {
|
|
100
|
+
issues.push({ code: 'I1', id: row.id, message: `version ${version} 与 ${versions.get(version)} 重复` });
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
versions.set(version, row.id);
|
|
104
|
+
}
|
|
105
|
+
if (versions.size) {
|
|
106
|
+
const max = Math.max(...versions.keys());
|
|
107
|
+
for (let expected = 1; expected <= max; expected++) {
|
|
108
|
+
if (!versions.has(expected)) issues.push({ code: 'I1', id: '', message: `缺少 version ${expected}` });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// I2 / I3:指针对称,知轴终点接上后继起点
|
|
113
|
+
for (const row of byId.values()) {
|
|
114
|
+
const nextId = String(row.supersededById || '');
|
|
115
|
+
if (nextId) {
|
|
116
|
+
const next = byId.get(nextId);
|
|
117
|
+
if (!next) {
|
|
118
|
+
issues.push({ code: 'I3', id: row.id, message: `supersededById 指向链外记录 ${nextId}` });
|
|
119
|
+
} else {
|
|
120
|
+
if (String(next.revisionOf || '') !== String(row.id)) {
|
|
121
|
+
issues.push({ code: 'I3', id: row.id, message: `后继 ${nextId} 的 revisionOf 不是本记录` });
|
|
122
|
+
}
|
|
123
|
+
const invalidatedAt = ms(row.invalidatedAt);
|
|
124
|
+
const nextStart = ms(next.factVersionAt);
|
|
125
|
+
if (invalidatedAt && nextStart && invalidatedAt !== nextStart) {
|
|
126
|
+
issues.push({ code: 'I2', id: row.id, message: `invalidatedAt(${invalidatedAt}) 与后继 factVersionAt(${nextStart}) 不一致` });
|
|
127
|
+
}
|
|
128
|
+
if (!invalidatedAt) {
|
|
129
|
+
issues.push({ code: 'I2', id: row.id, message: '有后继却缺 invalidatedAt' });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
} else if (ms(row.invalidatedAt)) {
|
|
133
|
+
issues.push({ code: 'I2', id: row.id, message: '写了 invalidatedAt 却没有后继' });
|
|
134
|
+
}
|
|
135
|
+
const reason = row.supersedeReason;
|
|
136
|
+
if (reason !== undefined && reason !== null && !SUPERSEDE_REASONS.has(String(reason))) {
|
|
137
|
+
issues.push({ code: 'I4', id: row.id, message: `supersedeReason 取值非法:${reason}` });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return issues;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export const SUPERSEDE_REASON_VALUES = [...SUPERSEDE_REASONS];
|
|
145
|
+
/**
|
|
146
|
+
* 迁移规划:给一条链排出序号。
|
|
147
|
+
*
|
|
148
|
+
* 两条原则:
|
|
149
|
+
* 1. 已有指针优先。revisionOf / supersededById 是写入时留下的追加记录,比时钟可信(设计文档 §0 序轴)。
|
|
150
|
+
* 2. 指针排不出完整路径时,退回按 factVersionAt 排序,并标记 orderBy='time' 让人复核,不假装指针是对的。
|
|
151
|
+
*
|
|
152
|
+
* 不写存储:返回每条记录该补的字段,由调用方决定是否落盘。
|
|
153
|
+
*/
|
|
154
|
+
export function planChainVersions(records) {
|
|
155
|
+
const rows = (Array.isArray(records) ? records : []).filter(Boolean)
|
|
156
|
+
const issues = []
|
|
157
|
+
if (!rows.length) return { order: [], patches: [], issues, orderBy: 'empty' }
|
|
158
|
+
|
|
159
|
+
const byId = new Map()
|
|
160
|
+
for (const row of rows) {
|
|
161
|
+
const id = String(row.id || '')
|
|
162
|
+
if (!id) { issues.push({ code: 'I0', id: '', message: '记录缺少 id' }); continue }
|
|
163
|
+
if (byId.has(id)) { issues.push({ code: 'I0', id, message: '同一链里出现重复 id' }); continue }
|
|
164
|
+
byId.set(id, row)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const defined = [...byId.values()]
|
|
168
|
+
const hasForward = (row) => Boolean(String(row.supersededById || ''))
|
|
169
|
+
const hasBackward = (row) => Boolean(String(row.revisionOf || ''))
|
|
170
|
+
const heads = defined.filter((row) => !hasBackward(row))
|
|
171
|
+
let order = []
|
|
172
|
+
|
|
173
|
+
// 链头不唯一 = 好几个「第一版」并存,指针没给出先后。按时间硬排会编出一个假顺序,
|
|
174
|
+
// 所以这里直接返回歧义,不给补丁,交给人看。
|
|
175
|
+
if (heads.length > 1) {
|
|
176
|
+
issues.push({ code: 'I6', id: '', message: `出现 ${heads.length} 个链头,无法确定先后` })
|
|
177
|
+
return { order: [], patches: [], issues, orderBy: 'ambiguous' }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// 只有「唯一链头 + 一路向前、不重复、走完全部记录」才算指针排得出来。
|
|
181
|
+
const walkable = heads.length === 1 && defined.every((row) => !hasBackward(row) || byId.has(String(row.revisionOf)))
|
|
182
|
+
if (walkable) {
|
|
183
|
+
const seen = new Set()
|
|
184
|
+
let cursor = heads[0]
|
|
185
|
+
while (cursor) {
|
|
186
|
+
const id = String(cursor.id)
|
|
187
|
+
if (seen.has(id)) { issues.push({ code: 'I5', id, message: '指针成环' }); break }
|
|
188
|
+
seen.add(id)
|
|
189
|
+
order.push(cursor)
|
|
190
|
+
const nextId = String(cursor.supersededById || '')
|
|
191
|
+
if (!nextId) break
|
|
192
|
+
const next = byId.get(nextId)
|
|
193
|
+
if (!next) { issues.push({ code: 'I3', id, message: `supersededById 指向链外记录 ${nextId}` }); break }
|
|
194
|
+
cursor = next
|
|
195
|
+
}
|
|
196
|
+
if (order.length !== defined.length) {
|
|
197
|
+
issues.push({ code: 'I5', id: '', message: `指针只串起 ${order.length}/${defined.length} 条,退回按时间排序` })
|
|
198
|
+
order = []
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
let orderBy = 'pointer'
|
|
203
|
+
if (!order.length) {
|
|
204
|
+
orderBy = 'time'
|
|
205
|
+
order = [...defined].sort((a, b) => (ms(a.factVersionAt) || 0) - (ms(b.factVersionAt) || 0) || String(a.id).localeCompare(String(b.id)))
|
|
206
|
+
if (defined.some(hasBackward) || defined.some(hasForward)) {
|
|
207
|
+
issues.push({ code: 'I5', id: '', message: '指针无法排出完整链,已按时间排序,需人工复核' })
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const patches = order.map((row, index) => {
|
|
212
|
+
const next = order[index + 1] || null
|
|
213
|
+
const patch = { id: String(row.id), version: index + 1, supersedeReason: next ? 'unknown' : null }
|
|
214
|
+
if (next) {
|
|
215
|
+
patch.invalidatedAt = ms(next.factVersionAt) || null
|
|
216
|
+
patch.supersededById = String(next.id)
|
|
217
|
+
} else {
|
|
218
|
+
patch.invalidatedAt = null
|
|
219
|
+
patch.supersededById = ''
|
|
220
|
+
}
|
|
221
|
+
if (index > 0) patch.revisionOf = String(order[index - 1].id)
|
|
222
|
+
return patch
|
|
223
|
+
})
|
|
224
|
+
|
|
225
|
+
return { order, patches, issues, orderBy }
|
|
226
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** 时间线查询:知轴 / 值轴 / 变化对比。纯函数,不读写存储。 */
|
|
2
|
+
|
|
3
|
+
export interface FactRow {
|
|
4
|
+
id?: string;
|
|
5
|
+
version?: number | string;
|
|
6
|
+
revisionOf?: string;
|
|
7
|
+
supersededById?: string;
|
|
8
|
+
factVersionAt?: number | string;
|
|
9
|
+
invalidatedAt?: number | string | null;
|
|
10
|
+
validFrom?: number | string | null;
|
|
11
|
+
validUntil?: number | string | null;
|
|
12
|
+
supersedeReason?: string;
|
|
13
|
+
lineageId?: string;
|
|
14
|
+
[key: string]: unknown;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ChangeEntry {
|
|
18
|
+
id: string;
|
|
19
|
+
version: number | null;
|
|
20
|
+
at: number;
|
|
21
|
+
revisionOf: string;
|
|
22
|
+
reason: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function orderChain(records: FactRow[] | null | undefined): FactRow[];
|
|
26
|
+
export function currentVersion(records: FactRow[] | null | undefined): FactRow | null;
|
|
27
|
+
export function versionKnownAt(records: FactRow[] | null | undefined, asOf: number): FactRow | null;
|
|
28
|
+
export function valueValidAt(records: FactRow[] | null | undefined, asOf: number): FactRow | null;
|
|
29
|
+
export function changesBetween(records: FactRow[] | null | undefined, from: number, to: number): ChangeEntry[];
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 时间线查询:用已有字段回答三种问法。
|
|
3
|
+
*
|
|
4
|
+
* 设计文档 §2.1 说得很清楚:所有问法都从两个谓词长出来——
|
|
5
|
+
* - **知轴**:她在这个时刻「知道」哪一版? factVersionAt <= t < invalidatedAt
|
|
6
|
+
* - **值轴**:这件事在这个时刻「为真」? validFrom <= t < validUntil
|
|
7
|
+
* 两者不能混:事实可以仍为真、但她还不知道(未来事实),也可以她已知道、但事实上已经变了。
|
|
8
|
+
*
|
|
9
|
+
* 这里只做纯计算,不读写存储。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
function ms(value) {
|
|
13
|
+
const n = Number(value);
|
|
14
|
+
return Number.isFinite(n) && n > 0 ? n : 0;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** 链按版本号升序;没有版本号的排最后,保持稳定。 */
|
|
18
|
+
export function orderChain(records) {
|
|
19
|
+
return (Array.isArray(records) ? records : [])
|
|
20
|
+
.filter(Boolean)
|
|
21
|
+
.slice()
|
|
22
|
+
.sort((a, b) => {
|
|
23
|
+
const va = Number(a.version);
|
|
24
|
+
const vb = Number(b.version);
|
|
25
|
+
const ha = Number.isFinite(va) && va > 0;
|
|
26
|
+
const hb = Number.isFinite(vb) && vb > 0;
|
|
27
|
+
if (ha && hb) return va - vb;
|
|
28
|
+
if (ha !== hb) return ha ? -1 : 1;
|
|
29
|
+
return (ms(a.factVersionAt) - ms(b.factVersionAt)) || String(a.id || '').localeCompare(String(b.id || ''));
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 当前版本:链里最后一个还有效的(没有后继、也没被 invalidatedAt 关掉)。 */
|
|
34
|
+
export function currentVersion(records) {
|
|
35
|
+
const chain = orderChain(records);
|
|
36
|
+
for (let i = chain.length - 1; i >= 0; i -= 1) {
|
|
37
|
+
const row = chain[i];
|
|
38
|
+
if (!String(row.supersededById || '') && !ms(row.invalidatedAt)) return row;
|
|
39
|
+
}
|
|
40
|
+
// 全部都已关闭时,返回最新那版(历史问题,调用方自己决定怎么讲)
|
|
41
|
+
return chain.length ? chain[chain.length - 1] : null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 知轴:在 asOf 时刻,她「认为」的是哪一版。
|
|
46
|
+
* 条件:factVersionAt <= asOf,且(没有 invalidatedAt,或 asOf < invalidatedAt)。
|
|
47
|
+
* 同一时刻有多版时取版本号最大的。
|
|
48
|
+
*/
|
|
49
|
+
export function versionKnownAt(records, asOf) {
|
|
50
|
+
const at = ms(asOf);
|
|
51
|
+
if (!at) return null;
|
|
52
|
+
const candidates = orderChain(records).filter((row) => {
|
|
53
|
+
const start = ms(row.factVersionAt);
|
|
54
|
+
if (!start || start > at) return false;
|
|
55
|
+
const end = ms(row.invalidatedAt);
|
|
56
|
+
return !end || at < end;
|
|
57
|
+
});
|
|
58
|
+
return candidates.length ? candidates[candidates.length - 1] : null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 值轴:在 asOf 时刻,这件事在世界上是否为真。
|
|
63
|
+
* validFrom 为 0 视为「不知道起点」,退回知轴(她什么时候知道的)。
|
|
64
|
+
*/
|
|
65
|
+
export function valueValidAt(records, asOf) {
|
|
66
|
+
const at = ms(asOf);
|
|
67
|
+
if (!at) return null;
|
|
68
|
+
const candidates = orderChain(records).filter((row) => {
|
|
69
|
+
const start = ms(row.validFrom) || ms(row.factVersionAt);
|
|
70
|
+
if (!start || start > at) return false;
|
|
71
|
+
const end = ms(row.validUntil);
|
|
72
|
+
return !end || at < end;
|
|
73
|
+
});
|
|
74
|
+
return candidates.length ? candidates[candidates.length - 1] : null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 两个时刻之间发生了什么:返回被新增、被取代的版本。
|
|
79
|
+
* 只列事实,不做解读。
|
|
80
|
+
*/
|
|
81
|
+
export function changesBetween(records, from, to) {
|
|
82
|
+
const start = ms(from);
|
|
83
|
+
const end = ms(to);
|
|
84
|
+
if (!start || !end || end <= start) return [];
|
|
85
|
+
return orderChain(records)
|
|
86
|
+
.filter((row) => {
|
|
87
|
+
const began = ms(row.factVersionAt);
|
|
88
|
+
return began > start && began <= end;
|
|
89
|
+
})
|
|
90
|
+
.map((row) => ({
|
|
91
|
+
id: String(row.id || ''),
|
|
92
|
+
version: Number(row.version) || null,
|
|
93
|
+
at: ms(row.factVersionAt),
|
|
94
|
+
revisionOf: String(row.revisionOf || ''),
|
|
95
|
+
reason: row.supersedeReason || ''
|
|
96
|
+
}));
|
|
97
|
+
}
|
package/lib/file-lock.js
CHANGED
|
@@ -17,7 +17,7 @@ export function withFileLock(lockPath, fn, { timeoutMs = 3000 } = {}) {
|
|
|
17
17
|
const st = fs.statSync(lockPath)
|
|
18
18
|
if (Date.now() - st.mtimeMs > 10000) { fs.rmSync(lockPath, { recursive: true, force: true }); continue }
|
|
19
19
|
} catch { /* 锁刚被释放 */ }
|
|
20
|
-
if (Date.now() - start > timeoutMs) throw new Error('
|
|
20
|
+
if (Date.now() - start > timeoutMs) throw new Error('The file is locked by another process; try again shortly.(文件被另一个进程锁着,稍后再试。)')
|
|
21
21
|
sleep(20)
|
|
22
22
|
}
|
|
23
23
|
}
|
package/lib/later-events.d.ts
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
export interface LaterEvent {
|
|
2
|
-
id: string
|
|
3
|
-
at: string
|
|
4
|
-
day: string
|
|
5
|
-
thought: string
|
|
6
|
-
reason: string
|
|
7
|
-
/** 她后来再想起时的感觉(0.12 起) */
|
|
8
|
-
feeling?: string[]
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
export function eventsFile(memDir: string): string
|
|
12
|
-
|
|
13
|
-
export function append(memDir: string, event: { id: string; thought: string; reason?: string; feeling?: string[] }, opts?: { timeoutMs?: number }): LaterEvent
|
|
14
|
-
|
|
15
|
-
export function readAll(memDir: string): { rows: LaterEvent[]; bad: number }
|
|
16
|
-
|
|
17
|
-
/** until:只要这一刻(毫秒时间戳)之前(含)的后记 */
|
|
18
|
-
export function groupByExp(memDir: string, opts?: { until?: number | null }): Map<string, LaterEvent[]>
|
|
19
|
-
|
|
20
|
-
export function list(memDir: string, opts?: { id?: string; limit?: number }): LaterEvent[]
|
|
21
|
-
|
|
1
|
+
export interface LaterEvent {
|
|
2
|
+
id: string
|
|
3
|
+
at: string
|
|
4
|
+
day: string
|
|
5
|
+
thought: string
|
|
6
|
+
reason: string
|
|
7
|
+
/** 她后来再想起时的感觉(0.12 起) */
|
|
8
|
+
feeling?: string[]
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function eventsFile(memDir: string): string
|
|
12
|
+
|
|
13
|
+
export function append(memDir: string, event: { id: string; thought: string; reason?: string; feeling?: string[] }, opts?: { timeoutMs?: number }): LaterEvent
|
|
14
|
+
|
|
15
|
+
export function readAll(memDir: string): { rows: LaterEvent[]; bad: number }
|
|
16
|
+
|
|
17
|
+
/** until:只要这一刻(毫秒时间戳)之前(含)的后记 */
|
|
18
|
+
export function groupByExp(memDir: string, opts?: { until?: number | null }): Map<string, LaterEvent[]>
|
|
19
|
+
|
|
20
|
+
export function list(memDir: string, opts?: { id?: string; limit?: number }): LaterEvent[]
|
|
21
|
+
|
|
22
22
|
export const internals: { FILE: string }
|