dsh-cortex-memory 0.4.21 → 0.4.146
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/CHANGELOG.md +2223 -7
- package/README.md +20 -9
- package/bench/migration-bench.mjs +1 -1
- package/bench/semantic-cn.js +7 -7
- package/bench/synthetic.js +2 -2
- package/bin/copy-db.mjs +47 -0
- package/bin/cortex.mjs +9 -4
- package/bin/repair.mjs +328 -0
- package/bin/verify.mjs +202 -0
- package/cordis.patch.yml +1 -1
- package/docs/install-windows.md +2 -2
- package/docs/models.md +1 -1
- package/docs/quota-compaction-design.md +175 -0
- package/index.js +27 -3
- package/package.json +3 -3
- package/src/adapters/shiori.js +1 -1
- package/src/api/routes.js +1 -1
- package/src/core/feature-overrides.js +2 -2
- package/src/engines/compression.js +172 -3
- package/src/engines/consolidate.js +397 -26
- package/src/engines/encode.js +16 -3
- package/src/engines/extract.js +72 -8
- package/src/engines/fact-guard.js +51 -0
- package/src/engines/health.js +263 -3
- package/src/engines/inhibition.js +39 -0
- package/src/engines/life.js +12 -1
- package/src/engines/llm-facts.js +12 -9
- package/src/engines/narrative.js +150 -13
- package/src/engines/reflect.js +172 -14
- package/src/engines/retrieve.js +44 -5
- package/src/engines/summary-coverage.js +62 -0
- package/src/engines/summary-dedupe.js +77 -0
- package/src/engines/summon-rank.js +132 -0
- package/src/host/runtime.js +64 -4
- package/src/host/scheduler.js +224 -3
- package/src/llm/adapter.js +29 -8
- package/src/memory/query.js +1 -1
- package/src/memory/spacing.js +15 -0
- package/src/memory/tokenizer.js +1 -1
- package/src/prompt/tiers.js +88 -12
- package/src/self/alias.js +25 -0
- package/src/self/emotion.js +3 -1
- package/src/self/relationship.js +44 -13
- package/src/self/state.js +20 -2
- package/src/self/working.js +34 -3
- package/src/service/cortex.js +493 -53
- package/src/store/repositories/facts.js +34 -1
- package/src/store/repositories/summaries.js +8 -1
- package/src/store/repositories/traces.js +22 -2
- package/src/tools/definitions.js +118 -4
- package/src/vector/index.js +96 -7
- package/test/integration/acceptance.test.js +47 -47
- package/test/integration/api-contract.test.js +17 -17
- package/test/integration/backup-privacy.test.js +10 -10
- package/test/integration/consolidate.test.js +6 -2
- package/test/integration/edge-cases.test.js +16 -15
- package/test/integration/exchange.test.js +26 -26
- package/test/integration/life-loop.test.js +7 -6
- package/test/integration/load.test.js +4 -4
- package/test/integration/policy-query-api.test.js +4 -4
- package/test/integration/resilience-writes.test.js +7 -7
- package/test/integration/tools-contract.test.js +57 -57
- package/test/unit/alias.test.js +87 -0
- package/test/unit/api-client.test.js +3 -3
- package/test/unit/api-validate.test.js +3 -3
- package/test/unit/api.test.js +3 -3
- package/test/unit/auto-reflect.test.js +141 -0
- package/test/unit/capture-filter.test.js +296 -0
- package/test/unit/cli-default-root.test.js +21 -0
- package/test/unit/compaction-preview.test.js +91 -0
- package/test/unit/compression.test.js +4 -4
- package/test/unit/consolidate-dedupe.test.js +174 -0
- package/test/unit/consolidate-errors.test.js +63 -0
- package/test/unit/consolidate-gate.test.js +26 -0
- package/test/unit/consolidate-preview.test.js +168 -0
- package/test/unit/consolidate-protection.test.js +156 -0
- package/test/unit/consolidate-reason.test.js +206 -0
- package/test/unit/consolidate-retry.test.js +91 -0
- package/test/unit/consolidate-selection.test.js +103 -0
- package/test/unit/core.test.js +11 -11
- package/test/unit/coverage-rewrite.test.js +38 -0
- package/test/unit/dedupe-episodes.test.js +34 -0
- package/test/unit/dedupe-threshold.test.js +14 -0
- package/test/unit/develop.test.js +4 -4
- package/test/unit/edges-candidates.test.js +2 -2
- package/test/unit/emotion.test.js +2 -1
- package/test/unit/encode.test.js +6 -6
- package/test/unit/evolution.test.js +5 -5
- package/test/unit/extract-question.test.js +41 -0
- package/test/unit/fact-guard.test.js +51 -0
- package/test/unit/fact-noise-llm.test.js +44 -0
- package/test/unit/facts-belief.test.js +4 -4
- package/test/unit/facts-compat.test.js +62 -0
- package/test/unit/facts.test.js +5 -5
- package/test/unit/fts-migration.test.js +6 -6
- package/test/unit/growth-reflect.test.js +4 -3
- package/test/unit/guardian.test.js +1 -1
- package/test/unit/health-consolidation.test.js +52 -0
- package/test/unit/health-fts-scope.test.js +33 -0
- package/test/unit/health-privacy.test.js +6 -6
- package/test/unit/health-summaries.test.js +24 -0
- package/test/unit/health-text-maintain.test.js +33 -0
- package/test/unit/health-today.test.js +45 -0
- package/test/unit/host-runtime.test.js +8 -8
- package/test/unit/host.test.js +1 -1
- package/test/unit/induct-evaluate.test.js +3 -3
- package/test/unit/ingest-extracted.test.js +3 -3
- package/test/unit/inhibition.test.js +90 -0
- package/test/unit/jobs.test.js +4 -4
- package/test/unit/json-snapshot.test.js +1 -1
- package/test/unit/label-entities-skip.test.js +18 -0
- package/test/unit/llm-facts-integration.test.js +2 -2
- package/test/unit/llm-facts.test.js +3 -3
- package/test/unit/llm.test.js +5 -5
- package/test/unit/locomo.test.js +2 -2
- package/test/unit/longmemeval.test.js +2 -2
- package/test/unit/maintain-dispute.test.js +62 -0
- package/test/unit/maintain-duration.test.js +194 -0
- package/test/unit/markdown-import.test.js +5 -5
- package/test/unit/markdown.test.js +2 -2
- package/test/unit/memory-edit.test.js +5 -5
- package/test/unit/migration.test.js +1 -1
- package/test/unit/mood-saturation.test.js +33 -0
- package/test/unit/narrative-weave.test.js +271 -0
- package/test/unit/privacy-scope.test.js +1 -1
- package/test/unit/prompt.test.js +1 -1
- package/test/unit/providers.test.js +2 -2
- package/test/unit/qa.test.js +9 -9
- package/test/unit/query.test.js +10 -10
- package/test/unit/reflect-backfill.test.js +158 -0
- package/test/unit/reflect-coverage.test.js +35 -0
- package/test/unit/reflect-overview.test.js +22 -0
- package/test/unit/reflect-phrasing.test.js +75 -0
- package/test/unit/reflect-sampling.test.js +80 -0
- package/test/unit/reflect-source-budget.test.js +24 -0
- package/test/unit/relationship-dynamics.test.js +29 -0
- package/test/unit/retrieve.test.js +9 -9
- package/test/unit/revive-on-read.test.js +84 -0
- package/test/unit/scanner.test.js +2 -2
- package/test/unit/scenario.test.js +2 -2
- package/test/unit/scheduler-autoconsolidate.test.js +95 -0
- package/test/unit/scheduler-autodedupe.test.js +52 -0
- package/test/unit/scheduler-autosleep.test.js +50 -0
- package/test/unit/scheduler-cadence.test.js +33 -0
- package/test/unit/scheduler-deep.test.js +62 -0
- package/test/unit/scheduler-tick-gate.test.js +38 -0
- package/test/unit/scheduler.test.js +2 -1
- package/test/unit/service.test.js +5 -5
- package/test/unit/shiori-import.test.js +4 -4
- package/test/unit/spacing.test.js +14 -0
- package/test/unit/store.test.js +13 -13
- package/test/unit/summon-left-slot.test.js +51 -0
- package/test/unit/summon-rank.test.js +51 -0
- package/test/unit/tiers-gist.test.js +140 -0
- package/test/unit/tiers.test.js +1 -1
- package/test/unit/tokenizer-fts.test.js +6 -6
- package/test/unit/tools.test.js +5 -5
- package/test/unit/upgrade-0412.test.js +10 -10
- package/test/unit/upgrade-0413.test.js +5 -5
- package/test/unit/upgrade-0414.test.js +5 -5
- package/test/unit/vector-ann.test.js +3 -3
- package/test/unit/vector-async.test.js +7 -7
- package/test/unit/vector-coverage.test.js +34 -0
- package/test/unit/vector-override.test.js +37 -0
- package/test/unit/vector-typed-array.test.js +47 -0
- package/test/unit/vector.test.js +8 -8
- package/test/unit/working.test.js +19 -0
package/src/engines/narrative.js
CHANGED
|
@@ -15,15 +15,44 @@ function sentence(text, max = 140) {
|
|
|
15
15
|
* around a seed memory, linked by time, tags and content. They are stored as
|
|
16
16
|
* `summaries` with level=thread, so they can be recalled as one memory.
|
|
17
17
|
*/
|
|
18
|
-
export function createNarrativeEngine({ traces, summaries, now = () => Date.now() } = {}) {
|
|
18
|
+
export function createNarrativeEngine({ traces, summaries, selfName = '助手', now = () => Date.now() } = {}) {
|
|
19
19
|
if (!traces || !summaries) throw new Error('narrative engine needs traces and summaries');
|
|
20
20
|
|
|
21
|
-
function buildThread({ scopeId = 'global', seedTraceId, windowDays = 7, max = 8, at = now() } = {}) {
|
|
21
|
+
function buildThread({ scopeId = 'global', seedTraceId, windowDays = 7, windowHours = 24, max = 8, at = now() } = {}) {
|
|
22
22
|
const seed = traces.get(seedTraceId);
|
|
23
23
|
if (!seed) return { skipped: true, reason: 'seed-not-found' };
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
24
|
+
// Query the seed's own time range. `listSince` walks forward from its start and
|
|
25
|
+
// stops at `limit`, so with a store older than the limit the pool held 11-11 /
|
|
26
|
+
// 11-12 residue while the seed was from tonight — every thread then fell through
|
|
27
|
+
// to the 7-day fallback and read like last week's diary.
|
|
28
|
+
const anchor = Date.parse(seed.recordedAt);
|
|
29
|
+
const around = (spanHours, limit = 600) => {
|
|
30
|
+
if (!Number.isFinite(anchor)) return [];
|
|
31
|
+
const span = Math.max(1, Number(spanHours) || 24) * 3_600_000;
|
|
32
|
+
const from = new Date(anchor - span).toISOString();
|
|
33
|
+
const to = new Date(anchor + span).toISOString();
|
|
34
|
+
const rows = typeof traces.range === 'function'
|
|
35
|
+
? traces.range(scopeId, from, to, { limit, state: 'active' })
|
|
36
|
+
: traces.listSince(scopeId, from, { limit }).filter((trace) => Date.parse(trace.recordedAt) <= anchor + span);
|
|
37
|
+
return rows.filter((trace) => trace.kind !== 'reflection');
|
|
38
|
+
};
|
|
39
|
+
// A thread is "what happened around this moment", not "the heaviest things I
|
|
40
|
+
// remember". Soft weights cannot stop a 1.0 identity trace from last week from
|
|
41
|
+
// crowding out the seed's neighbours, so the pool is bounded by time first:
|
|
42
|
+
// seed ± windowHours, then ±72h, then ±windowDays only when the neighbourhood is
|
|
43
|
+
// too quiet to make a line (a silent night still gets one). Every pass carries
|
|
44
|
+
// headroom above its own traffic: a busy day already reaches ~320 traces in 24h,
|
|
45
|
+
// so a 300-row cap would silently drop the newest neighbours.
|
|
46
|
+
let windowHoursUsed = Math.max(1, Number(windowHours) || 24);
|
|
47
|
+
let pool = around(windowHoursUsed, 600);
|
|
48
|
+
if (pool.filter((trace) => trace.id !== seed.id).length < 2) {
|
|
49
|
+
windowHoursUsed = Math.max(windowHoursUsed, 72);
|
|
50
|
+
pool = around(windowHoursUsed, 1200);
|
|
51
|
+
}
|
|
52
|
+
if (pool.filter((trace) => trace.id !== seed.id).length < 2) {
|
|
53
|
+
windowHoursUsed = Math.max(windowHoursUsed, Math.round(Math.max(0.5, windowDays) * 24));
|
|
54
|
+
pool = around(windowHoursUsed, 2000);
|
|
55
|
+
}
|
|
27
56
|
const seedTags = (seed.tags ?? []).join(' ');
|
|
28
57
|
const ranked = pool.map((trace) => {
|
|
29
58
|
const hours = Math.abs(Date.parse(trace.recordedAt) - Date.parse(seed.recordedAt)) / 3_600_000;
|
|
@@ -41,8 +70,98 @@ export function createNarrativeEngine({ traces, summaries, now = () => Date.now(
|
|
|
41
70
|
if (item.trace.id === seed.id || selected.every((chosen) => chosen.trace.id !== item.trace.id)) selected.push(item);
|
|
42
71
|
}
|
|
43
72
|
selected.sort((a, b) => String(a.trace.recordedAt).localeCompare(String(b.trace.recordedAt)));
|
|
44
|
-
|
|
45
|
-
|
|
73
|
+
// One flowing paragraph instead of a bullet dump: a thread is something you
|
|
74
|
+
// read back, not a list you scan. The date prefix is stripped before the date is
|
|
75
|
+
// stated once in the opener.
|
|
76
|
+
//
|
|
77
|
+
// Do not use sentence() here: it treats the dot inside a version number as a full
|
|
78
|
+
// stop, so "dsh-cortex 0.4.139 打包交付" came out as "dsh-cortex 0." and every
|
|
79
|
+
// thread read like a column of stumps. A dot counts as a sentence end only when
|
|
80
|
+
// it is not followed by a digit.
|
|
81
|
+
// Truncation must not stop mid-parenthesis or mid-clause: cut at the last
|
|
82
|
+
// punctuation inside the budget, and drop an unclosed bracket tail first.
|
|
83
|
+
const trimAtBoundary = (text, max = 90) => {
|
|
84
|
+
if (text.length <= max) return text;
|
|
85
|
+
let slice = text.slice(0, max);
|
|
86
|
+
const openCn = slice.lastIndexOf('(');
|
|
87
|
+
const closeCn = slice.lastIndexOf(')');
|
|
88
|
+
if (openCn > closeCn && openCn >= 20) slice = slice.slice(0, openCn);
|
|
89
|
+
const openEn = slice.lastIndexOf('(');
|
|
90
|
+
const closeEn = slice.lastIndexOf(')');
|
|
91
|
+
if (openEn > closeEn && openEn >= 20) slice = slice.slice(0, openEn);
|
|
92
|
+
const boundary = Math.max(
|
|
93
|
+
slice.lastIndexOf(','), slice.lastIndexOf(';'), slice.lastIndexOf('。'),
|
|
94
|
+
slice.lastIndexOf(':'), slice.lastIndexOf('、'),
|
|
95
|
+
);
|
|
96
|
+
if (boundary >= 20) slice = slice.slice(0, boundary);
|
|
97
|
+
return slice.trim();
|
|
98
|
+
};
|
|
99
|
+
// Capture stores a 40-char title (it stops mid-parenthesis: "…验收(豆包装:desk")
|
|
100
|
+
// while the content holds the whole turn. Read the content first and strip the
|
|
101
|
+
// speaker prefix ("用户:" / the assistant's own name) capture writes in front of it.
|
|
102
|
+
const speakerPrefix = ['用户', '助手', '系统', selfName, 'user', 'assistant']
|
|
103
|
+
.filter((item) => typeof item === 'string' && item.trim())
|
|
104
|
+
.map((item) => item.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
|
|
105
|
+
.join('|');
|
|
106
|
+
const stripSpeaker = (text) => String(text ?? '').replace(new RegExp(`^(?:${speakerPrefix})\\s*[::]\\s*`, 'i'), '');
|
|
107
|
+
// A quoted turn arrives as "用户:> …": the speaker prefix hides the quote marker, so
|
|
108
|
+
// both have to come off together — one pass strips only the prefix and leaves "> ".
|
|
109
|
+
const stripDecoration = (text) => {
|
|
110
|
+
let value = String(text ?? '');
|
|
111
|
+
for (let pass = 0; pass < 3; pass += 1) {
|
|
112
|
+
const before = value;
|
|
113
|
+
value = stripSpeaker(value).replace(/^\s*>\s*/, '');
|
|
114
|
+
if (value === before) break;
|
|
115
|
+
}
|
|
116
|
+
return value;
|
|
117
|
+
};
|
|
118
|
+
// The seed topic is read aloud too: quote marker, speaker prefix, markdown emphasis,
|
|
119
|
+
// a trailing dot, then a punctuation-safe cut. It must come from content as well —
|
|
120
|
+
// the seed's own title is captured at 40 chars and would end the topic mid-sentence.
|
|
121
|
+
const cleanTitle = (text) => stripDecoration(String(text ?? ''))
|
|
122
|
+
.replace(/^\s*>\s*/, '')
|
|
123
|
+
.replace(/\*\*/g, '')
|
|
124
|
+
.replace(/`/g, '')
|
|
125
|
+
.replace(/^20\d\d[-./年]\s*\d{1,2}[-./月]\s*\d{1,2}日?\s*[,,::、]?\s*/, '')
|
|
126
|
+
.replace(/[。;;.]+$/, '')
|
|
127
|
+
.trim();
|
|
128
|
+
const clean = (trace) => {
|
|
129
|
+
const value = String(trace.content || trace.title || trace.summary || '').replace(/\s+/g, ' ').trim();
|
|
130
|
+
const cut = value.search(/[。!?!?]|\.(?![0-9])/);
|
|
131
|
+
const first = cut > 0 ? value.slice(0, cut + 1) : value;
|
|
132
|
+
// Speaker prefix and quote marker come off together, in either order.
|
|
133
|
+
return trimAtBoundary(stripDecoration(first), 90)
|
|
134
|
+
.replace(/\*\*/g, '')
|
|
135
|
+
.replace(/`/g, '')
|
|
136
|
+
.replace(/^20\d\d[-./年]\s*\d{1,2}[-./月]\s*\d{1,2}日?\s*[,,::、]?\s*/, '')
|
|
137
|
+
.replace(/[。;;]+$/, '')
|
|
138
|
+
.trim();
|
|
139
|
+
};
|
|
140
|
+
// A fragment is not a beat in the story: skip stumps like "dsh-cortex 0." or a
|
|
141
|
+
// trailing open bracket. Short human titles ("两天前", "刚刚这句") are fine, and a
|
|
142
|
+
// full sentence that happens to end in an English dot is not a fragment.
|
|
143
|
+
const isFragment = (text) => !text
|
|
144
|
+
|| text.length < 3
|
|
145
|
+
|| /[0-9]\.$/.test(text)
|
|
146
|
+
|| /[((]$/.test(text)
|
|
147
|
+
|| /^[\s\p{P}\p{S}]+$/u.test(text);
|
|
148
|
+
const parts = selected.map(({ trace }) => clean(trace)).filter((part) => !isFragment(part));
|
|
149
|
+
const when = (iso) => {
|
|
150
|
+
const date = new Date(iso);
|
|
151
|
+
return Number.isFinite(date.getTime()) ? `${date.getMonth() + 1}月${date.getDate()}日` : '';
|
|
152
|
+
};
|
|
153
|
+
const opener = selected.length ? when(selected[0].trace.recordedAt) : '';
|
|
154
|
+
const clauses = parts.map((part, index) => {
|
|
155
|
+
if (index === 0) return part;
|
|
156
|
+
if (index === parts.length - 1 && parts.length > 2) return `最后,${part}`;
|
|
157
|
+
return `${index === 1 ? '接着' : '后来'},${part}`;
|
|
158
|
+
});
|
|
159
|
+
const body = clauses.length
|
|
160
|
+
? `${opener ? `${opener},` : ''}${clauses.join(';')}。`
|
|
161
|
+
: '只留下了这一个种子,附近还没别的痕迹。';
|
|
162
|
+
const seedTopic = cleanTitle(trimAtBoundary(String(seed.content || seed.title || '').replace(/\s+/g, ' ').trim(), 60))
|
|
163
|
+
|| sentence(seed.content, 40);
|
|
164
|
+
const content = `一段关于「${seedTopic}」的经历:${body}`;
|
|
46
165
|
const summary = summaries.insert({
|
|
47
166
|
scopeId,
|
|
48
167
|
level: 'thread',
|
|
@@ -53,7 +172,7 @@ export function createNarrativeEngine({ traces, summaries, now = () => Date.now(
|
|
|
53
172
|
coverage: pool.length ? selected.length / pool.length : 1,
|
|
54
173
|
model: 'narrative-v1',
|
|
55
174
|
});
|
|
56
|
-
return { skipped: false, summary, seed, traces: selected.map(({ trace }) => trace), coverage: summary.coverage, at: nowIso(at) };
|
|
175
|
+
return { skipped: false, summary, seed, traces: selected.map(({ trace }) => trace), coverage: summary.coverage, windowHours: windowHoursUsed, at: nowIso(at) };
|
|
57
176
|
}
|
|
58
177
|
|
|
59
178
|
function recallThreads(query, { scopeId = 'global', limit = 5 } = {}) {
|
|
@@ -65,21 +184,39 @@ export function createNarrativeEngine({ traces, summaries, now = () => Date.now(
|
|
|
65
184
|
.slice(0, Math.max(1, Math.min(20, limit)));
|
|
66
185
|
}
|
|
67
186
|
|
|
68
|
-
|
|
187
|
+
// Threads are rebuilt from the same recurring topics every pass, so without a
|
|
188
|
+
// retention cap the table grows forever. Keep the newest `maxTotal`, drop the
|
|
189
|
+
// oldest tail.
|
|
190
|
+
function pruneThreads(scopeId, maxTotal) {
|
|
191
|
+
const cap = Math.max(1, Math.min(200, Number(maxTotal) || 24));
|
|
192
|
+
const threads = summaries.list(scopeId, { level: 'thread', limit: 500 });
|
|
193
|
+
if (threads.length <= cap) return 0;
|
|
194
|
+
let removed = 0;
|
|
195
|
+
for (const thread of threads.slice(cap)) {
|
|
196
|
+
try { if (summaries.remove?.(thread.id)) removed += 1; } catch { /* retention is best effort */ }
|
|
197
|
+
}
|
|
198
|
+
return removed;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function weave({ scopeId = 'global', maxThreads = 3, maxTotal = 24, windowHours = 24, at = now() } = {}) {
|
|
202
|
+
const pruned = pruneThreads(scopeId, maxTotal);
|
|
203
|
+
// Seed by recency, not importance: sorting by importance kept threading the
|
|
204
|
+
// same old identity traces, so every thread read like "about the build" or
|
|
205
|
+
// "about the promise". Recency makes the line follow what actually happened.
|
|
69
206
|
const recent = traces.list({ scopeId, state: 'active', limit: 100 })
|
|
70
207
|
.filter((trace) => trace.kind !== 'reflection')
|
|
71
|
-
.sort((a, b) =>
|
|
208
|
+
.sort((a, b) => String(b.recordedAt).localeCompare(String(a.recordedAt)));
|
|
72
209
|
const built = [];
|
|
73
210
|
for (const trace of recent) {
|
|
74
211
|
if (built.length >= maxThreads) break;
|
|
75
212
|
const existing = summaries.list(scopeId, { level: 'thread', limit: 100 })
|
|
76
213
|
.some((summary) => summary.sourceIds.includes(trace.id));
|
|
77
214
|
if (existing) continue;
|
|
78
|
-
const result = buildThread({ scopeId, seedTraceId: trace.id, at });
|
|
215
|
+
const result = buildThread({ scopeId, seedTraceId: trace.id, windowHours, at });
|
|
79
216
|
if (!result.skipped) built.push(result);
|
|
80
217
|
}
|
|
81
|
-
return { built: built.length, threads: built };
|
|
218
|
+
return { built: built.length, threads: built, pruned };
|
|
82
219
|
}
|
|
83
220
|
|
|
84
|
-
return { buildThread, recallThreads, weave };
|
|
221
|
+
return { buildThread, recallThreads, weave, pruneThreads };
|
|
85
222
|
}
|
package/src/engines/reflect.js
CHANGED
|
@@ -16,6 +16,21 @@ function sentence(text, max = 160) {
|
|
|
16
16
|
* It does not delete anything; it creates a reflective trace and a summary
|
|
17
17
|
* record with source pointers and a coverage ratio.
|
|
18
18
|
*/
|
|
19
|
+
/**
|
|
20
|
+
* A fixed 8 sources meant a 160-trace day was reflected from 5% of it. Scale
|
|
21
|
+
* gently with the window, keeping the extractive summary bounded. Segments are
|
|
22
|
+
* short by construction (they start where the previous episode ended), so they
|
|
23
|
+
* get a larger share — otherwise a 40-trace segment is summarized from 8 rows
|
|
24
|
+
* and coverage stays near 20% no matter how the phrasing improves.
|
|
25
|
+
*/
|
|
26
|
+
export function sourceBudgetFor(count, { segment = false, maxSources = null } = {}) {
|
|
27
|
+
if (Number(maxSources) > 0) return Math.max(1, Math.min(40, Number(maxSources)));
|
|
28
|
+
const ratio = segment ? 0.25 : 0.12;
|
|
29
|
+
const cap = segment ? 24 : 16;
|
|
30
|
+
const n = Math.max(0, Number(count) || 0);
|
|
31
|
+
return Math.max(8, Math.min(cap, Math.ceil(n * ratio)));
|
|
32
|
+
}
|
|
33
|
+
|
|
19
34
|
export function createReflectEngine({ traces, summaries, encode, config = {} } = {}) {
|
|
20
35
|
if (!traces || !summaries || !encode) throw new Error('reflect engine needs traces, summaries and encode');
|
|
21
36
|
|
|
@@ -23,12 +38,19 @@ export function createReflectEngine({ traces, summaries, encode, config = {} } =
|
|
|
23
38
|
scopeId = 'global',
|
|
24
39
|
windowDays = 1,
|
|
25
40
|
now = Date.now(),
|
|
26
|
-
maxSources =
|
|
41
|
+
maxSources = null,
|
|
27
42
|
force = false,
|
|
43
|
+
// Explicit window start (used for segmented episodes: a new episode starts
|
|
44
|
+
// where the previous one ended, so consecutive episodes never overlap).
|
|
45
|
+
since = null,
|
|
46
|
+
// Exclusive window end for backfill: [since, until). Without it every call
|
|
47
|
+
// would cover "since until now" and one episode would swallow the timeline.
|
|
48
|
+
until = null,
|
|
49
|
+
segment = false,
|
|
28
50
|
} = {}) {
|
|
29
|
-
const
|
|
30
|
-
const all = traces.listSince(scopeId,
|
|
31
|
-
.filter((trace) => trace.kind !== 'reflection');
|
|
51
|
+
const sinceIso = since ?? new Date(now - Math.max(0.1, windowDays) * DAY_MS).toISOString();
|
|
52
|
+
const all = traces.listSince(scopeId, sinceIso, { limit: 500 })
|
|
53
|
+
.filter((trace) => trace.kind !== 'reflection' && (!until || trace.recordedAt < until));
|
|
32
54
|
if (all.length < 2) return { skipped: true, reason: 'not-enough-traces', count: all.length };
|
|
33
55
|
const periodStart = all[0].recordedAt;
|
|
34
56
|
const periodEnd = all[all.length - 1].recordedAt;
|
|
@@ -45,13 +67,57 @@ export function createReflectEngine({ traces, summaries, encode, config = {} } =
|
|
|
45
67
|
}))
|
|
46
68
|
.sort((a, b) => b.score - a.score);
|
|
47
69
|
const selected = [];
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
70
|
+
const sourceLimit = sourceBudgetFor(all.length, { segment, maxSources });
|
|
71
|
+
// Pure top-k lets the loudest strand of the day take every slot, so keep a
|
|
72
|
+
// share for a spread across the ranked list. The near-duplicate filter only
|
|
73
|
+
// runs over the head of the list: comparing every pair in a 500-trace window
|
|
74
|
+
// is O(n²) (~10s, measured, and `maintain()` is synchronous).
|
|
75
|
+
const dedupePool = Math.min(ranked.length, sourceLimit * 3);
|
|
76
|
+
const head = [];
|
|
77
|
+
for (const item of ranked.slice(0, dedupePool)) {
|
|
78
|
+
if (head.some((chosen) => jaccard(chosen.trace.content, item.trace.content) > 0.7)) continue;
|
|
79
|
+
head.push(item);
|
|
80
|
+
}
|
|
81
|
+
const pool = [...head, ...ranked.slice(dedupePool)];
|
|
82
|
+
const topSlots = Math.max(1, Math.min(pool.length, Math.ceil(sourceLimit * 0.6)));
|
|
83
|
+
selected.push(...pool.slice(0, topSlots));
|
|
84
|
+
const rest = pool.slice(topSlots);
|
|
85
|
+
const remaining = sourceLimit - selected.length;
|
|
86
|
+
const taken = new Set();
|
|
87
|
+
for (let slot = 0; slot < remaining && rest.length > 0; slot += 1) {
|
|
88
|
+
// Centre each pick inside its bucket: starting at rest[0] and stepping by a
|
|
89
|
+
// floor()'d stride never reaches the last ~17% of the list.
|
|
90
|
+
const index = Math.min(rest.length - 1, Math.floor(((slot + 0.5) * rest.length) / remaining));
|
|
91
|
+
if (taken.has(index)) continue;
|
|
92
|
+
taken.add(index);
|
|
93
|
+
selected.push(rest[index]);
|
|
52
94
|
}
|
|
53
95
|
const lines = selected.map(({ trace }) => `- ${sentence(trace.title || trace.content, 140)}`);
|
|
54
|
-
const
|
|
96
|
+
const bullets = lines.map((line) => line.replace(/^- /, ''));
|
|
97
|
+
// Phrasing only: same sources, same coverage maths below. The summary is
|
|
98
|
+
// something I read later, so it speaks in the first person instead of
|
|
99
|
+
// reading like a machine dump.
|
|
100
|
+
const heading = segment ? '这一段里,我记下了:' : '这段时间里,我记下了:';
|
|
101
|
+
// Compose the overview from the two most central *distinct* bullets (two
|
|
102
|
+
// different traces can share a title, and "X;X" is not a summary); with
|
|
103
|
+
// fewer than three bullets there is nothing to condense, so it is omitted.
|
|
104
|
+
const distinctBullets = bullets.filter((line, index) => bullets.indexOf(line) === index);
|
|
105
|
+
const gistLine = bullets.length >= 3 && distinctBullets.length >= 2
|
|
106
|
+
? `一句话:${truncate(`${distinctBullets[0].replace(/[。;;]+$/, '')};${distinctBullets[1].replace(/[。;;]+$/, '')}`, 90)}`
|
|
107
|
+
: '';
|
|
108
|
+
const content = [
|
|
109
|
+
heading,
|
|
110
|
+
gistLine,
|
|
111
|
+
...bullets.map((line) => `· ${line}`),
|
|
112
|
+
].filter(Boolean).join('\n');
|
|
113
|
+
// Coverage used to be a raw count ratio, so a busy day always read as "5%"
|
|
114
|
+
// even when the reflection had seen everything that mattered. Report both:
|
|
115
|
+
// the importance-weighted coverage drives the summary, the count stays for
|
|
116
|
+
// debugging how many traces were sampled.
|
|
117
|
+
const weightOf = (trace) => Math.max(0.05, Number(trace.importance) || 0.5);
|
|
118
|
+
const totalWeight = all.reduce((sum, trace) => sum + weightOf(trace), 0);
|
|
119
|
+
const coveredWeight = selected.reduce((sum, { trace }) => sum + weightOf(trace), 0);
|
|
120
|
+
const weightedCoverage = totalWeight ? Math.round((coveredWeight / totalWeight) * 1000) / 1000 : 0;
|
|
55
121
|
const coverage = selected.length / all.length;
|
|
56
122
|
const summary = summaries.insert({
|
|
57
123
|
scopeId,
|
|
@@ -60,8 +126,11 @@ export function createReflectEngine({ traces, summaries, encode, config = {} } =
|
|
|
60
126
|
periodEnd,
|
|
61
127
|
content,
|
|
62
128
|
sourceIds: selected.map(({ trace }) => trace.id),
|
|
63
|
-
coverage,
|
|
64
|
-
|
|
129
|
+
coverage: weightedCoverage,
|
|
130
|
+
// The `coverage` column changed meaning (count ratio → importance-weighted),
|
|
131
|
+
// so old rows cannot be compared with new ones. v2 records the mode in the
|
|
132
|
+
// model string: nothing needs a schema migration, and history stays honest.
|
|
133
|
+
model: segment ? 'extractive-v2-segment' : 'extractive-v2-weighted',
|
|
65
134
|
});
|
|
66
135
|
const reflected = encode.encode({
|
|
67
136
|
text: content,
|
|
@@ -76,7 +145,8 @@ export function createReflectEngine({ traces, summaries, encode, config = {} } =
|
|
|
76
145
|
skipped: false,
|
|
77
146
|
summary,
|
|
78
147
|
trace: reflected.trace ?? null,
|
|
79
|
-
coverage,
|
|
148
|
+
coverage: weightedCoverage,
|
|
149
|
+
countCoverage: Math.round(coverage * 1000) / 1000,
|
|
80
150
|
sources: selected.map(({ trace }) => trace.id),
|
|
81
151
|
at: nowIso(now),
|
|
82
152
|
};
|
|
@@ -84,12 +154,100 @@ export function createReflectEngine({ traces, summaries, encode, config = {} } =
|
|
|
84
154
|
|
|
85
155
|
function overview(scopeId = 'global') {
|
|
86
156
|
const list = summaries.list(scopeId, { level: 'episode', limit: 20 });
|
|
157
|
+
// `coverage` changed meaning in v2 (count share → importance share). Averaging
|
|
158
|
+
// the two kinds together would report a number that means neither, so only
|
|
159
|
+
// v2 rows contribute and the legacy rows are counted separately.
|
|
160
|
+
const weighted = list.filter((item) => String(item.model ?? '').includes('-v2'));
|
|
161
|
+
const legacy = list.length - weighted.length;
|
|
87
162
|
return {
|
|
88
163
|
count: list.length,
|
|
164
|
+
legacy,
|
|
89
165
|
latest: list[0] ?? null,
|
|
90
|
-
coverage:
|
|
166
|
+
coverage: weighted.length ? weighted.reduce((sum, item) => sum + Number(item.coverage ?? 0), 0) / weighted.length : 0,
|
|
91
167
|
};
|
|
92
168
|
}
|
|
93
169
|
|
|
94
|
-
|
|
170
|
+
/**
|
|
171
|
+
* Walk the timeline forward in fixed windows and write one episode per window.
|
|
172
|
+
* 32–60 traces wide: 32×25% lands exactly on sourceBudgetFor's min 8, so a smaller
|
|
173
|
+
* window would be silently over-sampled.
|
|
174
|
+
*/
|
|
175
|
+
function backfillEpisodes({ scopeId = 'global', now = Date.now(), windowSize = 40, maxWindows = 5, dryRun = true, force = false, since = null } = {}) {
|
|
176
|
+
const size = Math.max(32, Math.min(60, Number(windowSize) || 40));
|
|
177
|
+
const ceiling = Math.max(1, Math.min(64, Number(maxWindows) || 5));
|
|
178
|
+
const preview = dryRun !== false;
|
|
179
|
+
const plan = [];
|
|
180
|
+
const results = [];
|
|
181
|
+
// Resume support: every call used to restart at epoch, so a second batch burned
|
|
182
|
+
// its whole maxWindows quota on already-written windows and could never reach the
|
|
183
|
+
// tail (851 traces > 20 × 40). Callers pass the previous `until` as `since`.
|
|
184
|
+
let cursor = since ?? null;
|
|
185
|
+
for (let index = 0; index < ceiling; index += 1) {
|
|
186
|
+
const sinceIso = cursor ?? new Date(0).toISOString();
|
|
187
|
+
const batch = traces.listSince(scopeId, sinceIso, { limit: 500 })
|
|
188
|
+
.filter((trace) => trace.kind !== 'reflection');
|
|
189
|
+
if (batch.length < 8) { plan.push({ skipped: 'not-enough-traces', remaining: batch.length }); break; }
|
|
190
|
+
// Include every trace that shares the boundary millisecond: a batch write can
|
|
191
|
+
// put several traces on the same recordedAt, and cutting between them would
|
|
192
|
+
// drop the rest forever (the next window starts at >= the same timestamp).
|
|
193
|
+
let end = size;
|
|
194
|
+
while (end < batch.length && batch[end].recordedAt === batch[size - 1].recordedAt) end += 1;
|
|
195
|
+
const slice = batch.slice(0, end);
|
|
196
|
+
const lastAt = slice[slice.length - 1].recordedAt;
|
|
197
|
+
const until = end < batch.length
|
|
198
|
+
? batch[end].recordedAt
|
|
199
|
+
: new Date(Date.parse(lastAt) + 1).toISOString();
|
|
200
|
+
plan.push({ since: sinceIso, until, count: slice.length });
|
|
201
|
+
if (!preview) {
|
|
202
|
+
// Idempotent by default: re-running the same window must not write a second
|
|
203
|
+
// episode. force:true is only for "the window genuinely changed, recompute".
|
|
204
|
+
// Idempotency is measured in *traces*, not wall-clock time: the first window
|
|
205
|
+
// starts at 1970, so a summary covering recent traces can look tiny on a
|
|
206
|
+
// 56-year timeline.
|
|
207
|
+
const windowIds = slice.map((trace) => trace.id);
|
|
208
|
+
const episodes = force ? [] : summaries.list(scopeId, { level: 'episode', limit: 500 });
|
|
209
|
+
// Coverage is the union of every episode's sources: a window split between
|
|
210
|
+
// two episodes (30% + 30%) is still already reflected.
|
|
211
|
+
const coveredUnion = new Set();
|
|
212
|
+
for (const episode of episodes) {
|
|
213
|
+
for (const id of Array.isArray(episode.sourceIds) ? episode.sourceIds : []) coveredUnion.add(id);
|
|
214
|
+
}
|
|
215
|
+
let coveredCount = 0;
|
|
216
|
+
for (const id of windowIds) if (coveredUnion.has(id)) coveredCount += 1;
|
|
217
|
+
const coveredRatio = windowIds.length ? coveredCount / windowIds.length : 0;
|
|
218
|
+
// How many episodes contributed to that coverage; useful when tracing why a
|
|
219
|
+
// window was accepted (summaryId is null for union hits).
|
|
220
|
+
const windowSet = new Set(windowIds);
|
|
221
|
+
let matchedEpisodes = 0;
|
|
222
|
+
for (const episode of episodes) {
|
|
223
|
+
const ids = Array.isArray(episode.sourceIds) ? episode.sourceIds : [];
|
|
224
|
+
if (ids.some((id) => windowSet.has(id))) matchedEpisodes += 1;
|
|
225
|
+
}
|
|
226
|
+
// Threshold 0.5, not 0.8: reflect samples only ~60% of a window (24/40), so a
|
|
227
|
+
// fully reflected window scores ~0.6 and an 0.8 bar would never fire.
|
|
228
|
+
const existing = force
|
|
229
|
+
? null
|
|
230
|
+
: summaries.findPeriod(scopeId, 'episode', slice[0].recordedAt, lastAt)
|
|
231
|
+
?? (coveredRatio >= 0.5 ? { id: null } : null);
|
|
232
|
+
if (existing) {
|
|
233
|
+
results.push({ since: sinceIso, until, skipped: 'already-reflected', summaryId: existing.id ?? null, coveredRatio: Number(coveredRatio.toFixed(2)), matchedEpisodes });
|
|
234
|
+
} else {
|
|
235
|
+
try {
|
|
236
|
+
// 0.4.129 policy: 80% of each window, not 60%. Sampling 24 of 40 left a
|
|
237
|
+
// structural 40% of every backfilled window uncovered, and no number of
|
|
238
|
+
// extra windows could fix that ceiling.
|
|
239
|
+
const result = reflect({ scopeId, now, since: sinceIso, until, segment: true, force, maxSources: Math.min(Math.round(size * 0.8), size) });
|
|
240
|
+
results.push({ since: sinceIso, until, skipped: result.skipped ?? null, summaryId: result.summary?.id ?? null, sources: result.summary?.sourceIds?.length ?? 0 });
|
|
241
|
+
} catch (error) {
|
|
242
|
+
results.push({ since: sinceIso, until, error: error instanceof Error ? error.message : String(error) });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
cursor = until;
|
|
247
|
+
if (batch.length <= size) break;
|
|
248
|
+
}
|
|
249
|
+
return { dryRun: preview, windowSize: size, planned: plan.length, plan, results };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return { reflect, backfillEpisodes, overview };
|
|
95
253
|
}
|
package/src/engines/retrieve.js
CHANGED
|
@@ -2,6 +2,7 @@ import { retrievability } from '../memory/dsr.js';
|
|
|
2
2
|
import { estimateTokens, jaccard, overlapScore, tokens } from '../memory/tokenizer.js';
|
|
3
3
|
import { daysBetween, nowIso } from '../core/time.js';
|
|
4
4
|
import { matchesFilters } from '../memory/query.js';
|
|
5
|
+
import { competingFactor, withSuppression } from './inhibition.js';
|
|
5
6
|
|
|
6
7
|
const INTENT_RULES = [
|
|
7
8
|
[/昨天|今天|明天|上周|上个月|去年|什么时候|多久|时间|日期|几点|temporal/i, 'temporal'],
|
|
@@ -65,7 +66,7 @@ function queryCoverage(wanted, present) {
|
|
|
65
66
|
return shared / wanted.size;
|
|
66
67
|
}
|
|
67
68
|
|
|
68
|
-
function candidateFromTrace(trace, fusion, intent, now, decay, weights = null, queryTokens = null) {
|
|
69
|
+
function candidateFromTrace(trace, fusion, intent, now, decay, weights = null, queryTokens = null, inhibition = null) {
|
|
69
70
|
const recency = retrievability(trace.stability, daysBetween(trace.lastAccessAt || trace.recordedAt, now), decay);
|
|
70
71
|
const access = Math.log1p(Number(trace.accessCount) || 0) / Math.log1p(50);
|
|
71
72
|
const w = { ...(INTENT_WEIGHTS[intent] || INTENT_WEIGHTS.fact), ...(weights ?? {}) };
|
|
@@ -73,13 +74,13 @@ function candidateFromTrace(trace, fusion, intent, now, decay, weights = null, q
|
|
|
73
74
|
const text = `${trace.title ?? ''} ${trace.content ?? ''} ${trace.summary ?? ''}`;
|
|
74
75
|
const textTokens = tokens(text);
|
|
75
76
|
const match = queryCoverage(queryTokens, textTokens);
|
|
76
|
-
const utility = w.fusion * fusionScore
|
|
77
|
+
const utility = (w.fusion * fusionScore
|
|
77
78
|
+ w.importance * Number(trace.importance || 0)
|
|
78
79
|
+ w.recency * recency
|
|
79
80
|
+ w.confidence * Number(trace.confidence || 0)
|
|
80
81
|
+ w.access * access
|
|
81
82
|
+ w.match * match
|
|
82
|
-
+ w.exact * (match >= 0.999 ? 1 : 0);
|
|
83
|
+
+ w.exact * (match >= 0.999 ? 1 : 0)) * (inhibition ? competingFactor(trace.metadata, now, inhibition) : 1);
|
|
83
84
|
return {
|
|
84
85
|
id: trace.id,
|
|
85
86
|
type: 'trace',
|
|
@@ -155,6 +156,14 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
155
156
|
recentMinMatch: config.recentMinMatch ?? 0.12,
|
|
156
157
|
recentImportanceFloor: config.recentImportanceFloor ?? 0.8,
|
|
157
158
|
decay: config.dsr?.decay ?? -0.5,
|
|
159
|
+
inhibition: config.features?.inhibition === true
|
|
160
|
+
? {
|
|
161
|
+
strength: config.inhibitionStrength ?? 0.35,
|
|
162
|
+
halfLifeDays: config.inhibitionHalfLifeDays ?? 14,
|
|
163
|
+
step: config.inhibitionStep ?? 0.15,
|
|
164
|
+
competitorSim: config.inhibitionCompetitorSim ?? 0.5,
|
|
165
|
+
}
|
|
166
|
+
: null,
|
|
158
167
|
};
|
|
159
168
|
|
|
160
169
|
function searchSources(query, { scopeId = 'global', limit = 12, now = Date.now(), includeArchived = false, weights = null, filters = null, vectorHits = null, gate = 'none' } = {}, intent = 'fact') {
|
|
@@ -168,7 +177,7 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
168
177
|
let sourceName = 'fts';
|
|
169
178
|
if (!hits.length) {
|
|
170
179
|
// Character fallback: only when the exact bigram query has no hits.
|
|
171
|
-
// This keeps normal FTS precision and lets 米饭 find
|
|
180
|
+
// This keeps normal FTS precision and lets 米饭 find 饭 via 饭.
|
|
172
181
|
hits = traces.searchFts(query, {
|
|
173
182
|
scopeId,
|
|
174
183
|
limit: Math.max(limit * 3, defaults.ftsLimit),
|
|
@@ -239,7 +248,7 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
239
248
|
const trace = traces.get(id);
|
|
240
249
|
if (!trace || trace.state === 'archived' && !includeArchived) continue;
|
|
241
250
|
if (filters && !matchesFilters(trace, filters)) continue;
|
|
242
|
-
const candidate = candidateFromTrace(trace, { ...entry, score: normalize(entry.score, maxFusion) }, intent, now, defaults.decay, weights, queryTokens);
|
|
251
|
+
const candidate = candidateFromTrace(trace, { ...entry, score: normalize(entry.score, maxFusion) }, intent, now, defaults.decay, weights, queryTokens, defaults.inhibition);
|
|
243
252
|
// Prompt-injection gate: only weaken candidates that entered solely via
|
|
244
253
|
// the recency list or the soft FTS fallback. Strong sources still pass.
|
|
245
254
|
// High importance is allowed to bypass the match floor, preserving the
|
|
@@ -292,6 +301,36 @@ export function createRetrievalEngine({ traces, facts = null, graph = null, vect
|
|
|
292
301
|
lambda: defaults.lambda,
|
|
293
302
|
mu: defaults.mu,
|
|
294
303
|
});
|
|
304
|
+
if (defaults.inhibition) {
|
|
305
|
+
// Suppress only semantic competitors: candidates that lost the recall and
|
|
306
|
+
// are near-duplicates of something that was selected. At most three per
|
|
307
|
+
// recall, and at most once per 24h per trace so a busy loop cannot bury a
|
|
308
|
+
// memory permanently.
|
|
309
|
+
const selectedTexts = portfolio.selected.map((item) => item.text ?? '');
|
|
310
|
+
let suppressed = 0;
|
|
311
|
+
for (const candidate of sources.candidates) {
|
|
312
|
+
if (suppressed >= 3) break;
|
|
313
|
+
if (portfolio.selected.some((item) => item.id === candidate.id)) continue;
|
|
314
|
+
const text = candidate.text ?? '';
|
|
315
|
+
const similarity = selectedTexts.reduce((max, other) => (other ? Math.max(max, jaccard(text, other)) : max), 0);
|
|
316
|
+
if (similarity < (defaults.inhibition.competitorSim ?? 0.5)) continue;
|
|
317
|
+
const trace = traces.get(candidate.id);
|
|
318
|
+
if (!trace) continue;
|
|
319
|
+
const last = Date.parse(trace.metadata?.suppressedAt ?? '');
|
|
320
|
+
if (Number.isFinite(last) && now - last < 86_400_000) continue;
|
|
321
|
+
try {
|
|
322
|
+
traces.update(trace.id, {
|
|
323
|
+
metadata: withSuppression(trace.metadata, now, {
|
|
324
|
+
step: defaults.inhibition.step,
|
|
325
|
+
halfLifeDays: defaults.inhibition.halfLifeDays,
|
|
326
|
+
}),
|
|
327
|
+
});
|
|
328
|
+
suppressed += 1;
|
|
329
|
+
} catch {
|
|
330
|
+
/* suppression is best-effort; a recall must never fail because of it */
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
295
334
|
const items = portfolio.selected.map((item) => ({
|
|
296
335
|
id: item.id,
|
|
297
336
|
type: item.type,
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Recompute `coverage` for episode summaries that were written before the
|
|
5
|
+
* importance-weighted definition existed (v1 stored "share of traces sampled").
|
|
6
|
+
*
|
|
7
|
+
* This is a *report-first* helper: it never writes. `bin/repair.mjs --rewrite-
|
|
8
|
+
* coverage` decides whether to apply, and only behind the normal backup gate.
|
|
9
|
+
*
|
|
10
|
+
* For each v1 episode summary:
|
|
11
|
+
* total = importance sum of traces recorded inside [period_start, period_end]
|
|
12
|
+
* covered = importance sum of the summary's own source traces (still existing)
|
|
13
|
+
* coverage = covered / total (importance-weighted, same meaning as v2)
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
function weightOf(row) {
|
|
17
|
+
return Math.max(0.05, Number(row?.importance) || 0.5);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function recomputeEpisodeCoverage({ db, scopeId = 'global', limit = 200 } = {}) {
|
|
21
|
+
if (!db) throw new Error('recomputeEpisodeCoverage needs a db');
|
|
22
|
+
const rows = db.prepare(`
|
|
23
|
+
SELECT id, source_ids_json, coverage, period_start, period_end, model, content
|
|
24
|
+
FROM summaries
|
|
25
|
+
WHERE scope_id = ? AND level = 'episode'
|
|
26
|
+
AND (model IS NULL OR model NOT LIKE '%-v2%')
|
|
27
|
+
ORDER BY created_at DESC LIMIT ?
|
|
28
|
+
`).all(scopeId, Math.max(1, Number(limit) || 200));
|
|
29
|
+
|
|
30
|
+
const updates = [];
|
|
31
|
+
for (const row of rows) {
|
|
32
|
+
let sourceIds = [];
|
|
33
|
+
try { sourceIds = JSON.parse(row.source_ids_json ?? '[]'); } catch { sourceIds = []; }
|
|
34
|
+
if (!Array.isArray(sourceIds) || sourceIds.length === 0) continue;
|
|
35
|
+
const window = db.prepare(`
|
|
36
|
+
SELECT importance FROM traces
|
|
37
|
+
WHERE scope_id = ? AND recorded_at >= ? AND recorded_at <= ?
|
|
38
|
+
`).all(scopeId, row.period_start, row.period_end);
|
|
39
|
+
const total = window.reduce((sum, item) => sum + weightOf(item), 0);
|
|
40
|
+
if (total <= 0) continue;
|
|
41
|
+
const placeholders = sourceIds.map(() => '?').join(',');
|
|
42
|
+
const sources = db.prepare(`
|
|
43
|
+
SELECT id, importance FROM traces
|
|
44
|
+
WHERE scope_id = ? AND id IN (${placeholders})
|
|
45
|
+
`).all(scopeId, ...sourceIds);
|
|
46
|
+
const covered = sources.reduce((sum, item) => sum + weightOf(item), 0);
|
|
47
|
+
if (covered <= 0) continue;
|
|
48
|
+
const next = Math.min(1, Math.round((covered / total) * 1000) / 1000);
|
|
49
|
+
if (Math.abs(next - Number(row.coverage ?? 0)) < 0.001) continue;
|
|
50
|
+
const digest = createHash('sha256').update(`${row.id}:${next}`).digest('hex').slice(0, 12);
|
|
51
|
+
updates.push({
|
|
52
|
+
id: row.id,
|
|
53
|
+
from: Number(row.coverage ?? 0),
|
|
54
|
+
to: next,
|
|
55
|
+
sources: sources.length,
|
|
56
|
+
window: window.length,
|
|
57
|
+
digest,
|
|
58
|
+
title: String(row.content ?? '').slice(0, 40),
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
return { candidates: rows.length, updates };
|
|
62
|
+
}
|