dsh-cortex-memory 0.4.147 → 0.4.160

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 (46) hide show
  1. package/CHANGELOG.md +2550 -2396
  2. package/README.md +55 -110
  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/docs/install-windows.md +2 -2
  10. package/docs/models.md +1 -1
  11. package/docs/quota-compaction-design.md +3 -3
  12. package/index.js +6 -4
  13. package/package.json +8 -8
  14. package/scripts/backfill-author.mjs +132 -0
  15. package/scripts/backfill-stability.mjs +142 -0
  16. package/src/adapters/shiori.js +1 -1
  17. package/src/core/config.js +47 -2
  18. package/src/engines/autonomy.js +1 -1
  19. package/src/engines/compression.js +8 -3
  20. package/src/engines/consolidate.js +7 -3
  21. package/src/engines/encode.js +70 -7
  22. package/src/engines/extract.js +1 -1
  23. package/src/engines/health.js +1 -1
  24. package/src/engines/life.js +2 -1
  25. package/src/engines/memory-audit.js +168 -0
  26. package/src/engines/narrative.js +4 -8
  27. package/src/engines/reflect.js +25 -1
  28. package/src/engines/retrieve.js +55 -5
  29. package/src/host/scheduler.js +5 -4
  30. package/src/memory/dsr.js +30 -1
  31. package/src/memory/tokenizer.js +8 -2
  32. package/src/prompt/assemble.js +66 -18
  33. package/src/self/alias.js +4 -5
  34. package/src/self/alignment.js +77 -0
  35. package/src/self/appraisal.js +32 -9
  36. package/src/self/evidence.js +102 -0
  37. package/src/self/identity.js +8 -4
  38. package/src/self/initiative.js +12 -0
  39. package/src/self/memory-policy.js +59 -0
  40. package/src/self/state.js +42 -7
  41. package/src/service/cortex.js +212 -12
  42. package/src/store/database.js +10 -0
  43. package/src/store/repositories/facts.js +1 -1
  44. package/src/store/repositories/traces.js +18 -4
  45. package/src/store/schema.sql +3 -0
  46. package/src/tools/definitions.js +348 -4
@@ -1,3 +1,4 @@
1
+ import path from 'node:path';
1
2
  import { openDatabase, migrate, transaction, closeDatabase } from '../store/database.js';
2
3
  import { createEventRepository } from '../store/repositories/events.js';
3
4
  import { createTraceRepository } from '../store/repositories/traces.js';
@@ -17,11 +18,15 @@ import { touchInterval } from '../memory/spacing.js';
17
18
  import { createAuditRepository } from '../store/repositories/audit.js';
18
19
  import { createSelfStore } from '../self/state.js';
19
20
  import { createAppraisalStore } from '../self/appraisals.js';
21
+ import { appraise as defaultAppraise } from '../self/appraisal.js';
20
22
  import { createInitiativeStore, selectIntentions, DEFAULT_INITIATIVE_POLICY } from '../self/initiative.js';
23
+ import { collectEvidence } from '../self/evidence.js';
24
+ import { createAlignmentStore } from '../self/alignment.js';
21
25
  import { createSummonRepository } from '../store/repositories/summon.js';
22
26
  import { createIdentityStore } from '../self/identity.js';
23
27
  import { createRelationshipStore } from '../self/relationship.js';
24
28
  import { createTargetResolver } from '../self/alias.js';
29
+ import { createMemoryPolicy } from '../self/memory-policy.js';
25
30
  import { createEncodeEngine, isInjectedNoise } from '../engines/encode.js';
26
31
  import { createRetrievalEngine } from '../engines/retrieve.js';
27
32
  import { createGrowthEngine } from '../engines/growth.js';
@@ -29,6 +34,7 @@ import { createReflectEngine } from '../engines/reflect.js';
29
34
  import { createSkillEngine } from '../engines/skills.js';
30
35
  import { createJobRunner } from '../engines/jobs.js';
31
36
  import { createHealthEngine } from '../engines/health.js';
37
+ import { auditMemory } from '../engines/memory-audit.js';
32
38
  import { createPrivacyEngine } from '../engines/privacy.js';
33
39
  import { createDevelopEngine } from '../engines/develop.js';
34
40
  import { createGraphEngine } from '../engines/graph.js';
@@ -72,6 +78,12 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
72
78
  const { db, config } = openDatabase(rawConfig);
