dsh-cortex-memory 0.4.146 → 0.4.148

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/CHANGELOG.md +2423 -2369
  2. package/README.md +8 -8
  3. package/bench/governance.mjs +265 -0
  4. package/bench/migration-bench.mjs +1 -1
  5. package/bench/semantic-cn.js +4 -4
  6. package/bench/synthetic.js +3 -3
  7. package/bin/copy-db.mjs +1 -1
  8. package/bin/repair.mjs +7 -7
  9. package/client.js +1 -1
  10. package/docs/install-windows.md +2 -2
  11. package/docs/models.md +1 -1
  12. package/docs/quota-compaction-design.md +3 -3
  13. package/icon.svg +12 -2
  14. package/index.js +5 -6
  15. package/package.json +7 -8
  16. package/src/adapters/shiori.js +1 -1
  17. package/src/engines/compression.js +8 -3
  18. package/src/engines/consolidate.js +1 -1
  19. package/src/engines/encode.js +3 -3
  20. package/src/engines/extract.js +1 -1
  21. package/src/engines/health.js +1 -1
  22. package/src/engines/life.js +2 -2
  23. package/src/engines/narrative.js +4 -8
  24. package/src/engines/retrieve.js +41 -4
  25. package/src/host/scheduler.js +5 -4
  26. package/src/memory/tokenizer.js +1 -1
  27. package/src/self/alias.js +4 -5
  28. package/src/self/memory-policy.js +59 -0
  29. package/src/service/cortex.js +20 -2
  30. package/src/store/repositories/facts.js +1 -1
  31. package/src/store/repositories/traces.js +1 -1
  32. package/test/integration/_helpers.js +0 -128
  33. package/test/integration/acceptance.test.js +0 -803
  34. package/test/integration/ann-load.test.js +0 -61
  35. package/test/integration/api-contract.test.js +0 -1476
  36. package/test/integration/backup-privacy.test.js +0 -214
  37. package/test/integration/consolidate.test.js +0 -79
  38. package/test/integration/edge-cases.test.js +0 -1089
  39. package/test/integration/exchange.test.js +0 -326
  40. package/test/integration/life-loop.test.js +0 -189
  41. package/test/integration/load.test.js +0 -751
  42. package/test/integration/markdown-sync.test.js +0 -35
  43. package/test/integration/policy-query-api.test.js +0 -306
  44. package/test/integration/resilience-writes.test.js +0 -241
  45. package/test/integration/tools-contract.test.js +0 -1324
  46. package/test/unit/alias.test.js +0 -87
  47. package/test/unit/ann-edge.test.js +0 -102
  48. package/test/unit/ann.test.js +0 -77
  49. package/test/unit/api-client.test.js +0 -576
  50. package/test/unit/api-validate.test.js +0 -19
  51. package/test/unit/api.test.js +0 -555
  52. package/test/unit/appraisal.test.js +0 -48
  53. package/test/unit/attachments.test.js +0 -33
  54. package/test/unit/auto-reflect.test.js +0 -141
  55. package/test/unit/autonomy.test.js +0 -53
  56. package/test/unit/batch.test.js +0 -46
  57. package/test/unit/bench.test.js +0 -40
  58. package/test/unit/benchmark-synthetic.test.js +0 -52
  59. package/test/unit/capture-filter.test.js +0 -296
  60. package/test/unit/cli-default-root.test.js +0 -21
  61. package/test/unit/client-contract.test.js +0 -32
  62. package/test/unit/compaction-preview.test.js +0 -91
  63. package/test/unit/compression.test.js +0 -76
  64. package/test/unit/consolidate-dedupe.test.js +0 -174
  65. package/test/unit/consolidate-errors.test.js +0 -63
  66. package/test/unit/consolidate-gate.test.js +0 -26
  67. package/test/unit/consolidate-preview.test.js +0 -168
  68. package/test/unit/consolidate-protection.test.js +0 -156
  69. package/test/unit/consolidate-reason.test.js +0 -206
  70. package/test/unit/consolidate-retry.test.js +0 -91
  71. package/test/unit/consolidate-selection.test.js +0 -103
  72. package/test/unit/core.test.js +0 -77
  73. package/test/unit/coverage-rewrite.test.js +0 -38
  74. package/test/unit/dedupe-episodes.test.js +0 -34
  75. package/test/unit/dedupe-threshold.test.js +0 -14
  76. package/test/unit/develop.test.js +0 -130
  77. package/test/unit/development.test.js +0 -68
  78. package/test/unit/digest.test.js +0 -26
  79. package/test/unit/dsr.test.js +0 -111
  80. package/test/unit/edges-candidates.test.js +0 -113
  81. package/test/unit/emotion.test.js +0 -62
  82. package/test/unit/encode.test.js +0 -98
  83. package/test/unit/evolution.test.js +0 -130
  84. package/test/unit/external-ann-search.test.js +0 -50
  85. package/test/unit/external-ann.test.js +0 -29
  86. package/test/unit/extract-question.test.js +0 -41
  87. package/test/unit/fact-guard.test.js +0 -51
  88. package/test/unit/fact-noise-llm.test.js +0 -44
  89. package/test/unit/facts-belief.test.js +0 -32
  90. package/test/unit/facts-compat.test.js +0 -62
  91. package/test/unit/facts.test.js +0 -107
  92. package/test/unit/feature-overrides.test.js +0 -42
  93. package/test/unit/fts-migration.test.js +0 -42
  94. package/test/unit/graph.test.js +0 -79
  95. package/test/unit/growth-reflect.test.js +0 -124
  96. package/test/unit/guard-runtime.test.js +0 -40
  97. package/test/unit/guardian.test.js +0 -91
  98. package/test/unit/health-consolidation.test.js +0 -52
  99. package/test/unit/health-fts-scope.test.js +0 -33
  100. package/test/unit/health-privacy.test.js +0 -102
  101. package/test/unit/health-summaries.test.js +0 -24
  102. package/test/unit/health-text-maintain.test.js +0 -33
  103. package/test/unit/health-today.test.js +0 -45
  104. package/test/unit/hnsw.test.js +0 -35
  105. package/test/unit/host-runtime.test.js +0 -142
  106. package/test/unit/host.test.js +0 -58
  107. package/test/unit/identity.test.js +0 -98
  108. package/test/unit/induct-evaluate.test.js +0 -41
  109. package/test/unit/ingest-extracted.test.js +0 -35
  110. package/test/unit/inhibition.test.js +0 -90
  111. package/test/unit/initiative.test.js +0 -90
  112. package/test/unit/jobs.test.js +0 -93
  113. package/test/unit/json-snapshot.test.js +0 -57
  114. package/test/unit/label-entities-skip.test.js +0 -18
  115. package/test/unit/life-consolidate.test.js +0 -34
  116. package/test/unit/life.test.js +0 -149
  117. package/test/unit/llm-facts-integration.test.js +0 -27
  118. package/test/unit/llm-facts.test.js +0 -16
  119. package/test/unit/llm.test.js +0 -45
  120. package/test/unit/locomo.test.js +0 -45
  121. package/test/unit/longmemeval.test.js +0 -56
  122. package/test/unit/maintain-dispute.test.js +0 -62
  123. package/test/unit/maintain-duration.test.js +0 -194
  124. package/test/unit/markdown-import.test.js +0 -44
  125. package/test/unit/markdown.test.js +0 -34
  126. package/test/unit/memory-edit.test.js +0 -112
  127. package/test/unit/metrics.test.js +0 -26
  128. package/test/unit/migration.test.js +0 -38
  129. package/test/unit/model-config.test.js +0 -52
  130. package/test/unit/mood-saturation.test.js +0 -33
  131. package/test/unit/narrative-weave.test.js +0 -271
  132. package/test/unit/narrative.test.js +0 -62
  133. package/test/unit/playbook-consolidate.test.js +0 -24
  134. package/test/unit/privacy-scope.test.js +0 -39
  135. package/test/unit/profile-paths.test.js +0 -21
  136. package/test/unit/profile.test.js +0 -26
  137. package/test/unit/prompt.test.js +0 -42
  138. package/test/unit/providers.test.js +0 -42
  139. package/test/unit/qa.test.js +0 -100
  140. package/test/unit/query.test.js +0 -53
  141. package/test/unit/reflect-backfill.test.js +0 -158
  142. package/test/unit/reflect-coverage.test.js +0 -35
  143. package/test/unit/reflect-overview.test.js +0 -22
  144. package/test/unit/reflect-phrasing.test.js +0 -75
  145. package/test/unit/reflect-sampling.test.js +0 -80
  146. package/test/unit/reflect-source-budget.test.js +0 -24
  147. package/test/unit/relationship-dynamics.test.js +0 -29
  148. package/test/unit/retention.test.js +0 -31
  149. package/test/unit/retrieval-ranking.test.js +0 -31
  150. package/test/unit/retrieve.test.js +0 -117
  151. package/test/unit/revive-on-read.test.js +0 -84
  152. package/test/unit/rotation.test.js +0 -25
  153. package/test/unit/scanner.test.js +0 -50
  154. package/test/unit/scenario.test.js +0 -78
  155. package/test/unit/scheduler-autoconsolidate.test.js +0 -95
  156. package/test/unit/scheduler-autodedupe.test.js +0 -52
  157. package/test/unit/scheduler-autosleep.test.js +0 -50
  158. package/test/unit/scheduler-cadence.test.js +0 -33
  159. package/test/unit/scheduler-deep.test.js +0 -62
  160. package/test/unit/scheduler-tick-gate.test.js +0 -38
  161. package/test/unit/scheduler.test.js +0 -137
  162. package/test/unit/self-state.test.js +0 -94
  163. package/test/unit/service.test.js +0 -72
  164. package/test/unit/shiori-import.test.js +0 -77
  165. package/test/unit/skills.test.js +0 -104
  166. package/test/unit/spacing.test.js +0 -14
  167. package/test/unit/store.test.js +0 -111
  168. package/test/unit/summon-left-slot.test.js +0 -51
  169. package/test/unit/summon-rank.test.js +0 -51
  170. package/test/unit/temporal-graph.test.js +0 -44
  171. package/test/unit/tiers-gist.test.js +0 -140
  172. package/test/unit/tiers.test.js +0 -39
  173. package/test/unit/tokenizer-fts.test.js +0 -35
  174. package/test/unit/tools.test.js +0 -122
  175. package/test/unit/upgrade-0412.test.js +0 -104
  176. package/test/unit/upgrade-0413.test.js +0 -84
  177. package/test/unit/upgrade-0414.test.js +0 -101
  178. package/test/unit/vector-ann.test.js +0 -53
  179. package/test/unit/vector-async.test.js +0 -69
  180. package/test/unit/vector-coverage.test.js +0 -34
  181. package/test/unit/vector-override.test.js +0 -37
  182. package/test/unit/vector-typed-array.test.js +0 -47
  183. package/test/unit/vector.test.js +0 -68
  184. package/test/unit/working.test.js +0 -99
