dsh-tiddlywiki 0.16.13 → 0.16.14

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.
@@ -1,422 +1,422 @@
1
- /**
2
- * 会话相关 wiki 汇总(会话顶部「知识库」Tab 的后端)——把一次 DSH 会话(含其后代
3
- * subagent)在本会话中产生 / 读取 / 检索过的 wiki 笔记汇总成一篇 TW wikitext,写入
4
- * TW 的 volatile 命名空间 `$:/temp/dsh/session-summary/<会话ID>`。
5
- *
6
- * 判定来源(设计定稿,探查验证):
7
- * - Host 服务 `sessionQuery`(可选注入):`readSession(sessionId)` 返回完整事件日志
8
- * (events 升序),`traceSession` 返回祖先/后代树。绝不直接解析
9
- * `~/.dsh/sessions` 目录下的 session 文件——那是 zstd 压缩的。
10
- * - `tool/call` 事件精确记录每次 `tiddlywiki_*` 调用的 `name` 与
11
- * `arguments`(JSON 字符串)。
12
- * - `assistant/message` 事件 `message.content` 的 text 块可扫
13
- * `/dsh-tiddlywiki/tw/#...` 引用链接(视为「读取」)。
14
- *
15
- * 归类规则(§三 定稿):
16
- * 产生 📝 tiddlywiki_put / batch_put / rename(arguments 取 title)
17
- * 读取 👀 tiddlywiki_get(title)+ 助手回复里的 wiki 引用链接
18
- * 检索 🔍 search / recent(记关键词,不算单篇)
19
- * 范围 本会话 + 后代 subagent(traceSession 递归,仅子代理触达的笔记标注)
20
- *
21
- * 渲染(§四):写入 `$:/temp/...`——TW 5.4.1 默认 `$:/config/SyncFilter` 显式
22
- * `-[prefix[$:/temp/]]`(core/wiki/config/SyncFilter.tid),服务端 syncer 从不把
23
- * $:/temp 落盘:内存态、不进 git、TW 重启即消失(已实测:PUT 204、tiddlers/ 无文件、
24
- * git clean)。TW 用自己主题/链接/导航原生渲染,不另造 UI。
25
- *
26
- * @module dsh-tiddlywiki/host/session-summary
27
- */
28
- import type { TiddlyWebClient } from './tw-api.ts'
29
-
30
- /** 会话汇总 tiddler 的 $:/temp 命名空间前缀。 */
31
- export const SESSION_SUMMARY_PREFIX = '$:/temp/dsh/session-summary/'
32
-
33
- /** 会话内能触达 wiki 的 tiddlywiki_* 工具名(search/recent 只记检索记录,不算单篇)。 */
34
- const NOTE_TOOL_NAMES = new Set(['tiddlywiki_put', 'tiddlywiki_batch_put', 'tiddlywiki_rename', 'tiddlywiki_get', 'tiddlywiki_search', 'tiddlywiki_recent'])
35
-
36
- /** 每篇笔记的触达摘要(按 title 去重,时间取最近一次)。 */
37
- export interface NoteEntry {
38
- title: string
39
- action: 'produced' | 'read'
40
- /** 最近一次触达的 epoch ms。 */
41
- time: number
42
- /** 附加说明(如 rename 的旧标题)。 */
43
- detail?: string
44
- /** true = 仅由后代 subagent 触达过(本会话自己没碰过)。 */
45
- subagent: boolean
46
- }
47
-
48
- /** 一次检索类调用(search / recent),不算单篇笔记。 */
49
- export interface SearchRecord {
50
- kind: 'search' | 'recent'
51
- query: string
52
- tags: string[]
53
- time: number
54
- subagent: boolean
55
- }
56
-
57
- /** 一次会话扫描的收集结果。 */
58
- export interface Collected {
59
- produced: Map<string, NoteEntry>
60
- read: Map<string, NoteEntry>
61
- searches: SearchRecord[]
62
- }
63
-
64
- /**
65
- * 结构化 `sessionQuery` 服务脸(dsh-api-session-query 的极小子集,只声明本模块用到
66
- * 的方法;运行时实例是真实 Service,绝不是 Inspect 数据)。
67
- */
68
- export interface SessionQueryFace {
69
- /** Read and replay-validate one complete logical session log (events ascending). */
70
- readSession(sessionId: string): Promise<SessionLogSnapshot>
71
- /** Trace known ancestry and descendants from one corpus observation. */
72
- traceSession(sessionId: string, signal?: AbortSignal): Promise<SessionLineageTrace>
73
- }
74
-
75
- export interface SessionLogSnapshot {
76
- session: { id: string }
77
- events: SessionEvent[]
78
- }
79
-
80
- export interface SessionEvent {
81
- type: string
82
- seq: number
83
- time: number
84
- data: Record<string, unknown>
85
- }
86
-
87
- export interface SessionLineageTrace {
88
- descendants: SessionLineageNode[]
89
- }
90
-
91
- export interface SessionLineageNode {
92
- session: { header: { id: string } }
93
- descendants: SessionLineageNode[]
94
- }
95
-
96
- /** 递归收集后代树里所有 session id(不含根自身)。 */
97
- function collectDescendantIds(nodes: SessionLineageNode[] | undefined, out: string[]): void {
98
- if (!Array.isArray(nodes)) return
99
- for (const node of nodes) {
100
- const id = node?.session?.header?.id
101
- if (typeof id === 'string' && id.length > 0) {
102
- out.push(id)
103
- collectDescendantIds(node?.descendants, out)
104
- }
105
- }
106
- }
107
-
108
- /**
109
- * 汇总条目会直接写进 `[[标题]]` wikitext——标题既要能安全渲染、又不能制造死链。
110
- * 会话日志里常混入模型的示例/残缺写法(`#…`、`#标题`、带反引号的截断链接、
111
- * 控制字符等),这类收进来会被 TW 渲染成「佚失条目」;一律过滤。
112
- */
113
- function isPlausibleTitle(title: string): boolean {
114
- if (title.length === 0 || title.length > 300) return false
115
- if (title.trim().length === 0) return false
116
- if (/[\u0000-\u001f\u007f]/.test(title)) return false // 控制字符 / 换行
117
- if (/[\]|`#]/.test(title)) return false // 会破坏 [[…]] 链接语法
118
- if (title.startsWith('…') || title === '标题') return false // 占位 / 示例写法
119
- return true
120
- }
121
-
122
- /** 记录一篇笔记的触达;同标题合并(时间取最新、detail 取最新、subagent 取 AND)。 */
123
- function record(map: Map<string, NoteEntry>, entry: NoteEntry): void {
124
- if (entry.title.startsWith('$:/')) return
125
- if (!isPlausibleTitle(entry.title)) return
126
- const prev = map.get(entry.title)
127
- if (prev !== undefined) {
128
- prev.time = Math.max(prev.time, entry.time)
129
- if (entry.detail !== undefined) prev.detail = entry.detail
130
- prev.subagent = prev.subagent && entry.subagent
131
- return
132
- }
133
- map.set(entry.title, { ...entry })
134
- }
135
-
136
- /** 扫助手回复文本里的 `/dsh-tiddlywiki/tw/#标题` 引用链接 → 读取。 */
137
- function scanRefs(text: string, time: number, subagent: boolean, collected: Collected): void {
138
- // 只认到下一个 `)` / 空白 / `]` / `#` 为止——`#` 会截断后续碎片(模型示例常写成
139
- // `#…` 或 `#标题`,这些由 isPlausibleTitle 在 record 时过滤)。
140
- const re = /\/dsh-tiddlywiki\/tw\/#([^#)\s\]]+)/g
141
- let m: RegExpExecArray | null
142
- while ((m = re.exec(text)) !== null) {
143
- const raw = m[1] ?? ''
144
- if (raw.length === 0) continue
145
- let title = raw
146
- try {
147
- title = decodeURIComponent(raw)
148
- } catch {
149
- /* keep raw on malformed percent-encoding */
150
- }
151
- if (title.length === 0) continue
152
- record(collected.read, { title, action: 'read', time, subagent })
153
- }
154
- }
155
-
156
- /** 扫描一次会话的事件日志,按 §三 规则收集笔记触达与检索记录。 */
157
- function scanSnapshot(snap: SessionLogSnapshot | undefined, subagent: boolean, collected: Collected): void {
158
- const events = snap?.events
159
- if (!Array.isArray(events)) return
160
- for (const ev of events) {
161
- const type = ev?.type
162
- const t = typeof ev?.time === 'number' ? ev.time : Date.now()
163
- if (type === 'tool/call') {
164
- const name = ev.data?.name
165
- if (typeof name !== 'string' || !NOTE_TOOL_NAMES.has(name)) continue
166
- let args: Record<string, unknown> = {}
167
- if (typeof ev.data?.arguments === 'string') {
168
- try {
169
- args = JSON.parse(ev.data.arguments) as Record<string, unknown>
170
- } catch {
171
- args = {}
172
- }
173
- }
174
- switch (name) {
175
- case 'tiddlywiki_put':
176
- if (typeof args.title === 'string' && args.title.length > 0) {
177
- record(collected.produced, { title: args.title, action: 'produced', time: t, subagent })
178
- }
179
- break
180
- case 'tiddlywiki_batch_put':
181
- if (Array.isArray(args.items)) {
182
- for (const item of args.items) {
183
- if (item !== null && typeof item === 'object' && typeof (item as { title?: unknown }).title === 'string') {
184
- const title = (item as { title: string }).title
185
- if (title.length > 0) record(collected.produced, { title, action: 'produced', time: t, subagent })
186
- }
187
- }
188
- }
189
- break
190
- case 'tiddlywiki_rename':
191
- if (typeof args.newTitle === 'string' && args.newTitle.length > 0) {
192
- const old = typeof args.oldTitle === 'string' && args.oldTitle.length > 0 ? args.oldTitle : undefined
193
- record(collected.produced, {
194
- title: args.newTitle,
195
- action: 'produced',
196
- time: t,
197
- detail: old !== undefined ? `重命名自「${old}」` : undefined,
198
- subagent,
199
- })
200
- }
201
- break
202
- case 'tiddlywiki_get':
203
- if (typeof args.title === 'string' && args.title.length > 0) {
204
- record(collected.read, { title: args.title, action: 'read', time: t, subagent })
205
- }
206
- break
207
- case 'tiddlywiki_search': {
208
- const query = typeof args.query === 'string' ? args.query : ''
209
- const tags = Array.isArray(args.tags) ? args.tags.filter((x): x is string => typeof x === 'string') : []
210
- collected.searches.push({ kind: 'search', query, tags, time: t, subagent })
211
- break
212
- }
213
- case 'tiddlywiki_recent':
214
- collected.searches.push({ kind: 'recent', query: '', tags: [], time: t, subagent })
215
- break
216
- }
217
- } else if (type === 'assistant/message') {
218
- const message = ev.data?.message
219
- const content = message !== null && typeof message === 'object' ? (message as { content?: unknown }).content : undefined
220
- if (Array.isArray(content)) {
221
- for (const block of content) {
222
- if (block === null || typeof block !== 'object') continue
223
- const b = block as { type?: unknown; text?: unknown }
224
- if (b.type === 'text' && typeof b.text === 'string' && b.text.length > 0) {
225
- scanRefs(b.text, t, subagent, collected)
226
- }
227
- }
228
- }
229
- }
230
- }
231
- }
232
-
233
- /** 当前状态(存在?标签?修改时间?摘要)。 */
234
- interface TitleState {
235
- exists: boolean
236
- tags: string[]
237
- modified?: string
238
- snippet?: string
239
- }
240
-
241
- /** 并发(8 路)查询每篇笔记的当前状态(404 → 不存在/已删除)。 */
242
- async function enrichTitles(client: TiddlyWebClient, titles: string[]): Promise<Map<string, TitleState>> {
243
- const out = new Map<string, TitleState>()
244
- const enquire = async (title: string): Promise<[string, TitleState]> => {
245
- try {
246
- const t = await client.get(title)
247
- if (t === undefined) return [title, { exists: false, tags: [] }]
248
- const flat = typeof t.text === 'string' ? t.text.replace(/\s+/g, ' ').trim() : ''
249
- return [title, {
250
- exists: true,
251
- tags: t.tags ?? [],
252
- modified: typeof t.modified === 'string' ? t.modified : undefined,
253
- snippet: flat.length > 48 ? `${flat.slice(0, 48)}…` : flat,
254
- }]
255
- } catch {
256
- return [title, { exists: false, tags: [] }]
257
- }
258
- }
259
- // Bounded batches: parallel within a batch, insertion order preserved across
260
- // batches (Map order = the caller's title order, same as the old sequential).
261
- for (let i = 0; i < titles.length; i += 8) {
262
- const batch = titles.slice(i, i + 8)
263
- for (const [title, state] of await Promise.all(batch.map(enquire))) out.set(title, state)
264
- }
265
- return out
266
- }
267
-
268
- /** epoch ms → 本地 `YYYY-MM-DD HH:mm`。 */
269
- function fmtTime(ms: number): string {
270
- const d = new Date(ms)
271
- if (Number.isNaN(d.getTime())) return ''
272
- const p = (n: number): string => String(n).padStart(2, '0')
273
- return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
274
- }
275
-
276
- /** TW modified ISO → 本地时间(解析失败则原样返回)。 */
277
- function fmtModified(iso: string | undefined): string {
278
- if (iso === undefined || iso.length === 0) return ''
279
- const ms = Date.parse(iso)
280
- return Number.isNaN(ms) ? iso : fmtTime(ms)
281
- }
282
-
283
- /** 组装分组 wikitext:产生 / 读取(未产生过的)/ 检索记录。 */
284
- function buildWikitext(
285
- sessionId: string,
286
- collected: Collected,
287
- producedTitles: string[],
288
- readTitles: string[],
289
- stateByTitle: Map<string, TitleState>,
290
- ): string {
291
- const lines: string[] = []
292
- lines.push('! 会话相关 wiki 汇总')
293
- lines.push('')
294
- lines.push(
295
- `本页列出会话 \`${sessionId}\`(含其后代子代理)在本会话中产生 / 读取 / 检索过的知识库笔记。`,
296
- )
297
- lines.push('')
298
- const producedCount = producedTitles.length
299
- const readCount = readTitles.length
300
- const searchCount = collected.searches.length
301
- if (producedCount + readCount + searchCount === 0) {
302
- lines.push('> 本会话暂时没有产生、读取或检索过任何知识库笔记。')
303
- lines.push('>')
304
- lines.push('> 本页为会话自动生成的临时汇总(`$:/temp`,不落盘、不进 git,重启 TW 即消失);需要时点 Tab 顶栏的「🔄 刷新」重新生成。')
305
- return lines.join('\n')
306
- }
307
- lines.push(
308
- '| 产生 📝 | 读取 👀 | 检索 🔍 | 涉及会话 |',
309
- '| --- | --- | --- | --- |',
310
- `| ${producedCount} | ${readCount} | ${searchCount} | ${collected.produced.size + readTitles.length > 0 ? '本会话 + 子代理' : '本会话'} |`,
311
- )
312
- lines.push('')
313
-
314
- const entryLine = (title: string, state: TitleState | undefined, entry: NoteEntry): string => {
315
- const bits: string[] = [`[[${title}]]`]
316
- if (state === undefined || !state.exists) {
317
- bits.push('⚠️ 已删除/不存在')
318
- } else {
319
- if (state.tags.length > 0) bits.push(`标签 ${state.tags.slice(0, 6).join('、')}${state.tags.length > 6 ? '…' : ''}`)
320
- const mod = fmtModified(state.modified)
321
- if (mod.length > 0) bits.push(`修改 ${mod}`)
322
- }
323
- const t = fmtTime(entry.time)
324
- if (t.length > 0) bits.push(`会话内 ${t}`)
325
- if (entry.detail !== undefined) bits.push(entry.detail)
326
- if (entry.subagent) bits.push('(子代理)')
327
- return `* ${bits.join(' · ')}`
328
- }
329
-
330
- if (producedCount > 0) {
331
- lines.push('!!! 📝 产生')
332
- for (const title of producedTitles) {
333
- const entry = collected.produced.get(title)
334
- if (entry !== undefined) lines.push(entryLine(title, stateByTitle.get(title), entry))
335
- }
336
- lines.push('')
337
- }
338
- if (readCount > 0) {
339
- lines.push('!!! 👀 读取')
340
- for (const title of readTitles) {
341
- const entry = collected.read.get(title)
342
- if (entry !== undefined) lines.push(entryLine(title, stateByTitle.get(title), entry))
343
- }
344
- lines.push('')
345
- }
346
- if (searchCount > 0) {
347
- lines.push('!!! 🔍 检索记录')
348
- for (const r of collected.searches) {
349
- const bits: string[] = []
350
- if (r.kind === 'search') {
351
- bits.push(`\`tiddlywiki_search\` query=「${r.query.length > 0 ? r.query : '(空)'}」`)
352
- if (r.tags.length > 0) bits.push(`tags ${r.tags.join('、')}`)
353
- } else {
354
- bits.push('`tiddlywiki_recent`(最近修改)')
355
- }
356
- const t = fmtTime(r.time)
357
- if (t.length > 0) bits.push(t)
358
- if (r.subagent) bits.push('(子代理)')
359
- lines.push(`* ${bits.join(' · ')}`)
360
- }
361
- lines.push('')
362
- }
363
- lines.push('---')
364
- lines.push('> 本页为会话自动生成的临时汇总(`$:/temp`,不落盘、不进 git,重启 TW 即消失);需要时点 Tab 顶栏的「🔄 刷新」重新生成。')
365
- return lines.join('\n')
366
- }
367
-
368
- export interface SessionSummaryResult {
369
- title: string
370
- counts: { produced: number; read: number; searches: number; sessions: number }
371
- empty: boolean
372
- generatedAt: string
373
- }
374
-
375
- /**
376
- * 生成并写入一篇会话汇总 tiddler($:/temp,volatile)。
377
- * @param client 可用 TW 客户端(调用方已保证 wiki 服务在线)。
378
- * @param sq sessionQuery 服务(调用方已保证可用)。
379
- * @param sessionId 目标会话 id(本会话 + 后代 subagent)。
380
- */
381
- export async function writeSessionSummary(client: TiddlyWebClient, sq: SessionQueryFace, sessionId: string): Promise<SessionSummaryResult> {
382
- // 1) 会话范围:自身 + traceSession 后代树(递归)。trace 失败(会话已归档/不存在)
383
- // 就只汇总自身,绝不让单次失败拖垮整页。
384
- const ids: string[] = [sessionId]
385
- try {
386
- const trace = await sq.traceSession(sessionId, AbortSignal.timeout(10_000))
387
- collectDescendantIds(trace?.descendants, ids)
388
- } catch {
389
- /* trace unavailable → self only */
390
- }
391
-
392
- // 2) 逐个会话读完整事件日志并收集(任一失败跳过,其余照常)。
393
- const collected: Collected = { produced: new Map(), read: new Map(), searches: [] }
394
- for (const id of ids) {
395
- try {
396
- const snap = await sq.readSession(id)
397
- scanSnapshot(snap, id !== sessionId, collected)
398
- } catch {
399
- /* one bad session must not fail the whole summary */
400
- }
401
- }
402
-
403
- // 3) 产生优先:同时被产生+读取的笔记只列在「产生」,读取区只放未产生过的。
404
- const producedTitles = [...collected.produced.keys()].sort((a, b) => (collected.produced.get(b)?.time ?? 0) - (collected.produced.get(a)?.time ?? 0))
405
- const readTitles = [...collected.read.keys()]
406
- .filter((t) => !collected.produced.has(t))
407
- .sort((a, b) => (collected.read.get(b)?.time ?? 0) - (collected.read.get(a)?.time ?? 0))
408
- collected.searches.sort((a, b) => b.time - a.time)
409
-
410
- // 4) 查询当前状态(存在?标签?时间?)→ 组装 wikitext → PUT volatile tiddler。
411
- const stateByTitle = await enrichTitles(client, [...new Set([...producedTitles, ...readTitles])])
412
- const text = buildWikitext(sessionId, collected, producedTitles, readTitles, stateByTitle)
413
- const title = `${SESSION_SUMMARY_PREFIX}${sessionId}`
414
- await client.put({ title, text, type: 'text/vnd.tiddlywiki', tags: [] })
415
-
416
- return {
417
- title,
418
- counts: { produced: producedTitles.length, read: readTitles.length, searches: collected.searches.length, sessions: ids.length },
419
- empty: producedTitles.length + readTitles.length + collected.searches.length === 0,
420
- generatedAt: new Date().toISOString(),
421
- }
422
- }
1
+ /**
2
+ * 会话相关 wiki 汇总(会话顶部「知识库」Tab 的后端)——把一次 DSH 会话(含其后代
3
+ * subagent)在本会话中产生 / 读取 / 检索过的 wiki 笔记汇总成一篇 TW wikitext,写入
4
+ * TW 的 volatile 命名空间 `$:/temp/dsh/session-summary/<会话ID>`。
5
+ *
6
+ * 判定来源(设计定稿,探查验证):
7
+ * - Host 服务 `sessionQuery`(可选注入):`readSession(sessionId)` 返回完整事件日志
8
+ * (events 升序),`traceSession` 返回祖先/后代树。绝不直接解析
9
+ * `~/.dsh/sessions` 目录下的 session 文件——那是 zstd 压缩的。
10
+ * - `tool/call` 事件精确记录每次 `tiddlywiki_*` 调用的 `name` 与
11
+ * `arguments`(JSON 字符串)。
12
+ * - `assistant/message` 事件 `message.content` 的 text 块可扫
13
+ * `/dsh-tiddlywiki/tw/#...` 引用链接(视为「读取」)。
14
+ *
15
+ * 归类规则(§三 定稿):
16
+ * 产生 📝 tiddlywiki_put / batch_put / rename(arguments 取 title)
17
+ * 读取 👀 tiddlywiki_get(title)+ 助手回复里的 wiki 引用链接
18
+ * 检索 🔍 search / recent(记关键词,不算单篇)
19
+ * 范围 本会话 + 后代 subagent(traceSession 递归,仅子代理触达的笔记标注)
20
+ *
21
+ * 渲染(§四):写入 `$:/temp/...`——TW 5.4.1 默认 `$:/config/SyncFilter` 显式
22
+ * `-[prefix[$:/temp/]]`(core/wiki/config/SyncFilter.tid),服务端 syncer 从不把
23
+ * $:/temp 落盘:内存态、不进 git、TW 重启即消失(已实测:PUT 204、tiddlers/ 无文件、
24
+ * git clean)。TW 用自己主题/链接/导航原生渲染,不另造 UI。
25
+ *
26
+ * @module dsh-tiddlywiki/host/session-summary
27
+ */
28
+ import type { TiddlyWebClient } from './tw-api.ts'
29
+
30
+ /** 会话汇总 tiddler 的 $:/temp 命名空间前缀。 */
31
+ export const SESSION_SUMMARY_PREFIX = '$:/temp/dsh/session-summary/'
32
+
33
+ /** 会话内能触达 wiki 的 tiddlywiki_* 工具名(search/recent 只记检索记录,不算单篇)。 */
34
+ const NOTE_TOOL_NAMES = new Set(['tiddlywiki_put', 'tiddlywiki_batch_put', 'tiddlywiki_rename', 'tiddlywiki_get', 'tiddlywiki_search', 'tiddlywiki_recent'])
35
+
36
+ /** 每篇笔记的触达摘要(按 title 去重,时间取最近一次)。 */
37
+ export interface NoteEntry {
38
+ title: string
39
+ action: 'produced' | 'read'
40
+ /** 最近一次触达的 epoch ms。 */
41
+ time: number
42
+ /** 附加说明(如 rename 的旧标题)。 */
43
+ detail?: string
44
+ /** true = 仅由后代 subagent 触达过(本会话自己没碰过)。 */
45
+ subagent: boolean
46
+ }
47
+
48
+ /** 一次检索类调用(search / recent),不算单篇笔记。 */
49
+ export interface SearchRecord {
50
+ kind: 'search' | 'recent'
51
+ query: string
52
+ tags: string[]
53
+ time: number
54
+ subagent: boolean
55
+ }
56
+
57
+ /** 一次会话扫描的收集结果。 */
58
+ export interface Collected {
59
+ produced: Map<string, NoteEntry>
60
+ read: Map<string, NoteEntry>
61
+ searches: SearchRecord[]
62
+ }
63
+
64
+ /**
65
+ * 结构化 `sessionQuery` 服务脸(dsh-api-session-query 的极小子集,只声明本模块用到
66
+ * 的方法;运行时实例是真实 Service,绝不是 Inspect 数据)。
67
+ */
68
+ export interface SessionQueryFace {
69
+ /** Read and replay-validate one complete logical session log (events ascending). */
70
+ readSession(sessionId: string): Promise<SessionLogSnapshot>
71
+ /** Trace known ancestry and descendants from one corpus observation. */
72
+ traceSession(sessionId: string, signal?: AbortSignal): Promise<SessionLineageTrace>
73
+ }
74
+
75
+ export interface SessionLogSnapshot {
76
+ session: { id: string }
77
+ events: SessionEvent[]
78
+ }
79
+
80
+ export interface SessionEvent {
81
+ type: string
82
+ seq: number
83
+ time: number
84
+ data: Record<string, unknown>
85
+ }
86
+
87
+ export interface SessionLineageTrace {
88
+ descendants: SessionLineageNode[]
89
+ }
90
+
91
+ export interface SessionLineageNode {
92
+ session: { header: { id: string } }
93
+ descendants: SessionLineageNode[]
94
+ }
95
+
96
+ /** 递归收集后代树里所有 session id(不含根自身)。 */
97
+ function collectDescendantIds(nodes: SessionLineageNode[] | undefined, out: string[]): void {
98
+ if (!Array.isArray(nodes)) return
99
+ for (const node of nodes) {
100
+ const id = node?.session?.header?.id
101
+ if (typeof id === 'string' && id.length > 0) {
102
+ out.push(id)
103
+ collectDescendantIds(node?.descendants, out)
104
+ }
105
+ }
106
+ }
107
+
108
+ /**
109
+ * 汇总条目会直接写进 `[[标题]]` wikitext——标题既要能安全渲染、又不能制造死链。
110
+ * 会话日志里常混入模型的示例/残缺写法(`#…`、`#标题`、带反引号的截断链接、
111
+ * 控制字符等),这类收进来会被 TW 渲染成「佚失条目」;一律过滤。
112
+ */
113
+ function isPlausibleTitle(title: string): boolean {
114
+ if (title.length === 0 || title.length > 300) return false
115
+ if (title.trim().length === 0) return false
116
+ if (/[\u0000-\u001f\u007f]/.test(title)) return false // 控制字符 / 换行
117
+ if (/[\]|`#]/.test(title)) return false // 会破坏 [[…]] 链接语法
118
+ if (title.startsWith('…') || title === '标题') return false // 占位 / 示例写法
119
+ return true
120
+ }
121
+
122
+ /** 记录一篇笔记的触达;同标题合并(时间取最新、detail 取最新、subagent 取 AND)。 */
123
+ function record(map: Map<string, NoteEntry>, entry: NoteEntry): void {
124
+ if (entry.title.startsWith('$:/')) return
125
+ if (!isPlausibleTitle(entry.title)) return
126
+ const prev = map.get(entry.title)
127
+ if (prev !== undefined) {
128
+ prev.time = Math.max(prev.time, entry.time)
129
+ if (entry.detail !== undefined) prev.detail = entry.detail
130
+ prev.subagent = prev.subagent && entry.subagent
131
+ return
132
+ }
133
+ map.set(entry.title, { ...entry })
134
+ }
135
+
136
+ /** 扫助手回复文本里的 `/dsh-tiddlywiki/tw/#标题` 引用链接 → 读取。 */
137
+ function scanRefs(text: string, time: number, subagent: boolean, collected: Collected): void {
138
+ // 只认到下一个 `)` / 空白 / `]` / `#` 为止——`#` 会截断后续碎片(模型示例常写成
139
+ // `#…` 或 `#标题`,这些由 isPlausibleTitle 在 record 时过滤)。
140
+ const re = /\/dsh-tiddlywiki\/tw\/#([^#)\s\]]+)/g
141
+ let m: RegExpExecArray | null
142
+ while ((m = re.exec(text)) !== null) {
143
+ const raw = m[1] ?? ''
144
+ if (raw.length === 0) continue
145
+ let title = raw
146
+ try {
147
+ title = decodeURIComponent(raw)
148
+ } catch {
149
+ /* keep raw on malformed percent-encoding */
150
+ }
151
+ if (title.length === 0) continue
152
+ record(collected.read, { title, action: 'read', time, subagent })
153
+ }
154
+ }
155
+
156
+ /** 扫描一次会话的事件日志,按 §三 规则收集笔记触达与检索记录。 */
157
+ function scanSnapshot(snap: SessionLogSnapshot | undefined, subagent: boolean, collected: Collected): void {
158
+ const events = snap?.events
159
+ if (!Array.isArray(events)) return
160
+ for (const ev of events) {
161
+ const type = ev?.type
162
+ const t = typeof ev?.time === 'number' ? ev.time : Date.now()
163
+ if (type === 'tool/call') {
164
+ const name = ev.data?.name
165
+ if (typeof name !== 'string' || !NOTE_TOOL_NAMES.has(name)) continue
166
+ let args: Record<string, unknown> = {}
167
+ if (typeof ev.data?.arguments === 'string') {
168
+ try {
169
+ args = JSON.parse(ev.data.arguments) as Record<string, unknown>
170
+ } catch {
171
+ args = {}
172
+ }
173
+ }
174
+ switch (name) {
175
+ case 'tiddlywiki_put':
176
+ if (typeof args.title === 'string' && args.title.length > 0) {
177
+ record(collected.produced, { title: args.title, action: 'produced', time: t, subagent })
178
+ }
179
+ break
180
+ case 'tiddlywiki_batch_put':
181
+ if (Array.isArray(args.items)) {
182
+ for (const item of args.items) {
183
+ if (item !== null && typeof item === 'object' && typeof (item as { title?: unknown }).title === 'string') {
184
+ const title = (item as { title: string }).title
185
+ if (title.length > 0) record(collected.produced, { title, action: 'produced', time: t, subagent })
186
+ }
187
+ }
188
+ }
189
+ break
190
+ case 'tiddlywiki_rename':
191
+ if (typeof args.newTitle === 'string' && args.newTitle.length > 0) {
192
+ const old = typeof args.oldTitle === 'string' && args.oldTitle.length > 0 ? args.oldTitle : undefined
193
+ record(collected.produced, {
194
+ title: args.newTitle,
195
+ action: 'produced',
196
+ time: t,
197
+ detail: old !== undefined ? `重命名自「${old}」` : undefined,
198
+ subagent,
199
+ })
200
+ }
201
+ break
202
+ case 'tiddlywiki_get':
203
+ if (typeof args.title === 'string' && args.title.length > 0) {
204
+ record(collected.read, { title: args.title, action: 'read', time: t, subagent })
205
+ }
206
+ break
207
+ case 'tiddlywiki_search': {
208
+ const query = typeof args.query === 'string' ? args.query : ''
209
+ const tags = Array.isArray(args.tags) ? args.tags.filter((x): x is string => typeof x === 'string') : []
210
+ collected.searches.push({ kind: 'search', query, tags, time: t, subagent })
211
+ break
212
+ }
213
+ case 'tiddlywiki_recent':
214
+ collected.searches.push({ kind: 'recent', query: '', tags: [], time: t, subagent })
215
+ break
216
+ }
217
+ } else if (type === 'assistant/message') {
218
+ const message = ev.data?.message
219
+ const content = message !== null && typeof message === 'object' ? (message as { content?: unknown }).content : undefined
220
+ if (Array.isArray(content)) {
221
+ for (const block of content) {
222
+ if (block === null || typeof block !== 'object') continue
223
+ const b = block as { type?: unknown; text?: unknown }
224
+ if (b.type === 'text' && typeof b.text === 'string' && b.text.length > 0) {
225
+ scanRefs(b.text, t, subagent, collected)
226
+ }
227
+ }
228
+ }
229
+ }
230
+ }
231
+ }
232
+
233
+ /** 当前状态(存在?标签?修改时间?摘要)。 */
234
+ interface TitleState {
235
+ exists: boolean
236
+ tags: string[]
237
+ modified?: string
238
+ snippet?: string
239
+ }
240
+
241
+ /** 并发(8 路)查询每篇笔记的当前状态(404 → 不存在/已删除)。 */
242
+ async function enrichTitles(client: TiddlyWebClient, titles: string[]): Promise<Map<string, TitleState>> {
243
+ const out = new Map<string, TitleState>()
244
+ const enquire = async (title: string): Promise<[string, TitleState]> => {
245
+ try {
246
+ const t = await client.get(title)
247
+ if (t === undefined) return [title, { exists: false, tags: [] }]
248
+ const flat = typeof t.text === 'string' ? t.text.replace(/\s+/g, ' ').trim() : ''
249
+ return [title, {
250
+ exists: true,
251
+ tags: t.tags ?? [],
252
+ modified: typeof t.modified === 'string' ? t.modified : undefined,
253
+ snippet: flat.length > 48 ? `${flat.slice(0, 48)}…` : flat,
254
+ }]
255
+ } catch {
256
+ return [title, { exists: false, tags: [] }]
257
+ }
258
+ }
259
+ // Bounded batches: parallel within a batch, insertion order preserved across
260
+ // batches (Map order = the caller's title order, same as the old sequential).
261
+ for (let i = 0; i < titles.length; i += 8) {
262
+ const batch = titles.slice(i, i + 8)
263
+ for (const [title, state] of await Promise.all(batch.map(enquire))) out.set(title, state)
264
+ }
265
+ return out
266
+ }
267
+
268
+ /** epoch ms → 本地 `YYYY-MM-DD HH:mm`。 */
269
+ function fmtTime(ms: number): string {
270
+ const d = new Date(ms)
271
+ if (Number.isNaN(d.getTime())) return ''
272
+ const p = (n: number): string => String(n).padStart(2, '0')
273
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
274
+ }
275
+
276
+ /** TW modified ISO → 本地时间(解析失败则原样返回)。 */
277
+ function fmtModified(iso: string | undefined): string {
278
+ if (iso === undefined || iso.length === 0) return ''
279
+ const ms = Date.parse(iso)
280
+ return Number.isNaN(ms) ? iso : fmtTime(ms)
281
+ }
282
+
283
+ /** 组装分组 wikitext:产生 / 读取(未产生过的)/ 检索记录。 */
284
+ function buildWikitext(
285
+ sessionId: string,
286
+ collected: Collected,
287
+ producedTitles: string[],
288
+ readTitles: string[],
289
+ stateByTitle: Map<string, TitleState>,
290
+ ): string {
291
+ const lines: string[] = []
292
+ lines.push('! 会话相关 wiki 汇总')
293
+ lines.push('')
294
+ lines.push(
295
+ `本页列出会话 \`${sessionId}\`(含其后代子代理)在本会话中产生 / 读取 / 检索过的知识库笔记。`,
296
+ )
297
+ lines.push('')
298
+ const producedCount = producedTitles.length
299
+ const readCount = readTitles.length
300
+ const searchCount = collected.searches.length
301
+ if (producedCount + readCount + searchCount === 0) {
302
+ lines.push('> 本会话暂时没有产生、读取或检索过任何知识库笔记。')
303
+ lines.push('>')
304
+ lines.push('> 本页为会话自动生成的临时汇总(`$:/temp`,不落盘、不进 git,重启 TW 即消失);需要时点 Tab 顶栏的「🔄 刷新」重新生成。')
305
+ return lines.join('\n')
306
+ }
307
+ lines.push(
308
+ '| 产生 📝 | 读取 👀 | 检索 🔍 | 涉及会话 |',
309
+ '| --- | --- | --- | --- |',
310
+ `| ${producedCount} | ${readCount} | ${searchCount} | ${collected.produced.size + readTitles.length > 0 ? '本会话 + 子代理' : '本会话'} |`,
311
+ )
312
+ lines.push('')
313
+
314
+ const entryLine = (title: string, state: TitleState | undefined, entry: NoteEntry): string => {
315
+ const bits: string[] = [`[[${title}]]`]
316
+ if (state === undefined || !state.exists) {
317
+ bits.push('⚠️ 已删除/不存在')
318
+ } else {
319
+ if (state.tags.length > 0) bits.push(`标签 ${state.tags.slice(0, 6).join('、')}${state.tags.length > 6 ? '…' : ''}`)
320
+ const mod = fmtModified(state.modified)
321
+ if (mod.length > 0) bits.push(`修改 ${mod}`)
322
+ }
323
+ const t = fmtTime(entry.time)
324
+ if (t.length > 0) bits.push(`会话内 ${t}`)
325
+ if (entry.detail !== undefined) bits.push(entry.detail)
326
+ if (entry.subagent) bits.push('(子代理)')
327
+ return `* ${bits.join(' · ')}`
328
+ }
329
+
330
+ if (producedCount > 0) {
331
+ lines.push('!!! 📝 产生')
332
+ for (const title of producedTitles) {
333
+ const entry = collected.produced.get(title)
334
+ if (entry !== undefined) lines.push(entryLine(title, stateByTitle.get(title), entry))
335
+ }
336
+ lines.push('')
337
+ }
338
+ if (readCount > 0) {
339
+ lines.push('!!! 👀 读取')
340
+ for (const title of readTitles) {
341
+ const entry = collected.read.get(title)
342
+ if (entry !== undefined) lines.push(entryLine(title, stateByTitle.get(title), entry))
343
+ }
344
+ lines.push('')
345
+ }
346
+ if (searchCount > 0) {
347
+ lines.push('!!! 🔍 检索记录')
348
+ for (const r of collected.searches) {
349
+ const bits: string[] = []
350
+ if (r.kind === 'search') {
351
+ bits.push(`\`tiddlywiki_search\` query=「${r.query.length > 0 ? r.query : '(空)'}」`)
352
+ if (r.tags.length > 0) bits.push(`tags ${r.tags.join('、')}`)
353
+ } else {
354
+ bits.push('`tiddlywiki_recent`(最近修改)')
355
+ }
356
+ const t = fmtTime(r.time)
357
+ if (t.length > 0) bits.push(t)
358
+ if (r.subagent) bits.push('(子代理)')
359
+ lines.push(`* ${bits.join(' · ')}`)
360
+ }
361
+ lines.push('')
362
+ }
363
+ lines.push('---')
364
+ lines.push('> 本页为会话自动生成的临时汇总(`$:/temp`,不落盘、不进 git,重启 TW 即消失);需要时点 Tab 顶栏的「🔄 刷新」重新生成。')
365
+ return lines.join('\n')
366
+ }
367
+
368
+ export interface SessionSummaryResult {
369
+ title: string
370
+ counts: { produced: number; read: number; searches: number; sessions: number }
371
+ empty: boolean
372
+ generatedAt: string
373
+ }
374
+
375
+ /**
376
+ * 生成并写入一篇会话汇总 tiddler($:/temp,volatile)。
377
+ * @param client 可用 TW 客户端(调用方已保证 wiki 服务在线)。
378
+ * @param sq sessionQuery 服务(调用方已保证可用)。
379
+ * @param sessionId 目标会话 id(本会话 + 后代 subagent)。
380
+ */
381
+ export async function writeSessionSummary(client: TiddlyWebClient, sq: SessionQueryFace, sessionId: string): Promise<SessionSummaryResult> {
382
+ // 1) 会话范围:自身 + traceSession 后代树(递归)。trace 失败(会话已归档/不存在)
383
+ // 就只汇总自身,绝不让单次失败拖垮整页。
384
+ const ids: string[] = [sessionId]
385
+ try {
386
+ const trace = await sq.traceSession(sessionId, AbortSignal.timeout(10_000))
387
+ collectDescendantIds(trace?.descendants, ids)
388
+ } catch {
389
+ /* trace unavailable → self only */
390
+ }
391
+
392
+ // 2) 逐个会话读完整事件日志并收集(任一失败跳过,其余照常)。
393
+ const collected: Collected = { produced: new Map(), read: new Map(), searches: [] }
394
+ for (const id of ids) {
395
+ try {
396
+ const snap = await sq.readSession(id)
397
+ scanSnapshot(snap, id !== sessionId, collected)
398
+ } catch {
399
+ /* one bad session must not fail the whole summary */
400
+ }
401
+ }
402
+
403
+ // 3) 产生优先:同时被产生+读取的笔记只列在「产生」,读取区只放未产生过的。
404
+ const producedTitles = [...collected.produced.keys()].sort((a, b) => (collected.produced.get(b)?.time ?? 0) - (collected.produced.get(a)?.time ?? 0))
405
+ const readTitles = [...collected.read.keys()]
406
+ .filter((t) => !collected.produced.has(t))
407
+ .sort((a, b) => (collected.read.get(b)?.time ?? 0) - (collected.read.get(a)?.time ?? 0))
408
+ collected.searches.sort((a, b) => b.time - a.time)
409
+
410
+ // 4) 查询当前状态(存在?标签?时间?)→ 组装 wikitext → PUT volatile tiddler。
411
+ const stateByTitle = await enrichTitles(client, [...new Set([...producedTitles, ...readTitles])])
412
+ const text = buildWikitext(sessionId, collected, producedTitles, readTitles, stateByTitle)
413
+ const title = `${SESSION_SUMMARY_PREFIX}${sessionId}`
414
+ await client.put({ title, text, type: 'text/vnd.tiddlywiki', tags: [] })
415
+
416
+ return {
417
+ title,
418
+ counts: { produced: producedTitles.length, read: readTitles.length, searches: collected.searches.length, sessions: ids.length },
419
+ empty: producedTitles.length + readTitles.length + collected.searches.length === 0,
420
+ generatedAt: new Date().toISOString(),
421
+ }
422
+ }