mocode-ai 1.8.0 → 1.8.2

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
@@ -104,7 +104,7 @@ MoCode isn't a chat box with a coat of paint — it's an agent that actually get
104
104
  - **Sub-agents divide and conquer** — Workers have independent history branches and inherit the parent step's tool ceiling. They run in bounded parallel batches, write directly to the shared workspace, and share the parent's rollback turn. A final summary and execution metadata return to the parent; there is no per-worker filesystem isolation or merge stage.
105
105
  - **Plan / Auto dual mode** — In `plan` mode the agent explores and produces a plan without editing project files, running shell commands, or spawning sub-agents; internal session/plan records may still be persisted. `auto` mode permits execution. Tool capabilities are not a static “full” mode: a lightweight LLM router selects the minimum sufficient groups for each real user turn, and the main model may add groups on a later step when needed.
106
106
  - **Pressure-driven context compression** — Normal history keeps full tool evidence. At 80% occupancy, one scheduler event runs all enabled cleanup and always follows with a history summary. `/context` shows live usage and `/compact` remains an explicit manual override.
107
- - **Cross-session long-term memory** — The agent can save project architecture, conventions, and lessons learned as long-term memory, auto-loaded in future sessions. Optional background reflection mines conversations for useful memories when `AUTO_REFLECT=true` (off by default). Memories can be created, searched, updated, and forgotten, with recall-based decay.
107
+ - **Cross-session long-term memory** — The agent can save project architecture, conventions, and lessons learned as long-term memory, auto-loaded in future sessions. Background reflection is on by default (max 3 auto-reflections per session; `AUTO_REFLECT=false` to disable) and mines conversations for useful memories; profile facts are graded by provenance (reflection inferences stay candidates until the user confirms them); reflection also tallies behavioral evidence — a candidate is auto-internalized after several independent confirmations with zero contradiction, while a held belief demotes back to candidate after repeated behavioral contradiction (every such move is surfaced, and a user `/memory confirm` overrides it). Memories can be created, searched, updated, and forgotten, with recall-based decay.
108
108
  - **Project context (`AGENTS.md`)** — A single project-level memory file at `AGENTS.md` captures both static facts (project description, commands, module list, directory tree) and human/AI-written insights (conventions, architectural decisions, pitfalls). Generate it once with `/init`, then keep it up to date by hand or by asking the agent to refresh it. Auto-injected into the system prompt every turn, but lean by design: the `directory tree` and `extension points` sections stay out of the prompt as one-line pointers (read_file `AGENTS.md` on demand), keeping the always-on payload small. During work, the agent may append stable, non-obvious facts it discovers to `.mocode/agents-draft.md`; `/init` merges and clears that draft.
109
109
  - **Session notepad (notes.md)** — For complex multi-step tasks (≥3 file changes / ≥5 tool calls), the agent maintains a working notepad at `.mocode/sessions/<sessionId>/notes.md` (file-based, survives context compression). It records the execution plan with the dedicated `plan_update` tool — a three-state step machine (`pending`/`in_progress`/`completed`, at most one `in_progress`) that auto-settles to `## Done:` when finished. The active plan is re-injected into the system prompt after compaction and re-synced into context whenever notes.md changes, and a gentle reminder nudges the agent if it goes several tool-steps without updating the plan. A live progress chip in the TUI status bar shows `plan: [title] (3/7) ▸ [current step]`.
110
110
  - **Interruptible and reversible** — Ctrl+C propagates cancellation to model requests and supported running tools. History returns to the latest committed tool-batch checkpoint rather than unconditionally discarding the entire turn. Completed file writes remain until explicitly reverted; `/rollback` restores tracked file changes from turn snapshots with a per-file keep/undo choice, without requiring git.
@@ -215,7 +215,7 @@ Common backend `base_url` values:
215
215
  | `CONTEXT_WINDOW_TOKENS` | Model context window; must match the real model | `256000` |
216
216
  | `LLM_STREAM_USAGE` | Include `stream_options.include_usage` on streaming requests for real usage | `true` |
217
217
  | `AUTO_COMPACT` | Final history-compaction safety fallback | `true` |
218
- | `AUTO_REFLECT` | Background reflection pass (opt-in; periodically mines memories from conversations) | `false` |
218
+ | `AUTO_REFLECT` | Background reflection pass (on by default, max 3 auto runs/session; set `false` to disable) | `true` |
219
219
  | `REFLECT_EVERY_N` | Trigger a background reflection every N turns (runs alongside the agent, non-blocking) | `5` |
220
220
  | `ANYSEARCH_API_KEY` | Web search API key (falls back to anonymous free quota if unset) | none |
221
221
  | `ANYSEARCH_BASE_URL` | Search API endpoint | `https://api.anysearch.com` |
