@asd2233996/dsh-auto-context 0.0.0-stage → 1.15.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/LICENSE +21 -0
- package/README.en.md +113 -0
- package/README.md +250 -2
- package/cordis.patch.yml +23 -0
- package/docs/product-introduction.md +282 -0
- package/docs/structured-kb-notes.md +179 -0
- package/lib/actions.js +2758 -0
- package/lib/extract.js +1647 -0
- package/lib/graph.js +1628 -0
- package/lib/groups.js +307 -0
- package/lib/impl.js +170 -0
- package/lib/index.js +43 -0
- package/lib/kb-tools.js +384 -0
- package/lib/kb.js +254 -0
- package/lib/kg-archive.js +1042 -0
- package/lib/kg-store.js +1427 -0
- package/lib/recall.js +62 -0
- package/lib/scan.js +2537 -0
- package/lib/segments.js +660 -0
- package/lib/store.js +365 -0
- package/lib/util.js +64 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +87 -4
package/lib/kb-tools.js
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* context-manager — 结构化信息库模型工具(5 个)。
|
|
3
|
+
*
|
|
4
|
+
* 设计蓝本:`docs/structured-kb-notes.md`。
|
|
5
|
+
* 工具路径:`knowledge_index`(目录)→ `knowledge_digest`(某页分节)→ `knowledge_read`(整页)
|
|
6
|
+
* → `knowledge_search`(兜底)→ `knowledge_evidence`(取原文证据)。
|
|
7
|
+
* 替代原信息库的 knowledge_search/neighbors/scope/evidence(图遍历)。
|
|
8
|
+
*
|
|
9
|
+
* 本模块只负责「参数校验 + 调用 actions + 格式化文本」,不碰存储;
|
|
10
|
+
* 后端方法由 `createKbTools(kb)` 注入(actions.kbIndex/kbDigest/kbRead/kbSearch/kgEvidence)。
|
|
11
|
+
* @module context-manager/kb-tools
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
15
|
+
import { kbSectionLabel } from './kb.js'
|
|
16
|
+
|
|
17
|
+
/** knowledge_index 防抖窗口(毫秒):同会话内重复调用直接返回缓存。 */
|
|
18
|
+
export const KB_INDEX_CACHE_MS = 30_000
|
|
19
|
+
|
|
20
|
+
/** 输出预算(字符)。 */
|
|
21
|
+
export const KB_OUTPUT_LIMITS = {
|
|
22
|
+
lineChars: 200,
|
|
23
|
+
totalChars: 4000,
|
|
24
|
+
errorChars: 400,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const MAX_IDS = 16
|
|
28
|
+
|
|
29
|
+
/* -------------------------------------------------------------------------- */
|
|
30
|
+
/* 通用小工具 */
|
|
31
|
+
/* -------------------------------------------------------------------------- */
|
|
32
|
+
|
|
33
|
+
function isRecord(value) {
|
|
34
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function toErrorMessage(error) {
|
|
38
|
+
if (error instanceof Error) return error.message === '' ? error.name : error.message
|
|
39
|
+
try { return String(error) } catch { return '未知错误' }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function cleanInline(value) {
|
|
43
|
+
return typeof value === 'string' ? value.replace(/\s+/gu, ' ').trim() : ''
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function truncateCodePoints(text, maxChars) {
|
|
47
|
+
if (typeof text !== 'string') return ''
|
|
48
|
+
return [...text].slice(0, Math.max(0, maxChars)).join('')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function clampInteger(value, fallback, min, max) {
|
|
52
|
+
if (!Number.isFinite(value)) return fallback
|
|
53
|
+
return Math.min(max, Math.max(min, Math.trunc(value)))
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function joinBounded(lines, budget = KB_OUTPUT_LIMITS.totalChars, hint = '…(输出已截断:缩小范围或用更精确的参数)') {
|
|
57
|
+
const out = []
|
|
58
|
+
let used = 0
|
|
59
|
+
for (const line of lines) {
|
|
60
|
+
const text = String(line)
|
|
61
|
+
if (used + text.length + 1 > budget) {
|
|
62
|
+
out.push(hint)
|
|
63
|
+
break
|
|
64
|
+
}
|
|
65
|
+
out.push(text)
|
|
66
|
+
used += text.length + 1
|
|
67
|
+
}
|
|
68
|
+
return out.join('\n')
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function sessionIdOf(exec) {
|
|
72
|
+
if (!isRecord(exec)) return ''
|
|
73
|
+
const agent = exec.agent
|
|
74
|
+
if (!isRecord(agent)) return ''
|
|
75
|
+
const session = agent.session
|
|
76
|
+
if (!isRecord(session)) return ''
|
|
77
|
+
const id = session.id
|
|
78
|
+
return typeof id === 'string' && id !== '' ? id : ''
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function stringOutput() {
|
|
82
|
+
return {
|
|
83
|
+
schema: { type: 'string' },
|
|
84
|
+
render(_args, value) {
|
|
85
|
+
return [{ type: 'text', text: String(value) }]
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function formatNoSession(toolName) {
|
|
91
|
+
return `${toolName}:当前没有活动会话,无法访问信息库。`
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function formatToolError(toolName, error) {
|
|
95
|
+
return `${toolName} 失败:${truncateCodePoints(toErrorMessage(error), KB_OUTPUT_LIMITS.errorChars)}`
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function formatWhen(ts) {
|
|
99
|
+
if (!Number.isFinite(ts) || ts <= 0) return '—'
|
|
100
|
+
try {
|
|
101
|
+
const d = new Date(ts)
|
|
102
|
+
const pad = n => String(n).padStart(2, '0')
|
|
103
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
|
|
104
|
+
} catch { return '—' }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function statusMark(entry) {
|
|
108
|
+
if (entry.status === 'superseded') return '(已取代)'
|
|
109
|
+
if (entry.status === 'archived') return '(已归档)'
|
|
110
|
+
return ''
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/* -------------------------------------------------------------------------- */
|
|
114
|
+
/* 格式化(纯函数,便于单测) */
|
|
115
|
+
/* -------------------------------------------------------------------------- */
|
|
116
|
+
|
|
117
|
+
/** 目录:每页一行。 */
|
|
118
|
+
function formatIndex(result) {
|
|
119
|
+
const pages = Array.isArray(result?.pages) ? result.pages : []
|
|
120
|
+
const totals = isRecord(result?.totals) ? result.totals : { pages: pages.length, entries: 0 }
|
|
121
|
+
if (pages.length === 0) {
|
|
122
|
+
return '信息库目前为空(还没有提炼出项目事实)。随着对话进行,每轮结束会自动把项目级事实整理进来。'
|
|
123
|
+
}
|
|
124
|
+
const lines = [`项目信息库:${totals.pages} 页 / ${totals.entries} 条`, '']
|
|
125
|
+
for (const page of pages) {
|
|
126
|
+
const sections = isRecord(page.sections) ? Object.entries(page.sections).map(([id, n]) => `${kbSectionLabel(id)} ${n}`).join('、') : ''
|
|
127
|
+
lines.push(`- [${page.id === '' ? '(根)' : page.id}] ${page.title}:${page.entries} 条(${sections}),更新于 ${formatWhen(page.updatedAt)}`)
|
|
128
|
+
}
|
|
129
|
+
lines.push('', '提示:knowledge_digest(scope) 看某页分节;knowledge_read(id) 读整页;knowledge_search 兜底检索。')
|
|
130
|
+
return joinBounded(lines)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 分节视图。 */
|
|
134
|
+
function formatDigest(result) {
|
|
135
|
+
if (result?.ok === false || result === null) return '没有找到该页面。先用 knowledge_index 看目录,确认 scope 路径。'
|
|
136
|
+
const sections = Array.isArray(result?.sections) ? result.sections : []
|
|
137
|
+
const lines = [`# ${result.title}(${result.id === '' ? '(根)' : result.id})`, `更新于 ${formatWhen(result.updatedAt)}`, '']
|
|
138
|
+
if (sections.length === 0) lines.push('(本页暂无条目)')
|
|
139
|
+
for (const section of sections) {
|
|
140
|
+
lines.push(`## ${section.label}`)
|
|
141
|
+
for (const entry of section.entries ?? []) {
|
|
142
|
+
lines.push(`- [${entry.id}] ${truncateCodePoints(entry.text, KB_OUTPUT_LIMITS.lineChars)}${statusMark(entry)}`)
|
|
143
|
+
}
|
|
144
|
+
lines.push('')
|
|
145
|
+
}
|
|
146
|
+
return joinBounded(lines)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** 整页。 */
|
|
150
|
+
function formatRead(result) {
|
|
151
|
+
if (result?.ok === false || result === null) return '没有找到该页面。先用 knowledge_index 看目录。'
|
|
152
|
+
const lines = [`# ${result.title}(${result.id === '' ? '(根)' : result.id})`, `共 ${result.entries} 条,更新于 ${formatWhen(result.updatedAt)}`, '']
|
|
153
|
+
for (const section of result.sections ?? []) {
|
|
154
|
+
lines.push(`## ${section.label}`)
|
|
155
|
+
for (const entry of section.entries ?? []) {
|
|
156
|
+
const meta = [
|
|
157
|
+
entry.confidence,
|
|
158
|
+
entry.turn !== null && entry.turn !== undefined ? `第 ${entry.turn} 轮` : null,
|
|
159
|
+
entry.validFrom ? `自 ${formatWhen(entry.validFrom)}` : null,
|
|
160
|
+
].filter(Boolean).join(' · ')
|
|
161
|
+
lines.push(`- [${entry.id}] ${truncateCodePoints(entry.text, KB_OUTPUT_LIMITS.lineChars)}${statusMark(entry)}(${meta})`)
|
|
162
|
+
}
|
|
163
|
+
lines.push('')
|
|
164
|
+
}
|
|
165
|
+
const related = Array.isArray(result.related) ? result.related : []
|
|
166
|
+
if (related.length > 0) {
|
|
167
|
+
lines.push('相关页面:' + related.map(page => `[${page.id}] ${page.title}(${page.entries} 条)`).join(';'))
|
|
168
|
+
}
|
|
169
|
+
return joinBounded(lines)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** 检索命中。 */
|
|
173
|
+
function formatSearch(result, query) {
|
|
174
|
+
const hits = Array.isArray(result?.hits) ? result.hits : (Array.isArray(result) ? result : [])
|
|
175
|
+
if (hits.length === 0) return `没有命中「${query}」。提示:换关键词,或先用 knowledge_index 看目录、用 knowledge_digest 浏览相关页面。`
|
|
176
|
+
const lines = [`命中 ${hits.length} 条(「${query}」):`, '']
|
|
177
|
+
for (const hit of hits) {
|
|
178
|
+
lines.push(`- [${hit.id}](${hit.pageTitle} / ${kbSectionLabel(hit.section)})${truncateCodePoints(hit.text, KB_OUTPUT_LIMITS.lineChars)}${statusMark(hit)}`)
|
|
179
|
+
}
|
|
180
|
+
lines.push('', '提示:需要原文证据用 knowledge_evidence(ids);看整页用 knowledge_read。')
|
|
181
|
+
return joinBounded(lines)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** 证据摘录。 */
|
|
185
|
+
function formatEvidence(result) {
|
|
186
|
+
const items = Array.isArray(result?.items) ? result.items : (Array.isArray(result) ? result : [])
|
|
187
|
+
if (items.length === 0) return '没有取到证据(条目 id 可能已变化)。可先用 knowledge_search 确认 id。'
|
|
188
|
+
const lines = []
|
|
189
|
+
for (const item of items) {
|
|
190
|
+
// kgEvidence 返回的字段是 excerpt(不是 evidence/text)。
|
|
191
|
+
const text = typeof item?.excerpt === 'string' ? item.excerpt
|
|
192
|
+
: (typeof item?.evidence === 'string' ? item.evidence
|
|
193
|
+
: (typeof item?.text === 'string' ? item.text : ''))
|
|
194
|
+
const head = [`### [${item.id ?? ''}]`]
|
|
195
|
+
if (typeof item?.statement === 'string' && item.statement !== '') head.push(truncateCodePoints(item.statement, KB_OUTPUT_LIMITS.lineChars))
|
|
196
|
+
if (Number.isFinite(item?.turn)) head.push(`(第 ${item.turn} 轮)`)
|
|
197
|
+
lines.push(head.join(' '), truncateCodePoints(text, 1200), '')
|
|
198
|
+
}
|
|
199
|
+
return joinBounded(lines)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/* -------------------------------------------------------------------------- */
|
|
203
|
+
/* 工具定义 */
|
|
204
|
+
/* -------------------------------------------------------------------------- */
|
|
205
|
+
|
|
206
|
+
const INDEX_DESCRIPTION = [
|
|
207
|
+
'查看项目结构化信息库的目录(hub):每个项目/模块一页,含各分节条目数与更新时间。',
|
|
208
|
+
'信息库存放从对话中提炼的项目级持久事实(需求/约束/结构/决策/结果/接口/约定/当前状态)。',
|
|
209
|
+
'会话开始或需要旧信息时先用它看全貌,再用 knowledge_digest 深入某页。',
|
|
210
|
+
].join('')
|
|
211
|
+
|
|
212
|
+
const DIGEST_DESCRIPTION = [
|
|
213
|
+
'查看信息库中某一页的结构化分节摘要(需求/约束/结构/决策/结果/接口/约定/当前状态)。',
|
|
214
|
+
'scope 为页面路径(如 "context-manager/host"),从 knowledge_index 的目录获取。',
|
|
215
|
+
].join('')
|
|
216
|
+
|
|
217
|
+
const READ_DESCRIPTION = '读取信息库某一页的完整内容(全部条目 + 元数据 + 相关页面)。id 为页面路径,从 knowledge_index 获取。'
|
|
218
|
+
|
|
219
|
+
const SEARCH_DESCRIPTION = [
|
|
220
|
+
'在信息库中按关键词检索条目(兜底工具,返回所属页面与分节)。',
|
|
221
|
+
'优先用 knowledge_index / knowledge_digest 按结构浏览;检索用于快速定位具体事实。',
|
|
222
|
+
].join('')
|
|
223
|
+
|
|
224
|
+
const EVIDENCE_DESCRIPTION = '取信息库条目的原文证据摘录(有界)。用于核对该条目对应的原始对话依据。'
|
|
225
|
+
|
|
226
|
+
export function createKbTools(kb) {
|
|
227
|
+
const call = async (method, sessionId, args) => {
|
|
228
|
+
if (!isRecord(kb) || typeof kb[method] !== 'function') {
|
|
229
|
+
throw new Error(`信息库后端未启用(缺少 kb.${method})`)
|
|
230
|
+
}
|
|
231
|
+
return kb[method](sessionId, args)
|
|
232
|
+
}
|
|
233
|
+
// 信息库目录防抖(2026-12-03 加):同一会话在窗口内重复调用 knowledge_index
|
|
234
|
+
// 直接返回缓存并提示复用,防止模型把「看一眼信息库」当成默认动作而空转。
|
|
235
|
+
const indexCache = new Map()
|
|
236
|
+
const indexCacheGet = sessionId => {
|
|
237
|
+
const cached = indexCache.get(sessionId)
|
|
238
|
+
if (cached === undefined) return null
|
|
239
|
+
if (Date.now() - cached.at > KB_INDEX_CACHE_MS) {
|
|
240
|
+
indexCache.delete(sessionId)
|
|
241
|
+
return null
|
|
242
|
+
}
|
|
243
|
+
return cached
|
|
244
|
+
}
|
|
245
|
+
const indexCacheSet = (sessionId, value) => {
|
|
246
|
+
indexCache.delete(sessionId)
|
|
247
|
+
indexCache.set(sessionId, { value, at: Date.now() })
|
|
248
|
+
while (indexCache.size > 64) {
|
|
249
|
+
const oldest = indexCache.keys().next().value
|
|
250
|
+
if (oldest === undefined) break
|
|
251
|
+
indexCache.delete(oldest)
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return [
|
|
256
|
+
defineTool({
|
|
257
|
+
name: 'knowledge_index',
|
|
258
|
+
description: INDEX_DESCRIPTION,
|
|
259
|
+
parameters: {},
|
|
260
|
+
output: stringOutput(),
|
|
261
|
+
async execute(_args, exec) {
|
|
262
|
+
const sessionId = sessionIdOf(exec)
|
|
263
|
+
if (sessionId === '') return formatNoSession('knowledge_index')
|
|
264
|
+
const cached = indexCacheGet(sessionId)
|
|
265
|
+
if (cached !== null) {
|
|
266
|
+
const seconds = Math.max(1, Math.round((Date.now() - cached.at) / 1000))
|
|
267
|
+
return `${cached.value}\n\n(提示:本会话 ${seconds} 秒前刚查过信息库目录,内容未变——请直接使用上面的结果,不要重复调用 knowledge_index。)`
|
|
268
|
+
}
|
|
269
|
+
try {
|
|
270
|
+
const value = formatIndex(await call('index', sessionId, {}))
|
|
271
|
+
indexCacheSet(sessionId, value)
|
|
272
|
+
return value
|
|
273
|
+
} catch (error) {
|
|
274
|
+
return formatToolError('knowledge_index', error)
|
|
275
|
+
}
|
|
276
|
+
},
|
|
277
|
+
}),
|
|
278
|
+
|
|
279
|
+
defineTool({
|
|
280
|
+
name: 'knowledge_digest',
|
|
281
|
+
description: DIGEST_DESCRIPTION,
|
|
282
|
+
parameters: {
|
|
283
|
+
scope: {
|
|
284
|
+
type: 'string',
|
|
285
|
+
required: true,
|
|
286
|
+
description: '页面路径(scopePath.join("/"),如 "context-manager/host";根页面传空字符串)。',
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
output: stringOutput(),
|
|
290
|
+
async execute(args, exec) {
|
|
291
|
+
const sessionId = sessionIdOf(exec)
|
|
292
|
+
if (sessionId === '') return formatNoSession('knowledge_digest')
|
|
293
|
+
const scope = typeof args.scope === 'string' ? args.scope : ''
|
|
294
|
+
try {
|
|
295
|
+
return formatDigest(await call('digest', sessionId, { scope }))
|
|
296
|
+
} catch (error) {
|
|
297
|
+
return formatToolError('knowledge_digest', error)
|
|
298
|
+
}
|
|
299
|
+
},
|
|
300
|
+
}),
|
|
301
|
+
|
|
302
|
+
defineTool({
|
|
303
|
+
name: 'knowledge_read',
|
|
304
|
+
description: READ_DESCRIPTION,
|
|
305
|
+
parameters: {
|
|
306
|
+
id: {
|
|
307
|
+
type: 'string',
|
|
308
|
+
required: true,
|
|
309
|
+
description: '页面 id(scopePath.join("/"),从 knowledge_index 获取;根页面传空字符串)。',
|
|
310
|
+
},
|
|
311
|
+
},
|
|
312
|
+
output: stringOutput(),
|
|
313
|
+
async execute(args, exec) {
|
|
314
|
+
const sessionId = sessionIdOf(exec)
|
|
315
|
+
if (sessionId === '') return formatNoSession('knowledge_read')
|
|
316
|
+
const id = typeof args.id === 'string' ? args.id : ''
|
|
317
|
+
try {
|
|
318
|
+
return formatRead(await call('read', sessionId, { id }))
|
|
319
|
+
} catch (error) {
|
|
320
|
+
return formatToolError('knowledge_read', error)
|
|
321
|
+
}
|
|
322
|
+
},
|
|
323
|
+
}),
|
|
324
|
+
|
|
325
|
+
defineTool({
|
|
326
|
+
name: 'knowledge_search',
|
|
327
|
+
description: SEARCH_DESCRIPTION,
|
|
328
|
+
parameters: {
|
|
329
|
+
query: {
|
|
330
|
+
type: 'string',
|
|
331
|
+
required: true,
|
|
332
|
+
description: '简短检索词(项目内术语/模块名/事实关键词)。',
|
|
333
|
+
},
|
|
334
|
+
limit: {
|
|
335
|
+
type: 'integer',
|
|
336
|
+
description: '返回条数(默认 8,钳制到 1-50)。',
|
|
337
|
+
},
|
|
338
|
+
},
|
|
339
|
+
output: stringOutput(),
|
|
340
|
+
async execute(args, exec) {
|
|
341
|
+
const sessionId = sessionIdOf(exec)
|
|
342
|
+
if (sessionId === '') return formatNoSession('knowledge_search')
|
|
343
|
+
const query = cleanInline(args.query)
|
|
344
|
+
if (query === '') return 'knowledge_search:query 不能为空,请给出简短检索词。'
|
|
345
|
+
try {
|
|
346
|
+
const result = await call('search', sessionId, { query, limit: clampInteger(args.limit, 8, 1, 50) })
|
|
347
|
+
return formatSearch(result, query)
|
|
348
|
+
} catch (error) {
|
|
349
|
+
return formatToolError('knowledge_search', error)
|
|
350
|
+
}
|
|
351
|
+
},
|
|
352
|
+
}),
|
|
353
|
+
|
|
354
|
+
defineTool({
|
|
355
|
+
name: 'knowledge_evidence',
|
|
356
|
+
description: EVIDENCE_DESCRIPTION,
|
|
357
|
+
parameters: {
|
|
358
|
+
ids: {
|
|
359
|
+
type: 'array',
|
|
360
|
+
items: { type: 'string' },
|
|
361
|
+
required: true,
|
|
362
|
+
description: `条目 id 列表(最多 ${MAX_IDS} 个)。`,
|
|
363
|
+
},
|
|
364
|
+
maxChars: {
|
|
365
|
+
type: 'integer',
|
|
366
|
+
description: '每条证据最大字符数(默认 1200,钳制到 100-6000)。',
|
|
367
|
+
},
|
|
368
|
+
},
|
|
369
|
+
output: stringOutput(),
|
|
370
|
+
async execute(args, exec) {
|
|
371
|
+
const sessionId = sessionIdOf(exec)
|
|
372
|
+
if (sessionId === '') return formatNoSession('knowledge_evidence')
|
|
373
|
+
const ids = Array.isArray(args.ids) ? args.ids.filter(id => typeof id === 'string' && id !== '').slice(0, MAX_IDS) : []
|
|
374
|
+
if (ids.length === 0) return 'knowledge_evidence:请提供至少一个条目 id。'
|
|
375
|
+
try {
|
|
376
|
+
const result = await call('evidence', sessionId, { ids, maxChars: clampInteger(args.maxChars, 1200, 100, 6000) })
|
|
377
|
+
return formatEvidence(result)
|
|
378
|
+
} catch (error) {
|
|
379
|
+
return formatToolError('knowledge_evidence', error)
|
|
380
|
+
}
|
|
381
|
+
},
|
|
382
|
+
}),
|
|
383
|
+
]
|
|
384
|
+
}
|
package/lib/kb.js
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* context-manager — 结构化信息库(Structured Knowledge Base)。
|
|
3
|
+
*
|
|
4
|
+
* 设计蓝本:`docs/structured-kb-notes.md`(调研 Memory Bank / Basic Memory / repo-brain 等)。
|
|
5
|
+
*
|
|
6
|
+
* 定位:把「信息库(facts + edges)」重新组织为**信息库**:
|
|
7
|
+
* 项目 → 页面(按 scopePath 分组)→ 固定分节(8 类)→ 条目(fact)。
|
|
8
|
+
* 访问路径从「图遍历」改为信息库路径:
|
|
9
|
+
* index(目录)→ digest(某页分节)→ read(整页)→ search(兜底)→ evidence(取原文)。
|
|
10
|
+
*
|
|
11
|
+
* 本模块是**纯函数视图层**:输入现有 kg({facts, edges, scopes, turns}),输出信息库
|
|
12
|
+
* 视图对象;不碰 IO、不依赖 Cordis,可直接 `node --test` 用假 kg 测试。
|
|
13
|
+
* 数据层复用 facts(statement/kind/scopePath/confidence/status/validFrom/source),
|
|
14
|
+
* 不迁移、不重写存储。
|
|
15
|
+
* @module context-manager/kb
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** 固定分节(顺序即展示顺序)。kinds 是该节收纳的 fact.kind。 */
|
|
19
|
+
export const KB_SECTIONS = Object.freeze([
|
|
20
|
+
{ id: 'requirements', label: '需求与目标', kinds: ['requirement'] },
|
|
21
|
+
{ id: 'constraints', label: '约束与规则', kinds: ['constraint'] },
|
|
22
|
+
{ id: 'structure', label: '项目结构', kinds: ['structure'] },
|
|
23
|
+
{ id: 'decisions', label: '关键决策', kinds: ['decision'] },
|
|
24
|
+
{ id: 'results', label: '交付结果', kinds: ['result'] },
|
|
25
|
+
{ id: 'interfaces', label: '接口契约', kinds: ['interface'] },
|
|
26
|
+
{ id: 'conventions', label: '约定与规范', kinds: ['convention'] },
|
|
27
|
+
{ id: 'active', label: '当前状态', kinds: ['active', 'progress', 'status'] },
|
|
28
|
+
])
|
|
29
|
+
|
|
30
|
+
const KIND_TO_SECTION = (() => {
|
|
31
|
+
const map = new Map()
|
|
32
|
+
for (const section of KB_SECTIONS) for (const kind of section.kinds) map.set(kind, section.id)
|
|
33
|
+
return map
|
|
34
|
+
})()
|
|
35
|
+
|
|
36
|
+
/* -------------------------------------------------------------------------- */
|
|
37
|
+
/* 基础工具 */
|
|
38
|
+
/* -------------------------------------------------------------------------- */
|
|
39
|
+
|
|
40
|
+
function isRecord(value) {
|
|
41
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function factsOf(kg) {
|
|
45
|
+
const facts = isRecord(kg) ? kg.facts : null
|
|
46
|
+
if (Array.isArray(facts)) return facts.filter(isRecord)
|
|
47
|
+
if (isRecord(facts)) return Object.values(facts).filter(isRecord)
|
|
48
|
+
return []
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function scopeKeyOf(path) {
|
|
52
|
+
return Array.isArray(path) ? path.join('/') : ''
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function normalizeScopeInput(scope) {
|
|
56
|
+
if (Array.isArray(scope)) return scope.filter(part => typeof part === 'string' && part !== '')
|
|
57
|
+
if (typeof scope === 'string') return scope.split('/').filter(part => part !== '')
|
|
58
|
+
return []
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function sectionOfKind(kind) {
|
|
62
|
+
return KIND_TO_SECTION.get(typeof kind === 'string' ? kind : '') ?? 'active'
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function timestampOf(value) {
|
|
66
|
+
return Number.isFinite(value) ? value : 0
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 把 fact 转成信息库条目视图(不含证据原文)。 */
|
|
70
|
+
function entryOfFact(fact) {
|
|
71
|
+
const source = isRecord(fact.source) ? fact.source : {}
|
|
72
|
+
return {
|
|
73
|
+
id: typeof fact.id === 'string' ? fact.id : '',
|
|
74
|
+
text: typeof fact.statement === 'string' ? fact.statement : '',
|
|
75
|
+
section: sectionOfKind(fact.kind),
|
|
76
|
+
confidence: typeof fact.confidence === 'string' ? fact.confidence : 'medium',
|
|
77
|
+
status: typeof fact.status === 'string' ? fact.status : 'active',
|
|
78
|
+
validFrom: Number.isFinite(fact.validFrom) ? fact.validFrom : null,
|
|
79
|
+
validTo: Number.isFinite(fact.validTo) ? fact.validTo : null,
|
|
80
|
+
turn: Number.isFinite(source.turn) ? source.turn : (Number.isFinite(fact.turn) ? fact.turn : null),
|
|
81
|
+
cardId: typeof source.cardId === 'string' ? source.cardId : null,
|
|
82
|
+
updatedAt: timestampOf(fact.updatedAt ?? fact.createdAt),
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/* -------------------------------------------------------------------------- */
|
|
87
|
+
/* 页面(page) */
|
|
88
|
+
/* -------------------------------------------------------------------------- */
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 把 kg 组织成信息库页面数组(按 scopePath 分组,组内按分节归条目)。
|
|
92
|
+
* @param {object} kg - 现有图谱(facts/edges/scopes)。
|
|
93
|
+
* @param {{ includeArchived?: boolean }} [opts] - 是否包含 archived 条目(默认否)。
|
|
94
|
+
* @returns {Array<object>} 页面数组(按 scopePath 排序)。
|
|
95
|
+
*/
|
|
96
|
+
export function kbPagesOf(kg, opts = {}) {
|
|
97
|
+
const includeArchived = opts.includeArchived === true
|
|
98
|
+
const pages = new Map()
|
|
99
|
+
for (const fact of factsOf(kg)) {
|
|
100
|
+
const entry = entryOfFact(fact)
|
|
101
|
+
if (!includeArchived && entry.status === 'archived') continue
|
|
102
|
+
if (entry.text === '') continue
|
|
103
|
+
const path = Array.isArray(fact.scopePath) ? fact.scopePath : []
|
|
104
|
+
const key = scopeKeyOf(path)
|
|
105
|
+
let page = pages.get(key)
|
|
106
|
+
if (page === undefined) {
|
|
107
|
+
page = {
|
|
108
|
+
id: key,
|
|
109
|
+
title: path.length > 0 ? path[path.length - 1] : '项目概览',
|
|
110
|
+
scopePath: path,
|
|
111
|
+
sections: {},
|
|
112
|
+
entries: 0,
|
|
113
|
+
updatedAt: 0,
|
|
114
|
+
}
|
|
115
|
+
pages.set(key, page)
|
|
116
|
+
}
|
|
117
|
+
if (!Array.isArray(page.sections[entry.section])) page.sections[entry.section] = []
|
|
118
|
+
page.sections[entry.section].push(entry)
|
|
119
|
+
page.entries += 1
|
|
120
|
+
page.updatedAt = Math.max(page.updatedAt, entry.updatedAt)
|
|
121
|
+
}
|
|
122
|
+
// 组内条目按更新时间降序(信息库"最新在前")。
|
|
123
|
+
for (const page of pages.values()) {
|
|
124
|
+
for (const list of Object.values(page.sections)) list.sort((a, b) => b.updatedAt - a.updatedAt)
|
|
125
|
+
}
|
|
126
|
+
return [...pages.values()].sort((a, b) => {
|
|
127
|
+
if (a.scopePath.length !== b.scopePath.length) return a.scopePath.length - b.scopePath.length
|
|
128
|
+
return scopeKeyOf(a.scopePath).localeCompare(scopeKeyOf(b.scopePath))
|
|
129
|
+
})
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 按 id/路径找页面;找不到返回 null。 */
|
|
133
|
+
function pageById(pages, idOrScope) {
|
|
134
|
+
const key = typeof idOrScope === 'string' && !idOrScope.includes('/') && idOrScope !== ''
|
|
135
|
+
? idOrScope
|
|
136
|
+
: scopeKeyOf(normalizeScopeInput(idOrScope))
|
|
137
|
+
return pages.find(page => page.id === key) ?? null
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/* -------------------------------------------------------------------------- */
|
|
141
|
+
/* 视图:index / digest / read / search */
|
|
142
|
+
/* -------------------------------------------------------------------------- */
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* 信息库目录(hub):每页一行(标题/路径/条目数/分节计数/更新时间)。
|
|
146
|
+
* @param {object} kg - 图谱。
|
|
147
|
+
* @returns {{ pages: Array<object>, totals: { pages: number, entries: number } }}
|
|
148
|
+
*/
|
|
149
|
+
export function kbIndexOf(kg) {
|
|
150
|
+
const pages = kbPagesOf(kg)
|
|
151
|
+
return {
|
|
152
|
+
pages: pages.map(page => ({
|
|
153
|
+
id: page.id,
|
|
154
|
+
title: page.title,
|
|
155
|
+
scopePath: page.scopePath,
|
|
156
|
+
entries: page.entries,
|
|
157
|
+
sections: Object.fromEntries(Object.entries(page.sections).map(([id, list]) => [id, list.length])),
|
|
158
|
+
updatedAt: page.updatedAt,
|
|
159
|
+
})),
|
|
160
|
+
totals: {
|
|
161
|
+
pages: pages.length,
|
|
162
|
+
entries: pages.reduce((sum, page) => sum + page.entries, 0),
|
|
163
|
+
},
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 某页面的分节摘要(分节 + 条目,不含证据原文)。
|
|
169
|
+
* @param {object} kg - 图谱。
|
|
170
|
+
* @param {string|string[]} scope - 页面 id 或 scopePath。
|
|
171
|
+
* @returns {object|null} 页面分节视图;不存在返回 null。
|
|
172
|
+
*/
|
|
173
|
+
export function kbDigestOf(kg, scope) {
|
|
174
|
+
const page = pageById(kbPagesOf(kg), scope)
|
|
175
|
+
if (page === null) return null
|
|
176
|
+
return {
|
|
177
|
+
id: page.id,
|
|
178
|
+
title: page.title,
|
|
179
|
+
scopePath: page.scopePath,
|
|
180
|
+
updatedAt: page.updatedAt,
|
|
181
|
+
sections: KB_SECTIONS
|
|
182
|
+
.filter(section => Array.isArray(page.sections[section.id]) && page.sections[section.id].length > 0)
|
|
183
|
+
.map(section => ({ id: section.id, label: section.label, entries: page.sections[section.id] })),
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* 读完整页面(全部条目 + 相关页链接)。
|
|
189
|
+
* @param {object} kg - 图谱。
|
|
190
|
+
* @param {string} noteId - 页面 id(scopePath.join('/'),根页面为空串)。
|
|
191
|
+
* @returns {object|null}
|
|
192
|
+
*/
|
|
193
|
+
export function kbReadPage(kg, noteId) {
|
|
194
|
+
const page = pageById(kbPagesOf(kg, { includeArchived: true }), noteId)
|
|
195
|
+
if (page === null) return null
|
|
196
|
+
// 相关页:兄弟页(同父同级)+ 直接子页(信息库的"附近页面",替代图遍历)。
|
|
197
|
+
const parent = page.scopePath.slice(0, -1)
|
|
198
|
+
const related = kbPagesOf(kg)
|
|
199
|
+
.filter(other => {
|
|
200
|
+
if (other.id === page.id) return false
|
|
201
|
+
const isSibling = other.scopePath.length === page.scopePath.length
|
|
202
|
+
&& scopeKeyOf(other.scopePath.slice(0, -1)) === scopeKeyOf(parent)
|
|
203
|
+
const isChild = other.scopePath.length === page.scopePath.length + 1
|
|
204
|
+
&& scopeKeyOf(other.scopePath.slice(0, -1)) === page.id
|
|
205
|
+
return isSibling || isChild
|
|
206
|
+
})
|
|
207
|
+
.map(other => ({ id: other.id, title: other.title, entries: other.entries }))
|
|
208
|
+
return {
|
|
209
|
+
id: page.id,
|
|
210
|
+
title: page.title,
|
|
211
|
+
scopePath: page.scopePath,
|
|
212
|
+
updatedAt: page.updatedAt,
|
|
213
|
+
entries: page.entries,
|
|
214
|
+
sections: KB_SECTIONS
|
|
215
|
+
.filter(section => Array.isArray(page.sections[section.id]) && page.sections[section.id].length > 0)
|
|
216
|
+
.map(section => ({ id: section.id, label: section.label, entries: page.sections[section.id] })),
|
|
217
|
+
related,
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* 关键词检索条目(兜底):命中 statement 的条目,带所属页面/分节。
|
|
223
|
+
* @param {object} kg - 图谱。
|
|
224
|
+
* @param {string} query - 关键词(大小写不敏感,空格分词为 AND)。
|
|
225
|
+
* @param {{ limit?: number }} [opts] - 返回上限(默认 8,最大 50)。
|
|
226
|
+
* @returns {Array<object>} 命中条目。
|
|
227
|
+
*/
|
|
228
|
+
export function kbSearch(kg, query, opts = {}) {
|
|
229
|
+
const text = typeof query === 'string' ? query.trim().toLowerCase() : ''
|
|
230
|
+
if (text === '') return []
|
|
231
|
+
const terms = text.split(/\s+/u).filter(term => term !== '')
|
|
232
|
+
const limit = Number.isFinite(opts.limit) ? Math.min(50, Math.max(1, Math.trunc(opts.limit))) : 8
|
|
233
|
+
const hits = []
|
|
234
|
+
for (const fact of factsOf(kg)) {
|
|
235
|
+
const statement = typeof fact.statement === 'string' ? fact.statement.toLowerCase() : ''
|
|
236
|
+
if (statement === '') continue
|
|
237
|
+
if (!terms.every(term => statement.includes(term))) continue
|
|
238
|
+
const entry = entryOfFact(fact)
|
|
239
|
+
if (entry.status === 'archived') continue
|
|
240
|
+
const path = Array.isArray(fact.scopePath) ? fact.scopePath : []
|
|
241
|
+
hits.push({
|
|
242
|
+
...entry,
|
|
243
|
+
page: scopeKeyOf(path),
|
|
244
|
+
pageTitle: path.length > 0 ? path[path.length - 1] : '项目概览',
|
|
245
|
+
})
|
|
246
|
+
}
|
|
247
|
+
hits.sort((a, b) => b.updatedAt - a.updatedAt)
|
|
248
|
+
return hits.slice(0, limit)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** 分节标签(工具/格式化用)。 */
|
|
252
|
+
export function kbSectionLabel(sectionId) {
|
|
253
|
+
return KB_SECTIONS.find(section => section.id === sectionId)?.label ?? sectionId
|
|
254
|
+
}
|