feat(raw): add optional original-record layer as the sixth sub-plugin

Captures real user/assistant messages into per-session JSONL files under
\/brain/raw, separate from Mnemon's store. Adds memory_raw_search /
memory_raw_read / memory_raw_status, the Brain panel raw tab, the
dsh-brain-raw row in the bundle patch, and verify-raw-entry/verify-raw-memory.
This commit is contained in:
newbie 2026-11-27 17:13:28 +08:00
parent 7a4ad249fc
commit b889897dae
15 changed files with 1274 additions and 10 deletions

View File

@ -31,14 +31,16 @@
(脱敏、截断后)发送到独立的 summary 端点用于生成摘要——不开启该功能就
没有正文上传。令牌永不随页面回显原文,只回掩码。
## 五个子插件
## 六个子插件
0.10.1 起 `dsh-brain` 以一个包提供五个子插件行,可在宿主
0.10.1 起 `dsh-brain` 以一个包提供五个子插件行,0.10.3 起增加可选的
`dsh-brain-raw`(原始记录层),共六个,可在宿主
「设置 → 插件」页逐行开关(HMR 生效、重启保持):
| 子插件 | 提供什么 |
| --- | --- |
| `dsh-brain-cloudsync` | 连接与上报:登录/测试/补发/技能同步路由、重试定时器、同步定时器。 |
| `dsh-brain-raw` | 可选原始记录层:把 user/assistant 原话按会话追加到 `$DSH_HOME/brain/raw/`,提供 `memory_raw_search` / `memory_raw_read` / `memory_raw_status`。 |
| `dsh-brain-memory` | 五个 `memory_*` 工具注册。 |
| `dsh-brain-skills` | 技能管理页、`skill_list` 工具、技能市场、来源树。 |
| `dsh-brain-mcp` | MCP 管理页开关(页签与宿主桥接能力声明;MCP 连接本身由宿主 `dsh-mcp-connector` 管理,本插件不做 MCP 云同步)。 |
@ -135,6 +137,34 @@ memory 令牌时才切换为云端适配器。自动总结只保存用户明确
包名 `dsh-brain-mnemon`)。详见 `docs/LOCAL_MEMORY_IMPLEMENTATION.md` 与
`docs/MNEMON_FORK.md`;验收对照见 `docs/LOCAL_MEMORY_ACCEPTANCE.md`。
## 原始记录层(dsh-brain-raw)
`dsh-brain-raw` 是独立可选子插件,用来保存“原话”而不是摘要:监听宿主
`session/event`,把真实的 user / assistant 消息追加到
`$DSH_HOME/brain/raw/` 下的 JSONL 文件(每个会话一个文件,超过
`rawMaxBytesPerSession` 自动轮转),不写入 Mnemon 的 `mnemon.db`,也不
影响现有记忆条目。
默认配置(bundle patch 的 `dsh-brain-raw` 行):
```yaml
- id: dsh-brain-raw
name: dsh-brain/raw
config:
rawEnabled: true
rawCaptureAssistant: true
rawRetentionDays: 90
```
可用工具:
- `memory_raw_search`:按关键词搜索原话,返回会话 id、事件 seq、角色和片段;
- `memory_raw_read`:按 `session_id` + `seq` 读某一条原话,或按 `offset/limit` 浏览;
- `memory_raw_status`:查看保存目录、会话数、记录数、占用空间和保留天数。
原始记录只保存在本地,不参与云端同步;写入前会经过现有的密钥脱敏规则,
默认保留 90 天。停用 `dsh-brain-raw` 行即停止采集。
## Mnemon 集成(记忆空间 Provider)
本包同时保留 Mnemon 记忆空间 Provider 适配:Mnemon 管本地在场(运行时记忆

View File

@ -1,4 +1,4 @@
# dsh-brain bundle patch — five toggleable sub-plugins.
# dsh-brain bundle patch — six toggleable sub-plugins.
#
# Local-only build: this package is never published, so these rows are the
# only way the plugin reaches the desktop profile tree. The host Loader
@ -17,7 +17,7 @@
# top-level `- id: <row>` rows only.
#
# The compat root export (`.`) stays for older single-row profiles: it
# applies all five entries at once.
# applies all six entries at once.
- insert:
- id: dsh-brain-cloudsync
name: dsh-brain/cloudsync
@ -28,6 +28,12 @@
skillsSyncEnabled: true
- id: dsh-brain-memory
name: dsh-brain/memory
- id: dsh-brain-raw
name: dsh-brain/raw
config:
rawEnabled: true
rawCaptureAssistant: true
rawRetentionDays: 90
- id: dsh-brain-skills
name: dsh-brain/skills
- id: dsh-brain-mcp

View File

@ -13,6 +13,7 @@
"./skills": "./lib/entries/skills.js",
"./mcp": "./lib/entries/mcp.js",
"./ui": "./lib/entries/ui.js",
"./raw": "./lib/entries/raw.js",
"./settings-ui": "./lib/entries/ui.js",
"./cordis.patch.yml": "./cordis.patch.yml",
"./package.json": "./package.json",

View File

@ -2,6 +2,7 @@
import * as React from 'react'
import { Overview } from './Overview'
import { MemoryTab } from './MemoryTab'
import { RawTab } from './RawTab'
import { DepartmentTab } from './DepartmentTab'
import styles from './BrainPanel.module.css'
@ -10,6 +11,7 @@ const h = React.createElement
const TABS = [
{ id: 'overview', label: '概览' },
{ id: 'memory', label: '记忆' },
{ id: 'raw', label: '原始记录' },
{ id: 'departments', label: '部门' },
] as const
@ -18,6 +20,7 @@ export function BrainPanel(): any {
let content: any
if (tab === 'overview') content = h(Overview)
else if (tab === 'memory') content = h(MemoryTab, { scope: 'global' })
else if (tab === 'raw') content = h(RawTab, {})
else content = h(DepartmentTab, { scope: 'global' })
return h('div', { className: styles.nativeWorkspace, 'data-dsh-plugin': 'dsh-brain', 'data-dsh-part': 'brain-panel' },
h('div', { className: styles.windowDragBand, 'data-window-drag': true, 'aria-hidden': 'true' }),
@ -25,7 +28,7 @@ export function BrainPanel(): any {
h('div', { className: styles.header },
h('div', { className: styles.titleBlock },
h('h3', { className: styles.title }, 'Brain'),
h('p', { className: styles.subtitle }, '全局记忆、部门与运行状态'),
h('p', { className: styles.subtitle }, '全局记忆、原始记录、部门与运行状态'),
),
),
h('div', { className: styles.tabBar, role: 'tablist', 'aria-label': 'Brain 面板页签' },

277
src-client/panel/RawTab.tsx Normal file
View File

@ -0,0 +1,277 @@
// Raw records tab: search original messages and browse captured sessions.
import * as React from 'react'
import { request, messageOf } from '../api'
import { formatBytes, formatTime } from '../format'
import { Banner, Btn, Pill } from '../components'
import { useApi } from './useApi'
const h = React.createElement
const ROLE_USER = 'user'
const ROLE_ASSISTANT = 'assistant'
function roleLabel(role: string): string {
return role === ROLE_USER ? '你' : role === ROLE_ASSISTANT ? '助手' : role
}
function shortId(value: unknown): string {
const text = String(value ?? '')
if (text.length <= 18) return text || '—'
return text.slice(0, 10) + '…' + text.slice(-5)
}
function when(value: unknown): string {
if (typeof value === 'number' && Number.isFinite(value)) return formatTime(value)
if (typeof value === 'string' && value !== '') {
const parsed = Date.parse(value)
return Number.isFinite(parsed) ? formatTime(parsed) : value
}
return '—'
}
function metric(label: string, value: unknown): any {
return h('div', { style: s.metric },
h('div', { style: s.metricLabel }, label),
h('div', { style: s.metricValue }, String(value ?? '—')),
)
}
const s: Record<string, any> = {
page: { display: 'flex', flexDirection: 'column', gap: '14px' },
hero: {
display: 'flex', gap: '18px', flexWrap: 'wrap', alignItems: 'stretch',
padding: '20px 22px', borderRadius: '18px',
border: '1px solid rgba(127,127,127,0.22)',
background: 'linear-gradient(135deg, rgba(99,102,241,0.14), rgba(139,92,246,0.06) 58%, transparent)',
},
heroText: { flex: '1 1 260px', minWidth: '240px', display: 'flex', flexDirection: 'column', gap: '5px' },
kicker: { fontSize: '10.5px', letterSpacing: '.16em', fontWeight: 700, color: '#6366f1', opacity: 0.9 },
heroTitle: { margin: 0, fontSize: '22px', lineHeight: 1.2, fontWeight: 720 },
heroSub: { margin: 0, fontSize: '12px', opacity: 0.62, lineHeight: 1.6, maxWidth: '540px' },
metrics: { display: 'grid', gridTemplateColumns: 'repeat(2, minmax(84px, 1fr))', gap: '8px', flex: '0 1 280px', minWidth: '220px' },
metric: { border: '1px solid rgba(127,127,127,0.18)', borderRadius: '12px', padding: '10px 12px', background: 'rgba(127,127,127,0.07)' },
metricLabel: { fontSize: '10.5px', letterSpacing: '.08em', opacity: 0.55, fontWeight: 600 },
metricValue: { fontSize: '19px', fontWeight: 720, fontVariantNumeric: 'tabular-nums', marginTop: '2px' },
toolbar: { display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'center' },
searchBox: { display: 'flex', alignItems: 'center', gap: '8px', flex: '1 1 320px', minWidth: '240px', border: '1px solid rgba(127,127,127,0.28)', borderRadius: '12px', padding: '3px 10px', background: 'rgba(127,127,127,0.05)' },
searchGlyph: { fontSize: '16px', opacity: 0.5, flex: '0 0 auto' },
searchInput: { font: 'inherit', fontSize: '13px', padding: '7px 2px', border: 'none', outline: 'none', background: 'transparent', color: 'inherit', width: '100%', minWidth: 0 },
chips: { display: 'flex', gap: '4px', padding: '2px', borderRadius: '9px', border: '1px solid rgba(127,127,127,0.18)' },
chip: { font: 'inherit', fontSize: '11.5px', padding: '5px 9px', borderRadius: '7px', border: '1px solid transparent', background: 'transparent', color: 'inherit', cursor: 'pointer' },
chipActive: { border: '1px solid rgba(99,102,241,0.45)', background: 'rgba(99,102,241,0.14)', fontWeight: 600 },
layout: { display: 'grid', gridTemplateColumns: 'minmax(240px, .78fr) minmax(0, 1.55fr)', gap: '12px', alignItems: 'start' },
card: { border: '1px solid rgba(127,127,127,0.22)', borderRadius: '16px', padding: '16px', minWidth: 0, display: 'flex', flexDirection: 'column', gap: '10px' },
cardHead: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: '8px', flexWrap: 'wrap' },
cardTitle: { margin: 0, fontSize: '13.5px', fontWeight: 650 },
hint: { margin: 0, fontSize: '11.5px', opacity: 0.58, lineHeight: 1.55 },
sessionList: { display: 'flex', flexDirection: 'column', gap: '6px', maxHeight: '620px', overflow: 'auto' },
session: { display: 'flex', flexDirection: 'column', gap: '5px', padding: '10px 11px', borderRadius: '11px', border: '1px solid rgba(127,127,127,0.14)', cursor: 'pointer', background: 'transparent' },
sessionActive: { border: '1px solid rgba(99,102,241,0.55)', background: 'rgba(99,102,241,0.10)' },
sessionTitle: { fontWeight: 600, fontSize: '12.5px', overflowWrap: 'anywhere' },
sessionMeta: { display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'baseline', fontSize: '11px', opacity: 0.6 },
sessionSnippet: { fontSize: '11.5px', opacity: 0.72, overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', lineHeight: 1.45 },
main: { display: 'flex', flexDirection: 'column', gap: '10px', minWidth: 0 },
resultList: { display: 'flex', flexDirection: 'column', gap: '6px' },
result: { display: 'flex', flexDirection: 'column', gap: '5px', padding: '10px 12px', borderRadius: '11px', border: '1px solid rgba(127,127,127,0.14)', cursor: 'pointer' },
resultHead: { display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'baseline' },
resultSnippet: { fontSize: '12px', lineHeight: 1.55, whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' },
messageList: { display: 'flex', flexDirection: 'column', gap: '9px' },
message: { display: 'flex', flexDirection: 'column', gap: '5px', padding: '10px 12px', borderRadius: '11px', border: '1px solid rgba(127,127,127,0.12)', borderLeft: '3px solid rgba(99,102,241,0.65)', background: 'rgba(127,127,127,0.035)' },
messageAssistant: { borderLeft: '3px solid rgba(16,185,129,0.7)' },
msgHead: { display: 'flex', gap: '9px', flexWrap: 'wrap', alignItems: 'baseline' },
role: { fontSize: '11px', fontWeight: 700, padding: '1px 7px', borderRadius: '999px', background: 'rgba(99,102,241,0.14)', color: 'inherit' },
roleAssistant: { background: 'rgba(16,185,129,0.14)' },
msgMeta: { fontSize: '10.5px', opacity: 0.52 },
msgText: { fontSize: '12.5px', lineHeight: 1.65, whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' },
empty: { border: '1px dashed rgba(127,127,127,0.3)', borderRadius: '14px', padding: '26px 20px', textAlign: 'center', color: 'inherit', opacity: 0.72, fontSize: '12.5px' },
selectedBar: { display: 'flex', alignItems: 'baseline', gap: '8px', flexWrap: 'wrap' },
}
export function RawTab(props: { active?: boolean }): any {
const active = props.active !== false
const [query, setQuery] = React.useState('')
const [role, setRole] = React.useState('')
const [searchResult, setSearchResult] = React.useState<any>(null)
const [searchError, setSearchError] = React.useState<string | null>(null)
const [searching, setSearching] = React.useState(false)
const [selected, setSelected] = React.useState<any>(null)
const [detail, setDetail] = React.useState<any>(null)
const [detailError, setDetailError] = React.useState<string | null>(null)
const [detailLoading, setDetailLoading] = React.useState(false)
const status = useApi(async () => {
const result = await request('/dsh-brain/raw/status')
if (result.status === 404) throw new Error('原始记录接口还没加载:请完全退出并重启 DSH。')
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error('读取原始记录状态失败(HTTP ' + String(result.status) + ')')
return result.body
}, { visible: active, pollMs: 15000 })
const sessions = useApi(async () => {
const result = await request('/dsh-brain/raw/sessions?limit=30')
if (result.status === 404) throw new Error('原始记录接口还没加载:请完全退出并重启 DSH。')
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error('读取原始会话失败(HTTP ' + String(result.status) + ')')
return result.body
}, { visible: active })
const runSearch = async (): Promise<void> => {
const value = query.trim()
if (value === '') { setSearchResult(null); setSearchError('先输入要搜索的关键词。'); return }
setSearching(true)
setSearchError(null)
try {
const params = new URLSearchParams({ q: value, k: '30' })
if (role !== '') params.set('role', role)
const result = await request('/dsh-brain/raw/search?' + params.toString())
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error('搜索原始记录失败(HTTP ' + String(result.status) + ')')
setSearchResult(result.body)
} catch (failure) {
setSearchError(messageOf(failure))
} finally {
setSearching(false)
}
}
const openSession = async (sessionId: string, seq?: number): Promise<void> => {
setSelected({ sessionId, ...(seq === undefined ? {} : { seq }) })
setDetail(null)
setDetailError(null)
setDetailLoading(true)
try {
const params = new URLSearchParams({ session_id: sessionId, limit: '100' })
if (seq !== undefined) params.set('seq', String(seq))
const result = await request('/dsh-brain/raw/session?' + params.toString())
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error('读取会话失败(HTTP ' + String(result.status) + ')')
setDetail(result.body)
} catch (failure) {
setDetailError(messageOf(failure))
} finally {
setDetailLoading(false)
}
}
const sessionRows: any[] = Array.isArray(sessions.data?.sessions) ? sessions.data.sessions : []
const matches: any[] = Array.isArray(searchResult?.matches) ? searchResult.matches : []
const detailItems: any[] = Array.isArray(detail?.items) ? detail.items : []
const disabled = status.data?.enabled === false
return h('div', { style: s.page },
status.error === null ? null : h(Banner, { tone: 'bad' }, status.error),
disabled ? h(Banner, { tone: 'warn' }, '原始记录层当前已停用:在「设置 → 插件」中启用 dsh-brain-raw 子插件后重启 DSH。') : null,
h('div', { style: s.hero },
h('div', { style: s.heroText },
h('div', { style: s.kicker }, 'RAW MEMORY · 原话档案'),
h('h3', { style: s.heroTitle }, '原始记录'),
h('p', { style: s.heroSub }, '这里不筛摘要、不改写,只按会话保存真实对话。记忆条目说不清时,回到原话里核对。'),
),
h('div', { style: s.metrics },
metric('记录', status.status === 'loading' ? '…' : status.data?.records ?? 0),
metric('会话', status.status === 'loading' ? '…' : status.data?.sessions ?? 0),
metric('占用', status.status === 'loading' ? '…' : formatBytes(status.data?.bytes ?? 0)),
metric('保留', status.status === 'loading' ? '…' : String(status.data?.retentionDays ?? '—') + ' 天'),
),
),
status.data?.dir === undefined ? null : h('p', { style: s.hint }, '保存目录:' + String(status.data.dir)),
h('div', { style: s.toolbar },
h('div', { style: s.searchBox },
h('span', { style: s.searchGlyph }, '⌕'),
h('input', {
style: s.searchInput,
type: 'text',
value: query,
placeholder: '搜索原话,例如:预算、接口、苹果…',
spellCheck: false,
onChange: (event: any) => setQuery(event.target.value),
onKeyDown: (event: any) => { if (event.key === 'Enter') void runSearch() },
}),
),
h('div', { style: s.chips, role: 'tablist', 'aria-label': '原始记录角色筛选' },
[['', '全部'], ['user', '你'], ['assistant', '助手']].map((item) => h('button', {
key: item[0],
type: 'button',
role: 'tab',
'aria-selected': role === item[0],
style: role === item[0] ? Object.assign({}, s.chip, s.chipActive) : s.chip,
onClick: () => setRole(item[0]),
}, item[1])),
),
h(Btn, { label: searching ? '搜索中…' : '搜索', variant: 'primary', disabled: searching, onClick: () => { void runSearch() } }),
searchResult === null ? null : h(Btn, { label: '清空结果', variant: 'small', onClick: () => { setSearchResult(null); setSearchError(null) } }),
),
searchError === null ? null : h(Banner, { tone: 'bad' }, searchError),
searchResult === null ? null : h('div', { style: s.card },
h('div', { style: s.cardHead },
h('h4', { style: s.cardTitle }, '搜索结果(' + String(searchResult.total ?? matches.length) + ')'),
h('span', { style: s.hint }, searchResult.truncated === true ? '结果过多,已截断' : '点击结果查看原话'),
),
matches.length === 0 ? h('div', { style: s.empty }, '没有找到匹配的原话。') : h('div', { style: s.resultList },
matches.map((item: any, index: number) => h('div', {
key: String(item.sessionId) + ':' + String(item.seq ?? index) + ':' + String(index),
style: s.result,
onClick: () => { void openSession(String(item.sessionId), typeof item.seq === 'number' ? item.seq : undefined) },
},
h('div', { style: s.resultHead },
h(Pill, { label: '角色', value: roleLabel(String(item.role)), tone: 'muted' }),
h(Pill, { label: '会话', value: shortId(item.sessionId), tone: 'muted' }),
item.seq === undefined ? null : h(Pill, { label: 'seq', value: item.seq, tone: 'muted' }),
h('span', { style: s.msgMeta }, when(item.time ?? item.createdAt)),
),
h('div', { style: s.resultSnippet }, String(item.snippet ?? '')),
)),
),
),
h('div', { style: s.layout },
h('div', { style: s.card },
h('div', { style: s.cardHead },
h('h4', { style: s.cardTitle }, '最近会话'),
h(Btn, { label: '刷新', variant: 'small', onClick: () => { status.reload(); sessions.reload() } }),
),
sessions.error === null ? null : h(Banner, { tone: 'bad' }, sessions.error),
sessionRows.length === 0 ? h('div', { style: s.empty }, '还没有原始记录。重启 DSH 后,新的对话会开始采集。') : h('div', { style: s.sessionList },
sessionRows.map((item: any) => h('div', {
key: String(item.sessionId),
style: selected?.sessionId === item.sessionId ? Object.assign({}, s.session, s.sessionActive) : s.session,
onClick: () => { void openSession(String(item.sessionId)) },
},
h('div', { style: s.sessionTitle }, shortId(item.sessionId)),
h('div', { style: s.sessionMeta },
h('span', null, String(item.records ?? 0) + ' 条'),
h('span', null, when(item.lastAt)),
h('span', null, formatBytes(item.bytes ?? 0)),
),
item.latestSnippet === undefined ? null : h('div', { style: s.sessionSnippet }, String(item.latestSnippet)),
)),
),
),
h('div', { style: s.card },
selected === null
? h('div', { style: s.empty }, '从左侧选择一个会话,或在上方搜索原话。')
: h('div', { style: s.main },
h('div', { style: s.cardHead },
h('h4', { style: s.cardTitle }, '会话 ' + shortId(selected.sessionId)),
h('div', { style: s.chips },
h(Pill, { label: '总记录', value: detailLoading ? '…' : detail?.total ?? '—', tone: 'muted' }),
selected.seq === undefined ? null : h(Pill, { label: 'seq', value: selected.seq, tone: 'muted' }),
h(Btn, { label: '查看整个会话', variant: 'small', onClick: () => { void openSession(String(selected.sessionId)) } }),
),
),
detailError === null ? null : h(Banner, { tone: 'bad' }, detailError),
detailLoading ? h('p', { style: s.hint }, '正在读取原话…') : null,
!detailLoading && detailError === null && detailItems.length === 0 ? h('div', { style: s.empty }, '这个会话还没有原始记录。') : null,
detailItems.length === 0 ? null : h('div', { style: s.messageList },
detailItems.map((item: any, index: number) => h('div', {
key: String(item.messageId ?? item.seq ?? index),
style: item.role === ROLE_ASSISTANT ? Object.assign({}, s.message, s.messageAssistant) : s.message,
},
h('div', { style: s.msgHead },
h('span', { style: item.role === ROLE_ASSISTANT ? Object.assign({}, s.role, s.roleAssistant) : s.role }, roleLabel(String(item.role))),
item.seq === undefined ? null : h('span', { style: s.msgMeta }, 'seq ' + String(item.seq)),
item.turn === undefined ? null : h('span', { style: s.msgMeta }, 'turn ' + String(item.turn)),
h('span', { style: s.msgMeta }, when(item.time ?? item.createdAt)),
),
h('div', { style: s.msgText }, String(item.text ?? '')),
)),
),
),
),
),
)
}

126
src/entries/raw.ts Normal file
View File

@ -0,0 +1,126 @@
/**
* dsh-brain-raw — the optional original-record layer.
*
* It listens to the host's existing session stream and writes each real user
* or assistant message into its own append-only JSONL store. It never writes
* to Mnemon's mnemon.db, never changes Mnemon's source, and stays inert when
* this row is disabled.
*/
import type { CloudMemoryContext, SessionEventLike, SessionLike } from '../context-types.ts'
import { createRawMemoryRuntime } from '../raw-memory/index.ts'
import { createRawMemoryRoutes } from '../raw-memory/routes.ts'
import { conversationIdOf, redactSecrets, textOf, turnOf } from '../reporter.ts'
export const name = 'dsh-brain-raw'
/** Services required before `apply` runs. */
export const inject = ['tools']
function isInjected(value: unknown): boolean {
if (value === null || typeof value !== 'object') return false
const source = (value as Record<string, unknown>).source
if (source === null || typeof source !== 'object') return false
const kind = (source as Record<string, unknown>).kind
return typeof kind === 'string' && kind !== 'user'
}
function workspaceOf(session: SessionLike): string | undefined {
return session.cwd ?? session.workspace ?? session.header?.cwd ?? session.header?.workspace
}
function messageIdOf(value: unknown): string | undefined {
if (value === null || typeof value !== 'object') return undefined
const id = (value as Record<string, unknown>).id
return typeof id === 'string' && id !== '' ? id : undefined
}
function epochOf(time: number | string | undefined): number | undefined {
if (typeof time === 'number' && Number.isFinite(time)) return time
if (typeof time === 'string' && time.trim() !== '') {
const parsed = Date.parse(time)
return Number.isFinite(parsed) ? parsed : undefined
}
return undefined
}
/** Register the raw recorder with the host. */
export function apply(ctx: CloudMemoryContext, config: unknown): void {
const runtime = createRawMemoryRuntime(config)
const logger = ctx.logger('dsh-brain')
ctx.inject(['tools'], (toolsCtx) => {
const tools = (toolsCtx as CloudMemoryContext).tools
if (tools === undefined) return
for (const tool of runtime.tools) {
toolsCtx.effect(() => tools.register(tool), `dsh-brain-raw: tool ${tool.name}`)
}
})
ctx.inject(['webServer'], (webCtx) => {
const webServer = (webCtx as CloudMemoryContext).webServer
if (webServer === undefined) return
for (const route of createRawMemoryRoutes({ store: runtime.store, settings: () => runtime.settings })) {
webCtx.effect(() => webServer.register(route), `dsh-brain-raw: route ${route.path}`)
}
})
const seen = new Map<string, number>()
const onEvent = ctx.on as unknown as (
name: 'session/event',
listener: (session: SessionLike, event: SessionEventLike) => void,
) => () => void
ctx.effect(() => {
const dispose = onEvent('session/event', (session, event) => {
if (!runtime.settings.enabled) return
if (event === null || typeof event !== 'object') return
if (event.type !== 'user/message' && event.type !== 'assistant/message') return
if (event.type === 'assistant/message' && !runtime.settings.captureAssistant) return
const sessionId = conversationIdOf(session)
if (sessionId === undefined) return
const value = event.data?.message ?? event.data
if (event.type === 'user/message' && isInjected(value)) return
const raw = textOf(value)
if (raw === undefined || raw.trim() === '') return
const seq = typeof event.seq === 'number' && Number.isFinite(event.seq) ? event.seq : undefined
const dedupe = `${sessionId}:${seq === undefined ? event.type + ':' + raw.slice(0, 120) : String(seq)}:${event.type}`
if (seen.has(dedupe)) return
seen.set(dedupe, Date.now())
if (seen.size > 10_000) {
const oldest = seen.keys().next()
if (oldest.done !== true) seen.delete(oldest.value)
}
const turn = turnOf(event.data)
const messageId = messageIdOf(value)
const time = epochOf(event.time)
const workspace = workspaceOf(session)
const record = {
v: 1 as const,
sessionId,
...(seq === undefined ? {} : { seq }),
...(turn === undefined ? {} : { turn }),
role: event.type === 'user/message' ? 'user' as const : 'assistant' as const,
text: redactSecrets(raw).slice(0, runtime.settings.maxTextChars),
...(time === undefined ? {} : { time }),
...(messageId === undefined ? {} : { messageId }),
createdAt: Date.now(),
...(workspace === undefined ? {} : { workspace }),
}
void runtime.store.append(record).catch((error: unknown) => {
logger.warn('dsh-brain-raw capture failed: ' + (error instanceof Error ? error.message : String(error)))
})
})
return () => dispose()
}, 'dsh-brain-raw: session capture')
// Retention is checked once on load and then every six hours; it only deletes
// whole session files whose last write is older than the configured window.
ctx.effect(() => {
void runtime.store.prune(runtime.settings.retentionDays).catch(() => undefined)
const timer = setInterval(() => { void runtime.store.prune(runtime.settings.retentionDays) }, 6 * 60 * 60 * 1000)
timer.unref?.()
return () => clearInterval(timer)
}, 'dsh-brain-raw: retention')
}

View File

@ -1,12 +1,11 @@
/**
* Plugin entry — compat root.
*
* The package now ships five toggleable sub-plugin rows (see
* cordis.patch.yml): cloud-sync, memory, skills, mcp, and ui.
* The package now ships six toggleable sub-plugin rows (see
* cordis.patch.yml): cloud-sync, memory, skills, mcp, ui, and raw.
* This root entry remains for older single-row profiles: it applies all
* five entries against the same context, so the route and tool tables it
* registers are identical to the pre-split build, including the legacy
* /cloud-memory aliases.
* six entries against the same context, including the raw recorder and the
* legacy /cloud-memory aliases.
*
* Everything registers through `ctx.effect(...)` so a plugin reload tears
* down its routes, timers, listeners, and tools without leftovers.
@ -17,6 +16,7 @@ import * as memory from './entries/memory.ts'
import * as skills from './entries/skills.ts'
import * as mcp from './entries/mcp.ts'
import * as ui from './entries/ui.ts'
import * as raw from './entries/raw.ts'
/** Package name; also the client bundle id. */
export const name = 'dsh-brain'
@ -35,4 +35,5 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
skills.apply(ctx, config)
mcp.apply(ctx, config)
ui.apply(ctx, config)
raw.apply(ctx, config)
}

37
src/raw-memory/index.ts Normal file
View File

@ -0,0 +1,37 @@
/**
* Original-record layer public surface.
*
* This module deliberately has no dependency on Mnemon's core: a host entry
* can create the recorder, register its three tools, and feed it session
* events without changing any Mnemon source, database or UI.
*/
import { RawMemoryStore } from './store.ts'
import { rawMemorySettingsFromConfig, type RawMemorySettings } from './settings.ts'
import { createRawMemoryTools } from './tools.ts'
import type { ToolDefinitionLike } from '../context-types.ts'
export interface RawMemoryRuntime {
settings: RawMemorySettings
store: RawMemoryStore
tools: ToolDefinitionLike[]
}
/** Build the raw recorder and its tools from one row config. */
export function createRawMemoryRuntime(config: unknown): RawMemoryRuntime {
const settings = rawMemorySettingsFromConfig(config)
const store = new RawMemoryStore({
root: settings.dir,
maxBytesPerSession: settings.maxBytesPerSession,
})
return {
settings,
store,
tools: createRawMemoryTools({ store, settings: () => settings }),
}
}
export { RawMemoryStore } from './store.ts'
export { createRawMemoryTools } from './tools.ts'
export { rawMemorySettingsFromConfig } from './settings.ts'
export type { RawMemoryRecord, RawMemorySearchHit, RawMemoryStatus } from './types.ts'
export type { RawMemorySettings } from './settings.ts'

111
src/raw-memory/routes.ts Normal file
View File

@ -0,0 +1,111 @@
/**
* Read-only HTTP surface for the raw-record layer.
*
* These routes serve the Brain panel's 原始记录 tab. They are read-only:
* the only writer is the session/event recorder in entries/raw.ts.
*/
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { CloudMemoryWebRoute } from '../context-types.ts'
import { fail, json } from '../http.ts'
import type { RawMemorySettings } from './settings.ts'
import type { RawMemoryStore } from './store.ts'
export interface RawMemoryRouteDeps {
store: RawMemoryStore
settings: () => RawMemorySettings
}
function urlOf(req: IncomingMessage): URL {
return new URL(req.url ?? '/', 'http://localhost')
}
function method(req: IncomingMessage, res: ServerResponse, allowed: string): boolean {
if (req.method === allowed || (allowed === 'GET' && req.method === 'HEAD')) return true
fail(res, 405, 'method-not-allowed')
return false
}
function numberParam(url: URL, name: string, fallback: number, min: number, max: number): number {
const parsed = Number.parseInt(url.searchParams.get(name) ?? '', 10)
if (!Number.isFinite(parsed)) return fallback
return Math.min(max, Math.max(min, parsed))
}
function serveStatus(deps: RawMemoryRouteDeps, req: IncomingMessage, res: ServerResponse): void {
if (!method(req, res, 'GET')) return
const settings = deps.settings()
void deps.store.status(settings.enabled, settings.retentionDays).then((status) => {
json(res, 200, { ok: true, ...status })
}).catch((error: unknown) => {
fail(res, 500, error instanceof Error ? error.message : 'raw-status-failed')
})
}
function serveSessions(deps: RawMemoryRouteDeps, req: IncomingMessage, res: ServerResponse): void {
if (!method(req, res, 'GET')) return
const settings = deps.settings()
if (!settings.enabled) { fail(res, 503, 'raw-disabled'); return }
const url = urlOf(req)
const limit = numberParam(url, 'limit', 30, 1, 100)
void deps.store.listSessions(limit).then((sessions) => {
json(res, 200, { ok: true, sessions })
}).catch((error: unknown) => {
fail(res, 500, error instanceof Error ? error.message : 'raw-sessions-failed')
})
}
function serveSearch(deps: RawMemoryRouteDeps, req: IncomingMessage, res: ServerResponse): void {
if (!method(req, res, 'GET')) return
const settings = deps.settings()
if (!settings.enabled) { fail(res, 503, 'raw-disabled'); return }
const url = urlOf(req)
const query = (url.searchParams.get('q') ?? '').trim()
if (query === '') { fail(res, 400, 'query-required'); return }
const roleValue = url.searchParams.get('role')
const role = roleValue === 'user' || roleValue === 'assistant' ? roleValue : undefined
const k = numberParam(url, 'k', settings.maxSearchResults, 1, 50)
const sessionId = (url.searchParams.get('session_id') ?? '').trim() || undefined
void deps.store.search(query, { k, ...(role === undefined ? {} : { role }), ...(sessionId === undefined ? {} : { sessionId }) }).then((result) => {
json(res, 200, {
ok: true,
query,
total: result.total,
truncated: result.truncated,
sessions_scanned: result.sessionsScanned,
matches: result.matches,
})
}).catch((error: unknown) => {
fail(res, 500, error instanceof Error ? error.message : 'raw-search-failed')
})
}
function serveSession(deps: RawMemoryRouteDeps, req: IncomingMessage, res: ServerResponse): void {
if (!method(req, res, 'GET')) return
const settings = deps.settings()
if (!settings.enabled) { fail(res, 503, 'raw-disabled'); return }
const url = urlOf(req)
const sessionId = (url.searchParams.get('session_id') ?? '').trim()
if (sessionId === '') { fail(res, 400, 'session-id-required'); return }
const seqValue = url.searchParams.get('seq')
const seq = seqValue === null ? undefined : Number.parseInt(seqValue, 10)
const offset = numberParam(url, 'offset', 0, 0, 1000000)
const limit = numberParam(url, 'limit', settings.maxReadRecords, 1, 500)
void deps.store.readSession(sessionId, {
...(seq === undefined || !Number.isFinite(seq) ? {} : { seq }),
...(seq === undefined ? { offset } : {}),
limit,
}).then((result) => {
json(res, 200, { ok: true, session_id: result.sessionId, total: result.total, items: result.items })
}).catch((error: unknown) => {
fail(res, 500, error instanceof Error ? error.message : 'raw-session-failed')
})
}
export function createRawMemoryRoutes(deps: RawMemoryRouteDeps): CloudMemoryWebRoute[] {
return [
{ kind: 'exact', path: '/dsh-brain/raw/status', handler: (req, res) => serveStatus(deps, req, res) },
{ kind: 'exact', path: '/dsh-brain/raw/sessions', handler: (req, res) => serveSessions(deps, req, res) },
{ kind: 'exact', path: '/dsh-brain/raw/search', handler: (req, res) => serveSearch(deps, req, res) },
{ kind: 'exact', path: '/dsh-brain/raw/session', handler: (req, res) => serveSession(deps, req, res) },
]
}

View File

@ -0,0 +1,53 @@
/**
* Raw-layer configuration.
*
* The row config in cordis.patch.yml is the first-boot seed. Keeping the
* parser here (rather than in the five-bundle Settings store) lets the raw
* recorder stay an optional, self-contained row: disabling the row stops all
* capture, and changing its config changes the recorder without touching
* Mnemon or the existing memory bundles.
*/
import { join, resolve } from 'node:path'
import { dshHome } from '../store.ts'
/** Effective raw-layer settings. */
export interface RawMemorySettings {
enabled: boolean
captureAssistant: boolean
dir: string
retentionDays: number
maxBytesPerSession: number
maxTextChars: number
maxSearchResults: number
maxReadRecords: number
}
function asRecord(value: unknown): Record<string, unknown> {
if (value === null || typeof value !== 'object' || Array.isArray(value)) return {}
return value as Record<string, unknown>
}
function bool(value: unknown, fallback: boolean): boolean {
return typeof value === 'boolean' ? value : fallback
}
function integer(value: unknown, fallback: number, min: number, max: number): number {
if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
return Math.min(max, Math.max(min, Math.trunc(value)))
}
/** Parse one raw-row config defensively; every field is optional. */
export function rawMemorySettingsFromConfig(config: unknown): RawMemorySettings {
const source = asRecord(config)
const rawDir = typeof source.rawDir === 'string' ? source.rawDir.trim() : ''
return {
enabled: bool(source.rawEnabled, true),
captureAssistant: bool(source.rawCaptureAssistant, true),
dir: rawDir === '' ? join(dshHome(), 'brain', 'raw') : resolve(rawDir),
retentionDays: integer(source.rawRetentionDays, 90, 1, 3650),
maxBytesPerSession: integer(source.rawMaxBytesPerSession, 20_000_000, 100_000, 1_000_000_000),
maxTextChars: integer(source.rawMaxTextChars, 16_000, 1_000, 200_000),
maxSearchResults: integer(source.rawMaxSearchResults, 10, 1, 50),
maxReadRecords: integer(source.rawMaxReadRecords, 50, 1, 500),
}
}

291
src/raw-memory/store.ts Normal file
View File

@ -0,0 +1,291 @@
/**
* Append-only original-record store.
*
* One JSONL file per session, under a separate directory from Mnemon's
* mnemon.db. The raw layer deliberately does not join Mnemon's identity /
* merge tables: those walk every non-oplog row and would become slower with
* every captured message. Rotation keeps one session bounded; retention is
* enforced by the entry's maintenance timer.
*/
import { createHash } from 'node:crypto'
import { appendFile, mkdir, readdir, readFile, rename, rm, stat } from 'node:fs/promises'
import { join } from 'node:path'
import type { RawMemoryRecord, RawMemorySearchHit, RawMemorySessionSummary, RawMemoryStatus } from './types.ts'
export interface RawMemoryStoreOptions {
root: string
maxBytesPerSession: number
/** Upper bound for one search scan; protects the host from a huge archive. */
maxScanBytes?: number
}
export interface RawMemorySearchOptions {
k?: number
sessionId?: string
role?: 'user' | 'assistant'
}
export interface RawMemoryReadOptions {
seq?: number
offset?: number
limit?: number
}
function sizeOf(path: string): Promise<number> {
return stat(path).then((info) => info.size).catch(() => 0)
}
function snippetFor(text: string, terms: string[]): string {
const lower = text.toLowerCase()
let first = -1
for (const term of terms) {
const found = lower.indexOf(term)
if (found >= 0 && (first < 0 || found < first)) first = found
}
const start = first <= 80 ? 0 : first - 80
const end = Math.min(text.length, start + 500)
return `${start > 0 ? '…' : ''}${text.slice(start, end)}${end < text.length ? '…' : ''}`
}
function isRecord(value: unknown): value is RawMemoryRecord {
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
const record = value as Record<string, unknown>
return record.v === 1
&& typeof record.sessionId === 'string'
&& typeof record.text === 'string'
&& (record.role === 'user' || record.role === 'assistant')
&& typeof record.createdAt === 'number'
}
export class RawMemoryStore {
private readonly options: RawMemoryStoreOptions & { maxScanBytes: number }
private readonly queues = new Map<string, Promise<void>>()
private readonly sizes = new Map<string, number>()
constructor(options: RawMemoryStoreOptions) {
this.options = { ...options, maxScanBytes: options.maxScanBytes ?? 128 * 1024 * 1024 }
}
get dir(): string {
return this.options.root
}
private safeSessionName(sessionId: string): string {
const readable = sessionId.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 80) || 'session'
const hash = createHash('sha256').update(sessionId).digest('hex').slice(0, 8)
return `${readable}-${hash}`
}
private fileFor(sessionId: string): string {
return join(this.options.root, `${this.safeSessionName(sessionId)}.jsonl`)
}
private rotatedFor(file: string): string {
return file.replace(/\.jsonl$/, '.1.jsonl')
}
private async listFiles(): Promise<string[]> {
try {
const entries = await readdir(this.options.root, { withFileTypes: true })
return entries
.filter((entry) => entry.isFile() && entry.name.endsWith('.jsonl'))
.map((entry) => join(this.options.root, entry.name))
.sort()
} catch {
return []
}
}
private async readRecords(file: string): Promise<RawMemoryRecord[]> {
let text: string
try {
text = await readFile(file, 'utf8')
} catch {
return []
}
const records: RawMemoryRecord[] = []
for (const line of text.split(/\r?\n/)) {
if (line.trim() === '') continue
try {
const value: unknown = JSON.parse(line)
if (isRecord(value)) records.push(value)
} catch {
// A torn final line must not make the rest of the file unreadable.
}
}
return records
}
/** Append one message, serialized per session so concurrent turns cannot interleave. */
async append(record: RawMemoryRecord): Promise<void> {
const file = this.fileFor(record.sessionId)
const line = `${JSON.stringify(record)}\n`
const incoming = Buffer.byteLength(line, 'utf8')
const previous = this.queues.get(file) ?? Promise.resolve()
const next = previous.then(async () => {
await mkdir(this.options.root, { recursive: true })
let size = this.sizes.get(file)
if (size === undefined) size = await sizeOf(file)
if (size > 0 && size + incoming > this.options.maxBytesPerSession) {
const rotated = this.rotatedFor(file)
await rm(rotated, { force: true }).catch(() => undefined)
await rename(file, rotated).catch(() => undefined)
size = 0
}
await appendFile(file, line, { encoding: 'utf8', mode: 0o600 })
this.sizes.set(file, size + incoming)
}).finally(() => {
if (this.queues.get(file) === next) this.queues.delete(file)
})
this.queues.set(file, next)
await next
}
/** Keyword search over original text, newest / best match first. */
async search(query: string, options: RawMemorySearchOptions = {}): Promise<{
matches: RawMemorySearchHit[]
total: number
truncated: boolean
sessionsScanned: number
}> {
const normalized = query.trim().toLowerCase()
const terms = normalized.split(/\s+/).filter((term) => term !== '')
if (terms.length === 0) return { matches: [], total: 0, truncated: false, sessionsScanned: 0 }
// Boundary responsibility: callers (raw tools and routes) validate and clamp k.
const k = options.k ?? 10
const files = await this.listFiles()
const matches: RawMemorySearchHit[] = []
const seenSessions = new Set<string>()
let total = 0
let scannedBytes = 0
let truncated = false
for (const file of files) {
// The scan cap is always set by the constructor; hitting it is reported
// explicitly through `truncated`, never silently.
if (scannedBytes >= this.options.maxScanBytes) {
truncated = true
break
}
scannedBytes += await sizeOf(file)
for (const record of await this.readRecords(file)) {
seenSessions.add(record.sessionId)
if (options.sessionId !== undefined && record.sessionId !== options.sessionId) continue
if (options.role !== undefined && record.role !== options.role) continue
const haystack = `${record.text.toLowerCase()}\n${record.sessionId.toLowerCase()}`
let score = 0
for (const term of terms) if (haystack.includes(term)) score += 1
if (score === 0) continue
if (haystack.includes(normalized)) score += 2
total += 1
matches.push({
sessionId: record.sessionId,
...(record.seq === undefined ? {} : { seq: record.seq }),
...(record.turn === undefined ? {} : { turn: record.turn }),
role: record.role,
...(record.time === undefined ? {} : { time: record.time }),
createdAt: record.createdAt,
...(record.messageId === undefined ? {} : { messageId: record.messageId }),
snippet: snippetFor(record.text, terms),
score,
})
}
}
matches.sort((left, right) => right.score - left.score || right.createdAt - left.createdAt)
return { matches: matches.slice(0, k), total, truncated, sessionsScanned: seenSessions.size }
}
/** Read one session, either by exact event seq or by record offset. */
async readSession(sessionId: string, options: RawMemoryReadOptions = {}): Promise<{
sessionId: string
total: number
items: RawMemoryRecord[]
}> {
const file = this.fileFor(sessionId)
const records = [...await this.readRecords(this.rotatedFor(file)), ...await this.readRecords(file)]
let selected = records
if (options.seq !== undefined) {
selected = records.filter((record) => record.seq === options.seq)
} else {
// Boundary responsibility: callers (raw tools and routes) validate and clamp offset/limit.
const offset = options.offset ?? 0
const limit = options.limit ?? 50
selected = records.slice(offset, offset + limit)
}
return { sessionId, total: records.length, items: selected }
}
/** Aggregate counts for the status tool. */
async status(enabled: boolean, retentionDays: number): Promise<RawMemoryStatus> {
const files = await this.listFiles()
let records = 0
let bytes = 0
const sessions = new Set<string>()
let oldest: number | undefined
let newest: number | undefined
for (const file of files) {
bytes += await sizeOf(file)
for (const record of await this.readRecords(file)) {
records += 1
sessions.add(record.sessionId)
if (oldest === undefined || record.createdAt < oldest) oldest = record.createdAt
if (newest === undefined || record.createdAt > newest) newest = record.createdAt
}
}
return {
enabled,
dir: this.options.root,
sessions: sessions.size,
records,
bytes,
...(oldest === undefined ? {} : { oldestAt: new Date(oldest).toISOString() }),
...(newest === undefined ? {} : { newestAt: new Date(newest).toISOString() }),
retentionDays,
maxBytesPerSession: this.options.maxBytesPerSession,
}
}
/** Session rows for the Brain panel's session browser, newest first. */
async listSessions(limit = 30): Promise<RawMemorySessionSummary[]> {
const files = await this.listFiles()
const sessions = new Map<string, RawMemorySessionSummary>()
for (const file of files) {
const bytes = await sizeOf(file)
const records = await this.readRecords(file)
if (records.length === 0) continue
const sessionId = records[0]!.sessionId
const summary = sessions.get(sessionId) ?? { sessionId, records: 0, bytes: 0 }
summary.records += records.length
summary.bytes += bytes
for (const record of records) {
const stamp = record.time ?? record.createdAt
if (summary.firstAt === undefined || stamp < summary.firstAt) summary.firstAt = stamp
if (summary.lastAt === undefined || stamp > summary.lastAt) summary.lastAt = stamp
summary.latestSnippet = record.text.slice(0, 160)
}
sessions.set(sessionId, summary)
}
return [...sessions.values()]
.sort((left, right) => (right.lastAt ?? 0) - (left.lastAt ?? 0))
.slice(0, Math.max(1, Math.min(200, Math.trunc(limit))))
}
/** Delete session files whose last write is older than the retention window. */
async prune(retentionDays: number): Promise<number> {
const cutoff = Date.now() - retentionDays * 24 * 60 * 60 * 1000
let removed = 0
for (const file of await this.listFiles()) {
try {
const info = await stat(file)
if (info.mtimeMs < cutoff) {
await rm(file, { force: true })
removed += 1
this.sizes.delete(file)
}
} catch {
// A file removed concurrently is already in the desired state.
}
}
return removed
}
}

145
src/raw-memory/tools.ts Normal file
View File

@ -0,0 +1,145 @@
/**
* Agent-facing tools for the original-record layer.
*
* These are deliberately separate from memory_search / memory_read: those
* search distilled entries, while these search what was actually said. The
* model can go from a memory card back to its source conversation instead of
* treating the card as the only truth.
*/
import type { ToolDefinitionLike } from '../context-types.ts'
import type { RawMemoryStore } from './store.ts'
import type { RawMemorySettings } from './settings.ts'
export interface RawMemoryToolDeps {
store: RawMemoryStore
settings: () => RawMemorySettings
}
interface TextBlock {
type: 'text'
text: string
}
function renderJson(_args: unknown, value: unknown): TextBlock[] {
const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2)
return [{ type: 'text', text }]
}
function searchTool(deps: RawMemoryToolDeps): ToolDefinitionLike {
return {
name: 'memory_raw_search',
description:
'在原始对话记录中按关键词搜索原话(不是记忆条目,也不是摘要)。返回会话 id、事件 seq、说话角色、时间和原文片段;' +
'需要完整上下文时用 memory_raw_read 按 session_id + seq 读取。纯本地关键词匹配。',
parameters: {
type: 'object',
properties: {
query: { type: 'string', description: '检索关键词或短语(必填)。' },
k: { type: 'integer', description: '最多返回条数(1..50,默认取配置值)。' },
session_id: { type: 'string', description: '可选:只在这个会话内搜索。' },
role: { type: 'string', enum: ['user', 'assistant'], description: '可选:只看用户或助手原话。' },
},
required: ['query'],
additionalProperties: false,
},
output: {
schema: {
type: 'object',
properties: {
query: { type: 'string' },
total: { type: 'number' },
truncated: { type: 'boolean' },
sessions_scanned: { type: 'number' },
matches: { type: 'array', items: { type: 'object' } },
},
required: ['query', 'matches'],
additionalProperties: true,
},
render: renderJson,
},
async execute(args: Record<string, unknown>): Promise<unknown> {
const settings = deps.settings()
if (!settings.enabled) throw new Error('原始记录层当前已禁用(dsh-brain-raw 行未启用)。')
const query = typeof args.query === 'string' ? args.query.trim() : ''
if (query === '') throw new Error('query 不能为空。')
const requested = typeof args.k === 'number' && Number.isFinite(args.k) ? Math.trunc(args.k) : settings.maxSearchResults
const k = Math.min(50, Math.max(1, requested))
const sessionId = typeof args.session_id === 'string' && args.session_id !== '' ? args.session_id : undefined
const role = args.role === 'user' || args.role === 'assistant' ? args.role : undefined
const result = await deps.store.search(query, { k, ...(sessionId === undefined ? {} : { sessionId }), ...(role === undefined ? {} : { role }) })
return {
query,
total: result.total,
truncated: result.truncated,
sessions_scanned: result.sessionsScanned,
matches: result.matches,
}
},
}
}
function readTool(deps: RawMemoryToolDeps): ToolDefinitionLike {
return {
name: 'memory_raw_read',
description:
'读取某个会话的原始记录:给 seq 时返回那一条原话,否则按 offset/limit 分页浏览。' +
'返回 sessionId、seq、turn、role、text 与时间。用于核对记忆条目、追查原话出处。',
parameters: {
type: 'object',
properties: {
session_id: { type: 'string', description: '会话 id(必填,可用 memory_raw_search 获得)。' },
seq: { type: 'integer', description: '可选:精确读取该事件 seq 对应的那一条。' },
offset: { type: 'integer', description: '可选:从第几条开始(默认 0)。' },
limit: { type: 'integer', description: '可选:读取条数(1..500,默认取配置值)。' },
},
required: ['session_id'],
additionalProperties: false,
},
output: {
schema: {
type: 'object',
properties: {
session_id: { type: 'string' },
total: { type: 'number' },
items: { type: 'array', items: { type: 'object' } },
},
required: ['session_id', 'items'],
additionalProperties: true,
},
render: renderJson,
},
async execute(args: Record<string, unknown>): Promise<unknown> {
const settings = deps.settings()
if (!settings.enabled) throw new Error('原始记录层当前已禁用(dsh-brain-raw 行未启用)。')
const sessionId = typeof args.session_id === 'string' ? args.session_id.trim() : ''
if (sessionId === '') throw new Error('session_id 不能为空。')
const seq = typeof args.seq === 'number' && Number.isFinite(args.seq) ? Math.trunc(args.seq) : undefined
const offset = typeof args.offset === 'number' && Number.isFinite(args.offset) ? Math.trunc(args.offset) : 0
const requested = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.trunc(args.limit) : settings.maxReadRecords
const limit = Math.min(500, Math.max(1, requested))
const result = await deps.store.readSession(sessionId, { ...(seq === undefined ? {} : { seq }), offset, limit })
return { session_id: result.sessionId, total: result.total, items: result.items }
},
}
}
function statusTool(deps: RawMemoryToolDeps): ToolDefinitionLike {
return {
name: 'memory_raw_status',
description: '查看原始记录层状态:保存目录、会话数、记录数、占用空间、最早/最新时间与保留天数。',
parameters: { type: 'object', properties: {}, additionalProperties: false },
output: {
schema: { type: 'object', properties: {}, required: [], additionalProperties: true },
render: renderJson,
},
async execute(): Promise<unknown> {
const settings = deps.settings()
return deps.store.status(settings.enabled, settings.retentionDays)
},
}
}
/** Build the three raw-layer tools. */
export function createRawMemoryTools(deps: RawMemoryToolDeps): ToolDefinitionLike[] {
return [searchTool(deps), readTool(deps), statusTool(deps)]
}

63
src/raw-memory/types.ts Normal file
View File

@ -0,0 +1,63 @@
/**
* One original conversation message captured by the raw layer.
*
* The JSONL file is append-only: records are never rewritten in place, so a
* later reader can always reconstruct the exact text that was captured.
*/
export interface RawMemoryRecord {
/** Schema version, so a future format can migrate old files deliberately. */
v: 1
/** Host session id (the same id used by session/event). */
sessionId: string
/** Host event sequence, when the host supplies one. */
seq?: number
/** Turn number within the session, when known. */
turn?: number
/** Who spoke. Tool results are intentionally not captured in this version. */
role: 'user' | 'assistant'
/** Redacted original text. */
text: string
/** Host event time in epoch milliseconds, when parseable. */
time?: number
/** Local capture time in epoch milliseconds. */
createdAt: number
/** Host message id, when supplied; useful for deduplication and tracing. */
messageId?: string
/** Session workspace at capture time, when known. */
workspace?: string
}
/** One search hit returned to the model. */
export interface RawMemorySearchHit {
sessionId: string
seq?: number
turn?: number
role: 'user' | 'assistant'
time?: number
createdAt: number
messageId?: string
snippet: string
score: number
}
/** Compact status card for the raw layer. */
export interface RawMemorySessionSummary {
sessionId: string
records: number
bytes: number
firstAt?: number
lastAt?: number
latestSnippet?: string
}
export interface RawMemoryStatus {
enabled: boolean
dir: string
sessions: number
records: number
bytes: number
oldestAt?: string
newestAt?: string
retentionDays: number
maxBytesPerSession: number
}

60
verify-raw-entry.mjs Normal file
View File

@ -0,0 +1,60 @@
// Raw entry: capture real user/assistant messages, ignore injected and duplicate events.
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const root = mkdtempSync(join(tmpdir(), 'brain-raw-entry-'))
process.env.DSH_HOME = join(root, 'home')
const results = []
function check(name, ok, detail = '') { results.push({ name, ok }); console.log((ok ? 'PASS ' : 'FAIL ') + name + (detail ? ' :: ' + detail : '')) }
const noop = () => {}
const logger = { info: noop, warn: noop }
function fakeCtx() {
const tools = []
const listeners = []
const disposers = []
return {
tools, listeners, disposers,
ctx: {
logger: () => logger,
effect: (fn) => { const dispose = fn(); if (typeof dispose === 'function') disposers.push(dispose); return () => {} },
on: (name, listener) => { if (name === 'session/event') listeners.push(listener); return () => {} },
inject: (_deps, fn) => fn({
tools: { register: (tool) => { tools.push(tool); return () => {} } },
effect: (inner) => { inner(); return () => {} },
}),
},
}
}
const { RawMemoryStore } = await import('./lib/raw-memory/index.js')
const rawEntry = await import('./lib/entries/raw.js')
const rawDir = join(root, 'raw')
const host = fakeCtx()
rawEntry.apply(host.ctx, { rawDir, rawEnabled: true, rawCaptureAssistant: true, rawMaxTextChars: 4000 })
check('raw entry registers three tools', host.tools.length === 3 && host.tools.every((tool) => tool.name.startsWith('memory_raw_')), host.tools.map((tool) => tool.name).join(','))
const emit = (event, sessionId = 'session-x') => { for (const listener of host.listeners) listener({ id: sessionId }, event) }
emit({ type: 'user/message', seq: 1, time: Date.now(), data: { message: { id: 'm1', content: [{ type: 'text', text: '请记住:我喜欢苹果' }] } } })
emit({ type: 'user/message', seq: 2, time: Date.now(), data: { message: { source: { kind: 'plugin' }, content: [{ type: 'text', text: '内部注入,不应记录' }] } } })
emit({ type: 'assistant/message', seq: 3, time: Date.now(), data: { message: { id: 'm3', content: [{ type: 'text', text: '好的,记住了。' }] } } })
emit({ type: 'assistant/message', seq: 3, time: Date.now(), data: { message: { id: 'm3', content: [{ type: 'text', text: '好的,记住了。' }] } } })
await new Promise((resolve) => setTimeout(resolve, 80))
const store = new RawMemoryStore({ root: rawDir, maxBytesPerSession: 20_000_000 })
const status = await store.status(true, 90)
check('captures user + assistant, ignores injected and duplicate seq', status.records === 2 && status.sessions === 1, JSON.stringify(status))
const read = await store.readSession('session-x', { offset: 0, limit: 10 })
check('captured text keeps original wording', read.items.some((item) => item.role === 'user' && item.text.includes('我喜欢苹果')) && read.items.some((item) => item.role === 'assistant' && item.text.includes('记住了')))
const disabledDir = join(root, 'raw-disabled')
const disabled = fakeCtx()
rawEntry.apply(disabled.ctx, { rawDir: disabledDir, rawEnabled: false })
for (const listener of disabled.listeners) listener({ id: 'session-y' }, { type: 'user/message', seq: 1, data: { message: { content: [{ type: 'text', text: '不应记录' }] } } })
await new Promise((resolve) => setTimeout(resolve, 50))
const disabledStore = new RawMemoryStore({ root: disabledDir, maxBytesPerSession: 20_000_000 })
const disabledStatus = await disabledStore.status(false, 90)
check('disabled raw row writes nothing', disabledStatus.records === 0 && disabledStatus.sessions === 0)
const failed = results.filter((result) => !result.ok)
console.log('')
console.log(failed.length ? 'FAILED ' + failed.length + '/' + results.length : 'ALL ' + results.length + ' CHECKS PASSED')
rmSync(root, { recursive: true, force: true })
process.exit(failed.length ? 1 : 0)

60
verify-raw-memory.mjs Normal file
View File

@ -0,0 +1,60 @@
// Raw layer: append/search/read/status/rotation/prune without touching Mnemon.
import { existsSync, mkdtempSync, readdirSync, rmSync, utimesSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const root = mkdtempSync(join(tmpdir(), 'brain-raw-'))
process.env.DSH_HOME = join(root, 'home')
const results = []
function check(name, ok, detail = '') { results.push({ name, ok }); console.log((ok ? 'PASS ' : 'FAIL ') + name + (detail ? ' :: ' + detail : '')) }
const { RawMemoryStore, createRawMemoryTools, rawMemorySettingsFromConfig } = await import('./lib/raw-memory/index.js')
const settings = rawMemorySettingsFromConfig({ rawEnabled: true, rawRetentionDays: 7, rawMaxTextChars: 2000 })
check('default directory is under DSH_HOME, not a mnemon database', settings.dir === join(root, 'home', 'brain', 'raw'), settings.dir)
const store = new RawMemoryStore({ root: join(root, 'raw'), maxBytesPerSession: 300 })
const base = Date.now() - 10_000
await store.append({ v: 1, sessionId: 'session-a', seq: 1, turn: 1, role: 'user', text: '我喜欢吃苹果和香蕉 apple banana', createdAt: base })
await store.append({ v: 1, sessionId: 'session-a', seq: 2, turn: 1, role: 'assistant', text: '好的,记住了。你喜欢苹果。', createdAt: base + 1000 })
await store.append({ v: 1, sessionId: 'session-b', seq: 1, turn: 1, role: 'user', text: 'Another topic: database indexing', createdAt: base + 2000 })
await store.append({ v: 1, sessionId: 'session-a', seq: 3, turn: 2, role: 'user', text: 'x'.repeat(400), createdAt: base + 3000 })
const search = await store.search('苹果')
check('keyword search finds original text', search.total === 2 && search.matches.some((hit) => hit.sessionId === 'session-a' && hit.seq === 1))
const english = await store.search('database indexing')
check('english keyword search works', english.total === 1 && english.matches[0].role === 'user')
const roleFiltered = await store.search('苹果', { role: 'assistant' })
check('role filter narrows search', roleFiltered.total === 1 && roleFiltered.matches[0].seq === 2)
const read = await store.readSession('session-a', { seq: 2 })
check('read by seq returns one exact record', read.total === 3 && read.items.length === 1 && read.items[0].text.includes('记住了'))
const firstPage = await store.readSession('session-a', { offset: 0, limit: 2 })
check('read pagination keeps order', firstPage.items.length === 2 && firstPage.items[0].seq === 1 && firstPage.items[1].seq === 2)
const status = await store.status(true, 7)
check('status counts sessions and records', status.sessions === 2 && status.records === 4 && status.bytes > 0)
check('raw store never creates mnemon.db', !existsSync(join(root, 'raw', 'mnemon.db')))
const tools = createRawMemoryTools({ store, settings: () => settings })
const searchTool = tools.find((tool) => tool.name === 'memory_raw_search')
const readTool = tools.find((tool) => tool.name === 'memory_raw_read')
const statusTool = tools.find((tool) => tool.name === 'memory_raw_status')
check('three raw tools are exported', tools.length === 3 && searchTool && readTool && statusTool)
const toolSearch = await searchTool.execute({ query: '苹果', k: 5 })
check('memory_raw_search returns matches', toolSearch.matches.length === 2 && toolSearch.matches[0].sessionId === 'session-a')
const toolRead = await readTool.execute({ session_id: 'session-b', limit: 10 })
check('memory_raw_read returns items', toolRead.total === 1 && toolRead.items[0].text.includes('database'))
const toolStatus = await statusTool.execute({})
check('memory_raw_status reports enabled', toolStatus.enabled === true && toolStatus.records === 4)
const names = readdirSync(join(root, 'raw'))
const oldFile = join(root, 'raw', names.find((name) => name.startsWith('session-b')) ?? 'missing')
const old = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
utimesSync(oldFile, old, old)
const removed = await store.prune(7)
const afterPrune = await store.status(true, 7)
check('retention removes expired session files only', removed === 1 && afterPrune.sessions === 1)
const failed = results.filter((result) => !result.ok)
console.log('')
console.log(failed.length ? 'FAILED ' + failed.length + '/' + results.length : 'ALL ' + results.length + ' CHECKS PASSED')
rmSync(root, { recursive: true, force: true })
process.exit(failed.length ? 1 : 0)