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/lib/index.js CHANGED
@@ -26,9 +26,9 @@ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
26
26
  import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises'
27
27
  import { join } from 'node:path'
28
28
  import { checkUpdate as checkUpdateImpl } from './update.js'
29
- import { applySettingsPatch, autodreamConfigSnapshot, clampInt, MAX_RAW_BYTES, parseExperimentalPatch, parseUiPatch, pendingExperimental, pendingUi, rawName, readReservedFile, readSettingsFileDetailed, readSettingsSnapshot, RESERVED_FILE, SETTINGS_FILE } from './settings.js'
29
+ import { applySettingsPatch, autodreamConfigSnapshot, MAX_RAW_BYTES, parseExperimentalPatch, parseUiPatch, pendingExperimental, pendingUi, rawName, readExternalSettings, readReservedFile, readSettingsFileDetailed, readSettingsSnapshot, RESERVED_FILE, SETTINGS_FILE } from './settings.js'
30
30
  import { createRecallInjector, createSessionInjectState, readRecallDebug } from './recall/index.js'
31
- import { mountAutodream, mountMemoryTools, mountObserve, mountPreCompact, mountWriteGate } from './assembly/index.js'
31
+ import { mountAutodream, mountMemoryTools, mountMirror, mountObserve, mountPreCompact, mountWriteGate } from './assembly/index.js'
32
32
 
33
33
  /**
34
34
  * 读方法的拒绝:**抛**一个带 `.code` 的 Error(写方法返回 `{ok:false, code}` 回执,见 prepareWrite)。
@@ -83,6 +83,12 @@ export class MemoryGateway extends TypertRemoteService {
83
83
  // 2.17.0:压缩前提醒(实验性,默认关;关着时每步只是一次开关读取)。
84
84
  mountPreCompact(ctx, { memoryDir: MEMORY_DIR })
85
85
 
86
+ // 2.25.0:外部访问读侧(白名单导出 + 只读 MCP)。默认关,关着时一行都不跑。
87
+ // `readExternal` 给的是**现读**设置(不进 restartRequired):开关改完立刻起停。
88
+ this.mirror = mountMirror(ctx, { memoryDir: MEMORY_DIR, stateRoot: STATE_ROOT, readExternal: readExternalSettings })
89
+ this.mirror.refresh().catch(() => {})
90
+ if (typeof ctx.effect === 'function') ctx.effect(() => () => this.mirror.dispose())
91
+
86
92
  // 会话级注入状态:一处持有、一处提交(见 lib/recall/state.js 的头注)。
87
93
  const injectState = createSessionInjectState()
88
94
 
@@ -507,9 +513,42 @@ export class MemoryGateway extends TypertRemoteService {
507
513
 
508
514
  /**
509
515
  * 改设置:先全验、后一起写,任何一个非法就整份不落盘。实现在 `lib/settings.js`。
516
+ *
517
+ * 2.25.0:补丁里有 `external`(或任何补丁)成功落盘后,让外部访问挂载层重读一次 ——
518
+ * 开关 / 白名单 / 端口都是**现读现用**的,点完保存就该生效,不该等人重启。
510
519
  */
511
520
  async setSettings(patch) {
512
- return applySettingsPatch(this.ctx, patch)
521
+ const result = await applySettingsPatch(this.ctx, patch)
522
+ if (result?.ok && this.mirror) {
523
+ // 失败不影响保存结果(设置已经落盘了):状态在 externalStatus 里如实显示。
524
+ await this.mirror.refresh().catch(() => {})
525
+ }
526
+ return result
527
+ }
528
+
529
+ /**
530
+ * 外部访问(2.25.0 读侧)的**运行状态**:开关、当前暴露条目数、最近一轮导出的时间与错误、
531
+ * 端点是否在听。设置本身在 `getSettings().external`,这里只答「现在跑成什么样」。
532
+ *
533
+ * 不需要入参 —— 面板拿到就显示,改设置走 `setSettings({ external })`。
534
+ */
535
+ async externalStatus() {
536
+ return this.mirror.status()
537
+ }
538
+
539
+ /** 外部来件(2.26.0):待处理提交 + 每条现算的提案 + 最近报告。只读。 */
540
+ async externalSubmissions() {
541
+ return this.mirror.intake.merger.overview()
542
+ }
543
+
544
+ /** 批准一条 `new`:排他写主库 + 补索引。`conflict` / `manual` / `patch` 一律不写,回原因。 */
545
+ async intakeApprove(id) {
546
+ return this.mirror.intake.merger.approve(id)
547
+ }
548
+
549
+ /** 拒绝一条:原件留档 `rejected/`(不删),理由进报告与审计。 */
550
+ async intakeReject(id, reason) {
551
+ return this.mirror.intake.merger.reject(id, reason)
513
552
  }
514
553
 
515
554
  /**
@@ -580,6 +619,12 @@ markRemote(MemoryGateway, 'setLocked', 'setLocked')
580
619
  markRemote(MemoryGateway, 'archiveCandidates', 'archiveCandidates')
581
620
  markRemote(MemoryGateway, 'getSettings', 'getSettings')
582
621
  markRemote(MemoryGateway, 'setSettings', 'setSettings')
622
+ // 2.25.0:外部访问读侧的运行状态(第 41 条)。只读、无入参 —— 面板不看账,只看出没出问题。
623
+ markRemote(MemoryGateway, 'externalStatus', 'externalStatus')
624
+ // 2.26.0:写侧三条 —— 来件总览 / 批准 / 拒绝。批准是唯一能把外来内容写进主库的入口。
625
+ markRemote(MemoryGateway, 'externalSubmissions', 'externalSubmissions')
626
+ markRemote(MemoryGateway, 'intakeApprove', 'intakeApprove')
627
+ markRemote(MemoryGateway, 'intakeReject', 'intakeReject')
583
628
  markRemote(MemoryGateway, 'readRaw', 'readRaw')
584
629
  markRemote(MemoryGateway, 'writeRaw', 'writeRaw')
585
630
  // 1.7.0:注入调试账(只读;开关关着时返回 { enabled: false, records: [] })
@@ -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
+ }