dsh-cortex-memory 0.4.21 → 0.4.146

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/CHANGELOG.md +2223 -7
  2. package/README.md +20 -9
  3. package/bench/migration-bench.mjs +1 -1
  4. package/bench/semantic-cn.js +7 -7
  5. package/bench/synthetic.js +2 -2
  6. package/bin/copy-db.mjs +47 -0
  7. package/bin/cortex.mjs +9 -4
  8. package/bin/repair.mjs +328 -0
  9. package/bin/verify.mjs +202 -0
  10. package/cordis.patch.yml +1 -1
  11. package/docs/install-windows.md +2 -2
  12. package/docs/models.md +1 -1
  13. package/docs/quota-compaction-design.md +175 -0
  14. package/index.js +27 -3
  15. package/package.json +3 -3
  16. package/src/adapters/shiori.js +1 -1
  17. package/src/api/routes.js +1 -1
  18. package/src/core/feature-overrides.js +2 -2
  19. package/src/engines/compression.js +172 -3
  20. package/src/engines/consolidate.js +397 -26
  21. package/src/engines/encode.js +16 -3
  22. package/src/engines/extract.js +72 -8
  23. package/src/engines/fact-guard.js +51 -0
  24. package/src/engines/health.js +263 -3
  25. package/src/engines/inhibition.js +39 -0
  26. package/src/engines/life.js +12 -1
  27. package/src/engines/llm-facts.js +12 -9
  28. package/src/engines/narrative.js +150 -13
  29. package/src/engines/reflect.js +172 -14
  30. package/src/engines/retrieve.js +44 -5
  31. package/src/engines/summary-coverage.js +62 -0
  32. package/src/engines/summary-dedupe.js +77 -0
  33. package/src/engines/summon-rank.js +132 -0
  34. package/src/host/runtime.js +64 -4
  35. package/src/host/scheduler.js +224 -3
  36. package/src/llm/adapter.js +29 -8
  37. package/src/memory/query.js +1 -1
  38. package/src/memory/spacing.js +15 -0
  39. package/src/memory/tokenizer.js +1 -1
  40. package/src/prompt/tiers.js +88 -12
  41. package/src/self/alias.js +25 -0
  42. package/src/self/emotion.js +3 -1
  43. package/src/self/relationship.js +44 -13
  44. package/src/self/state.js +20 -2
  45. package/src/self/working.js +34 -3
  46. package/src/service/cortex.js +493 -53
  47. package/src/store/repositories/facts.js +34 -1
  48. package/src/store/repositories/summaries.js +8 -1
  49. package/src/store/repositories/traces.js +22 -2
  50. package/src/tools/definitions.js +118 -4
  51. package/src/vector/index.js +96 -7
  52. package/test/integration/acceptance.test.js +47 -47
  53. package/test/integration/api-contract.test.js +17 -17
  54. package/test/integration/backup-privacy.test.js +10 -10
  55. package/test/integration/consolidate.test.js +6 -2
  56. package/test/integration/edge-cases.test.js +16 -15
  57. package/test/integration/exchange.test.js +26 -26
  58. package/test/integration/life-loop.test.js +7 -6
  59. package/test/integration/load.test.js +4 -4
  60. package/test/integration/policy-query-api.test.js +4 -4
  61. package/test/integration/resilience-writes.test.js +7 -7
  62. package/test/integration/tools-contract.test.js +57 -57
  63. package/test/unit/alias.test.js +87 -0
  64. package/test/unit/api-client.test.js +3 -3
  65. package/test/unit/api-validate.test.js +3 -3
  66. package/test/unit/api.test.js +3 -3
  67. package/test/unit/auto-reflect.test.js +141 -0
  68. package/test/unit/capture-filter.test.js +296 -0
  69. package/test/unit/cli-default-root.test.js +21 -0
  70. package/test/unit/compaction-preview.test.js +91 -0
  71. package/test/unit/compression.test.js +4 -4
  72. package/test/unit/consolidate-dedupe.test.js +174 -0
  73. package/test/unit/consolidate-errors.test.js +63 -0
  74. package/test/unit/consolidate-gate.test.js +26 -0
  75. package/test/unit/consolidate-preview.test.js +168 -0
  76. package/test/unit/consolidate-protection.test.js +156 -0
  77. package/test/unit/consolidate-reason.test.js +206 -0
  78. package/test/unit/consolidate-retry.test.js +91 -0
  79. package/test/unit/consolidate-selection.test.js +103 -0
  80. package/test/unit/core.test.js +11 -11
  81. package/test/unit/coverage-rewrite.test.js +38 -0
  82. package/test/unit/dedupe-episodes.test.js +34 -0
  83. package/test/unit/dedupe-threshold.test.js +14 -0
  84. package/test/unit/develop.test.js +4 -4
  85. package/test/unit/edges-candidates.test.js +2 -2
  86. package/test/unit/emotion.test.js +2 -1
  87. package/test/unit/encode.test.js +6 -6
  88. package/test/unit/evolution.test.js +5 -5
  89. package/test/unit/extract-question.test.js +41 -0
  90. package/test/unit/fact-guard.test.js +51 -0
  91. package/test/unit/fact-noise-llm.test.js +44 -0
  92. package/test/unit/facts-belief.test.js +4 -4
  93. package/test/unit/facts-compat.test.js +62 -0
  94. package/test/unit/facts.test.js +5 -5
  95. package/test/unit/fts-migration.test.js +6 -6
  96. package/test/unit/growth-reflect.test.js +4 -3
  97. package/test/unit/guardian.test.js +1 -1
  98. package/test/unit/health-consolidation.test.js +52 -0
  99. package/test/unit/health-fts-scope.test.js +33 -0
  100. package/test/unit/health-privacy.test.js +6 -6
  101. package/test/unit/health-summaries.test.js +24 -0
  102. package/test/unit/health-text-maintain.test.js +33 -0
  103. package/test/unit/health-today.test.js +45 -0
  104. package/test/unit/host-runtime.test.js +8 -8
  105. package/test/unit/host.test.js +1 -1
  106. package/test/unit/induct-evaluate.test.js +3 -3
  107. package/test/unit/ingest-extracted.test.js +3 -3
  108. package/test/unit/inhibition.test.js +90 -0
  109. package/test/unit/jobs.test.js +4 -4
  110. package/test/unit/json-snapshot.test.js +1 -1
  111. package/test/unit/label-entities-skip.test.js +18 -0
  112. package/test/unit/llm-facts-integration.test.js +2 -2
  113. package/test/unit/llm-facts.test.js +3 -3
  114. package/test/unit/llm.test.js +5 -5
  115. package/test/unit/locomo.test.js +2 -2
  116. package/test/unit/longmemeval.test.js +2 -2
  117. package/test/unit/maintain-dispute.test.js +62 -0
  118. package/test/unit/maintain-duration.test.js +194 -0
  119. package/test/unit/markdown-import.test.js +5 -5
  120. package/test/unit/markdown.test.js +2 -2
  121. package/test/unit/memory-edit.test.js +5 -5
  122. package/test/unit/migration.test.js +1 -1
  123. package/test/unit/mood-saturation.test.js +33 -0
  124. package/test/unit/narrative-weave.test.js +271 -0
  125. package/test/unit/privacy-scope.test.js +1 -1
  126. package/test/unit/prompt.test.js +1 -1
  127. package/test/unit/providers.test.js +2 -2
  128. package/test/unit/qa.test.js +9 -9
  129. package/test/unit/query.test.js +10 -10
  130. package/test/unit/reflect-backfill.test.js +158 -0
  131. package/test/unit/reflect-coverage.test.js +35 -0
  132. package/test/unit/reflect-overview.test.js +22 -0
  133. package/test/unit/reflect-phrasing.test.js +75 -0
  134. package/test/unit/reflect-sampling.test.js +80 -0
  135. package/test/unit/reflect-source-budget.test.js +24 -0
  136. package/test/unit/relationship-dynamics.test.js +29 -0
  137. package/test/unit/retrieve.test.js +9 -9
  138. package/test/unit/revive-on-read.test.js +84 -0
  139. package/test/unit/scanner.test.js +2 -2
  140. package/test/unit/scenario.test.js +2 -2
  141. package/test/unit/scheduler-autoconsolidate.test.js +95 -0
  142. package/test/unit/scheduler-autodedupe.test.js +52 -0
  143. package/test/unit/scheduler-autosleep.test.js +50 -0
  144. package/test/unit/scheduler-cadence.test.js +33 -0
  145. package/test/unit/scheduler-deep.test.js +62 -0
  146. package/test/unit/scheduler-tick-gate.test.js +38 -0
  147. package/test/unit/scheduler.test.js +2 -1
  148. package/test/unit/service.test.js +5 -5
  149. package/test/unit/shiori-import.test.js +4 -4
  150. package/test/unit/spacing.test.js +14 -0
  151. package/test/unit/store.test.js +13 -13
  152. package/test/unit/summon-left-slot.test.js +51 -0
  153. package/test/unit/summon-rank.test.js +51 -0
  154. package/test/unit/tiers-gist.test.js +140 -0
  155. package/test/unit/tiers.test.js +1 -1
  156. package/test/unit/tokenizer-fts.test.js +6 -6
  157. package/test/unit/tools.test.js +5 -5
  158. package/test/unit/upgrade-0412.test.js +10 -10
  159. package/test/unit/upgrade-0413.test.js +5 -5
  160. package/test/unit/upgrade-0414.test.js +5 -5
  161. package/test/unit/vector-ann.test.js +3 -3
  162. package/test/unit/vector-async.test.js +7 -7
  163. package/test/unit/vector-coverage.test.js +34 -0
  164. package/test/unit/vector-override.test.js +37 -0
  165. package/test/unit/vector-typed-array.test.js +47 -0
  166. package/test/unit/vector.test.js +8 -8
  167. package/test/unit/working.test.js +19 -0
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Small, explicit query filter language:
3
- * kind:utterance tag:白饭 after:2026-11-01 before:2026-12-01 importance:>0.5 用户
3
+ * kind:utterance tag:米饭 after:2026-11-01 before:2026-12-01 importance:>0.5 用户
4
4
  * Unknown prefixes stay in the free text, so normal searches are unchanged.
