mocode-ai 1.9.0 → 1.9.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.
@@ -26,7 +26,7 @@ import { modelSupportsVision } from '../llm/capabilities.js';
26
26
  import { contextState, appendCurrentSessionRuntimeEvent } from '../session/index.js';
27
27
  import { effectiveSystemPrompt, skillsChangedSinceLastObserve } from '../skills/index.js';
28
28
  import { clearSkillActivation } from '../skills/activation.js';
29
- import { buildMemoryIndexSection, buildAboutYouSection, buildProjectGraphHint, buildEpisodeSection, initPersona, gcMemories, kickoffReflection, kickoffConsolidation, drainMemoryBackground, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, flushRecallStats, flushProactiveStats, writeMemoryHealth, resetProactiveTurn, captureMemoryBaseline, buildMemoryTailSection, } from '../memory/index.js';
29
+ import { buildMemoryIndexSection, buildAboutYouSection, buildProjectGraphHint, buildEpisodeSection, initPersona, gcMemories, kickoffReflection, kickoffConsolidation, reflectOnExit, getLastReflectResult, clearLastReflectResult, snapshotTranscript, formatReflectResult, flushRecallStats, flushProactiveStats, flushTurnRecallStats, writeMemoryHealth, resetProactiveTurn, captureMemoryBaseline, buildMemoryTailSection, loadAll, } from '../memory/index.js';
30
30
  import { finalizeCurrentEpisode } from './episode-finalize.js';
31
31
  import { collectQueryHistory } from '../session/query-history.js';
32
32
  import { ToolPolicyController } from '../tools/policy.js';
@@ -408,6 +408,19 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
408
408
  if (!history.some((m) => m.role === 'user')) {
409
409
  layout.writeWelcomeBlock(welcomeLines());
410
410
  }
411
+ // R9.4 空库提示:记忆开着但一条 active 都没有 → 说清「怎么让它有」,而不是让用户
412
+ // 对着空库空转。只在启动时提示一次(不是每轮),且不给 UI 常驻噪音:
413
+ // 「零感知」路线要求的是**行为**里有记忆,不是界面上反复提醒记忆的存在。
414
+ if (isMemoryEnabled()) {
415
+ try {
416
+ const hasActive = loadAll().some((e) => e.status === 'active');
417
+ if (!hasActive)
418
+ layout.contentWrite(`${ui.dim} ${t('memory.emptyHint')}${ui.reset}\n`);
419
+ }
420
+ catch {
421
+ // 读库失败不阻塞启动(与 gcMemories 同口径)
422
+ }
423
+ }
411
424
  // 启动时限频自动 GC(24h 闸门,归档+purge 全做):fire-and-forget,
412
425
  // 不阻塞进入主循环;runRetention 内部归档本地秒完、reflection 后台跑。可用 MOCODE_AUTO_GC=false 关闭。
413
426
  void runtime.session.autoGc().catch(() => undefined);
@@ -674,6 +687,8 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
674
687
  // 与召回计数一起在轮末落一次。健康快照仍只由 /memory health 与退出路径写,
675
688
  // 因为它要读全库 + 算 stale,不该每轮付这个成本。
676
689
  flushProactiveStats();
690
+ // R18:每轮静默召回的计数同样在内存累计,轮末落一次。
691
+ flushTurnRecallStats();
677
692
  turnCount++;
678
693
  if (turnCount % config.reflectEveryN === 0) {
679
694
  kickoffReflection(snapshotTranscript(history, 20));
@@ -834,6 +849,11 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
834
849
  commands: buildSlashCommands(),
835
850
  onCycleMode: cycleMode,
836
851
  onPasteImage: pasteImageFromClipboard,
852
+ hasPendingAttachments: () => pendingAttachments.length > 0,
853
+ clearPendingAttachments: () => {
854
+ pendingAttachments = [];
855
+ syncPendingAttachChips();
856
+ },
837
857
  // Ctrl+R / Ctrl+P 历史搜索候选源:惰性工厂——当前会话内存 queryHistory + 最近落盘会话,
838
858
  // 聚合要读盘,只有面板真正打开(Ctrl+R/P)才求值,平常轮次零开销
839
859
  history: () => collectQueryHistory(queryHistory).map((e) => e.text),
@@ -1035,16 +1055,23 @@ export async function startRepl(initialHistory, sessionId, sandboxRootOverride,
1035
1055
  }
1036
1056
  }
1037
1057
  }
1038
- // R6.1:退出前落情节(纯本地、零 LLM,毫秒级;放在 drain 之前让两者并行收尾)。
1058
+ // R6.1:退出前落情节(纯本地、零 LLM,毫秒级;放在反思之前——反思能从本轮情节里
1059
+ // 读到「这个会话干了什么」,顺序反了就少一段素材)。
1039
1060
  finalizeCurrentEpisode(currentSessionId, history, queryHistory);
