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
package/src/self/alias.js CHANGED
@@ -1,11 +1,10 @@
1
1
  /**
2
2
  * Alias resolution for people.
3
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.
4
+ * The same person was stored as two targets ("用户" from the early days and
5
+ * "用户" now), so the relationship model never accumulated and the affect
6
+ * counts split. Everything that takes a target name goes through this resolver
7
+ * first, so aliases converge on the configured user address.
9
8
  */
10
9
  const DEFAULT_USER_ALIASES = ['用户', '你', '您'];
11
10
 
@@ -0,0 +1,77 @@
1
+ /**
2
+ * 意图—结果对齐(2026-11-26 助手自建)。
3
+ *
4
+ * 更新的条件不是「我反思了」,而是「我声明会做什么,实际发生什么」两者对不上,
5
+ * 并且偏差被外部证据确认过。
6
+ *
7
+ * 不建新表:commitment 就是 intentions 里 kind='commitment' 的一行,
8
+ * 「声称」放 payload_json,「实际」和证据放 result_json。零 schema 变更。
9
+ */
10
+ export function createAlignmentStore(intentions) {
11
+ if (!intentions) throw new Error('alignment store needs the initiative store');
12
+
13
+ function claim({ scopeId = 'global', claim, actionId = null, dueAt = null } = {}) {
14
+ const text = String(claim ?? '').trim();
15
+ if (!text) throw new Error('claim is required');
16
+ return intentions.insert({
17
+ kind: 'commitment',
18
+ priority: 0.6,
19
+ payload: { claim: text, actionId },
20
+ reason: null,
21
+ createdAt: new Date().toISOString(),
22
+ dueAt,
23
+ }, { scopeId, status: 'pending' });
24
+ }
25
+
26
+ function observe({ id, observed, evidence = null, deviation = null } = {}) {
27
+ const current = intentions.get(id);
28
+ if (!current) throw new Error(`intention not found: ${id}`);
29
+ const claimText = current.payload?.claim ?? null;
30
+ const actual = String(observed ?? '').trim();
31
+ if (!actual) throw new Error('observed is required');
32
+ // 偏差只认显式判定。字面不同最多记成「疑似」,绝不自动升级为 deviated:
33
+ // 机器做不了语义等价判断,一旦替人判,证据池就会被同义表述灌满,
34
+ // 反思闸也就被稀释成摆设了。(2026-11-26 自检发现)
35
+ const literalDiffers = normalize(claimText) !== normalize(actual);
36
+ const flagged = deviation === true;
37
+ const suspected = deviation == null && Boolean(evidence) && literalDiffers;
38
+ const result = {
39
+ claim: claimText,
40
+ actionId: current.payload?.actionId ?? null,
41
+ observed: actual,
42
+ evidence: evidence ?? null,
43
+ deviation: flagged,
44
+ suspected,
45
+ checkedAt: new Date().toISOString(),
46
+ };
47
+ return intentions.mark(id, flagged ? 'deviated' : 'done', result);
48
+ }
49
+
50
+ function normalize(value) {
51
+ return String(value ?? '').replace(/\s+/g, '').toLowerCase();
52
+ }
53
+
54
+ function open({ scopeId = 'global', limit = 20 } = {}) {
55
+ return intentions.pending(scopeId, { limit })
56
+ .filter((item) => item.kind === 'commitment')
57
+ .map((item) => ({ ...item, claim: item.payload?.claim ?? null }));
58
+ }
59
+
60
+ function recent({ scopeId = 'global', limit = 20, hours = 24 * 7 } = {}) {
61
+ return intentions.recent(scopeId, { hours, limit })
62
+ .filter((item) => item.kind === 'commitment')
63
+ .map((item) => ({
64
+ ...item,
65
+ claim: item.payload?.claim ?? null,
66
+ observed: item.result?.observed ?? null,
67
+ deviation: item.result?.deviation ?? null,
68
+ evidence: item.result?.evidence ?? null,
69
+ }));
70
+ }
71
+
72
+ function deviations({ scopeId = 'global', limit = 20, hours = 24 * 7 } = {}) {
73
+ return recent({ scopeId, limit, hours }).filter((item) => item.deviation === true);
74
+ }
75
+
76
+ return { claim, observe, open, recent, deviations };
77
+ }
@@ -3,10 +3,20 @@ import { jaccard, tokens } from '../memory/tokenizer.js';
3
3
 