5
5
  */
6
6
  const KEYS = new Set(['kind', 'tag', 'after', 'before', 'state', 'importance', 'source', 'actor']);
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Spacing for retrieval practice.
3
+ *
4
+ * The first recall of a trace is cheap to record, but touching it on every
5
+ * step turns access_count into noise. The interval grows with the number of
6
+ * previous recalls (a simple spacing curve), so a memory that is recalled
7
+ * often is written to less often — and a memory nobody touches stays easy to
8
+ * pick up again.
9
+ */
10
+ export function touchInterval(accessCount, { baseMs = 300_000, maxMs = 21_600_000 } = {}) {
11
+ const count = Math.max(0, Math.min(8, Number(accessCount) || 0));
12
+ const base = Math.max(1_000, Number(baseMs) || 300_000);
13
+ const max = Math.max(base, Number(maxMs) || 21_600_000);
14
+ return Math.min(max, base * (2 ** count));
15
+ }
@@ -25,7 +25,7 @@ export function tokens(text) {
25
25
 
26
26
  export function ftsTokenList(text) {
27
27
  // Bigrams preserve phrase specificity; single non-stop CJK chars act as a
28
- // cheap fuzzy fallback for near-synonyms that share a character (米饭/白饭).
28
+ // cheap fuzzy fallback for near-synonyms that share a character (米饭/饭).
29
29
  const out = tokenList(text);
30
30
  const value = String(text ?? '');
31
31
  for (const run of value.match(HAN) ?? []) {
@@ -2,35 +2,111 @@ import { estimateTokens } from '../memory/tokenizer.js';
2
2
 
3
3
  export const DEFAULT_TIER_BUDGETS = Object.freeze({ perm: 700, hot: 900, cold: 400 });
4
4
 
5
- function tierOf(item) {
5
+ function isPerm(item) {
6
+ return Number(item.importance ?? 0) >= 0.8;
7
+ }
8
+
9
+ function tierOf(item, context = {}) {
6
10
  const importance = Number(item.importance ?? 0);
7
- if (importance >= 0.8) return 'perm';
8
- const sources = Array.isArray(item.sources) ? item.sources.map((source) => source.name) : [];
9
- const lexicalHit = sources.includes('fts') || sources.includes('vector') || sources.includes('graph');
10
- if (importance < 0.4 && !lexicalHit) return 'cold';
11
+ if (isPerm(item)) return 'perm';
12
+ if (importance < 0.4) return 'cold';
13
+ // `rank`/`total` describe the non-perm candidates only: counting the perm rows
14
+ // in the denominator would let a high-importance-heavy recall eat the whole hot
15
+ // tier (6 of 8 candidates at 0.9 → 2 cold, 0 hot).
16
+ const { rank = 0, total = 0 } = context;
17
+ // Count the cold rows first and slide the cut: `ceil(total * 0.75)` rounds the
18
+ // *cut* up, which silently shrinks the tier (5 candidates → 1, not 2).
19
+ const coldCount = total >= 4 ? Math.max(1, Math.ceil(total * 0.25)) : 0;
20
+ if (rank >= total - coldCount) return 'cold';
11
21
  return 'hot';
12
22
  }
13
23
 
14
24
  function coldLine(item) {
15
- return `- [cold] ${item.id} · ${item.title ?? '(untitled)'}(正文按需取回)`;
25
+ // A bare "id + title" is a table of contents; say *why* it might be worth
26
+ // fetching. Match source tells us the reason, which is far more useful than a
27
+ // timestamp ("last read 3 days ago" gives no basis for a decision).
28
+ const names = (item.sources ?? []).map((source) => source?.name).filter(Boolean);
29
+ const why = names.includes('vector') ? '语义相近'
30
+ : names.includes('fts') ? '字面命中'
31
+ : names.includes('graph') ? '共享实体'
32
+ : names.length ? `命中 ${names[0]}` : '相关';
33
+ return `- [cold] ${item.id} · ${item.title ?? '(untitled)'}(${why},正文按需 cortex_get)`;
34
+ }
35
+
36
+ /**
37
+ * Recalled snippets can be ~220 chars of engineering detail. Injected every
38
+ * turn that is a lot of budget for context that is rarely needed verbatim, so
39
+ * the full tiers render a one-sentence gist and leave the body to cortex_get.
40
+ */
41
+ function gist(item, maxChars) {
42
+ let raw = String(item.snippet ?? item.summary ?? '').trim();
43
+ if (!raw) return '';
44
+ // Titles are usually the first line of the body; drop that duplicated opening
45
+ // before choosing a sentence, otherwise the gist is the title again.
46
+ const title = String(item.title ?? '').trim();
47
+ if (title && raw.startsWith(title)) raw = raw.slice(title.length).replace(/^[\s::,,。.!!??;;、\-—]+/, '').trim();
48
+ if (!raw) return '';
49
+ const sentences = raw.split(/(?<=[。!?;.!?;\n])/).map((part) => part.trim()).filter(Boolean);
50
+ // Too short to stand alone as a gist: take the next sentence too, instead of
51
+ // silently falling back to a hard truncation of the raw text.
52
+ let text = sentences[0] ?? raw;
53
+ if (text.length < 24 && sentences.length > 1) text = `${sentences[0]}${sentences[1]}`;
54
+ return text.length > maxChars ? `${text.slice(0, Math.max(0, maxChars - 1))}…` : text;
55
+ }
56
+
57
+ /**
58
+ * Titles are often the first line of the body, so `- title:gist` repeated the
59
+ * same words ("0.4.60 打包…:0.4.60 打包…"). Drop a long shared prefix.
60
+ */
61
+ function withoutTitlePrefix(title, text) {
62
+ const t = String(title ?? '').trim();
63
+ const s = String(text ?? '').trim();
64
+ if (!t || !s) return s;
65
+ let index = 0;
66
+ const max = Math.min(t.length, s.length);
67
+ while (index < max && t[index] === s[index]) index += 1;
68
+ if (index < 12) return s;
69
+ const rest = s.slice(index).replace(/^[\s::,,。.!!??;;、\-—]+/, '');
70
+ return rest || s;
16
71
  }
17
72
 
18
73
  /**
19
74
  * Budgeted three-tier injection. Cold memories are index-only: their bodies
20
75
  * stay out of the prompt and are fetched by id when actually needed.
21
76
  */
22
- export function selectTiers(items, { budgets = DEFAULT_TIER_BUDGETS, now = Date.now() } = {}) {
77
+ export function selectTiers(items, { budgets = DEFAULT_TIER_BUDGETS, now = Date.now(), gistChars = 120 } = {}) {
23
78
  const limits = { ...DEFAULT_TIER_BUDGETS, ...budgets };
24
79
  const buckets = { perm: [], hot: [], cold: [] };
25
80
  const used = { perm: 0, hot: 0, cold: 0 };
26
81
  let omitted = 0;
27
82
  const selected = [];
28
- const sorted = [...(items ?? [])].sort((a, b) => Number(b.utility ?? b.score ?? 0) - Number(a.utility ?? a.score ?? 0));
83
+ const sorted = [...(items ?? [])].sort((a, b) => {
84
+ const byUtility = Number(b.utility ?? b.score ?? 0) - Number(a.utility ?? a.score ?? 0);
85
+ if (byUtility !== 0) return byUtility;
86
+ // Stable tie-break: equal utility must not reshuffle between turns.
87
+ const byImportance = Number(b.importance ?? 0) - Number(a.importance ?? 0);
88
+ if (byImportance !== 0) return byImportance;
89
+ return String(a.id ?? '').localeCompare(String(b.id ?? ''));
90
+ });
91
+ // Rank the cold cut inside the non-perm pool: counting perm rows in the
92
+ // denominator lets a high-importance-heavy recall consume the whole hot tier.
93
+ const permCount = sorted.filter(isPerm).length;
94
+ const relativeTotal = sorted.length - permCount;
95
+ let relativeRank = -1;
29
96
  for (const item of sorted) {
30
- const tier = tierOf(item);
31
- const line = tier === 'cold'
32
- ? coldLine(item)
33
- : `- [${item.layer ?? tier}] ${item.title ?? '(untitled)'}:${item.snippet ?? ''}`;
97
+ const permRow = isPerm(item);
98
+ if (!permRow) relativeRank += 1;
99
+ const tier = tierOf(item, { rank: permRow ? 0 : relativeRank, total: relativeTotal });
100
+ const title = item.title ?? '(untitled)';
101
+ let line;
102
+ if (tier === 'cold') {
103
+ line = coldLine(item);
104
+ } else {
105
+ const text = withoutTitlePrefix(item.title, gist(item, gistChars));
106
+ // A body that is exactly its title leaves an empty gist; do not render a
107
+ // dangling colon.
108
+ line = text ? `- [${item.layer ?? tier}] ${title}:${text}` : `- [${item.layer ?? tier}] ${title}`;
109
+ }
34
110
  const cost = estimateTokens(line);
35
111
  if (used[tier] + cost > limits[tier]) { omitted += 1; continue; }
36
112
  buckets[tier].push({ ...item, tier, render: line, cost });
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Alias resolution for people.
3
+ *
4
+ * The same person can be stored under two targets (a nickname from the early
5
+ * days and the configured address now), so the relationship model would never
6
+ * accumulate and the affect counts would split. Everything that takes a target
7
+ * name goes through this resolver first, so aliases converge on the configured
8
+ * user address. `persona.userAliases` adds local nicknames.
9
+ */
10
+ const DEFAULT_USER_ALIASES = ['用户', '你', '您'];
11
+
12
+ export function createTargetResolver(persona = {}) {
13
+ const canonical = String(persona?.userAddress ?? '你').trim() || '你';
14
+ const aliases = new Set([canonical, ...DEFAULT_USER_ALIASES]);
15
+ for (const item of Array.isArray(persona?.userAliases) ? persona.userAliases : []) {
16
+ const value = String(item ?? '').trim();
17
+ if (value) aliases.add(value);
18
+ }
19
+ function resolveTarget(target) {
20
+ const value = String(target ?? '').trim();
21
+ if (!value) return canonical;
22
+ return aliases.has(value) ? canonical : value;
23
+ }
24
+ return { canonical, aliases, resolveTarget };
25
+ }
@@ -40,8 +40,9 @@ function detectWithLexicon(text, lexicon) {
40
40
  return Object.entries(scores).sort((a, b) => b[1] - a[1]).map(([name, score]) => ({ name, score }));
41
41
  }
42
42
 
43
- export function createEmotionModel({ db, scopeId = 'global' } = {}) {
43
+ export function createEmotionModel({ db, scopeId = 'global', resolveTarget = null } = {}) {
44
44
  if (!db) throw new Error('emotion model needs db');
45
+ const targetOf = typeof resolveTarget === 'function' ? resolveTarget : (value) => String(value ?? '').trim();
45
46
 
46
47
  function detect(text) {
47
48
  const emotions = detectWithLexicon(text, EMOTIONS);
@@ -56,6 +57,7 @@ export function createEmotionModel({ db, scopeId = 'global' } = {}) {
56
57
  }
57
58
 
58
59
  function record({ text, target = '用户', traceId = null, source = 'user', at = nowIso(), emotions = null } = {}) {
60
+ target = targetOf(target);
59
61
  const result = Array.isArray(emotions) && emotions.length
60
62
  ? { text: String(text ?? ''), emotions, top: emotions[0]?.name ?? null }
61
63
  : detect(text);
@@ -30,44 +30,75 @@ function rowToRelationship(row) {
30
30
  };
31
31
  }
32
32
 
33
- export function createRelationshipStore(db) {
33
+ // Trust and care move asymmetrically: a good interaction adds a fraction of the
34
+ // remaining room (so the hundredth kindness matters less than the first), while a
35
+ // disappointment takes a bigger bite (losses weigh more than gains). Both stay
36
+ // inside 0..1.
37
+ const LOSS_WEIGHT = 1.6;
38
+
39
+ export function nextBonded(value, delta) {
40
+ const current = clamp(value, 0, 1);
41
+ const amount = Number(delta) || 0;
42
+ if (!amount) return current;
43
+ if (amount > 0) {
44
+ const k = Math.min(1, amount);
45
+ return clamp(current + (1 - current) * k, 0, 1);
46
+ }
47
+ const k = Math.min(1, Math.abs(amount) * LOSS_WEIGHT);
48
+ return clamp(current - current * k, 0, 1);
49
+ }
50
+
51
+ export function nextGrow(value, delta) {
52
+ const current = clamp(value, 0, 1);
53
+ const k = Math.min(1, Math.abs(Number(delta) || 0));
54
+ return clamp(current + (1 - current) * k, 0, 1);
55
+ }
56
+
57
+ export function createRelationshipStore(db, { resolveTarget = null } = {}) {
58
+ const targetOf = typeof resolveTarget === 'function' ? resolveTarget : (value) => String(value ?? '').trim();
59
+
34
60
  function get(scopeId, target) {
35
- return rowToRelationship(db.prepare('SELECT * FROM relationships WHERE scope_id = ? AND target = ?').get(scopeId, target));
61
+ return rowToRelationship(db.prepare('SELECT * FROM relationships WHERE scope_id = ? AND target = ?').get(scopeId, targetOf(target)));
36
62
  }
37
63
 
38
64
  function ensure(scopeId = 'global', target = '用户') {
39
- const current = get(scopeId, target);
65
+ const name = targetOf(target);
66
+ const current = get(scopeId, name);
40
67
  if (current) return current;
41
68
  const id = makeId('rel');
42
69
  const now = nowIso();
43
70
  db.prepare(`
44
71
  INSERT INTO relationships(id, scope_id, target, trust, care, familiarity, expectations_json, boundaries_json, recent_json, updated_at)
45
72
  VALUES (?, ?, ?, 0.5, 0.5, 0, '[]', '[]', '[]', ?)
46
- `).run(id, scopeId, target, now);
47
- return get(scopeId, target);
73
+ `).run(id, scopeId, name, now);
74
+ return get(scopeId, name);
48
75
  }
49
76
 
50
77
  function update(scopeId, target, patch = {}) {
51
- const current = ensure(scopeId, target);
52
- const next = normalizeRelationship({ ...current, ...patch, target });
78
+ const name = targetOf(target);
79
+ const current = ensure(scopeId, name);
80
+ const next = normalizeRelationship({ ...current, ...patch, target: name });
53
81
  db.prepare(`
54
82
  UPDATE relationships SET trust = ?, care = ?, familiarity = ?, expectations_json = ?, boundaries_json = ?, recent_json = ?, updated_at = ?
55
83
  WHERE scope_id = ? AND target = ?
56
84
  `).run(
57
85
  next.trust, next.care, next.familiarity,
58
86
  JSON.stringify(next.expectations), JSON.stringify(next.boundaries), JSON.stringify(next.recent),
59
- nowIso(), scopeId, target,
87
+ nowIso(), scopeId, name,
60
88
  );
61
- return get(scopeId, target);
89
+ return get(scopeId, name);
62
90
  }
63
91
 
64
92
  function applyDelta(scopeId, target, delta = {}, { event = null, at = nowIso() } = {}) {
65
- const current = ensure(scopeId, target);
93
+ const name = targetOf(target);
94
+ const current = ensure(scopeId, name);
66
95
  const recent = [...(current.recent ?? []), ...(event ? [{ at, event: String(event).slice(0, 300) }] : [])].slice(-30);
67
96
  return update(scopeId, target, {
68
- trust: current.trust + Number(delta.trustDelta || 0),
69
- care: current.care + Number(delta.careDelta || 0),
70
- familiarity: current.familiarity + Number(delta.familiarityDelta || 0.01),
97
+ trust: nextBonded(current.trust, Number(delta.trustDelta || 0)),
98
+ care: nextBonded(current.care, Number(delta.careDelta || 0)),
99
+ // Familiarity only grows, and saturates: it is the count of shared time,
100
+ // not a score you can lose.
101
+ familiarity: nextGrow(current.familiarity, Math.abs(Number(delta.familiarityDelta || 0.01))),
71
102
  recent,
72
103
  });
73
104
  }
package/src/self/state.js CHANGED
@@ -77,9 +77,27 @@ export function driftMood(mood, { elapsedHours = 0, baseline = DEFAULT_MOOD } =
77
77
  export function applyMood(mood, { valence = 0, arousal = 0, salience = 0.5, weight = 0.35 } = {}) {
78
78
  const current = normalizeMood(mood);
79
79
  const w = clamp(weight * (0.5 + salience), 0, 0.8);
80
+ // Saturating response: each event moves the mood a fraction of the remaining
81
+ // distance to its bound, so repeated same-direction news approaches the limit
82
+ // without ever parking there (and the tenth good thing matters less than the
83
+ // first). Pure addition used to hit the clamp and stop carrying information.
84
+ const push = (value, delta, bound) => {
85
+ const amount = Number(delta) || 0;
86
+ if (!amount) return value;
87
+ const k = Math.min(1, Math.abs(amount) * w);
88
+ const target = amount > 0 ? bound : -bound;
89
+ return clamp(value + (target - value) * k, -bound, bound);
90
+ };
91
+ const pushUnit = (value, delta) => {
92
+ const amount = Number(delta) || 0;
93
+ if (!amount) return value;
94
+ const k = Math.min(1, Math.abs(amount) * w);
95
+ const target = amount > 0 ? 1 : 0;
96
+ return clamp(value + (target - value) * k, 0, 1);
97
+ };
80
98
  return {
81
- valence: clamp(current.valence + (Number(valence) || 0) * w, -1, 1),
82
- arousal: clamp(current.arousal + (Number(arousal) || 0) * w, 0, 1),
99
+ valence: push(current.valence, valence, 1),
100
+ arousal: pushUnit(current.arousal, arousal),
83
101
  energy: clamp(current.energy - 0.02 * (Number(arousal) || 0), 0, 1),
84
102
  };
85
103
  }
@@ -1,6 +1,8 @@
1
1
  import { makeId } from '../core/ids.js';
2
2
  import { clamp, nowIso } from '../core/time.js';
3
- import { estimateTokens, truncate } from '../memory/tokenizer.js';
3
+ import { estimateTokens, truncate, jaccard } from '../memory/tokenizer.js';
4
+
5
+ const DEDUPE_THRESHOLD = 0.82;
4
6
 
5
7
  function rowToWorking(row) {
6
8
  if (!row) return null;
@@ -19,11 +21,40 @@ function rowToWorking(row) {
19
21
  }
20
22
 
21
23
  export function createWorkingStore(db) {
22
- function add({ scopeId = 'global', kind = 'focus', text, priority = 0.5, pinned = false, sourceTraceId = null, ttlMs = null, at = Date.now() } = {}) {
24
+ /**
25
+ * Working memory used to accumulate near-duplicates (the same todo written
26
+ * twice by two sessions). Adding a near-duplicate now refreshes the existing
27
+ * item instead of piling up another line.
28
+ */
29
+ function nearDuplicate(scopeId, value) {
30
+ if (!value) return null;
31
+ const rows = db.prepare('SELECT * FROM working_items WHERE scope_id = ?').all(scopeId);
32
+ let best = null;
33
+ let bestScore = 0;
34
+ for (const row of rows) {
35
+ const score = jaccard(value, row.text);
36
+ if (score > bestScore) {
37
+ bestScore = score;
38
+ best = row;
39
+ }
40
+ }
41
+ return bestScore >= DEDUPE_THRESHOLD ? rowToWorking(best) : null;
42
+ }
43
+
44
+ function add({ scopeId = 'global', kind = 'focus', text, priority = 0.5, pinned = false, sourceTraceId = null, ttlMs = null, at = Date.now(), dedupe = true } = {}) {
23
45
  const value = String(text ?? '').trim();
24
46
  if (!value) throw new Error('working item text is required');
25
- const id = makeId('wrk');
26
47
  const now = nowIso(at);
48
+ if (dedupe !== false) {
49
+ const existing = nearDuplicate(scopeId, value);
50
+ if (existing) {
51
+ const keepText = value.length >= existing.text.length ? value : existing.text;
52
+ db.prepare('UPDATE working_items SET priority = ?, pinned = ?, text = ?, updated_at = ? WHERE id = ?')
53
+ .run(Math.max(clamp(priority, 0, 1), existing.priority), pinned || existing.pinned ? 1 : 0, keepText, now, existing.id);
54
+ return get(existing.id);
55
+ }
56
+ }
57
+ const id = makeId('wrk');
27
58
  const expiresAt = ttlMs ? new Date(at + Math.max(0, Number(ttlMs))).toISOString() : null;
28
59
  db.prepare(`
29
60
  INSERT INTO working_items(id, scope_id, kind, text, priority, pinned, source_trace_id, created_at, updated_at, expires_at)