mocode-ai 1.8.9 → 1.9.0

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.
Files changed (65) hide show
  1. package/dist/agent/index.js +17 -17
  2. package/dist/agent/model-turn.js +8 -4
  3. package/dist/agent/run-coordinator.js +6 -0
  4. package/dist/agent/spawn.js +8 -4
  5. package/dist/agent/stages/tool-dispatcher.js +31 -11
  6. package/dist/attachments/clipboard.js +22 -0
  7. package/dist/attachments/image.js +63 -0
  8. package/dist/changeset/hash.js +17 -0
  9. package/dist/changeset/index.js +6 -10
  10. package/dist/context/text-search.js +28 -10
  11. package/dist/flows/cli.js +1 -1
  12. package/dist/flows/flow.js +1 -1
  13. package/dist/flows/trace.js +1 -1
  14. package/dist/headless.js +23 -0
  15. package/dist/i18n/index.js +16 -2
  16. package/dist/index.js +1 -1
  17. package/dist/memory/anchor.js +319 -0
  18. package/dist/memory/audit.js +65 -0
  19. package/dist/memory/episodic.js +546 -0
  20. package/dist/memory/graph.js +233 -9
  21. package/dist/memory/health.js +208 -0
  22. package/dist/memory/index.js +12 -3
  23. package/dist/memory/pending.js +269 -0
  24. package/dist/memory/portable.js +150 -0
  25. package/dist/memory/proactive.js +588 -0
  26. package/dist/memory/recall-stats.js +1 -1
  27. package/dist/memory/reflect.js +260 -6
  28. package/dist/memory/relation-vocab.js +26 -4
  29. package/dist/memory/store.js +587 -41
  30. package/dist/memory/tail.js +88 -0
  31. package/dist/memory/write-gate.js +44 -0
  32. package/dist/permissions/computer-review.js +1 -1
  33. package/dist/permissions/flow-review.js +1 -1
  34. package/dist/repl/commands/flow.js +1 -1
  35. package/dist/repl/commands/image.js +30 -17
  36. package/dist/repl/commands/memory.js +257 -6
  37. package/dist/repl/commands/session.js +13 -0
  38. package/dist/repl/commands/tool-group.js +6 -0
  39. package/dist/repl/commands.js +1 -0
  40. package/dist/repl/episode-finalize.js +55 -0
  41. package/dist/repl/message-format.js +18 -0
  42. package/dist/repl/runtime.js +110 -5
  43. package/dist/runtime/uia-selector.js +1 -1
  44. package/dist/runtime/uia-service.js +3 -3
  45. package/dist/runtime/wait-until.js +1 -1
  46. package/dist/runtime/window-list.js +1 -1
  47. package/dist/sandbox/policy.js +49 -0
  48. package/dist/session/compact.js +47 -12
  49. package/dist/session/gui-actions.js +1 -1
  50. package/dist/tools/builtins/computer.js +5 -5
  51. package/dist/tools/builtins/memory-graph.js +12 -1
  52. package/dist/tools/builtins/memory-list.js +13 -3
  53. package/dist/tools/builtins/memory-save.js +82 -2
  54. package/dist/tools/builtins/memory-search.js +57 -2
  55. package/dist/tools/builtins/memory-update.js +52 -1
  56. package/dist/tools/builtins/read-file.js +51 -2
  57. package/dist/tools/builtins/run-flow.js +1 -1
  58. package/dist/tools/constants.js +60 -0
  59. package/dist/ui/clipboard.js +97 -0
  60. package/dist/ui/layout-internal/core.js +1 -1
  61. package/dist/ui/layout-internal/input-paint.js +7 -5
  62. package/dist/ui/layout-internal/state.js +8 -0
  63. package/dist/ui/layout-internal/statusbar.js +22 -1
  64. package/dist/ui/prompt-internal/editor.js +39 -0
  65. package/package.json +6 -1
