dsh-cortex-memory 0.3.1 → 0.4.14

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 (140) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/LICENSE +1 -1
  3. package/README.md +67 -14
  4. package/client.js +33 -19
  5. package/cordis.patch.yml +1 -1
  6. package/docs/compatibility.md +39 -0
  7. package/docs/install-windows.md +2 -1
  8. package/docs/permissions.md +6 -2
  9. package/docs/privacy.md +3 -1
  10. package/examples/README.md +3 -2
  11. package/examples/uninstall-cortex.ps1 +1 -0
  12. package/index.js +31 -1
  13. package/package.json +8 -12
  14. package/src/adapters/shiori.js +1 -1
  15. package/src/api/routes.js +30 -3
  16. package/src/core/config.js +33 -0
  17. package/src/engines/develop.js +1 -1
  18. package/src/engines/extract.js +26 -7
  19. package/src/engines/growth.js +1 -1
  20. package/src/engines/life.js +56 -41
  21. package/src/engines/reflect.js +1 -1
  22. package/src/engines/retrieve.js +34 -5
  23. package/src/guardian/guardian.js +3 -2
  24. package/src/guardian/invariants.js +9 -5
  25. package/src/host/runtime.js +13 -7
  26. package/src/host/scheduler.js +11 -2
  27. package/src/llm/adapter.js +19 -7
  28. package/src/memory/query.js +1 -1
  29. package/src/self/appraisal.js +3 -3
  30. package/src/self/emotion.js +1 -1
  31. package/src/self/evolution.js +142 -4
  32. package/src/self/identity.js +1 -1
  33. package/src/self/policies.js +27 -1
  34. package/src/self/relationship.js +2 -2
  35. package/src/service/cortex.js +97 -15
  36. package/src/store/database.js +9 -1
  37. package/src/store/schema.sql +2 -1
  38. package/src/tools/definitions.js +19 -1
  39. package/src/vector/hnsw.js +5 -5
  40. package/src/web/search.js +97 -0
  41. package/test/integration/_helpers.js +128 -0
  42. package/test/integration/acceptance.test.js +803 -0
  43. package/test/integration/ann-load.test.js +61 -0
  44. package/test/integration/api-contract.test.js +1476 -0
  45. package/test/integration/backup-privacy.test.js +214 -0
  46. package/test/integration/consolidate.test.js +75 -0
  47. package/test/integration/edge-cases.test.js +1088 -0
  48. package/test/integration/exchange.test.js +326 -0
  49. package/test/integration/life-loop.test.js +188 -0
  50. package/test/integration/load.test.js +751 -0
  51. package/test/integration/markdown-sync.test.js +35 -0
  52. package/test/integration/policy-query-api.test.js +306 -0
  53. package/test/integration/resilience-writes.test.js +241 -0
  54. package/test/integration/tools-contract.test.js +1324 -0
  55. package/test/unit/ann-edge.test.js +102 -0
  56. package/test/unit/ann.test.js +77 -0
  57. package/test/unit/api-client.test.js +576 -0
  58. package/test/unit/api-validate.test.js +19 -0
  59. package/test/unit/api.test.js +555 -0
  60. package/test/unit/appraisal.test.js +48 -0
  61. package/test/unit/attachments.test.js +33 -0
  62. package/test/unit/autonomy.test.js +53 -0
  63. package/test/unit/batch.test.js +46 -0
  64. package/test/unit/bench.test.js +40 -0
  65. package/test/unit/benchmark-synthetic.test.js +52 -0
  66. package/test/unit/client-contract.test.js +29 -0
  67. package/test/unit/compression.test.js +76 -0
  68. package/test/unit/core.test.js +77 -0
  69. package/test/unit/develop.test.js +130 -0
  70. package/test/unit/development.test.js +68 -0
  71. package/test/unit/digest.test.js +26 -0
  72. package/test/unit/dsr.test.js +111 -0
  73. package/test/unit/edges-candidates.test.js +113 -0
  74. package/test/unit/emotion.test.js +61 -0
  75. package/test/unit/encode.test.js +98 -0
  76. package/test/unit/evolution.test.js +130 -0
  77. package/test/unit/external-ann-search.test.js +50 -0
  78. package/test/unit/external-ann.test.js +29 -0
  79. package/test/unit/facts-belief.test.js +32 -0
  80. package/test/unit/facts.test.js +107 -0
  81. package/test/unit/feature-overrides.test.js +42 -0
  82. package/test/unit/fts-migration.test.js +42 -0
  83. package/test/unit/graph.test.js +79 -0
  84. package/test/unit/growth-reflect.test.js +123 -0
  85. package/test/unit/guard-runtime.test.js +40 -0
  86. package/test/unit/guardian.test.js +91 -0
  87. package/test/unit/health-privacy.test.js +102 -0
  88. package/test/unit/hnsw.test.js +35 -0
  89. package/test/unit/host-runtime.test.js +142 -0
  90. package/test/unit/host.test.js +58 -0
  91. package/test/unit/identity.test.js +98 -0
  92. package/test/unit/induct-evaluate.test.js +41 -0
  93. package/test/unit/ingest-extracted.test.js +35 -0
  94. package/test/unit/initiative.test.js +90 -0
  95. package/test/unit/jobs.test.js +93 -0
  96. package/test/unit/json-snapshot.test.js +57 -0
  97. package/test/unit/life-consolidate.test.js +34 -0
  98. package/test/unit/life.test.js +149 -0
  99. package/test/unit/llm-facts-integration.test.js +27 -0
  100. package/test/unit/llm-facts.test.js +16 -0
  101. package/test/unit/llm.test.js +45 -0
  102. package/test/unit/locomo.test.js +45 -0
  103. package/test/unit/longmemeval.test.js +56 -0
  104. package/test/unit/markdown-import.test.js +44 -0
  105. package/test/unit/markdown.test.js +34 -0
  106. package/test/unit/memory-edit.test.js +112 -0
  107. package/test/unit/metrics.test.js +26 -0
  108. package/test/unit/migration.test.js +38 -0
  109. package/test/unit/model-config.test.js +52 -0
  110. package/test/unit/narrative.test.js +62 -0
  111. package/test/unit/playbook-consolidate.test.js +24 -0
  112. package/test/unit/privacy-scope.test.js +39 -0
  113. package/test/unit/profile.test.js +20 -0
  114. package/test/unit/prompt.test.js +42 -0
  115. package/test/unit/providers.test.js +42 -0
  116. package/test/unit/qa.test.js +100 -0
  117. package/test/unit/query.test.js +53 -0
  118. package/test/unit/retention.test.js +31 -0
  119. package/test/unit/retrieval-ranking.test.js +31 -0
  120. package/test/unit/retrieve.test.js +117 -0
  121. package/test/unit/rotation.test.js +25 -0
  122. package/test/unit/scanner.test.js +50 -0
  123. package/test/unit/scenario.test.js +78 -0
  124. package/test/unit/scheduler.test.js +136 -0
  125. package/test/unit/self-state.test.js +94 -0
  126. package/test/unit/service.test.js +72 -0
  127. package/test/unit/shiori-import.test.js +77 -0
  128. package/test/unit/skills.test.js +104 -0
  129. package/test/unit/store.test.js +111 -0
  130. package/test/unit/temporal-graph.test.js +44 -0
  131. package/test/unit/tiers.test.js +39 -0
  132. package/test/unit/tokenizer-fts.test.js +35 -0
  133. package/test/unit/tools.test.js +122 -0
  134. package/test/unit/upgrade-0412.test.js +104 -0
  135. package/test/unit/upgrade-0413.test.js +84 -0
  136. package/test/unit/upgrade-0414.test.js +101 -0
  137. package/test/unit/vector-ann.test.js +53 -0
  138. package/test/unit/vector-async.test.js +69 -0
  139. package/test/unit/vector.test.js +68 -0
  140. package/test/unit/working.test.js +80 -0