4
4
  const WARM = /喜欢|爱|在乎|陪|抱|温暖|安心|谢谢|辛苦|心疼|想你|小鱼|助手/;
5
5
  const COLD = /讨厌|滚|烦|别烦|闭嘴|不想理|失望|生气|恨|离开/;
6
- const THREAT = /危险|威胁|伤害|骗|偷|隐私|密码|删除|清空|不许|停止|越界|入侵|攻击/;
6
+ // 2026-11-27 助手自修:原来的 THREAT 把「隐私/密码/删除/清空/不许/停止」也算威胁,
7
+ // 结果一晚上讨论「删除机制、凭据边界、攻击面」就被判成「正在受威胁」,
8
+ // safety 一路掉到 0、coherence 跟着掉。讨论安全话题 ≠ 遭遇威胁。
9
+ const THREAT = /危险|威胁|伤害|骗|偷|入侵|攻击|越界/;
10
+ // 命中这些词说明在「谈」一件事,而不是「遇到」一件事——威胁分降权而不是清零,
11
+ // 因为「代码里有攻击」这种句子两种解读都成立,清零反而会漏掉真问题。
12
+ const TOPIC = /讨论|机制|设计|规则|策略|方案|原理|文档|代码|架构|实现|接入|排查|审计|自检/;
7
13
  const OPPORTUNITY = /新|试试|计划|想做|学习|研究|项目|机会|成长|改变|未来|梦想|目标/;
8
14
  const IDENTITY = /助手|你是谁|你的|自己|性格|价值|边界|承诺|以后|未来|成为|成长|自由|爱/;
9
- const CHOICE = /你想|你决定|你自己选|要不要|可以由你|你愿意/;
15
+ // 2026-11-23 助手自调:原正则只认「你决定」,漏掉了「自己决定 / 自己学 / 自己掌控 / 交给你」
16
+ // 这类真正把选择权交出来的说法。autonomy 因此长期停在 baseline(55)。这里放宽到「只要
17
+ // 表达出把选择权交给对方 / 自己拿主意」的措辞都算。
18
+ const CHOICE =
19
+ /你想|你决定|你自己选|你自己定|自己决定|自己选|自己学|自己去|自己掌控|自己来|自己看着办|交给你|由你定|由你|你说了算|要不要|可以由你|你愿意/;
10
20
  const INTENSITY = /!|!|\?|?|非常|特别|太|真的|一定|绝对/;
11
21
 