package/README.zh-CN.md CHANGED
@@ -104,7 +104,7 @@ mocode 不是一个套壳聊天框,而是一个能真正动手干活的 agent:
104
104
  - **子 agent 分而治之** — 子任务拥有独立历史分支,工具权限不超过父 step 的能力上限;按并发上限分批运行,直接写入共享工作区并共用父级回滚轮次。主线接收最终摘要及执行元数据;没有每个 worker 独立的文件系统隔离或合并阶段。
105
105
  - **计划 / 执行双模式** — `plan` 模式下探查并产出计划,不修改项目文件、不跑 shell 命令、不派生子 agent;内部会话和计划记录仍可持久化。`auto` 模式允许执行,但不是静态“全工具”模式:每个真实用户轮先由轻量 LLM router 选择最小充分工具簇,主模型需要时可在后续 step 追加能力。
106
106
  - **统一压力驱动压缩** — 正常 history 保留完整工具证据;达到 80% 后由一次调度事件运行所有已启用的清理,并始终继续 history 摘要。`/context` 显示实时用量,`/compact` 仍是用户显式覆盖。
107
- - **跨会话长期记忆** — agent 能把项目架构、约定、踩过的坑存成长期记忆,下次会话自动加载;可通过 `AUTO_REFLECT=true` 开启后台反思,从对话中挖掘值得记住的事实(默认关闭)。记忆可增删改、带召回衰减。
107
+ - **跨会话长期记忆** — agent 能把项目架构、约定、踩过的坑存成长期记忆,下次会话自动加载;后台反思默认开启(每会话至多 3 次、`AUTO_REFLECT=false` 可关),从对话中挖掘值得记住的事实,画像事实按来源分级(反思推断先作候选,用户确认才内化);反思还会累计行为证据——候选经多次独立印证且零反驳会自动内化,已内化信念若被后续行为反复相悖则退回候选(每次自动升降级都会提示,用户可用 `/memory confirm` 翻案)。记忆可增删改、带召回衰减。
108
108
  - **会话记事本(notes.md)** — 复杂多步任务(≥3 处文件改动 / ≥5 步工具调用)时,agent 在 `.mocode/sessions/<sessionId>/notes.md` 维护一个工作记事本(落盘抗压缩),可记录中间发现、设计决策、待验证问题和结构化计划。执行计划由专用 `plan_update` 工具维护——三态步骤机(`pending`/`in_progress`/`completed`,同一时刻至多一个 `in_progress`),全部完成自动结算为 `## Done:`。活跃 plan 在压缩后重注入系统提示、notes.md 一变就重同步进上下文,若连续多步未更新还会有温和提醒。TUI 状态栏实时显示进度 chip:`plan: [标题] (3/7) ▸ [当前步]`。
109
109
  - **可中断、可回滚** — Ctrl+C 将中断信号传给模型请求及支持取消的运行中工具;历史恢复到最近已提交工具批次的检查点,而不是无条件丢弃整轮。已经完成的文件写入仍保留,需显式撤销;`/rollback` 可从轮次快照恢复已追踪文件,逐个选择「保留/撤销」,不依赖 git。
110
110
  - **输入安全网** — 长 prompt 不再怕误按 Enter:`Ctrl+G` 弹出 TUI 内「输入面板」(记事本式编辑,Enter=换行、软换行、选区、复制/剪切/粘贴、撤销,Ctrl+S 填回输入框不自动发送);`Ctrl+R`/`Ctrl+P` 模糊搜索历史输入(Enter 只回填不发送);长文本误发后撤回窗口自动放宽到 2 秒且任意键可撤回。
@@ -214,7 +214,7 @@ LLM_MODEL=glm-4.6 # 换成你的模型名
214
214
  | `CONTEXT_WINDOW_TOKENS` | 模型上下文窗口,须对齐真实模型 | `256000` |
215
215
  | `LLM_STREAM_USAGE` | 流式请求带 `stream_options.include_usage` 拿真实用量 | `true` |
216
216
  | `AUTO_COMPACT` | 最终 history compact 安全保护 | `true` |
217
- | `AUTO_REFLECT` | 后台反思 pass(默认关闭,需要时显式开启) | `false` |
217
+ | `AUTO_REFLECT` | 后台反思 pass(默认开启,每会话至多 3 次自动反思;显式 `false` 关闭) | `true` |
218
218
  | `REFLECT_EVERY_N` | 每 N 轮触发一次后台反思(与 agent 并发,不阻塞) | `5` |
219
219
  | `ANYSEARCH_API_KEY` | 联网搜索 API key(不配走匿名免费额度) | 无 |
220
220
  | `ANYSEARCH_BASE_URL` | 搜索 API 端点 | `https://api.anysearch.com` |