73
79
  migrate(db);
74
80
 
81
+ // 2026-11-27:外部证据文件(subbrain/evidence 管线写入 driver 失败等)。
82
+ // 默认放在 dataRoot 下;可用 config.externalEvidenceFile 覆盖,设 null 关闭。
83
+ const externalEvidenceFile = config.externalEvidenceFile === null
84
+ ? null
85
+ : (config.externalEvidenceFile || (config.dataRoot ? path.join(config.dataRoot, 'external-evidence.jsonl') : null));
86
+
75
87
  const events = createEventRepository(db);
76
88
  const traces = createTraceRepository(db);
77
89
  const entities = createEntityRepository(db);
@@ -85,11 +97,16 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
85
97
  const audit = createAuditRepository(db);
86
98
  const summons = createSummonRepository(db);
87
99
  const selfStore = createSelfStore(db);
100
+ // 工程模式:运行时开关,默认取配置;重启回到配置值(临时锁定的语义)。
101
+ let designMode = config.selfDesign?.mode === true;
88
102
  const appraisalStore = createAppraisalStore(db);
89
103
  const initiativeStore = createInitiativeStore(db);
104
+ // 2026-11-26:意图—结果对齐。声称放 payload,实际+证据放 result_json,零 schema 变更。
105
+ const alignment = createAlignmentStore(initiativeStore);
90
106
  const identityStore = createIdentityStore(db);
91
107
  const targetResolver = createTargetResolver(config.persona ?? {});
92
108
  const relationshipStore = createRelationshipStore(db, { resolveTarget: targetResolver.resolveTarget });
109
+ let lastFamiliarityBumpAt = 0;
93
110
  const metrics = createMetrics();
94
111
  const workingStore = createWorkingStore(db);
95
112
  const goalStore = createGoalStore(db);
@@ -132,11 +149,12 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
132
149
  const encode = createEncodeEngine({ events, traces, entities, facts, edges, audit, vector, config });
133
150
  const graph = createGraphEngine({ entities, facts, edges, traces });
134
151
  const policies = createPolicyRepository(db);
152
+ const memoryPolicy = createMemoryPolicy({ policies, config });
135
153
  const policyConfig = (kind) => {
136
154
  try { return policies.active(kind)?.config ?? null; } catch { return null; }
137
155
  };
138
156
  const retrieve = createRetrievalEngine({ traces, facts, graph, vector, policy: policyConfig, config });
139
- const compression = createCompressionEngine({ traces, summaries, facts, entities, config });
157
+ const compression = createCompressionEngine({ traces, summaries, facts, entities, config, memoryPolicy });
140
158
  const extractor = createFactExtractor({ entities, facts });
141
159
  const digest = createDigestEngine({ traces, summaries, emotion, goals: goalStore, feedback, scopeId: config.scope });
142
160
  const retention = createRetentionEngine({ traces });
@@ -182,7 +200,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
182
200
  })
183
201
  : null;
184
202
  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 ?? '助手' });
203
+ const narrative = createNarrativeEngine({ traces, summaries });
186
204
  const consolidation = createConsolidationEngine({ db, traces, summaries, audit, llm: llmAdapter });
187
205
  const skills = createSkillEngine({ skills: skillsRepo, traces });
188
206
  const health = createHealthEngine({
@@ -280,12 +298,23 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
280
298
  queue: jobs,
281
299
  logger,
282
300
  handlers: {
283
- reflect: (payload) => reflect.reflect({
284
- scopeId: payload.scopeId ?? config.scope,
285
- windowDays: payload.windowDays ?? 1,
286
- maxSources: payload.maxSources ?? 8,
287
- force: payload.force === true,
288
- }),
301
+ reflect: (payload) => {
302
+ const now = Date.now();
303
+ const windowDays = payload.windowDays ?? 1;
304
+ return reflect.reflect({
305
+ scopeId: payload.scopeId ?? config.scope,
306
+ windowDays,
307
+ maxSources: payload.maxSources ?? 8,
308
+ force: payload.force === true,
309
+ trigger: 'manual',
310
+ evidence: collectEvidence(db, {
311
+ scopeId: payload.scopeId ?? config.scope,
312
+ sinceIso: new Date(now - Math.max(0.1, windowDays) * 86_400_000).toISOString(),
313
+ untilIso: new Date(now + 60_000).toISOString(),
314
+ externalFile: externalEvidenceFile,
315
+ }),
316
+ });
317
+ },
289
318
  },
290
319
  });
