mocode-ai 1.8.0 → 1.8.1
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 +2 -2
- package/README.zh-CN.md +2 -2
- package/dist/config/index.js +1 -1
- package/dist/headless.js +10 -1
- package/dist/i18n/index.js +6 -0
- package/dist/llm/index.js +6 -2
- package/dist/memory/graph.js +181 -11
- package/dist/memory/index.js +3 -3
- package/dist/memory/persona.js +94 -3
- package/dist/memory/reflect.js +229 -20
- package/dist/memory/relation-vocab.js +19 -0
- package/dist/memory/store.js +19 -0
- package/dist/repl/commands/memory.js +90 -5
- package/dist/repl/commands.js +3 -0
- package/dist/repl/runtime.js +11 -1
- package/dist/tools/builtins/edit-file.js +1 -1
- package/dist/tools/builtins/memory-forget.js +26 -5
- package/dist/tools/builtins/memory-graph.js +7 -0
- package/package.json +1 -1
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.
|
|
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 (
|
|
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
|
|
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
|
|
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` |
|
package/dist/config/index.js
CHANGED
|
@@ -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
|
|
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) +
|
package/dist/i18n/index.js
CHANGED
|
@@ -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',
|
|
@@ -418,6 +421,9 @@ const en = {
|
|
|
418
421
|
'commands.memoryOff': 'Disable the memory subsystem',
|
|
419
422
|
'commands.memoryStatus': 'Show current state and behavior',
|
|
420
423
|
'commands.memoryReflect': 'Run background memory reflection',
|
|
424
|
+
'commands.memoryProfile': 'Show long-term profile and pending candidates',
|
|
425
|
+
'commands.memoryProfileConfirm': 'Confirm a profile candidate and internalize it (/memory confirm <edge-id>)',
|
|
426
|
+
'commands.memoryProfileDrop': 'Withdraw a profile fact (/memory drop <edge-id>)',
|
|
421
427
|
'commands.memoryInit': 'Scan project and generate AGENTS.md',
|
|
422
428
|
'commands.subagent': 'Sub-agent automatic-routing gate',
|
|
423
429
|
'commands.subagentOn': 'Allow orchestration to be routed when needed',
|
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
|
-
|
|
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 >=
|
|
609
|
+
if (attempt >= maxAttempts || (!isRetryableError(err, signal) && !streamRetryable)) {
|
|
606
610
|
throw err;
|
|
607
611
|
}
|
|
608
612
|
if (streamRetryable)
|
package/dist/memory/graph.js
CHANGED
|
@@ -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
|
-
*
|
|
186
|
-
* -
|
|
187
|
-
*
|
|
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
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
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:
|
|
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
|
|
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
|
+
}
|
package/dist/memory/index.js
CHANGED
|
@@ -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';
|
package/dist/memory/persona.js
CHANGED
|
@@ -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 /
|
|
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() {
|
package/dist/memory/reflect.js
CHANGED
|
@@ -12,8 +12,9 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
|
12
12
|
import path from 'node:path';
|
|
13
13
|
import { chat } from '../llm/index.js';
|
|
14
14
|
import { config, isMemoryEnabled } from '../config/index.js';
|
|
15
|
-
import { saveEntry, updateEntry, forgetEntry, loadAll, gcMemories } from './store.js';
|
|
16
|
-
import { addTriple, ensurePrimaryPerson, PRIMARY_PERSON_ID } from './graph.js';
|
|
15
|
+
import { saveEntry, updateEntry, forgetEntry, supersedeEntry, loadAll, gcMemories } from './store.js';
|
|
16
|
+
import { addTriple, ensurePrimaryPerson, invalidateProfileEdges, voteEdge, loadScopeGraph, PRIMARY_PERSON_ID, } from './graph.js';
|
|
17
|
+
import { isInternalizedEdge } from './persona.js';
|
|
17
18
|
import { normalizeRelation, isKnownRelation, relationCheatSheet } from './relation-vocab.js';
|
|
18
19
|
// ── 日志(静默容错,裁尾保最近)─────────────────────────────────────────────
|
|
19
20
|
function logPath() {
|
|
@@ -90,20 +91,60 @@ function buildMemorySample() {
|
|
|
90
91
|
})
|
|
91
92
|
.join('\n---\n');
|
|
92
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* 待投票的画像边快照(反思 prompt 用):当前 global 图里 person-primary 的 active 边,
|
|
96
|
+
* 连同当前证据计数/后验,让模型只对"本轮对话行为确实印证或相悖"的边投票。
|
|
97
|
+
* 关键:这是**本轮反思开始前**拍的快照,本轮新建的 profile/corrections 边不在白名单——
|
|
98
|
+
* 防止模型给自己刚推断出的信念投票一次转正(自我强化)。
|
|
99
|
+
*/
|
|
100
|
+
function buildProfileEvidenceSnapshot() {
|
|
101
|
+
const g = loadScopeGraph('global');
|
|
102
|
+
const byId = new Map(g.entities.map((e) => [e.id, e]));
|
|
103
|
+
const edges = g.edges
|
|
104
|
+
.filter((e) => !e.invalidAt && e.src === PRIMARY_PERSON_ID && e.dst !== PRIMARY_PERSON_ID)
|
|
105
|
+
.slice(0, 20);
|
|
106
|
+
const votable = new Set();
|
|
107
|
+
const statements = new Map();
|
|
108
|
+
const text = edges
|
|
109
|
+
.map((e) => {
|
|
110
|
+
const dst = byId.get(e.dst);
|
|
111
|
+
const target = dst?.name ?? e.dst;
|
|
112
|
+
const statement = e.fact?.trim() || `${e.relation}:${target}`;
|
|
113
|
+
votable.add(e.id);
|
|
114
|
+
statements.set(e.id, statement);
|
|
115
|
+
const c = e.evidence?.confirmed ?? 0;
|
|
116
|
+
const x = e.evidence?.contradicted ?? 0;
|
|
117
|
+
const state = isInternalizedEdge(e) ? 'internalized' : 'candidate';
|
|
118
|
+
return `[${e.id}] (${state}, evidence confirm=${c} contradict=${x}) ${statement}`;
|
|
119
|
+
})
|
|
120
|
+
.join('\n');
|
|
121
|
+
return { text: edges.length === 0 ? '(无)' : text, votable, statements };
|
|
122
|
+
}
|
|
93
123
|
const TYPES = 'decision | fact | pitfall | reference | feedback';
|
|
124
|
+
/** 后台反思整体超时:卡住的请求不能拖过退出 drain,也不该长期占用在飞槽位。 */
|
|
125
|
+
const REFLECT_TIMEOUT_MS = 60_000;
|
|
126
|
+
/**
|
|
127
|
+
* 后台任务的重试预算:只要 3 次尝试(连接类首败零等待,其后退避 ~1s、~2s)。
|
|
128
|
+
* 不能用交互式 chat 默认的 10 次——指数退避累计 0+1+2+4+8+16+30≈61s,恰好打满
|
|
129
|
+
* 上面的 60s 超时:后端持续失败时超时会落在退避 sleep 里,最后只剩一条含义不明的
|
|
130
|
+
* 'AbortError: This operation was aborted'(实测 2026-10 多次出现在状态行)。
|
|
131
|
+
*/
|
|
132
|
+
const REFLECT_MAX_ATTEMPTS = 3;
|
|
94
133
|
const REFLECT_SYS = `You are mocode's memory reflector. Review the recent session and existing memories, producing **only** updates worth remembering long-term.
|
|
95
|
-
Output strictly JSON (no markdown code blocks, no explanatory text): {"saves":[{"type":"...","name":"...","summary":"...","body":"..."}],"updates":[{"id":"...","reason":"...","summary":"...","body":"..."}],"forgets":[{"id":"...","reason":"..."}],"triples":[{"src":"...","relation":"...","dst":"...","fact":"..."}],"profile":[{"relation":"...","dst":"...","fact":"..."}]}
|
|
134
|
+
Output strictly JSON (no markdown code blocks, no explanatory text): {"saves":[{"type":"...","name":"...","summary":"...","body":"...","supersedes":"old-id-or-empty"}],"updates":[{"id":"...","reason":"...","summary":"...","body":"..."}],"forgets":[{"id":"...","reason":"..."}],"triples":[{"src":"...","relation":"...","dst":"...","fact":"..."}],"profile":[{"relation":"...","dst":"...","fact":"..."}],"corrections":[{"relation":"...","dst":"...","fact":"...","old":"..."}],"evidence":[{"edgeId":"...","vote":"confirm|contradict","reason":"..."}]}
|
|
96
135
|
Empty arrays are valid (if nothing is worth saving, all arrays are empty).
|
|
97
136
|
Rules:
|
|
98
137
|
① Only store non-obvious, cross-session-useful facts/decisions/pitfalls; do not store current bugs, temp files, undecided TODOs, or volatile items;
|
|
99
138
|
② Better to store less than to store trivially correct info (e.g. "keep it concise");
|
|
100
|
-
③ ids in updates/forgets must come from the "existing memories" list below; do not fabricate ids not listed there;
|
|
139
|
+
③ ids in updates/forgets/supersedes must come from the "existing memories" list below; do not fabricate ids not listed there;
|
|
101
140
|
④ names in saves must be concise and not collide with existing ones; type ∈ {${TYPES}};
|
|
102
|
-
⑤ If an existing memory contradicts new facts or is outdated, update the old entry (modify summary/body) rather than creating a duplicate;
|
|
141
|
+
⑤ If an existing memory contradicts new facts or is outdated, update the old entry (modify summary/body) rather than creating a duplicate; if a NEW entry fully replaces an old one whose title/scope differs, put the old id in that save's "supersedes" field (the old entry is marked superseded, not deleted);
|
|
103
142
|
⑥ forgets are for memories clearly stale / superseded by a new entry (archive, not hard-delete);
|
|
104
143
|
⑦ triples are PROJECT knowledge-graph facts about THIS CODEBASE distilled from this session: concise entity names (lowercase snake_case or proper nouns) plus a one-line fact. Prioritize the high-reuse structural relations in this order — dependency/ownership (depends_on, uses, used_by, calls, part_of), location (implemented_in, reads, writes, configured_by, runs_on, listens_on), verification (tests, documented_in), rationale/risk (decided_by, conflicts_with); full list: ${relationCheatSheet('project')}. Favor facts that would help a future session navigate or avoid re-deriving (which module implements X, what depends on Y, what conflicts with Z). A relation outside this list is allowed only when none fits (it gets flagged for review). Only emit triples that are stable, non-obvious and reusable in this repo (2-6 at most).
|
|
105
|
-
⑧ profile is for facts about THE USER (the human), which must apply across ALL projects — identity, role, expertise, language/communication style, stable preferences, current goals, constraints. They are attached to the single canonical person entity. Each item: dst is a short atomic value/entity, fact is one neutral Chinese sentence stating it. Prefer these relations: ${relationCheatSheet('global')}. A relation outside this list is allowed only when none fits. NEVER put repo paths, commands, file names, ports, secrets or one-task details in profile — those belong in triples. Only emit profile when the user explicitly revealed something durable about themselves (0-3 items); when unsure, omit
|
|
106
|
-
|
|
144
|
+
⑧ profile is for facts about THE USER (the human), which must apply across ALL projects — identity, role, expertise, language/communication style, stable preferences, current goals, constraints. They are attached to the single canonical person entity. Each item: dst is a short atomic value/entity, fact is one neutral Chinese sentence stating it. Prefer these relations: ${relationCheatSheet('global')}. A relation outside this list is allowed only when none fits. NEVER put repo paths, commands, file names, ports, secrets or one-task details in profile — those belong in triples. Only emit profile when the user explicitly revealed something durable about themselves (0-3 items); when unsure, omit. Profile items from your own inference are stored as LOW confidence and will NOT be internalized until the user confirms them — do not inflate them.
|
|
145
|
+
⑨ corrections is the HIGHEST signal channel: use it ONLY when the user explicitly corrects a prior belief about themselves ("不对/别这样/我已经不在 X 了/我更喜欢…"). Each correction invalidates the previous value for that relation and installs the new one as user-confirmed. "relation" is the profile relation being corrected, "dst"/"fact" are the NEW value (same shape as profile), "old" is the old value being withdrawn (short hint, may be empty). Do not put repo/code corrections here — those use updates/forgets.
|
|
146
|
+
⑩ evidence is the ONLY channel that adjusts confidence of an EXISTING profile belief from observed behavior — it never creates facts. You are given "Profile beliefs under review" containing only votable edge ids with their current counts. Rules: vote only on ids from that list, at most one vote per id, and only when THIS session genuinely bears on the belief — "confirm" when the user acts/chooses/agrees consistently with it, "contradict" when they act against it or state something incompatible; mere non-mention is NEITHER (omit). NEVER vote on beliefs you are newly creating in profile/corrections this same turn. Be conservative: a few independent confirms (with zero contradicts) auto-internalize a candidate; repeated contradicts demote an internalized belief back to candidate, and every such move is surfaced to the user. When unsure, cast no vote.`;
|
|
147
|
+
const REFLECT_USER = (transcript, sample, profileEdges) => `## Recent session\n${transcript}\n\n## Existing memories\n${sample}\n\n## Profile beliefs under review (evidence votes may only target these ids)\n${profileEdges}\n\nProduce JSON:`;
|
|
107
148
|
export function parsePlan(content) {
|
|
108
149
|
if (!content)
|
|
109
150
|
return null;
|
|
@@ -138,7 +179,10 @@ export function parsePlan(content) {
|
|
|
138
179
|
}
|
|
139
180
|
/** 取一次反思 LLM 返回的可解析文本(content 优先;tool_calls 的 JSON 串参数兜底)。 */
|
|
140
181
|
async function fetchReflection(messages, signal) {
|
|
141
|
-
const r = await chat(messages, {}, signal, undefined, {
|
|
182
|
+
const r = await chat(messages, {}, signal, undefined, {
|
|
183
|
+
reasoningEffort: 'low',
|
|
184
|
+
maxAttempts: REFLECT_MAX_ATTEMPTS,
|
|
185
|
+
});
|
|
142
186
|
if (!r.toolCalls.length && r.content)
|
|
143
187
|
return { content: r.content, raw: null };
|
|
144
188
|
// 推理模型偶发只把 JSON 塞进 tool_calls 参数、或 content 为 null:从工具调用里捞 JSON 串。
|
|
@@ -158,13 +202,22 @@ async function fetchReflection(messages, signal) {
|
|
|
158
202
|
* 首轮解析失败时做**一次修复式重试**(明确要求"只输出 JSON、不要思考过程"),
|
|
159
203
|
* 重试仍失败才报 parse-failed——此时 rawParseFailure 带原始返回指纹,由 kickoff 落
|
|
160
204
|
* memory.log,不再像旧版那样无声丢掉一整轮且无从排查。store 调用全同步。
|
|
161
|
-
*
|
|
205
|
+
* REFLECT_TIMEOUT_MS 超时(AbortSignal.timeout)防 exit 时 drain 挂死;重试预算收紧到
|
|
206
|
+
* REFLECT_MAX_ATTEMPTS 次,避免交互式 10 次退避打满超时后只剩含义不明的 AbortError。
|
|
162
207
|
*/
|
|
163
208
|
export async function runReflection(transcript, signal) {
|
|
164
209
|
const ts = new Date().toISOString();
|
|
165
210
|
const sample = buildMemorySample();
|
|
211
|
+
// 本轮开始前的画像边快照:evidence 票只能投给这些 id(本轮新建边无法自我投票)。
|
|
212
|
+
const evidenceSnap = buildProfileEvidenceSnapshot();
|
|
213
|
+
const beforeInternalized = new Set(loadScopeGraph('global')
|
|
214
|
+
.edges.filter((e) => evidenceSnap.votable.has(e.id) && isInternalizedEdge(e))
|
|
215
|
+
.map((e) => e.id));
|
|
166
216
|
const sys = { role: 'system', content: REFLECT_SYS };
|
|
167
|
-
const user = {
|
|
217
|
+
const user = {
|
|
218
|
+
role: 'user',
|
|
219
|
+
content: REFLECT_USER(transcript, sample, evidenceSnap.text),
|
|
220
|
+
};
|
|
168
221
|
const result = {
|
|
169
222
|
ts,
|
|
170
223
|
saves: 0,
|
|
@@ -175,7 +228,7 @@ export async function runReflection(transcript, signal) {
|
|
|
175
228
|
gcCapped: 0,
|
|
176
229
|
gcGced: 0,
|
|
177
230
|
};
|
|
178
|
-
const timeoutSignal = signal ?? AbortSignal.timeout(
|
|
231
|
+
const timeoutSignal = signal ?? AbortSignal.timeout(REFLECT_TIMEOUT_MS);
|
|
179
232
|
let content = null;
|
|
180
233
|
try {
|
|
181
234
|
const first = await fetchReflection([sys, user], timeoutSignal);
|
|
@@ -198,7 +251,18 @@ export async function runReflection(transcript, signal) {
|
|
|
198
251
|
}
|
|
199
252
|
}
|
|
200
253
|
catch (e) {
|
|
201
|
-
|
|
254
|
+
// 超时到期时 fetch/退避 sleep 抛的是 AbortError/DOMException,文案 'This operation
|
|
255
|
+
// was aborted' 完全无法区分原因;统一归类成可读的超时提示(秒数按实际信号预算)。
|
|
256
|
+
if (timeoutSignal.aborted) {
|
|
257
|
+
// 内部自建信号的预算由本模块常量决定,可给出准确秒数;外部传入的信号(retention
|
|
258
|
+
// 巩固)预算在调用方,不臆测数字。
|
|
259
|
+
result.error = signal
|
|
260
|
+
? '反思超时(后端持续失败或无响应)'
|
|
261
|
+
: `反思超时(${REFLECT_TIMEOUT_MS / 1000}s,后端持续失败或无响应)`;
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
result.error = e instanceof Error ? e.name + ': ' + e.message : String(e);
|
|
265
|
+
}
|
|
202
266
|
return result;
|
|
203
267
|
}
|
|
204
268
|
const plan = parsePlan(content);
|
|
@@ -221,8 +285,15 @@ export async function runReflection(transcript, signal) {
|
|
|
221
285
|
body: String(s.body ?? s.summary),
|
|
222
286
|
type: normalizeType(s.type),
|
|
223
287
|
});
|
|
224
|
-
if (r.ok)
|
|
288
|
+
if (r.ok) {
|
|
225
289
|
saves++;
|
|
290
|
+
// 新条目显式取代旧条目(标题/范围不同,不适合原地 update):回填取代链,
|
|
291
|
+
// 旧条目转 superseded(从默认索引隐藏但不删除,可审计)。
|
|
292
|
+
const oldId = typeof s.supersedes === 'string' ? s.supersedes.trim() : '';
|
|
293
|
+
if (oldId && oldId !== r.id) {
|
|
294
|
+
supersedeEntry(oldId, r.id, 'superseded by new entry from reflection');
|
|
295
|
+
}
|
|
296
|
+
}
|
|
226
297
|
}
|
|
227
298
|
}
|
|
228
299
|
if (Array.isArray(plan.updates)) {
|
|
@@ -269,6 +340,8 @@ export async function runReflection(transcript, signal) {
|
|
|
269
340
|
}
|
|
270
341
|
}
|
|
271
342
|
// 全局用户画像:挂到规范 person-primary、写 global 图(与项目 triples 分流)。
|
|
343
|
+
// M2 信念分级:反思**推断**的画像以 prov=reflection / confidence=0.4 落库——
|
|
344
|
+
// 不进 About you(L2),只进候选(L1),等用户确认或多会话佐证后晋升。
|
|
272
345
|
let profiles = 0;
|
|
273
346
|
if (Array.isArray(plan.profile) && plan.profile.length > 0) {
|
|
274
347
|
let personId = PRIMARY_PERSON_ID;
|
|
@@ -290,11 +363,87 @@ export async function runReflection(transcript, signal) {
|
|
|
290
363
|
dst: String(p.dst),
|
|
291
364
|
fact: p.fact ? String(p.fact) : undefined,
|
|
292
365
|
scope: 'global',
|
|
366
|
+
prov: 'reflection',
|
|
367
|
+
confidence: 0.4,
|
|
293
368
|
});
|
|
294
369
|
if (r.ok && !r.duplicate)
|
|
295
370
|
profiles++;
|
|
296
371
|
}
|
|
297
372
|
}
|
|
373
|
+
// 用户纠正桶(最高信号):失效同关系旧画像值,以 user_confirmed(1.0,直接 L2)安装新值。
|
|
374
|
+
// 单值关系即便不显式失效旧边,addTriple 也会按 (src,relation) 时序取代;这里多做一步
|
|
375
|
+
// 是为了 old 指向的非单值旧值(prefers/constraint 等多值关系)也能被精准撤回。
|
|
376
|
+
let corrections = 0;
|
|
377
|
+
const profileChangedFacts = [];
|
|
378
|
+
if (Array.isArray(plan.corrections)) {
|
|
379
|
+
let personId = PRIMARY_PERSON_ID;
|
|
380
|
+
try {
|
|
381
|
+
personId = ensurePrimaryPerson().id;
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
personId = PRIMARY_PERSON_ID;
|
|
385
|
+
}
|
|
386
|
+
for (const c of plan.corrections.slice(0, 6)) {
|
|
387
|
+
if (!c?.relation || !c.dst)
|
|
388
|
+
continue;
|
|
389
|
+
const relation = normalizeRelation(String(c.relation));
|
|
390
|
+
if (!isKnownRelation(relation, 'global'))
|
|
391
|
+
relViolations++;
|
|
392
|
+
const oldHint = typeof c.old === 'string' ? c.old.trim() : '';
|
|
393
|
+
invalidateProfileEdges(relation, oldHint || undefined);
|
|
394
|
+
const r = addTriple({
|
|
395
|
+
src: personId,
|
|
396
|
+
relation,
|
|
397
|
+
dst: String(c.dst),
|
|
398
|
+
fact: c.fact ? String(c.fact) : undefined,
|
|
399
|
+
scope: 'global',
|
|
400
|
+
prov: 'user_confirmed',
|
|
401
|
+
confidence: 1,
|
|
402
|
+
});
|
|
403
|
+
if (r.ok && !r.duplicate) {
|
|
404
|
+
corrections++;
|
|
405
|
+
const factText = c.fact ? String(c.fact) : String(c.dst);
|
|
406
|
+
profileChangedFacts.push(factText);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
// 环境证据投票:只能投本轮开始前快照里的边;同 id 一轮一票;不存在/本轮新建的 id 一律
|
|
411
|
+
// 丢弃(防自我强化)。以投票前后的内化态变化识别自动转正/降级。
|
|
412
|
+
let promotions = 0;
|
|
413
|
+
let demotions = 0;
|
|
414
|
+
let evidenceVotes = 0;
|
|
415
|
+
const promotionFacts = [];
|
|
416
|
+
const demotionFacts = [];
|
|
417
|
+
if (Array.isArray(plan.evidence)) {
|
|
418
|
+
const seen = new Set();
|
|
419
|
+
for (const v of plan.evidence.slice(0, 20)) {
|
|
420
|
+
const id = typeof v?.edgeId === 'string' ? v.edgeId.trim() : '';
|
|
421
|
+
if (!id || seen.has(id))
|
|
422
|
+
continue;
|
|
423
|
+
if (!evidenceSnap.votable.has(id))
|
|
424
|
+
continue;
|
|
425
|
+
const vote = typeof v.vote === 'string' ? v.vote.trim().toLowerCase() : '';
|
|
426
|
+
if (vote !== 'confirm' && vote !== 'contradict')
|
|
427
|
+
continue;
|
|
428
|
+
seen.add(id);
|
|
429
|
+
const was = beforeInternalized.has(id);
|
|
430
|
+
const vr = voteEdge(id, vote);
|
|
431
|
+
if (!vr.ok)
|
|
432
|
+
continue;
|
|
433
|
+
evidenceVotes++;
|
|
434
|
+
const eNow = loadScopeGraph('global').edges.find((x) => x.id === id);
|
|
435
|
+
const now = eNow ? isInternalizedEdge(eNow) : false;
|
|
436
|
+
const fact = evidenceSnap.statements.get(id) ?? id;
|
|
437
|
+
if (!was && now) {
|
|
438
|
+
promotions++;
|
|
439
|
+
promotionFacts.push(fact);
|
|
440
|
+
}
|
|
441
|
+
else if (was && !now) {
|
|
442
|
+
demotions++;
|
|
443
|
+
demotionFacts.push(fact);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
298
447
|
const gc = gcMemories();
|
|
299
448
|
result.saves = saves;
|
|
300
449
|
result.updates = updates;
|
|
@@ -302,6 +451,15 @@ export async function runReflection(transcript, signal) {
|
|
|
302
451
|
result.triples = triples;
|
|
303
452
|
result.profiles = profiles;
|
|
304
453
|
result.relViolations = relViolations;
|
|
454
|
+
result.corrections = corrections;
|
|
455
|
+
result.profileChanged = corrections > 0;
|
|
456
|
+
result.profileChangedFacts = profileChangedFacts.slice(0, 3);
|
|
457
|
+
result.promotions = promotions;
|
|
458
|
+
result.promotionFacts = promotionFacts.slice(0, 3);
|
|
459
|
+
result.demotions = demotions;
|
|
460
|
+
result.demotionFacts = demotionFacts.slice(0, 3);
|
|
461
|
+
if (evidenceVotes)
|
|
462
|
+
result.evidenceVotes = evidenceVotes;
|
|
305
463
|
result.gcDecayed = gc.decayed;
|
|
306
464
|
result.gcCapped = gc.capped;
|
|
307
465
|
result.gcGced = gc.gced;
|
|
@@ -318,30 +476,81 @@ function normalizeType(t) {
|
|
|
318
476
|
// ── 后台编排:kickoff / drain / 缓存 ─────────────────────────────────────────
|
|
319
477
|
let inflight = null;
|
|
320
478
|
let lastReflectResult = null;
|
|
321
|
-
/**
|
|
479
|
+
/**
|
|
480
|
+
* 自动反思节流(默认开启后必须配成本闸,否则每 reflectEveryN 轮一个后台 LLM 请求):
|
|
481
|
+
* - 每进程至多 N 次自动反思(/reflect 手动不受限);
|
|
482
|
+
* - 转录里 user 实质内容低于阈值不触发(纯工具轮/空轮没有可记的东西)。
|
|
483
|
+
* env:MOCODE_REFLECT_MAX_PER_SESSION 覆盖次数。
|
|
484
|
+
*/
|
|
485
|
+
const MAX_AUTO_REFLECTS = Math.max(1, Number(process.env.MOCODE_REFLECT_MAX_PER_SESSION) || 3);
|
|
486
|
+
const MIN_USER_CHARS = 40;
|
|
487
|
+
let autoReflectCount = 0;
|
|
488
|
+
/** 转录里是否有足够的"用户原话"值得反思(tool_call/assistant 行不计)。 */
|
|
489
|
+
export function hasSubstantialUserContent(transcript) {
|
|
490
|
+
const userText = transcript
|
|
491
|
+
.split('\n')
|
|
492
|
+
.filter((line) => line.startsWith('user:'))
|
|
493
|
+
.map((line) => line.slice(5).trim())
|
|
494
|
+
.join(' ')
|
|
495
|
+
.trim();
|
|
496
|
+
return userText.length >= MIN_USER_CHARS;
|
|
497
|
+
}
|
|
498
|
+
/** 测试专用:重置自动反思计数。 */
|
|
499
|
+
export function __resetReflectThrottleForTests() {
|
|
500
|
+
autoReflectCount = 0;
|
|
501
|
+
}
|
|
502
|
+
/** 摘要串(供 repl flush):存N 改N 忘N 图N [画像N 纠N 违N];有错误附上。 */
|
|
322
503
|
export function formatReflectResult(r) {
|
|
323
504
|
const parts = [`存${r.saves}`, `改${r.updates}`, `忘${r.forgets}`, `图${r.triples}`];
|
|
324
505
|
if (r.profiles)
|
|
325
|
-
parts.push(
|
|
506
|
+
parts.push(`画像候选${r.profiles}`);
|
|
507
|
+
if (r.corrections)
|
|
508
|
+
parts.push(`纠正${r.corrections}`);
|
|
509
|
+
if (r.promotions)
|
|
510
|
+
parts.push(`印证转正${r.promotions}`);
|
|
511
|
+
if (r.demotions)
|
|
512
|
+
parts.push(`反证降级${r.demotions}`);
|
|
326
513
|
if (r.relViolations)
|
|
327
514
|
parts.push(`违${r.relViolations}`);
|
|
328
515
|
if (r.gcDecayed || r.gcCapped || r.gcGced) {
|
|
329
516
|
parts.push(`遗忘(衰减${r.gcDecayed}/封顶${r.gcCapped}/清除${r.gcGced})`);
|
|
330
517
|
}
|
|
331
|
-
|
|
518
|
+
let line = `记忆反思:${parts.join(' ')}${r.error ? ` [${r.error}]` : ''}`;
|
|
519
|
+
// 关于人的信念被改动必须让用户有机会否决(区别于仓库事实的静默写入)。
|
|
520
|
+
// 不加 ANSI:repl flush 时整串已包 ui.gray。
|
|
521
|
+
if (r.profileChanged && r.profileChangedFacts?.length) {
|
|
522
|
+
line += `\n ↳ 已按你的纠正更新长期画像:${r.profileChangedFacts.join(';')}(/memory profile 可查看或撤销)`;
|
|
523
|
+
}
|
|
524
|
+
// 信念分级的自动升降级同样必须透明:它们改了常驻画像却没经过显式批准,要给用户否决机会。
|
|
525
|
+
if (r.promotions && r.promotionFacts?.length) {
|
|
526
|
+
line += `\n ↳ 多次行为印证,已自动内化:${r.promotionFacts.join(';')}(/memory drop 可撤销)`;
|
|
527
|
+
}
|
|
528
|
+
if (r.demotions && r.demotionFacts?.length) {
|
|
529
|
+
line += `\n ↳ 与近期行为反复相悖,已退回候选:${r.demotionFacts.join(';')}(/memory confirm 可恢复)`;
|
|
530
|
+
}
|
|
531
|
+
return line;
|
|
332
532
|
}
|
|
333
533
|
/**
|
|
334
|
-
* fire-and-forget 触发反思。已有在飞任务 /
|
|
534
|
+
* fire-and-forget 触发反思。已有在飞任务 / 记忆子系统总开关关闭 → 跳过。
|
|
535
|
+
* 自动触发(manual=false)还受两道成本闸:config.autoReflect 开关、每进程次数上限、
|
|
536
|
+
* 转录需含足够用户原话;手动 /reflect(manual=true)绕过前两道(仍要求记忆开关开)。
|
|
335
537
|
* 记忆关闭时反思毫无意义(没有可存的地方),且会误打日志、误弹摘要,故一并短路。
|
|
336
538
|
* repl 轮末调:与下一轮 agent 并发跑,不阻塞。
|
|
337
539
|
*/
|
|
338
|
-
export function kickoffReflection(transcript) {
|
|
540
|
+
export function kickoffReflection(transcript, manual = false) {
|
|
339
541
|
if (inflight)
|
|
340
542
|
return;
|
|
341
|
-
if (!config.autoReflect)
|
|
342
|
-
return;
|
|
343
543
|
if (!isMemoryEnabled())
|
|
344
544
|
return;
|
|
545
|
+
if (!manual) {
|
|
546
|
+
if (!config.autoReflect)
|
|
547
|
+
return;
|
|
548
|
+
if (autoReflectCount >= MAX_AUTO_REFLECTS)
|
|
549
|
+
return;
|
|
550
|
+
if (!hasSubstantialUserContent(transcript))
|
|
551
|
+
return;
|
|
552
|
+
autoReflectCount++;
|
|
553
|
+
}
|
|
345
554
|
inflight = (async () => {
|
|
346
555
|
try {
|
|
347
556
|
const r = await runReflection(transcript);
|
|
@@ -65,6 +65,21 @@ export const RELATION_ALIASES = {
|
|
|
65
65
|
};
|
|
66
66
|
const PROJECT_SET = new Set(PROJECT_RELATIONS);
|
|
67
67
|
const PROFILE_SET = new Set(PROFILE_RELATIONS);
|
|
68
|
+
/**
|
|
69
|
+
* 画像轨的**单值关系**(Wikidata single-value 约束的最小落地):同一主语在该关系上
|
|
70
|
+
* 只允许一条 active 边——写入新值(哪怕 dst 不同,如换城市/换工作)时,同 src+relation
|
|
71
|
+
* 的旧边一律时序失效。多值关系(prefers / has_hobby / constraint…)不在此列。
|
|
72
|
+
*/
|
|
73
|
+
const PROFILE_SINGLE_VALUE = new Set([
|
|
74
|
+
'named',
|
|
75
|
+
'has_role',
|
|
76
|
+
'works_at',
|
|
77
|
+
'located_in',
|
|
78
|
+
'speaks',
|
|
79
|
+
'verbosity',
|
|
80
|
+
'communication_style',
|
|
81
|
+
'current_goal',
|
|
82
|
+
]);
|
|
68
83
|
/** 关系名归一:lowercase + 空白转下划线 + 别名映射。 */
|
|
69
84
|
export function normalizeRelation(raw) {
|
|
70
85
|
const base = String(raw ?? '')
|
|
@@ -78,6 +93,10 @@ export function isKnownRelation(relation, scope) {
|
|
|
78
93
|
const r = normalizeRelation(relation);
|
|
79
94
|
return scope === 'global' ? PROFILE_SET.has(r) : PROJECT_SET.has(r);
|
|
80
95
|
}
|
|
96
|
+
/** 画像关系是否单值(换值即作废旧边;先归一再判定)。 */
|
|
97
|
+
export function isSingleValueProfile(relation) {
|
|
98
|
+
return PROFILE_SINGLE_VALUE.has(normalizeRelation(relation));
|
|
99
|
+
}
|
|
81
100
|
/** 注入反思提示词的紧凑词表(按 scope)。 */
|
|
82
101
|
export function relationCheatSheet(scope) {
|
|
83
102
|
return scope === 'global' ? PROFILE_RELATIONS.join(', ') : PROJECT_RELATIONS.join(', ');
|
package/dist/memory/store.js
CHANGED
|
@@ -225,6 +225,25 @@ export function updateEntry(id, patch) {
|
|
|
225
225
|
writeAtomic(p, entries);
|
|
226
226
|
return { ok: true };
|
|
227
227
|
}
|
|
228
|
+
/**
|
|
229
|
+
* 把旧条目标记为被新条目取代(status=superseded + supersededBy 链,不删除可审计)。
|
|
230
|
+
* 与 forgetEntry 的区别:这是 belief-revision 语义——"旧信念被新事实取代",
|
|
231
|
+
* 而不是"过期清理"。pinned 条目同样允许被取代(取代链是显式修正,不是自动遗忘)。
|
|
232
|
+
*/
|
|
233
|
+
export function supersedeEntry(oldId, newId, reason) {
|
|
234
|
+
const all = loadAll();
|
|
235
|
+
const oldE = all.find((x) => x.id === oldId);
|
|
236
|
+
if (!oldE)
|
|
237
|
+
return { ok: false, notFound: true };
|
|
238
|
+
oldE.status = 'superseded';
|
|
239
|
+
oldE.supersededBy = newId;
|
|
240
|
+
oldE.updatedAt = nowIso();
|
|
241
|
+
if (reason)
|
|
242
|
+
oldE.lastUpdateReason = reason;
|
|
243
|
+
const p = pathForScope(oldE.scope);
|
|
244
|
+
writeAtomic(p, all.filter((x) => x.scope === oldE.scope));
|
|
245
|
+
return { ok: true };
|
|
246
|
+
}
|
|
228
247
|
/** 归档(默认,可复活)/ 硬删;pinned 拒删。 */
|
|
229
248
|
export function forgetEntry(id, mode = 'archive') {
|
|
230
249
|
const all = loadAll();
|
|
@@ -1,14 +1,54 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* 记忆命令组:/memory · /reflect
|
|
2
|
+
* 记忆命令组:/memory · /reflect · /memory profile|confirm|drop
|
|
3
3
|
*
|
|
4
|
-
* 只读概览 +
|
|
5
|
-
*
|
|
4
|
+
* 只读概览 + 后台反思触发 + 长期画像检视/纠错。/memory_switch /memory_status 是
|
|
5
|
+
* **配置写入**命令,与 /subagent /fe /mcp 同属 tool-group,放 tool-group.ts,不在这里。
|
|
6
|
+
* 注意:顶层 /profile 被刻意禁用(见 tests/tool-profiles.test.ts),画像命令并入 /memory 组。
|
|
6
7
|
*/
|
|
7
8
|
import * as layout from '../../ui/layout.js';
|
|
8
9
|
import { ui } from '../../ui/theme.js';
|
|
9
10
|
import { isMemoryEnabled } from '../../config/index.js';
|
|
10
|
-
import {
|
|
11
|
+
import { getAgentMode } from '../../agent/mode.js';
|
|
12
|
+
import { kickoffReflection, snapshotTranscript, loadAll, listInternalizedProfile, listProfileCandidates, promoteEdge, invalidateEdge, } from '../../memory/index.js';
|
|
11
13
|
import { unhandled, next } from './types.js';
|
|
14
|
+
/** /profile 改动画像后,让 About you 段(history[0])立刻反映,不用等重启。 */
|
|
15
|
+
function refreshSystemPrompt(ctx) {
|
|
16
|
+
ctx.history[0] = { role: 'system', content: ctx.buildSystemMessage(getAgentMode() === 'plan') };
|
|
17
|
+
ctx.refreshStatusBase(ctx.history);
|
|
18
|
+
}
|
|
19
|
+
/** 渲染 /profile:已内化(L2)与待确认候选(L1)两段。 */
|
|
20
|
+
function renderProfile() {
|
|
21
|
+
const internalized = listInternalizedProfile();
|
|
22
|
+
const candidates = listProfileCandidates();
|
|
23
|
+
const ev = (e) => {
|
|
24
|
+
const c = e?.confirmed ?? 0;
|
|
25
|
+
const x = e?.contradicted ?? 0;
|
|
26
|
+
return c || x ? ` [印证${c}/相悖${x}]` : '';
|
|
27
|
+
};
|
|
28
|
+
const lines = [];
|
|
29
|
+
lines.push(`${ui.accent}长期画像(已内化,每轮常驻 About you)${ui.reset}`);
|
|
30
|
+
if (internalized.length === 0) {
|
|
31
|
+
lines.push(`${ui.dim} (暂无;用户亲述/确认,或多次行为印证零反驳的稳定事实才会进这里)${ui.reset}`);
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
for (const c of internalized) {
|
|
35
|
+
lines.push(` ${ui.accent}${c.edge.id}${ui.reset} ${c.text}${ui.dim}${ev(c.edge.evidence)}${ui.reset}`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
lines.push('');
|
|
39
|
+
lines.push(`${ui.accent}待确认候选(反思推断,未内化、不常驻)${ui.reset}`);
|
|
40
|
+
if (candidates.length === 0) {
|
|
41
|
+
lines.push(`${ui.dim} (暂无)${ui.reset}`);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
for (const c of candidates) {
|
|
45
|
+
lines.push(` ${ui.dim}${c.edge.id}${ui.reset} ${c.text} ${ui.dim}[conf ${c.edge.confidence ?? '?'}${ev(c.edge.evidence)}]${ui.reset}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
lines.push('');
|
|
49
|
+
lines.push(`${ui.dim}/memory confirm <edge-id> 确认候选并内化 · /memory drop <edge-id> 撤销某条${ui.reset}`);
|
|
50
|
+
return lines.join('\n') + '\n';
|
|
51
|
+
}
|
|
12
52
|
export const memoryCommands = [
|
|
13
53
|
(ctx) => {
|
|
14
54
|
if (ctx.line !== '/memory')
|
|
@@ -44,8 +84,53 @@ export const memoryCommands = [
|
|
|
44
84
|
return next();
|
|
45
85
|
}
|
|
46
86
|
// 手动触发后台反思 pass(不等;完成后下次 INPUT 态显摘要)。
|
|
47
|
-
|
|
87
|
+
// manual=true:绕过自动节流(次数/转录闸门),但记忆总开关关闭时仍短路。
|
|
88
|
+
kickoffReflection(snapshotTranscript(ctx.history, 20), true);
|
|
48
89
|
layout.contentWrite(`${ui.dim}(反思已触发,后台进行;完成后下次输入态显示摘要。日志见 .mocode/memory.log)${ui.reset}\n`);
|
|
49
90
|
return next();
|
|
50
91
|
},
|
|
92
|
+
(ctx) => {
|
|
93
|
+
if (ctx.line !== '/memory profile')
|
|
94
|
+
return unhandled();
|
|
95
|
+
if (!isMemoryEnabled()) {
|
|
96
|
+
layout.contentWrite(`${ui.dim}(记忆子系统已关闭,/memory profile 无效。用 /memory_switch 打开)${ui.reset}\n`);
|
|
97
|
+
return next();
|
|
98
|
+
}
|
|
99
|
+
layout.contentWrite(renderProfile());
|
|
100
|
+
return next();
|
|
101
|
+
},
|
|
102
|
+
(ctx) => {
|
|
103
|
+
if (!ctx.line.startsWith('/memory confirm'))
|
|
104
|
+
return unhandled();
|
|
105
|
+
const edgeId = ctx.line.slice('/memory confirm'.length).trim();
|
|
106
|
+
if (!edgeId) {
|
|
107
|
+
layout.contentWrite(`${ui.dim}用法:/memory confirm <edge-id>(先 /memory profile 看候选)${ui.reset}\n`);
|
|
108
|
+
return next();
|
|
109
|
+
}
|
|
110
|
+
const r = promoteEdge(edgeId);
|
|
111
|
+
if (!r.ok) {
|
|
112
|
+
layout.contentWrite(`${ui.dim}(确认失败:${r.reason})${ui.reset}\n`);
|
|
113
|
+
return next();
|
|
114
|
+
}
|
|
115
|
+
refreshSystemPrompt(ctx);
|
|
116
|
+
layout.contentWrite(`${ui.dim}(已确认并内化 [${edgeId}],下一轮起常驻 About you)${ui.reset}\n`);
|
|
117
|
+
return next();
|
|
118
|
+
},
|
|
119
|
+
(ctx) => {
|
|
120
|
+
if (!ctx.line.startsWith('/memory drop'))
|
|
121
|
+
return unhandled();
|
|
122
|
+
const edgeId = ctx.line.slice('/memory drop'.length).trim();
|
|
123
|
+
if (!edgeId) {
|
|
124
|
+
layout.contentWrite(`${ui.dim}用法:/memory drop <edge-id>(先 /memory profile 看列表)${ui.reset}\n`);
|
|
125
|
+
return next();
|
|
126
|
+
}
|
|
127
|
+
const r = invalidateEdge(edgeId, 'profile-dropped');
|
|
128
|
+
if (!r.ok) {
|
|
129
|
+
layout.contentWrite(`${ui.dim}(撤销失败:${r.reason})${ui.reset}\n`);
|
|
130
|
+
return next();
|
|
131
|
+
}
|
|
132
|
+
refreshSystemPrompt(ctx);
|
|
133
|
+
layout.contentWrite(`${ui.dim}(已撤销画像 [${edgeId}],时序失效、可审计;下一轮 About you 不再含它)${ui.reset}\n`);
|
|
134
|
+
return next();
|
|
135
|
+
},
|
|
51
136
|
];
|
package/dist/repl/commands.js
CHANGED
|
@@ -44,6 +44,9 @@ export function buildSlashCommands() {
|
|
|
44
44
|
{ name: 'off', value: '/memory_switch off', desc: d('commands.memoryOff') },
|
|
45
45
|
{ name: 'status', value: '/memory_status', desc: d('commands.memoryStatus') },
|
|
46
46
|
{ name: 'reflect', value: '/reflect', desc: d('commands.memoryReflect') },
|
|
47
|
+
{ name: 'profile', value: '/memory profile', desc: d('commands.memoryProfile') },
|
|
48
|
+
{ name: 'confirm', value: '/memory confirm ', submit: false, desc: d('commands.memoryProfileConfirm') },
|
|
49
|
+
{ name: 'drop', value: '/memory drop ', submit: false, desc: d('commands.memoryProfileDrop') },
|
|
47
50
|
],
|
|
48
51
|
},
|
|
49
52
|
{ name: '/init', desc: d('commands.memoryInit') },
|
package/dist/repl/runtime.js
CHANGED
|
@@ -24,7 +24,7 @@ import { renderChip } from '../attachments/image.js';
|
|
|
24
24
|
import { contextState, appendCurrentSessionRuntimeEvent } from '../session/index.js';
|
|
25
25
|
import { effectiveSystemPrompt } from '../skills/index.js';
|
|
26
26
|
import { clearSkillActivation } from '../skills/activation.js';
|
|
27
|
-
import { buildMemoryIndexSection, buildAboutYouSection, buildProjectGraphHint, initPersona, kickoffReflection, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, } from '../memory/index.js';
|
|
27
|
+
import { buildMemoryIndexSection, buildAboutYouSection, buildProjectGraphHint, initPersona, gcMemories, kickoffReflection, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, } from '../memory/index.js';
|
|
28
28
|
import { collectQueryHistory } from '../session/query-history.js';
|
|
29
29
|
import { ToolPolicyController } from '../tools/policy.js';
|
|
30
30
|
import { routeToolGroups } from '../tools/router.js';
|
|
@@ -201,6 +201,16 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
|
|
|
201
201
|
// 启动期一次性身份归一(幂等,best-effort):把全局图里的用户指称碎片并入
|
|
202
202
|
// person-primary,随后 About you 段才能渲染出完整画像。
|
|
203
203
|
initPersona(isMemoryEnabled());
|
|
204
|
+
// 遗忘 GC 与反思解耦:启动时跑一次(30 天衰减/90 天清除/封顶),
|
|
205
|
+
// 不再依赖 AUTO_REFLECT 是否开启。静默容错——GC 失败绝不拖垮 REPL 启动。
|
|
206
|
+
if (isMemoryEnabled()) {
|
|
207
|
+
try {
|
|
208
|
+
gcMemories();
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
// best-effort
|
|
212
|
+
}
|
|
213
|
+
}
|
|
204
214
|
// 开关现读:运行时 /memory_switch 重建 history[0] 时,About you 与 Memory Index 同步显隐。
|
|
205
215
|
const buildSystemMessage = (planMode) => {
|
|
206
216
|
const memoryOn = isMemoryEnabled();
|
|
@@ -98,7 +98,7 @@ export const editFileTool = {
|
|
|
98
98
|
}
|
|
99
99
|
const toLf = (s) => s.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
|
100
100
|
// multi:数组形状校验(schema 已守,这里给富指导并归一化 CRLF)。
|
|
101
|
-
|
|
101
|
+
const multiEdits = [];
|
|
102
102
|
if (mode === 'multi') {
|
|
103
103
|
const arr = args.replacements;
|
|
104
104
|
if (!Array.isArray(arr) || arr.length === 0) {
|
|
@@ -1,19 +1,31 @@
|
|
|
1
1
|
import { forgetEntry } from '../../memory/store.js';
|
|
2
|
+
import { invalidateEdge } from '../../memory/graph.js';
|
|
2
3
|
// ---------- memory_forget ----------
|
|
3
|
-
//
|
|
4
|
+
// 遗忘两类对象:
|
|
5
|
+
// - 记忆条目(默认):归档(archived,从索引/默认搜索隐藏,可复活)或 mode=delete 硬删;
|
|
6
|
+
// pinned 拒删。
|
|
7
|
+
// - 图谱边(kind=edge,id 形如 edge-…):时序失效(invalidAt,不删除可审计),
|
|
8
|
+
// 这是撤销错误画像/错误三元组的产品内出口(此前只能手改 memory-graph.json)。
|
|
4
9
|
export const memoryForgetTool = {
|
|
5
10
|
name: 'memory_forget',
|
|
6
|
-
description: "Forget a memory entry
|
|
11
|
+
description: "Forget a memory entry (kind=entry, default): archive (hidden, revivable via memory_update) or mode=delete hard-delete; pinned entries can't be deleted (unpin first). " +
|
|
12
|
+
"Or invalidate a knowledge-graph edge (kind=edge, id starts with 'edge-', shown by memory_graph neighbors/path): temporally revoked, kept for audit. Use edge to correct a wrong profile fact or triple.",
|
|
7
13
|
risk: 'confirm',
|
|
8
14
|
parameters: {
|
|
9
15
|
type: 'object',
|
|
10
16
|
properties: {
|
|
11
|
-
id: { type: 'string' },
|
|
17
|
+
id: { type: 'string', description: 'Entry id, or edge id (edge-…) when kind=edge' },
|
|
12
18
|
mode: {
|
|
13
19
|
type: 'string',
|
|
14
20
|
enum: ['archive', 'delete'],
|
|
15
|
-
description: '
|
|
21
|
+
description: 'kind=entry only: default archive',
|
|
16
22
|
},
|
|
23
|
+
kind: {
|
|
24
|
+
type: 'string',
|
|
25
|
+
enum: ['entry', 'edge', 'auto'],
|
|
26
|
+
description: "What to forget: entry (default), edge (graph triple, id 'edge-…'), or auto (edge-* prefix → edge, else entry)",
|
|
27
|
+
},
|
|
28
|
+
reason: { type: 'string', description: 'Why it is forgotten/withdrawn (audit trail for edges)' },
|
|
17
29
|
},
|
|
18
30
|
required: ['id'],
|
|
19
31
|
},
|
|
@@ -21,12 +33,21 @@ export const memoryForgetTool = {
|
|
|
21
33
|
const id = String(args.id ?? '').trim();
|
|
22
34
|
if (!id)
|
|
23
35
|
return '错误:缺少 id。';
|
|
36
|
+
const reason = typeof args.reason === 'string' ? args.reason.trim() : '';
|
|
37
|
+
const kind = args.kind === 'edge' || args.kind === 'entry' ? args.kind : 'auto';
|
|
38
|
+
const wantEdge = kind === 'edge' || (kind === 'auto' && id.startsWith('edge-'));
|
|
39
|
+
if (wantEdge) {
|
|
40
|
+
const r = invalidateEdge(id, reason || 'manual-forget');
|
|
41
|
+
if (r.ok)
|
|
42
|
+
return `已撤销图谱边 [${id}]${reason ? `(原因:${reason})` : ''}(时序失效,可审计)。`;
|
|
43
|
+
return `错误:找不到 active 图谱边 id="${id}"。`;
|
|
44
|
+
}
|
|
24
45
|
const mode = args.mode === 'delete' ? 'delete' : 'archive';
|
|
25
46
|
const r = forgetEntry(id, mode);
|
|
26
47
|
if (r.ok)
|
|
27
48
|
return `已${mode === 'delete' ? '硬删' : '归档'}记忆 [${id}]。`;
|
|
28
49
|
if ('notFound' in r)
|
|
29
|
-
return `错误:找不到记忆 id="${id}"
|
|
50
|
+
return `错误:找不到记忆 id="${id}"。(图谱边请用 kind=edge)`;
|
|
30
51
|
// pinned
|
|
31
52
|
return `错误:[${id}] 已钉住,拒绝遗忘。先 memory_update(id="${id}", pinned=false) 解钉。`;
|
|
32
53
|
},
|
|
@@ -45,6 +45,11 @@ export const memoryGraphTool = {
|
|
|
45
45
|
enum: ['project', 'global'],
|
|
46
46
|
description: 'add: which graph file to write, default project',
|
|
47
47
|
},
|
|
48
|
+
prov: {
|
|
49
|
+
type: 'string',
|
|
50
|
+
enum: ['user_said', 'user_confirmed', 'tool_observed', 'reflection'],
|
|
51
|
+
description: 'add: provenance for belief grading. Global profile facts the user stated directly → user_said (internalized); reflection-only guesses → reflection (0.4, not internalized until confirmed).',
|
|
52
|
+
},
|
|
48
53
|
},
|
|
49
54
|
required: ['action'],
|
|
50
55
|
},
|
|
@@ -98,12 +103,14 @@ export const memoryGraphTool = {
|
|
|
98
103
|
const dst = String(args.dst ?? '').trim();
|
|
99
104
|
if (!src || !relation || !dst)
|
|
100
105
|
return '错误:add 需要 src、relation、dst。';
|
|
106
|
+
const prov = ['user_said', 'user_confirmed', 'tool_observed', 'reflection'].find((p) => args.prov === p);
|
|
101
107
|
const r = addTriple({
|
|
102
108
|
src,
|
|
103
109
|
relation,
|
|
104
110
|
dst,
|
|
105
111
|
fact: typeof args.fact === 'string' ? args.fact : undefined,
|
|
106
112
|
scope: args.scope === 'global' ? 'global' : 'project',
|
|
113
|
+
prov,
|
|
107
114
|
});
|
|
108
115
|
if (!r.ok)
|
|
109
116
|
return `错误:三元组未写入 (${r.reason})。`;
|