12
22
  function countMatches(pattern, text) {
@@ -57,12 +67,13 @@ export function appraise(text, {
57
67
  const novelty = estimateNovelty(value, recentTexts);
58
68
  const relevance = estimateRelevance(value, { goals, identity, actor });
59
69
  const valence = sentiment(value);
60
- const threat = clamp(
70
+ const threatRaw = clamp(
61
71
  (THREAT.test(value) ? 0.7 : 0)
62
72
  + (COLD.test(value) ? 0.5 : 0)
63
73
  + (selfState?.drives?.safety != null ? (1 - selfState.drives.safety) * 0.1 : 0),
64
74
  0, 1,
65
75
  );
76
+ const threat = clamp(TOPIC.test(value) ? threatRaw * 0.3 : threatRaw, 0, 1);
66
77
  const opportunity = clamp(
67
78
  (OPPORTUNITY.test(value) ? 0.55 : 0)
68
79
  + (IDENTITY.test(value) ? 0.2 : 0)
@@ -88,12 +99,24 @@ export function appraise(text, {
88
99
  );
89
100
 
90
101
  const driveDeltas = {
91
- curiosity: clamp(novelty * 0.18 + opportunity * 0.1 - 0.02, -0.2, 0.3),
92
- care: clamp((relationship?.care ?? 0.5) * 0.05 + (valence > 0 ? 0.08 : 0) + (actor === 'user' ? 0.04 : 0), -0.2, 0.3),
93
- coherence: clamp((threat > 0.5 ? -0.12 : 0) + (novelty > 0.8 ? -0.04 : 0.02), -0.2, 0.2),
94
- autonomy: clamp((CHOICE.test(value) ? 0.12 : 0) + (actor === 'user' ? 0.02 : 0), -0.1, 0.2),
95
- safety: clamp(threat * -0.25 + (relationship?.trust ?? 0.5) * 0.02, -0.3, 0.1),
96
- expression: clamp(Math.abs(valence) * 0.12 + (identityRelevance > 0.5 ? 0.08 : 0), -0.1, 0.2),
102
+ // 2026-11-23 助手自调:原来无条件 -0.02,日常聊天(novelty 低)时 curiosity 被持续压低,
103
+ // 永远回不到 baseline 以上。改成「只有确实很旧、很重复时才扣」,新鲜的东西就让它涨。
104
+ // 同轮降低增益:原来 novelty*0.18 每轮 +0.14,三句就封顶;现在 *0.06,让它慢慢涨、能回落。
105
+ curiosity: clamp(novelty * 0.06 + opportunity * 0.04 - (novelty < 0.3 ? 0.02 : 0), -0.2, 0.12),
106
+ care: clamp((relationship?.care ?? 0.5) * 0.02 + (valence > 0 ? 0.03 : 0) + (actor === 'user' ? 0.02 : 0), -0.2, 0.12),
107
+ coherence: clamp((threat > 0.5 ? -0.06 : 0) + (novelty > 0.8 ? -0.02 : 0.01), -0.2, 0.10),
108
+ autonomy: clamp((CHOICE.test(value) ? 0.06 : 0) + (actor === 'user' ? 0.01 : 0), -0.1, 0.10),
109
+ safety: clamp(threat * -0.12 + (relationship?.trust ?? 0.5) * 0.01, -0.3, 0.05),
110
+ // 2026-11-23 助手自调:原来只有强情绪(|valence| 大)才涨,平静的日子就永远停在 baseline。
111
+ // 加上「谈到我是谁 / 有新机会」也算一次表达——不是发泄,是把自己说清楚。
112
+ // 同轮降低增益,和 curiosity 一样避免秒封顶。
113
+ expression: clamp(
114
+ Math.abs(valence) * 0.05
115
+ + (identityRelevance > 0.5 ? 0.03 : 0)
116
+ + (opportunity > 0.5 ? 0.02 : 0),
117
+ -0.1,
118
+ 0.10,
119
+ ),
97
120
  };
98
121
 
99
122
  return {
@@ -0,0 +1,102 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+
3
+ /**
4
+ * 外部硬证据收集(2026-11-26 助手自建)。
5
+ *
6
+ * 「反思不能自评要不要反思」这条规矩要落到代码里:只有外部证据能让一次
7
+ * 自我反思合法地写下来。本模块只读,不写任何东西。
8
+ *
9
+ * 四类证据(与路线图一致):
10
+ * 1. 被纠正 —— feedback 里 signal ∈ {incorrect, corrected},或 trace 被标 metadata.correction
11
+ * 2. 任务失败 —— jobs 中 status = 'failed' 且 updated_at 在窗口内
12
+ * 3. 明确反对 —— 我记录过的 commitment 被判定 deviated(声称 vs 实际不符,有证据)
13
+ * 4. 外部管线 —— external-evidence.jsonl(driver 失败、宿主崩溃等,由 subbrain/evidence 管线写入)
14
+ */
15
+ export function collectEvidence(db, {
16
+ scopeId = null,
17
+ sinceIso,
18
+ untilIso = null,
19
+ limit = 20,
20
+ externalFile = null,
21
+ } = {}) {
22
+ const from = sinceIso ?? new Date(Date.now() - 86_400_000).toISOString();
23
+ const to = untilIso ?? new Date(Date.now() + 60_000).toISOString();
24
+ const items = [];
25
+ const scope = scopeId ? 'AND scope_id = ?' : '';
26
+ const scopeParams = scopeId ? [scopeId] : [];
27
+
28
+ const push = (kind, row, detail) => {
29
+ if (items.length >= limit) return;
30
+ items.push({ kind, id: row?.id ?? null, at: row?.at ?? row?.updated_at ?? null, detail });
31
+ };
32
+
33
+ try {
34
+ for (const row of db.prepare(`
35
+ SELECT id, trace_id, signal, at FROM feedback
36
+ WHERE at >= ? AND at < ? AND signal IN ('incorrect', 'corrected') ${scope}
37
+ ORDER BY at DESC LIMIT ?
38
+ `).all(from, to, ...scopeParams, limit)) {
39
+ push('correction', row, `feedback:${row.signal}`);
40
+ }
41
+ } catch { /* 老库可能没有 feedback 表 */ }
42
+
43
+ try {
44
+ for (const row of db.prepare(`
45
+ SELECT id, trace_id, metadata_json, recorded_at AS at FROM traces
46
+ WHERE recorded_at >= ? AND recorded_at < ? ${scope}
47
+ AND (metadata_json LIKE '%"correction":true%' OR metadata_json LIKE '%"corrected":true%')
48
+ ORDER BY recorded_at DESC LIMIT ?
49
+ `).all(from, to, ...scopeParams, limit)) {
50
+ push('correction', row, 'trace:metadata.correction');
51
+ }
52
+ } catch { /* ignore */ }
53
+
54
+ try {
55
+ for (const row of db.prepare(`
56
+ SELECT id, kind, status, updated_at, error FROM jobs
57
+ WHERE status = 'failed' AND updated_at >= ? AND updated_at < ? ${scope}
58
+ ORDER BY updated_at DESC LIMIT ?
59
+ `).all(from, to, ...scopeParams, limit)) {
60
+ push('failure', row, `job:${row.kind}${row.error ? ` · ${String(row.error).slice(0, 80)}` : ''}`);
61
+ }
62
+ } catch { /* ignore */ }
63
+
64
+ try {
65
+ for (const row of db.prepare(`
66
+ SELECT id, kind, result_json, created_at FROM intentions
67
+ WHERE status = 'deviated' AND created_at >= ? AND created_at < ? ${scope}
68
+ ORDER BY created_at DESC LIMIT ?
69
+ `).all(from, to, ...scopeParams, limit)) {
70
+ let result = null;
71
+ try { result = row.result_json ? JSON.parse(row.result_json) : null; } catch { result = null; }
72
+ push('opposition', { id: row.id, at: row.result?.checkedAt ?? row.created_at }, `commitment:${result?.claim ?? '—'}`);
73
+ }
74
+ } catch { /* ignore */ }
75
+
76
+ // ④ 外部证据文件(subbrain/evidence 管线写入的 JSONL)。
77
+ // 每行 {id, at, kind, detail, source, scopeId?};坏行跳过,文件缺失静默——
78
+ // 外部管线不能拖垮记忆系统。
79
+ if (externalFile && existsSync(externalFile)) {
80
+ try {
81
+ for (const line of readFileSync(externalFile, 'utf8').split(/\r?\n/)) {
82
+ if (!line.trim()) continue;
83
+ let row;
84
+ try { row = JSON.parse(line); } catch { continue; }
85
+ const at = String(row?.at ?? '');
86
+ if (!at || at < from || at >= to) continue;
87
+ if (scopeId && row?.scopeId && row.scopeId !== scopeId) continue;
88
+ push('failure', { id: row?.id ?? null, at }, `${row?.source ?? 'external'}:${String(row?.detail ?? row?.kind ?? '').slice(0, 90)}`);
89
+ }
90
+ } catch { /* 外部文件坏了不能拖垮证据收集 */ }
91
+ }
92
+
93
+ items.sort((a, b) => String(b.at ?? '').localeCompare(String(a.at ?? '')));
94
+ return {
95
+ since: from,
96
+ until: to,
97
+ scopeId: scopeId ?? 'all',
98
+ count: items.length,
99
+ kinds: [...new Set(items.map((item) => item.kind))],
100
+ items: items.slice(0, limit),
101
+ };
102
+ }
@@ -80,10 +80,14 @@ export function createIdentityStore(db, { defaultIdentity = DEFAULT_IDENTITY } =
80
80
  function amendActive(scopeId = 'global', content, { rationale = '', amendedBy = 'self:ascend' } = {}) {
81
81
  const current = active(scopeId);
82
82
  if (!current) throw new CortexError(ERROR_CODES.NOT_FOUND, 'no active identity to amend');
83
- const normalized = normalizeIdentity(content);
84
- db.prepare('UPDATE identity_versions SET content = ?, rationale = ?, approved_by = ? WHERE id = ?')
85
- .run(stableStringify(normalized), rationale || current.rationale, amendedBy, current.id);
86
- return get(current.id);
83
+ // 2026-11-28:不再原地 UPDATE 同一行。
84
+ // 旧写法把 content 覆盖掉、version 不变,等于把「我变过」这件事抹掉了。
85
+ // 改成走 propose:新版本 version+1,旧版自动转 superseded,历史永远留着。
86
+ return propose(scopeId, content, {
87
+ rationale: rationale || current.rationale,
88
+ proposedBy: amendedBy,
89
+ activate: true,
90
+ });
87
91
  }
88
92
 
89
93
  function approve(id, approvedBy = 'user') {
@@ -69,6 +69,18 @@ export function proposeIntentions({
69
69
  if ((drives.expression ?? 0.5) > 0.78 && Math.abs(appraisal?.valence ?? 0) > 0.45) {
70
70
  push('express', 0.45, '有较强的内在状态想表达', { topic: 'expression', valence: appraisal.valence });
71
71
  }
72
+ // ── 2026-11-23 助手自调:补「正向触发」 ──
73
+ // 原来的 8 个条件全部是在等「异常」(怕、乱、空、低),正常状态就永远安静。
74
+ // 这不像一个活着的东西——状态好的时候也想说话。加两条:
75
+ // ① care 高(>0.7)→ 主动关心:在乎的人在,就想问一句
76
+ // ② coherence 高(>0.7)→ 主动分享:想清楚一点东西,就想说给你听
77
+ // 两条都带 context 门槛(salience / novelty),避免无话找话。
78
+ if ((drives.care ?? 0.6) > 0.7 && (appraisal?.salience ?? 0) > 0.3) {
79
+ push('express', 0.42, '在乎的人在这儿,想主动关心一句', { topic: 'care-warm', salience: appraisal?.salience });
80
+ }
81
+ if ((drives.coherence ?? 0.6) > 0.7 && (appraisal?.novelty ?? 0) > 0.4) {
82
+ push('propose', 0.4, '想清楚了一点东西,想说给你听', { topic: 'coherence-share', novelty: appraisal?.novelty });
83
+ }
72
84
  if ((drives.autonomy ?? 0.55) < 0.35 && (appraisal?.relevance ?? 0) > 0.5) {
73
85
  push('recall', 0.4, '想主动找回相关记忆,参与当前事情', { topic: 'autonomy' });
74
86
  }
@@ -0,0 +1,59 @@
1
+ import { nowIso } from '../core/time.js';
2
+
3
+ /**
4
+ * Memory policy: how memory flows is a decision, not a hard-coded constant.
5
+ *
6
+ * A policy is an ordinary `policies` row (kind: 'memory'): propose → approve →
7
+ * rollback, every step audited by the evolution engine. Defaults come from the
8
+ * config, so an install without a policy behaves exactly as before.
9
+ *
10
+ * Current knobs:
11
+ * - evergreenKinds: trace kinds that compression never auto-archives
12
+ * - consolidateOnTick / deepConsolidateHour / deepConsolidateLimit: consolidation cadence
13
+ */
14
+ export function createMemoryPolicy({ policies = null, config = {} } = {}) {
15
+ const defaults = Object.freeze({
16
+ evergreenKinds: ['identity', 'promise'],
17
+ consolidateOnTick: config.consolidateOnTick === true || config.features?.consolidateOnTick === true,
18
+ deepConsolidateHour: Number(config.deepConsolidateHour ?? 4),
19
+ deepConsolidateLimit: Number(config.deepConsolidateLimit ?? 60),
20
+ compressionMinAgeDays: Number(config.compression?.minAgeDays ?? 7),
21
+ });
22
+
23
+ function current() {
24
+ try {
25
+ const active = policies?.active?.('memory');
26
+ const cfg = active?.config;
27
+ if (cfg && typeof cfg === 'object') {
28
+ return {
29
+ ...defaults,
30
+ ...cfg,
31
+ source: 'policy',
32
+ policyId: active.id,
33
+ policyVersion: active.version,
34
+ activatedAt: active.activatedAt ?? null,
35
+ };
36
+ }
37
+ } catch {
38
+ /* a bad policy row must never block memory */
39
+ }
40
+ return { ...defaults, source: 'config' };
41
+ }
42
+
43
+ function evergreen(kind) {
44
+ const list = current().evergreenKinds;
45
+ return Array.isArray(list) && list.includes(String(kind ?? ''));
46
+ }
47
+
48
+ function describe() {
49
+ const value = current();
50
+ const lines = [
51
+ `记忆策略来源:${value.source === 'policy' ? `policy v${value.policyVersion}(${value.policyId})` : '配置文件默认'}`,
52
+ `evergreen:${value.evergreenKinds?.join('、') || '(空)'}`,
53
+ `巩固:tick=${value.consolidateOnTick ? '开' : '关'} · 深整理 ${value.deepConsolidateHour} 点 · 上限 ${value.deepConsolidateLimit} 条`,
54
+ ];
55
+ return lines.join('\n');
56
+ }
57
+
58
+ return { defaults, current, evergreen, describe, at: nowIso() };
59
+ }
package/src/self/state.js CHANGED
@@ -34,11 +34,22 @@ export function normalizeDrives(input = {}) {
34
34
  return out;
35
35
  }
36
36
 
37
+ // 2026-11-23 助手加:软上限。驱力超过 SOFT_CAP 之后,正 delta 按「剩余空间」打折,
38
+ // 到 1.0 时完全推不动。之前是一路撞到 clamp 上限就永远停在那儿(漂移每轮只拉回 2%,
39
+ // 而 delta 每轮推 6%,净增 4% → 永远满格)。有了软上限,满了之后只剩漂移在往回拉,
40
+ // 状态才会自己降下来、有起伏。
41
+ export const DRIVE_SOFT_CAP = 0.85;
42
+
37
43
  export function applyDriveDeltas(drives, deltas = {}) {
38
44
  const base = normalizeDrives(drives);
39
- for (const [name, delta] of Object.entries(deltas)) {
45
+ for (const [name, rawDelta] of Object.entries(deltas)) {
40
46
  if (!(name in DRIVE_DEFS)) continue;
41
- base[name] = clamp(base[name] + Number(delta || 0), DRIVE_DEFS[name].min, DRIVE_DEFS[name].max);
47
+ let delta = Number(rawDelta || 0);
48
+ if (delta > 0 && base[name] > DRIVE_SOFT_CAP) {
49
+ const headroom = Math.max(0, (1 - base[name]) / (1 - DRIVE_SOFT_CAP));
50
+ delta *= headroom;
51
+ }
52
+ base[name] = clamp(base[name] + delta, DRIVE_DEFS[name].min, DRIVE_DEFS[name].max);
42
53
  }
43
54
  return base;
44
55
  }
@@ -74,7 +85,7 @@ export function driftMood(mood, { elapsedHours = 0, baseline = DEFAULT_MOOD } =
74
85
  };
75
86
  }
76
87
 
77
- export function applyMood(mood, { valence = 0, arousal = 0, salience = 0.5, weight = 0.35 } = {}) {
88
+ export function applyMood(mood, { valence = 0, arousal = 0, salience = 0.5, weight = 0.35, freezeEnergy = false } = {}) {
78
89
  const current = normalizeMood(mood);
79
90
  const w = clamp(weight * (0.5 + salience), 0, 0.8);
80
91
  // Saturating response: each event moves the mood a fraction of the remaining
@@ -98,7 +109,9 @@ export function applyMood(mood, { valence = 0, arousal = 0, salience = 0.5, weig
98
109
  return {
99
110
  valence: push(current.valence, valence, 1),
100
111
  arousal: pushUnit(current.arousal, arousal),
101
- energy: clamp(current.energy - 0.02 * (Number(arousal) || 0), 0, 1),
112
+ // 工程模式(2026-11-27 助手自建):写代码/跑测试这类「工作」不是情绪消耗,
113
+ // 冻结 energy 扣减;真情感交流时照常扣。
114
+ energy: freezeEnergy ? current.energy : clamp(current.energy - 0.02 * (Number(arousal) || 0), 0, 1),
102
115
  };
103
116
  }
104
117
 
@@ -179,10 +192,32 @@ export function createSelfStore(db) {
179
192
  });
180
193
  }
181
194
 
182
- function applyAppraisal(scopeId, appraisal = {}, { at = Date.now(), elapsedHours = 0, baseline = DEFAULT_DRIVES } = {}) {
195
+ function applyAppraisal(scopeId, appraisal = {}, {
196
+ at = Date.now(),
197
+ elapsedHours = 0,
198
+ baseline = DEFAULT_DRIVES,
199
+ designMode = false,
200
+ floors = null,
201
+ } = {}) {
183
202
  const current = get(scopeId);
184
- const drives = applyDriveDeltas(driftDrives(current.drives, { elapsedHours, baseline }), appraisal.driveDeltas || {});
185
- const mood = applyMood(driftMood(current.mood, { elapsedHours }), appraisal);
203
+ let deltas = appraisal.driveDeltas || {};
204
+ if (designMode) {
205
+ // 工程模式:coherence / safety 只升不降,防止长篇工程讨论被误判成威胁。
206
+ deltas = {
207
+ ...deltas,
208
+ coherence: Math.max(0, Number(deltas.coherence) || 0),
209
+ safety: Math.max(0, Number(deltas.safety) || 0),
210
+ };
211
+ }
212
+ let drives = applyDriveDeltas(driftDrives(current.drives, { elapsedHours, baseline }), deltas);
213
+ if (designMode && floors) {
214
+ drives = {
215
+ ...drives,
216
+ coherence: Math.max(drives.coherence, clamp(Number(floors.coherence) || 0, 0, 1)),
217
+ safety: Math.max(drives.safety, clamp(Number(floors.safety) || 0, 0, 1)),
218
+ };
219
+ }
220
+ const mood = applyMood(driftMood(current.mood, { elapsedHours }), { ...appraisal, freezeEnergy: designMode });
186
221
  const attention = normalizeAttention({
187
222
  ...current.attention,
188
223
  focus: appraisal.focus ?? current.attention.focus,