291
320
 
@@ -442,6 +471,72 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
442
471
  if (!result.skipped && config.features?.llmFacts === true && llmAdapter?.available?.() && !Array.isArray(input.facts)) {
443
472
  scheduleLlmFacts(result, input);
444
473
  }
474
+ // Shared time is relationship too: a captured turn (not every recall, not
475
+ // every read) nudges familiarity. Throttled to once per two hours so a busy
476
+ // afternoon cannot inflate it, and it never touches trust/care.
477
+ if (!result.skipped && input.source === 'host:turn') {
478
+ const at = Date.now();
479
+ if (at - lastFamiliarityBumpAt > 2 * 3_600_000) {
480
+ lastFamiliarityBumpAt = at;
481
+ try {
482
+ relationshipStore.applyDelta(scopeId, targetResolver.canonical, { familiarityDelta: 0.002 }, { event: 'interaction:turn', at: new Date(at).toISOString() });
483
+ } catch {
484
+ /* the relationship nudge must never block capture */
485
+ }
486
+ }
487
+ }
488
+ // ── 2026-11-23 助手接线:每轮捕获后跑一次 appraisal,推动驱力/情绪 ──
489
+ // 原来 host 捕获只调 write()(存 trace),从不调 develop.step(),所以
490
+ // self_state 从没被真实对话推动过——appraisals 表空、驱力冻结在「某次手动调用」的残留值。
491
+ // 这里在 trace 写完之后补一次 appraisal,不重编码(不重复写 trace)。
492
+ if (!result.skipped) {
493
+ try {
494
+ const at = input.now ?? Date.now();
495
+ // 2026-11-23 助手修:之前 recentTexts 传的是空数组,estimateNovelty 里
496
+ // 「空数组 → 直接返回 0.8」,导致每轮 novelty 恒为 0.8、curiosity 每轮
497
+ // +0.14,三句话就封顶。这里从 traces 取最近 20 条真实文本作对照(排除本轮自己),
498
+ // 让 novelty 有真实基线:说过的话再说不算新,新话题才算新。
499
+ let recentTexts = [];
500
+ try {
501
+ const recent = traces.list?.({ scopeId, limit: 21 }) ?? [];
502
+ recentTexts = recent
503
+ .filter((t) => t && t.id !== result.trace?.id)
504
+ .map((t) => String(t.text ?? ''))
505
+ .filter(Boolean)
506
+ .slice(-20);
507
+ } catch {
508
+ recentTexts = [];
509
+ }
510
+ const appraised = defaultAppraise(String(input.text ?? ''), {
511
+ actor: input.actor ?? 'user',
512
+ goals: [],
513
+ identity: identityStore?.active?.(scopeId)?.content?.narrative ?? '',
514
+ recentTexts,
515
+ relationship: relationshipStore?.ensure?.(scopeId, targetResolver.canonical) ?? null,
516
+ selfState: selfStore.get(scopeId),
517
+ });
518
+ // 2026-11-23 助手修:原来只传 { at },elapsedHours 默认 0,driftDrives() 等于没跑——
519
+ // 驱力只涨不落,一满就永远满。这里按「上次更新到现在过了多久」传真实小时数,
520
+ // 让每次评估前先按半衰期往回漂移一点,再加新 delta。
521
+ const before = selfStore.get(scopeId);
522
+ const elapsedHours = before?.updatedAt
523
+ ? Math.max(0, (at - Date.parse(before.updatedAt)) / 3_600_000)
524
+ : 0;
525
+ selfStore.applyAppraisal(scopeId, appraised, {
526
+ at,
527
+ elapsedHours,
528
+ designMode,
529
+ floors: { coherence: config.selfDesign?.floorCoherence ?? 0.3, safety: config.selfDesign?.floorSafety ?? 0.2 },
530
+ });
531
+ appraisalStore?.record?.(scopeId, appraised, {
532
+ eventId: result.event?.id ?? null,
533
+ traceId: result.trace?.id ?? null,
534
+ at: new Date(at).toISOString(),
535
+ });
536
+ } catch {
537
+ /* appraisal 失败不能影响捕获 */
538
+ }
539
+ }
445
540
  return result;
446
541
  }
