mocode-ai 1.9.3 → 1.9.5

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.
package/README.md CHANGED
@@ -41,7 +41,7 @@ MoCode keeps code-level control light and leaves task strategy to the agent:
41
41
  - **Advisory working discipline** — The system prompt asks the agent to make focused changes, avoid redundant retrieval, and decide for itself whether validation is useful. Validation is optional and is never a completion gate.
42
42
  - **Bounded tool retries, explicit failures** — The runtime automatically retries only transient errors from tools explicitly marked `idempotent`, at most twice. `TIMEOUT`, permission denial, cancellation, and non-idempotent calls are not automatically retried. The resulting structured outcome is returned to the agent for any further recovery decision; see [Automatic retry](#automatic-retry-the-retryable-contract).
43
43
  - **`ask_human` for user-owned decisions** — The agent must ask before any decision the user has not made (multiple reasonable approaches) and before key modifications (public APIs, schemas, dependencies, file moves/deletes, architecture, security, large or irreversible changes). Only trivial, repository-precedent details are decided alone.
44
- - **Five-zone context controls + token self-calibration** — Five independent dials (`autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget`) manage context pressure. Token estimation self-calibrates against provider usage.
44
+ - **Five independent context dials + token self-calibration** — `autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget` each manage one layer of context pressure. Triggering is a single threshold — request occupancy (raw or corrected, whichever is larger) at 80% of the window — not a per-zone quota: a zone being over its share never rewrites anything on its own. Token estimation self-calibrates against provider usage.
45
45
 
46
46
  ## Architecture
47
47
 
package/README.zh-CN.md CHANGED
@@ -93,7 +93,7 @@ mocode 把代码层控制保持得尽量轻,把任务策略交给 agent:
93
93
  - **建议式工作纪律** — system prompt 只要求聚焦改动、避免重复检索、诚实报告不确定性;是否验证及验证范围由 agent 自主决定,不是完成硬门。
94
94
  - **有界重试,明确报告失败** — runtime 仅对显式声明 `idempotent` 的工具瞬时错误自动重试,最多两次;`TIMEOUT`、权限拒绝、中断和非幂等调用不自动重试。最终结构化结果交给 agent,由其决定后续恢复方式,详见[自动重试](#自动重试retryable-契约)。
95
95
  - **ask_human 决策与关键修改先问** — 用户尚未做出的决策(存在多个合理方案)和关键修改(公共 API、schema、依赖、文件移动/删除、架构、安全、大范围或不可逆改动)必须先询问用户;只有符合仓库惯例的琐碎细节才由 agent 自行决定。
96
- - **五区上下文控制 + token 自校准** — 独立旋钮管理上下文压力,token 估算根据真实 provider 用量校准。
96
+ - **五个独立的上下文旋钮 + token 自校准** — `autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget` 各管一层上下文压力。触发条件是单一阈值:请求占用(裸估算与校正后取大者)到达窗口的 80%,不是分区配额——某个分区超配额本身不会改写任何内容。token 估算根据真实 provider 用量校准。
97
97
 
98
98
  ## 为什么用 mocode
99
99
 
@@ -1,28 +1,17 @@
1
- // 五区 Context Budget accounting and the shared pressure threshold.
1
+ // Context Budget accounting and the shared pressure threshold.
2
2
  //
3
3
  // This module only estimates and reports. session/scheduler.ts owns the sole
4
4
  // automatic rewrite sequence and starts all pressure cleanup plus compact_history
5
5
  // when corrected or raw request occupancy reaches 80%.
6
- import { chatTools, estimateMessagesTokens, estimateToolSchemaTokens, messageTokens } from '../llm/index.js';
6
+ //
7
+ // 产出只有四个标量:total / rawTotal / window / hotBoundary(外加 systemCosts 拆分)。
8
+ // 曾经这里还有一套「五区分账」(system/history/toolRecent/toolOld/summary/reserve 各自的
9
+ // ratio 与 overBudget/overRatio),但它的全部产物只流向一个无人调用的 formatReport(),
10
+ // 调度器从头到尾只看总阈值 —— 留着会让后来的人以为改 ratios 能改变压缩行为,实际零影响。
11
+ // 2026-11 已删除,避免误判。
12
+ import { chatTools, estimateToolSchemaTokens, messageTokens } from '../llm/index.js';
7
13
  import { toText } from './utils.js';
8
- /** 五区分账(占比对齐 CONTEXT_WINDOW)。顺序固定,便于遍历。 */
9
- export const BUDGET_LAYERS = [
10
- 'system',
11
- 'history',
12
- 'toolRecent', // Hot Tool
13
- 'toolOld', // Cold Tool
14
- 'summary',
15
- 'reserve', // Reserve(不占内容,只占预算分配;5%)
16
- ];
17
14
  export const DEFAULT_BUDGET_POLICY = {
18
- ratios: {
19
- system: 0.15,
20
- history: 0.2,
21
- toolRecent: 0.25,
22
- toolOld: 0.25,
23
- summary: 0.1,
24
- reserve: 0.05,
25
- },
26
15
  hotTurnWindow: 4,
27
16
  // 压缩保留区:自动 15% / 强压 5%,且绝对上限 48k——摘要+最近几轮足够续工,
28
17
  // 旧 0.40 在大窗口下导致"160k 压到 100k"的无效压缩。
@@ -30,12 +19,8 @@ export const DEFAULT_BUDGET_POLICY = {
30
19
  compactForceKeepRatio: 0.05,
31
20
  compactKeepMaxTokens: 48000,
32
21
  pressureTriggerRatio: 0.8,
33
- schedulerTargetRatio: 0.8,
34
- estimateSafetyFactor: 1.05,
35
- compactHeadroomTokens: 1500,
36
22
  };
37
23
  /** 兼容既有调用方的只读别名;配置只在 DEFAULT_BUDGET_POLICY 中维护。 */
38
- export const BUDGET_RATIO = DEFAULT_BUDGET_POLICY.ratios;
39
24
  export const HOT_TURN_WINDOW = DEFAULT_BUDGET_POLICY.hotTurnWindow;
40
25
  function msgTokens(m) {
41
26
  // 与请求预估复用同一实现,避免角色结构开销、多模态和 tool_calls 在两个预算路径中漂移。
@@ -55,20 +40,17 @@ export function userTurnBoundary(history, window) {
55
40
  }
56
41
  return 1; // 没攒够 N 个 user 之前的全归 Cold(history[0] system 不动)
57
42
  }
58
- /** 评估当前 history 的五区预算(纯函数,改不动 history)。
43
+ /** 评估当前 history 的请求占用(纯函数,改不动 history)。
59
44
  * 传入 step 是当前所在 step 编号(agent 循环 step 变量),用于日志/调试。
60
45
  * correction:API 实测 / 估算的校正系数(默认 1);>1 表示粗估偏低,乘以系数后 actual 更接近真实值。
61
46
  * activeTools 必须与下一次 chat() 实际发送的工具集合一致,避免 plan/子 agent 误算 schema。
62
47
  * ephemeralTokens:本次请求会追加、但不在 history 里的尾部注入(会话状态提醒等)的裸 token,
63
48
  * 必须传入,否则压力线看不见这部分开销(见 SystemCostBreakdown.ephemeral)。 */
64
49
  export function evaluateBudget(history, window, step = 0, correction = 1, activeTools = chatTools, ephemeralTokens = 0) {
65
- const layers = {};
66
- for (const k of BUDGET_LAYERS) {
67
- const budget = Math.floor(BUDGET_RATIO[k] * window);
68
- layers[k] = { actual: 0, budget, overBudget: false, overRatio: 0 };
69
- }
70
50
  // 校正后的 token 数:raw * correction,最小 1(raw > 0 时)。
71
51
  const adj = (raw) => (raw > 0 ? Math.max(1, Math.round(raw * correction)) : 0);
52
+ // 校正后总量:逐段累加,不再先分桶再求和。
53
+ let total = 0;
72
54
  // 裸总量(不乘 correction):硬闸用它判断,防止 correction 折扣否决真实溢出。
73
55
  let rawTotal = 0;
74
56
  const sysMsg = history[0];
@@ -81,7 +63,7 @@ export function evaluateBudget(history, window, step = 0, correction = 1, active
81
63
  // 工具 schema、system prompt 与尾部 ephemeral 注入同属请求固定开销;
82
64
  // 必须计入总量才能可靠触发压缩(尾部注入不在 history 里,只能由调用方传入)。
83
65
  const systemRaw = systemCosts.prompt + systemCosts.toolSchemas + systemCosts.ephemeralInjection;
84
- layers.system.actual = adj(systemRaw);
66
+ total += adj(systemRaw);
85
67
  rawTotal += systemRaw;
86
68
  // Summary 检测:role:'system' 且不是 history[0] 的,视为摘要(compact.ts 摘要插 index 1)。
87
69
  // 简单启发:若 history[1]?.role === 'system' 且 content 含「# 会话摘要」特征串,计入 summary。
@@ -91,55 +73,31 @@ export function evaluateBudget(history, window, step = 0, correction = 1, active
91
73
  const c1 = toText(history[1].content);
92
74
  if (c1.startsWith('# 会话摘要') || c1.includes('会话摘要')) {
93
75
  const summaryRaw = msgTokens(history[1]);
94
- layers.summary.actual = adj(summaryRaw);
76
+ total += adj(summaryRaw);
95
77
  rawTotal += summaryRaw;
96
78
  summaryHit = true;
97
79
  }
98
80
  }
99
81
  // 划 Hot/Cold 边界
100
82
  const hotStart = userTurnBoundary(history, HOT_TURN_WINDOW);
101
- // history 区 = 减去 summary + tool 单算;tool 按 Hot/Cold 分。
83
+ // tool / user / assistant 一并计入总量(冷热区划分只用于决定改写范围,不影响总量)。
102
84
  for (let i = 1; i < history.length; i++) {
103
85
  const m = history[i];
104
86
  if (i === 1 && summaryHit)
105
87
  continue; // summary 已单独算过
88
+ if (m.role === 'system')
89
+ continue; // 其它 system(几乎不存在)跳过
106
90
  const raw = msgTokens(m);
107
- if (m.role === 'tool') {
108
- if (i >= hotStart)
109
- layers.toolRecent.actual += adj(raw);
110
- else
111
- layers.toolOld.actual += adj(raw);
112
- rawTotal += raw;
113
- }
114
- else if (m.role !== 'system') {
115
- // user / assistant 全部计入 history(对话轨迹)
116
- layers.history.actual += adj(raw);
117
- rawTotal += raw;
118
- }
119
- // 其它 system(几乎不存在)跳过
120
- }
121
- // 计算 overBudget + overRatio
122
- const triggers = [];
123
- for (const k of BUDGET_LAYERS) {
124
- const lb = layers[k];
125
- if (lb.actual > lb.budget) {
126
- lb.overBudget = true;
127
- lb.overRatio = (lb.actual - lb.budget) / Math.max(lb.budget, 1);
128
- triggers.push(k);
129
- }
91
+ total += adj(raw);
92
+ rawTotal += raw;
130
93
  }
131
- // 按 overRatio 降序
132
- triggers.sort((a, b) => layers[b].overRatio - layers[a].overRatio);
133
- const total = BUDGET_LAYERS.reduce((s, k) => s + (k === 'reserve' ? 0 : layers[k].actual), 0);
134
94
  const totalOver = total >= DEFAULT_BUDGET_POLICY.pressureTriggerRatio * window;
135
95
  return {
136
96
  step,
137
97
  total,
138
98
  rawTotal,
139
99
  window,
140
- layers,
141
100
  systemCosts,
142
- triggers,
143
101
  totalOver,
144
102
  hotBoundary: hotStart,
145
103
  correction,
@@ -147,7 +105,7 @@ export function evaluateBudget(history, window, step = 0, correction = 1, active
147
105
  }
148
106
  /** 根据 BudgetReport 生成可执行动作。
149
107
  * History compaction is the final fallback after pressure-only tool stages.
150
- * Per-layer overages are diagnostics, never independent rewrite triggers. */
108
+ * 唯一判定条件是总占用(裸估或校正后的较大者)过 80% 压力线。 */
151
109
  export function scheduleActions(report) {
152
110
  const actions = [];
153
111
  const pressureLine = DEFAULT_BUDGET_POLICY.pressureTriggerRatio * report.window;
@@ -156,23 +114,3 @@ export function scheduleActions(report) {
156
114
  }
157
115
  return actions;
158
116
  }
159
- /** 拍平成人类可读(供 /context 命令与 check-budget 脚本用)。 */
160
- export function formatReport(report) {
161
- const lines = [];
162
- lines.push(`step ${report.step} total ${report.total}/${report.window} (${((report.total / report.window) * 100).toFixed(1)}%) raw ${report.rawTotal}`);
163
- for (const k of BUDGET_LAYERS) {
164
- const lb = report.layers[k];
165
- const pct = lb.budget > 0 ? ((lb.actual / lb.budget) * 100).toFixed(0) : '-';
166
- const flag = lb.overBudget ? '⚠' : ' ';
167
- lines.push(` ${flag} ${k.padEnd(10)} ${String(lb.actual).padStart(6)} / ${String(lb.budget).padStart(6)} (${pct.padStart(3)}%)`);
168
- }
169
- if (report.triggers.length > 0) {
170
- lines.push(` triggers: ${report.triggers.join(' → ')}`);
171
- }
172
- return lines.join('\n');
173
- }
174
- /** 便捷:把 history 一把估成总 token 数(给 cap.js 等复用,避免重复实现)。
175
- * 注意:此处是粗估(只看 content 长度),不区分五区——只用于「系统层整体还剩多少」快查。 */
176
- export function quickEstimate(history) {
177
- return estimateMessagesTokens(history);
178
- }
@@ -6,4 +6,4 @@ export { classify, knownToolKinds } from './classifier.js';
6
6
  export { recordArtifact, invalidateArtifacts, rehydrateArtifacts, refreshArtifactFreshness, pruneStaleArtifacts, collectArtifactRefs, formatArtifactTokenSources, knownEditTargets, } from './artifacts.js';
7
7
  export { registerEncoder, registerAll, getEncoder, registeredKinds } from './registry.js';
8
8
  // ── Context Budget Scheduler ───────────────────────────────────────────────
9
- export { evaluateBudget, scheduleActions, formatReport, quickEstimate, userTurnBoundary, BUDGET_LAYERS, DEFAULT_BUDGET_POLICY, BUDGET_RATIO, HOT_TURN_WINDOW, } from './budget.js';
9
+ export { evaluateBudget, scheduleActions, userTurnBoundary, DEFAULT_BUDGET_POLICY, HOT_TURN_WINDOW } from './budget.js';
package/dist/headless.js CHANGED
@@ -29,6 +29,7 @@ import { buildEpisodeSection, collectChangedFiles, extractCompactionSummary, rec
29
29
  import { flushProactiveStats } from './memory/proactive.js';
30
30
  import { flushTurnRecallStats, buildTurnRecallSection, isTurnRecallEnabled } from './memory/turn-recall.js';
31
31
  import { writeMemoryHealth } from './memory/health.js';
32
+ import { pruneAdoptionLedger } from './memory/adoption.js';
32
33
  import { defaultRuntime, Runtime } from './runtime/index.js';
33
34
  import { runAgentCore } from './agent/core.js';
34
35
  import { summarizeToolCall, summarizeToolResult } from './ui/render.js';
@@ -308,6 +309,7 @@ export async function runHeadless(opts) {
308
309
  flushProactiveStats();
309
310
  // R18:一次性执行的静默召回计数同样落盘,否则 `mocode -p` 那一侧永远空白。
310
311
  flushTurnRecallStats();
312
+ pruneAdoptionLedger();
311
313
  writeMemoryHealth(memoryOn);
312
314
  await runtime.close();
313
315
  if (wt) {
@@ -11,6 +11,7 @@ const zhCN = {
11
11
  'commands.skills': '列出已发现的 skill',
12
12
  'commands.compact': '压缩历史(可带焦点 /compact …)',
13
13
  'commands.usage': '跨工作空间按天统计 token 用量(/usage [天数])',
14
+ 'commands.usageOverview': '查看最近 7 天 token 用量(可 /usage 30 改天数)',
14
15
  'commands.usageImport': '回填各工作区历史会话的 token 用量(幂等)',
15
16
  'commands.session': '会话恢复与回滚',
16
17
  'commands.sessionResume': '续接最近 10 个已保存会话(快速)',
@@ -189,6 +190,9 @@ const zhCN = {
189
190
  'repl.forkDone': '已分叉出新会话 {id}(继承全部上下文,与原会话独立)',
190
191
  'repl.forkHint': '本窗口仍在原会话;新终端执行 mocode --resume {id},或在本窗口 /resume 选择该会话',
191
192
  'repl.usageTitle': 'Token 用量(全局 · {from} ~ {to} · {days} 天)',
193
+ 'repl.usageBarsNote': '按天用量(对数刻度;柱高看相对趋势,精确值见高峰日与排行)',
194
+ 'repl.usageBarsBucket': '每柱聚合 {span} 天',
195
+ 'repl.usagePeaks': '高峰日:{days}',
192
196
  'repl.usageKMetric': '指标',
193
197
  'repl.usageKValue': '数值',
194
198
  'repl.usageKTotal': '总用量',
@@ -202,18 +206,12 @@ const zhCN = {
202
206
  'repl.usageKCacheWrite': '缓存写入',
203
207
  'repl.usageKDailyAvg': '日均用量',
204
208
  'repl.usageKCompact': '其中压缩(compact)',
205
- 'repl.usageColDate': '日期',
206
209
  'repl.usageColWorkspace': '工作空间',
207
210
  'repl.usageColModel': '模型',
208
211
  'repl.usageColIn': '输入',
209
212
  'repl.usageColOut': '输出',
210
- 'repl.usageColCached': '缓存命中',
211
- 'repl.usageColReason': '推理',
212
213
  'repl.usageColCalls': '请求数',
213
- 'repl.usageColHit': '命中率',
214
214
  'repl.usageColSessions': '会话数',
215
- 'repl.usageEmptyDay': '(无用量)',
216
- 'repl.usageTotalRow': '合计',
217
215
  'repl.usageByWorkspace': '按工作空间',
218
216
  'repl.usageByModel': '按模型',
219
217
  'repl.usageMore': '… 其余 {n} 项已省略',
@@ -325,6 +323,7 @@ const zhCN = {
325
323
  'status.queued': '排队 ·',
326
324
  'status.queuedCount': '排队 ×{count} ·',
327
325
  'status.queuePlanTag': '(Plan)',
326
+ 'status.planMoreSteps': '还有 {count} 步',
328
327
  'status.measured': '实测',
329
328
  'status.estimated': '估算',
330
329
  'status.messages': '{count} 条消息',
@@ -522,6 +521,7 @@ const en = {
522
521
  'commands.skills': 'List discovered skills',
523
522
  'commands.compact': 'Compact history (optional focus: /compact …)',
524
523
  'commands.usage': 'Cross-workspace daily token usage (/usage [days])',
524
+ 'commands.usageOverview': 'Show token usage for the last 7 days (try /usage 30)',
525
525
  'commands.usageImport': 'Backfill token usage from historical sessions (idempotent)',
526
526
  'commands.session': 'Resume sessions and roll back turns',
527
527
  'commands.sessionResume': 'Resume one of the 10 latest saved sessions',
@@ -695,6 +695,9 @@ const en = {
695
695
  'repl.forkDone': 'Forked new session {id} (inherits full context; independent from the original)',
696
696
  'repl.forkHint': 'This window stays on the original session; run mocode --resume {id} in a new terminal, or use /resume here',
697
697
  'repl.usageTitle': 'Token usage (global · {from} ~ {to} · {days}d)',
698
+ 'repl.usageBarsNote': 'Daily usage (log scale; bar height shows relative trend, see peaks and rankings for values)',
699
+ 'repl.usageBarsBucket': 'each bar aggregates {span} days',
700
+ 'repl.usagePeaks': 'Peak days: {days}',
698
701
  'repl.usageKMetric': 'Metric',
699
702
  'repl.usageKValue': 'Value',
700
703
  'repl.usageKTotal': 'Total tokens',
@@ -708,18 +711,12 @@ const en = {
708
711
  'repl.usageKCacheWrite': 'Cache write',
709
712
  'repl.usageKDailyAvg': 'Daily average',
710
713
  'repl.usageKCompact': 'of which compact',
711
- 'repl.usageColDate': 'Date',
712
714
  'repl.usageColWorkspace': 'Workspace',
713
715
  'repl.usageColModel': 'Model',
714
716
  'repl.usageColIn': 'Input',
715
717
  'repl.usageColOut': 'Output',
716
- 'repl.usageColCached': 'Cached',
717
- 'repl.usageColReason': 'Reasoning',
718
718
  'repl.usageColCalls': 'Requests',
719
- 'repl.usageColHit': 'Hit rate',
720
719
  'repl.usageColSessions': 'Sessions',
721
- 'repl.usageEmptyDay': '(no usage)',
722
- 'repl.usageTotalRow': 'Total',
723
720
  'repl.usageByWorkspace': 'By workspace',
724
721
  'repl.usageByModel': 'By model',
725
722
  'repl.usageMore': '… {n} more hidden',
@@ -830,6 +827,7 @@ const en = {
830
827
  'status.queued': 'queued ·',
831
828
  'status.queuedCount': 'queued ×{count} ·',
832
829
  'status.queuePlanTag': ' (Plan)',
830
+ 'status.planMoreSteps': '{count} more step(s)',
833
831
  'status.measured': 'measured',
834
832
  'status.estimated': 'estimated',
835
833
  'status.messages': '{count} messages',
@@ -0,0 +1,326 @@
1
+ // adoption.ts —— R19 记忆送达/采纳观测账本。
2
+ //
3
+ // 这不是记忆库,也不参与检索、注入或排序。它只回答一件事:某条已送达的记忆,
4
+ // 后续是否真的影响了 agent 的决策。评估是既有反思/压缩调用的副产物;无评估时保留
5
+ // pending,绝不因为“没被提及”就把它判成未采纳。
6
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
7
+ import path from 'node:path';
8
+ import { getCurrentSessionId } from '../session/state.js';
9
+ import { memoryWriteBlockReason } from './write-gate.js';
10
+ const RETAIN_DAYS = 90;
11
+ const MAX_REASON_CHARS = 120;
12
+ const MAX_PENDING_FOR_EVALUATION = 12;
13
+ const CHANNELS = [
14
+ 'proactive_trigger',
15
+ 'proactive_anchor',
16
+ 'anchor_read',
17
+ 'turn_recall',
18
+ 'memory_tail',
19
+ ];
20
+ let serial = 0;
21
+ function ledgerPath() {
22
+ return path.join(process.cwd(), '.mocode', 'memory-adoption.jsonl');
23
+ }
24
+ function summaryPath() {
25
+ return path.join(process.cwd(), '.mocode', 'memory-adoption-summary.json');
26
+ }
27
+ function emptyStats() {
28
+ return {
29
+ delivered: 0,
30
+ suppressed: 0,
31
+ evaluated: 0,
32
+ adopted: 0,
33
+ notApplicable: 0,
34
+ unclear: 0,
35
+ pending: 0,
36
+ byChannel: {
37
+ proactive_trigger: 0,
38
+ proactive_anchor: 0,
39
+ anchor_read: 0,
40
+ turn_recall: 0,
41
+ memory_tail: 0,
42
+ },
43
+ suppressedByReason: {},
44
+ };
45
+ }
46
+ function isChannel(value) {
47
+ return typeof value === 'string' && CHANNELS.includes(value);
48
+ }
49
+ function isVerdict(value) {
50
+ return value === 'adopted' || value === 'not_applicable' || value === 'unclear';
51
+ }
52
+ function readLedger() {
53
+ try {
54
+ if (!existsSync(ledgerPath()))
55
+ return [];
56
+ const out = [];
57
+ for (const line of readFileSync(ledgerPath(), 'utf8').split(/\r?\n/)) {
58
+ if (!line.trim())
59
+ continue;
60
+ try {
61
+ const e = JSON.parse(line);
62
+ if (!e ||
63
+ typeof e.id !== 'string' ||
64
+ typeof e.at !== 'string' ||
65
+ typeof e.memoryId !== 'string' ||
66
+ !isChannel(e.channel))
67
+ continue;
68
+ if (e.kind !== 'delivered' && e.kind !== 'suppressed' && e.kind !== 'evaluated')
69
+ continue;
70
+ if (e.kind === 'evaluated' && (!e.deliveryId || !isVerdict(e.verdict)))
71
+ continue;
72
+ out.push(e);
73
+ }
74
+ catch {
75
+ // 单行损坏不应让健康报告和反思都失效。
76
+ }
77
+ }
78
+ return out;
79
+ }
80
+ catch {
81
+ return [];
82
+ }
83
+ }
84
+ function readSummary() {
85
+ try {
86
+ const raw = JSON.parse(readFileSync(summaryPath(), 'utf8'));
87
+ if (!raw || raw.schemaVersion !== 1 || !raw.totals)
88
+ return null;
89
+ const totals = emptyStats();
90
+ for (const key of ['delivered', 'suppressed', 'evaluated', 'adopted', 'notApplicable', 'unclear']) {
91
+ const n = raw.totals[key];
92
+ totals[key] = typeof n === 'number' && n >= 0 ? Math.floor(n) : 0;
93
+ }
94
+ for (const channel of CHANNELS) {
95
+ const n = raw.totals.byChannel?.[channel];
96
+ totals.byChannel[channel] = typeof n === 'number' && n >= 0 ? Math.floor(n) : 0;
97
+ }
98
+ for (const [reason, n] of Object.entries(raw.totals.suppressedByReason ?? {})) {
99
+ if (typeof n === 'number' && n >= 0)
100
+ totals.suppressedByReason[reason] = Math.floor(n);
101
+ }
102
+ return { schemaVersion: 1, updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : '', totals };
103
+ }
104
+ catch {
105
+ return null;
106
+ }
107
+ }
108
+ function summarize(events) {
109
+ const out = emptyStats();
110
+ const delivered = new Set();
111
+ const evaluated = new Set();
112
+ for (const e of events) {
113
+ if (e.kind === 'delivered') {
114
+ delivered.add(e.id);
115
+ out.delivered++;
116
+ out.byChannel[e.channel]++;
117
+ }
118
+ else if (e.kind === 'suppressed') {
119
+ out.suppressed++;
120
+ if (e.reason)
121
+ out.suppressedByReason[e.reason] =
122
+ (out.suppressedByReason[e.reason] ?? 0) + 1;
123
+ }
124
+ else {
125
+ evaluated.add(e.deliveryId);
126
+ out.evaluated++;
127
+ if (e.verdict === 'adopted')
128
+ out.adopted++;
129
+ else if (e.verdict === 'not_applicable')
130
+ out.notApplicable++;
131
+ else
132
+ out.unclear++;
133
+ }
134
+ }
135
+ out.pending = [...delivered].filter((id) => !evaluated.has(id)).length;
136
+ return out;
137
+ }
138
+ function mergeStats(target, add) {
139
+ for (const key of ['delivered', 'suppressed', 'evaluated', 'adopted', 'notApplicable', 'unclear'])
140
+ target[key] += add[key];
141
+ for (const channel of CHANNELS)
142
+ target.byChannel[channel] += add.byChannel[channel];
143
+ for (const [reason, count] of Object.entries(add.suppressedByReason)) {
144
+ target.suppressedByReason[reason] =
145
+ (target.suppressedByReason[reason] ?? 0) + count;
146
+ }
147
+ }
148
+ function append(event) {
149
+ if (memoryWriteBlockReason())
150
+ return null;
151
+ const now = new Date().toISOString();
152
+ const id = `adopt-${now.replace(/[-:.TZ]/g, '')}-${++serial}`;
153
+ const record = {
154
+ id,
155
+ at: now,
156
+ ...(getCurrentSessionId() ? { sessionId: getCurrentSessionId() } : {}),
157
+ ...event,
158
+ };
159
+ try {
160
+ const p = ledgerPath();
161
+ mkdirSync(path.dirname(p), { recursive: true });
162
+ appendFileSync(p, JSON.stringify(record) + '\n', 'utf8');
163
+ return id;
164
+ }
165
+ catch {
166
+ return null;
167
+ }
168
+ }
169
+ /** 记录一条真正进入模型上下文或工具结果的记忆。 */
170
+ export function recordMemoryDelivery(memoryId, channel) {
171
+ if (!memoryId)
172
+ return null;
173
+ return append({ memoryId, channel, kind: 'delivered' });
174
+ }
175
+ /** 记录命中但被限流/去重治理挡住的记忆;它从未进入采纳分母。 */
176
+ export function recordMemorySuppression(memoryId, channel, reason) {
177
+ if (!memoryId)
178
+ return;
179
+ append({ memoryId, channel, kind: 'suppressed', reason });
180
+ }
181
+ /** 当前会话里等待既有反思/压缩调用判定的送达事件。 */
182
+ export function pendingAdoptionDeliveries(limit = MAX_PENDING_FOR_EVALUATION) {
183
+ const sessionId = getCurrentSessionId();
184
+ const events = readLedger();
185
+ const evaluated = new Set(events.filter((e) => e.kind === 'evaluated').map((e) => e.deliveryId));
186
+ return events
187
+ .filter((e) => e.kind === 'delivered' && !evaluated.has(e.id) && (!sessionId || e.sessionId === sessionId))
188
+ .slice(-Math.max(1, limit));
189
+ }
190
+ /** 给既有模型调用的紧凑评估任务;无待评估送达时为空,绝不要求模型凑数。 */
191
+ export function adoptionEvaluationInstruction(target = 'compact') {
192
+ const pending = pendingAdoptionDeliveries();
193
+ if (pending.length === 0)
194
+ return '';
195
+ const rows = pending.map((e) => `- deliveryId=${e.id}; memoryId=${e.memoryId}; channel=${e.channel}`).join('\n');
196
+ const rule = 'Evaluate only the deliveryId values listed below. adopted means a later decision/tool action clearly used the memory; not_applicable means later context clearly made it irrelevant; unclear is the correct default when evidence is insufficient. Do not evaluate a memory merely because it was mentioned.';
197
+ if (target === 'reflection') {
198
+ return ('\n## Memory adoption evaluation\n' +
199
+ 'The following memories were delivered during this session. Based ONLY on the transcript, add an "adoptions" array to your normal JSON output. Each item is {"deliveryId":"...","verdict":"adopted|not_applicable|unclear","reason":"≤120 chars"}. ' +
200
+ `${rule} Use an empty array when no verdict is defensible.\n` +
201
+ rows);
202
+ }
203
+ return ('\n## Memory adoption evaluation\n' +
204
+ 'The following memories were delivered during this session. Based ONLY on the transcript above, append this JSON-only section after your normal output:\n' +
205
+ '## Memory Adoptions\n' +
206
+ '- {"deliveryId":"...","verdict":"adopted|not_applicable|unclear","reason":"≤120 chars"}\n' +
207
+ `${rule} Omit the heading when no verdict is defensible.\n` +
208
+ rows);
209
+ }
210
+ /** 从模型输出中切走采纳评估段;容错且不影响原输出。 */
211
+ export function extractAdoptionEvaluations(raw) {
212
+ const lines = String(raw ?? '').split('\n');
213
+ const head = /^ {0,3}##\s+memory\s+adoptions\b/i;
214
+ const start = lines.findIndex((line) => head.test(line));
215
+ if (start < 0)
216
+ return { text: String(raw ?? ''), evaluations: [] };
217
+ const heading = /^ {0,3}##\s+\S/;
218
+ let end = lines.length;
219
+ for (let i = start + 1; i < lines.length; i++)
220
+ if (heading.test(lines[i])) {
221
+ end = i;
222
+ break;
223
+ }
224
+ const evaluations = [];
225
+ const seen = new Set();
226
+ for (const line of lines.slice(start + 1, end)) {
227
+ const text = line.replace(/^\s*[-*•]\s*/, '').trim();
228
+ if (!text)
229
+ continue;
230
+ try {
231
+ const e = JSON.parse(text);
232
+ const deliveryId = typeof e.deliveryId === 'string' ? e.deliveryId.trim() : '';
233
+ if (!deliveryId || seen.has(deliveryId) || !isVerdict(e.verdict))
234
+ continue;
235
+ seen.add(deliveryId);
236
+ evaluations.push({
237
+ deliveryId,
238
+ verdict: e.verdict,
239
+ ...(typeof e.reason === 'string' && e.reason.trim()
240
+ ? { reason: e.reason.replace(/\s+/g, ' ').trim().slice(0, MAX_REASON_CHARS) }
241
+ : {}),
242
+ });
243
+ }
244
+ catch {
245
+ // 某一行坏 JSON 不影响其余有效评估。
246
+ }
247
+ }
248
+ return {
249
+ text: [...lines.slice(0, start), ...lines.slice(end)]
250
+ .join('\n')
251
+ .replace(/\n{3,}/g, '\n\n')
252
+ .trimEnd(),
253
+ evaluations,
254
+ };
255
+ }
256
+ /** 应用模型评估。白名单只允许当前尚未评估的真实送达,不能伪造/覆盖历史。 */
257
+ export function applyAdoptionEvaluations(evaluations) {
258
+ const pending = new Map(pendingAdoptionDeliveries(200).map((e) => [e.id, e]));
259
+ let count = 0;
260
+ for (const item of evaluations.slice(0, 20)) {
261
+ const delivery = typeof item.deliveryId === 'string' ? pending.get(item.deliveryId) : undefined;
262
+ const verdict = item.verdict;
263
+ if (!delivery || !isVerdict(verdict))
264
+ continue;
265
+ const reason = typeof item.reason === 'string' ? item.reason.replace(/\s+/g, ' ').trim().slice(0, MAX_REASON_CHARS) : '';
266
+ if (append({
267
+ memoryId: delivery.memoryId,
268
+ channel: delivery.channel,
269
+ kind: 'evaluated',
270
+ deliveryId: delivery.id,
271
+ verdict,
272
+ ...(reason ? { reason } : {}),
273
+ })) {
274
+ pending.delete(delivery.id);
275
+ count++;
276
+ }
277
+ }
278
+ return count;
279
+ }
280
+ /** 当前 90 天明细 + 已压缩历史的总统计。 */
281
+ export function adoptionStats() {
282
+ const current = summarize(readLedger());
283
+ const summary = readSummary();
284
+ if (summary)
285
+ mergeStats(current, summary.totals);
286
+ return current;
287
+ }
288
+ /** 只读详情,按条目过滤时用于 `/memory adoption <memory-id>`。 */
289
+ export function adoptionEvents(memoryId, limit = 30) {
290
+ const all = readLedger().filter((e) => !memoryId || e.memoryId === memoryId);
291
+ return all.slice(-Math.max(1, limit));
292
+ }
293
+ /** 将超过 90 天的原始事件压为聚合统计,保留最近明细以便审计。 */
294
+ export function pruneAdoptionLedger(now = Date.now()) {
295
+ const all = readLedger();
296
+ if (all.length === 0)
297
+ return;
298
+ const cutoff = now - RETAIN_DAYS * 24 * 60 * 60 * 1000;
299
+ const old = all.filter((e) => Date.parse(e.at) < cutoff);
300
+ if (old.length === 0)
301
+ return;
302
+ const retained = all.filter((e) => !old.includes(e));
303
+ try {
304
+ const existing = readSummary();
305
+ const totals = emptyStats();
306
+ if (existing)
307
+ mergeStats(totals, existing.totals);
308
+ mergeStats(totals, summarize(old));
309
+ const p = summaryPath();
310
+ mkdirSync(path.dirname(p), { recursive: true });
311
+ const tmp = p + '.tmp';
312
+ writeFileSync(tmp, JSON.stringify({ schemaVersion: 1, updatedAt: new Date(now).toISOString(), totals }, null, 2) + '\n', 'utf8');
313
+ renameSync(tmp, p);
314
+ const ledger = ledgerPath();
315
+ const ledgerTmp = ledger + '.tmp';
316
+ writeFileSync(ledgerTmp, retained.map((e) => JSON.stringify(e)).join('\n') + (retained.length ? '\n' : ''), 'utf8');
317
+ renameSync(ledgerTmp, ledger);
318
+ }
319
+ catch {
320
+ // 保守失败:原账本还在,最多下次再尝试压缩。
321
+ }
322
+ }
323
+ /** 测试隔离用。 */
324
+ export function __resetAdoptionForTests() {
325
+ serial = 0;
326
+ }