@@ -22,6 +22,7 @@ import { createSummonRepository } from '../store/repositories/summon.js';
22
22
  import { createIdentityStore } from '../self/identity.js';
23
23
  import { createRelationshipStore } from '../self/relationship.js';
24
24
  import { createTargetResolver } from '../self/alias.js';
25
+ import { createMemoryPolicy } from '../self/memory-policy.js';
25
26
  import { createEncodeEngine, isInjectedNoise } from '../engines/encode.js';
26
27
  import { createRetrievalEngine } from '../engines/retrieve.js';
27
28
  import { createGrowthEngine } from '../engines/growth.js';
@@ -90,6 +91,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
90
91
  const identityStore = createIdentityStore(db);
91
92
  const targetResolver = createTargetResolver(config.persona ?? {});
92
93
  const relationshipStore = createRelationshipStore(db, { resolveTarget: targetResolver.resolveTarget });
94
+ let lastFamiliarityBumpAt = 0;
93
95
  const metrics = createMetrics();
94
96
  const workingStore = createWorkingStore(db);
95
97
  const goalStore = createGoalStore(db);
@@ -132,11 +134,12 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
132
134
  const encode = createEncodeEngine({ events, traces, entities, facts, edges, audit, vector, config });
133
135
  const graph = createGraphEngine({ entities, facts, edges, traces });