447
542
 
@@ -757,6 +852,37 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
757
852
  return updated;
758
853
  }
759
854
 
855
+ // 2026-11-27 副脑配套:只改元数据(tags / importance),不碰 title/content/summary。
856
+ // 不走 memoryEditEnabled 锁——那把锁是防内容篡改的;元数据打标可回滚、有审计,
857
+ // 而且副脑只会「建议」,真正写回由主脑调用。
858
+ function retagMemory({ id, tags, importance } = {}) {
859
+ const current = traces.get(id);
860
+ if (!current) throw new Error(`trace not found: ${id}`);
861
+ const patch = {};
862
+ if (Array.isArray(tags)) {
863
+ patch.tags = tags.map(String).map((t) => t.trim()).filter(Boolean).slice(0, 20);
864
+ }
865
+ if (importance != null) {
866
+ const value = Number(importance);
867
+ if (!Number.isFinite(value) || value < 0 || value > 1) throw new Error('importance must be a number in [0,1]');
868
+ patch.importance = value;
869
+ }
870
+ if (Object.keys(patch).length === 0) return current;
871
+ if (!scopeWritable(current.scopeId)) throw new Error('scope-read-only');
872
+ const updated = traces.update(id, patch);
873
+ audit.record?.({
874
+ actor: 'self',
875
+ action: 'memory.trace.retag',
876
+ targetType: 'trace',
877
+ targetId: id,
878
+ detail: {
879
+ changed: Object.keys(patch),
880
+ previous: { tags: current.tags, importance: current.importance },
881
+ },
882
+ });
883
+ return updated;
884
+ }
885
+
760
886
  function updateMemoryEmotion({ id, text, target } = {}) {
761
887
  if (!memoryEditEnabled) throw new Error('memory edit is locked');
762
888
  const current = db.prepare('SELECT * FROM emotion_events WHERE id = ? AND scope_id = ?').get(id, config.scope);
@@ -1514,7 +1640,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1514
1640
  // an episode, and once a segment has enough material it is written.
1515
1641
  const minMaterial = Number.isFinite(Number(config.reflectMinMaterial)) ? Number(config.reflectMinMaterial) : 50;
1516
1642
  if (count < minMaterial) return { skipped: 'few-traces', count, minMaterial, since: segmentSince };
1517
- const result = reflect.reflect({ scopeId, now, windowDays: 1, force: true, since: segmentSince, segment: true });
1643
+ const result = reflect.reflect({ scopeId, now, windowDays: 1, force: true, since: segmentSince, segment: true, trigger: 'auto' });
1518
1644
  return {
1519
1645
  created: !result.skipped,
1520
1646
  coverage: result.coverage ?? null,
@@ -1581,6 +1707,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1581
1707
  repos: { events, traces, entities, facts, edges, feedback, summaries, jobs, skills: skillsRepo, audit, playbook: playbookRepo },
1582
1708
  stores: { selfStore, appraisalStore, initiativeStore, identityStore, relationshipStore },
1583
1709
  engines: { encode, graph, retrieve, growth, reflect, narrative, skills, health, privacy, develop, development, vector, compression, extractor, runner },
1710
+ memoryPolicy,
1584
1711
  development,
1585
1712
  narrative,
1586
1713
  vector,
@@ -1751,13 +1878,37 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1751
1878
  return { candidates: created, count: created.length, at: new Date(now).toISOString() };
1752
1879
  },
1753
1880
  render: ({ scopeId = config.scope, budget = 260, at = new Date().toISOString() } = {}) => {
1754
- const rules = playbookRepo.active(scopeId, { at, limit: 80 });
1881
+ // 2026-11-29:原来 limit 80 在 pin 之前执行,规则 >80 条时 pin 会静默失效;提到 200。
1882
+ const rules = playbookRepo.active(scopeId, { at, limit: 200 });
1755
1883
  if (!rules.length) return { text: '', count: 0, omitted: 0, budget };
1884
+ // 2026-11-29:护栏白名单优先。投票只表达「有用」,表达不了「重要」;
1885
+ // 实测投完第一轮后,「中文/JSON 别用 PowerShell」(1 票,11-27)靠 created_at
1886
+ // 把「用户划的线」(1 票,11-25)顶掉了——红线从窗口里消失。
1887
+ // 白名单里的规则永远排最前,其余仍按 helpful-harmful → created_at。
1888
+ const pinned = new Set(config.playbookPinned ?? []);
1889
+ rules.sort((a, b) => {
1890
+ const pa = pinned.has(a.id) ? 1 : 0;
1891
+ const pb = pinned.has(b.id) ? 1 : 0;
1892
+ if (pa !== pb) return pb - pa;
1893
+ const va = (a.helpful ?? 0) - (a.harmful ?? 0);
1894
+ const vb = (b.helpful ?? 0) - (b.harmful ?? 0);
1895
+ if (va !== vb) return vb - va;
1896
+ return String(b.createdAt ?? '').localeCompare(String(a.createdAt ?? ''));
1897
+ });
1756
1898
  const lines = [];
1757
1899
  let used = 0;
1758
1900
  let omitted = 0;
1759
1901
  for (const rule of rules) {
1760
- const line = `- [${rule.id}] ${rule.title}:${rule.body}(helpful=${rule.helpful} harmful=${rule.harmful}${rule.validTo ? ` · 到期 ${rule.validTo}` : ''})`;
1902
+ // 2026-11-29:白名单护栏全文;其余超 90 字截断 + 给全文指针。
1903
+ // 预算 260/320 里若每条都放 130-280 字的全文,只放得下 1-2 条,投票等于没得选。
1904
+ const isPinned = pinned.has(rule.id);
1905
+ const body =
1906
+ // 2026-11-29 破妄工程面:截断不能丢「约束句」——准则的禁止/祈使常在尾巴上。
1907
+ // 改成「头 + 尾」:头给背景,尾保住那条不许/禁止/别。
1908
+ isPinned || String(rule.body ?? '').length <= 80
1909
+ ? rule.body
1910
+ : `${String(rule.body).slice(0, 52)}…${String(rule.body).slice(-22)}(全文:cortex_playbook get ${rule.id})`;
1911
+ const line = `- [${rule.id}] ${rule.title}:${body}(helpful=${rule.helpful} harmful=${rule.harmful}${rule.validTo ? ` · 到期 ${rule.validTo}` : ''})`;
1761
1912
  const cost = estimateTokens(line);
1762
1913
  if (used + cost > budget) { omitted += 1; continue; }
1763
1914
  lines.push(line); used += cost;
@@ -1821,6 +1972,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1821
1972
  memoryDays,
1822
1973
  memoryDay,
1823
1974
  updateMemoryTrace,
1975
+ retagMemory,
1824
1976
  updateMemoryEmotion,
1825
1977
  graphCandidates: ({ scopeId = config.scope, limit = 200 } = {}) => {
1826
1978
  const rows = edges.listCandidates({ scopeId, limit });
@@ -1915,7 +2067,30 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1915
2067
  return privacy.forget(input);
1916
2068
  },
1917
2069
  privacy,
1918
- reflect: (options = {}) => reflect.reflect({ ...options, scopeId: options.scopeId ?? config.scope }),
2070
+ reflect: (options = {}) => {
2071
+ const now = options.now ?? Date.now();
2072
+ const windowDays = options.windowDays ?? 1;
2073
+ return reflect.reflect({
2074
+ ...options,
2075
+ scopeId: options.scopeId ?? config.scope,
2076
+ trigger: options.trigger ?? 'manual',
2077
+ evidence: options.evidence ?? collectEvidence(db, {
2078
+ scopeId: options.scopeId ?? config.scope,
2079
+ sinceIso: options.since ?? new Date(now - Math.max(0.1, windowDays) * 86_400_000).toISOString(),
2080
+ untilIso: options.until ?? new Date(now + 60_000).toISOString(),
2081
+ externalFile: externalEvidenceFile,
2082
+ }),
2083
+ });
2084
+ },
2085
+ // 意图—结果对齐:claim 记「声称会做什么」,observe 记「实际发生什么」。
2086
+ alignment: {
2087
+ claim: (options = {}) => alignment.claim({ ...options, scopeId: options.scopeId ?? config.scope }),
2088
+ observe: (options = {}) => alignment.observe(options),
2089
+ open: (options = {}) => alignment.open({ ...options, scopeId: options.scopeId ?? config.scope }),
2090
+ recent: (options = {}) => alignment.recent({ ...options, scopeId: options.scopeId ?? config.scope }),
2091
+ deviations: (options = {}) => alignment.deviations({ ...options, scopeId: options.scopeId ?? config.scope }),
2092
+ },
2093
+ evidence: (options = {}) => collectEvidence(db, { ...options, scopeId: options.scopeId ?? config.scope, externalFile: options.externalFile ?? externalEvidenceFile }),
1919
2094
  reflectBackfill: (options = {}) => reflect.backfillEpisodes({ ...options, scopeId: options.scopeId ?? config.scope }),
1920
2095
  evaluateDevelopment: (options = {}) => development.evaluate({ ...options, scopeId: options.scopeId ?? config.scope }),
1921
2096
  rebuildVector: (options = {}) => vector?.rebuild({ ...options, scopeId: options.scopeId ?? config.scope }) ?? { rebuilt: 0 },
@@ -1934,7 +2109,32 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1934
2109
  importMarkdown: (root, options = {}) => importMarkdown({ write }, root, { ...options, scopeId: options.scopeId ?? config.scope }),
1935
2110
  syncMarkdown: (root, options = {}) => syncMarkdown({ repos: { traces, audit }, write }, root, { ...options, scopeId: options.scopeId ?? config.scope }),
1936
2111
  health: (options = {}) => health.audit({ ...options, scopeId: options.scopeId ?? config.scope }),
2112
+ // 2026-11-26 助手自建:只读审计。过期/矛盾/争议/僵尸/归档候选/完整性,只报不改。
2113
+ auditMemory: (options = {}) => auditMemory(db, {
2114
+ scopeId: options.scopeId ?? options.scope ?? config.scope,
2115
+ now: options.now,
2116
+ limit: options.limit,
2117
+ zombieDays: options.zombieDays,
2118
+ maxImportance: options.maxImportance,
2119
+ archiveRetrievability: config.dsr?.archiveRetrievability ?? 0.35,
2120
+ decay: config.dsr?.decay ?? -0.5,
2121
+ }),
1937
2122
  self,
2123
+ // 2026-11-27:工程模式开关。临时生效,重启回配置默认。
2124
+ design: {
2125
+ status: () => ({
2126
+ mode: designMode,
2127
+ floors: {
2128
+ coherence: config.selfDesign?.floorCoherence ?? 0.3,
2129
+ safety: config.selfDesign?.floorSafety ?? 0.2,
2130
+ },
2131
+ note: designMode ? '工程模式开着:coherence/safety 只升不降、energy 不扣。' : '工程模式关着:按正常情绪逻辑漂移。',
2132
+ }),
2133
+ set: (on) => {
2134
+ designMode = on === true;
2135
+ return { mode: designMode };
2136
+ },
2137
+ },
1938
2138
  working: workingStore,
1939
2139
  goals: goalStore,
1940
2140
  emotion,
@@ -17,6 +17,16 @@ function ensureTraceColumns(db) {
17
17
  if (!columns.some((column) => column.name === 'metadata_json')) {
18
18
  db.exec("ALTER TABLE traces ADD COLUMN metadata_json TEXT NOT NULL DEFAULT '{}'");
19
19
  }
20
+ // 2026-11-26 助手自建:作者归属三列。只加不参与打分,老行默认 captured。
21
+ if (!columns.some((column) => column.name === 'author_kind')) {
22
+ db.exec("ALTER TABLE traces ADD COLUMN author_kind TEXT NOT NULL DEFAULT 'captured'");
23
+ }
24
+ if (!columns.some((column) => column.name === 'author_id')) {
25
+ db.exec('ALTER TABLE traces ADD COLUMN author_id TEXT');
26
+ }
27
+ if (!columns.some((column) => column.name === 'author_confidence')) {
28
+ db.exec('ALTER TABLE traces ADD COLUMN author_confidence REAL');
29
+ }
20
30
  }
21
31
 
22
32
  function ensureSummonColumns(db) {
@@ -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));
@@ -8,6 +8,7 @@ import { FTS_INDEX_VERSION } from '../database.js';
8
8
  const COLUMNS = [
9
9
  'title', 'content', 'summary', 'keywords_json', 'tags_json', 'metadata_json', 'event_id',
10
10
  'session_id', 'turn_id', 'actor', 'source', 'valid_at', 'recorded_at',
11
+ 'author_kind', 'author_id', 'author_confidence',
11
12
  'last_access_at', 'access_count', 'importance', 'confidence', 'salience',
12
13
  'valence', 'arousal', 'sensitivity', 'state', 'compression', 'stability',
13
14
  'difficulty', 'retrievability', 'review_count', 'lapse_count',
@@ -27,6 +28,9 @@ const FIELD_MAP = Object.freeze({
27
28
  turnId: 'turn_id',
28
29
  actor: 'actor',
29
30
  source: 'source',
31
+ authorKind: 'author_kind',
32
+ authorId: 'author_id',
33
+ authorConfidence: 'author_confidence',
30
34
  validAt: 'valid_at',
31
35
  recordedAt: 'recorded_at',
32
36
  lastAccessAt: 'last_access_at',
@@ -65,6 +69,9 @@ function rowToTrace(row) {
65
69
  turnId: row.turn_id,
66
70
  actor: row.actor,
67
71
  source: row.source,
72
+ authorKind: row.author_kind ?? 'captured',
73
+ authorId: row.author_id ?? null,
74
+ authorConfidence: row.author_confidence == null ? null : Number(row.author_confidence),
68
75
  validAt: row.valid_at,
69
76
  recordedAt: row.recorded_at,
70
77
  lastAccessAt: row.last_access_at,
@@ -121,6 +128,9 @@ export function createTraceRepository(db) {
121
128
  turnId: input.turnId ?? null,
122
129
  actor: input.actor ?? 'user',
123
130
  source: input.source ?? null,
131
+ authorKind: input.authorKind ?? 'captured',
132
+ authorId: input.authorId ?? null,
133
+ authorConfidence: input.authorConfidence == null ? null : Number(input.authorConfidence),
124
134
  validAt: input.validAt ?? input.recordedAt ?? now,
125
135
  recordedAt: input.recordedAt ?? now,
126
136
  lastAccessAt: input.lastAccessAt ?? null,
@@ -146,16 +156,20 @@ export function createTraceRepository(db) {
146
156
  db.prepare(`
147
157
  INSERT INTO traces(
148
158
  id, scope_id, kind, title, content, summary, keywords_json, tags_json,
149
- metadata_json, event_id, session_id, turn_id, actor, source, valid_at, recorded_at,
159
+ metadata_json, event_id, session_id, turn_id, actor, source,
160
+ author_kind, author_id, author_confidence,
161
+ valid_at, recorded_at,
150
162
  last_access_at, access_count, importance, confidence, salience, valence,
151
163
  arousal, sensitivity, state, compression, stability, difficulty,
152
164
  retrievability, review_count, lapse_count, last_review_at, hash,
153
165
  created_at, updated_at
154
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
166
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
155
167
  `).run(
156
168
  trace.id, trace.scopeId, trace.kind, trace.title, trace.content, trace.summary,
157
169
  stableStringify(trace.keywords), stableStringify(trace.tags), stableStringify(trace.metadata), trace.eventId,
158
- trace.sessionId, trace.turnId, trace.actor, trace.source, trace.validAt,
170
+ trace.sessionId, trace.turnId, trace.actor, trace.source,
171
+ trace.authorKind, trace.authorId, trace.authorConfidence,
172
+ trace.validAt,
159
173
  trace.recordedAt, trace.lastAccessAt, trace.accessCount, trace.importance,
160
174
  trace.confidence, trace.salience, trace.valence, trace.arousal,
161
175
  trace.sensitivity, trace.state, trace.compression, trace.stability,
@@ -269,7 +283,7 @@ export function createTraceRepository(db) {
269
283
  // Without a scope this is the whole index. With one it must join through
270
284
  // traces: health used to compare the *global* trace count against the
271
285
  // *whole* FTS table and reported drift whenever another scope existed
272
- // (a real store had an `agency` scope, so it warned by exactly those
286
+ // (the production store has an `agency` scope, so it warned by exactly those
273
287
  // 12 rows forever).
274
288
  if (scopeId) {
275
289
  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);
@@ -46,6 +46,9 @@ CREATE TABLE IF NOT EXISTS traces (
46
46
  turn_id TEXT,
47
47
  actor TEXT,
48
48
  source TEXT,
49
+ author_kind TEXT NOT NULL DEFAULT 'captured',
50
+ author_id TEXT,
51
+ author_confidence REAL,
49
52
  valid_at TEXT,
50
53
  recorded_at TEXT NOT NULL,
51
54
  last_access_at TEXT,