@@ -612,7 +612,7 @@ export const config = {
612
612
  contextBudget: process.env.MOCODE_BUDGET_SCHEDULER !== 'false',
613
613
  lowPressureRatio: Math.min(0.95, Math.max(0.1, Number(process.env.MOCODE_LOW_PRESSURE_RATIO) || 0.6)),
614
614
  toolClearing: process.env.MOCODE_TOOL_CLEARING !== 'false',
615
- autoReflect: process.env.AUTO_REFLECT === 'true',
615
+ autoReflect: process.env.AUTO_REFLECT !== 'false',
616
616
  memoryEnabled: process.env.MEMORY_ENABLED === 'true',
617
617
  reflectEveryN: Number(process.env.REFLECT_EVERY_N) || 5,
618
618
  maxSteps: Number(process.env.MAX_STEPS) || 1000,
package/dist/headless.js CHANGED
@@ -22,7 +22,7 @@ import './tools/builtins/index.js';
22
22
  import { initializeAllMcp, getMcpTools, closeAllMcp } from './mcp/index.js';
23
23
  import { config, buildBasePrompt, isMemoryEnabled } from './config/index.js';
24
24
  import { effectiveSystemPrompt } from './skills/index.js';
25
- import { buildMemoryIndexSection } from './memory/store.js';
25
+ import { buildMemoryIndexSection, gcMemories } from './memory/store.js';
26
26
  import { buildAboutYouSection, initPersona } from './memory/persona.js';
27
27
  import { buildProjectGraphHint } from './memory/recall.js';
28
28
  import { defaultRuntime, Runtime } from './runtime/index.js';
@@ -158,6 +158,15 @@ export async function runHeadless(opts) {
158
158
  // 系统提示:Bot 岗位角色在前,基础约定在后;白名单存在时补一句工具边界。
159
159
  const memoryOn = isMemoryEnabled();
160
160
  initPersona(memoryOn);
161
+ // 遗忘 GC 与反思解耦:headless 启动也跑一次(best-effort,不拖垮一次性执行)。
162
+ if (memoryOn) {
163
+ try {
164
+ gcMemories();
165
+ }
166
+ catch {
167
+ // best-effort
168
+ }
169
+ }
161
170
  const baseConventions = buildBasePrompt(sessionId) +
162
171
  buildAboutYouSection(memoryOn) +
163
172
  buildMemoryIndexSection(memoryOn) +
@@ -21,6 +21,9 @@ const zhCN = {
21
21
  'commands.memoryOff': '关闭记忆子系统',
22
22
  'commands.memoryStatus': '查看当前开关与原理',
23
23
  'commands.memoryReflect': '手动触发后台记忆反思',
24
+ 'commands.memoryProfile': '查看长期画像与待确认候选',
25
+ 'commands.memoryProfileConfirm': '确认一条画像候选并内化(/memory confirm <edge-id>)',
26
+ 'commands.memoryProfileDrop': '撤销一条画像(/memory drop <edge-id>)',
24
27
  'commands.memoryInit': '扫描项目生成 AGENTS.md 项目记忆',
25
28
  'commands.subagent': '子 Agent 自动路由 gate',
26
29
  'commands.subagentOn': '允许按需路由 orchestration',
@@ -212,6 +215,7 @@ const zhCN = {
212
215
  'status.modeSwitch': 'Shift+Tab 切换',
213
216
  'status.history': '历史 ↑{count}(PgDn 回底)',
214
217
  'status.queued': '排队 ·',
218
+ 'status.queuedCount': '排队 ×{count} ·',
215
219
  'status.queuePlanTag': '(Plan)',
216
220
  'status.measured': '实测',
217
221
  'status.estimated': '估算',
@@ -418,6 +422,9 @@ const en = {
418
422
  'commands.memoryOff': 'Disable the memory subsystem',
419
423
  'commands.memoryStatus': 'Show current state and behavior',
420
424
  'commands.memoryReflect': 'Run background memory reflection',
425
+ 'commands.memoryProfile': 'Show long-term profile and pending candidates',
426
+ 'commands.memoryProfileConfirm': 'Confirm a profile candidate and internalize it (/memory confirm <edge-id>)',
427
+ 'commands.memoryProfileDrop': 'Withdraw a profile fact (/memory drop <edge-id>)',
421
428
  'commands.memoryInit': 'Scan project and generate AGENTS.md',
422
429
  'commands.subagent': 'Sub-agent automatic-routing gate',
423
430
  'commands.subagentOn': 'Allow orchestration to be routed when needed',
@@ -604,6 +611,7 @@ const en = {
604
611
  'status.modeSwitch': 'Shift+Tab Switch',
605
612
  'status.history': 'History ↑{count} (PgDn to bottom)',
606
613
  'status.queued': 'queued ·',
614
+ 'status.queuedCount': 'queued ×{count} ·',
607
615
  'status.queuePlanTag': ' (Plan)',
608
616
  'status.measured': 'measured',
609
617
  'status.estimated': 'estimated',
package/dist/llm/index.js CHANGED
@@ -579,7 +579,11 @@ async function chatWithRuntime(runtime, messages, handlers, signal, toolsOverrid
579
579
  };
580
580
  // 流中途故障用独立计数,避免与 HTTP 层共享 10 次预算(理由见 STREAM_RETRY_MAX_ATTEMPTS)。
581
581
  let streamRetries = 0;
582
- for (let attempt = 1; attempt <= RETRY_MAX_ATTEMPTS; attempt++) {
582
+ // 后台任务可收紧总尝试数(见 LlmRequestOverrides.maxAttempts);非法值回落到默认。
583
+ const maxAttempts = overrides?.maxAttempts && Number.isFinite(overrides.maxAttempts)
584
+ ? Math.min(RETRY_MAX_ATTEMPTS, Math.max(1, Math.floor(overrides.maxAttempts)))
585
+ : RETRY_MAX_ATTEMPTS;
586
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
583
587
  if (signal?.aborted) {
584
588
  throw new DOMException('This operation was aborted', 'AbortError');
585
589
  }
@@ -602,7 +606,7 @@ async function chatWithRuntime(runtime, messages, handlers, signal, toolsOverrid
602
606
  isStreamInterruptedError(err) &&
603
607
  !producedOutput &&
604
608
  streamRetries < STREAM_RETRY_MAX_ATTEMPTS;
605
- if (attempt >= RETRY_MAX_ATTEMPTS || (!isRetryableError(err, signal) && !streamRetryable)) {
609
+ if (attempt >= maxAttempts || (!isRetryableError(err, signal) && !streamRetryable)) {
606
610
  throw err;
607
611
  }
608
612
  if (streamRetryable)
@@ -14,6 +14,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from '
14
14
  import os from 'node:os';
15
15
  import path from 'node:path';
16
16
  import { MAX_GRAPH_EDGES, MAX_GRAPH_ENTITIES } from '../tools/constants.js';
17
+ import { isSingleValueProfile, isKnownRelation } from './relation-vocab.js';
17
18
  // ── 路径 / 原子写(同 store.ts 风格)──────────────────────────────────────
18
19
  function globalGraphPath() {
19
20
  return path.join(os.homedir(), '.mocode', 'memory-graph.json');
@@ -182,9 +183,11 @@ export function upsertEntity(name, opts = {}) {
182
183
  }
183
184
  /**
184
185
  * 写一条三元组。src/dst 自动 upsert 为实体。
185
- * 冲突策略:同 scope 内已有 active 边同(src,dst,relation):
186
- * - fact 相同 → 幂等跳过(duplicate);
187
- * - fact 不同 → 旧边 invalidAt=now(时序失效),新边入库。
186
+ * 冲突策略:
187
+ * - 画像单值关系(global,如 located_in/works_at):同 src+relation 的**所有** active 旧边
188
+ * 一律 invalidAt=now——即便 dst 不同(换城市/换工作),不允许新旧值并存;
189
+ * - 其余关系:同(src,dst,relation)已有 active 边,fact 相同 → 幂等跳过(duplicate),
190
+ * fact 不同 → 旧边时序失效,新边入库。
188
191
  * 容量保护:边超限先清已失效边;仍超 → 拒绝。
189
192
  */
190
193
  export function addTriple(input) {
@@ -205,12 +208,26 @@ export function addTriple(input) {
205
208
  return { ok: false, reason: `dst entity: ${d.rejected}` };
206
209
  const g = loadScopeGraph(scope);
207
210
  const fact = (input.fact ?? '').trim();
208
- const clash = g.edges.find((e) => !e.invalidAt && e.src === s.id && e.dst === d.id && e.relation === relation);
209
- if (clash) {
210
- if (!fact || clash.fact === fact) {
211
- return { ok: true, edgeId: clash.id, superseded: 0, duplicate: true };
212
- }
213
- clash.invalidAt = nowIso(); // 时序失效,保留可追溯
211
+ const singleValue = scope === 'global' && isSingleValueProfile(relation);
212
+ // 单值关系:先圈定同 src+relation 的全部 active 旧边(换 dst 也失效)。
213
+ const sameKey = [];
214
+ for (const e of g.edges) {
215
+ if (e.invalidAt || e.src !== s.id || e.relation !== relation)
216
+ continue;
217
+ if (singleValue || e.dst === d.id)
218
+ sameKey.push(e);
219
+ }
220
+ // 完全等价(src+relation+dst 全等且 fact 相同/空)→ 幂等跳过。
221
+ const exact = sameKey.find((e) => e.dst === d.id && (!fact || e.fact === fact));
222
+ if (exact) {
223
+ return { ok: true, edgeId: exact.id, superseded: 0, duplicate: true };
224
+ }
225
+ let superseded = 0;
226
+ const ts = nowIso();
227
+ for (const e of sameKey) {
228
+ e.invalidAt = ts;
229
+ e.invalidReason = singleValue ? 'single-value-replaced' : 'fact-changed';
230
+ superseded++;
214
231
  }
215
232
  // 容量保护:先清失效边
216
233
  if (g.edges.length >= MAX_GRAPH_EDGES) {
@@ -225,14 +242,133 @@ export function addTriple(input) {
225
242
  dst: d.id,
226
243
  relation,
227
244
  fact,
228
- validAt: nowIso(),
245
+ validAt: ts,
229
246
  invalidAt: null,
230
247
  sourceEntry: input.sourceEntry ?? null,
231
248
  scope,
232
249
  };
250
+ if (input.prov)
251
+ edge.prov = input.prov;
252
+ if (typeof input.confidence === 'number' && Number.isFinite(input.confidence)) {
253
+ edge.confidence = Math.min(1, Math.max(0, input.confidence));
254
+ }
233
255
  g.edges.push(edge);
234
256
  writeGraphForScope(scope, g);
235
- return { ok: true, edgeId: edge.id, superseded: clash ? 1 : 0 };
257
+ return { ok: true, edgeId: edge.id, superseded };
258
+ }
259
+ /** 按时序失效一条边(不删除,可审计);edge id 或 (src,relation,dst 候选) 定位。 */
260
+ export function invalidateEdge(edgeId, reason = 'manual') {
261
+ const id = edgeId.trim();
262
+ if (!id)
263
+ return { ok: false, reason: 'missing edge id' };
264
+ for (const scope of ['global', 'project']) {
265
+ const g = loadScopeGraph(scope);
266
+ const e = g.edges.find((x) => x.id === id && !x.invalidAt);
267
+ if (e) {
268
+ e.invalidAt = nowIso();
269
+ e.invalidReason = reason;
270
+ writeGraphForScope(scope, g);
271
+ return { ok: true };
272
+ }
273
+ }
274
+ return { ok: false, reason: 'not-found' };
275
+ }
276
+ /**
277
+ * 用户确认一条画像边:补 prov=user_confirmed / confidence=1,立即获得 L2 内化资格。
278
+ * 仅对 person-primary 出发的画像边生效(/profile confirm 的落地点)。
279
+ */
280
+ export function promoteEdge(edgeId) {
281
+ const id = edgeId.trim();
282
+ if (!id)
283
+ return { ok: false, reason: 'missing edge id' };
284
+ const scope = 'global';
285
+ const g = loadScopeGraph(scope);
286
+ const e = g.edges.find((x) => x.id === id);
287
+ if (!e)
288
+ return { ok: false, reason: 'not-found' };
289
+ if (e.src !== PRIMARY_PERSON_ID)
290
+ return { ok: false, reason: 'not-a-profile-edge' };
291
+ e.prov = 'user_confirmed';
292
+ e.confidence = 1;
293
+ // 显式确认是用户主权动作,优先级高于自动行为证据:清零相悖计数(否则一条被强反证
294
+ // 自动降级的边,用户 /memory confirm 翻案后仍会被 persona 的强反证否决挡在门外)。
295
+ e.evidence = { confirmed: (e.evidence?.confirmed ?? 0) + 1, contradicted: 0 };
296
+ if (e.invalidAt) {
297
+ e.invalidAt = null; // 确认一条被误失效的边=复活
298
+ e.invalidReason = undefined;
299
+ }
300
+ writeGraphForScope(scope, g);
301
+ return { ok: true };
302
+ }
303
+ /**
304
+ * 环境证据累计(反思 evidence 桶的落地点):对一条 active 画像边加一张确认/反对票。
305
+ * 与 promoteEdge 的本质区别——**不碰 prov/confidence**:这里只做可涨可跌、可逆的纯证据
306
+ * 计数,能否内化交给 persona.isInternalizedEdge 按 β 后验统一判定。因此:
307
+ * - 反思候选可经多次行为印证自动转正(无需用户手敲 /memory confirm);
308
+ * - 已内化边被多轮行为矛盾后自动退回候选(不硬删,用户仍可 promoteEdge 翻案)。
309
+ * 只对 person-primary 出发的 global 画像边开放;project triples 不参与画像分级。
310
+ */
311
+ export function voteEdge(edgeId, vote) {
312
+ const id = edgeId.trim();
313
+ if (!id)
314
+ return { ok: false, reason: 'missing edge id' };
315
+ if (vote !== 'confirm' && vote !== 'contradict')
316
+ return { ok: false, reason: 'bad-vote' };
317
+ const scope = 'global';
318
+ const g = loadScopeGraph(scope);
319
+ const e = g.edges.find((x) => x.id === id);
320
+ if (!e)
321
+ return { ok: false, reason: 'not-found' };
322
+ if (e.invalidAt)
323
+ return { ok: false, reason: 'edge-invalid' };
324
+ if (e.src !== PRIMARY_PERSON_ID)
325
+ return { ok: false, reason: 'not-a-profile-edge' };
326
+ const prev = e.evidence ?? { confirmed: 0, contradicted: 0 };
327
+ const next = vote === 'confirm'
328
+ ? { confirmed: prev.confirmed + 1, contradicted: prev.contradicted }
329
+ : { confirmed: prev.confirmed, contradicted: prev.contradicted + 1 };
330
+ e.evidence = next;
331
+ writeGraphForScope(scope, g);
332
+ return {
333
+ ok: true,
334
+ confirmed: next.confirmed,
335
+ contradicted: next.contradicted,
336
+ posterior: (next.confirmed + 1) / (next.confirmed + next.contradicted + 2),
337
+ };
338
+ }
339
+ /**
340
+ * 失效 person-primary 在某个画像关系上的 active 边(自然语言纠正的落地点:
341
+ * "别再当我在 X 了" → invalidateProfileEdges('located_in'))。多值关系只按 dst 过滤。
342
+ * 返回失效条数。
343
+ */
344
+ export function invalidateProfileEdges(relation, dst) {
345
+ const rel = relation.trim().toLowerCase().replace(/\s+/g, '_');
346
+ if (!rel)
347
+ return 0;
348
+ const scope = 'global';
349
+ const g = loadScopeGraph(scope);
350
+ const dstWant = dst?.trim().toLowerCase();
351
+ let n = 0;
352
+ const ts = nowIso();
353
+ for (const e of g.edges) {
354
+ if (e.invalidAt || e.src !== PRIMARY_PERSON_ID || e.relation !== rel)
355
+ continue;
356
+ if (dstWant) {
357
+ const target = g.entities.find((x) => x.id === e.dst);
358
+ const names = [e.dst, target?.name ?? '', ...(target?.aliases ?? [])]
359
+ .map((s) => s.trim().toLowerCase())
360
+ .filter((s) => s.length > 0);
361
+ const hit = names.some((s) => s.includes(dstWant) || dstWant.includes(s));
362
+ if (!hit)
363
+ continue;
364
+ }
365
+ e.invalidAt = ts;
366
+ e.invalidReason = 'user-correction';
367
+ n++;
368
+ }
369
+ if (n > 0)
370
+ writeGraphForScope(scope, g);
371
+ return n;
236
372
  }
237
373
  /** 实体关键词搜索(多词子串,name/alias/id 加权),返回命中实体 + 相连 active 边。 */
238
374
  export function searchGraph(query, limit = 8) {
@@ -668,3 +804,37 @@ export function canonicalizePrimaryPerson() {
668
804
  }
669
805
  return { primary: PRIMARY_PERSON_ID, displayName, merged, dedupedEdges: deduped };
670
806
  }
807
+ // ── 遗留画像边溯源迁移(M2)─────────────────────────────────────────────────
808
+ //
809
+ // 引入 prov/confidence 之前,所有画像边都"挂上 person-primary 即无条件常驻",
810
+ // 反思单次推断与用户亲述同权。升级后新反思边带 prov='reflection'(0.4,不内化);
811
+ // 而升级前落库的边没有 prov——它们大多来自用户亲口陈述或人工添加,一次性保守补成
812
+ // user_said(0.9,可内化),避免收紧 About you 门槛后真实画像整体消失。
813
+ // 幂等:已有 prov 的边不动;进程内只跑一次(initPersona 守卫)。
814
+ let legacyMigrationDone = false;
815
+ export function migrateLegacyProfileProvenance(force = false) {
816
+ if (legacyMigrationDone && !force)
817
+ return { migrated: 0 };
818
+ legacyMigrationDone = true;
819
+ const scope = 'global';
820
+ const g = loadScopeGraph(scope);
821
+ let migrated = 0;
822
+ for (const e of g.edges) {
823
+ if (e.prov || e.invalidAt)
824
+ continue;
825
+ if (e.src !== PRIMARY_PERSON_ID)
826
+ continue;
827
+ if (!isKnownRelation(e.relation, 'global'))
828
+ continue; // 只提升词表内画像关系
829
+ e.prov = 'user_said';
830
+ e.confidence = 0.9;
831
+ migrated++;
832
+ }
833
+ if (migrated > 0)
834
+ writeGraphForScope(scope, g);
835
+ return { migrated };
836
+ }
837
+ /** 测试专用:重置遗留迁移的进程内守卫。 */
838
+ export function __resetLegacyMigrationForTests() {
839
+ legacyMigrationDone = false;
840
+ }
@@ -2,8 +2,8 @@
2
2
  // AGENTS.md is intentionally not loaded here either: config/index.ts
3
3
  // (buildAgentsImportSection) auto-imports the workspace-root AGENTS.md body into the
4
4
  // system prompt — independent of the memory switch — truncating it when it exceeds the cap.
5
- export { buildMemoryIndexSection, loadAll, gcMemories, } from './store.js';
6
- export { addTriple, upsertEntity, findEntity, searchGraph, searchGraphFacts, neighborsOf, pathBetween, graphStats, ensurePrimaryPerson, mergeEntities, canonicalizePrimaryPerson, PRIMARY_PERSON_ID, } from './graph.js';
7
- export { buildAboutYouSection, initPersona, __resetPersonaInitForTests, ABOUT_YOU_MAX_CHARS } from './persona.js';
5
+ export { buildMemoryIndexSection, loadAll, gcMemories, supersedeEntry, } from './store.js';
6
+ export { addTriple, upsertEntity, findEntity, searchGraph, searchGraphFacts, neighborsOf, pathBetween, graphStats, ensurePrimaryPerson, mergeEntities, canonicalizePrimaryPerson, invalidateEdge, promoteEdge, voteEdge, invalidateProfileEdges, migrateLegacyProfileProvenance, __resetLegacyMigrationForTests, PRIMARY_PERSON_ID, } from './graph.js';
7
+ export { buildAboutYouSection, initPersona, isInternalizedEdge, listProfileCandidates, listInternalizedProfile, inspectPrimaryProfile, __resetPersonaInitForTests, ABOUT_YOU_MAX_CHARS, } from './persona.js';
8
8
  export { buildProjectGraphHint, GRAPH_HINT_MAX_CHARS } from './recall.js';
9
9
  export { kickoffReflection, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, runReflection, } from './reflect.js';
@@ -7,7 +7,47 @@
7
7
  // 30 天衰减影响——这是"越用越懂用户"那条易失通道之外的确定性内化通道。
8
8
  //
9
9
  // 纯读、不建实体(建实体/归一走 graph.canonicalizePrimaryPerson,在启动期显式做)。
10
- import { loadScopeGraph, canonicalizePrimaryPerson, PRIMARY_PERSON_ID, } from './graph.js';
10
+ import { loadScopeGraph, canonicalizePrimaryPerson, migrateLegacyProfileProvenance, PRIMARY_PERSON_ID, } from './graph.js';
11
+ /** β(1,1) 后验:P(信念为真 | 证据)。confirmed/contradicted 来自反思对对话行为的计票。 */
12
+ export function edgePosterior(e) {
13
+ const c = e.evidence?.confirmed ?? 0;
14
+ const x = e.evidence?.contradicted ?? 0;
15
+ return (c + 1) / (c + x + 2);
16
+ }
17
+ /** 行为印证自动转正:连续 ≥3 次确认且零反驳(β=0.8)——"多次默认、从不反对"。 */
18
+ const BEHAVIOR_PROMOTE_MIN_CONFIRMS = 3;
19
+ /** 强反证自动降级:≥3 次行为相悖且后验 <0.4,连 user_said 也退回候选(用户 promote 可翻案)。 */
20
+ const STRONG_VETO_MIN_CONTRADICTS = 3;
21
+ const STRONG_VETO_POSTERIOR = 0.4;
22
+ /**
23
+ * L2 内化判定:只有"被验证过的"画像边才配常驻每轮 system prompt。
24
+ * - 强反证否决优先:≥3 次行为相悖且后验 <0.4 → 一律退回候选(即使用户亲述过;
25
+ * 显式纠正应走 corrections 桶,这里只处理"用下来发现不对"的弱信号累积);
26
+ * - prov=user_said / user_confirmed:用户亲述或确认(迁移的旧边保守视作亲述);
27
+ * - confidence ≥ 0.85:显式高置信;
28
+ * - β 后验 ≥ 0.85 且至少 1 次环境确认;
29
+ * - 或连续 ≥3 次行为印证、零反驳(反思候选的自动转正通道,无需手敲 confirm)。
30
+ * 反思单次推断(prov=reflection,0.4)不达标 → 只作候选,不进 About you。
31
+ */
32
+ export function isInternalizedEdge(e) {
33
+ const x = e.evidence?.contradicted ?? 0;
34
+ if (x >= STRONG_VETO_MIN_CONTRADICTS && edgePosterior(e) < STRONG_VETO_POSTERIOR)
35
+ return false;
36
+ if (e.prov === 'user_said' || e.prov === 'user_confirmed')
37
+ return true;
38
+ if (typeof e.confidence === 'number' && e.confidence >= 0.85)
39
+ return true;
40
+ const c = e.evidence?.confirmed ?? 0;
41
+ if (c >= 1) {
42
+ const posterior = edgePosterior(e);
43
+ if (posterior >= 0.85)
44
+ return true;
45
+ // 纯行为通道:多次印证 + 零反驳。任何一次相悖都留在候选,等用户显式确认。
46
+ if (c >= BEHAVIOR_PROMOTE_MIN_CONFIRMS && x === 0)
47
+ return true;
48
+ }
49
+ return false;
50
+ }
11
51
  /** About you 段硬预算(字符):只放高等级画像,超了按置信/顺序截断。 */
12
52
  export const ABOUT_YOU_MAX_CHARS = 800;
13
53
  /** 关系 → 人类可读标签(画像白名单;不在表内的关系用 fact 原文,仍可展示)。 */
@@ -35,7 +75,9 @@ function displayName(name) {
35
75
  return name.replace(/[_-]+/g, ' ').trim();
36
76
  }
37
77
  /**
38
- * 渲染全局 L2 画像段。无 person-primary / 无 active 画像边 → 空串(零注入)。
78
+ * 渲染全局 L2 画像段。无 person-primary / 无**达内化门槛**的 active 画像边 → 空串。
79
+ * 内化门槛见 isInternalizedEdge:反思推断(0.4)不常驻,用户亲述/确认/高置信,
80
+ * 或多次行为印证零反驳(≥3 confirm)才在;强反证(≥3 contradict 且后验<0.4)会降回候选。
39
81
  * 优先用边上的中文 fact 原文;没有 fact 时用「关系标签 + 目标实体名」。
40
82
  * 同名去重;has_hobby 合并为一行;整体截断到 ABOUT_YOU_MAX_CHARS。
41
83
  */
@@ -47,7 +89,7 @@ export function buildAboutYouSection(memoryEnabled = true) {
47
89
  if (!me)
48
90
  return '';
49
91
  const byId = new Map(g.entities.map((e) => [e.id, e]));
50
- const outgoing = g.edges.filter((e) => !e.invalidAt && e.src === PRIMARY_PERSON_ID && e.dst !== PRIMARY_PERSON_ID);
92
+ const outgoing = g.edges.filter((e) => !e.invalidAt && e.src === PRIMARY_PERSON_ID && e.dst !== PRIMARY_PERSON_ID && isInternalizedEdge(e));
51
93
  if (outgoing.length === 0)
52
94
  return '';
53
95
  const hobbies = [];
@@ -117,6 +159,48 @@ export function inspectPrimaryProfile() {
117
159
  const edges = g.edges.filter((e) => !e.invalidAt && (e.src === PRIMARY_PERSON_ID || e.dst === PRIMARY_PERSON_ID));
118
160
  return { me, edges };
119
161
  }
162
+ /** L2 内化画像列表(当前会渲染进 About you 的边),与 listProfileCandidates 对称。 */
163
+ export function listInternalizedProfile(limit = 20) {
164
+ const g = loadScopeGraph('global');
165
+ const byId = new Map(g.entities.map((e) => [e.id, e]));
166
+ const out = [];
167
+ for (const e of g.edges) {
168
+ if (e.invalidAt || e.src !== PRIMARY_PERSON_ID || e.dst === PRIMARY_PERSON_ID)
169
+ continue;
170
+ if (!isInternalizedEdge(e))
171
+ continue;
172
+ const dst = byId.get(e.dst);
173
+ const target = dst ? displayName(dst.name) : displayName(e.dst);
174
+ const text = e.fact?.trim() || `${RELATION_LABEL[e.relation] ?? e.relation.replace(/_/g, ' ')}:${target}`;
175
+ out.push({ edge: e, text, relation: e.relation });
176
+ if (out.length >= limit)
177
+ break;
178
+ }
179
+ return out;
180
+ }
181
+ /**
182
+ * L1 候选画像:挂在 person-primary 上、active、但**未达内化门槛**的边
183
+ * (典型:反思单次推断 prov=reflection/0.4)。供 /profile 展示"待确认"列表,
184
+ * 用户确认后 promoteEdge 升 L2。不含已渲染在 About you 里的内化边。
185
+ */
186
+ export function listProfileCandidates(limit = 10) {
187
+ const g = loadScopeGraph('global');
188
+ const byId = new Map(g.entities.map((e) => [e.id, e]));
189
+ const out = [];
190
+ for (const e of g.edges) {
191
+ if (e.invalidAt || e.src !== PRIMARY_PERSON_ID || e.dst === PRIMARY_PERSON_ID)
192
+ continue;
193
+ if (isInternalizedEdge(e))
194
+ continue;
195
+ const dst = byId.get(e.dst);
196
+ const target = dst ? displayName(dst.name) : displayName(e.dst);
197
+ const text = e.fact?.trim() || `${RELATION_LABEL[e.relation] ?? e.relation.replace(/_/g, ' ')}:${target}`;
198
+ out.push({ edge: e, text, relation: e.relation });
199
+ if (out.length >= limit)
200
+ break;
201
+ }
202
+ return out;
203
+ }
120
204
  let personaInitialized = false;
121
205
  /**
122
206
  * 启动期幂等初始化:做一次全局身份归一(把 mocode-user / user-name-* / 自称等碎片
@@ -135,6 +219,13 @@ export function initPersona(memoryEnabled = true) {
135
219
  catch {
136
220
  // 归一只是增强(图谱损坏/IO 异常),绝不能拖垮 REPL 启动。
137
221
  }
222
+ try {
223
+ // M2:升级前落库的画像边没有 prov,保守补 user_said(详见函数注释)。
224
+ migrateLegacyProfileProvenance();
225
+ }
226
+ catch {
227
+ // 迁移同样只是增强。
228
+ }
138
229
  }
139
230
  /** 测试专用:重置进程内初始化标记。 */
140
231
  export function __resetPersonaInitForTests() {