134
136
  const policies = createPolicyRepository(db);
137
+ const memoryPolicy = createMemoryPolicy({ policies, config });
135
138
  const policyConfig = (kind) => {
136
139
  try { return policies.active(kind)?.config ?? null; } catch { return null; }
137
140
  };
138
141
  const retrieve = createRetrievalEngine({ traces, facts, graph, vector, policy: policyConfig, config });
139
- const compression = createCompressionEngine({ traces, summaries, facts, entities, config });
142
+ const compression = createCompressionEngine({ traces, summaries, facts, entities, config, memoryPolicy });
140
143
  const extractor = createFactExtractor({ entities, facts });
141
144
  const digest = createDigestEngine({ traces, summaries, emotion, goals: goalStore, feedback, scopeId: config.scope });
142
145
  const retention = createRetentionEngine({ traces });
@@ -182,7 +185,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
182
185
  })
183
186
  : null;
184
187
  const qa = createQaEngine({ cortex: { search: (query, options) => search(query, options), searchAsync: (query, options) => searchAsync(query, options) }, llm: llmAdapter, reranker, limit: config.qa?.limit ?? 8, budget: config.qa?.budget ?? 3000 });
185
- const narrative = createNarrativeEngine({ traces, summaries, selfName: config.persona?.selfName ?? '助手' });
188
+ const narrative = createNarrativeEngine({ traces, summaries });
186
189
  const consolidation = createConsolidationEngine({ db, traces, summaries, audit, llm: llmAdapter });
