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
|
@@ -36,6 +36,26 @@ function combineConfidence(a, b) {
|
|
|
36
36
|
return Math.min(1, 1 - (1 - Number(a || 0)) * (1 - Number(b || 0)));
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
const NEGATION_HEAD = /^(?:不|没|未|别|没有|不会|不是)/;
|
|
40
|
+
|
|
41
|
+
function normalizeLiteral(value) {
|
|
42
|
+
return String(value ?? '').toLowerCase().replace(/[\s\p{P}\p{S}]/gu, '');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Same subject + same predicate does not automatically mean a conflict.
|
|
47
|
+
* "一直在" and "一直存在着" say compatible things. Only a negation that flips
|
|
48
|
+
* the claim ("会一直在" vs "不会一直在") is treated as a real dispute; the
|
|
49
|
+
* negation must lead the literal, otherwise it is part of the object itself
|
|
50
|
+
* ("记忆不丢"), not a contradiction.
|
|
51
|
+
*/
|
|
52
|
+
export function negationFlip(a, b) {
|
|
53
|
+
const left = normalizeLiteral(a);
|
|
54
|
+
const right = normalizeLiteral(b);
|
|
55
|
+
if (!left || !right) return false;
|
|
56
|
+
return NEGATION_HEAD.test(left) !== NEGATION_HEAD.test(right);
|
|
57
|
+
}
|
|
58
|
+
|
|
39
59
|
export function createFactRepository(db) {
|
|
40
60
|
function get(id) {
|
|
41
61
|
return rowToFact(db.prepare('SELECT * FROM facts WHERE id = ?').get(id));
|
|
@@ -120,7 +140,20 @@ export function createFactRepository(db) {
|
|
|
120
140
|
const later = existing.filter((fact) => fact.validFrom <= validFrom).at(-1);
|
|
121
141
|
if (later) {
|
|
122
142
|
if (later.validFrom === validFrom) {
|
|
123
|
-
// Same start, different object
|
|
143
|
+
// Same start, different object. The compatibility rule only applies
|
|
144
|
+
// when both sides are free text: "一直在" and "一直存在着" can coexist.
|
|
145
|
+
// Entity-to-entity conflicts (likes 咖啡 vs likes 茶) still dispute.
|
|
146
|
+
const newLiteral = objectLiteral ?? null;
|
|
147
|
+
const allLiterals = Boolean(newLiteral) && existing.every((fact) => Boolean(fact.objectLiteral));
|
|
148
|
+
const flip = allLiterals && existing.some((fact) => negationFlip(fact.objectLiteral, newLiteral));
|
|
149
|
+
if (allLiterals && !flip) {
|
|
150
|
+
const fact = insertFact({
|
|
151
|
+
scopeId, subjectId, predicate, objectId, objectLiteral, validFrom, validTo,
|
|
152
|
+
recordedAt, confidence, status: 'active', sourceEventId, evidence,
|
|
153
|
+
});
|
|
154
|
+
return { action: 'compatible', fact, invalidated: [] };
|
|
155
|
+
}
|
|
156
|
+
// Genuinely contradictory: keep both but mark them disputed and
|
|
124
157
|
// record the dispute. A later reflection/verification can resolve it.
|
|
125
158
|
const disputed = existing.map((fact) => {
|
|
126
159
|
db.prepare("UPDATE facts SET status = 'disputed', updated_at = ? WHERE id = ?").run(nowIso(), fact.id);
|
|
@@ -48,5 +48,12 @@ export function createSummaryRepository(db) {
|
|
|
48
48
|
return rows.map(rowToSummary);
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
|
|
51
|
+
// Narrative threads need a retention knob: they are rebuilt from the same
|
|
52
|
+
// recurring topics, so without a cap the table grows forever.
|
|
53
|
+
function remove(id) {
|
|
54
|
+
const result = db.prepare('DELETE FROM summaries WHERE id = ?').run(id);
|
|
55
|
+
return result.changes > 0;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return { insert, get, findPeriod, list, remove };
|
|
52
59
|
}
|
|
@@ -195,6 +195,18 @@ export function createTraceRepository(db) {
|
|
|
195
195
|
return rows.map(rowToTrace);
|
|
196
196
|
}
|
|
197
197
|
|
|
198
|
+
// Range query by recorded_at. listSince() walks forward from a start instant and
|
|
199
|
+
// stops at `limit`, so asking it for "the pool around this trace" silently
|
|
200
|
+
// returns the OLDEST rows when the store is older than the limit — the narrative
|
|
201
|
+
// engine hit that and every thread's bullets came out as 11-11/11-12 residue.
|
|
202
|
+
function range(scopeId = 'global', fromIso, toIso, { limit = 500, state = 'active' } = {}) {
|
|
203
|
+
const count = Math.max(1, Math.min(4000, Number(limit) || 500));
|
|
204
|
+
const rows = state
|
|
205
|
+
? db.prepare('SELECT * FROM traces WHERE scope_id = ? AND state = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY recorded_at ASC LIMIT ?').all(scopeId, state, fromIso, toIso, count)
|
|
206
|
+
: db.prepare('SELECT * FROM traces WHERE scope_id = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY recorded_at ASC LIMIT ?').all(scopeId, fromIso, toIso, count);
|
|
207
|
+
return rows.map(rowToTrace);
|
|
208
|
+
}
|
|
209
|
+
|
|
198
210
|
function update(id, patch = {}) {
|
|
199
211
|
const current = get(id);
|
|
200
212
|
if (!current) throw new CortexError(ERROR_CODES.NOT_FOUND, `trace not found: ${id}`);
|
|
@@ -253,7 +265,15 @@ export function createTraceRepository(db) {
|
|
|
253
265
|
return Number(db.prepare('SELECT COUNT(*) AS c FROM traces').get().c);
|
|
254
266
|
}
|
|
255
267
|
|
|
256
|
-
function ftsCount() {
|
|
268
|
+
function ftsCount({ scopeId = null } = {}) {
|
|
269
|
+
// Without a scope this is the whole index. With one it must join through
|
|
270
|
+
// traces: health used to compare the *global* trace count against the
|
|
271
|
+
// *whole* FTS table and reported drift whenever another scope existed
|
|
272
|
+
// (the live store has an `agency` scope, so it warned by exactly those
|
|
273
|
+
// 12 rows forever).
|
|
274
|
+
if (scopeId) {
|
|
275
|
+
return Number(db.prepare('SELECT COUNT(*) AS c FROM traces_fts_index f JOIN traces t ON t.id = f.trace_id WHERE t.scope_id = ?').get(scopeId).c);
|
|
276
|
+
}
|
|
257
277
|
return Number(db.prepare('SELECT COUNT(*) AS c FROM traces_fts_index').get().c);
|
|
258
278
|
}
|
|
259
279
|
|
|
@@ -274,5 +294,5 @@ export function createTraceRepository(db) {
|
|
|
274
294
|
`).all(scopeId, Math.max(1, Math.min(100, limit))).map((row) => ({ hash: row.hash, count: Number(row.c) }));
|
|
275
295
|
}
|
|
276
296
|
|
|
277
|
-
return { insert, get, findByEvent, findByHash, list, listSince, update, touch, remove, searchFts, count, ftsCount, reindexFts, duplicateHashes };
|
|
297
|
+
return { insert, get, findByEvent, findByHash, list, listSince, range, update, touch, remove, searchFts, count, ftsCount, reindexFts, duplicateHashes };
|
|
278
298
|
}
|
package/src/tools/definitions.js
CHANGED
|
@@ -50,6 +50,47 @@ function formatSelf(snapshot) {
|
|
|
50
50
|
|
|
51
51
|
function formatHealth(report) {
|
|
52
52
|
const lines = [`健康分:${report.score}/100`, `事件 ${report.counts.events} · 痕迹 ${report.counts.traces.total}(active ${report.counts.traces.active})· 事实 ${report.counts.facts.active} · 技能 ${report.counts.skills}`];
|
|
53
|
+
if (report.inhibition?.enabled) lines.push(`抑制:${report.inhibition.count} 条 · 均值 ${report.inhibition.average}`);
|
|
54
|
+
if (report.capture?.total) lines.push(`捕获:${report.capture.total} 轮 · 剥掉 ${report.capture.stripped} · 截断 ${report.capture.truncated}`);
|
|
55
|
+
if (report.capture?.days?.length) lines.push(`按天:${report.capture.days.slice(0, 3).map((day) => `${day.day} ${day.total}轮/剥${day.stripped}`).join(' · ')}`);
|
|
56
|
+
if (report.vectors) lines.push(`向量:${Math.round(report.vectors.coverage * 100)}%(${report.vectors.embedded}/${report.counts.traces.active})`);
|
|
57
|
+
if (report.consolidation?.dream || report.consolidation?.sleep) {
|
|
58
|
+
const dream = report.consolidation.dream;
|
|
59
|
+
const sleep = report.consolidation.sleep;
|
|
60
|
+
const stamp = (value) => (typeof value === 'string' ? value.slice(0, 19) : '—');
|
|
61
|
+
const dreamText = dream
|
|
62
|
+
? `巩固 ${stamp(dream.at)} ${dream.error
|
|
63
|
+
? `空转(${dream.error})`
|
|
64
|
+
: `${dream.status ?? 'done'},决策 ${dream.decisions}(keep ${dream.keep ?? 0})· 应用 ${dream.applied}`}`
|
|
65
|
+
: '巩固 还没跑过';
|
|
66
|
+
const sleepText = sleep
|
|
67
|
+
? `睡眠 ${stamp(sleep.at)}(${sleep.consolidation ?? '—'},反思 ${sleep.reflected})`
|
|
68
|
+
: '睡眠 还没有记录';
|
|
69
|
+
lines.push(`${dreamText} · ${sleepText}`);
|
|
70
|
+
const today = report.consolidation?.today;
|
|
71
|
+
if (today && (today.archived || today.merged)) {
|
|
72
|
+
lines.push(`今日整理:${today.runs} 趟 · 归档 ${today.archived} 条 · 合并 ${today.merged} 条`);
|
|
73
|
+
} else {
|
|
74
|
+
lines.push('今日整理:暂无改动');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (report.summaryLayers) {
|
|
78
|
+
const layers = report.summaryLayers;
|
|
79
|
+
const last = layers.lastEpisodeAt ? layers.lastEpisodeAt.slice(0, 16) : '—';
|
|
80
|
+
lines.push(`摘要:每日 ${layers.episode} 条(最近 ${last})· 合并记录 ${layers.merge} · 线 ${layers.thread}`);
|
|
81
|
+
}
|
|
82
|
+
if (report.maintain) {
|
|
83
|
+
const maintain = report.maintain;
|
|
84
|
+
const ms = Number.isFinite(maintain.ms) ? ` · ${maintain.ms}ms` : '';
|
|
85
|
+
lines.push(`维护:最近一趟 ${String(maintain.at).slice(0, 19)}(意图 ${maintain.intentions} · 工作记忆 ${maintain.working}${ms})`);
|
|
86
|
+
// A quiet pass leaves the newest audit row stale; name it separately so the
|
|
87
|
+
// timestamp above is not read as "nothing has run in hours".
|
|
88
|
+
const changed = report.maintainLastChanged;
|
|
89
|
+
const changedAt = changed?.passAt ?? changed?.at ?? null;
|
|
90
|
+
if (changedAt && changedAt !== maintain.at) {
|
|
91
|
+
lines.push(` 最近一次有变更:${String(changedAt).slice(0, 19)}(意图 ${changed.intentions} · 工作记忆 ${changed.working})`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
53
94
|
if (report.issues.length) {
|
|
54
95
|
lines.push('问题:');
|
|
55
96
|
for (const issue of report.issues) lines.push(`- [${issue.severity}] ${issue.message}`);
|
|
@@ -86,6 +127,33 @@ export function createToolDefinitions(service) {
|
|
|
86
127
|
},
|
|
87
128
|
presentCall: () => ({ card: 'generic', title: '自主 tick', kind: 'other' }),
|
|
88
129
|
},
|
|
130
|
+
{
|
|
131
|
+
name: 'cortex_inhibition',
|
|
132
|
+
description: 'Inspect or clear the retrieval-induced-forgetting marks. list shows suppressed traces with their decayed strength; clear removes the mark from one trace (id) or all of them (all: true).',
|
|
133
|
+
parameters: {
|
|
134
|
+
type: 'object',
|
|
135
|
+
additionalProperties: false,
|
|
136
|
+
required: ['action'],
|
|
137
|
+
properties: {
|
|
138
|
+
action: { type: 'string', enum: ['list', 'clear'] },
|
|
139
|
+
id: { type: 'string', description: '要清除的记忆 id(clear 时用)' },
|
|
140
|
+
all: { type: 'boolean', description: 'clear 时清全部' },
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
output: TEXT_OUTPUT,
|
|
144
|
+
isConcurrencySafe: () => false,
|
|
145
|
+
async execute(args = {}) {
|
|
146
|
+
if (args.action === 'list') {
|
|
147
|
+
const items = service.inhibition.list({});
|
|
148
|
+
if (!items.length) return { text: '没有被抑制的记忆。' };
|
|
149
|
+
return { text: items.slice(0, 20).map((item) => `- ${item.id} · ${item.title ?? '(untitled)'} · 强度 ${item.value}`).join('\n') };
|
|
150
|
+
}
|
|
151
|
+
if (!args.id && args.all !== true) return { text: 'clear 需要 id,或者 all: true。' };
|
|
152
|
+
const result = service.inhibition.clear({ id: args.id ?? null, all: args.all === true });
|
|
153
|
+
return { text: `已清除 ${result.cleared} 条抑制标记。` };
|
|
154
|
+
},
|
|
155
|
+
presentCall: () => ({ card: 'generic', title: '记忆抑制', kind: 'other' }),
|
|
156
|
+
},
|
|
89
157
|
{
|
|
90
158
|
name: 'cortex_digest',
|
|
91
159
|
description: 'Generate a daily memory digest (counts, important traces, emotions, feedback, goals) and persist it as a digest summary.',
|
|
@@ -581,15 +649,21 @@ export function createToolDefinitions(service) {
|
|
|
581
649
|
},
|
|
582
650
|
{
|
|
583
651
|
name: 'cortex_consolidate',
|
|
584
|
-
description: 'Run LLM memory consolidation (keep/merge/archive/update/conflict) with validation and a replayable dream_runs record. Without an LLM it records a skipped run and changes nothing. Use list to inspect past runs.',
|
|
652
|
+
description: 'Run LLM memory consolidation (keep/merge/archive/update/conflict) with validation and a replayable dream_runs record. Without an LLM it records a skipped run and changes nothing. action=dedupe merges near-duplicate traces deterministically (no LLM; dryRun defaults to true). Use list to inspect past runs.',
|
|
585
653
|
parameters: {
|
|
586
654
|
type: 'object',
|
|
587
655
|
additionalProperties: false,
|
|
588
656
|
required: ['action'],
|
|
589
657
|
properties: {
|
|
590
|
-
action: { type: 'string', enum: ['run', 'list'] },
|
|
658
|
+
action: { type: 'string', enum: ['run', 'list', 'dedupe', 'preview', 'backfill'] },
|
|
591
659
|
limit: { type: 'number' },
|
|
592
660
|
dryRun: { type: 'boolean' },
|
|
661
|
+
threshold: { type: 'number', minimum: 0.5, maximum: 0.99, description: 'dedupe 相似度阈值(2-gram Jaccard),默认 0.8,超出 0.5–0.99 会被夹住' },
|
|
662
|
+
coverageThreshold: { type: 'number', minimum: 0.2, maximum: 0.9, description: '覆盖预演阈值(默认 0.35,超出 0.2–0.9 会被夹住)' },
|
|
663
|
+
windowSize: { type: 'number', minimum: 32, maximum: 60, description: '窗口补齐:每段痕迹数(32–60,默认 40)' },
|
|
664
|
+
maxWindows: { type: 'number', minimum: 1, maximum: 64, description: '窗口补齐:本次最多补几段(默认 8)' },
|
|
665
|
+
force: { type: 'boolean', description: '窗口补齐:同一窗口已存在摘要时是否重写(默认 false,幂等跳过)' },
|
|
666
|
+
since: { type: 'string', description: '窗口补齐:从哪个时间点续跑(传上一批的 until;不传则从最早痕迹开始)' },
|
|
593
667
|
scope: { type: 'string' },
|
|
594
668
|
},
|
|
595
669
|
},
|
|
@@ -600,7 +674,47 @@ export function createToolDefinitions(service) {
|
|
|
600
674
|
const runs = service.consolidation.list({ scopeId: args.scope, limit: args.limit });
|
|
601
675
|
return { text: runs.length ? runs.map((run) => `- ${run.id} · ${run.at} · ${run.status} · applied ${run.applied.length} · ${run.inputDigest.slice(0, 12)}`).join('\n') : '(还没有巩固记录)' };
|
|
602
676
|
}
|
|
603
|
-
|
|
677
|
+
if (args.action === 'backfill') {
|
|
678
|
+
const report = await service.reflectBackfill({
|
|
679
|
+
scopeId: args.scope ?? service.settings().scope,
|
|
680
|
+
windowSize: args.windowSize ?? 40,
|
|
681
|
+
maxWindows: args.maxWindows ?? 8,
|
|
682
|
+
dryRun: args.dryRun !== false,
|
|
683
|
+
force: args.force === true,
|
|
684
|
+
since: args.since ?? null,
|
|
685
|
+
});
|
|
686
|
+
// The last entry can be { skipped: 'not-enough-traces' } with no window.
|
|
687
|
+
const windows = report.plan.filter((row) => row.since && row.until);
|
|
688
|
+
const first = windows[0];
|
|
689
|
+
const last = windows[windows.length - 1];
|
|
690
|
+
const span = first && last ? `${first.since.slice(0, 16)} → ${last.until.slice(0, 16)}` : '—';
|
|
691
|
+
const made = report.results.filter((row) => row.summaryId).length;
|
|
692
|
+
return { text: `窗口补齐${report.dryRun ? '预演' : ''}:每段 ${report.windowSize} 条 · 计划 ${report.planned} 段 · 跨度 ${span}${report.dryRun ? '' : ` · 新摘要 ${made}`}` };
|
|
693
|
+
}
|
|
694
|
+
if (args.action === 'preview') {
|
|
695
|
+
const report = service.compression.previewCoverage({ scopeId: args.scope ?? service.settings().scope, limit: args.limit ?? 5000, threshold: args.coverageThreshold ?? 0.35 });
|
|
696
|
+
const top = report.top.slice(0, 5).map((row) => `- ${row.r} · ${row.title}(${row.basis},命中 ${row.hit},覆盖 ${(row.rate * 100).toFixed(0)}%)`).join('\n');
|
|
697
|
+
return {
|
|
698
|
+
text: `覆盖预演(不改库):扫描 ${report.scanned} · 跳过 保护 ${report.protectedSkipped}/近访问 ${report.recentSkipped} · 摘要覆盖 ${report.summaryCovered} · 事实覆盖 ${report.factCovered}(两类都有 ${report.bothCovered})· 摘要 ${report.summaries}/事实 ${report.facts}\n分布 p50 ${report.percentiles.p50} / p90 ${report.percentiles.p90}(p90−p50 ${report.percentiles.spread})· 阈值 ${report.threshold} · 池 ${report.pool}(两类 ${report.strongPool})· 可用 ${report.usable}${report.reason ? `(${report.reason})` : ''}\n${top || '(没有可核验的覆盖候选)'}`,
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
if (args.action === 'dedupe') {
|
|
702
|
+
if (args.dryRun === false && typeof service.scopeWritable === 'function' && !service.scopeWritable(args.scope ?? service.settings().scope)) {
|
|
703
|
+
return { text: '未执行:该 scope 只读共享。' };
|
|
704
|
+
}
|
|
705
|
+
const result = await service.consolidation.dedupe({
|
|
706
|
+
scopeId: args.scope,
|
|
707
|
+
limit: args.limit ?? 30,
|
|
708
|
+
threshold: args.threshold ?? 0.8,
|
|
709
|
+
dryRun: args.dryRun !== false,
|
|
710
|
+
caller: 'tool',
|
|
711
|
+
});
|
|
712
|
+
return { text: `去重 ${result.dryRun ? '预演' : result.run.status}:${result.run.id} · 可合并组 ${result.decisions.length} · 归档 ${result.applied.length}${result.run.groupsDropped ? ` · 跳过组 ${result.run.groupsDropped}` : ''}` };
|
|
713
|
+
}
|
|
714
|
+
if (args.dryRun !== true && typeof service.scopeWritable === 'function' && !service.scopeWritable(args.scope ?? service.settings().scope)) {
|
|
715
|
+
return { text: '未执行:该 scope 只读共享。' };
|
|
716
|
+
}
|
|
717
|
+
const result = await service.consolidation.run({ scopeId: args.scope, limit: args.limit ?? 30, dryRun: args.dryRun === true, caller: 'tool' });
|
|
604
718
|
return { text: `巩固 ${result.run.status}:${result.run.id} · 决策 ${result.decisions.length} · 应用 ${result.applied.length}${result.run.error ? ` · ${result.run.error}` : ''}` };
|
|
605
719
|
},
|
|
606
720
|
presentCall: () => ({ card: 'generic', title: '记忆巩固', kind: 'other' }),
|
|
@@ -618,7 +732,7 @@ export function createToolDefinitions(service) {
|
|
|
618
732
|
isConcurrencySafe: () => true,
|
|
619
733
|
async execute(args = {}) {
|
|
620
734
|
if (!args.id || !String(args.id).trim()) return { text: `没有这条记忆:${args.id}` };
|
|
621
|
-
const trace = service.get(args.id);
|
|
735
|
+
const trace = service.get(args.id, { revive: true });
|
|
622
736
|
if (!trace) return { text: `没有这条记忆:${args.id}` };
|
|
623
737
|
return {
|
|
624
738
|
text: [
|
package/src/vector/index.js
CHANGED
|
@@ -32,6 +32,8 @@ export function createVectorIndex({
|
|
|
32
32
|
annOptions = {},
|
|
33
33
|
externalAnnEnabled = false,
|
|
34
34
|
externalAnnOptions = {},
|
|
35
|
+
logger = null,
|
|
36
|
+
queueMaxAttempts = 4,
|
|
35
37
|
} = {}) {
|
|
36
38
|
if (!db || !embedder) throw new Error('vector index needs db and embedder');
|
|
37
39
|
const effectiveModel = model ?? embedder.model ?? 'unknown';
|
|
@@ -45,6 +47,79 @@ export function createVectorIndex({
|
|
|
45
47
|
? createExternalAnnClient(externalAnnOptions)
|
|
46
48
|
: null;
|
|
47
49
|
let annBuilt = false;
|
|
50
|
+
// Async embedders used to fire-and-forget: a failed call left the trace with
|
|
51
|
+
// no vector and nobody noticed. Keep a small persistent-in-process queue with
|
|
52
|
+
// backoff so a temporary outage heals itself instead of silently rotting.
|
|
53
|
+
const pending = new Map();
|
|
54
|
+
const failed = new Set();
|
|
55
|
+
const maxAttempts = Math.max(1, Number(queueMaxAttempts) || 4);
|
|
56
|
+
const isAsyncEmbedder = () => embedder.kind === 'openai-embedding' || embedder.async === true;
|
|
57
|
+
|
|
58
|
+
function enqueue(traceId, text) {
|
|
59
|
+
if (!traceId) return;
|
|
60
|
+
failed.delete(traceId);
|
|
61
|
+
pending.set(traceId, { text: String(text ?? ''), attempts: 0, nextAt: Date.now() });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function drainQueue({ max = 20, budgetMs = 0 } = {}) {
|
|
65
|
+
const started = Date.now();
|
|
66
|
+
const now = Date.now();
|
|
67
|
+
const ready = [...pending.entries()]
|
|
68
|
+
.filter(([, task]) => task.nextAt <= now)
|
|
69
|
+
.slice(0, Math.max(1, Math.min(2000, Number(max) || 20)));
|
|
70
|
+
let ok = 0;
|
|
71
|
+
let gaveUp = 0;
|
|
72
|
+
let stoppedBy = 'done';
|
|
73
|
+
const budget = Math.max(0, Number(budgetMs) || 0);
|
|
74
|
+
for (const [traceId, task] of ready) {
|
|
75
|
+
if (budget > 0 && Date.now() - started >= budget) {
|
|
76
|
+
stoppedBy = 'time';
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
const vector = await embedder.embed(task.text);
|
|
81
|
+
// Remote embedders hand back a Float32Array, not a plain Array; the old
|
|
82
|
+
// Array.isArray() check rejected every real embedding, so the backfill
|
|
83
|
+
// queue retried forever and coverage never moved.
|
|
84
|
+
const length = vector && typeof vector.length === 'number' ? vector.length : -1;
|
|
85
|
+
if (length !== effectiveDim) throw new Error(`embedding dimension mismatch (${length} vs ${effectiveDim})`);
|
|
86
|
+
store(traceId, task.text, vector);
|
|
87
|
+
pending.delete(traceId);
|
|
88
|
+
ok += 1;
|
|
89
|
+
} catch (error) {
|
|
90
|
+
task.attempts += 1;
|
|
91
|
+
logger?.debug?.(`cortex vector attempt ${task.attempts} failed for ${traceId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
92
|
+
if (task.attempts >= maxAttempts) {
|
|
93
|
+
pending.delete(traceId);
|
|
94
|
+
failed.add(traceId);
|
|
95
|
+
gaveUp += 1;
|
|
96
|
+
logger?.warn?.(`cortex vector failed after ${task.attempts} attempts for ${traceId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
97
|
+
} else {
|
|
98
|
+
task.nextAt = now + Math.min(300_000, 1000 * (3 ** task.attempts));
|
|
99
|
+
// A single retryable failure must not stop the whole drain: the old code
|
|
100
|
+
// broke out here, so one bad item starved every other pending vector.
|
|
101
|
+
logger?.info?.(`cortex vector retry scheduled for ${traceId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { ok, failed: gaveUp, pending: pending.size, elapsedMs: Date.now() - started, stoppedBy };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Queue every active trace that has no embedding yet. This is what makes a
|
|
110
|
+
* recovery possible: the index can lag behind the trace table without
|
|
111
|
+
* needing a full, expensive rebuild.
|
|
112
|
+
*/
|
|
113
|
+
function backfillMissing({ scopeId = 'global', limit = 50 } = {}) {
|
|
114
|
+
const rows = db.prepare(`
|
|
115
|
+
SELECT t.id, t.title, t.content, t.summary FROM traces t
|
|
116
|
+
LEFT JOIN embeddings e ON e.trace_id = t.id
|
|
117
|
+
WHERE t.scope_id = ? AND t.state = 'active' AND e.trace_id IS NULL
|
|
118
|
+
ORDER BY t.recorded_at DESC LIMIT ?
|
|
119
|
+
`).all(scopeId, Math.max(1, Math.min(2000, Number(limit) || 50)));
|
|
120
|
+
for (const row of rows) enqueue(row.id, `${row.title ?? ''} ${row.content ?? ''} ${row.summary ?? ''}`);
|
|
121
|
+
return { queued: rows.length, pending: pending.size };
|
|
122
|
+
}
|
|
48
123
|
|
|
49
124
|
function ensureAnn() {
|
|
50
125
|
if (!ann || annBuilt) return;
|
|
@@ -55,11 +130,11 @@ export function createVectorIndex({
|
|
|
55
130
|
|
|
56
131
|
function upsert(traceId, text) {
|
|
57
132
|
if (!traceId) return null;
|
|
58
|
-
// Remote providers are async. A write must not block on the network:
|
|
59
|
-
//
|
|
60
|
-
// use upsertAsync().
|
|
61
|
-
if (
|
|
62
|
-
|
|
133
|
+
// Remote providers are async. A write must not block on the network: queue
|
|
134
|
+
// it, and let the scheduler drain the queue with retries. Callers that need
|
|
135
|
+
// completion use upsertAsync().
|
|
136
|
+
if (isAsyncEmbedder()) {
|
|
137
|
+
enqueue(traceId, text);
|
|
63
138
|
return { traceId, pending: true };
|
|
64
139
|
}
|
|
65
140
|
const vector = embedder.embed(String(text ?? ''));
|
|
@@ -100,7 +175,8 @@ export function createVectorIndex({
|
|
|
100
175
|
model: effectiveModel,
|
|
101
176
|
dim: effectiveDim,
|
|
102
177
|
count: Number(row?.c ?? 0),
|
|
103
|
-
async:
|
|
178
|
+
async: isAsyncEmbedder(),
|
|
179
|
+
queue: { pending: pending.size, failed: failed.size, maxAttempts },
|
|
104
180
|
ann: ann ? { enabled: true, engine: annEngine === 'nsw' ? 'nsw' : 'hnsw', size: ann.size(), min: annMinCount, built: annBuilt } : { enabled: false },
|
|
105
181
|
externalAnn: externalAnn ? { enabled: true, endpoint: externalAnn.endpoint } : { enabled: false },
|
|
106
182
|
};
|
|
@@ -205,5 +281,18 @@ export function createVectorIndex({
|
|
|
205
281
|
return { rebuilt, ...status() };
|
|
206
282
|
}
|
|
207
283
|
|
|
208
|
-
return {
|
|
284
|
+
return {
|
|
285
|
+
upsert,
|
|
286
|
+
upsertAsync,
|
|
287
|
+
remove,
|
|
288
|
+
search,
|
|
289
|
+
searchAsync,
|
|
290
|
+
status,
|
|
291
|
+
rebuild,
|
|
292
|
+
rebuildAsync,
|
|
293
|
+
backfillMissing,
|
|
294
|
+
drainQueue,
|
|
295
|
+
model: effectiveModel,
|
|
296
|
+
dim: effectiveDim,
|
|
297
|
+
};
|
|
209
298
|
}
|