@@ -180,7 +180,40 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
180
180
  identityStore, selfStore, config,
181
181
  });
182
182
  const privacy = createPrivacyEngine({ db, traces, events, audit });
183
- const evolution = createEvolutionEngine({ policies, identityStore, skills: skillsRepo, health, growth, audit });
183
+
184
+ function retrievalQuality({ scopeId = config.scope, phase = 'after', baseline = null } = {}) {
185
+ const rows = db.prepare(`
186
+ SELECT id, title, content FROM traces
187
+ WHERE scope_id = ? AND state = 'active'
188
+ ORDER BY importance DESC, recorded_at DESC LIMIT 8
189
+ `).all(scopeId);
190
+ const probes = rows.map((row) => {
191
+ const title = String(row.title ?? '').trim();
192
+ const content = String(row.content ?? '').replace(/^\s*(用户|user)\s*[::]\s*/i, '').trim();
193
+ const query = title && !/^会话\s*\d+\s*的对话$/.test(title) ? title.slice(0, 100) : content.slice(0, 100);
194
+ return { id: row.id, query };
195
+ }).filter((probe) => probe.query.length >= 4).slice(0, 6);
196
+ if (probes.length < 5) return { ok: true, skipped: 'insufficient-samples', n: probes.length };
197
+ let hits = 0;
198
+ for (const probe of probes) {
199
+ try {
200
+ const result = retrieve.search(probe.query, { scopeId, limit: 5 });
201
+ if (result.items.some((item) => item.id === probe.id)) hits += 1;
202
+ } catch { /* one probe must not abort the guard */ }
203
+ }
204
+ const recall = hits / probes.length;
205
+ const after = { n: probes.length, hits, recall: Math.round(recall * 1000) / 1000 };
206
+ if (phase === 'before') return { ok: true, ...after };
207
+ if (baseline?.recall == null) return { ok: true, ...after, skipped: 'no-baseline' };
208
+ return {
209
+ ok: recall >= Math.max(0.4, baseline.recall - 0.25),
210
+ ...after,
211
+ baselineRecall: baseline.recall,
212
+ threshold: Math.round(Math.max(0.4, baseline.recall - 0.25) * 1000) / 1000,
213
+ };
214
+ }
215
+
216
+ const evolution = createEvolutionEngine({ policies, identityStore, skills: skillsRepo, health, growth, audit, guard: config.evolution ?? null, qualityGuard: retrievalQuality });
184
217
  const guardian = createGuardian({ db, config, events, traces, selfStore, identityStore, logger });
