sage-mem 2.25.0 → 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 +34 -1
- package/README.md +34 -1
- package/lib/assembly/mirror-mount.js +14 -3
- package/lib/client.js +236 -0
- package/lib/index.js +19 -0
- package/lib/intake/merge.js +193 -0
- package/lib/intake/policy.js +238 -0
- package/lib/intake/store.js +247 -0
- package/lib/mirror/mcp.js +53 -6
- package/lib/mirror/policy.js +17 -6
- package/lib/typert/schemas.js +47 -0
- package/lib/typert.host.js +39 -1
- package/package.json +1 -1
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* intake 层 —— 外来提交的**纯判据**(零 `node:` 内建 import)。
|
|
3
|
+
*
|
|
4
|
+
* 这一层回答三个问题,一句 IO 都不做:
|
|
5
|
+
* 1. **这份提交合不合法**(不合法就在 MCP 入口拒掉,连 `pending/` 都不让进);
|
|
6
|
+
* 2. **它该走哪条处置**(新建 / 撞名 / 需人工并入 / 打回);
|
|
7
|
+
* 3. **落盘时长什么样**(把结构化参数渲染成一份人可读的 markdown)。
|
|
8
|
+
*
|
|
9
|
+
* 为什么必须纯:校验规则是**安全边界**(外来 agent 不许写关于用户本人的记忆、不许覆盖同名文件),
|
|
10
|
+
* 而它的故障形态是「安静地放进来一条本不该收的」。这种判据要能对着字符串写断言。
|
|
11
|
+
*
|
|
12
|
+
* 边界与取舍见 `docs/2.26.0-plan.md`;决定见 `docs/decisions.md` D59。
|
|
13
|
+
*/
|
|
14
|
+
import { INDEX_FILE_KEY, SESSION_LOG_KEY, isPlainMdName } from '../shared/md-name.js'
|
|
15
|
+
|
|
16
|
+
/** 提交的体积与形状上限(**唯一定义**)。 */
|
|
17
|
+
export const SUBMIT_LIMITS = Object.freeze({
|
|
18
|
+
/** 正文 + frontmatter 合计上限。 */
|
|
19
|
+
totalBytes: 64 * 1024,
|
|
20
|
+
/** 单条正文上限。 */
|
|
21
|
+
bodyBytes: 32 * 1024,
|
|
22
|
+
description: 200,
|
|
23
|
+
nameLength: 80,
|
|
24
|
+
sourceLength: 40,
|
|
25
|
+
tags: 8,
|
|
26
|
+
tagLength: 40,
|
|
27
|
+
/** `patch` 两段各自的上限。 */
|
|
28
|
+
patchSection: 16 * 1024,
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
/** 外来提交只许建这两类 —— `user_*` / `feedback_*` 是关于用户本人的,外来 agent 不许写。 */
|
|
32
|
+
export const SUBMIT_TYPES = Object.freeze(['project', 'reference'])
|
|
33
|
+
|
|
34
|
+
/** `kind` 只有两种。 */
|
|
35
|
+
export const SUBMIT_KINDS = Object.freeze(['new', 'patch'])
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 内置保留名(索引 / 流水)。**用户自己声明的**保留名不在这里判 —— 那要读
|
|
39
|
+
eserved.json,
|
|
40
|
+
* 属于 IO 层,由 merge.js 在真正落盘前再兜一道。这里只保证「外来提交永远占不到这两个名字」。
|
|
41
|
+
*/
|
|
42
|
+
const RESERVED_BUILTIN = new Set([INDEX_FILE_KEY, SESSION_LOG_KEY])
|
|
43
|
+
|
|
44
|
+
/** 每种 type 对应的文件名前缀 —— 名字与类型对不上会让注入链与白名单都失配。 */
|
|
45
|
+
const TYPE_PREFIX = Object.freeze({ project: 'project_', reference: 'reference_' })
|
|
46
|
+
|
|
47
|
+
const SOURCE_RE = /^[a-z0-9][a-z0-9-]*$/
|
|
48
|
+
const SLUG_RE = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/
|
|
49
|
+
|
|
50
|
+
const byteLength = (text) => Buffer.byteLength(String(text ?? ''), 'utf8')
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 规范化来源标识:小写、只留字母数字与 `-`。
|
|
54
|
+
*
|
|
55
|
+
* ⚠️ 它是**声明**,不是凭证 —— MCP 端点无鉴权,谁都能说自己叫 `claude-code`。
|
|
56
|
+
* 契约里写明了这一点(6.17),不要把它当安全边界用。
|
|
57
|
+
*/
|
|
58
|
+
export function normalizeSource(raw) {
|
|
59
|
+
if (typeof raw !== 'string') return null
|
|
60
|
+
const s = raw.trim().toLowerCase()
|
|
61
|
+
if (s === '' || s.length > SUBMIT_LIMITS.sourceLength) return null
|
|
62
|
+
if (!SOURCE_RE.test(s)) return null
|
|
63
|
+
return s
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 名字(slug,不带 `.md`)能不能当一条记忆的文件名。 */
|
|
67
|
+
function normalizeEntryName(raw) {
|
|
68
|
+
if (typeof raw !== 'string') return null
|
|
69
|
+
const s = raw.trim()
|
|
70
|
+
if (s === '') return null
|
|
71
|
+
// 允许调用方顺手带上 `.md`:外来 agent 常见的写法,收下来比拒了更友好。
|
|
72
|
+
const slug = s.toLowerCase().endsWith('.md') ? s.slice(0, -3) : s
|
|
73
|
+
if (slug.length > SUBMIT_LIMITS.nameLength) return null
|
|
74
|
+
if (!SLUG_RE.test(slug)) return null
|
|
75
|
+
if (slug.startsWith('.')) return null
|
|
76
|
+
if (!isPlainMdName(`${slug}.md`)) return null
|
|
77
|
+
if (RESERVED_BUILTIN.has(`${slug}.md`.toLowerCase())) return null
|
|
78
|
+
return slug
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 标签:短、无控制字符、去重、截到上限。 */
|
|
82
|
+
function normalizeTags(raw) {
|
|
83
|
+
const out = []
|
|
84
|
+
const seen = new Set()
|
|
85
|
+
for (const item of Array.isArray(raw) ? raw : []) {
|
|
86
|
+
// 只要字符串:数字 / 对象当标签是笔误,收下来会在 frontmatter 里变成奇怪的东西。
|
|
87
|
+
if (typeof item !== 'string') continue
|
|
88
|
+
const s = item.trim().replace(/^["']|["']$/g, '').trim()
|
|
89
|
+
if (s === '' || s.length > SUBMIT_LIMITS.tagLength) continue
|
|
90
|
+
if (/[\u0000-\u001f]/.test(s)) continue
|
|
91
|
+
const key = s.toLowerCase()
|
|
92
|
+
if (seen.has(key)) continue
|
|
93
|
+
seen.add(key)
|
|
94
|
+
out.push(s)
|
|
95
|
+
if (out.length >= SUBMIT_LIMITS.tags) break
|
|
96
|
+
}
|
|
97
|
+
return out
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 正文不许自带 frontmatter —— 我们会自己生成一份,两份叠在一起就是坏文件。 */
|
|
101
|
+
function bodyProblem(text) {
|
|
102
|
+
const s = String(text ?? '')
|
|
103
|
+
if (s.trim() === '') return '正文是空的'
|
|
104
|
+
if (/^---\r?\n/.test(s.trimStart())) return '正文不能自带 frontmatter(第一行是 ---);frontmatter 由 sage-mem 生成'
|
|
105
|
+
return ''
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 校验一份提交。**入口唯一的判据** —— MCP 的 `memory_submit`、面板的「手动导入」、测试都走它。
|
|
110
|
+
*
|
|
111
|
+
* @param {object} input — 工具入参(结构化,不是 markdown)
|
|
112
|
+
* @returns {{ok:true, submission:object} | {ok:false, error:string}}
|
|
113
|
+
*/
|
|
114
|
+
export function validateSubmission(input) {
|
|
115
|
+
const raw = input && typeof input === 'object' && !Array.isArray(input) ? input : {}
|
|
116
|
+
const source = normalizeSource(raw.source)
|
|
117
|
+
if (!source) return { ok: false, error: `source 必填,且只能是小写字母 / 数字 / 连字符(≤ ${SUBMIT_LIMITS.sourceLength} 字符)` }
|
|
118
|
+
const kind = String(raw.kind ?? '').trim().toLowerCase()
|
|
119
|
+
if (!SUBMIT_KINDS.includes(kind)) return { ok: false, error: `kind 只能是 ${SUBMIT_KINDS.join(' 或 ')}` }
|
|
120
|
+
|
|
121
|
+
if (kind === 'new') {
|
|
122
|
+
const name = normalizeEntryName(raw.name)
|
|
123
|
+
if (!name) return { ok: false, error: 'name 必须是合法的单段文件名(不含路径分隔符、不是保留名、不是点文件)' }
|
|
124
|
+
const type = String(raw.type ?? '').trim().toLowerCase()
|
|
125
|
+
if (!SUBMIT_TYPES.includes(type)) {
|
|
126
|
+
return { ok: false, error: `type 只能是 ${SUBMIT_TYPES.join(' 或 ')} —— 外来提交不许写 user_* / feedback_*(那是关于用户本人的)` }
|
|
127
|
+
}
|
|
128
|
+
const wantPrefix = TYPE_PREFIX[type]
|
|
129
|
+
if (!name.toLowerCase().startsWith(wantPrefix)) {
|
|
130
|
+
return { ok: false, error: `type=${type} 的名字必须以 ${wantPrefix} 开头(否则注入链与白名单都认不出它)` }
|
|
131
|
+
}
|
|
132
|
+
const description = String(raw.description ?? '').trim()
|
|
133
|
+
if (description === '') return { ok: false, error: 'description 必填(一句话说明这条记忆是什么)' }
|
|
134
|
+
if (description.length > SUBMIT_LIMITS.description) return { ok: false, error: `description 超过 ${SUBMIT_LIMITS.description} 字符` }
|
|
135
|
+
const body = String(raw.body ?? '')
|
|
136
|
+
const problem = bodyProblem(body)
|
|
137
|
+
if (problem) return { ok: false, error: problem }
|
|
138
|
+
if (byteLength(body) > SUBMIT_LIMITS.bodyBytes) return { ok: false, error: `正文超过 ${Math.round(SUBMIT_LIMITS.bodyBytes / 1024)} KB` }
|
|
139
|
+
const submission = { kind, source, name, type, description, tags: normalizeTags(raw.tags), body }
|
|
140
|
+
if (byteLength(renderSubmission(submission, '1970-01-01T00:00:00+00:00')) > SUBMIT_LIMITS.totalBytes) {
|
|
141
|
+
return { ok: false, error: `提交合计超过 ${Math.round(SUBMIT_LIMITS.totalBytes / 1024)} KB` }
|
|
142
|
+
}
|
|
143
|
+
return { ok: true, submission }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// kind === 'patch'
|
|
147
|
+
const name = normalizeEntryName(raw.name)
|
|
148
|
+
if (!name) return { ok: false, error: 'patch 的 name 必须是主库里某条记忆的文件名(或它的 slug)' }
|
|
149
|
+
const changes = String(raw.changes ?? '')
|
|
150
|
+
const suggested = String(raw.suggested ?? '')
|
|
151
|
+
const problem = bodyProblem(changes) || bodyProblem(suggested)
|
|
152
|
+
if (problem) return { ok: false, error: problem.includes('空') ? 'patch 的 changes 与 suggested 都不能为空' : problem }
|
|
153
|
+
if (byteLength(changes) > SUBMIT_LIMITS.patchSection || byteLength(suggested) > SUBMIT_LIMITS.patchSection) {
|
|
154
|
+
return { ok: false, error: `patch 的 changes / suggested 各不得超过 ${Math.round(SUBMIT_LIMITS.patchSection / 1024)} KB` }
|
|
155
|
+
}
|
|
156
|
+
const submission = {
|
|
157
|
+
kind, source, name,
|
|
158
|
+
changes: changes.trim(),
|
|
159
|
+
suggested: suggested.trim(),
|
|
160
|
+
reason: String(raw.reason ?? '').trim().slice(0, 1000),
|
|
161
|
+
}
|
|
162
|
+
if (byteLength(renderSubmission(submission, '1970-01-01T00:00:00+00:00')) > SUBMIT_LIMITS.totalBytes) {
|
|
163
|
+
return { ok: false, error: `提交合计超过 ${Math.round(SUBMIT_LIMITS.totalBytes / 1024)} KB` }
|
|
164
|
+
}
|
|
165
|
+
return { ok: true, submission }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* 渲染成落盘的 markdown(人可读、可 diff、可手工检查)。
|
|
170
|
+
*
|
|
171
|
+
* @param {object} submission — `validateSubmission` 的产物
|
|
172
|
+
* @param {string} atISO — 提交时间(**由调用方给**:纯函数不读时钟)
|
|
173
|
+
*/
|
|
174
|
+
export function renderSubmission(submission, atISO) {
|
|
175
|
+
const s = submission ?? {}
|
|
176
|
+
const lines = ['---', `kind: ${s.kind}`, `source: ${s.source}`, `submitted_at: ${atISO}`, `name: ${s.name}`]
|
|
177
|
+
if (s.kind === 'new') {
|
|
178
|
+
lines.push(`description: ${JSON.stringify(String(s.description ?? ''))}`)
|
|
179
|
+
lines.push(`type: ${s.type}`)
|
|
180
|
+
if (Array.isArray(s.tags) && s.tags.length) lines.push(`tags: [${s.tags.join(', ')}]`)
|
|
181
|
+
lines.push('---', '', String(s.body ?? '').replace(/\s+$/, ''), '')
|
|
182
|
+
return lines.join('\n')
|
|
183
|
+
}
|
|
184
|
+
lines.push('---', '', '## 要改的地方', '', String(s.changes ?? '').trim(), '', '## 建议改成', '', String(s.suggested ?? '').trim())
|
|
185
|
+
if (s.reason) lines.push('', '## 理由', '', String(s.reason).trim())
|
|
186
|
+
lines.push('')
|
|
187
|
+
return lines.join('\n')
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* 归并器:这条提交该怎么处置。**只出提案,不动任何文件。**
|
|
192
|
+
*
|
|
193
|
+
* @param {object} submission
|
|
194
|
+
* @param {Iterable<string>} existingNames — 主库现有文件名(大小写不敏感比对)
|
|
195
|
+
* @returns {{action:'create'|'conflict'|'manual'|'reject', targetFile:string, reason:string}}
|
|
196
|
+
*/
|
|
197
|
+
export function proposeFor(submission, existingNames) {
|
|
198
|
+
const set = new Set()
|
|
199
|
+
for (const n of existingNames ?? []) set.add(String(n).toLowerCase())
|
|
200
|
+
const name = String(submission?.name ?? '')
|
|
201
|
+
const targetFile = name.toLowerCase().endsWith('.md') ? name : `${name}.md`
|
|
202
|
+
const exists = set.has(targetFile.toLowerCase())
|
|
203
|
+
if (submission?.kind === 'new') {
|
|
204
|
+
return exists
|
|
205
|
+
? { action: 'conflict', targetFile, reason: '主库里已经有同名条目 —— 只能拒绝,或让提交方改用 patch / 换个名字重提' }
|
|
206
|
+
: { action: 'create', targetFile, reason: '新条目;批准后会排他创建(不覆盖任何已有文件)并补齐索引' }
|
|
207
|
+
}
|
|
208
|
+
return exists
|
|
209
|
+
? { action: 'manual', targetFile, reason: '目标是已有记忆;建议需人工并入,插件不会自动写它' }
|
|
210
|
+
: { action: 'reject', targetFile, reason: '目标条目不存在 —— 这条修改提案无的放矢' }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* 人读的报告(一条提交一份,落 `intake/reports/`)。
|
|
215
|
+
*/
|
|
216
|
+
export function renderReport({ submission, proposal, result, atISO } = {}) {
|
|
217
|
+
const s = submission ?? {}
|
|
218
|
+
const p = proposal ?? {}
|
|
219
|
+
const lines = [
|
|
220
|
+
`# 外来提交处置:${s.name ?? '(无名字)'}`,
|
|
221
|
+
'',
|
|
222
|
+
`- 时间:${atISO ?? ''}`,
|
|
223
|
+
`- 来源:${s.source ?? ''}(声明值,不是凭证)`,
|
|
224
|
+
`- 类型:${s.kind ?? ''}`,
|
|
225
|
+
`- 提案:${p.action ?? ''} —— ${p.reason ?? ''}`,
|
|
226
|
+
`- 结果:${result ?? ''}`,
|
|
227
|
+
'',
|
|
228
|
+
'## 提交原文',
|
|
229
|
+
'',
|
|
230
|
+
'```markdown',
|
|
231
|
+
String(s.kind === 'patch'
|
|
232
|
+
? `## 要改的地方\n${s.changes ?? ''}\n\n## 建议改成\n${s.suggested ?? ''}${s.reason ? `\n\n## 理由\n${s.reason}` : ''}`
|
|
233
|
+
: String(s.body ?? '')),
|
|
234
|
+
'```',
|
|
235
|
+
'',
|
|
236
|
+
]
|
|
237
|
+
return lines.join('\n')
|
|
238
|
+
}
|
|
@@ -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/mirror/mcp.js
CHANGED
|
@@ -19,6 +19,7 @@ import { buildStats, queryTermsOf, scoreDoc, termFreq, tokenize } from '../memor
|
|
|
19
19
|
import { stripFrontmatterBlock } from '../memory/frontmatter.js'
|
|
20
20
|
import { warnLog, writeFileAtomic } from '../memory/util.js'
|
|
21
21
|
import { MIRROR_MCP_NAME, isMirrorReadableName } from './policy.js'
|
|
22
|
+
import { validateSubmission } from '../intake/policy.js'
|
|
22
23
|
import { currentVersion } from '../update.js'
|
|
23
24
|
|
|
24
25
|
/** 认识且愿意应答的协议版本(按新到旧)。客户端报别的 → 回落最新一个。 */
|
|
@@ -59,13 +60,40 @@ const TOOL_DEFS = Object.freeze([
|
|
|
59
60
|
description: '列出副本里全部可读条目(名字 + 一句话 + 类型 + 标签)。只读。',
|
|
60
61
|
inputSchema: { type: 'object', properties: {} },
|
|
61
62
|
},
|
|
63
|
+
{
|
|
64
|
+
// 2.26.0:写侧的唯一入口 —— 它不写记忆库,只把提交放进归并队列。
|
|
65
|
+
name: 'memory_submit',
|
|
66
|
+
description: '向用户提交一条记忆(进入归并队列,由用户逐条批准后才可能进主库;不会直接写入记忆库)。kind=new 提交一条完整的新记忆(只接受 type=project/reference);kind=patch 提交对现有条目的修改建议(永不自动写入)。格式见 initialize 的 instructions。',
|
|
67
|
+
inputSchema: {
|
|
68
|
+
type: 'object',
|
|
69
|
+
properties: {
|
|
70
|
+
kind: { type: 'string', enum: ['new', 'patch'], description: 'new = 新记忆;patch = 对现有条目的修改建议' },
|
|
71
|
+
source: { type: 'string', description: '你的名字,小写字母 / 数字 / 连字符,如 claude-code' },
|
|
72
|
+
name: { type: 'string', description: 'new:文件名(不带 .md,必须以 project_ 或 reference_ 开头);patch:目标条目的名字' },
|
|
73
|
+
description: { type: 'string', description: 'new 必填:一句话说明这条记忆是什么' },
|
|
74
|
+
type: { type: 'string', enum: ['project', 'reference'], description: 'new 必填:只接受 project / reference' },
|
|
75
|
+
tags: { type: 'array', items: { type: 'string' }, description: 'new 可选:最多 8 个标签' },
|
|
76
|
+
body: { type: 'string', description: 'new 必填:正文 markdown(不要自带 frontmatter)' },
|
|
77
|
+
changes: { type: 'string', description: 'patch 必填:要改的地方(引用原文片段)' },
|
|
78
|
+
suggested: { type: 'string', description: 'patch 必填:建议改成什么' },
|
|
79
|
+
reason: { type: 'string', description: 'patch 可选:为什么' },
|
|
80
|
+
},
|
|
81
|
+
required: ['kind', 'source', 'name'],
|
|
82
|
+
},
|
|
83
|
+
},
|
|
62
84
|
])
|
|
63
85
|
|
|
64
86
|
const INSTRUCTIONS = [
|
|
65
|
-
'
|
|
66
|
-
'可用工具:memory_list(有哪些)/ memory_search(按关键词找)/ memory_read
|
|
87
|
+
'这是一个记忆库端点:默认只能**读**(读的是主记忆库按白名单导出的副本)。',
|
|
88
|
+
'可用工具:memory_list(有哪些)/ memory_search(按关键词找)/ memory_read(读全文)/ memory_submit(提交一条记忆或修改建议)。',
|
|
67
89
|
'引用某条记忆时请带上它的 name(如 project_xxx.md),不要假设文件路径 —— 这里不提供路径。',
|
|
68
|
-
'
|
|
90
|
+
'',
|
|
91
|
+
'## memory_submit 的格式',
|
|
92
|
+
'- 提交**不会**直接写入用户的记忆库:它进入归并队列,由用户逐条批准。',
|
|
93
|
+
'- kind=new:必填 source / name / description / type / body;type 只能是 project 或 reference,且 name 要以对应的 project_ / reference_ 开头。正文不要自带 frontmatter。',
|
|
94
|
+
'- kind=patch:必填 source / name / changes / suggested;name 是**现有条目**的名字(不带 .md)。patch 永远不会自动写入,用户只会看到一份建议。',
|
|
95
|
+
'- 体积上限:正文 32 KB,整条 64 KB。格式不对会被当场拒绝(isError 里写明原因)。',
|
|
96
|
+
'- source 是你的**声明**(如 claude-code),不是凭证。',
|
|
69
97
|
].join('\n')
|
|
70
98
|
|
|
71
99
|
/** 正文 → 片段:去掉 frontmatter、压平空白、截断。 */
|
|
@@ -90,7 +118,7 @@ function textResult(value) {
|
|
|
90
118
|
* @param {object} opts.ctx — 宿主上下文(只为 `warnLog`)
|
|
91
119
|
* @param {object} opts.exporter — `createMirrorExporter()` 的产物(只读面)
|
|
92
120
|
*/
|
|
93
|
-
export function createMirrorMcpServer({ ctx, exporter }) {
|
|
121
|
+
export function createMirrorMcpServer({ ctx, exporter, intake }) {
|
|
94
122
|
let server = null
|
|
95
123
|
let listening = false
|
|
96
124
|
let boundPort = 0
|
|
@@ -110,7 +138,9 @@ export function createMirrorMcpServer({ ctx, exporter }) {
|
|
|
110
138
|
url: url(),
|
|
111
139
|
transport: 'http',
|
|
112
140
|
tools: TOOL_DEFS.map((t) => t.name),
|
|
141
|
+
// 对**记忆库**只读;提交只进归并队列,不写主库(2.26.0)。
|
|
113
142
|
readOnly: true,
|
|
143
|
+
acceptsSubmissions: true,
|
|
114
144
|
generatedAt: new Date().toISOString(),
|
|
115
145
|
}
|
|
116
146
|
try {
|
|
@@ -176,8 +206,25 @@ export function createMirrorMcpServer({ ctx, exporter }) {
|
|
|
176
206
|
})
|
|
177
207
|
}
|
|
178
208
|
|
|
179
|
-
/**
|
|
180
|
-
|
|
209
|
+
/**
|
|
210
|
+
* 提交一条记忆(2.26.0)。**全端点唯一的写入口**,而且它只写 intake/ —— 主库要人批准。
|
|
211
|
+
*
|
|
212
|
+
* 两道闸:开关(用户是否允许接收)+ 校验(格式不对当场拒,连 pending 都进不去)。
|
|
213
|
+
*/
|
|
214
|
+
async function toolSubmit(args) {
|
|
215
|
+
if (!intake || !intake.store) return toolError('这个端点没有开启接收提交')
|
|
216
|
+
if (!intake.acceptSubmissions()) {
|
|
217
|
+
return toolError('用户没有打开「接收外来提交」(external.acceptSubmissions=0)。请把这条内容直接告诉用户,或请他们开启后再提交。')
|
|
218
|
+
}
|
|
219
|
+
const check = validateSubmission(args)
|
|
220
|
+
if (!check.ok) return toolError(`提交被拒:${check.error}`)
|
|
221
|
+
const saved = await intake.store.save(check.submission)
|
|
222
|
+
if (!saved.ok) return toolError(`提交没落盘:${saved.error}`)
|
|
223
|
+
return textResult({ ok: true, id: saved.id, status: 'pending', note: '已进入归并队列,等待用户批准;不会直接写入记忆库' })
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** 工具名 → 实现。读的三个 + 一个只写 intake 的提交口。 */
|
|
227
|
+
const TOOLS = Object.freeze({ memory_search: toolSearch, memory_read: toolRead, memory_list: toolList, memory_submit: toolSubmit })
|
|
181
228
|
|
|
182
229
|
// ── JSON-RPC 分派 ──────────────────────────────────────────────────
|
|
183
230
|
|
package/lib/mirror/policy.js
CHANGED
|
@@ -34,6 +34,8 @@ export const MIRROR_DEBOUNCE_MS = 10_000
|
|
|
34
34
|
*/
|
|
35
35
|
export const MIRROR_SPECS = Object.freeze({
|
|
36
36
|
enabled: { env: 'SAGE_MEM_EXTERNAL', dflt: 0, lo: 0, hi: 1 },
|
|
37
|
+
// 2.26.0:收不收外来提交。与 nabled 是两件事 —— 「能不能读副本」不等于「能不能往里塞东西」。
|
|
38
|
+
acceptSubmissions: { env: 'SAGE_MEM_EXTERNAL_SUBMIT', dflt: 0, lo: 0, hi: 1 },
|
|
37
39
|
port: { env: 'SAGE_MEM_EXTERNAL_PORT', dflt: 7461, lo: 1024, hi: 65535 },
|
|
38
40
|
pollSeconds: { env: 'SAGE_MEM_EXTERNAL_POLL', dflt: 45, lo: 15, hi: 600 },
|
|
39
41
|
})
|
|
@@ -53,6 +55,7 @@ export const DEFAULT_PREFIXES = Object.freeze(['project_', 'reference_'])
|
|
|
53
55
|
*/
|
|
54
56
|
export const DEFAULT_EXTERNAL = Object.freeze({
|
|
55
57
|
enabled: MIRROR_SPECS.enabled.dflt,
|
|
58
|
+
acceptSubmissions: MIRROR_SPECS.acceptSubmissions.dflt,
|
|
56
59
|
prefixes: DEFAULT_PREFIXES,
|
|
57
60
|
tags: [],
|
|
58
61
|
include: [],
|
|
@@ -108,10 +111,18 @@ function normalizeList(value, kind) {
|
|
|
108
111
|
return { list: out, dropped }
|
|
109
112
|
}
|
|
110
113
|
|
|
111
|
-
/**
|
|
114
|
+
/**
|
|
115
|
+
* 0/1 型开关的两个键:`enabled`(读侧端点)与 `acceptSubmissions`(收不收外来提交)。
|
|
116
|
+
* 归一与严格校验都走同一套 —— 两个开关的语义不同,但**取值范围与笔误形态完全一样**。
|
|
117
|
+
*/
|
|
118
|
+
const FLAG_KEYS = new Set(['enabled', 'acceptSubmissions'])
|
|
119
|
+
|
|
120
|
+
/** 开关收数字或布尔(手改 JSON 时写成 `true` 是常见笔误,不该让整份设置失效)。 */
|
|
112
121
|
function normalizeEnabled(raw) {
|
|
113
122
|
if (typeof raw === 'boolean') return raw ? 1 : 0
|
|
114
|
-
|
|
123
|
+
// 两个开关的取值范围都是 {0, 1};这里不借用任何一个 key 的 spec,免得日后某个开关改了边界
|
|
124
|
+
// 把另一个开关的语义悄悄带走。
|
|
125
|
+
return parseLimitValue(raw, { lo: 0, hi: 1 })
|
|
115
126
|
}
|
|
116
127
|
|
|
117
128
|
/**
|
|
@@ -131,10 +142,10 @@ export function resolveExternal(saved, env = process.env) {
|
|
|
131
142
|
const external = { ...DEFAULT_EXTERNAL, prefixes: [...DEFAULT_PREFIXES], tags: [], include: [], exclude: [] }
|
|
132
143
|
|
|
133
144
|
// ── 三个整数项 ─────────────────────────────────────────────────────
|
|
134
|
-
for (const key of ['enabled', 'port', 'pollSeconds']) {
|
|
145
|
+
for (const key of ['enabled', 'acceptSubmissions', 'port', 'pollSeconds']) {
|
|
135
146
|
const spec = MIRROR_SPECS[key]
|
|
136
147
|
if (savedObj !== null && Object.prototype.hasOwnProperty.call(savedObj, key)) {
|
|
137
|
-
const value = key
|
|
148
|
+
const value = FLAG_KEYS.has(key) ? normalizeEnabled(savedObj[key]) : parseLimitValue(savedObj[key], spec)
|
|
138
149
|
if (value !== undefined) {
|
|
139
150
|
external[key] = value
|
|
140
151
|
// 手写成 `true` / `"1"` 是合法的(归一成功),但写成 `" 1 "` 这种「看着像、其实被收敛过」
|
|
@@ -146,7 +157,7 @@ export function resolveExternal(saved, env = process.env) {
|
|
|
146
157
|
}
|
|
147
158
|
diagnostics.push(`settings.json 的 external.${key}=${JSON.stringify(savedObj[key])} 不是有效数字,已回落环境变量/默认值`)
|
|
148
159
|
}
|
|
149
|
-
const envValue = key
|
|
160
|
+
const envValue = FLAG_KEYS.has(key) ? normalizeEnabled(env?.[spec.env]) : parseLimitValue(env?.[spec.env], spec)
|
|
150
161
|
external[key] = envValue === undefined ? spec.dflt : envValue
|
|
151
162
|
}
|
|
152
163
|
|
|
@@ -179,7 +190,7 @@ export function parseExternalPatch(external) {
|
|
|
179
190
|
}
|
|
180
191
|
const patch = {}
|
|
181
192
|
for (const [key, value] of Object.entries(external)) {
|
|
182
|
-
if (key
|
|
193
|
+
if (FLAG_KEYS.has(key)) {
|
|
183
194
|
// ⚠️ 这里**不用** `parseLimitValue`:那条路的语义是「越界收敛到边界」,
|
|
184
195
|
// 而补丁的语义是「笔误就报错」。用前者会让 `enabled: 2` 静默变成 1。
|
|
185
196
|
if (value === true || value === 1) { patch.enabled = 1; continue }
|