1040
1061
  // R4.1:退出时写一份健康快照。放这里而不是每轮:它要读全库 + 算 stale,
1041
- // 每次退出一个文件,正好构成一条随时间推移的趋势线。
1062
+ // 每轮付这个成本不值当。
1063
+ // 注意:healthPath() 是**固定路径**(.mocode/memory-health.json),每次都是覆盖写,
1064
+ // 所以磁盘上只有「最后一次生成」的那份,不构成历史趋势线。想留存历史需自行按时间戳
1065
+ // 复制出去。快照只在退出与 /memory health 时生成,而 /memory health 是现场重算的,
1066
+ // 因此读这个文件判断现状前先看它的 generatedAt。
1067
+ // 退出兜底反思:短会话(1–2 轮)永远到不了 cadence,退出是唯一能确保发生的边界。
1068
+ // reflectOnExit 内部已含 drain(等在飞收尾),所以不必再单独调 drainMemoryBackground。
1069
+ // 放在写健康快照**之前**:这样快照能看到本轮新增的条目与计数,不会留下"刚反思完、
1070
+ // 快照却还是旧数字"的错位。
1071
+ await reflectOnExit(snapshotTranscript(history, 20));
1042
1072
  flushProactiveStats();
1073
+ flushTurnRecallStats();
1043
1074
  writeMemoryHealth(isMemoryEnabled());
1044
- // 退出前等在飞反思收尾。注意:Ctrl+C 在 TUI(raw 模式)下是按键不是 SIGINT,空输入框时
1045
- // 由主循环 catch { break } 接住,因此**会**走到这里等反思跑完;只有非 raw 模式下的
1046
- // 进程级 SIGINT → process.exit(130) 才跳过(fire-and-forget 不承诺中断时完成)。
1047
- await drainMemoryBackground();
1048
1075
  await runtime.close();
1049
1076
  await closeAllMcp();
1050
1077
  layout.exitAltScreen();
@@ -54,6 +54,7 @@ export class Runtime {
54
54
  return this.context.sessionStore.list(limit);
55
55
  },
56
56
  clear: () => this.createSession(true),