187
190
  const skills = createSkillEngine({ skills: skillsRepo, traces });
188
191
  const health = createHealthEngine({
@@ -442,6 +445,20 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
442
445
  if (!result.skipped && config.features?.llmFacts === true && llmAdapter?.available?.() && !Array.isArray(input.facts)) {
443
446
  scheduleLlmFacts(result, input);
444
447
  }
448
+ // Shared time is relationship too: a captured turn (not every recall, not
449
+ // every read) nudges familiarity. Throttled to once per two hours so a busy
450
+ // afternoon cannot inflate it, and it never touches trust/care.
451
+ if (!result.skipped && input.source === 'host:turn') {
452
+ const at = Date.now();
453
+ if (at - lastFamiliarityBumpAt > 2 * 3_600_000) {
454
+ lastFamiliarityBumpAt = at;
455
+ try {
456
+ relationshipStore.applyDelta(scopeId, targetResolver.canonical, { familiarityDelta: 0.002 }, { event: 'interaction:turn', at: new Date(at).toISOString() });
457
+ } catch {
458
+ /* the relationship nudge must never block capture */
459
+ }
460
+ }
461
+ }
445
462
  return result;
446
463
  }
447
464
 
@@ -1581,6 +1598,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1581
1598
  repos: { events, traces, entities, facts, edges, feedback, summaries, jobs, skills: skillsRepo, audit, playbook: playbookRepo },
1582
1599
  stores: { selfStore, appraisalStore, initiativeStore, identityStore, relationshipStore },
1583
1600
  engines: { encode, graph, retrieve, growth, reflect, narrative, skills, health, privacy, develop, development, vector, compression, extractor, runner },
1601
+ memoryPolicy,
1584
1602
  development,
1585
1603
  narrative,
1586
1604
  vector,
@@ -142,7 +142,7 @@ export function createFactRepository(db) {
142
142
  if (later.validFrom === validFrom) {
143
143
  // Same start, different object. The compatibility rule only applies
144
144
  // when both sides are free text: "一直在" and "一直存在着" can coexist.
145
- // Entity-to-entity conflicts (likes 咖啡 vs likes 茶) still dispute.
145
+ // Entity-to-entity conflicts (likes 米饭 vs likes 米饭) still dispute.
146
146
  const newLiteral = objectLiteral ?? null;
147
147
  const allLiterals = Boolean(newLiteral) && existing.every((fact) => Boolean(fact.objectLiteral));
148
148
  const flip = allLiterals && existing.some((fact) => negationFlip(fact.objectLiteral, newLiteral));
@@ -269,7 +269,7 @@ export function createTraceRepository(db) {
269
269
  // Without a scope this is the whole index. With one it must join through
270
270
  // traces: health used to compare the *global* trace count against the
271
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
272
+ // (the production store has an `agency` scope, so it warned by exactly those
273
273
  // 12 rows forever).
274
274
  if (scopeId) {
275
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);
@@ -1,128 +0,0 @@
1
- /**
2
- * Shared helpers for the integration suite.
3
- *
4
- * The tests are deliberately black-box: every helper here only creates real
5
- * cortex instances in throwaway directories, drives real repository/engine
6
- * code, and cleans up afterwards. Nothing mocks the module under test.
7
- */
8
- import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
9
- import os from 'node:os';
10
- import path from 'node:path';
11
- import { Readable } from 'node:stream';
12
- import { createCortex } from '../../src/service/cortex.js';
13
- import { API_BASE } from '../../src/api/routes.js';
14
-
15
- export const DAY_MS = 86_400_000;
16
- /** Fixed reference instant: 2026-11-11T10:00:00+08:00. */
17
- export const BASE_MS = Date.parse('2026-11-11T10:00:00+08:00');
18
-
19
- /**
20
- * Create a cortex backed by a fresh temporary directory.
21
- * Returns the directory (for cleanup) and the service.
22
- */
23
- export function makeCortex(config = {}) {
24
- const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-integration-'));
25
- const dataRoot = config.dataRoot ?? path.join(dir, 'data');
26
- const dbFile = config.dbFile ?? path.join(dataRoot, 'cortex.sqlite');
27
- const cortex = createCortex({ config: { ...config, dataRoot, dbFile } });
28
- return { dir, cortex };
29
- }
30
-
31
- /**
32
- * Close every cortex first, then delete every temporary directory. Safe to
33
- * call from a finally block even when the test failed halfway through setup.
34
- */
35
- export function cleanup(...contexts) {
36
- for (const context of contexts) {
37
- try {
38
- context?.cortex?.close();
39
- } catch {
40
- /* closing is best-effort, cleanup must not mask the real assertion */
41
- }
42
- if (context?.dir) rmSync(context.dir, { recursive: true, force: true });
43
- }
44
- }
45
-
46
- /** Request stream shaped the way the API handler expects node:http objects. */
47
- export function apiRequest({
48
- method = 'GET',
49
- route = '/ping',
50
- body = null,
51
- headers = {},
52
- remoteAddress = '127.0.0.1',
53
- host = '127.0.0.1:7430',
54
- origin = 'http://127.0.0.1:7430',
55
- site = 'same-origin',
56
- url = null,
57
- } = {}) {
58
- const stream = Readable.from(body === null ? [] : [Buffer.from(JSON.stringify(body), 'utf8')]);
59
- stream.method = method;
60
- stream.url = url ?? `${API_BASE}${route}`;
61
- const merged = {
62
- host,
63
- origin,
64
- 'sec-fetch-site': site,
65
- ...(body === null ? {} : { 'content-type': 'application/json' }),
66
- ...headers,
67
- };
68
- for (const [key, value] of Object.entries(merged)) {
69
- if (value === undefined) delete merged[key];
70
- }
71
- stream.headers = merged;
72
- stream.socket = { remoteAddress };
73
- return stream;
74
- }
75
-
76
- /** Minimal ServerResponse recorder: enough for the route handler. */
77
- export function apiResponse() {
78
- return {
79
- statusCode: 0,
80
- headers: null,
81
- body: '',
82
- writeHead(code, headers) {
83
- this.statusCode = code;
84
- this.headers = headers ?? null;
85
- },
86
- end(chunk) {
87
- if (chunk != null) this.body += String(chunk);
88
- },
89
- };
90
- }
91
-
92
- export async function invokeApi(handler, options = {}) {
93
- const response = apiResponse();
94
- await handler(apiRequest(options), response);
95
- return { status: response.statusCode, headers: response.headers, json: JSON.parse(response.body || '{}') };
96
- }
97
-
98
- /**
99
- * Split an exported MEMORY.md mirror into its per-memory frontmatter blocks.
100
- *
101
- * The exporter writes one multi-entry document; the importer expects one
102
- * memory per file. This helper converts the mirror into the vault shape the
103
- * importer documents, using the same textual boundaries the exporter emits.
104
- */
105
- export function splitMirrorEntries(markdown) {
106
- const entries = [];
107
- const pattern = /^---\n([\s\S]*?)\n---\n\n([\s\S]*?)(?=\n---\n|$)/gm;
108
- for (const match of String(markdown ?? '').matchAll(pattern)) {
109
- entries.push({ frontmatter: match[1], body: match[2].trim() });
110
- }
111
- return entries;
112
- }
113
-
114
- /** Write one frontmatter memory file into a vault directory. */
115
- export function writeVaultEntry(dir, name, { frontmatter, body }) {
116
- mkdirSync(dir, { recursive: true });
117
- const file = path.join(dir, name);
118
- writeFileSync(file, `---\n${frontmatter}\n---\n\n${body}\n`, 'utf8');
119
- return file;
120
- }
121
-
122
- /** Write a raw file, mainly for hand-authored vault fixtures. */
123
- export function writeRaw(dir, name, content) {
124
- mkdirSync(dir, { recursive: true });
125
- const file = path.join(dir, name);
126
- writeFileSync(file, content, 'utf8');
127
- return file;
128
- }