dsh-cortex-memory 0.4.148 → 0.4.161

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.
@@ -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
  }
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,
@@ -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,7 +18,10 @@ 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';
@@ -30,6 +34,7 @@ import { createReflectEngine } from '../engines/reflect.js';
30
34
  import { createSkillEngine } from '../engines/skills.js';
31
35
  import { createJobRunner } from '../engines/jobs.js';
32
36
  import { createHealthEngine } from '../engines/health.js';
37
+ import { auditMemory } from '../engines/memory-audit.js';
33
38
  import { createPrivacyEngine } from '../engines/privacy.js';
34
39
  import { createDevelopEngine } from '../engines/develop.js';
35
40
  import { createGraphEngine } from '../engines/graph.js';
@@ -73,6 +78,12 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
73
78
  const { db, config } = openDatabase(rawConfig);
74
79
  migrate(db);
75
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
+
76
87
  const events = createEventRepository(db);
77
88
  const traces = createTraceRepository(db);
78
89
  const entities = createEntityRepository(db);
@@ -86,8 +97,12 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
86
97
  const audit = createAuditRepository(db);
87
98
  const summons = createSummonRepository(db);
88
99
  const selfStore = createSelfStore(db);
100
+ // 工程模式:运行时开关,默认取配置;重启回到配置值(临时锁定的语义)。
101
+ let designMode = config.selfDesign?.mode === true;
89
102
  const appraisalStore = createAppraisalStore(db);
90
103
  const initiativeStore = createInitiativeStore(db);
104
+ // 2026-11-26:意图—结果对齐。声称放 payload,实际+证据放 result_json,零 schema 变更。
105
+ const alignment = createAlignmentStore(initiativeStore);
91
106
  const identityStore = createIdentityStore(db);
92
107
  const targetResolver = createTargetResolver(config.persona ?? {});
93
108
  const relationshipStore = createRelationshipStore(db, { resolveTarget: targetResolver.resolveTarget });
@@ -283,12 +298,23 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
283
298
  queue: jobs,
284
299
  logger,
285
300
  handlers: {
286
- reflect: (payload) => reflect.reflect({
287
- scopeId: payload.scopeId ?? config.scope,
288
- windowDays: payload.windowDays ?? 1,
289
- maxSources: payload.maxSources ?? 8,
290
- force: payload.force === true,
291
- }),
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
+ },
292
318
  },
293
319
  });
294
320
 
@@ -459,6 +485,58 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
459
485
  }
460
486
  }
461
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
+ }
462
540
  return result;
463
541
  }
464
542
 
@@ -774,6 +852,37 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
774
852
  return updated;
775
853
  }
776
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
+
777
886
  function updateMemoryEmotion({ id, text, target } = {}) {
778
887
  if (!memoryEditEnabled) throw new Error('memory edit is locked');
779
888
  const current = db.prepare('SELECT * FROM emotion_events WHERE id = ? AND scope_id = ?').get(id, config.scope);
@@ -1531,7 +1640,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1531
1640
  // an episode, and once a segment has enough material it is written.
1532
1641
  const minMaterial = Number.isFinite(Number(config.reflectMinMaterial)) ? Number(config.reflectMinMaterial) : 50;
1533
1642
  if (count < minMaterial) return { skipped: 'few-traces', count, minMaterial, since: segmentSince };
1534
- 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' });
1535
1644
  return {
1536
1645
  created: !result.skipped,
1537
1646
  coverage: result.coverage ?? null,
@@ -1769,13 +1878,37 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1769
1878
  return { candidates: created, count: created.length, at: new Date(now).toISOString() };
1770
1879
  },
1771
1880
  render: ({ scopeId = config.scope, budget = 260, at = new Date().toISOString() } = {}) => {
1772
- 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 });
1773
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
+ });
1774
1898
  const lines = [];
1775
1899
  let used = 0;
1776
1900
  let omitted = 0;
1777
1901
  for (const rule of rules) {
1778
- 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}` : ''})`;
1779
1912
  const cost = estimateTokens(line);
1780
1913
  if (used + cost > budget) { omitted += 1; continue; }
1781
1914
  lines.push(line); used += cost;
@@ -1839,6 +1972,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1839
1972
  memoryDays,
1840
1973
  memoryDay,
1841
1974
  updateMemoryTrace,
1975
+ retagMemory,
1842
1976
  updateMemoryEmotion,
1843
1977
  graphCandidates: ({ scopeId = config.scope, limit = 200 } = {}) => {
1844
1978
  const rows = edges.listCandidates({ scopeId, limit });
@@ -1933,7 +2067,30 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1933
2067
  return privacy.forget(input);
1934
2068
  },
1935
2069
  privacy,
1936
- 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 }),
1937
2094
  reflectBackfill: (options = {}) => reflect.backfillEpisodes({ ...options, scopeId: options.scopeId ?? config.scope }),
1938
2095
  evaluateDevelopment: (options = {}) => development.evaluate({ ...options, scopeId: options.scopeId ?? config.scope }),
1939
2096
  rebuildVector: (options = {}) => vector?.rebuild({ ...options, scopeId: options.scopeId ?? config.scope }) ?? { rebuilt: 0 },
@@ -1952,7 +2109,32 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
1952
2109
  importMarkdown: (root, options = {}) => importMarkdown({ write }, root, { ...options, scopeId: options.scopeId ?? config.scope }),
1953
2110
  syncMarkdown: (root, options = {}) => syncMarkdown({ repos: { traces, audit }, write }, root, { ...options, scopeId: options.scopeId ?? config.scope }),
1954
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
+ }),
1955
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
+ },
1956
2138
  working: workingStore,
1957
2139
  goals: goalStore,
1958
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) {