@@ -0,0 +1,269 @@
1
+ /**
2
+ * R13 压缩 → 记忆交接:压缩候选的暂存区。
3
+ *
4
+ * 为什么需要这一层(而不是压缩时直接写记忆库):
5
+ * 压缩是**高频路径**——一轮里可能压好几次,每次都由一次摘要 LLM 调用顺带产出候选。
6
+ * 这些候选**未经任何闸门**:模型在压上下文时顺手写的一句话,可能只是"当前这个 bug 还没修好"
7
+ * 这类一次性状态。直接进正式库等于绕过了反思的全部规则(①只收跨会话有用的、②宁少勿多、
8
+ * ⑤先改旧的别新建重复)。所以候选先落这里,等下一次反思按既有六桶规则裁决。
9
+ *
10
+ * 为什么落在 `<cwd>/.mocode/` 而不是 session 目录:
11
+ * 候选是**项目级**的(压缩掉的是本项目的会话),且反思进程与 REPL 是同一个;放 session 目录
12
+ * 会让跨会话的候选随会话 id 散成一堆,反思还得去猜读哪个。
13
+ *
14
+ * 叶子依赖约定:本模块只依赖 node 内置。不能 import config(= 有环)或 agent/llm/tools,
15
+ * 开关由调用方算好布尔值传进来(与 store.ts 的 memory 开关同一套约定)。
16
+ */
17
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
18
+ import path from 'node:path';
19
+ // R8.3/R8.5:暂停或关闭时这条交接通道也要闭嘴——否则用户在 /memory pause 之后
20
+ // 仍然会在 .mocode/ 里看到新文件被建出来,那正是「暂停」最不该有的行为。
21
+ import { memoryWriteBlockReason } from './write-gate.js';
22
+ /**
23
+ * 队列上限。压缩是高频路径,无上限会让文件无限增长,也让反思 prompt 被候选挤爆。
24
+ * 40 条约等于十几次压缩的量;超过就丢最旧的——最近压掉的推理链才是还有救的。
25
+ */
26
+ const MAX_PENDING = 40;
27
+ /** 单条候选正文上限(字符)。候选是"一句话提示",不是正文;长了说明模型在抄摘要。 */
28
+ const MAX_TEXT_CHARS = 300;
29
+ /**
30
+ * R13 交接开关。默认开启,`MOCODE_MEMORY_COMPACT_HANDOFF=0/false/off/no` 关闭。
31
+ * 与 R3 的 `MOCODE_MEMORY_PROACTIVE` 同一套写法:env-only,不新增 config 字段。
32
+ * **不代替** memory 总开关——调用方仍需先判 `isMemoryEnabled()`,两者是与关系。
33
+ */
34
+ export function isCompactHandoffEnabled() {
35
+ const raw = process.env.MOCODE_MEMORY_COMPACT_HANDOFF;
36
+ if (raw === undefined)
37
+ return true;
38
+ return !['0', 'false', 'off', 'no'].includes(raw.trim().toLowerCase());
39
+ }
40
+ function pendingPath() {
41
+ return path.join(process.cwd(), '.mocode', 'memory-pending.jsonl');
42
+ }
43
+ function ensureParent(p) {
44
+ const dir = path.dirname(p);
45
+ if (!existsSync(dir))
46
+ mkdirSync(dir, { recursive: true });
47
+ }
48
+ /** 读队列(静默容错:不存在 / 读失败 / 坏行 → 跳过,永不抛)。 */
49
+ export function loadPendingCandidates() {
50
+ const p = pendingPath();
51
+ if (!existsSync(p))
52
+ return [];
53
+ let content;
54
+ try {
55
+ content = readFileSync(p, 'utf8');
56
+ }
57
+ catch {
58
+ return [];
59
+ }
60
+ if (!content.trim())
61
+ return [];
62
+ const out = [];
63
+ for (const line of content.split('\n')) {
64
+ if (!line.trim())
65
+ continue;
66
+ try {
67
+ const c = JSON.parse(line);
68
+ if (c && typeof c.text === 'string' && c.text.trim())
69
+ out.push(c);
70
+ }
71
+ catch {
72
+ /* 坏行跳过:队列是 best-effort 通道,不值得为一行坏数据中断 */
73
+ }
74
+ }
75
+ return out;
76
+ }
77
+ function writeAll(items) {
78
+ const p = pendingPath();
79
+ ensureParent(p);
80
+ const body = items.map((c) => JSON.stringify(c)).join('\n');
81
+ const tmp = `${p}.tmp`;
82
+ writeFileSync(tmp, body, 'utf8');
83
+ renameSync(tmp, p);
84
+ }
85
+ /** 归一一行文本用于去重:去标点/空白差异后小写,避免同一条被反复压进队列。 */
86
+ function textKey(s) {
87
+ return s
88
+ .toLowerCase()
89
+ .replace(/\s+/g, ' ')
90
+ .replace(/[。.,;;::!!??]+$/g, '')
91
+ .trim();
92
+ }
93
+ /**
94
+ * 追加候选。返回**实际新增**的条数(已存在的、空的、超长的被滤掉)。
95
+ *
96
+ * 幂等性:同一句话只会进队一次。压缩可能对同一段旧区压两次(先失败后成功、
97
+ * 或手动 /compact 重跑),没有这层去重队列会被同一批候选灌满。
98
+ */
99
+ export function appendPendingCandidates(items) {
100
+ if (items.length === 0)
101
+ return 0;
102
+ // R8.3/R8.5:暂停写入时连队列都不该涨。这里返回 0 而不是抛错——压缩是后台路径,
103
+ // 它的调用方只关心「进了几条」。
104
+ if (memoryWriteBlockReason())
105
+ return 0;
106
+ const existing = loadPendingCandidates();
107
+ const seen = new Set(existing.map((c) => textKey(c.text)));
108
+ const now = new Date().toISOString();
109
+ const fresh = [];
110
+ for (const raw of items) {
111
+ const text = String(raw.text ?? '')
112
+ .replace(/\s+/g, ' ')
113
+ .trim();
114
+ if (!text)
115
+ continue;
116
+ const key = textKey(text);
117
+ if (!key || seen.has(key))
118
+ continue;
119
+ seen.add(key);
120
+ fresh.push({
121
+ kind: String(raw.kind ?? '')
122
+ .trim()
123
+ .toLowerCase() || 'unknown',
124
+ text: text.length > MAX_TEXT_CHARS ? text.slice(0, MAX_TEXT_CHARS) + '…' : text,
125
+ at: now,
126
+ source: 'compact',
127
+ });
128
+ }
129
+ if (fresh.length === 0)
130
+ return 0;
131
+ // 超上限丢最旧的:队列按时间追加,slice(-MAX_PENDING) 即保最新。
132
+ const merged = [...existing, ...fresh].slice(-MAX_PENDING);
133
+ writeAll(merged);
134
+ return fresh.length;
135
+ }
136
+ /**
137
+ * 丢弃**反思已裁决过的那批候选**,保留其余。
138
+ *
139
+ * 为什么不是"清空":反思是几十秒的后台请求,期间主 agent 完全可能又压了一次上下文、
140
+ * 又追加了候选。无脑清空会把**这一轮根本没被看过**的新候选一起删掉。
141
+ *
142
+ * 为什么按**身份**而不是"前 N 条":队列有 40 条上限,满队时新增候选会把最旧的挤出去,
143
+ * 队列长度仍是 40。此时"切掉前 40 条"= 整队清空,反思期间刚追加的候选一条不剩——
144
+ * 正是上面那句论证要防的事,却因为 cap 让「长度不变」而绕过。改为传入已裁决的那批
145
+ * 候选本身,按 `textKey` 身份删除:被 cap 挤掉的条目删不到(已不在队列里,无害),
146
+ * 期间新增的条目身份不匹配,必然保留。
147
+ *
148
+ * **只在反思成功裁决后调用**——反思失败(超时/解析失败)时一条都不能丢,
149
+ * 否则一次网络抖动就把压缩捞出来的推理链永久扔掉,而那正是这条通道唯一的价值。
150
+ */
151
+ export function trimPendingCandidates(consumed) {
152
+ if (consumed.length === 0)
153
+ return;
154
+ const p = pendingPath();
155
+ if (!existsSync(p))
156
+ return;
157
+ try {
158
+ const drop = new Set(consumed.map((c) => textKey(String(c?.text ?? ''))).filter(Boolean));
159
+ if (drop.size === 0)
160
+ return;
161
+ const all = loadPendingCandidates();
162
+ const kept = all.filter((c) => !drop.has(textKey(c.text)));
163
+ if (kept.length !== all.length)
164
+ writeAll(kept);
165
+ }
166
+ catch {
167
+ /* best-effort:清不掉只会让下一轮多看到几条已裁决的候选,不致命 */
168
+ }
169
+ }
170
+ /** 待裁决条数(观测/测试用)。 */
171
+ export function pendingCandidateCount() {
172
+ return loadPendingCandidates().length;
173
+ } // ── 与压缩摘要器共享的协议 ──────────────────────────────────────────────────
174
+ //
175
+ // 摘要器是压缩路径上**已有**的那次 LLM 调用,不能再加一次(R13.1 的硬约束)。
176
+ // 所以候选只能作为「摘要正文之后的附加段」被顺带产出,再由确定性代码切走。
177
+ // 三条硬要求:
178
+ // 1. 候选段必须在存进 history 之前被剥掉——否则摘要里会混进一段"给反思看的草稿",
179
+ // 白白占上下文,还会被下一代摘要当成叙述再压一遍。
180
+ // 2. 段标题必须与 `## Key Facts` 同级且唯一,否则 splitSummaryText 的分段会错位。
181
+ // 3. 措辞由本模块统一产出:legacy 与 fork 两条路径若各写一份,迟早漂移成两种格式,
182
+ // 而解析端只有一套。
183
+ /** 候选段标题。解析端与提示词端共用;改动即破坏跨版本兼容(旧摘要里可能还有旧标题)。 */
184
+ export const MEMORY_CANDIDATES_HEADING = '## Memory Candidates';
185
+ /** 单次压缩最多收几条。压上下文时模型的注意力在"总结"上,多要只会换来凑数。 */
186
+ const MAX_CANDIDATES_PER_COMPACTION = 3;
187
+ /**
188
+ * 追加到摘要提示词末尾的要求。
189
+ *
190
+ * 为什么强调「空白是正常结果」:不写这句,模型会为了填满字段而编出"改代码时要小心"
191
+ * 这类零信息量的候选,把队列挤满,再让反思白读一遍——这比没有候选更糟。
192
+ */
193
+ export function memoryCandidatesInstruction() {
194
+ return (`\nAFTER the summary, if and only if the transcript above contains something a FUTURE session would need ` +
195
+ `and that is about to be lost with this context, append this section (it is NOT part of the 400-word limit):\n` +
196
+ `${MEMORY_CANDIDATES_HEADING}\n` +
197
+ `- [pitfall|decision|feedback|fact|reference] <one line: the situation it applies to + what to remember, ≤120 chars>\n` +
198
+ `At most ${MAX_CANDIDATES_PER_COMPACTION} items. Report ONLY things that compaction is about to destroy: ` +
199
+ `a dead end that cost real time and must not be retried, a constraint the user stated once and will not repeat, ` +
200
+ `a non-obvious cause discovered by experiment, a decision with its reason. ` +
201
+ `Do NOT report task progress, files changed, next steps (the summary already carries those), ` +
202
+ `anything re-derivable by re-reading the repo, or generic advice. ` +
203
+ `An EMPTY section is the normal and expected outcome — omit the heading entirely when nothing qualifies.`);
204
+ }
205
+ /**
206
+ * 从摘要正文里切走候选段。返回「干净的摘要」+「候选列表」。
207
+ *
208
+ * 容错优先:模型可能写成 `## memory candidates`、可能在段内用 `*` 而非 `-`、
209
+ * 也可能压根不输出这一段(常态)。任何一种都不能让压缩本身失败——所以这里
210
+ * 全程不抛,认不出就原样返回。
211
+ */
212
+ export function extractMemoryCandidates(raw) {
213
+ const text = String(raw ?? '');
214
+ const lines = text.split('\n');
215
+ const headRe = /^ {0,3}##\s+memory\s+candidates\b/i;
216
+ const start = lines.findIndex((l) => headRe.test(l));
217
+ if (start < 0)
218
+ return { summary: text, candidates: [] };
219
+ // 段尾 = 下一个 `## ` 级标题(若模型把候选段放在中间),否则到文末。
220
+ const anyHeading = /^ {0,3}##\s+\S/;
221
+ let end = lines.length;
222
+ for (let i = start + 1; i < lines.length; i++) {
223
+ if (anyHeading.test(lines[i])) {
224
+ end = i;
225
+ break;
226
+ }
227
+ }
228
+ const candidates = [];
229
+ for (const line of lines.slice(start + 1, end)) {
230
+ const m = /^\s*[-*•]\s*(?:\[([^\]]*)\]\s*)?(.+?)\s*$/.exec(line);
231
+ if (!m)
232
+ continue;
233
+ const body = m[2].trim();
234
+ if (!body)
235
+ continue;
236
+ // 占位符式回答("无"/"none")不该变成候选。
237
+ if (/^(无|没有|none|n\/a|-)$/i.test(body))
238
+ continue;
239
+ candidates.push({
240
+ kind: (m[1] ?? '').trim().toLowerCase() || 'unknown',
241
+ text: body,
242
+ });
243
+ if (candidates.length >= MAX_CANDIDATES_PER_COMPACTION)
244
+ break;
245
+ }
246
+ // 剥段:连同它前面的空行一起去掉,避免摘要尾部留一串空行。
247
+ const kept = [...lines.slice(0, start), ...lines.slice(end)];
248
+ while (kept.length > 0 && kept[kept.length - 1].trim() === '')
249
+ kept.pop();
250
+ return { summary: kept.join('\n'), candidates };
251
+ }
252
+ /**
253
+ * 把待裁决候选渲染成反思 prompt 的一节。空队列返回空串(调用方据此不加这一节)。
254
+ *
255
+ * 措辞上必须把它们降级成「未经验证的提示」:它们出自压缩器,而压缩器的任务是
256
+ * 总结不是记忆裁决,它不知道库里有哪条旧记忆、也不知道①/②/⑨/⑪ 这些规则。
257
+ */
258
+ export function formatPendingForReflect(items) {
259
+ if (items.length === 0)
260
+ return '';
261
+ const lines = items.map((c) => `- [${c.kind}] ${c.text}`).join('\n');
262
+ return (`\n## Candidates salvaged from context compaction\n` +
263
+ `These one-liners were pulled out of reasoning that compaction was about to discard. ` +
264
+ `They are UNVERIFIED hints produced by a summarizer, NOT memories: it never saw your rules and never saw the library. ` +
265
+ `Judge each under the normal rules and turn it into saves/updates only when it genuinely passes them; ` +
266
+ `prefer updating an existing entry over adding a near-duplicate. ` +
267
+ `Dropping all of them is a normal and correct outcome — one-off task state, restated progress and generic advice must all be dropped.\n` +
268
+ `${lines}`);
269
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * R8.1 / R9.2:记忆包的导出与导入。
3
+ *
4
+ * 为什么需要它:开源项目的记忆是**用户自己的数据**,而"能导出"是信任的前提——
5
+ * 换成"你只能在这台机器的这个目录下看到它",用户就没法迁移、备份、或在怀疑
6
+ * 被写脏时拿出证据。同时它也是 R9 冷启动的载体:换机后一条命令接上。
7
+ *
8
+ * 为什么打包成**单文件 JSON**而不是 zip:
9
+ * ① 无依赖(仓库纯 ESM,不想为一个导出功能引入压缩库);
10
+ * ② 用户能直接 `less` 看内容——"我能看到"和"我能删"同等重要;
11
+ * ③ 记忆库本身是 JSONL + JSON,体量在几 MB 量级,压缩收益不抵可读性的损失。
12
+ *
13
+ * 叶子模块约定:只依赖 node 内置 + memory 内部模块。不碰 config / agent / llm。
14
+ */
15
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
16
+ import path from 'node:path';
17
+ import { loadAll, importEntries } from './store.js';
18
+ import { loadAllGraph, importGraphPart } from './graph.js';
19
+ import { memoryWriteBlockReason } from './write-gate.js';
20
+ import { appendAudit } from './audit.js';
21
+ /**
22
+ * 包格式版本。**只在结构发生不兼容变化时**才 +1:
23
+ * 新增可选字段不算(旧包能读,新字段缺失由各读路径惰性兜住)。
24
+ * 读端对**更高**版本拒收(可能是新版本写的、含当前代码不认识的语义),
25
+ * 对更低版本放行(missing 字段按既有惰性约定处理)。
26
+ */
27
+ export const MEMORY_PACK_SCHEMA_VERSION = 1;
28
+ /** 全量打包(global + project 两库 + 图谱)。 */
29
+ export function buildPack() {
30
+ const g = loadAllGraph();
31
+ return {
32
+ schemaVersion: MEMORY_PACK_SCHEMA_VERSION,
33
+ exportedAt: new Date().toISOString(),
34
+ entries: loadAll(),
35
+ graph: { entities: g.entities, edges: g.edges },
36
+ };
37
+ }
38
+ /** 默认导出路径:带时间戳,避免连续导出互相覆盖。 */
39
+ export function defaultPackPath() {
40
+ const ts = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
41
+ return path.join(process.cwd(), '.mocode', `memory-pack-${ts}.json`);
42
+ }
43
+ /** 写包(原子写;父目录不存在则建)。返回实际路径。 */
44
+ export function writePack(pack, target) {
45
+ const p = target ? path.resolve(target) : defaultPackPath();
46
+ mkdirSync(path.dirname(p), { recursive: true });
47
+ const tmp = p + '.tmp';
48
+ writeFileSync(tmp, JSON.stringify(pack, null, 2), 'utf8');
49
+ renameSync(tmp, p);
50
+ appendAudit({
51
+ at: pack.exportedAt,
52
+ action: 'export',
53
+ detail: `导出 ${pack.entries.length} 条记忆 + ${pack.graph.entities.length} 实体/${pack.graph.edges.length} 边 → ${p}`,
54
+ });
55
+ return p;
56
+ }
57
+ /**
58
+ * 解析并校验一个包。
59
+ *
60
+ * 校验刻意**宽松但明确**:只要顶层结构与 version 对得上就放行,单条坏数据由
61
+ * `importEntries` / `importGraphPart` 各自跳过。理由与读库一致——一个字段写坏的
62
+ * 条目不该让整份备份无法还原,那是备份最没用的时刻。
63
+ */
64
+ export function parsePack(raw) {
65
+ let obj;
66
+ try {
67
+ obj = JSON.parse(raw);
68
+ }
69
+ catch (e) {
70
+ return { ok: false, reason: `不是合法 JSON:${e instanceof Error ? e.message : String(e)}` };
71
+ }
72
+ if (!obj || typeof obj !== 'object')
73
+ return { ok: false, reason: '包内容不是对象' };
74
+ const o = obj;
75
+ const v = typeof o.schemaVersion === 'number' ? o.schemaVersion : NaN;
76
+ if (!Number.isFinite(v))
77
+ return { ok: false, reason: '缺少 schemaVersion' };
78
+ if (v > MEMORY_PACK_SCHEMA_VERSION) {
79
+ return {
80
+ ok: false,
81
+ reason: `包的 schemaVersion=${v} 高于当前支持的 ${MEMORY_PACK_SCHEMA_VERSION},请升级 mocode 后再导入`,
82
+ };
83
+ }
84
+ if (!Array.isArray(o.entries))
85
+ return { ok: false, reason: '缺少 entries 数组' };
86
+ const graph = o.graph && typeof o.graph === 'object' ? o.graph : { entities: [], edges: [] };
87
+ return {
88
+ ok: true,
89
+ pack: {
90
+ schemaVersion: v,
91
+ exportedAt: typeof o.exportedAt === 'string' ? o.exportedAt : new Date().toISOString(),
92
+ entries: o.entries,
93
+ graph: {
94
+ entities: Array.isArray(graph.entities)
95
+ ? graph.entities
96
+ : [],
97
+ edges: Array.isArray(graph.edges)
98
+ ? graph.edges
99
+ : [],
100
+ },
101
+ },
102
+ };
103
+ }
104
+ /**
105
+ * 把包落库。**先条目后图谱**:条目是主数据,图谱是派生引用(sourceEntry 指向条目 id);
106
+ * 若顺序反过来,一次中途失败会留下指向不存在条目的边。
107
+ *
108
+ * 暂停/关闭时整体拒收,而不是部分导入——半个包比没有包更难排查。
109
+ */
110
+ export function applyPack(pack) {
111
+ const blocked = memoryWriteBlockReason();
112
+ if (blocked)
113
+ return { ok: false, blocked };
114
+ const e = importEntries(pack.entries);
115
+ if ('blocked' in e)
116
+ return { ok: false, blocked: e.blocked };
117
+ const g = importGraphPart(pack.graph.entities, pack.graph.edges);
118
+ if ('blocked' in g)
119
+ return { ok: false, blocked: g.blocked };
120
+ appendAudit({
121
+ at: new Date().toISOString(),
122
+ action: 'import',
123
+ detail: `导入 ${e.added} 新增/${e.updated} 更新/${e.skipped} 跳过条目,` + `${g.addedEntities} 实体/${g.addedEdges} 边`,
124
+ });
125
+ return {
126
+ ok: true,
127
+ added: e.added,
128
+ updated: e.updated,
129
+ skipped: e.skipped,
130
+ addedEntities: g.addedEntities,
131
+ addedEdges: g.addedEdges,
132
+ };
133
+ }
134
+ /** 从磁盘读一个包并落库(命令层的便捷入口)。 */
135
+ export function importPackFile(file) {
136
+ const p = path.resolve(file);
137
+ if (!existsSync(p))
138
+ return { ok: false, reason: `文件不存在:${p}` };
139
+ let raw;
140
+ try {
141
+ raw = readFileSync(p, 'utf8');
142
+ }
143
+ catch (e) {
144
+ return { ok: false, reason: `读取失败:${e instanceof Error ? e.message : String(e)}` };
145
+ }
146
+ const parsed = parsePack(raw);
147
+ if (!parsed.ok)
148
+ return { ok: false, reason: parsed.reason };
149
+ return applyPack(parsed.pack);
150
+ }