sage-mem 2.25.0 → 2.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,193 @@
1
+ /**
2
+ * intake 层 —— **批准之后**唯一能写主库的地方。
3
+ *
4
+ * 四条纪律:
5
+ * 1. **只有 `create` 能落库**。`patch` 永远不自动写(半成品直接写会毁目标文件),
6
+ * 它只产出一份「建议」,由人复制过去。
7
+ * 2. **排他创建**:写入用 `writeFileExclusive`。写之前查一次主库、写完再看一眼冲突 ——
8
+ * 两步之间被人抢先建了同名文件时报冲突、不覆盖。
9
+ * 3. **判据不在本文件**:合不合法在 `policy.validateSubmission`,该走哪条处置在
10
+ * `policy.proposeFor`。这里只负责「照着提案动手」。
11
+ * 4. **没有第二套写入协议**:落库走既有的 `writeFileExclusive` 与 `ensureIndexEntry`,
12
+ * 不绕过版本守卫,也不另写一份索引逻辑。
13
+ */
14
+ import { readFile } from 'node:fs/promises'
15
+ import { join } from 'node:path'
16
+ import { parseFrontmatter, stripFrontmatterBlock } from '../memory/frontmatter.js'
17
+ import { frontmatterField } from '../memory/frontmatter.js'
18
+ import { ensureIndexEntry } from '../memory/index-file.js'
19
+ import { RESERVED_FILES } from '../memory/config.js'
20
+ import { scanMemoryDirDetailed } from '../memory/scan.js'
21
+ import { warnLog, writeFileExclusive } from '../memory/util.js'
22
+ import { proposeFor } from './policy.js'
23
+
24
+ /** 从落盘的提交 markdown 里还原出「批准时要写什么」。 */
25
+ function payloadOf(raw) {
26
+ const meta = parseFrontmatter(raw)
27
+ return {
28
+ name: meta.name || frontmatterField(raw, 'name'),
29
+ description: meta.description || '',
30
+ type: meta.type || '',
31
+ tags: meta.tags || [],
32
+ body: stripFrontmatterBlock(raw),
33
+ source: frontmatterField(raw, 'source'),
34
+ submittedAt: frontmatterField(raw, 'submitted_at'),
35
+ }
36
+ }
37
+
38
+ /** 生成写进主库的正文:干净 frontmatter + 原正文(外来那层的 `kind` 等字段不搬进来)。 */
39
+ function renderMemoryFile(payload, atISO) {
40
+ const lines = ['---', `name: ${payload.name}`, `description: ${JSON.stringify(payload.description)}`, `type: ${payload.type}`]
41
+ if (payload.tags.length) lines.push(`tags: [${payload.tags.join(', ')}]`)
42
+ lines.push(`source: ${payload.source || 'external'}`)
43
+ lines.push(`imported_at: ${atISO}`)
44
+ lines.push(`updated: ${String(payload.submittedAt || atISO).slice(0, 10)}`, '---', '')
45
+ lines.push(String(payload.body).replace(/^\s+/, '').replace(/\s+$/, ''))
46
+ lines.push('')
47
+ return lines.join('\n')
48
+ }
49
+
50
+ /** 一段正文用于列表预览(压平空白、截断)。 */
51
+ function excerptOf(text, max = 200) {
52
+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim()
53
+ return flat.length > max ? `${flat.slice(0, max)}…` : flat
54
+ }
55
+
56
+ /**
57
+ * @param {object} opts
58
+ * @param {object} opts.ctx — 宿主上下文(`warnLog` 用)
59
+ * @param {string} opts.memoryDir — 主库目录(**本文件唯一写它的地方**)
60
+ * @param {object} opts.store — `createIntakeStore()` 的产物
61
+ */
62
+ export function createIntakeMerger({ ctx, memoryDir, store }) {
63
+ /** 主库现有文件名(一次扫描,供提案与冲突判定共用)。 */
64
+ async function existingNames() {
65
+ const scanned = await scanMemoryDirDetailed(ctx, '', memoryDir)
66
+ if (scanned.complete === false) return { ok: false, names: [], error: '主库目录读不出来,本轮不判冲突' }
67
+ // 目录不存在也不能当「空库」放行:写进去会失败,而且「盘掉线」与「新装」在这里长得一样。
68
+ if (scanned.missing === true) return { ok: false, names: [], error: '主库目录不存在,本轮不判冲突(也不落库)' }
69
+ return { ok: true, names: scanned.files.map((f) => f.file), error: '' }
70
+ }
71
+
72
+ /**
73
+ * 面板要的一份总览:待处理条目 + 每条的提案 + 最近报告。
74
+ * 提案**每次现算**(不落盘):主库随时可能变,缓存提案等于让面板说旧话。
75
+ */
76
+ async function overview({ reportLimit = 5 } = {}) {
77
+ const [items, scan, reports] = await Promise.all([store.listPending(), existingNames(), store.listReports(reportLimit)])
78
+ const out = items.map((item) => {
79
+ const kind = frontmatterField(item.raw, 'kind') || 'new'
80
+ const body = stripFrontmatterBlock(item.raw)
81
+ const proposal = proposeFor(
82
+ kind === 'patch'
83
+ ? { kind: 'patch', name: item.name }
84
+ : { kind: 'new', name: item.name },
85
+ scan.names,
86
+ )
87
+ return {
88
+ id: item.id,
89
+ source: item.source,
90
+ kind,
91
+ name: item.name || '',
92
+ description: item.description || '',
93
+ type: item.type || '',
94
+ submittedAt: item.submittedAt || '',
95
+ action: proposal.action,
96
+ targetFile: proposal.targetFile,
97
+ reason: proposal.reason,
98
+ // 列表只给预览;完整原文在报告里、也在 pending 文件里。
99
+ excerpt: excerptOf(kind === 'patch' ? body.replace(/^## +要改的地方/m, '') : body),
100
+ // patch 的「建议改成」单独给一份:面板上的「复制建议」要的就是这一段(
101
+ // 复制整份 patch 过去反而要人再删两段)。
102
+ suggestion: kind === 'patch' ? String(body.split(/## +建议改成/)[1] ?? '').split(/## +理由/)[0].trim().slice(0, 4000) : '',
103
+ }
104
+ })
105
+ return {
106
+ pending: out.length,
107
+ items: out,
108
+ scanError: scan.ok ? '' : scan.error,
109
+ reports: reports.map((r) => ({ name: r.name, text: r.text.slice(0, 2000) })),
110
+ }
111
+ }
112
+
113
+ /**
114
+ * 批准一条 `new` 提交:落进主库 + 补索引 + 记账 + 写报告。
115
+ *
116
+ * 失败一律**不删 pending**(人可以再试或改成拒绝),也不留半份文件:
117
+ * 记忆写入与索引补齐是两步,索引失败只告警(记忆已在盘上,索引是可选件)。
118
+ *
119
+ * @param {string} id
120
+ * @returns {Promise<{ok:boolean, action?:string, targetFile?:string, error?:string, report?:string}>}
121
+ */
122
+ async function approve(id) {
123
+ const item = await store.findPending(id)
124
+ if (!item) return { ok: false, error: '找不到这条待处理提交(可能已被处理)' }
125
+ if (await store.isProcessed(item.id)) return { ok: false, error: '这条提交已经处理过了' }
126
+
127
+ const raw = await readFile(join(store.intakeDir, 'agents', item.agentId, 'pending', `${item.id}.md`), 'utf8').catch(() => null)
128
+ if (raw === null) return { ok: false, error: '读不到提交正文(文件可能已被移走)' }
129
+ // patch **永远不自动写**:它不是一份成品,直接落盘会毁掉目标文件。这里先拦,不靠面板禁用按钮。
130
+ if ((frontmatterField(raw, 'kind') || 'new') === 'patch') {
131
+ return { ok: false, action: 'manual', error: '这是修改建议(patch):插件不会自动写主库,请在面板里复制建议后手工并入' }
132
+ }
133
+ const payload = payloadOf(raw)
134
+ const scan = await existingNames()
135
+ if (!scan.ok) return { ok: false, error: scan.error }
136
+ const proposal = proposeFor({ kind: 'new', name: payload.name }, scan.names)
137
+ if (proposal.action !== 'create') {
138
+ return { ok: false, action: proposal.action, targetFile: proposal.targetFile, error: proposal.reason }
139
+ }
140
+ // 用户声明的保护名(`reserved.json`)在真落盘前再兜一道:policy 只认识两个内置名。
141
+ if (RESERVED_FILES.has(String(proposal.targetFile).toLowerCase())) {
142
+ return { ok: false, action: 'reject', targetFile: proposal.targetFile, error: '目标是保留名(索引 / 流水 / 用户声明的保护名),不接受外来写入' }
143
+ }
144
+
145
+ const at = Date.now()
146
+ const atISO = new Date(at).toISOString()
147
+ try {
148
+ await writeFileExclusive(join(memoryDir, proposal.targetFile), renderMemoryFile(payload, atISO))
149
+ } catch (err) {
150
+ if (err?.code === 'EEXIST') {
151
+ return { ok: false, action: 'conflict', targetFile: proposal.targetFile, error: '目标文件已经存在(两次检查之间新建的),未覆盖' }
152
+ }
153
+ return { ok: false, error: `写主库失败(${err?.code ?? err?.message ?? err})` }
154
+ }
155
+ const indexed = await ensureIndexEntry(memoryDir, proposal.targetFile).catch((err) => {
156
+ warnLog(ctx, `外来提交:补索引失败(${err?.message ?? err})`)
157
+ return { ok: false }
158
+ })
159
+ if (indexed && indexed.ok === false) warnLog(ctx, `外来提交:补索引失败(${indexed.error})`)
160
+
161
+ await store.consume(item.id)
162
+ await store.markProcessed(item.id, { action: 'approve', target: proposal.targetFile, note: payload.source })
163
+ const report = await store.writeReport({
164
+ submission: { kind: 'new', name: payload.name, source: payload.source, body: payload.body },
165
+ proposal,
166
+ result: `已写入主库:${proposal.targetFile}(索引 ${indexed && indexed.added ? '已补' : '未变或无索引'})`,
167
+ id: item.id,
168
+ at,
169
+ })
170
+ await store.audit({ at, source: payload.source, action: 'approve', target: proposal.targetFile, result: 'written' })
171
+ return { ok: true, action: 'create', targetFile: proposal.targetFile, report }
172
+ }
173
+
174
+ /** 拒绝一条提交(原件留档在 `rejected/`,不删)。 */
175
+ async function reject(id, reason = '') {
176
+ const item = await store.findPending(id)
177
+ if (!item) return { ok: false, error: '找不到这条待处理提交(可能已被处理)' }
178
+ const kind = frontmatterField(item.raw, 'kind') || 'new'
179
+ const scan = await existingNames()
180
+ const proposal = proposeFor({ kind, name: item.name }, scan.names)
181
+ const result = await store.reject(item.id, reason)
182
+ if (!result.ok) return result
183
+ await store.writeReport({
184
+ submission: { kind, name: item.name, source: item.source, body: stripFrontmatterBlock(item.raw) },
185
+ proposal,
186
+ result: `已拒绝${reason ? `:${reason}` : ''}`,
187
+ id: item.id,
188
+ })
189
+ return { ok: true, id: item.id }
190
+ }
191
+
192
+ return { overview, approve, reject, existingNames }
193
+ }
@@ -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
+ }