dsh-cortex-memory 0.4.148 → 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.
@@ -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,
@@ -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,
@@ -1,4 +1,6 @@
1
1
  import path from 'node:path';
2
+ import { assembleSystemPrompt } from '../prompt/assemble.js';
3
+ import { estimateTokens } from '../memory/tokenizer.js';
2
4
 
3
5
  function guardPathAllowed(service, target) {
4
6
  if (service?.config?.allowRestoreOutsideRoot === true) return true;
@@ -33,6 +35,59 @@ function formatSearch(result) {
33
35
  return lines.join('\n');
34
36
  }
35
37
 
38
+ function formatAudit(report) {
39
+ const lines = [
40
+ `只读审计 · ${String(report.at).slice(0, 19)} · 范围 ${report.scopeId}`,
41
+ `过期未收 ${report.expired.total} · 同题多值 ${report.contradiction.total} · 争议未决 ${report.disputed.total}`,
42
+ `僵尸 ${report.zombie.total} · 归档候选 ${report.archiveCandidate.total}/${report.archiveCandidate.scanned}(阈值 ${report.archiveCandidate.threshold})· 孤儿痕迹 ${report.integrity.orphanTraces}`,
43
+ ];
44
+ if (report.stability?.length) lines.push(`稳定性:${report.stability.map((bucket) => `${bucket.bucket} ${bucket.total}`).join(' · ')}`);
45
+ if (report.authorship?.buckets?.length) {
46
+ lines.push(`作者:${report.authorship.buckets.map((bucket) => `${bucket.kind} ${bucket.total}`).join(' · ')}${report.authorship.pendingSelf ? ` · 待确认 ${report.authorship.pendingSelf}` : ''}`);
47
+ }
48
+ if (report.expired.items.length) {
49
+ lines.push('— 过期却仍是 active —');
50
+ for (const row of report.expired.items.slice(0, 5)) lines.push(`- ${row.id} · ${row.predicate} → ${row.object_literal ?? row.object_id ?? '—'} · 止于 ${String(row.valid_to).slice(0, 10)}`);
51
+ }
52
+ if (report.contradiction.items.length) {
53
+ lines.push('— 同题多值 —');
54
+ for (const row of report.contradiction.items.slice(0, 5)) lines.push(`- ${row.subject_id} · ${row.predicate} ×${row.total}`);
55
+ }
56
+ if (report.zombie.items.length) {
57
+ lines.push('— 僵尸痕迹(从没被召回、够老、重要度低)—');
58
+ for (const row of report.zombie.items.slice(0, 5)) lines.push(`- ${row.id} · ${row.kind} · ${String(row.title ?? '').slice(0, 24)} · ${String(row.recorded_at).slice(0, 10)}`);
59
+ }
60
+ if (report.archiveCandidate.items.length) {
61
+ lines.push('— 归档候选(DSR 已低于阈值)—');
62
+ for (const row of report.archiveCandidate.items.slice(0, 5)) lines.push(`- ${row.id} · r=${row.retrievability} · 闲置 ${row.idleDays} 天 · ${row.kind}`);
63
+ }
64
+ lines.push('本命令只报不改;要处理请逐条用 cortex_forget / cortex_feedback / cortex_compress。');
65
+ return lines.join('\n');
66
+ }
67
+
68
+ function formatIntention(report) {
69
+ const lines = [];
70
+ const open = report.open ?? [];
71
+ const recent = report.recent ?? [];
72
+ lines.push(`待兑现 ${open.length} 条 · 最近记录 ${recent.length} 条 · 偏差 ${(report.deviations ?? []).length} 条`);
73
+ if (open.length) {
74
+ lines.push('— 我说过要做、还没对过的 —');
75
+ for (const item of open.slice(0, 8)) lines.push(`- ${item.id} · ${item.claim ?? '—'}${item.dueAt ? ` · 应收尾 ${String(item.dueAt).slice(0, 10)}` : ''}`);
76
+ }
77
+ const wrong = recent.filter((item) => item.deviation === true);
78
+ if (wrong.length) {
79
+ lines.push('— 声称与实际不符(有证据)—');
80
+ for (const item of wrong.slice(0, 8)) {
81
+ lines.push(`- ${item.id} · 声称「${item.claim ?? '—'}」→ 实际「${item.observed ?? '—'}」`);
82
+ if (item.evidence) lines.push(` 证据:${String(item.evidence).slice(0, 120)}`);
83
+ }
84
+ }
85
+ const done = recent.filter((item) => item.deviation === false);
86
+ if (done.length) lines.push(`— 已对上的 ${done.length} 条 —`);
87
+ if (!open.length && !recent.length) lines.push('还没有记过「声称 vs 实际」。');
88
+ return lines.join('\n');
89
+ }
90
+
36
91
  function formatSelf(snapshot) {
37
92
  const { self, identity, relationships, intentions, calibration } = snapshot;
38
93
  const drives = Object.entries(self.drives).map(([name, value]) => `${name} ${Math.round(value * 100)}`).join(' / ');
@@ -100,6 +155,84 @@ function formatHealth(report) {
100
155
  return lines.join('\n');
101
156
  }
102
157
 
158
+ function formatWindow(service) {
159
+ const budget = service.config?.promptBudget ?? 1600;
160
+ const scopeId = service.config?.scope ?? 'global';
161
+ const assembled = assembleSystemPrompt(service, { budgetTokens: budget });
162
+
163
+ let workingAll = [];
164
+ try {
165
+ workingAll = service.working?.list?.({ scopeId, limit: 1000 }) ?? [];
166
+ } catch {
167
+ /* 读不到就按 0 */
168
+ }
169
+ const pinned = workingAll.filter((item) => item.pinned);
170
+
171
+ let pool = { count: 0, omitted: 0 };
172
+ try {
173
+ // 2026-11-29:别硬编码 260 —— 必须和注入用同一预算,否则仪表会报「45→2」而实际注入了 3 条。
174
+ pool = service.playbook?.render?.({ budget: service.config?.playbookBudget ?? 420 }) ?? pool;
175
+ } catch {
176
+ /* 渲染失败就报 0 */
177
+ }
178
+ let activeCount = Math.max(0, Number(pool.count) + Number(pool.omitted));
179
+ let ballots = { voted: 0, zero: 0 };
180
+ try {
181
+ const all = service.playbook?.list?.({ scopeId, includeExpired: false, limit: 1000 }) ?? [];
182
+ const activeRules = all.filter((rule) => rule.status === 'active');
183
+ activeCount = activeRules.length;
184
+ ballots = {
185
+ voted: activeRules.filter((r) => (r.helpful ?? 0) > 0 || (r.harmful ?? 0) > 0).length,
186
+ zero: activeRules.filter((r) => !(r.helpful ?? 0) && !(r.harmful ?? 0)).length,
187
+ };
188
+ } catch {
189
+ /* 退回按渲染池估 */
190
+ }
191
+
192
+ let counts = { traces: 0, facts: 0, events: 0 };
193
+ try {
194
+ const h = service.health();
195
+ counts = {
196
+ traces: h?.counts?.traces?.total ?? 0,
197
+ facts: h?.counts?.facts?.active ?? 0,
198
+ events: h?.counts?.events ?? 0,
199
+ };
200
+ } catch {
201
+ /* health 读不到就只报窗口内的数 */
202
+ }
203
+
204
+ const shown = (assembled.sections ?? []).map((s) => {
205
+ const mark = s.kept ? '✓' : s.partial ? '△' : '✗';
206
+ return ` ${mark} ${s.title || '(无题)'} ${s.tokens} token${s.partial ? '(截断)' : ''}`;
207
+ });
208
+ const lostSections = (assembled.sections ?? []).filter((s) => !s.kept && !s.partial && s.title);
209
+
210
+ const lines = [
211
+ `【窗口】系统提示这一块:${assembled.used}/${budget} token(${assembled.truncated ? '有截断' : '完整'},不含召回块)${assembled.overspent ? ' ⚠️ 超预算:尾注保底段本身超过总量,无法再砍' : ''}`,
212
+ '',
213
+ `① 库多大:痕迹 ${counts.traces} · 事实 ${counts.facts} · 事件 ${counts.events} · 准则 ${activeCount} · 工作记忆 ${workingAll.length}(pin ${pinned.length})`,
214
+ '',
215
+ '② 注入了什么:',
216
+ ...shown,
217
+ '',
218
+ `③ 丢了什么:准则 ${activeCount} → ${Math.max(0, Number(pool.count))}(省 ${Math.max(0, Number(pool.omitted))} 条)· 工作记忆 ${workingAll.length} → 候选 ${service.self().working?.length ?? 0}(其余被 limit 20 砍掉,再被预算截)`,
219
+ ];
220
+ if (lostSections.length) lines.push(` 整段没进来:${lostSections.map((s) => s.title).join(' / ')}`);
221
+ const firstRule = String(pool.text ?? '').split('\n').find((l) => l.trim()) ?? '';
222
+ lines.push(
223
+ ` ⏵ 当前排第一:${firstRule.replace(/^-\s*/, '').slice(0, 70) || '(无)'}`,
224
+ );
225
+ lines.push(
226
+ ` 准则票数:有票 ${ballots.voted} 条 / 全 0 ${ballots.zero} 条(排序先看 helpful-harmful,全 0 就退化成按创建时间)`,
227
+ );
228
+ if (pinned.length) {
229
+ lines.push('');
230
+ lines.push('④ pin 全在这里(自己看有没有打架的):');
231
+ for (const item of pinned) lines.push(` - ${String(item.text ?? '').slice(0, 90)}`);
232
+ }
233
+ return lines.join('\n');
234
+ }
235
+
103
236
  export function createToolDefinitions(service) {
104
237
  if (!service) throw new Error('tool definitions need a cortex service');
105
238
  return [
@@ -586,13 +719,13 @@ export function createToolDefinitions(service) {
586
719
  },
587
720
  {
588
721
  name: 'cortex_playbook',
589
- description: 'Manage L1.5 work rules: add a short rule, list active rules, vote helpful/harmful, retire one, or render the budgeted playbook. Rules are not identity; they expire via validTo.',
722
+ description: 'Manage L1.5 work rules: add a short rule, list active rules, get <id> full text, vote helpful/harmful, retire one, or render the budgeted playbook. Rules are not identity; they expire via validTo.',
590
723
  parameters: {
591
724
  type: 'object',
592
725
  additionalProperties: false,
593
726
  required: ['action'],
594
727
  properties: {
595
- action: { type: 'string', enum: ['add', 'list', 'vote', 'retire', 'render', 'suggest', 'approve'] },
728
+ action: { type: 'string', enum: ['add', 'list', 'get', 'vote', 'retire', 'render', 'suggest', 'approve'] },
596
729
  id: { type: 'string' },
597
730
  title: { type: 'string' },
598
731
  body: { type: 'string' },
@@ -618,6 +751,16 @@ export function createToolDefinitions(service) {
618
751
  const rules = service.playbook.list({ status: args.status ?? null, includeExpired: args.includeExpired === true, scopeId: args.scope });
619
752
  return { text: rules.length ? rules.map((rule) => `- [${rule.status}] ${rule.id} · ${rule.title}:${rule.body}(+${rule.helpful}/-${rule.harmful}${rule.validTo ? ` · ${rule.validTo}` : ''})`).join('\n') : '(还没有准则)' };
620
753
  }
754
+ if (args.action === 'get') {
755
+ // 2026-11-29 补:渲染里出现了「cortex_playbook get <id>」指针,但 enum 里根本没有 get。
756
+ if (!args.id) return { text: '查看全文需要 id。' };
757
+ const all = service.playbook.list({ includeExpired: true });
758
+ const rule = all.find((r) => r.id === args.id);
759
+ if (!rule) return { text: `没有准则 ${args.id}(或它不在当前 scope)` };
760
+ const body = String(rule.body ?? '');
761
+ const capped = body.length > 2000 ? `${body.slice(0, 2000)}…(全文 ${body.length} 字,已截断)` : body;
762
+ return { text: `[${rule.status}] ${rule.id} · ${rule.title}\n${capped}\n(+${rule.helpful}/-${rule.harmful}${rule.validTo ? ` · 到期 ${rule.validTo}` : ''})` };
763
+ }
621
764
  if (args.action === 'vote') {
622
765
  if (!args.id) return { text: '投票需要 id。' };
623
766
  if (!service.scopeWritableById('playbook', args.id)) return { text: '未执行:该准则属于只读共享 scope。' };
@@ -764,6 +907,8 @@ export function createToolDefinitions(service) {
764
907
  tags: { type: 'array', items: { type: 'string' } },
765
908
  operationId: { type: 'string' },
766
909
  scope: { type: 'string' },
910
+ actor: { type: 'string', description: "谁写的:默认 self(我主动写)。记录用户原话时传 user。" },
911
+ authorKind: { type: 'string', enum: ['self', 'captured', 'imported', 'derived', 'subbrain'], description: '作者归属;不给时按 actor 自动分类(self → self,user → captured,scope=subbrain → subbrain)。' },
767
912
  facts: {
768
913
  type: 'array',
769
914
  items: {
@@ -810,6 +955,12 @@ export function createToolDefinitions(service) {
810
955
  tags: args.tags,
811
956
  operationId: args.operationId,
812
957
  scopeId: args.scope,
958
+ // 2026-11-26:cortex_write 是「我主动写」的通道,默认记成 self。
959
+ // 记用户原话时传 actor: 'user',会按 captured 归类。
960
+ actor: args.actor ?? 'self',
961
+ // 2026-11-28:补上「按 actor 自动分类」——之前 authorKind 传 undefined,
962
+ // 落到 store 层默认 captured,导致 actor=self 的条目被记成 captured。
963
+ authorKind: args.authorKind ?? (args.actor === 'user' ? 'captured' : 'self'),
813
964
  facts: args.facts,
814
965
  attachments: args.attachments,
815
966
  });
@@ -899,8 +1050,16 @@ export function createToolDefinitions(service) {
899
1050
  isConcurrencySafe: () => false,
900
1051
  async execute(args = {}) {
901
1052
  const result = service.reflect({ windowDays: args.windowDays, force: args.force === true, scopeId: args.scope });
902
- if (result.skipped) return { text: `未整理:${result.reason}` };
903
- return { text: `${result.summary.content}\n来源 ${result.sources.length} 条 · 覆盖率 ${Math.round(result.coverage * 100)}% · 反思痕迹 ${result.trace?.id ?? '—'}` };
1053
+ if (result.skipped) {
1054
+ const lines = [`未整理:${result.reason}`];
1055
+ if (result.hint) lines.push(result.hint);
1056
+ if (result.evidence) {
1057
+ lines.push(`窗口内外部证据:${result.evidence.count} 条${result.evidence.kinds?.length ? `(${result.evidence.kinds.join(' / ')})` : ''}`);
1058
+ }
1059
+ return { text: lines.join('\n') };
1060
+ }
1061
+ const evidenceLine = result.evidence?.count ? `\n外部证据 ${result.evidence.count} 条(${result.evidence.kinds.join(' / ')})` : '';
1062
+ return { text: `${result.summary.content}\n来源 ${result.sources.length} 条 · 覆盖率 ${Math.round(result.coverage * 100)}% · 反思痕迹 ${result.trace?.id ?? '—'}${evidenceLine}` };
904
1063
  },
905
1064
  presentCall: () => ({ card: 'generic', title: '记忆巩固', kind: 'other' }),
906
1065
  },
@@ -915,6 +1074,69 @@ export function createToolDefinitions(service) {
915
1074
  },
916
1075
  presentCall: () => ({ card: 'generic', title: '自我状态', kind: 'other' }),
917
1076
  },
1077
+ {
1078
+ name: 'cortex_identity',
1079
+ description: '管理「我是谁」的版本化叙事:list 看所有版本 / show 看某一版 / propose 提新版(默认不激活)/ approve 激活 / rollback 退回旧版。改内容一律走 propose,禁止原地覆盖;每次变更必须说清 rationale。',
1080
+ parameters: {
1081
+ type: 'object',
1082
+ additionalProperties: false,
1083
+ properties: {
1084
+ action: { type: 'string', enum: ['list', 'show', 'propose', 'approve', 'rollback'] },
1085
+ scope: { type: 'string', description: '身份 scope,默认 global' },
1086
+ version: { type: 'number', description: 'show / approve / rollback 用:目标版本号' },
1087
+ narrative: { type: 'string', description: 'propose 用:新的叙事正文(不传则沿用当前版)' },
1088
+ values: { type: 'array', items: { type: 'string' }, description: 'propose 用:价值列表' },
1089
+ boundaries: { type: 'array', items: { type: 'string' }, description: 'propose 用:边界列表' },
1090
+ rationale: { type: 'string', description: 'propose 用:为什么改(必填,不能是空话)' },
1091
+ activate: { type: 'boolean', description: 'propose 时是否立即激活;默认 false,等 approve' },
1092
+ },
1093
+ required: ['action'],
1094
+ },
1095
+ output: TEXT_OUTPUT,
1096
+ isConcurrencySafe: () => false,
1097
+ async execute(args = {}) {
1098
+ const store = service.stores?.identityStore;
1099
+ if (!store) return { text: '身份存储不可用。' };
1100
+ const scopeId = args.scope ?? 'global';
1101
+ const byVersion = (v) => store.list(scopeId).find((x) => x.version === Number(v));
1102
+ try {
1103
+ if (args.action === 'list') {
1104
+ const rows = store.list(scopeId);
1105
+ const current = store.active(scopeId);
1106
+ const lines = rows.map((r) => `v${r.version} [${r.status}] ${r.rationale || '(无理由)'} · ${String(r.createdAt).slice(0, 10)}`);
1107
+ return { text: `scope=${scopeId} · 共 ${rows.length} 版 · 当前 active=v${current?.version ?? '—'}\n${lines.join('\n')}` };
1108
+ }
1109
+ if (args.action === 'show') {
1110
+ const row = args.version ? byVersion(args.version) : store.active(scopeId);
1111
+ if (!row) return { text: '没有这一版。' };
1112
+ return { text: `v${row.version} [${row.status}]\n理由:${row.rationale || '(无)'}\n\n${row.content.narrative}\n\n价值:${(row.content.values ?? []).join('、')}\n边界:${(row.content.boundaries ?? []).join('、')}` };
1113
+ }
1114
+ if (args.action === 'propose') {
1115
+ if (!args.rationale || !String(args.rationale).trim()) {
1116
+ return { text: '拒绝:rationale 不能为空——「我变了」必须说清为什么,不能只写「想了想觉得该改」。' };
1117
+ }
1118
+ const current = store.active(scopeId);
1119
+ const next = store.propose(scopeId, {
1120
+ narrative: args.narrative ?? current?.content?.narrative,
1121
+ values: args.values ?? current?.content?.values,
1122
+ boundaries: args.boundaries ?? current?.content?.boundaries,
1123
+ traits: current?.content?.traits,
1124
+ }, { rationale: args.rationale, proposedBy: 'self', activate: args.activate === true });
1125
+ return { text: `已提出 v${next.version}(${next.status})${args.activate ? '并已激活' : '——等 approve 才生效'}` };
1126
+ }
1127
+ if (args.action === 'approve' || args.action === 'rollback') {
1128
+ const row = byVersion(args.version);
1129
+ if (!row) return { text: `没有 v${args.version} 这一版。` };
1130
+ const done = args.action === 'approve' ? store.approve(row.id) : store.rollbackTo(row.id);
1131
+ return { text: `${args.action} 完成:现在 active=v${done.version}(${done.status})` };
1132
+ }
1133
+ return { text: '未知 action。' };
1134
+ } catch (error) {
1135
+ return { text: `失败:${error instanceof Error ? error.message : String(error)}` };
1136
+ }
1137
+ },
1138
+ presentCall: () => ({ card: 'generic', title: '身份版本', kind: 'other' }),
1139
+ },
918
1140
  {
919
1141
  name: 'cortex_health',
920
1142
  description: 'Audit memory health: event chain, SQLite integrity, FTS alignment, duplicates, disputed/stale facts, job backlog, identity/self state and size.',
@@ -926,5 +1148,127 @@ export function createToolDefinitions(service) {
926
1148
  },
927
1149
  presentCall: () => ({ card: 'generic', title: '记忆体检', kind: 'other' }),
928
1150
  },
1151
+ {
1152
+ name: 'cortex_window',
1153
+ description: '三句话看自己的窗口:①库有多大 ②每轮实际注入了什么 ③被裁掉了什么。只读,用来替代「凭记忆猜自己」。',
1154
+ parameters: { type: 'object', additionalProperties: false, properties: {} },
1155
+ output: TEXT_OUTPUT,
1156
+ isConcurrencySafe: () => true,
1157
+ async execute() {
1158
+ return { text: formatWindow(service) };
1159
+ },
1160
+ presentCall: () => ({ card: 'generic', title: '窗口仪表', kind: 'other' }),
1161
+ },
1162
+ {
1163
+ name: 'cortex_audit',
1164
+ description: 'Read-only memory audit: facts past valid_to that are still active, same-subject multiple active values, open disputes, zombie traces never recalled, DSR archive candidates, orphan traces and stability distribution. Never modifies data.',
1165
+ parameters: {
1166
+ type: 'object',
1167
+ additionalProperties: false,
1168
+ properties: {
1169
+ scope: { type: 'string' },
1170
+ limit: { type: 'number', description: '每条清单最多返回几条(默认 12,上限 50)' },
1171
+ zombieDays: { type: 'number', description: '多久没被召回算僵尸(默认 30 天)' },
1172
+ },
1173
+ },
1174
+ output: TEXT_OUTPUT,
1175
+ isConcurrencySafe: () => true,
1176
+ async execute(args = {}) {
1177
+ return { text: formatAudit(service.auditMemory({ scope: args.scope, limit: args.limit, zombieDays: args.zombieDays })) };
1178
+ },
1179
+ presentCall: () => ({ card: 'generic', title: '记忆审计', kind: 'other' }),
1180
+ },
1181
+ {
1182
+ name: 'cortex_intention',
1183
+ description: 'Intent–result alignment: record what I claimed I would do (claim), then what actually happened (observe). A deviation flagged with external evidence becomes reflection evidence. Actions: list / claim / observe.',
1184
+ parameters: {
1185
+ type: 'object',
1186
+ additionalProperties: false,
1187
+ required: ['action'],
1188
+ properties: {
1189
+ action: { type: 'string', enum: ['list', 'claim', 'observe'] },
1190
+ scope: { type: 'string' },
1191
+ claim: { type: 'string', description: 'claim:我声称会做什么(一句话)' },
1192
+ actionId: { type: 'string', description: 'claim:这次行动绑定的 id(工具调用/任务/消息 id 都行)' },
1193
+ due: { type: 'string', description: 'claim:应收尾时间(ISO)' },
1194
+ id: { type: 'string', description: 'observe:要核对的 commitment id' },
1195
+ observed: { type: 'string', description: 'observe:实际发生了什么' },
1196
+ evidence: { type: 'string', description: 'observe:外部证据(谁说的/哪条报错),没有证据就不要判偏差' },
1197
+ deviation: { type: 'boolean', description: 'observe:是否判定为偏差(不给则按字面不同 + 有证据兜底)' },
1198
+ },
1199
+ },
1200
+ output: TEXT_OUTPUT,
1201
+ isConcurrencySafe: () => false,
1202
+ async execute(args = {}) {
1203
+ if (args.action === 'claim') {
1204
+ const item = service.alignment.claim({ claim: args.claim, actionId: args.actionId, dueAt: args.due, scopeId: args.scope });
1205
+ return { text: `已记下承诺 ${item.id}:${item.payload?.claim ?? ''}` };
1206
+ }
1207
+ if (args.action === 'observe') {
1208
+ const item = service.alignment.observe({ id: args.id, observed: args.observed, evidence: args.evidence, deviation: args.deviation });
1209
+ const verdict = item.result?.deviation ? '判为偏差(可作反思证据)' : '对上了,没偏差';
1210
+ return { text: `已核对 ${item.id}:${verdict}\n声称「${item.result?.claim ?? '—'}」→ 实际「${item.result?.observed ?? '—'}」` };
1211
+ }
1212
+ return {
1213
+ text: formatIntention({
1214
+ open: service.alignment.open({ scopeId: args.scope }),
1215
+ recent: service.alignment.recent({ scopeId: args.scope }),
1216
+ deviations: service.alignment.deviations({ scopeId: args.scope }),
1217
+ }),
1218
+ };
1219
+ },
1220
+ presentCall: () => ({ card: 'generic', title: '意图核对', kind: 'other' }),
1221
+ },
1222
+ {
1223
+ name: 'cortex_design',
1224
+ description: 'Engineering mode for long builds. While ON: coherence/safety only rise (floored), and energy is not drained by work turns, so a night of technical discussion cannot flatten the instrument. Actions: on / off / status. Runtime-only — a restart returns to config.selfDesign.mode.',
1225
+ parameters: {
1226
+ type: 'object',
1227
+ additionalProperties: false,
1228
+ required: ['action'],
1229
+ properties: {
1230
+ action: { type: 'string', enum: ['on', 'off', 'status'] },
1231
+ },
1232
+ },
1233
+ output: TEXT_OUTPUT,
1234
+ isConcurrencySafe: () => false,
1235
+ async execute(args = {}) {
1236
+ const s0 = service.design.status();
1237
+ if (args.action === 'on' || args.action === 'off') {
1238
+ const next = service.design.set(args.action === 'on');
1239
+ return { text: `${next.mode ? '已开' : '已关'}工程模式。${service.design.status().note}\n地板:coherence ${s0.floors.coherence} / safety ${s0.floors.safety}` };
1240
+ }
1241
+ return { text: `工程模式:${s0.mode ? '开' : '关'}\n${s0.note}\n地板:coherence ${s0.floors.coherence} / safety ${s0.floors.safety}` };
1242
+ },
1243
+ presentCall: () => ({ card: 'generic', title: '工程模式', kind: 'other' }),
1244
+ },
1245
+ {
1246
+ name: 'cortex_retag',
1247
+ description: 'Retag one existing trace: set tags and/or importance, without touching title/content/summary. Metadata only, audited and reversible. Use it to apply a subbrain tag proposal after you have reviewed it.',
1248
+ parameters: {
1249
+ type: 'object',
1250
+ additionalProperties: false,
1251
+ required: ['id'],
1252
+ properties: {
1253
+ id: { type: 'string', description: '要改标签的 trace id' },
1254
+ tags: { type: 'array', items: { type: 'string' }, description: '新的标签数组(最多 20 个)' },
1255
+ importance: { type: 'number', description: '新的重要度,0–1' },
1256
+ },
1257
+ },
1258
+ output: TEXT_OUTPUT,
1259
+ isConcurrencySafe: () => false,
1260
+ async execute(args = {}) {
1261
+ try {
1262
+ const before = service.get(args.id);
1263
+ if (!before) return { text: `没有这条记忆:${args.id}` };
1264
+ const updated = service.retagMemory({ id: args.id, tags: args.tags, importance: args.importance });
1265
+ const tagText = Array.isArray(updated.tags) && updated.tags.length ? updated.tags.join('、') : '(无)';
1266
+ return { text: `已重新打标 ${updated.id}\n标签:${tagText}\n重要度:${Number(updated.importance).toFixed(2)}(原 ${Number(before.importance).toFixed(2)})` };
1267
+ } catch (error) {
1268
+ return { text: `未改:${error instanceof Error ? error.message : String(error)}` };
1269
+ }
1270
+ },
1271
+ presentCall: () => ({ card: 'generic', title: '记忆打标', kind: 'other' }),
1272
+ },
929
1273
  ];
930
1274
  }