185
218
  const circuit = createCircuitBreaker({ threshold: config.circuitThreshold ?? 5, cooldownMs: config.circuitCooldownMs ?? 60_000 });
186
219
  const budget = createBudgetGuard({ maxCallsPerHour: config.maxCallsPerHour ?? 120, maxTokensPerHour: config.maxTokensPerHour ?? 120_000 });
@@ -192,6 +225,8 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
192
225
  const life = createLifeEngine({
193
226
  db, traces, reflect, development, working: workingStore, emotion, scopeId: config.scope,
194
227
  consolidation, features: config.features ?? {},
228
+ selfName: config.persona?.selfName ?? '助手',
229
+ userAddress: config.persona?.userAddress ?? '你',
195
230
  llm: llmAdapter ? (args) => llmAdapter.dream(args) : null,
196
231
  diaryLlm: llmAdapter ? (args) => llmAdapter.diary(args) : null,
197
232
  feelingLlm: llmAdapter ? (args) => llmAdapter.feeling(args) : null,
@@ -304,8 +339,9 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
304
339
  traceId: result.trace?.id ?? null,
305
340
  eventId: result.event?.id ?? null,
306
341
  recordedAt: result.trace?.recordedAt ?? null,
342
+ persona: config.persona,
307
343
  });
308
- if (config.features?.graphCandidateAutoFacts === true) {
344
+ if (config.features?.autoGraphCandidates === true || config.features?.graphCandidateAutoFacts === true) {
309
345
  const queued = [];
310
346
  for (const resolution of result.autoFacts.resolved ?? []) {
311
347
  const fact = resolution?.fact;
@@ -472,6 +508,26 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
472
508
  return retrieve.timeline({ ...options, scopeId: options.scopeId ?? config.scope });
473
509
  }
474
510
 
511
+ function recentTimeline({ scopeId = config.scope, limit = 20 } = {}) {
512
+ const rows = db.prepare(`
513
+ SELECT id, title, kind, content, importance, recorded_at
514
+ FROM traces WHERE scope_id = ? AND state = 'active'
515
+ ORDER BY recorded_at DESC LIMIT ?
516
+ `).all(scopeId, Math.max(1, Math.min(100, Number(limit) || 20)));
517
+ return {
518
+ items: rows.map((row) => ({
519
+ id: row.id,
520
+ title: row.title || String(row.content ?? '').slice(0, 50) || row.kind,
521
+ snippet: String(row.content ?? '').replace(/\s+/g, ' ').slice(0, 180),
522
+ recordedAt: row.recorded_at,
523
+ kind: row.kind,
524
+ layer: row.kind === 'reflection' ? 'L5' : 'L2',
525
+ importance: Number(row.importance ?? 0),
526
+ isAnchor: false,
527
+ })),
528
+ };
529
+ }
530
+
475
531
  function self(scopeId = config.scope) {
476
532
  const identity = identityStore.active(scopeId);
477
533
  const identityText = identity ? `${identity.content.narrative}\n${(identity.content.values ?? []).join('、')}\n${(identity.content.boundaries ?? []).join('、')}` : '';
@@ -737,15 +793,30 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
737
793
  return { cards: cards.length, volumes };
738
794
  }
739
795
 
740
- function rebuildSummonBook({ scopeId = config.scope } = {}) {
741
- const emotions = db.prepare('SELECT * FROM emotion_events WHERE scope_id = ? ORDER BY at DESC LIMIT 1000').all(scopeId);
796
+ const summonSourceAt = new Map();
797
+
798
+ function rebuildSummonBook({ scopeId = config.scope, incremental = false } = {}) {
799
+ const latest = {
800
+ emotion: db.prepare('SELECT MAX(at) AS at FROM emotion_events WHERE scope_id = ?').get(scopeId)?.at ?? null,
801
+ fact: db.prepare('SELECT MAX(recorded_at) AS at FROM facts WHERE scope_id = ?').get(scopeId)?.at ?? null,
802
+ trace: db.prepare('SELECT MAX(recorded_at) AS at FROM traces WHERE scope_id = ?').get(scopeId)?.at ?? null,
803
+ };
804
+ const since = summonSourceAt.get(scopeId) ?? null;
805
+ if (incremental && since) {
806
+ const unchanged = Object.entries(latest).every(([kind, at]) => !at || String(at) <= String(since[kind] ?? ''));
807
+ if (unchanged) return { skipped: true, emotions: 0, facts: 0, traces: 0, merged: null };
808
+ }
809
+ const emotionSince = incremental && since?.emotion ? since.emotion : null;
810
+ const factSince = incremental && since?.fact ? since.fact : null;
811
+ const traceSince = incremental && since?.trace ? since.trace : null;
812
+ const emotions = db.prepare(`SELECT * FROM emotion_events WHERE scope_id = ?${emotionSince ? ' AND at > ?' : ''} ORDER BY at DESC LIMIT 1000`).all(scopeId, ...(emotionSince ? [emotionSince] : []));
742
813
  for (const row of emotions) {
743
814
  const parsed = (() => { try { return JSON.parse(row.emotions_json); } catch { return []; } })();
744
815
  const labels = parsed.map((item) => item.name).filter(Boolean);
745
816
  summons.upsertCard({
746
817
  scopeId,
747
818
  side: 'left',
748
- title: `${labels.slice(0, 2).join(' / ') || '情感'} · ${row.target ?? '主人'}`,
819
+ title: `${labels.slice(0, 2).join(' / ') || '情感'} · ${row.target ?? '用户'}`,
749
820
  content: row.text,
750
821
  triggers: summonTriggers(row.text, labels),
751
822
  category: labels[0] ?? '情感',
@@ -761,9 +832,9 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
761
832
  FROM facts f
762
833
  LEFT JOIN entities s ON s.id = f.subject_id
763
834
  LEFT JOIN entities o ON o.id = f.object_id
764
- WHERE f.scope_id = ? AND f.status = 'active' AND f.confidence >= 0.65
835
+ WHERE f.scope_id = ? AND f.status = 'active' AND f.confidence >= 0.65${factSince ? ' AND f.recorded_at > ?' : ''}
765
836
  ORDER BY f.recorded_at DESC LIMIT 500
766
- `).all(scopeId);
837
+ `).all(scopeId, ...(factSince ? [factSince] : []));
767
838
  for (const fact of facts) {
768
839
  const title = `${fact.subject_name || fact.subject_id} ${fact.predicate} ${fact.object_literal || fact.object_name || fact.object_id || ''}`.trim();
769
840
  summons.upsertCard({
@@ -781,13 +852,13 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
781
852
  }
782
853
  const traces = db.prepare(`
783
854
  SELECT * FROM traces WHERE scope_id = ?
784
- AND (kind IN ('decision', 'reflection', 'identity') OR importance >= 0.6)
855
+ AND (kind IN ('decision', 'reflection', 'identity') OR importance >= 0.6)${traceSince ? ' AND recorded_at > ?' : ''}
785
856
  ORDER BY recorded_at DESC LIMIT 800
786
- `).all(scopeId);
857
+ `).all(scopeId, ...(traceSince ? [traceSince] : []));
787
858
  for (const row of traces) {
788
859
  const tags = (() => { try { return JSON.parse(row.tags_json); } catch { return []; } })();
789
860
  const content = String(row.content ?? '');
790
- const fallbackTitle = content.split(/\n/).map((line) => line.replace(/^\s*(用户|本鲸|assistant|user)[::]\s*/i, '').trim()).find(Boolean) ?? '';
861
+ const fallbackTitle = content.split(/\n/).map((line) => line.replace(/^\s*(用户|助手|assistant|user)[::]\s*/i, '').trim()).find(Boolean) ?? '';
791
862
  const title = /^会话\s*\d+\s*的对话/.test(String(row.title ?? ''))
792
863
  ? fallbackTitle.slice(0, 60)
793
864
  : (row.title || fallbackTitle.slice(0, 60) || '工作记忆');
@@ -805,8 +876,9 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
805
876
  });
806
877
  }
807
878
  const merged = mergeSummonVolumes({ scopeId });
808
- audit.record?.({ actor: 'self:summon', action: 'summon.rebuild', targetType: 'summon', targetId: scopeId, detail: { emotions: emotions.length, facts: facts.length, traces: traces.length, ...merged } });
809
- return { emotions: emotions.length, facts: facts.length, traces: traces.length, ...merged };
879
+ summonSourceAt.set(scopeId, latest);
880
+ audit.record?.({ actor: 'self:summon', action: 'summon.rebuild', targetType: 'summon', targetId: scopeId, detail: { incremental, emotions: emotions.length, facts: facts.length, traces: traces.length, ...merged } });
881
+ return { incremental, emotions: emotions.length, facts: facts.length, traces: traces.length, ...merged };
810
882
  }
811
883
 
812
884
  function summonBook({ date = null, scopeId = config.scope } = {}) {
@@ -1311,7 +1383,16 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1311
1383
  memoryDay,
1312
1384
  updateMemoryTrace,
1313
1385
  updateMemoryEmotion,
1314
- graphCandidates: ({ scopeId = config.scope, limit = 200 } = {}) => edges.listCandidates({ scopeId, limit }),
1386
+ graphCandidates: ({ scopeId = config.scope, limit = 200 } = {}) => {
1387
+ const rows = edges.listCandidates({ scopeId, limit });
1388
+ const labels = { at: '在', is: '是', will: '会', likes: '喜欢', dislikes: '不喜欢', related: '相关' };
1389
+ return rows.map((edge) => ({
1390
+ ...edge,
1391
+ fromName: entities.get(edge.fromId)?.name ?? edge.fromId,
1392
+ toName: entities.get(edge.toId)?.name ?? edge.toId,
1393
+ relLabel: labels[edge.rel] ?? edge.rel,
1394
+ }));
1395
+ },
1315
1396
  reviewGraphCandidate,
1316
1397
  graphCandidateAction: ({ action, id, scopeId = config.scope, fromId, toId, rel, weight, confidence, sourceEventId, sourceTraceId, evidence, metadata, review = null } = {}) => {
1317
1398
  if (!scopeWritable(scopeId)) throw new Error('scope-read-only');
@@ -1375,17 +1456,18 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1375
1456
  },
1376
1457
  flushLlmFacts,
1377
1458
  recallTiered: ({ query, limit = 20, permBudget = 700, hotBudget = 900, coldBudget = 400, scopeId = config.scope, includeArchived = false } = {}) => {
1378
- const result = search(query, { limit, budget: permBudget + hotBudget + coldBudget, scopeId, includeArchived, noBudget: true });
1459
+ const result = search(query, { limit, budget: permBudget + hotBudget + coldBudget, scopeId, includeArchived, gate: config.injectionGate === false ? 'none' : 'inject', noBudget: true });
1379
1460
  const selection = selectTiers(result.items, { budgets: { perm: permBudget, hot: hotBudget, cold: coldBudget } });
1380
1461
  return { query, result, selection, text: renderTiers(selection) };
1381
1462
  },
1382
1463
  recallTieredAsync: async ({ query, limit = 20, permBudget = 700, hotBudget = 900, coldBudget = 400, scopeId = config.scope, includeArchived = false } = {}) => {
1383
- const result = await searchAsync(query, { limit, budget: permBudget + hotBudget + coldBudget, scopeId, includeArchived, noBudget: true });
1464
+ const result = await searchAsync(query, { limit, budget: permBudget + hotBudget + coldBudget, scopeId, includeArchived, gate: config.injectionGate === false ? 'none' : 'inject', noBudget: true });
1384
1465
  const selection = selectTiers(result.items, { budgets: { perm: permBudget, hot: hotBudget, cold: coldBudget } });
1385
1466
  return { query, result, selection, text: renderTiers(selection) };
1386
1467
  },
1387
1468
  get,
1388
1469
  timeline,
1470
+ recentTimeline,
1389
1471
  step: develop.step,
1390
1472
  feedback: (input) => growth.applyFeedback({ ...input, scopeId: input.scopeId ?? config.scope }),
1391
1473
  forget: (input) => {
@@ -9,7 +9,7 @@ import { ftsText } from '../memory/tokenizer.js';
9
9
 
10
10
  const HERE = path.dirname(fileURLToPath(import.meta.url));
11
11
  const SCHEMA_FILE = path.join(HERE, 'schema.sql');
12
- export const SCHEMA_VERSION = 6;
12
+ export const SCHEMA_VERSION = 7;
13
13
  export const FTS_INDEX_VERSION = 2;
14
14
 
15
15
  function ensureTraceColumns(db) {
@@ -28,6 +28,13 @@ function ensureSummonColumns(db) {
28
28
  }
29
29
  }
30
30
 
31
+ function ensurePolicyColumns(db) {
32
+ const columns = db.prepare('PRAGMA table_info(policies)').all();
33
+ if (!columns.some((column) => column.name === 'canary_json')) {
34
+ db.exec('ALTER TABLE policies ADD COLUMN canary_json TEXT');
35
+ }
36
+ }
37
+
31
38
  function ensureFactsColumns(db) {
32
39
  const columns = db.prepare('PRAGMA table_info(facts)').all();
33
40
  if (!columns.some((column) => column.name === 'superseded_at')) {
@@ -86,6 +93,7 @@ export function migrate(db, { version = SCHEMA_VERSION } = {}) {
86
93
  ensureTraceColumns(db);
87
94
  ensureFactsColumns(db);
88
95
  ensureSummonColumns(db);
96
+ ensurePolicyColumns(db);
89
97
  const row = db.prepare('SELECT value FROM meta WHERE key = ?').get('schema_version');
90
98
  if (!row) {
91
99
  db.prepare('INSERT INTO meta(key, value, updated_at) VALUES (?, ?, ?)').run('schema_version', String(version), nowIso());
@@ -259,7 +259,8 @@ CREATE TABLE IF NOT EXISTS policies (
259
259
  metrics_json TEXT,
260
260
  status TEXT NOT NULL DEFAULT 'candidate',
261
261
  created_at TEXT NOT NULL,
262
- activated_at TEXT
262
+ activated_at TEXT,
263
+ canary_json TEXT
263
264
  );
264
265
 
265
266
  CREATE TABLE IF NOT EXISTS audit (
@@ -1,3 +1,12 @@
1
+ import path from 'node:path';
2
+
3
+ function guardPathAllowed(service, target) {
4
+ if (service?.config?.allowRestoreOutsideRoot === true) return true;
5
+ const root = path.resolve(String(service?.config?.dataRoot ?? process.cwd()));
6
+ const absolute = path.resolve(String(target ?? ''));
7
+ return absolute === root || absolute.startsWith(`${root}${path.sep}`);
8
+ }
9
+
1
10
  const TEXT_OUTPUT = Object.freeze({
2
11
  schema: {
3
12
  type: 'object',
@@ -364,6 +373,7 @@ export function createToolDefinitions(service) {
364
373
  isConcurrencySafe: () => false,
365
374
  async execute(args = {}) {
366
375
  if (args.action === 'backup') {
376
+ if (args.file && !guardPathAllowed(service, args.file)) return { text: '未执行:备份路径在 dataRoot 外。' };
367
377
  const result = service.guardian.backup(args.file);
368
378
  return { text: `备份完成:${result.path}(${result.bytes} B)` };
369
379
  }
@@ -372,12 +382,18 @@ export function createToolDefinitions(service) {
372
382
  return { text: result.ok ? `备份有效:${args.file}(${result.tables} 张表)` : `备份无效:${result.reason ?? result.missing?.join(',')}` };
373
383
  }
374
384
  if (args.action === 'restore') {
385
+ if (!args.file) return { text: '恢复失败:file-required' };
386
+ if (!args.target) return { text: '恢复失败:target-required' };
387
+ if (!guardPathAllowed(service, args.file) || !guardPathAllowed(service, args.target)) {
388
+ return { text: '未执行:恢复文件或目标在 dataRoot 外。' };
389
+ }
375
390
  const result = service.guardian.restore(args.file, args.target);
376
391
  return { text: result.restored ? `已恢复到离线库:${result.target}` : `恢复失败:${result.reason}${result.message ? `(${result.message})` : ''}` };
377
392
  }
378
393
  if (args.action === 'sync') {
379
394
  const dir = args.dir;
380
395
  if (!dir) return { text: '同步 Markdown 需要 dir。' };
396
+ if (!guardPathAllowed(service, dir)) return { text: '未执行:同步目录在 dataRoot 外。' };
381
397
  if (args.dryRun !== true && !service.scopeWritable(args.scope ?? service.settings().scope)) return { text: '未执行:该 scope 只读共享。' };
382
398
  const result = service.syncMarkdown(dir, { dryRun: args.dryRun === true, scopeId: args.scope });
383
399
  return { text: `Markdown 同步${result.dryRun ? '(dry-run)' : ''}:更新 ${result.updated},新建 ${result.created},文件 ${result.files}` };
@@ -387,7 +403,9 @@ export function createToolDefinitions(service) {
387
403
  return { text: `FTS 重建完成:${result.before} → ${result.after}(${result.reindexed} 条)` };
388
404
  }
389
405
  if (args.action === 'export') {
390
- const result = service.exportMarkdown(args.dir ?? 'cortex-mirror');
406
+ const dir = args.dir ?? path.join(service.config?.dataRoot ?? process.cwd(), 'cortex-mirror');
407
+ if (!guardPathAllowed(service, dir)) return { text: '未执行:导出目录在 dataRoot 外。' };
408
+ const result = service.exportMarkdown(dir);
391
409
  return { text: `Markdown 镜像已导出:${result.root}\n文件:${result.files.join('、')}\n记忆 ${result.traces} 条(跳过 secret ${result.skippedSecrets} 条)` };
392
410
  }
393
411
  const report = service.guardian.check();
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * Small dependency-free HNSW index for Cortex.
3
3
  *
4
- * This is a candidate replacement for the single-layer NSW in ann.js. It is
5
- * intentionally not wired into the production vector index until a benchmark
6
- * shows acceptable recall. The implementation uses simple sorted frontiers
7
- * (not a binary heap) because it is easier to audit; this is a benchmark
8
- * candidate, not a final large-corpus engine.
4
+ * This is the default ANN engine in `src/vector/index.js` (`annEngine: 'hnsw'`);
5
+ * the older single-layer NSW implementation remains selectable as `'nsw'`.
6
+ * The implementation uses simple sorted frontiers (not a binary heap) because
7
+ * it is easier to audit; run `bench/hnsw-bench.mjs` before changing parameters
8
+ * for a large corpus.
9
9
  */
10
10
  function mulberry32(seed) {
11
11
  let state = seed >>> 0;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Small, dependency-free web search adapters.
3
+ *
4
+ * Wikipedia and SearXNG need no API key. Search results are returned as
5
+ * citeable sources; the caller decides whether to pass them to the LLM.
6
+ */
7
+ const DEFAULT_TIMEOUT_MS = 8_000;
8
+ const MAX_RESULTS = 5;
9
+
10
+ function text(value, max = 500) {
11
+ return String(value ?? '').replace(/\s+/g, ' ').trim().slice(0, max);
12
+ }
13
+
14
+ function stripHtml(value) {
15
+ return text(String(value ?? '').replace(/<[^>]+>/g, ' '), 600);
16
+ }
17
+
18
+ function withTimeout(ms) {
19
+ const controller = new AbortController();
20
+ const timer = setTimeout(() => controller.abort(new Error('web search timed out')), ms);
21
+ return { signal: controller.signal, done: () => clearTimeout(timer) };
22
+ }
23
+
24
+ function sourcesFromWikipedia(payload, language) {
25
+ const rows = payload?.query?.search;
26
+ if (!Array.isArray(rows)) return [];
27
+ return rows.slice(0, MAX_RESULTS).map((row) => ({
28
+ title: text(row.title, 160),
29
+ url: `https://${language || 'zh'}.wikipedia.org/wiki/${encodeURIComponent(String(row.title ?? '').replace(/ /g, '_'))}`,
30
+ snippet: stripHtml(row.snippet),
31
+ provider: 'wikipedia',
32
+ })).filter((row) => row.title && row.url);
33
+ }
34
+
35
+ function sourcesFromSearxng(payload) {
36
+ const rows = payload?.results;
37
+ if (!Array.isArray(rows)) return [];
38
+ return rows.slice(0, MAX_RESULTS).map((row) => ({
39
+ title: text(row.title || row.url, 160),
40
+ url: text(row.url, 800),
41
+ snippet: text(row.content || row.snippet || '', 600),
42
+ provider: 'searxng',
43
+ })).filter((row) => row.url);
44
+ }
45
+
46
+ export function createWebSearch({
47
+ provider = 'wikipedia',
48
+ endpoint = 'http://127.0.0.1:8080',
49
+ language = 'zh',
50
+ maxResults = 3,
51
+ timeoutMs = DEFAULT_TIMEOUT_MS,
52
+ fetchImpl = fetch,
53
+ } = {}) {
54
+ const limit = Math.max(1, Math.min(MAX_RESULTS, Number(maxResults) || 3));
55
+
56
+ async function search({ query = '', maxResults: requested } = {}) {
57
+ const q = text(query, 500);
58
+ if (!q) return { sources: [], provider };
59
+ if (provider === 'none') throw new Error('联网未启用:请选择 Wikipedia 或 SearXNG');
60
+ if (typeof fetchImpl !== 'function') throw new Error('联网失败:当前运行环境没有 fetch');
61
+ const count = Math.max(1, Math.min(MAX_RESULTS, Number(requested) || limit));
62
+ const timeout = withTimeout(Math.max(1_000, Math.min(30_000, Number(timeoutMs) || DEFAULT_TIMEOUT_MS)));
63
+ try {
64
+ if (provider === 'wikipedia') {
65
+ const url = new URL(`https://${language || 'zh'}.wikipedia.org/w/api.php`);
66
+ url.searchParams.set('action', 'query');
67
+ url.searchParams.set('list', 'search');
68
+ url.searchParams.set('srsearch', q);
69
+ url.searchParams.set('srlimit', String(count));
70
+ url.searchParams.set('format', 'json');
71
+ url.searchParams.set('utf8', '1');
72
+ url.searchParams.set('origin', '*');
73
+ const response = await fetchImpl(url, { signal: timeout.signal, headers: { accept: 'application/json' } });
74
+ if (!response.ok) throw new Error(`Wikipedia HTTP ${response.status}`);
75
+ const payload = await response.json();
76
+ return { sources: sourcesFromWikipedia(payload, language), provider: 'wikipedia', query: q };
77
+ }
78
+ if (provider === 'searxng') {
79
+ if (!endpoint) throw new Error('SearXNG endpoint 为空');
80
+ const base = String(endpoint).replace(/\/+$/, '');
81
+ const url = new URL(`${base}/search`);
82
+ url.searchParams.set('q', q);
83
+ url.searchParams.set('format', 'json');
84
+ url.searchParams.set('language', language || 'zh');
85
+ const response = await fetchImpl(url, { signal: timeout.signal, headers: { accept: 'application/json' } });
86
+ if (!response.ok) throw new Error(`SearXNG HTTP ${response.status}`);
87
+ const payload = await response.json();
88
+ return { sources: sourcesFromSearxng(payload).slice(0, count), provider: 'searxng', query: q };
89
+ }
90
+ throw new Error(`未知联网 provider: ${provider}`);
91
+ } finally {
92
+ timeout.done();
93
+ }
94
+ }
95
+
96
+ return { search, provider, endpoint, language, maxResults: limit };
97
+ }
@@ -0,0 +1,128 @@
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
+ }