sage-mem 2.24.1 → 2.26.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.
- package/README.en.md +69 -1
- package/README.md +69 -1
- package/lib/assembly/index.js +3 -0
- package/lib/assembly/mirror-mount.js +195 -0
- package/lib/client.js +599 -0
- package/lib/index.js +48 -3
- package/lib/intake/merge.js +193 -0
- package/lib/intake/policy.js +238 -0
- package/lib/intake/store.js +247 -0
- package/lib/memory/config.js +7 -15
- package/lib/mirror/export.js +224 -0
- package/lib/mirror/mcp.js +443 -0
- package/lib/mirror/policy.js +311 -0
- package/lib/settings.js +34 -6
- package/lib/shared/int-spec.js +28 -0
- package/lib/typert/schemas.js +105 -0
- package/lib/typert.host.js +51 -1
- package/package.json +1 -1
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* intake 层 —— **唯一**写 `intake/` 目录的地方(IO 与副作用层)。
|
|
3
|
+
*
|
|
4
|
+
* 三条纪律:
|
|
5
|
+
* 1. **只写 intake,不写主库**。落盘、归档、报告、审计都在这里;主库那条路在 `merge.js`。
|
|
6
|
+
* 2. **不做判据**。合不合法在 `policy.js`,该不该收由人决定 —— 这里只负责「放进去 / 挪走 / 记账」。
|
|
7
|
+
* 3. **失败要出声**。写不进 `pending/` 时调用方要能拿到原因(提交方那边会看到 `isError`);
|
|
8
|
+
* 报告与审计写失败只告警,不影响已经完成的处置。
|
|
9
|
+
*/
|
|
10
|
+
import { appendFile, mkdir, readdir, readFile, rename, unlink } from 'node:fs/promises'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
import { frontmatterField } from '../memory/frontmatter.js'
|
|
13
|
+
import { warnLog, writeFileAtomic } from '../memory/util.js'
|
|
14
|
+
import { stampCompact, stampHuman } from '../shared/stamp.js'
|
|
15
|
+
import { renderReport, renderSubmission } from './policy.js'
|
|
16
|
+
|
|
17
|
+
/** 状态账的格式版本。 */
|
|
18
|
+
const STATE_VERSION = 1
|
|
19
|
+
|
|
20
|
+
let seq = 0
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {object} opts
|
|
24
|
+
* @param {object} opts.ctx — 宿主上下文(只为 `warnLog`)
|
|
25
|
+
* @param {string} opts.stateRoot — 状态根;intake 落 `join(stateRoot, 'intake')`
|
|
26
|
+
*/
|
|
27
|
+
export function createIntakeStore({ ctx, stateRoot }) {
|
|
28
|
+
const intakeDir = join(stateRoot, 'intake')
|
|
29
|
+
const agentsDir = join(intakeDir, 'agents')
|
|
30
|
+
const reportsDir = join(intakeDir, 'reports')
|
|
31
|
+
const stateFile = join(intakeDir, 'state.json')
|
|
32
|
+
const auditFile = join(intakeDir, 'audit.jsonl')
|
|
33
|
+
|
|
34
|
+
/** 读状态账(坏文件当空账:最坏后果是同一条被再审一次,不会误删任何东西)。 */
|
|
35
|
+
async function readState() {
|
|
36
|
+
try {
|
|
37
|
+
const parsed = JSON.parse(await readFile(stateFile, 'utf8'))
|
|
38
|
+
if (!parsed || typeof parsed !== 'object' || parsed.version !== STATE_VERSION) return { version: STATE_VERSION, processed: {} }
|
|
39
|
+
const processed = parsed.processed && typeof parsed.processed === 'object' ? parsed.processed : {}
|
|
40
|
+
return { version: STATE_VERSION, processed }
|
|
41
|
+
} catch {
|
|
42
|
+
return { version: STATE_VERSION, processed: {} }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function writeState(state) {
|
|
47
|
+
await mkdir(intakeDir, { recursive: true })
|
|
48
|
+
await writeFileAtomic(stateFile, `${JSON.stringify(state, null, 2)}\n`)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 提交 id:时间戳 + 进程内序号 + 随机尾巴(同一毫秒里连提两条也不会撞)。 */
|
|
52
|
+
function nextId(at = Date.now()) {
|
|
53
|
+
seq += 1
|
|
54
|
+
const rand = Math.random().toString(16).slice(2, 6)
|
|
55
|
+
return `${stampCompact(at)}-${seq.toString(36)}${rand}`
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 把一份**已校验**的提交落进 `pending/`。
|
|
60
|
+
*
|
|
61
|
+
* @param {object} submission — `policy.validateSubmission()` 的产物
|
|
62
|
+
* @param {number} [at]
|
|
63
|
+
* @returns {Promise<{ok:true, id:string, agentId:string, file:string} | {ok:false, error:string}>}
|
|
64
|
+
*/
|
|
65
|
+
async function save(submission, at = Date.now()) {
|
|
66
|
+
const agentId = String(submission?.source ?? '').trim()
|
|
67
|
+
if (agentId === '') return { ok: false, error: '提交缺少 source' }
|
|
68
|
+
const id = nextId(at)
|
|
69
|
+
const dir = join(agentsDir, agentId, 'pending')
|
|
70
|
+
const file = join(dir, `${id}.md`)
|
|
71
|
+
try {
|
|
72
|
+
await mkdir(dir, { recursive: true })
|
|
73
|
+
await writeFileAtomic(file, renderSubmission(submission, new Date(at).toISOString()))
|
|
74
|
+
} catch (err) {
|
|
75
|
+
const error = `写不进 pending(${err?.code ?? err?.message ?? err})`
|
|
76
|
+
warnLog(ctx, `外来提交:${error}`)
|
|
77
|
+
return { ok: false, error }
|
|
78
|
+
}
|
|
79
|
+
await audit({ at, source: agentId, action: 'submit', target: `${agentId}/${id}`, result: `pending(${submission.kind})` })
|
|
80
|
+
return { ok: true, id, agentId, file }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 一条待处理提交的元数据(从落盘的 markdown 里读回来,不另存一份索引)。 */
|
|
84
|
+
function describe(agentId, id, raw) {
|
|
85
|
+
return {
|
|
86
|
+
id,
|
|
87
|
+
agentId,
|
|
88
|
+
raw,
|
|
89
|
+
kind: frontmatterField(raw, 'kind'),
|
|
90
|
+
source: frontmatterField(raw, 'source') || agentId,
|
|
91
|
+
submittedAt: frontmatterField(raw, 'submitted_at'),
|
|
92
|
+
name: frontmatterField(raw, 'name'),
|
|
93
|
+
description: frontmatterField(raw, 'description'),
|
|
94
|
+
type: frontmatterField(raw, 'type'),
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 列出全部待处理提交(按 id 倒序 = 新的在前)。 */
|
|
99
|
+
async function listPending() {
|
|
100
|
+
const out = []
|
|
101
|
+
let agents = []
|
|
102
|
+
try {
|
|
103
|
+
agents = await readdir(agentsDir, { withFileTypes: true })
|
|
104
|
+
} catch {
|
|
105
|
+
return out
|
|
106
|
+
}
|
|
107
|
+
for (const agent of agents) {
|
|
108
|
+
if (!agent.isDirectory()) continue
|
|
109
|
+
const dir = join(agentsDir, agent.name, 'pending')
|
|
110
|
+
let names = []
|
|
111
|
+
try {
|
|
112
|
+
names = await readdir(dir)
|
|
113
|
+
} catch {
|
|
114
|
+
continue
|
|
115
|
+
}
|
|
116
|
+
for (const name of names) {
|
|
117
|
+
if (!name.endsWith('.md')) continue
|
|
118
|
+
const raw = await readFile(join(dir, name), 'utf8').catch(() => null)
|
|
119
|
+
if (raw === null) continue
|
|
120
|
+
out.push(describe(agent.name, name.replace(/\.md$/, ''), raw))
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
out.sort((a, b) => (a.id < b.id ? 1 : a.id > b.id ? -1 : 0))
|
|
124
|
+
return out
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** 按 id 找一条待处理提交(找不到返回 null)。 */
|
|
128
|
+
async function findPending(id) {
|
|
129
|
+
const want = String(id ?? '')
|
|
130
|
+
if (want === '') return null
|
|
131
|
+
const pending = await listPending()
|
|
132
|
+
return pending.find((p) => p.id === want) ?? null
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** 拒绝:把原件留档到 `rejected/`,不删。 */
|
|
136
|
+
async function reject(id, reason = '') {
|
|
137
|
+
const item = await findPending(id)
|
|
138
|
+
if (!item) return { ok: false, error: '找不到这条待处理提交(可能已被处理)' }
|
|
139
|
+
const from = join(agentsDir, item.agentId, 'pending', `${item.id}.md`)
|
|
140
|
+
const to = join(agentsDir, item.agentId, 'rejected', `${item.id}.md`)
|
|
141
|
+
try {
|
|
142
|
+
await mkdir(join(agentsDir, item.agentId, 'rejected'), { recursive: true })
|
|
143
|
+
await rename(from, to)
|
|
144
|
+
} catch (err) {
|
|
145
|
+
return { ok: false, error: `挪进 rejected 失败(${err?.code ?? err?.message ?? err})` }
|
|
146
|
+
}
|
|
147
|
+
await markProcessed(item.id, { action: 'reject', target: item.name, note: reason })
|
|
148
|
+
await audit({ source: item.source, action: 'reject', target: item.name || item.id, result: reason || '已拒绝' })
|
|
149
|
+
return { ok: true, id: item.id, file: to }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 批准后的收尾:删掉 pending 原件(全文已在报告里),状态账记一笔。 */
|
|
153
|
+
async function consume(id) {
|
|
154
|
+
const item = await findPending(id)
|
|
155
|
+
if (!item) return { ok: false, error: '找不到这条待处理提交(可能已被处理)' }
|
|
156
|
+
const file = join(agentsDir, item.agentId, 'pending', `${item.id}.md`)
|
|
157
|
+
try {
|
|
158
|
+
await unlink(file)
|
|
159
|
+
} catch (err) {
|
|
160
|
+
if (err?.code !== 'ENOENT') warnLog(ctx, `外来提交:删 pending 失败(${err?.code ?? err?.message ?? err})`)
|
|
161
|
+
}
|
|
162
|
+
return { ok: true, item }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** 状态账:这条 id 已经被处置过(幂等用)。 */
|
|
166
|
+
async function markProcessed(id, info) {
|
|
167
|
+
const state = await readState()
|
|
168
|
+
state.processed[id] = { at: Date.now(), ...info }
|
|
169
|
+
try {
|
|
170
|
+
await writeState(state)
|
|
171
|
+
} catch (err) {
|
|
172
|
+
warnLog(ctx, `外来提交:写状态账失败(${err?.code ?? err?.message ?? err})`)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function isProcessed(id) {
|
|
177
|
+
const state = await readState()
|
|
178
|
+
return !!state.processed[String(id ?? '')]
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** 审计:一行一条 JSON(只追加,不改历史)。 */
|
|
182
|
+
async function audit(entry) {
|
|
183
|
+
const line = JSON.stringify({
|
|
184
|
+
at: new Date(entry.at ?? Date.now()).toISOString(),
|
|
185
|
+
time: stampHuman(entry.at ?? Date.now()),
|
|
186
|
+
source: entry.source ?? '',
|
|
187
|
+
action: entry.action ?? '',
|
|
188
|
+
target: entry.target ?? '',
|
|
189
|
+
result: entry.result ?? '',
|
|
190
|
+
})
|
|
191
|
+
try {
|
|
192
|
+
await mkdir(intakeDir, { recursive: true })
|
|
193
|
+
// 追加用 appendFile:审计是「只追加的流水」。整份读-改-写在两个进程同时记账时会丢行,
|
|
194
|
+
// 而审计最不能接受的就是「少了一行」—— 那正是要查的那条。
|
|
195
|
+
await appendFile(auditFile, `${line}\n`, 'utf8')
|
|
196
|
+
} catch (err) {
|
|
197
|
+
warnLog(ctx, `外来提交:写审计失败(${err?.code ?? err?.message ?? err})`)
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** 写一份人读报告;返回文件名(失败不抛)。 */
|
|
202
|
+
async function writeReport({ submission, proposal, result, id, at = Date.now() }) {
|
|
203
|
+
const atISO = new Date(at).toISOString()
|
|
204
|
+
const name = `${stampCompact(at)}-${id}.md`
|
|
205
|
+
try {
|
|
206
|
+
await mkdir(reportsDir, { recursive: true })
|
|
207
|
+
await writeFileAtomic(join(reportsDir, name), renderReport({ submission, proposal, result, atISO }))
|
|
208
|
+
return name
|
|
209
|
+
} catch (err) {
|
|
210
|
+
warnLog(ctx, `外来提交:写报告失败(${err?.code ?? err?.message ?? err})`)
|
|
211
|
+
return ''
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** 最近 N 份报告(新的在前)。 */
|
|
216
|
+
async function listReports(limit = 5) {
|
|
217
|
+
let names = []
|
|
218
|
+
try {
|
|
219
|
+
names = await readdir(reportsDir)
|
|
220
|
+
} catch {
|
|
221
|
+
return []
|
|
222
|
+
}
|
|
223
|
+
const picked = names.filter((n) => n.endsWith('.md')).sort((a, b) => (a < b ? 1 : a > b ? -1 : 0)).slice(0, Math.max(1, limit))
|
|
224
|
+
const out = []
|
|
225
|
+
for (const name of picked) {
|
|
226
|
+
const text = await readFile(join(reportsDir, name), 'utf8').catch(() => '')
|
|
227
|
+
out.push({ name, text })
|
|
228
|
+
}
|
|
229
|
+
return out
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
intakeDir,
|
|
234
|
+
stateFile,
|
|
235
|
+
auditFile,
|
|
236
|
+
save,
|
|
237
|
+
listPending,
|
|
238
|
+
findPending,
|
|
239
|
+
reject,
|
|
240
|
+
consume,
|
|
241
|
+
markProcessed,
|
|
242
|
+
isProcessed,
|
|
243
|
+
audit,
|
|
244
|
+
writeReport,
|
|
245
|
+
listReports,
|
|
246
|
+
}
|
|
247
|
+
}
|
package/lib/memory/config.js
CHANGED
|
@@ -9,6 +9,7 @@ import { readFileSync } from 'node:fs'
|
|
|
9
9
|
import { homedir } from 'node:os'
|
|
10
10
|
import { dirname, join } from 'node:path'
|
|
11
11
|
import { INDEX_FILE_KEY, SESSION_LOG_KEY, isPlainMdName } from '../shared/md-name.js'
|
|
12
|
+
import { parseLimitValue } from '../shared/int-spec.js'
|
|
12
13
|
|
|
13
14
|
export const MEMORY_DIR = process.env.SAGE_MEM_DIR || join(homedir(), '.sage-mem', 'memory')
|
|
14
15
|
/**
|
|
@@ -77,22 +78,13 @@ export const LIMIT_SPECS = {
|
|
|
77
78
|
staleDays: { env: 'SAGE_MEM_STALE_DAYS', dflt: 1, lo: 0, hi: 365 },
|
|
78
79
|
}
|
|
79
80
|
/**
|
|
80
|
-
* 单项上限的**唯一**校验:非法返回 `undefined`,合法返回收敛到 `[lo, hi]` 的整数。
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
81
|
+
* 单项上限的**唯一**校验:非法返回 `undefined`,合法返回收敛到 `[lo, hi]` 的整数。
|
|
82
|
+
*
|
|
83
|
+
* 2.25.0 起实现在 `lib/shared/int-spec.js`:`mirror/policy.js`(纯逻辑层,不许 import 本模块,
|
|
84
|
+
* 因为本模块在加载时就读盘)也要用同一套语义。这里 import 进来自己用、并原样转出 ——
|
|
85
|
+
* `resolveLimits` 用的仍是同一个函数,判据没有第二份。
|
|
84
86
|
*/
|
|
85
|
-
export
|
|
86
|
-
if (typeof raw === 'number') {
|
|
87
|
-
return Number.isFinite(raw) ? Math.max(spec.lo, Math.min(spec.hi, Math.round(raw))) : undefined
|
|
88
|
-
}
|
|
89
|
-
if (typeof raw !== 'string') return undefined
|
|
90
|
-
const text = raw.trim()
|
|
91
|
-
if (text === '') return undefined
|
|
92
|
-
const n = Number(text)
|
|
93
|
-
if (!Number.isFinite(n)) return undefined
|
|
94
|
-
return Math.max(spec.lo, Math.min(spec.hi, Math.round(n)))
|
|
95
|
-
}
|
|
87
|
+
export { parseLimitValue }
|
|
96
88
|
|
|
97
89
|
/**
|
|
98
90
|
* 五项上限的**单一解析器**:持久设置 > 环境变量 > 内置默认。
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mirror 层 —— **唯一**写 `mirror/` 目录的地方(IO 与副作用层)。
|
|
3
|
+
*
|
|
4
|
+
* 三条纪律,改这个文件之前先读:
|
|
5
|
+
* 1. **只写副本,不碰主库**。这里没有任何指向 `memory/` 的写操作,连 rename 都不做。
|
|
6
|
+
* 2. **判据不在本文件**。要不要暴露、索引写成什么样,全在 `policy.js`;本文件只负责
|
|
7
|
+
* 「读主库 → 问 policy → 落盘 / 删盘」,一句自己的判据都不许有。
|
|
8
|
+
* 3. **拿不准就不动手**。主库列不出来(盘掉线 / 无权限 / 目录还没建)时,副本与账
|
|
9
|
+
* **一个字节都不动**并如实上报 —— 把「扫描失败」当成「主库空了」会清空副本,
|
|
10
|
+
* 而那份副本正是别的 agent 此刻在读的东西。
|
|
11
|
+
*
|
|
12
|
+
* 增量判据是**副本自己的内容 sha**,不是账里的记录:账只用来回答「上次导了什么」,
|
|
13
|
+
* 不用来回答「还要不要导」。差别在于副本被外部改坏 / 删掉之后,账看起来一切正常,
|
|
14
|
+
* 而按内容比对会立刻发现并重写。
|
|
15
|
+
*/
|
|
16
|
+
import { mkdir, readdir, readFile, unlink } from 'node:fs/promises'
|
|
17
|
+
import { join } from 'node:path'
|
|
18
|
+
import { parseFrontmatter } from '../memory/frontmatter.js'
|
|
19
|
+
import { revisionOf } from '../memory/write-protocol.js'
|
|
20
|
+
import { scanMemoryDirDetailed } from '../memory/scan.js'
|
|
21
|
+
import { warnLog, writeFileAtomic } from '../memory/util.js'
|
|
22
|
+
import { stampHuman } from '../shared/stamp.js'
|
|
23
|
+
import {
|
|
24
|
+
MIRROR_DIR_NAME,
|
|
25
|
+
MIRROR_INDEX_NAME,
|
|
26
|
+
MIRROR_MCP_NAME,
|
|
27
|
+
MIRROR_STATE_NAME,
|
|
28
|
+
buildMirrorIndex,
|
|
29
|
+
isExposed,
|
|
30
|
+
isMirrorReadableName,
|
|
31
|
+
} from './policy.js'
|
|
32
|
+
|
|
33
|
+
/** 增量账的格式版本。形状(不是加字段)变了才 +1。 */
|
|
34
|
+
const STATE_VERSION = 1
|
|
35
|
+
|
|
36
|
+
const shaOf = (text) => revisionOf(Buffer.from(text, 'utf8'))
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 建一个导出器。
|
|
40
|
+
*
|
|
41
|
+
* @param {object} opts
|
|
42
|
+
* @param {object} opts.ctx — 宿主上下文(只为 `warnLog`)
|
|
43
|
+
* @param {string} opts.memoryDir — 主库目录(**只读**)
|
|
44
|
+
* @param {string} opts.stateRoot — 状态根;副本落 `join(stateRoot, 'mirror')`
|
|
45
|
+
* @param {Function} [opts.scan] — 测试注入用;默认 `scanMemoryDirDetailed`
|
|
46
|
+
*/
|
|
47
|
+
export function createMirrorExporter({ ctx, memoryDir, stateRoot, scan = scanMemoryDirDetailed }) {
|
|
48
|
+
const mirrorDir = join(stateRoot, MIRROR_DIR_NAME)
|
|
49
|
+
const stateFile = join(mirrorDir, MIRROR_STATE_NAME)
|
|
50
|
+
const indexPath = join(mirrorDir, MIRROR_INDEX_NAME)
|
|
51
|
+
|
|
52
|
+
/** 读增量账。坏文件 / 旧版本当空账(只影响「上次导了什么」的叙述,不影响是否要写)。 */
|
|
53
|
+
async function readState() {
|
|
54
|
+
try {
|
|
55
|
+
const parsed = JSON.parse(await readFile(stateFile, 'utf8'))
|
|
56
|
+
if (!parsed || typeof parsed !== 'object' || parsed.version !== STATE_VERSION) return { entries: {} }
|
|
57
|
+
const entries = parsed.entries && typeof parsed.entries === 'object' && !Array.isArray(parsed.entries) ? parsed.entries : {}
|
|
58
|
+
return { entries }
|
|
59
|
+
} catch {
|
|
60
|
+
return { entries: {} }
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 副本目录里现在有哪些**可读条目**(点文件与索引不算)。 */
|
|
65
|
+
async function listMirrorNames() {
|
|
66
|
+
const names = await readdir(mirrorDir).catch(() => [])
|
|
67
|
+
return names.filter((n) => isMirrorReadableName(n))
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 跑一轮导出。**不抛**:任何失败都进 `errors` 并如实上报(挂载层会写进面板状态)。
|
|
72
|
+
*
|
|
73
|
+
* @param {object} external — `resolveExternal` 的产物
|
|
74
|
+
* @returns {Promise<{ok:boolean, at:number, exposed:number, written:number, unchanged:number,
|
|
75
|
+
* deleted:number, indexed:boolean, skipped:string[], errors:string[]}>}
|
|
76
|
+
*/
|
|
77
|
+
async function run(external) {
|
|
78
|
+
const at = Date.now()
|
|
79
|
+
const report = { ok: true, at, disabled: false, exposed: 0, names: [], written: 0, unchanged: 0, deleted: 0, indexed: false, skipped: [], errors: [] }
|
|
80
|
+
// 开关关着时**什么都不碰**:不清副本、不写账。副本是「可重建的只读快照」,
|
|
81
|
+
// 关掉端点不等于要求删文件;而「关一次清一次」会让下次打开时有一段空窗期。
|
|
82
|
+
if (!external || !external.enabled) {
|
|
83
|
+
report.disabled = true
|
|
84
|
+
return report
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ── 1. 读主库(只读)─────────────────────────────────────────────
|
|
88
|
+
const scanned = await scan(ctx, '', memoryDir)
|
|
89
|
+
if (scanned.complete === false) {
|
|
90
|
+
report.ok = false
|
|
91
|
+
report.errors.push(`主库目录读不出来,本轮不动副本:${scanned.errors.map((e) => e.code || e.message).join(';') || '未知原因'}`)
|
|
92
|
+
warnLog(ctx, `外部访问导出有问题:${report.errors.join(';')}`)
|
|
93
|
+
return report
|
|
94
|
+
}
|
|
95
|
+
if (scanned.missing === true) {
|
|
96
|
+
report.ok = false
|
|
97
|
+
report.errors.push('主库目录不存在,本轮不动副本(避免把一次盘掉线当成「主库空了」)')
|
|
98
|
+
warnLog(ctx, `外部访问导出有问题:${report.errors.join(';')}`)
|
|
99
|
+
return report
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ── 2. 问 policy:这一轮该暴露谁 ─────────────────────────────────
|
|
103
|
+
/** name → {content, meta, sha} */
|
|
104
|
+
const desired = new Map()
|
|
105
|
+
for (const file of scanned.files) {
|
|
106
|
+
const meta = parseFrontmatter(file.content)
|
|
107
|
+
if (!isExposed(file.file, meta.tags, external)) continue
|
|
108
|
+
desired.set(file.file, { content: file.content, meta, sha: shaOf(file.content), mtimeMs: file.mtimeMs ?? 0 })
|
|
109
|
+
}
|
|
110
|
+
report.exposed = desired.size
|
|
111
|
+
report.names = [...desired.keys()].sort()
|
|
112
|
+
|
|
113
|
+
// ── 3. 落盘(内容 sha 相同就不写)────────────────────────────────
|
|
114
|
+
try {
|
|
115
|
+
await mkdir(mirrorDir, { recursive: true })
|
|
116
|
+
} catch (err) {
|
|
117
|
+
report.ok = false
|
|
118
|
+
report.errors.push(`建不了副本目录(${err?.code ?? err?.message ?? err})`)
|
|
119
|
+
return report
|
|
120
|
+
}
|
|
121
|
+
const existing = new Set(await listMirrorNames())
|
|
122
|
+
const next = {}
|
|
123
|
+
for (const [name, item] of desired) {
|
|
124
|
+
next[name] = { sha: item.sha, size: Buffer.byteLength(item.content, 'utf8'), mtimeMs: item.mtimeMs }
|
|
125
|
+
const current = existing.has(name) ? await readFile(join(mirrorDir, name), 'utf8').catch(() => null) : null
|
|
126
|
+
if (current !== null && shaOf(current) === item.sha) {
|
|
127
|
+
report.unchanged += 1
|
|
128
|
+
continue
|
|
129
|
+
}
|
|
130
|
+
try {
|
|
131
|
+
await writeFileAtomic(join(mirrorDir, name), item.content)
|
|
132
|
+
report.written += 1
|
|
133
|
+
} catch (err) {
|
|
134
|
+
// 单条写失败不拖垮整轮:报出来、下一轮再来。
|
|
135
|
+
report.ok = false
|
|
136
|
+
report.skipped.push(name)
|
|
137
|
+
report.errors.push(`写副本失败 ${name}:${err?.code ?? err?.message ?? err}`)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ── 4. 删掉退出白名单 / 主库已删的副本 ───────────────────────────
|
|
142
|
+
for (const name of existing) {
|
|
143
|
+
if (desired.has(name)) continue
|
|
144
|
+
try {
|
|
145
|
+
await unlink(join(mirrorDir, name))
|
|
146
|
+
report.deleted += 1
|
|
147
|
+
} catch (err) {
|
|
148
|
+
if (err?.code === 'ENOENT') continue
|
|
149
|
+
report.ok = false
|
|
150
|
+
report.errors.push(`删副本失败 ${name}:${err?.code ?? err?.message ?? err}`)
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ── 5. 副本索引(重新生成;只有真的变了才写)──────────────────────
|
|
155
|
+
const indexText = buildMirrorIndex(
|
|
156
|
+
[...desired].map(([name, item]) => ({ name, title: item.meta.name, description: item.meta.description, tags: item.meta.tags })),
|
|
157
|
+
{ stamp: stampHuman(at) },
|
|
158
|
+
)
|
|
159
|
+
const currentIndex = await readFile(indexPath, 'utf8').catch(() => null)
|
|
160
|
+
if (currentIndex !== indexText) {
|
|
161
|
+
try {
|
|
162
|
+
await writeFileAtomic(indexPath, indexText)
|
|
163
|
+
report.indexed = true
|
|
164
|
+
} catch (err) {
|
|
165
|
+
report.ok = false
|
|
166
|
+
report.errors.push(`写副本索引失败:${err?.code ?? err?.message ?? err}`)
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ── 6. 记账 ─────────────────────────────────────────────────────
|
|
171
|
+
try {
|
|
172
|
+
await writeFileAtomic(stateFile, `${JSON.stringify({ version: STATE_VERSION, at, entries: next }, null, 2)}\n`)
|
|
173
|
+
} catch (err) {
|
|
174
|
+
report.ok = false
|
|
175
|
+
report.errors.push(`写增量账失败:${err?.code ?? err?.message ?? err}`)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (report.errors.length > 0) warnLog(ctx, `外部访问导出有问题:${report.errors.join(';')}`)
|
|
179
|
+
return report
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 副本里的一条正文(MCP `memory_read` 用)。**不存在就返回 null**,不抛 ——
|
|
184
|
+
* 外部调用方要的是一句「没有这条」,不是一个异常栈。
|
|
185
|
+
*/
|
|
186
|
+
async function readMirrorEntry(name) {
|
|
187
|
+
if (!isMirrorReadableName(name)) return null
|
|
188
|
+
try {
|
|
189
|
+
return await readFile(join(mirrorDir, name), 'utf8')
|
|
190
|
+
} catch {
|
|
191
|
+
return null
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 副本里**此刻真的能读到**的条目(MCP `memory_list` / `memory_search` 的语料)。
|
|
197
|
+
*
|
|
198
|
+
* 读的是副本目录本身,不是增量账:账里可能记着一条刚被删掉的副本,
|
|
199
|
+
* 而工具面必须只说「现在能读到什么」。
|
|
200
|
+
*/
|
|
201
|
+
async function listMirrorEntries() {
|
|
202
|
+
const out = []
|
|
203
|
+
for (const name of await listMirrorNames()) {
|
|
204
|
+
const content = await readFile(join(mirrorDir, name), 'utf8').catch(() => null)
|
|
205
|
+
if (content === null) continue
|
|
206
|
+
const meta = parseFrontmatter(content)
|
|
207
|
+
out.push({
|
|
208
|
+
name,
|
|
209
|
+
title: meta.name || name.replace(/\.md$/i, ''),
|
|
210
|
+
description: meta.description || '',
|
|
211
|
+
type: meta.type || '',
|
|
212
|
+
tags: meta.tags,
|
|
213
|
+
content,
|
|
214
|
+
})
|
|
215
|
+
}
|
|
216
|
+
out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
217
|
+
return out
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** 记在副本目录里的端点发现文件路径(MCP 层写它)。 */
|
|
221
|
+
const mcpFile = join(mirrorDir, MIRROR_MCP_NAME)
|
|
222
|
+
|
|
223
|
+
return { mirrorDir, stateFile, indexPath, mcpFile, run, readMirrorEntry, listMirrorEntries, listMirrorNames, readState }
|
|
224
|
+
}
|