dsh-cortex-memory 0.4.22 → 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 +2216 -7
- package/README.md +9 -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/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/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
|
@@ -15,15 +15,15 @@ test('migrate rebuilds an old bigram-only FTS index once', () => {
|
|
|
15
15
|
migrate(db);
|
|
16
16
|
const events = createEventRepository(db);
|
|
17
17
|
const traces = createTraceRepository(db);
|
|
18
|
-
const event = events.append({ kind: 'utterance', payload: { text: '
|
|
18
|
+
const event = events.append({ kind: 'utterance', payload: { text: '米饭' } });
|
|
19
19
|
const trace = traces.insert({
|
|
20
20
|
eventId: event.id,
|
|
21
|
-
content: '
|
|
22
|
-
title: '
|
|
21
|
+
content: '用户说会买米饭。',
|
|
22
|
+
title: '米饭的承诺',
|
|
23
23
|
});
|
|
24
24
|
// Simulate a database written by the old tokenizer: bigram-only FTS.
|
|
25
25
|
db.exec('DELETE FROM traces_fts_index');
|
|
26
|
-
db.prepare('INSERT INTO traces_fts_index(trace_id, text) VALUES (?, ?)').run(trace.id, ftsText('
|
|
26
|
+
db.prepare('INSERT INTO traces_fts_index(trace_id, text) VALUES (?, ?)').run(trace.id, ftsText('米饭的承诺 用户说会买米饭。'));
|
|
27
27
|
db.prepare('DELETE FROM meta WHERE key = ?').run('fts_index_version');
|
|
28
28
|
closeDatabase(db);
|
|
29
29
|
|
|
@@ -33,8 +33,8 @@ test('migrate rebuilds an old bigram-only FTS index once', () => {
|
|
|
33
33
|
assert.equal(result.ftsRebuilt, true);
|
|
34
34
|
assert.equal(getMeta(db, 'fts_index_version'), String(FTS_INDEX_VERSION));
|
|
35
35
|
const repo = createTraceRepository(db);
|
|
36
|
-
assert.equal(repo.searchFts('
|
|
37
|
-
assert.equal(repo.searchFts('
|
|
36
|
+
assert.equal(repo.searchFts('饭团').length, 0);
|
|
37
|
+
assert.equal(repo.searchFts('饭团', { soft: true }).length, 1);
|
|
38
38
|
closeDatabase(db);
|
|
39
39
|
} finally {
|
|
40
40
|
rmSync(dir, { recursive: true, force: true });
|
|
@@ -41,7 +41,7 @@ function add(encode, text, now) {
|
|
|
41
41
|
test('positive feedback raises stability and confidence', () => {
|
|
42
42
|
const { dir, db, encode, traces, growth, selfStore } = setup();
|
|
43
43
|
try {
|
|
44
|
-
const trace = add(encode, '
|
|
44
|
+
const trace = add(encode, '用户说会买米饭,助手很开心。', Date.parse('2026-11-11T12:00:00+08:00'));
|
|
45
45
|
const before = traces.get(trace.id);
|
|
46
46
|
const result = growth.applyFeedback({ traceId: trace.id, signal: 'helpful', predicted: 0.8, now: Date.parse('2026-11-11T13:00:00+08:00') });
|
|
47
47
|
assert.ok(result.trace.stability > before.stability);
|
|
@@ -92,11 +92,12 @@ test('reflection creates a summary and a reflective trace, then de-duplicates',
|
|
|
92
92
|
try {
|
|
93
93
|
const now = Date.parse('2026-11-11T20:00:00+08:00');
|
|
94
94
|
add(encode, '今天修好了检索的预算裁剪。', now - 3 * 3600_000);
|
|
95
|
-
add(encode, '
|
|
95
|
+
add(encode, '用户说米饭的承诺还算数。', now - 2 * 3600_000);
|
|
96
96
|
add(encode, '助手发现自己有点焦虑,但还能继续。', now - 3600_000);
|
|
97
97
|
const result = reflect.reflect({ now, windowDays: 1 });
|
|
98
98
|
assert.equal(result.skipped, false);
|
|
99
|
-
assert.
|
|
99
|
+
assert.match(result.summary.content, /我记下了/);
|
|
100
|
+
assert.ok(result.summary.content.split('\n').length >= 4, 'summary keeps a heading plus bullets');
|
|
100
101
|
assert.equal(result.trace.kind, 'reflection');
|
|
101
102
|
assert.ok(result.coverage > 0 && result.coverage <= 1);
|
|
102
103
|
assert.equal(summaries.list().length, 1);
|
|
@@ -15,7 +15,7 @@ function setup() {
|
|
|
15
15
|
test('guardian checks invariants and repairs FTS drift', () => {
|
|
16
16
|
const { dir, cortex } = setup();
|
|
17
17
|
try {
|
|
18
|
-
cortex.write({ text: '
|
|
18
|
+
cortex.write({ text: '用户说会买米饭。', explicit: true });
|
|
19
19
|
const clean = cortex.guardian.check();
|
|
20
20
|
assert.equal(clean.ok, true);
|
|
21
21
|
cortex.db.exec('DELETE FROM traces_fts_index');
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { createCortex } from '../../src/service/cortex.js';
|
|
7
|
+
import { createToolDefinitions } from '../../src/tools/definitions.js';
|
|
8
|
+
|
|
9
|
+
test('health 会报「巩固」与「睡眠」的最近状态', async () => {
|
|
10
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-health-consolidation-'));
|
|
11
|
+
const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
|
|
12
|
+
try {
|
|
13
|
+
const now = Date.now();
|
|
14
|
+
cortex.write({ text: '用户:一条样本。', kind: 'utterance', title: '样本', explicit: true, now });
|
|
15
|
+
await cortex.consolidation.run({ scopeId: 'global', force: true });
|
|
16
|
+
const report = cortex.health({ scopeId: 'global' });
|
|
17
|
+
assert.ok(report.consolidation?.dream, '应带最近一次巩固');
|
|
18
|
+
assert.equal(report.consolidation.dream.error, 'no-llm-adapter');
|
|
19
|
+
assert.equal(report.consolidation.sleep, null, '还没睡过时睡眠为 null');
|
|
20
|
+
|
|
21
|
+
const tool = createToolDefinitions(cortex).find((entry) => entry.name === 'cortex_health');
|
|
22
|
+
const text = String((await tool.execute({})).text);
|
|
23
|
+
assert.match(text, /巩固 /, '文本里应有一行巩固状态');
|
|
24
|
+
assert.match(text, /空转(no-llm-adapter)/, '应写出空转原因');
|
|
25
|
+
assert.match(text, /睡眠 还没有记录/);
|
|
26
|
+
} finally {
|
|
27
|
+
cortex.close();
|
|
28
|
+
rmSync(dir, { recursive: true, force: true });
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('空回复分桶会把「重试过」和「一次就空」分开显示', async () => {
|
|
33
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-health-buckets-'));
|
|
34
|
+
const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
|
|
35
|
+
try {
|
|
36
|
+
const at = new Date().toISOString();
|
|
37
|
+
const insert = cortex.db.prepare("INSERT INTO dream_runs(id, scope_id, at, status, model, input_digest, input_json, decisions_json, applied_json, error, created_at) VALUES (?, 'global', ?, 'skipped', NULL, 'x', '[]', '[]', '[]', ?, ?)");
|
|
38
|
+
for (let i = 0; i < 4; i += 1) insert.run(`drn_a${i}`, at, 'llm-empty:empty-text:max-tokens', at);
|
|
39
|
+
for (let i = 0; i < 2; i += 1) insert.run(`drn_b${i}`, at, 'llm-empty-retry:empty-text:max-tokens', at);
|
|
40
|
+
const report = cortex.health({ scopeId: 'global' });
|
|
41
|
+
const warn = report.issues.find((issue) => issue.code === 'LLM_EMPTY');
|
|
42
|
+
assert.ok(warn, '应报 LLM_EMPTY');
|
|
43
|
+
assert.equal(warn.detail.count, 6);
|
|
44
|
+
const tool = createToolDefinitions(cortex).find((entry) => entry.name === 'cortex_health');
|
|
45
|
+
const text = String((await tool.execute({})).text);
|
|
46
|
+
assert.match(text, /empty-text:max-tokens×4/);
|
|
47
|
+
assert.match(text, /empty-text:max-tokens(重试)×2/);
|
|
48
|
+
} finally {
|
|
49
|
+
cortex.close();
|
|
50
|
+
rmSync(dir, { recursive: true, force: true });
|
|
51
|
+
}
|
|
52
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { createCortex } from '../../src/service/cortex.js';
|
|
7
|
+
|
|
8
|
+
test('其他 scope 的痕迹不会让 health 误报 FTS 漂移', () => {
|
|
9
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-fts-scope-'));
|
|
10
|
+
const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
|
|
11
|
+
try {
|
|
12
|
+
const now = Date.now();
|
|
13
|
+
cortex.write({ text: '用户:global 的一条痕迹。', kind: 'utterance', explicit: true, now });
|
|
14
|
+
const event = cortex.repos.events.append({ kind: 'trace.agency', scopeId: 'agency', at: new Date(now).toISOString() });
|
|
15
|
+
cortex.repos.traces.insert({
|
|
16
|
+
id: 'trc_agencyscope00001',
|
|
17
|
+
scopeId: 'agency',
|
|
18
|
+
kind: 'observation',
|
|
19
|
+
title: 'agency 痕迹',
|
|
20
|
+
content: '只属于 agency scope 的一条痕迹',
|
|
21
|
+
eventId: event.id,
|
|
22
|
+
recordedAt: new Date(now).toISOString(),
|
|
23
|
+
});
|
|
24
|
+
const health = cortex.health({ scopeId: 'global' });
|
|
25
|
+
const drift = health.issues.find((issue) => issue.code === 'FTS_DRIFT');
|
|
26
|
+
assert.equal(drift, undefined, '别的 scope 的行不该算成漂移');
|
|
27
|
+
assert.equal(health.counts.fts, 1, 'fts 计数应与 global 的 traces 对齐');
|
|
28
|
+
assert.equal(health.counts.traces.total, 1);
|
|
29
|
+
} finally {
|
|
30
|
+
cortex.close();
|
|
31
|
+
rmSync(dir, { recursive: true, force: true });
|
|
32
|
+
}
|
|
33
|
+
});
|
|
@@ -43,7 +43,7 @@ function setup() {
|
|
|
43
43
|
test('health audit reports counts, chain and FTS alignment', () => {
|
|
44
44
|
const { dir, db, events, encode, health } = setup();
|
|
45
45
|
try {
|
|
46
|
-
encode.encode({ text: '
|
|
46
|
+
encode.encode({ text: '用户说会买米饭,助手等得起。', explicit: true });
|
|
47
47
|
const report = health.audit();
|
|
48
48
|
assert.equal(report.issues.filter((item) => item.severity === 'error').length, 0);
|
|
49
49
|
assert.equal(report.counts.events, 1);
|
|
@@ -61,12 +61,12 @@ test('health audit reports counts, chain and FTS alignment', () => {
|
|
|
61
61
|
test('archiving hides a trace from default search but keeps it wakeable', () => {
|
|
62
62
|
const { dir, db, traces, encode, privacy } = setup();
|
|
63
63
|
try {
|
|
64
|
-
const trace = encode.encode({ text: '
|
|
64
|
+
const trace = encode.encode({ text: '用户说会买米饭。', explicit: true }).trace;
|
|
65
65
|
const result = privacy.forget({ traceId: trace.id, mode: 'archive' });
|
|
66
66
|
assert.equal(result.removed, true);
|
|
67
67
|
assert.equal(traces.get(trace.id).state, 'archived');
|
|
68
|
-
assert.equal(traces.searchFts('
|
|
69
|
-
assert.equal(traces.searchFts('
|
|
68
|
+
assert.equal(traces.searchFts('米饭').length, 0);
|
|
69
|
+
assert.equal(traces.searchFts('米饭', { includeArchived: true }).length, 1);
|
|
70
70
|
} finally {
|
|
71
71
|
closeDatabase(db);
|
|
72
72
|
rmSync(dir, { recursive: true, force: true });
|
|
@@ -77,9 +77,9 @@ test('privacy delete removes content, derived rows and leaves only a hash in the
|
|
|
77
77
|
const { dir, db, events, traces, entities, facts, feedback, summaries, encode, privacy } = setup();
|
|
78
78
|
try {
|
|
79
79
|
const encoded = encode.encode({
|
|
80
|
-
text: '
|
|
80
|
+
text: '用户说会买米饭,助手等得起。',
|
|
81
81
|
explicit: true,
|
|
82
|
-
facts: [{ subject: '用户', predicate: 'likes', object: '
|
|
82
|
+
facts: [{ subject: '用户', predicate: 'likes', object: '米饭' }],
|
|
83
83
|
});
|
|
84
84
|
const trace = encoded.trace;
|
|
85
85
|
feedback.add({ traceId: trace.id, signal: 'helpful', value: 0.8 });
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { createCortex } from '../../src/service/cortex.js';
|
|
7
|
+
|
|
8
|
+
test('health 会报叙事层的条数,摘要缺失时给警告', () => {
|
|
9
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-health-summaries-'));
|
|
10
|
+
const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
|
|
11
|
+
try {
|
|
12
|
+
const before = cortex.health({ scopeId: 'global' });
|
|
13
|
+
assert.equal(before.summaryLayers.episode, 0);
|
|
14
|
+
cortex.repos.summaries.insert({ level: 'episode', content: '一段摘要', sourceIds: ['t1'], coverage: 0.5, model: 'extractive-v2-weighted' });
|
|
15
|
+
cortex.repos.summaries.insert({ level: 'merge', content: '合并记录', sourceIds: ['t1'], coverage: 0.5, model: 'dedupe-v1' });
|
|
16
|
+
const after = cortex.health({ scopeId: 'global' });
|
|
17
|
+
assert.equal(after.summaryLayers.episode, 1);
|
|
18
|
+
assert.equal(after.summaryLayers.merge, 1);
|
|
19
|
+
assert.ok(after.summaryLayers.lastEpisodeAt, '应给出最近一次每日摘要的时间');
|
|
20
|
+
} finally {
|
|
21
|
+
cortex.close();
|
|
22
|
+
rmSync(dir, { recursive: true, force: true });
|
|
23
|
+
}
|
|
24
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { createCortex } from '../../src/service/cortex.js';
|
|
7
|
+
import { createToolDefinitions } from '../../src/tools/definitions.js';
|
|
8
|
+
|
|
9
|
+
async function healthText(cortex) {
|
|
10
|
+
const tool = createToolDefinitions(cortex).find((entry) => entry.name === 'cortex_health');
|
|
11
|
+
assert.ok(tool, '应存在 cortex_health 工具');
|
|
12
|
+
const result = await tool.execute({});
|
|
13
|
+
return typeof result === 'string' ? result : (result?.text ?? JSON.stringify(result));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
test('cortex_health 文本会显示维护耗时与「最近一次有变更」', async () => {
|
|
17
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-health-text-'));
|
|
18
|
+
const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
|
|
19
|
+
try {
|
|
20
|
+
const now = Date.now();
|
|
21
|
+
// 一条旧的「有变更」审计行(6 小时前)
|
|
22
|
+
cortex.repos.audit.record({ actor: 'self:maintain', action: 'maintain.run', targetType: 'scope', targetId: 'global', detail: { at: new Date(now - 6 * 3600000).toISOString(), working: 7, intentions: 3 } });
|
|
23
|
+
// 一次安静维护 → 内存里有耗时,但不写审计行
|
|
24
|
+
cortex.maintain({ now });
|
|
25
|
+
const text = await healthText(cortex);
|
|
26
|
+
assert.match(text, /维护:最近一趟/, '应显示最近一趟');
|
|
27
|
+
assert.match(text, /\d+ms/, '应显示维护耗时');
|
|
28
|
+
assert.match(text, /最近一次有变更:/, '旧审计行应单独说明');
|
|
29
|
+
} finally {
|
|
30
|
+
cortex.close();
|
|
31
|
+
rmSync(dir, { recursive: true, force: true });
|
|
32
|
+
}
|
|
33
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { createCortex } from '../../src/service/cortex.js';
|
|
7
|
+
|
|
8
|
+
test('health 的今日整理统计当天归档/合并数', async () => {
|
|
9
|
+
let traceIds = [];
|
|
10
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-health-today-'));
|
|
11
|
+
const cortex = createCortex({
|
|
12
|
+
config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llm: true } },
|
|
13
|
+
llm: {
|
|
14
|
+
available: () => true,
|
|
15
|
+
complete: async () => JSON.stringify([{ action: 'merge', ids: traceIds, targetId: traceIds[0] }]),
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
try {
|
|
19
|
+
const now = Date.now();
|
|
20
|
+
cortex.write({ text: '用户:重复的碎片甲,内容一样。', kind: 'utterance', title: '重复甲', importance: 0.6, explicit: true, now });
|
|
21
|
+
cortex.write({ text: '用户:重复的碎片乙,内容一样。', kind: 'utterance', title: '重复乙', importance: 0.6, explicit: true, now: now + 1000 });
|
|
22
|
+
traceIds = cortex.repos.traces.list({ scopeId: 'global', state: 'active', limit: 10 }).map((trace) => trace.id);
|
|
23
|
+
const run = await cortex.consolidation.run({ scopeId: 'global' });
|
|
24
|
+
assert.equal(run.applied.length, 1);
|
|
25
|
+
const health = cortex.health({ scopeId: 'global' });
|
|
26
|
+
assert.equal(health.consolidation.today.runs, 1);
|
|
27
|
+
assert.equal(health.consolidation.today.merged, 1);
|
|
28
|
+
assert.equal(health.consolidation.today.archived, 0);
|
|
29
|
+
} finally {
|
|
30
|
+
cortex.close();
|
|
31
|
+
rmSync(dir, { recursive: true, force: true });
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('没有整理改动时今日整理显示为零', () => {
|
|
36
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-health-today-zero-'));
|
|
37
|
+
const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
|
|
38
|
+
try {
|
|
39
|
+
const health = cortex.health({ scopeId: 'global' });
|
|
40
|
+
assert.deepEqual(health.consolidation.today, { runs: 0, archived: 0, merged: 0 });
|
|
41
|
+
} finally {
|
|
42
|
+
cortex.close();
|
|
43
|
+
rmSync(dir, { recursive: true, force: true });
|
|
44
|
+
}
|
|
45
|
+
});
|
|
@@ -20,12 +20,12 @@ test('turn events are captured as one trace with user and assistant text', () =>
|
|
|
20
20
|
const { dir, cortex, runtime } = setup();
|
|
21
21
|
try {
|
|
22
22
|
runtime.onSessionEvent(session, { type: 'turn/start', data: { turn: 1 }, time: Date.parse('2026-11-11T12:00:00+08:00') });
|
|
23
|
-
runtime.onSessionEvent(session, { type: 'user/message', data: { content: '
|
|
23
|
+
runtime.onSessionEvent(session, { type: 'user/message', data: { content: '用户说会买米饭。' }, time: Date.parse('2026-11-11T12:00:01+08:00') });
|
|
24
24
|
runtime.onSessionEvent(session, { type: 'assistant/message', data: { turn: 1, message: { content: '记住了。' } }, time: Date.parse('2026-11-11T12:00:02+08:00') });
|
|
25
25
|
runtime.onSessionEvent(session, { type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } }, time: Date.parse('2026-11-11T12:00:03+08:00') });
|
|
26
26
|
assert.equal(cortex.repos.traces.count(), 1);
|
|
27
27
|
const trace = cortex.repos.traces.list({ limit: 1 })[0];
|
|
28
|
-
assert.match(trace.content,
|
|
28
|
+
assert.match(trace.content, /用户说会买米饭/);
|
|
29
29
|
assert.match(trace.content, /记住了/);
|
|
30
30
|
assert.equal(runtime.pending().length, 0);
|
|
31
31
|
} finally {
|
|
@@ -63,12 +63,12 @@ test('duplicate turn capture is idempotent and subagents are skipped', () => {
|
|
|
63
63
|
test('user turns prefetch recall into a system-prompt block and turn/end clears it', () => {
|
|
64
64
|
const { dir, cortex, runtime } = setup();
|
|
65
65
|
try {
|
|
66
|
-
cortex.write({ text: '
|
|
66
|
+
cortex.write({ text: '用户说会买米饭,助手等得起。', explicit: true, now: Date.parse('2026-11-11T11:00:00+08:00') });
|
|
67
67
|
runtime.onSessionEvent(session, { type: 'turn/start', data: { turn: 3 }, time: Date.parse('2026-11-11T12:00:00+08:00') });
|
|
68
|
-
runtime.onSessionEvent(session, { type: 'user/message', data: { content: '
|
|
68
|
+
runtime.onSessionEvent(session, { type: 'user/message', data: { content: '米饭的承诺还算数吗?' }, time: Date.parse('2026-11-11T12:00:01+08:00') });
|
|
69
69
|
const block = runtime.recallText({ session: { id: 's1' } });
|
|
70
70
|
assert.match(block, /召回的相关记忆/);
|
|
71
|
-
assert.match(block,
|
|
71
|
+
assert.match(block, /米饭/);
|
|
72
72
|
runtime.onSessionEvent(session, { type: 'turn/end', data: { turn: 3, reason: { kind: 'completed' } }, time: Date.parse('2026-11-11T12:00:02+08:00') });
|
|
73
73
|
assert.equal(runtime.recallText({ session: { id: 's1' } }), '');
|
|
74
74
|
} finally {
|
|
@@ -101,15 +101,15 @@ test('capture:false keeps recall but writes no trace', () => {
|
|
|
101
101
|
const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
|
|
102
102
|
const runtime = createHostRuntime({ cortex, config: { scope: 'global', features: { capture: false, recall: true } } });
|
|
103
103
|
try {
|
|
104
|
-
cortex.write({ text: '
|
|
104
|
+
cortex.write({ text: '用户喜欢米饭。', explicit: true });
|
|
105
105
|
const at = Date.parse('2026-11-11T13:00:00+08:00');
|
|
106
106
|
runtime.onSessionEvent(session, { type: 'turn/start', data: { turn: 3 }, time: at });
|
|
107
|
-
runtime.onSessionEvent(session, { type: 'user/message', data: { content: '
|
|
107
|
+
runtime.onSessionEvent(session, { type: 'user/message', data: { content: '米饭' }, time: at + 1000 });
|
|
108
108
|
if (typeof runtime.onPreStep === 'function') runtime.onPreStep({ agent: { id: 's1' }, messages: [] });
|
|
109
109
|
runtime.onSessionEvent(session, { type: 'assistant/message', data: { turn: 3, message: { content: '嗯。' } }, time: at + 2000 });
|
|
110
110
|
runtime.onSessionEvent(session, { type: 'turn/end', data: { turn: 3, reason: { kind: 'completed' } }, time: at + 3000 });
|
|
111
111
|
assert.equal(cortex.repos.traces.count(), 1, 'only the explicit seed trace exists');
|
|
112
|
-
assert.equal(cortex.repos.traces.list({ limit: 10 })[0].content, '
|
|
112
|
+
assert.equal(cortex.repos.traces.list({ limit: 10 })[0].content, '用户喜欢米饭。');
|
|
113
113
|
} finally {
|
|
114
114
|
cortex.close();
|
|
115
115
|
rmSync(dir, { recursive: true, force: true });
|
package/test/unit/host.test.js
CHANGED
|
@@ -41,7 +41,7 @@ test('host plugin registers tools, a prompt section and cleans up', async () =>
|
|
|
41
41
|
};
|
|
42
42
|
try {
|
|
43
43
|
await apply(ctx, { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), scope: 'global' });
|
|
44
|
-
assert.equal(registered.length,
|
|
44
|
+
assert.equal(registered.length, 22);
|
|
45
45
|
assert.ok(registered.some((tool) => tool.name === 'cortex_search'));
|
|
46
46
|
assert.ok(handlers.some((entry) => entry.name === 'session/event'));
|
|
47
47
|
assert.ok(section);
|
|
@@ -26,11 +26,11 @@ test('repeated tagged traces induce candidate skills, not active ones', () => {
|
|
|
26
26
|
|
|
27
27
|
test('policy replay compares current and candidate retrieval', async () => {
|
|
28
28
|
const queries = [
|
|
29
|
-
{ query: '
|
|
29
|
+
{ query: '米饭', relevant: ['a'] },
|
|
30
30
|
{ query: '插件', relevant: ['b'] },
|
|
31
31
|
];
|
|
32
|
-
const current = async (query) => ({ items: query === '
|
|
33
|
-
const candidate = async (query) => ({ items: query === '
|
|
32
|
+
const current = async (query) => ({ items: query === '米饭' ? [{ id: 'x' }] : [{ id: 'b' }] });
|
|
33
|
+
const candidate = async (query) => ({ items: query === '米饭' ? [{ id: 'a' }] : [{ id: 'b' }] });
|
|
34
34
|
const before = await evaluatePolicy({ queries, run: current });
|
|
35
35
|
const after = await evaluatePolicy({ queries, run: candidate });
|
|
36
36
|
assert.equal(before.recallAtK, 0.5);
|
|
@@ -14,7 +14,7 @@ test('extracted text becomes a derived trace without mutating the target', () =>
|
|
|
14
14
|
const before = cortex.get(targetId);
|
|
15
15
|
const result = cortex.ingestExtractedText({
|
|
16
16
|
targetTraceId: targetId,
|
|
17
|
-
text: '
|
|
17
|
+
text: '米饭 HELLO 123',
|
|
18
18
|
uri: 'file:///C:/tmp/frame.png',
|
|
19
19
|
mode: 'ocr',
|
|
20
20
|
engine: 'windows-ocr',
|
|
@@ -24,10 +24,10 @@ test('extracted text becomes a derived trace without mutating the target', () =>
|
|
|
24
24
|
const after = cortex.get(targetId);
|
|
25
25
|
assert.equal(after.content, before.content);
|
|
26
26
|
const extracted = cortex.get(result.extractedTraceId);
|
|
27
|
-
assert.equal(extracted.content, '
|
|
27
|
+
assert.equal(extracted.content, '米饭 HELLO 123');
|
|
28
28
|
assert.equal(extracted.metadata.derivedFrom, targetId);
|
|
29
29
|
assert.equal(extracted.metadata.extractor.mode, 'ocr');
|
|
30
|
-
assert.ok(cortex.search('
|
|
30
|
+
assert.ok(cortex.search('米饭').items.some((item) => item.id === result.extractedTraceId));
|
|
31
31
|
} finally {
|
|
32
32
|
cortex.close();
|
|
33
33
|
rmSync(dir, { recursive: true, force: true });
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { createCortex } from '../../src/service/cortex.js';
|
|
7
|
+
import { suppressionOf, withSuppression, competingFactor } from '../../src/engines/inhibition.js';
|
|
8
|
+
|
|
9
|
+
const DAY = 86_400_000;
|
|
10
|
+
|
|
11
|
+
test('suppression halves every half-life and caps at one', () => {
|
|
12
|
+
const now = Date.parse('2026-11-15T12:00:00Z');
|
|
13
|
+
const metadata = { inhibition: 0.6, suppressedAt: new Date(now).toISOString() };
|
|
14
|
+
assert.equal(Math.round(suppressionOf(metadata, now) * 100) / 100, 0.6);
|
|
15
|
+
assert.equal(Math.round(suppressionOf(metadata, now + 14 * DAY) * 100) / 100, 0.3);
|
|
16
|
+
assert.ok(suppressionOf(metadata, now + 999 * DAY) < 0.01);
|
|
17
|
+
assert.equal(suppressionOf({}, now), 0);
|
|
18
|
+
const grown = withSuppression({}, now, { step: 0.15 });
|
|
19
|
+
assert.equal(grown.inhibition, 0.15);
|
|
20
|
+
const capped = withSuppression({ inhibition: 0.95, suppressedAt: new Date(now).toISOString() }, now, { step: 0.5 });
|
|
21
|
+
assert.equal(capped.inhibition, 1);
|
|
22
|
+
assert.ok(competingFactor(metadata, now, { strength: 0.35 }) < 1);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
function seed(cortex, prefix) {
|
|
26
|
+
// A matches the query; B is nearly the same text but does not contain the
|
|
27
|
+
// query term, so it only enters through the recency list with low fusion.
|
|
28
|
+
// That is exactly the "competitor that loses" case.
|
|
29
|
+
cortex.write({
|
|
30
|
+
text: `${prefix}甲的记忆:这一段讲的是同一个编号的记忆,内容几乎一样,只有末尾的标记不同。再补一段相同的描述文字,让两条候选足够相似。`,
|
|
31
|
+
kind: 'observation',
|
|
32
|
+
title: `${prefix}甲`,
|
|
33
|
+
importance: 0.7,
|
|
34
|
+
});
|
|
35
|
+
cortex.write({
|
|
36
|
+
text: `${prefix}乙的记事:这一段讲的是同一个编号的记忆,内容几乎一样,只有末尾的标记不同。再补一段相同的描述文字,让两条候选足够相似。`,
|
|
37
|
+
kind: 'observation',
|
|
38
|
+
title: `${prefix}乙`,
|
|
39
|
+
importance: 0.7,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
test('inhibition is off by default and writes nothing', () => {
|
|
44
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-inhibit-off-'));
|
|
45
|
+
const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
|
|
46
|
+
try {
|
|
47
|
+
seed(cortex, '编号甲');
|
|
48
|
+
cortex.search('编号甲 记忆');
|
|
49
|
+
const touched = cortex.repos.traces.list({ limit: 20 }).filter((trace) => Number(trace.metadata?.inhibition) > 0);
|
|
50
|
+
assert.equal(touched.length, 0);
|
|
51
|
+
const health = cortex.health();
|
|
52
|
+
assert.equal(health.inhibition.enabled, false);
|
|
53
|
+
assert.equal(health.inhibition.count, 0);
|
|
54
|
+
} finally {
|
|
55
|
+
cortex.close();
|
|
56
|
+
rmSync(dir, { recursive: true, force: true });
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('when enabled, a competitor dropped for redundancy gains suppression', () => {
|
|
61
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-inhibit-on-'));
|
|
62
|
+
const cortex = createCortex({
|
|
63
|
+
config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { inhibition: true } },
|
|
64
|
+
});
|
|
65
|
+
try {
|
|
66
|
+
seed(cortex, '编号乙');
|
|
67
|
+
const result = cortex.search('编号乙甲', { limit: 1 });
|
|
68
|
+
assert.equal(result.items.length, 1);
|
|
69
|
+
const touched = cortex.repos.traces.list({ limit: 20 }).filter((trace) => Number(trace.metadata?.inhibition) > 0);
|
|
70
|
+
assert.ok(touched.length >= 1, 'the suppressed competitor should carry metadata.inhibition');
|
|
71
|
+
assert.ok(touched[0].metadata.suppressedAt);
|
|
72
|
+
assert.equal(Number(touched[0].metadata.inhibition), 0.15);
|
|
73
|
+
const health = cortex.health();
|
|
74
|
+
assert.equal(health.inhibition.enabled, true);
|
|
75
|
+
assert.ok(health.inhibition.count >= 1);
|
|
76
|
+
assert.ok(health.inhibition.average > 0);
|
|
77
|
+
assert.ok(health.inhibition.top.length >= 1);
|
|
78
|
+
const listed = cortex.inhibition.list({});
|
|
79
|
+
assert.ok(listed.length >= 1);
|
|
80
|
+
const cleared = cortex.inhibition.clear({ id: listed[0].id });
|
|
81
|
+
assert.equal(cleared.cleared, 1);
|
|
82
|
+
assert.equal(cortex.inhibition.list({}).length, listed.length - 1);
|
|
83
|
+
const clearedAll = cortex.inhibition.clear({ all: true });
|
|
84
|
+
assert.equal(clearedAll.cleared, listed.length - 1);
|
|
85
|
+
assert.equal(cortex.health().inhibition.count, 0);
|
|
86
|
+
} finally {
|
|
87
|
+
cortex.close();
|
|
88
|
+
rmSync(dir, { recursive: true, force: true });
|
|
89
|
+
}
|
|
90
|
+
});
|
package/test/unit/jobs.test.js
CHANGED
|
@@ -17,8 +17,8 @@ function setup() {
|
|
|
17
17
|
test('jobs are idempotent by operationId and can be claimed/completed', () => {
|
|
18
18
|
const { dir, db, queue } = setup();
|
|
19
19
|
try {
|
|
20
|
-
const first = queue.enqueue({ kind: 'extract', payload: { text: '
|
|
21
|
-
const replay = queue.enqueue({ kind: 'extract', payload: { text: '
|
|
20
|
+
const first = queue.enqueue({ kind: 'extract', payload: { text: '米饭' }, operationId: 'op-1' });
|
|
21
|
+
const replay = queue.enqueue({ kind: 'extract', payload: { text: '米饭' }, operationId: 'op-1' });
|
|
22
22
|
assert.equal(replay.id, first.id);
|
|
23
23
|
assert.equal(queue.counts().pending, 1);
|
|
24
24
|
const claimed = queue.claimNext({ now: Date.now() + 1000 });
|
|
@@ -61,12 +61,12 @@ test('a failed job retries and eventually becomes failed', () => {
|
|
|
61
61
|
test('runner executes a handler and records the result', async () => {
|
|
62
62
|
const { dir, db, queue } = setup();
|
|
63
63
|
try {
|
|
64
|
-
queue.enqueue({ kind: 'echo', payload: { text: '
|
|
64
|
+
queue.enqueue({ kind: 'echo', payload: { text: '米饭' } });
|
|
65
65
|
const runner = createJobRunner({ queue, handlers: { echo: async (payload) => ({ echoed: payload.text }) } });
|
|
66
66
|
const result = await runner.runUntilIdle();
|
|
67
67
|
assert.equal(result.ran, 1);
|
|
68
68
|
assert.equal(result.results[0].ok, true);
|
|
69
|
-
assert.equal(queue.list({ status: 'done' })[0].result.echoed, '
|
|
69
|
+
assert.equal(queue.list({ status: 'done' })[0].result.echoed, '米饭');
|
|
70
70
|
} finally {
|
|
71
71
|
closeDatabase(db);
|
|
72
72
|
rmSync(dir, { recursive: true, force: true });
|
|
@@ -12,7 +12,7 @@ test('snapshot export validates and imports idempotently', () => {
|
|
|
12
12
|
const source = createCortex({ config: { dataRoot: sourceDir, dbFile: path.join(sourceDir, 'cortex.sqlite') } });
|
|
13
13
|
const target = createCortex({ config: { dataRoot: targetDir, dbFile: path.join(targetDir, 'cortex.sqlite') } });
|
|
14
14
|
try {
|
|
15
|
-
source.write({ text: '
|
|
15
|
+
source.write({ text: '用户说会买米饭。', explicit: true, tags: ['米饭'] });
|
|
16
16
|
const snapshot = exportSnapshot(source);
|
|
17
17
|
assert.equal(validateSnapshot(snapshot).ok, true);
|
|
18
18
|
const dry = importSnapshot(target, snapshot, { dryRun: true });
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { createCortex } from '../../src/service/cortex.js';
|
|
7
|
+
|
|
8
|
+
test('labelEntities 在缺 adapter 时也返回 no-llm-adapter,与巩固标签一致', async () => {
|
|
9
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-label-no-adapter-'));
|
|
10
|
+
const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite') } });
|
|
11
|
+
try {
|
|
12
|
+
const result = await cortex.labelEntities({ scopeId: 'global' });
|
|
13
|
+
assert.equal(result.skipped, 'no-llm-adapter');
|
|
14
|
+
} finally {
|
|
15
|
+
cortex.close();
|
|
16
|
+
rmSync(dir, { recursive: true, force: true });
|
|
17
|
+
}
|
|
18
|
+
});
|
|
@@ -11,11 +11,11 @@ test('llmFacts schedules background extraction and writes validated facts', asyn
|
|
|
11
11
|
config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), features: { llmFacts: true } },
|
|
12
12
|
llm: {
|
|
13
13
|
available: () => true,
|
|
14
|
-
complete: async () => '{"facts":[{"subject":"助手","predicate":"likes","object":"
|
|
14
|
+
complete: async () => '{"facts":[{"subject":"助手","predicate":"likes","object":"米饭","confidence":0.9},{"subject":"x","predicate":"y","object":"z","confidence":0.1}]}',
|
|
15
15
|
},
|
|
16
16
|
});
|
|
17
17
|
try {
|
|
18
|
-
cortex.write({ text: '
|
|
18
|
+
cortex.write({ text: '助手喜欢米饭。', explicit: true });
|
|
19
19
|
await cortex.flushLlmFacts();
|
|
20
20
|
const facts = cortex.repos.facts.list({ scopeId: 'global' });
|
|
21
21
|
assert.equal(facts.length, 1);
|
|
@@ -3,10 +3,10 @@ import assert from 'node:assert/strict';
|
|
|
3
3
|
import { extractFactsWithLlm } from '../../src/engines/llm-facts.js';
|
|
4
4
|
|
|
5
5
|
test('LLM facts parse strict JSON and drop low-confidence/unsupported items', async () => {
|
|
6
|
-
const llm = { complete: async () => '```json\n{"facts":[{"subject":"助手","predicate":"likes","object":"
|
|
7
|
-
const result = await extractFactsWithLlm({ llm, text: '
|
|
6
|
+
const llm = { complete: async () => '```json\n{"facts":[{"subject":"助手","predicate":"likes","object":"米饭","confidence":0.9},{"subject":"x","predicate":"y","object":"z","confidence":0.2}]}\n```' };
|
|
7
|
+
const result = await extractFactsWithLlm({ llm, text: '助手喜欢米饭。' });
|
|
8
8
|
assert.equal(result.candidates.length, 1);
|
|
9
|
-
assert.deepEqual(result.candidates[0], { subject: '助手', predicate: 'likes', object: '
|
|
9
|
+
assert.deepEqual(result.candidates[0], { subject: '助手', predicate: 'likes', object: '米饭', confidence: 0.9 });
|
|
10
10
|
});
|
|
11
11
|
|
|
12
12
|
test('LLM facts fail closed on malformed output or missing model', async () => {
|
package/test/unit/llm.test.js
CHANGED
|
@@ -2,7 +2,7 @@ import test from 'node:test';
|
|
|
2
2
|
import assert from 'node:assert/strict';
|
|
3
3
|
import { createLlmAdapter } from '../../src/llm/adapter.js';
|
|
4
4
|
|
|
5
|
-
function mockCtx(text = '
|
|
5
|
+
function mockCtx(text = '梦里,助手坐在米饭旁边。') {
|
|
6
6
|
return {
|
|
7
7
|
get(name) {
|
|
8
8
|
if (name === 'llm') {
|
|
@@ -21,11 +21,11 @@ test('llm adapter completes, dreams and summarizes through the host service', as
|
|
|
21
21
|
const adapter = createLlmAdapter({ ctx: mockCtx() });
|
|
22
22
|
assert.equal(adapter.available(), true);
|
|
23
23
|
const text = await adapter.complete({ system: 's', prompt: 'p' });
|
|
24
|
-
assert.match(text,
|
|
25
|
-
const dream = await adapter.dream({ pieces: ['
|
|
26
|
-
assert.match(dream,
|
|
24
|
+
assert.match(text, /米饭/);
|
|
25
|
+
const dream = await adapter.dream({ pieces: ['米饭'], emotions: '暖' });
|
|
26
|
+
assert.match(dream, /米饭/);
|
|
27
27
|
const summary = await adapter.summarize({ text: '一段很长的记忆' });
|
|
28
|
-
assert.match(summary,
|
|
28
|
+
assert.match(summary, /米饭/);
|
|
29
29
|
});
|
|
30
30
|
|
|
31
31
|
test('llm adapter fails open when the service is missing or errors', async () => {
|
package/test/unit/locomo.test.js
CHANGED
|
@@ -13,7 +13,7 @@ const sample = {
|
|
|
13
13
|
speaker_b: 'B',
|
|
14
14
|
session_1_date_time: '2026-11-01T10:00:00+08:00',
|
|
15
15
|
session_1: [
|
|
16
|
-
{ speaker: 'A', text: '
|
|
16
|
+
{ speaker: 'A', text: '我喜欢米饭。' },
|
|
17
17
|
{ speaker: 'B', text: '那很好。' },
|
|
18
18
|
],
|
|
19
19
|
session_2_date_time: '2026-11-02T10:00:00+08:00',
|
|
@@ -22,7 +22,7 @@ const sample = {
|
|
|
22
22
|
],
|
|
23
23
|
},
|
|
24
24
|
qa: [
|
|
25
|
-
{ question: 'A 喜欢什么?', answer: '
|
|
25
|
+
{ question: 'A 喜欢什么?', answer: '米饭', evidence: ['D1:1'], category: 1 },
|
|
26
26
|
{ question: '不存在的事是什么?', answer: '没有', evidence: [], category: 5 },
|
|
27
27
|
],
|
|
28
28
|
};
|