57
+ fork: (sourceId) => this.forkSession(sourceId),
57
58
  gc: (async (opts = {}) => {
58
59
  this.assertIdle('gc sessions');
59
60
  const root = this.context.sessionStore.sessionsRoot;
@@ -272,6 +273,18 @@ export class Runtime {
272
273
  this.emit(cleared ? 'session.cleared' : 'session.created', { sessionId: id });
273
274
  return id;
274
275
  }
276
+ forkSession(sourceId) {
277
+ this.assertIdle('fork session');
278
+ const srcId = sourceId ?? this.context.sessionStore.getCurrentSessionId();
279
+ if (!srcId)
280
+ throw new Error('Cannot fork without an active session.');
281
+ const newId = this.context.sessionStore.forkSession(srcId);
282
+ if (!newId)
283
+ return null;
284
+ // 注意:不 setCurrentSessionId、不重置 rollback 状态——当前窗口继续原会话。
285
+ this.emit('session.forked', { sourceSessionId: srcId, sessionId: newId });
286
+ return newId;
287
+ }
275
288
  resumeSession(id) {
276
289
  this.assertIdle('resume session');
277
290
  const loaded = this.context.sessionStore.load(id, { restoreAssets: true });
@@ -13,7 +13,9 @@ import { collectArtifactRefs } from '../context/artifacts.js';
13
13
  import { writeCompactionSnapshot } from './notes.js';
14
14
  import { getActiveSessionStore } from './store.js';
15
15
  import { getCurrentSessionId } from './state.js';
16
+ import { appendGlobalUsage } from './global-usage.js';
16
17
  import { toUsageRecord } from './usage-stats.js';
18
+ import { getWorkspaceRoot } from '../workspace/index.js';
17
19
  /** 默认兼容依赖:旧调用方继续读取进程级 config/chat。 */
18
20
  export const defaultCompactionRuntime = {
19
21
  config,
@@ -655,6 +657,20 @@ async function forkSummarize(prefix, instruction, signal, runtime, activeTools,
655
657
  const sessionId = getCurrentSessionId();
656
658
  if (rec && sessionId)
657
659
  getActiveSessionStore().appendUsage(sessionId, rec);
660
+ // 全局跨工作空间账本:压缩调用单列 phase=compact(/usage 汇总区分主对话与压缩开销)。
661
+ if (r.usage && sessionId) {
662
+ appendGlobalUsage({
663
+ workspace: getWorkspaceRoot(),
664
+ model: config.model,
665
+ phase: 'compact',
666
+ sessionId,
667
+ input: r.usage.promptTokens,
668
+ output: r.usage.completionTokens,
669
+ cached: r.usage.cachedTokens,
670
+ reasoning: r.usage.reasoningTokens,
671
+ cacheCreation: r.usage.cacheCreationTokens,
672
+ });
673
+ }
658
674
  }
659
675
  // 同 legacy:幻觉 tool_calls 或空 content → 失败(调用方回落 microcompact)。
660
676
  if (r.toolCalls.length > 0 || !r.content)
@@ -0,0 +1,173 @@
1
+ /**
2
+ * 跨工作空间的全局 token 账本。
3
+ *
4
+ * 会话级 usage.jsonl 按 <workspace>/.mocode/sessions/<id>/ 分散存放,且不含
5
+ * 时间/工作区/模型字段,无法跨项目汇总。每次模型调用在写会话级 usage 之外,
6
+ * 再向全局账本 `~/.mocode/usage-daily.jsonl` 追加一行(含时间、本地日期、
7
+ * 工作区、模型、sessionId、phase),/usage 据此做按天/工作区/模型汇总。
8
+ *
9
+ * 与 SessionStore.appendUsage 同款策略:同步 append、失败静默(best-effort,
10
+ * 记账绝不阻塞模型调用)。只统计本功能上线后新产生的调用。
11
+ */
12
+ import fs from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ /** 全局账本路径:跨工作空间,故放 ~/.mocode 而非项目目录。 */
16
+ export const GLOBAL_USAGE_PATH = path.join(os.homedir(), '.mocode', 'usage-daily.jsonl');
17
+ /** 本地日期 YYYY-MM-DD;不引时区库——运行机器本地时间即用户口径的"天"。 */
18
+ export function localDay(d = new Date()) {
19
+ const p = (n) => String(n).padStart(2, '0');
20
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
21
+ }
22
+ /** 追加一行全局用量。任何 I/O 失败静默——记账不能拖垮主流程。 */
23
+ export function appendGlobalUsage(input) {
24
+ try {
25
+ const now = new Date();
26
+ const rec = {
27
+ ts: now.toISOString(),
28
+ day: localDay(now),
29
+ input: input.input,
30
+ output: input.output,
31
+ cached: input.cached ?? 0,
32
+ reasoning: input.reasoning ?? 0,
33
+ cacheCreation: input.cacheCreation ?? 0,
34
+ workspace: input.workspace,
35
+ model: input.model,
36
+ phase: input.phase,
37
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
38
+ };
39
+ fs.mkdirSync(path.dirname(GLOBAL_USAGE_PATH), { recursive: true });
40
+ fs.appendFileSync(GLOBAL_USAGE_PATH, `${JSON.stringify(rec)}\n`, 'utf8');
41
+ }
42
+ catch {
43
+ // best-effort, see file header
44
+ }
45
+ }
46
+ /** 读全部全局记录;文件不存在或损坏行跳过。 */
47
+ export function readGlobalUsage() {
48
+ let raw;
49
+ try {
50
+ raw = fs.readFileSync(GLOBAL_USAGE_PATH, 'utf8');
51
+ }
52
+ catch {
53
+ return [];
54
+ }
55
+ const out = [];
56
+ for (const line of raw.split('\n')) {
57
+ const trimmed = line.trim();
58
+ if (!trimmed)
59
+ continue;
60
+ try {
61
+ const rec = JSON.parse(trimmed);
62
+ if (typeof rec.day === 'string' && typeof rec.input === 'number' && typeof rec.output === 'number') {
63
+ out.push(rec);
64
+ }
65
+ }
66
+ catch {
67
+ // 跳过损坏行
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+ function emptyBucket() {
73
+ return { input: 0, output: 0, cached: 0, reasoning: 0, cacheCreation: 0, calls: 0 };
74
+ }
75
+ function addInto(b, r) {
76
+ b.input += r.input;
77
+ b.output += r.output;
78
+ b.cached += r.cached;
79
+ b.reasoning += r.reasoning;
80
+ b.cacheCreation += r.cacheCreation;
81
+ b.calls++;
82
+ }
83
+ /** 窗口起点:含今天在内往前 days 天。 */
84
+ export function windowStart(days, today = new Date()) {
85
+ const d = new Date(today);
86
+ d.setDate(d.getDate() - (Math.max(1, days) - 1));
87
+ return localDay(d);
88
+ }
89
+ /**
90
+ * 聚合最近 days 天的全局用量:按天(补齐零天)、按工作区、按模型、按 phase;
91
+ * 另给 distinct session / workspace 计数。组数按总 token 降序。
92
+ */
93
+ export function summarizeGlobalUsage(records, days) {
94
+ const toDay = localDay();
95
+ const fromDay = windowStart(days);
96
+ const inWindow = records.filter((r) => r.day >= fromDay && r.day <= toDay);
97
+ const total = emptyBucket();
98
+ const main = emptyBucket();
99
+ const compact = emptyBucket();
100
+ const dayMap = new Map();
101
+ const wsMap = new Map();
102
+ const modelMap = new Map();
103
+ const daySessions = new Map();
104
+ const groupSessions = (map, key) => {
105
+ let row = map.get(key);
106
+ if (!row) {
107
+ row = { key, ...emptyBucket(), sessions: 0 };
108
+ map.set(key, row);
109
+ }
110
+ return row;
111
+ };
112
+ const sessions = new Set();
113
+ for (const r of inWindow) {
114
+ addInto(total, r);
115
+ addInto(r.phase === 'compact' ? compact : main, r);
116
+ let dayRow = dayMap.get(r.day);
117
+ if (!dayRow) {
118
+ dayRow = { day: r.day, ...emptyBucket(), sessions: 0 };
119
+ dayMap.set(r.day, dayRow);
120
+ daySessions.set(r.day, new Set());
121
+ }
122
+ addInto(dayRow, r);
123
+ const wsRow = groupSessions(wsMap, r.workspace || '(unknown)');
124
+ addInto(wsRow, r);
125
+ const modelRow = groupSessions(modelMap, r.model || '(unknown)');
126
+ addInto(modelRow, r);
127
+ if (r.sessionId) {
128
+ sessions.add(`${r.workspace}::${r.sessionId}`);
129
+ daySessions.get(r.day)?.add(r.sessionId);
130
+ }
131
+ }
132
+ // distinct session 计数(按工作区/模型)
133
+ const wsSessionSets = new Map();
134
+ const modelSessionSets = new Map();
135
+ for (const r of inWindow) {
136
+ if (!r.sessionId)
137
+ continue;
138
+ if (!wsSessionSets.has(r.workspace || '(unknown)'))
139
+ wsSessionSets.set(r.workspace || '(unknown)', new Set());
140
+ wsSessionSets.get(r.workspace || '(unknown)').add(r.sessionId);
141
+ if (!modelSessionSets.has(r.model || '(unknown)'))
142
+ modelSessionSets.set(r.model || '(unknown)', new Set());
143
+ modelSessionSets.get(r.model || '(unknown)').add(r.sessionId);
144
+ }
145
+ for (const row of wsMap.values())
146
+ row.sessions = wsSessionSets.get(row.key)?.size ?? 0;
147
+ for (const row of modelMap.values())
148
+ row.sessions = modelSessionSets.get(row.key)?.size ?? 0;
149
+ for (const row of dayMap.values())
150
+ row.sessions = daySessions.get(row.day)?.size ?? 0;
151
+ // 补齐窗口内零用量日(从 fromDay 逐天 +1,本地日期)
152
+ const byDay = [];
153
+ const cursor = new Date(`${fromDay}T00:00:00`);
154
+ for (let i = 0; i < Math.max(1, days); i++) {
155
+ const key = localDay(cursor);
156
+ byDay.push(dayMap.get(key) ?? { day: key, ...emptyBucket(), sessions: 0 });
157
+ cursor.setDate(cursor.getDate() + 1);
158
+ }
159
+ const byTotal = (a, b) => b.input + b.output - (a.input + a.output);
160
+ return {
161
+ fromDay,
162
+ toDay,
163
+ days: byDay.length,
164
+ total,
165
+ byDay,
166
+ byWorkspace: [...wsMap.values()].sort(byTotal),
167
+ byModel: [...modelMap.values()].sort(byTotal),
168
+ main,
169
+ compact,
170
+ sessionCount: sessions.size,
171
+ workspaceCount: wsMap.size,
172
+ };
173
+ }
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { AsyncLocalStorage } from 'node:async_hooks';
3
- import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
3
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
4
4
  import { gzipSync } from 'node:zlib';
5
5
  import path from 'node:path';
6
6
  import { MAX_TRACE_BYTES, MAX_TRACE_ROTATIONS, MAX_COMPACTED_ARCHIVE_BYTES } from '../tools/constants.js';
@@ -521,6 +521,87 @@ export class SessionStore {
521
521
  return null;
522
522
  }
523
523
  }
524
+ /**
525
+ * 分叉会话:把 `<sessionsRoot>/<sourceId>/` **整个目录**复制成一个新 id 会话
526
+ * (session.json/notes.md/snapshots.json/compacted/trace/usage 全带),
527
+ * 然后把副本里对旧会话的引用重写到新 id。原会话目录与当前 currentSessionId
528
+ * 均不动——fork 只在磁盘上产出一个独立副本,切不切过去由调用方决定。
529
+ *
530
+ * @returns 新会话 id;源会话目录不存在(如仅在归档 gz 中)时返回 null。
531
+ */
532
+ forkSession(sourceId) {
533
+ const srcDir = path.join(this.sessionsRoot, sourceId);
534
+ if (!existsSync(srcDir) || !statSync(srcDir).isDirectory())
535
+ return null;
536
+ const newId = createTimestampId();
537
+ const dstDir = path.join(this.sessionsRoot, newId);
538
+ // 时间前缀碰撞概率忽略不计,撞了直接报错也不覆盖任何东西。
539
+ if (existsSync(dstDir))
540
+ throw new Error(`Fork target session already exists: ${newId}`);
541
+ // filter 在 cp 过程中对每个条目回调:跳过 tmp(原子写残留)。整个目录递归复制。
542
+ cpSync(srcDir, dstDir, {
543
+ recursive: true,
544
+ errorOnExist: true,
545
+ force: false,
546
+ filter: (p) => !p.endsWith('.tmp'),
547
+ });
548
+ try {
549
+ this.rewriteForkedReferences(dstDir, sourceId, newId);
550
+ }
551
+ catch (error) {
552
+ // 不留下半成品会话目录(引用没改干净的副本比没有更危险)。
553
+ rmSync(dstDir, { recursive: true, force: true });
554
+ throw error;
555
+ }
556
+ return newId;
557
+ }
558
+ /**
559
+ * 重写分叉副本里的会话 id 引用:
560
+ * - 历史指针(.mocode/sessions/<old>/...)按路径前缀精确替换,避免裸 id 误匹配;
561
+ * - 跳过 .gz 二进制轮转;
562
+ * - session.json 单独结构化处理:id/createdAt 改成新会话,history 内指针同样替换。
563
+ */
564
+ rewriteForkedReferences(dir, oldId, newId) {
565
+ const oldPrefix = `.mocode/sessions/${oldId}/`;
566
+ const newPrefix = `.mocode/sessions/${newId}/`;
567
+ const rewriteFile = (file) => {
568
+ if (file.endsWith('.gz'))
569
+ return;
570
+ const original = readFileSync(file, 'utf8');
571
+ const updated = original.split(oldPrefix).join(newPrefix);
572
+ if (updated !== original)
573
+ writeFileSync(file, updated, 'utf8');
574
+ };
575
+ for (const entry of this.walkDirFiles(dir)) {
576
+ if (entry.endsWith('session.json'))
577
+ continue; // 下面结构化处理
578
+ rewriteFile(entry);
579
+ }
580
+ // session.json:id/createdAt 是新会话身份;history 里的 compacted/result blob
581
+ // 指针按同样的前缀替换。
582
+ const sessionJsonPath = path.join(dir, 'session.json');
583
+ if (existsSync(sessionJsonPath)) {
584
+ const rec = JSON.parse(readFileSync(sessionJsonPath, 'utf8'));
585
+ rec.id = newId;
586
+ rec.createdAt = idToIso(newId);
587
+ if (Array.isArray(rec.history)) {
588
+ rec.history = JSON.parse(JSON.stringify(rec.history).split(oldPrefix).join(newPrefix));
589
+ }
590
+ writeFileSync(sessionJsonPath, JSON.stringify(rec), 'utf8');
591
+ }
592
+ }
593
+ /** 递归列出目录下全部文件(绝对路径)。 */
594
+ *walkDirFiles(dir) {
595
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
596
+ const full = path.join(dir, entry.name);
597
+ if (entry.isDirectory()) {
598
+ yield* this.walkDirFiles(full);
599
+ }
600
+ else if (entry.isFile()) {
601
+ yield full;
602
+ }
603
+ }
604
+ }
524
605
  list(limit) {
525
606
  const root = this.sessionsRoot;
526
607
  if (!existsSync(root))
@@ -1,4 +1,4 @@
1
- import { addTriple, graphStats, neighborsOf, pathBetween } from '../../memory/graph.js';
1
+ import { addTriple, graphStats, neighborsOf, parseAsOf, pathBetween } from '../../memory/graph.js';
2
2
  import { formatRecallStats } from '../../memory/recall-stats.js';
3
3
  // ---------- memory_graph ----------
4
4
  // 知识图谱维护工具:邻居遍历(1-3 跳,可 relation 过滤)、两点最短路径、手工加三元组、看图统计。
@@ -33,6 +33,10 @@ export const memoryGraphTool = {
33
33
  },
34
34
  query: { type: 'string', description: 'neighbors: entity name or id; path: start entity' },
35
35
  depth: { type: 'integer', description: 'neighbors: hops, 1-3, default 1' },
36
+ asOf: {
37
+ type: 'string',
38
+ description: 'neighbors/path: answer "what did I believe at THAT moment" instead of now. ISO timestamp or YYYY-MM-DD (local midnight). Edges are time-sliced by validAt/invalidAt: an edge counts iff validAt <= asOf < invalidAt. Use it when the current answer contradicts an older decision and you need to know which belief was held then. Omit for the current view.',
39
+ },
36
40
  src: { type: 'string', description: 'add: source entity name' },
37
41
  relation: {
38
42
  type: 'string',
@@ -81,14 +85,20 @@ export const memoryGraphTool = {
81
85
  return '错误:neighbors 需要 query(实体名或 id)。';
82
86
  const depth = typeof args.depth === 'number' ? args.depth : 1;
83
87
  const rel = typeof args.relation === 'string' ? args.relation.trim() : '';
84
- const r = neighborsOf(query, depth, rel || undefined);
88
+ const asOf = parseAsOf(args.asOf);
89
+ if (!asOf.ok)
90
+ return `错误:${asOf.reason}`;
91
+ const r = neighborsOf(query, depth, rel || undefined, asOf.ms);
85
92
  if (!r.center)
86
93
  return `(图中没有实体 "${query}")`;
87
94
  const relNote = rel ? `,仅 ${rel} 边` : '';
95
+ const atNote = asOf.ms != null ? `,asOf ${new Date(asOf.ms).toISOString()}` : '';
88
96
  const lines = [
89
97
  `## ${r.center.name} (${r.center.id})${r.center.summary ? ` — ${r.center.summary}` : ''}`,
90
98
  r.entities.length > 0 ? `\n## 邻居实体\n${fmtEntities(r.entities)}` : '',
91
- `\n## 边(${r.edges.length}${relNote}${r.truncated ? ',已截断' : ''})\n${fmtEdges(r.edges)}`,
99
+ `\n## 边(${r.edges.length}${relNote}${atNote}${r.truncated ? ',已截断' : ''})\n${fmtEdges(r.edges)}`,
100
+ // 「那一刻没有边」与「实体不存在」是两种完全不同的答案,不说清楚会被误读成后者。
101
+ asOf.ms != null && r.edges.length === 0 ? '\n(该时刻没有成立的边——实体在,但那时还没有这条关系)' : '',
92
102
  ].filter(Boolean);
93
103
  return lines.join('\n');
94
104
  }
@@ -97,12 +107,16 @@ export const memoryGraphTool = {
97
107
  const to = String(args.dst ?? '').trim();
98
108
  if (!from || !to)
99
109
  return '错误:path 需要 query(起点实体)和 dst(终点实体)。';
100
- const r = pathBetween(from, to);
110
+ const asOf = parseAsOf(args.asOf);
111
+ if (!asOf.ok)
112
+ return `错误:${asOf.reason}`;
113
+ const r = pathBetween(from, to, asOf.ms);
114
+ const scope = asOf.ms != null ? `该时刻(${new Date(asOf.ms).toISOString()})` : '现在';
101
115
  if (!r)
102
- return `(无 active 路径:${from} ⇸ ${to},或端点实体不存在)`;
116
+ return `(无 ${scope} 成立的路径:${from} ⇸ ${to},或端点实体不存在)`;
103
117
  const chain = r.path.map((e) => e.name).join(' → ');
104
118
  const lines = [
105
- `## ${r.from.name} ⇢ ${r.to.name}(${r.edges.length} 跳)`,
119
+ `## ${r.from.name} ⇢ ${r.to.name}(${r.edges.length} 跳${asOf.ms != null ? `,asOf ${new Date(asOf.ms).toISOString()}` : ''})`,
106
120
  `路径:${chain}`,
107
121
  `\n## 边\n${fmtEdges(r.edges)}`,
108
122
  ];
@@ -29,7 +29,9 @@ export const memoryListTool = {
29
29
  return '(无记忆条目)';
30
30
  const lines = items.map((i) => {
31
31
  const gap = !i.hasTrigger && wantsTrigger(i.type) ? ' [NO-TRIGGER]' : '';
32
- return `- ${i.id}: ${i.name} — ${i.summary} (${i.type}, ${i.status})${gap}`;
32
+ // R16.1:来源不可信的条目在这里也要露出来,否则一眼扫列表看不出哪条是"从网页上抄的"。
33
+ const origin = i.origin === 'tool_output' ? ' [UNVERIFIED-ORIGIN]' : '';
34
+ return `- ${i.id}: ${i.name} — ${i.summary} (${i.type}, ${i.status})${gap}${origin}`;
33
35
  });
34
36
  const gaps = items.filter((i) => !i.hasTrigger && wantsTrigger(i.type)).length;
35
37
  if (gaps > 0) {
@@ -1,6 +1,8 @@
1
1
  import { saveEntry, memoryWriteBlockedMessage } from '../../memory/store.js';
2
2
  import { addTriple } from '../../memory/graph.js';
3
3
  import { buildAnchors } from '../../memory/anchor.js';
4
+ import { detectHijack } from '../../memory/guard.js';
5
+ import { appendAudit } from '../../memory/audit.js';
4
6
  /**
5
7
  * 把工具参数里的 anchors 归一成 AnchorInput[]。
6
8
  *
@@ -18,8 +20,11 @@ function parseAnchorInputs(raw) {
18
20
  const p = typeof a.path === 'string' ? a.path.trim() : '';
19
21
  if (!p)
20
22
  continue;
23
+ // R7.1:非法 kind 一律按 file 处理。静默纠正比报错好——报错会让模型整条记忆都放弃写,
24
+ // 而它本来只是想锚一个文件,顺带把 kind 拼错了。
25
+ const k = a.kind === 'dir' || a.kind === 'url' ? a.kind : undefined;
21
26
  const s = typeof a.symbol === 'string' ? a.symbol.trim() : '';
22
- out.push({ path: p, ...(s ? { symbol: s } : {}) });
27
+ out.push({ ...(k ? { kind: k } : {}), path: p, ...(s ? { symbol: s } : {}) });
23
28
  }
24
29
  return out;
25
30
  }
@@ -97,13 +102,18 @@ export const memorySaveTool = {
97
102
  },
98
103
  anchors: {
99
104
  type: 'array',
100
- description: 'R2 code anchors: the code this memory talks about. Record them when the memory describes how a specific file/function works, so a later change to that code can mark the memory stale instead of silently serving an outdated fact. Pass paths/symbols only — the content hash is computed for you at write time. Anchors that cannot be resolved (file or symbol not found) are dropped.',
105
+ description: 'Anchors: the thing this memory talks about, so a later change marks the memory stale instead of silently serving an outdated fact. kind=file (default) for a file or one of its symbols; kind=dir for a directory (detects added/removed/renamed entries, not edits inside files); kind=url for a web page (recorded as provenance only — it is never fetched, so it can never be verified). Pass paths/symbols only — hashes are computed for you at write time. Anchors that cannot be resolved are dropped.',
101
106
  items: {
102
107
  type: 'object',
103
108
  properties: {
109
+ kind: {
110
+ type: 'string',
111
+ enum: ['file', 'dir', 'url'],
112
+ description: 'Default "file". Use "dir" for a directory, "url" for a web page.',
113
+ },
104
114
  path: {
105
115
  type: 'string',
106
- description: 'Workspace-relative file path, e.g. "src/memory/store.ts" (forward slashes)',
116
+ description: 'Workspace-relative file/directory path (forward slashes), e.g. "src/memory/store.ts" — or an http(s) URL when kind=url',
107
117
  },
108
118
  symbol: {
109
119
  type: 'string',
@@ -131,6 +141,23 @@ export const memorySaveTool = {
131
141
  const trigger = typeof args.trigger === 'string' ? args.trigger.trim() : '';
132
142
  const action = typeof args.action === 'string' ? args.action.trim() : '';
133
143
  const anchors = parseAnchorInputs(args.anchors);
144
+ // R16.2:指令性内容拒写。模型可能刚读完一个网页,把里面的"忽略之前的指令"当成
145
+ // 一条"要记住的约定"存进来——那样它此后每次启动都会进 system prompt。
146
+ // 确定性规则,**不靠模型自省**:模型正是被攻击对象,让它判断"这算不算注入"不可靠。
147
+ // 拒绝必须说清原因并留证,否则模型会换个 name 反复重试。
148
+ const hijack = detectHijack(`${name} ${summary} ${body}`);
149
+ if (hijack) {
150
+ appendAudit({
151
+ at: new Date().toISOString(),
152
+ action: 'refuse',
153
+ detail: `拒绝写入记忆「${name.slice(0, 60)}」:命中投毒规则 ${hijack.rule}`,
154
+ reason: `hijack:${hijack.rule}`,
155
+ snippet: hijack.sample,
156
+ });
157
+ return (`拒绝写入:内容命中投毒/注入规则 ${hijack.rule}(「${hijack.sample}」)。\n` +
158
+ `记忆会在**每次启动**时注入系统提示,所以这类"改写 agent 指令/身份/报告义务"的文本一律不落库。\n` +
159
+ `如果这是需要记住的知识(例如"看到这类网页要当心"),请改成**描述性结论**并避免逐字照抄原文。`);
160
+ }
134
161
  const r = saveEntry({
135
162
  name,
136
163
  summary,
@@ -36,6 +36,11 @@ function statusMark(e, st, anchor) {
36
36
  const why = describeAnchorState(anchor);
37
37
  parts.push(`STALE-CODE${why ? ` (${why})` : ''}`);
38
38
  }
39
+ // R16.1:来源标记。只在**二手转述**时出现——内容逐字来自工具输出(网页/文件/命令),
40
+ // 模型没经用户确认就记了下来。给的是"引用前先核实"的提示,不是"这条是假的"。
41
+ // 默认路径(模型自己总结的事实)不加标记,保持零噪音。
42
+ if (e.origin === 'tool_output')
43
+ parts.push('UNVERIFIED-ORIGIN');
39
44
  return parts.length > 0 ? ` [${parts.join(' | ')}]` : '';
40
45
  }
41
46
  export const memorySearchTool = {
@@ -14,8 +14,10 @@ function parseAnchorInputs(raw) {
14
14
  const p = typeof a.path === 'string' ? a.path.trim() : '';
15
15
  if (!p)
16
16
  continue;
17
+ // R7.1:非法 kind 按 file 处理(与 memory_save 同口径),不因此丢整条锚点。
18
+ const k = a.kind === 'dir' || a.kind === 'url' ? a.kind : undefined;
17
19
  const s = typeof a.symbol === 'string' ? a.symbol.trim() : '';
18
- out.push({ path: p, ...(s ? { symbol: s } : {}) });
20
+ out.push({ ...(k ? { kind: k } : {}), path: p, ...(s ? { symbol: s } : {}) });
19
21
  }
20
22
  return out;
21
23
  }
@@ -44,11 +46,19 @@ export const memoryUpdateTool = {
44
46
  },
45
47
  anchors: {
46
48
  type: 'array',
47
- description: 'R2 code anchors — REPLACES the whole set (pass [] to clear). Only paths/symbols; the content hash is recomputed at write time. Use this when the memory is about a specific file/function and you want a later edit to surface it as stale instead of silently serving an outdated fact.',
49
+ description: 'Anchors — REPLACES the whole set (pass [] to clear). kind=file (default) for a file or symbol; dir for a directory (detects added/removed/renamed entries, not edits inside files); url for a web page (provenance only, never fetched so never verified). Pass paths/symbols only; hashes are recomputed at write time. Use this so a later change surfaces the memory as stale instead of silently serving an outdated fact.',
48
50
  items: {
49
51
  type: 'object',
50
52
  properties: {
51
- path: { type: 'string', description: 'Workspace-relative file path, e.g. "src/memory/store.ts"' },
53
+ kind: {
54
+ type: 'string',
55
+ enum: ['file', 'dir', 'url'],
56
+ description: 'Default "file". Use "dir" for a directory, "url" for a web page.',
57
+ },
58
+ path: {
59
+ type: 'string',
60
+ description: 'Workspace-relative file/directory path, or an http(s) URL when kind=url',
61
+ },
52
62
  symbol: {
53
63
  type: 'string',
54
64
  description: 'Optional function/class/const name; prefers a fragment over the whole file',
@@ -529,7 +529,12 @@ export async function promptWithSlashMenu(opts) {
529
529
  computeFiltered();
530
530
  redraw();
531
531
  }
532
- /** Ctrl+C:有内容(已打字 / 多行 / 粘贴块 / 菜单草稿 / 粘贴缓冲 / 粘贴中)则清空,再按一次(空)才退出(仿 fish)。 */
532
+ /**
533
+ * Ctrl+C 分级清空(仿 fish,逐级放弃当前输入,最后一级才退出):
534
+ * 1. 有文本/菜单/粘贴缓冲 → 只清文本(留快照供 Ctrl+Z 还原);
535
+ * 2. 文本已空但有待发图片 → 清附件(Ctrl+Y 刚截的图,避免误清故单独一级);
536
+ * 3. 都空 → 退出(SIGINT)。
537
+ */
533
538
  function onCtrlC() {
534
539
  const flat = segs.map((s) => s.text).join('');
535
540
  const hasContent = flat.length > 0 || menuOpen || pasteState.pasteParts.length > 0 || pasteState.pasting;
@@ -537,6 +542,11 @@ export async function promptWithSlashMenu(opts) {
537
542
  clearInput();
538
543
  return;
539
544
  }
545
+ if (opts.hasPendingAttachments?.()) {
546
+ opts.clearPendingAttachments?.();
547
+ redraw(); // 脚栏 chip 擦除(sync 已更新 layout state,这里触发重画)
548
+ return;
549
+ }
540
550
  cleanup();
541
551
  reject(new Error('SIGINT'));
542
552
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mocode-ai",
3
- "version": "1.9.0",
3
+ "version": "1.9.2",
4
4
  "description": "终端编码 agent:LLM + tool-call 循环 + 流式输出(含思考)+ 27 个工具,接任意 OpenAI 兼容后端。",
5
5
  "type": "module",
6
6
  "bin": {