dsh-context-kit 0.1.0 → 0.2.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/index.js CHANGED
@@ -1,385 +1,385 @@
1
- // context-index — 压缩安全的上下文索引(Host 插件,零依赖)
2
- //
3
- // 目标:压缩(compaction)把历史换成摘要后,模型仍能"看见"指针——
4
- // 最近的 artifact(token-guard 落盘的全文)和最近触碰过的路径。
5
- //
6
- // 更新节奏(2026-11-14 修正,依据 sp-index-api):
7
- // deepseek-flash 的 systemPromptUpdate 是 "in-history":system prompt 每变一次就
8
- // append 一条新的 system 消息进历史,之后每个请求都要重发。因此**不做步数节流,
9
- // 也不每步重建**,只在事件点重建:
10
- // - 会话开始(session/created、agent/created)→ reason 'start'
11
- // - 每次压缩总结之后(session/event 里的 compaction/summary)→ reason 'compaction'
12
- // - 显式入口 ctx.contextIndex.rebuild('manual')
13
- // text() 返回"当前状态字符串";重建后字符串没变就丢掉(同值 → 投影零事件)。
14
- // 渲染头不带 step(A2)——step 每步都变,会让"同值"保护失效;step 只进审计。
15
- //
16
- // 其余原则:
17
- // 1. 失败开放:任何异常都返回上一次的索引或空串,绝不阻断 agent / 工具。
18
- // 2. 硬上限:≤1,000 token(字符口径估算,见 lib/tokens.cjs),超了先裁最不常用的路径。
19
- // 3. 只记路径不记内容;命中脱敏规则的路径整条丢弃;非工作区的用户目录只留尾部两段。
20
- // 4. 审计:每次真正改变内容的重建写一行 ~/.dsh/context-index/manifest.jsonl。
21
- import { appendFile, mkdir } from 'node:fs/promises'
22
- import { homedir } from 'node:os'
23
- import path from 'node:path'
24
- import { createRequire } from 'node:module'
25
-
26
- const require = createRequire(import.meta.url)
27
- const S = require('./lib/index/sources.cjs')
28
- const R = require('./lib/index/render.cjs')
29
- const E = require('./lib/index/events.cjs')
30
-
31
- const DEFAULTS = {
32
- enabled: true,
33
- // 'section' = 注册一个 system prompt section;'none' = 只记账不注入,用来观察成本。
34
- injectMode: 'section',
35
- sectionName: 'index:index-page',
36
- // 必须 > DEPLOYMENT_PERSONA_SUFFIX(10200),才是最后一个 section(A1:上界不能夹掉它)
37
- sectionOrder: 10500,
38
- maxTokens: 1000,
39
- pathLimit: 40,
40
- artifactLimit: 20,
41
- targetChars: 48,
42
- manifestLines: 500,
43
- maxTrackedPaths: 300,
44
- tokenGuardManifest: path.join(homedir(), '.dsh', 'token-guard', 'manifest.jsonl'),
45
- auditManifest: path.join(homedir(), '.dsh', 'context-index', 'manifest.jsonl'),
46
- }
47
-
48
- function pickInt(value, fallback, min, max) {
49
- const n = Number(value)
50
- if (!Number.isFinite(n)) return fallback
51
- return Math.max(min, Math.min(max, Math.floor(n)))
52
- }
53
-
54
- function normalizeConfig(config = {}) {
55
- const cfg = config && typeof config === 'object' ? config : {}
56
- const cwd = typeof cfg.cwd === 'string' && cfg.cwd ? cfg.cwd : process.cwd()
57
- return {
58
- enabled: cfg.enabled !== false,
59
- injectMode: cfg.injectMode === 'none' ? 'none' : 'section',
60
- sectionName: typeof cfg.sectionName === 'string' && cfg.sectionName ? cfg.sectionName : DEFAULTS.sectionName,
61
- sectionOrder: pickInt(cfg.sectionOrder, DEFAULTS.sectionOrder, -10000, 20000),
62
- maxTokens: pickInt(cfg.maxTokens, DEFAULTS.maxTokens, 120, 100000),
63
- pathLimit: pickInt(cfg.pathLimit, DEFAULTS.pathLimit, 1, 200),
64
- artifactLimit: pickInt(cfg.artifactLimit, DEFAULTS.artifactLimit, 1, 100),
65
- targetChars: pickInt(cfg.targetChars, DEFAULTS.targetChars, 12, 120),
66
- manifestLines: pickInt(cfg.manifestLines, DEFAULTS.manifestLines, 1, 2000),
67
- maxTrackedPaths: pickInt(cfg.maxTrackedPaths, DEFAULTS.maxTrackedPaths, 40, 2000),
68
- tokenGuardManifest: path.resolve(String(cfg.tokenGuardManifest ?? DEFAULTS.tokenGuardManifest)),
69
- auditManifest: path.resolve(String(cfg.auditManifest ?? DEFAULTS.auditManifest)),
70
- cwd,
71
- // 工作区根:工作区内的路径原样显示;工作区外 + 用户目录降级(B2)
72
- workspaceRoot: typeof cfg.workspaceRoot === 'string' && cfg.workspaceRoot ? cfg.workspaceRoot : cwd,
73
- }
74
- }
75
-
76
- // 可选依赖:拿不到 systemPrompt 服务时退化为"只记账"
77
- function resolveSystemPrompt(ctx) {
78
- try {
79
- if (typeof ctx?.get === 'function') {
80
- const viaGet = ctx.get('systemPrompt')
81
- if (viaGet) return viaGet
82
- }
83
- } catch {}
84
- try {
85
- return ctx?.systemPrompt ?? null
86
- } catch {
87
- return null
88
- }
89
- }
90
-
91
- export const name = 'dsh-context-index'
92
- // systemPrompt 是可选依赖:主路径用全局 section;服务不在本层时退化到 agent.ctx(见 installInjection)
93
- export const inject = ['tools', 'systemPrompt']
94
-
95
- export function apply(ctx, config = {}) {
96
- const cfg = normalizeConfig(config)
97
- if (!cfg.enabled) return
98
-
99
- // 路径:最近使用在前(索引即输出顺序)
100
- const paths = []
101
- const pathKeys = new Map()
102
- const sections = new Map()
103
-
104
- const state = {
105
- text: '', // 当前对外文本;只在重建后改变,且"同值不更新"
106
- step: 0,
107
- compactions: 0,
108
- reason: '',
109
- rebuiltAt: 0,
110
- // 实际走了哪条注入路径:'global' | 'agent' | 'none'(写进审计,便于诊断)
111
- injection: 'none',
112
- }
113
- const stats = { rebuilds: 0, unchanged: 0, audits: 0, recordedPaths: 0 }
114
- const seenCompactions = new Set()
115
- const startedCompactions = new Set()
116
- const seenSummaries = new Set()
117
- let sawSessionEvent = false
118
- let artifactCache = { key: null, value: [] }
119
- let auditChain = Promise.resolve()
120
-
121
- const on = (event, handler) => {
122
- try {
123
- if (typeof ctx?.on === 'function') ctx.on(event, handler)
124
- } catch {}
125
- }
126
-
127
- // ---- 数据来源 1:路径(只更新内存,不重建文本) -------------------------
128
-
129
- const touchPath = (raw) => {
130
- try {
131
- const abs = S.normalizePath(raw, { cwd: cfg.cwd, workspaceRoot: cfg.workspaceRoot })
132
- if (!abs) return
133
- const key = abs.toLowerCase()
134
- const existing = pathKeys.get(key)
135
- if (existing === 0) return // 已在最前
136
- if (existing !== undefined) paths.splice(existing, 1)
137
- paths.unshift(abs)
138
- if (paths.length > cfg.maxTrackedPaths) paths.length = cfg.maxTrackedPaths
139
- pathKeys.clear()
140
- for (let i = 0; i < paths.length; i += 1) pathKeys.set(paths[i].toLowerCase(), i)
141
- stats.recordedPaths += 1
142
- } catch {}
143
- }
144
-
145
- const recordPaths = (values) => {
146
- try {
147
- if (!Array.isArray(values)) return
148
- for (const value of values) touchPath(value)
149
- } catch {}
150
- }
151
-
152
- // ---- 数据来源 2:token-guard artifact -----------------------------------
153
-
154
- const readArtifacts = () => {
155
- try {
156
- const read = S.readManifestTail(cfg.tokenGuardManifest, cfg.manifestLines)
157
- const key = `${read.size}:${read.mtimeMs}`
158
- if (key === artifactCache.key) return artifactCache.value
159
- // 不在这里截断:让 render 知道总条数,才能写出 "(+N more)"
160
- const value = S.summarizeArtifacts(read.records)
161
- artifactCache = { key, value }
162
- return value
163
- } catch {
164
- return []
165
- }
166
- }
167
-
168
- // ---- 审计 ---------------------------------------------------------------
169
-
170
- const scheduleAudit = (entry) => {
171
- stats.audits += 1
172
- auditChain = auditChain
173
- .then(async () => {
174
- await mkdir(path.dirname(cfg.auditManifest), { recursive: true })
175
- await appendFile(cfg.auditManifest, `${JSON.stringify({ ts: Date.now(), ...entry })}\n`, 'utf8')
176
- })
177
- .catch(() => {})
178
- }
179
-
180
- // ---- 重建(唯一入口;事件点调用) ---------------------------------------
181
-
182
- const rebuild = (reason = 'manual') => {
183
- try {
184
- const artifacts = readArtifacts()
185
- const built = R.buildIndex({ paths: paths.slice(), artifacts, step: state.step, compactions: state.compactions, limits: cfg })
186
- const text = built.text || ''
187
- stats.rebuilds += 1
188
- // 关键:字符串没变就丢掉(同值 → 不产生新的 system 消息)
189
- if (text === state.text) {
190
- stats.unchanged += 1
191
- return state.text
192
- }
193
- state.text = text
194
- state.reason = reason
195
- state.rebuiltAt = Date.now()
196
- scheduleAudit({
197
- reason,
198
- step: state.step,
199
- chars: built.chars,
200
- estTokens: built.estTokens,
201
- paths: built.pathLines,
202
- artifacts: built.artifactLines,
203
- injection: state.injection,
204
- })
205
- return state.text
206
- } catch {
207
- return state.text // 失败开放:保持上一次
208
- }
209
- }
210
-
211
- // ---- 注入(封装在一处,便于替换注入方式) -------------------------------
212
-
213
- const installInjection = () => {
214
- if (cfg.injectMode === 'none') {
215
- state.injection = 'none'
216
- return
217
- }
218
- const section = {
219
- name: cfg.sectionName,
220
- order: cfg.sectionOrder,
221
- interpolate: false,
222
- text: () => state.text,
223
- }
224
- const systemPrompt = resolveSystemPrompt(ctx)
225
- if (systemPrompt && typeof systemPrompt.section === 'function') {
226
- try {
227
- sections.set('global', systemPrompt.section(section))
228
- state.injection = 'global'
229
- return
230
- } catch {
231
- // 注册失败(例如重名)→ 落到 per-agent 路径,并在审计里可见
232
- }
233
- }
234
- state.injection = 'agent'
235
- // 退化:服务不在本层时,挂到每个 agent 的 scope 上(dsh-memory-local 的写法)
236
- on('agent/created', (payload) => {
237
- try {
238
- const agent = payload?.agent
239
- if (!agent?.id) return
240
- const scoped = agent.ctx?.systemPrompt ?? agent.ctx?.get?.('systemPrompt')
241
- if (!scoped || typeof scoped.section !== 'function') {
242
- state.injection = 'none'
243
- return
244
- }
245
- sections.set(agent.id, scoped.section(section))
246
- } catch {
247
- state.injection = 'none'
248
- }
249
- })
250
- on('agent/disposed', (payload) => {
251
- try {
252
- sections.get(payload?.agent?.id)?.()
253
- sections.delete(payload?.agent?.id)
254
- } catch {}
255
- })
256
- }
257
-
258
- // ---- 压缩事件 → 计数 + 重建 --------------------------------------------
259
-
260
- const noteCompaction = (event) => {
261
- try {
262
- const type = E.eventType(event)
263
- const key = E.compactionKey(event) || `type:${type}`
264
- if (type === 'compaction/start') {
265
- startedCompactions.add(key)
266
- return
267
- }
268
- if (type === 'compaction/end') {
269
- // 正常路径在 summary 就计过数;只有"有 start 没有 summary"时才补记
270
- if (seenCompactions.has(key) || !startedCompactions.has(key)) return
271
- }
272
- if (seenCompactions.has(key)) return
273
- seenCompactions.add(key)
274
- state.compactions += 1
275
- rebuild('compaction')
276
- // 去重集合不无限增长
277
- if (seenCompactions.size > 500) seenCompactions.delete(seenCompactions.values().next().value)
278
- if (startedCompactions.size > 500) startedCompactions.delete(startedCompactions.values().next().value)
279
- } catch {}
280
- }
281
-
282
- // ---- 事件接线 -----------------------------------------------------------
283
-
284
- // 会话开始:首次装配时就有索引(内容为空时 rebuild 是 no-op,不写审计)
285
- on('session/created', () => {
286
- try {
287
- rebuild('start')
288
- } catch {}
289
- })
290
- // 子 agent 也会触发 agent/created:只在“还没有任何索引”时做首次构建,
291
- // 避免子 agent 每次创建都白跑一次重建(字符串不变虽不产生事件,但没必要)。
292
- on('agent/created', () => {
293
- try {
294
- if (!state.text) rebuild('start')
295
- } catch {}
296
- })
297
-
298
- // 路径记录 + 步数跟踪:只更新内存,绝不重建文本
299
- on('tools/post-execute', async (exec, result, next) => {
300
- try {
301
- const toolName = exec?.name ?? exec?.tool?.name
302
- const found = S.extractPaths(toolName, exec?.arguments)
303
- if (found.length) recordPaths(found)
304
- } catch {}
305
- return next()
306
- })
307
-
308
- on('agent/pre-step', (payload, next) => {
309
- try {
310
- const step = Number(payload?.step)
311
- if (Number.isFinite(step)) state.step = Math.max(state.step, step)
312
- // 退化路径:拿不到 session/event 时,从进入本步的消息里识别压缩总结
313
- if (!sawSessionEvent) {
314
- const key = E.detectSummaryText(payload?.messages)
315
- if (key && !seenSummaries.has(key)) {
316
- seenSummaries.add(key)
317
- state.compactions += 1
318
- rebuild('compaction')
319
- }
320
- }
321
- } catch {}
322
- return next()
323
- })
324
-
325
- // 主路径:session/event 的压缩事件(真实日志里是 compaction/start|summary|end)
326
- // 兼容一参/两参签名(C3):真实签名可能是 (event) 或 (session, event)。
327
- on('session/event', (a, b) => {
328
- try {
329
- const event = b ?? a
330
- sawSessionEvent = true
331
- if (E.isCompactionEvent(event)) noteCompaction(event)
332
- } catch {}
333
- })
334
- // 若某个版本直接以命名事件广播压缩总结,也接住
335
- on('compaction/summary', (payload) => {
336
- try {
337
- noteCompaction(payload?.event ?? payload)
338
- } catch {}
339
- })
340
-
341
- installInjection()
342
-
343
- // 插件卸载/作用域销毁时释放所有 section(全局注册与 agent 作用域注册都覆盖)
344
- try {
345
- if (typeof ctx?.effect === 'function') {
346
- ctx.effect(() => () => {
347
- for (const dispose of sections.values()) {
348
- try {
349
- dispose?.()
350
- } catch {}
351
- }
352
- sections.clear()
353
- })
354
- }
355
- } catch {}
356
-
357
- // ---- 显式入口(手动重建 / 诊断) ---------------------------------------
358
-
359
- const api = {
360
- rebuild: (reason = 'manual') => rebuild(reason),
361
- get text() {
362
- return state.text
363
- },
364
- get stats() {
365
- return {
366
- ...stats,
367
- paths: paths.length,
368
- compactions: state.compactions,
369
- reason: state.reason,
370
- builtAt: state.rebuiltAt,
371
- injection: state.injection,
372
- }
373
- },
374
- }
375
- try {
376
- ctx.contextIndex = api
377
- } catch {
378
- try {
379
- Object.defineProperty(ctx, 'contextIndex', { configurable: true, value: api })
380
- } catch {}
381
- }
382
- }
383
-
384
- // 供测试直接引用(测试用假的 ctx 驱动 apply)
385
- export const __test = { normalizeConfig, DEFAULTS }
1
+ // context-index — 压缩安全的上下文索引(Host 插件,零依赖)
2
+ //
3
+ // 目标:压缩(compaction)把历史换成摘要后,模型仍能"看见"指针——
4
+ // 最近的 artifact(token-guard 落盘的全文)和最近触碰过的路径。
5
+ //
6
+ // 更新节奏(2026-11-14 修正,依据 sp-index-api):
7
+ // deepseek-flash 的 systemPromptUpdate 是 "in-history":system prompt 每变一次就
8
+ // append 一条新的 system 消息进历史,之后每个请求都要重发。因此**不做步数节流,
9
+ // 也不每步重建**,只在事件点重建:
10
+ // - 会话开始(session/created、agent/created)→ reason 'start'
11
+ // - 每次压缩总结之后(session/event 里的 compaction/summary)→ reason 'compaction'
12
+ // - 显式入口 ctx.contextIndex.rebuild('manual')
13
+ // text() 返回"当前状态字符串";重建后字符串没变就丢掉(同值 → 投影零事件)。
14
+ // 渲染头不带 step(A2)——step 每步都变,会让"同值"保护失效;step 只进审计。
15
+ //
16
+ // 其余原则:
17
+ // 1. 失败开放:任何异常都返回上一次的索引或空串,绝不阻断 agent / 工具。
18
+ // 2. 硬上限:≤1,000 token(字符口径估算,见 lib/tokens.cjs),超了先裁最不常用的路径。
19
+ // 3. 只记路径不记内容;命中脱敏规则的路径整条丢弃;非工作区的用户目录只留尾部两段。
20
+ // 4. 审计:每次真正改变内容的重建写一行 ~/.dsh/context-index/manifest.jsonl。
21
+ import { appendFile, mkdir } from 'node:fs/promises'
22
+ import { homedir } from 'node:os'
23
+ import path from 'node:path'
24
+ import { createRequire } from 'node:module'
25
+
26
+ const require = createRequire(import.meta.url)
27
+ const S = require('./lib/index/sources.cjs')
28
+ const R = require('./lib/index/render.cjs')
29
+ const E = require('./lib/index/events.cjs')
30
+
31
+ const DEFAULTS = {
32
+ enabled: true,
33
+ // 'section' = 注册一个 system prompt section;'none' = 只记账不注入,用来观察成本。
34
+ injectMode: 'section',
35
+ sectionName: 'index:index-page',
36
+ // 必须 > DEPLOYMENT_PERSONA_SUFFIX(10200),才是最后一个 section(A1:上界不能夹掉它)
37
+ sectionOrder: 10500,
38
+ maxTokens: 1000,
39
+ pathLimit: 40,
40
+ artifactLimit: 20,
41
+ targetChars: 48,
42
+ manifestLines: 500,
43
+ maxTrackedPaths: 300,
44
+ tokenGuardManifest: path.join(homedir(), '.dsh', 'token-guard', 'manifest.jsonl'),
45
+ auditManifest: path.join(homedir(), '.dsh', 'context-index', 'manifest.jsonl'),
46
+ }
47
+
48
+ function pickInt(value, fallback, min, max) {
49
+ const n = Number(value)
50
+ if (!Number.isFinite(n)) return fallback
51
+ return Math.max(min, Math.min(max, Math.floor(n)))
52
+ }
53
+
54
+ function normalizeConfig(config = {}) {
55
+ const cfg = config && typeof config === 'object' ? config : {}
56
+ const cwd = typeof cfg.cwd === 'string' && cfg.cwd ? cfg.cwd : process.cwd()
57
+ return {
58
+ enabled: cfg.enabled !== false,
59
+ injectMode: cfg.injectMode === 'none' ? 'none' : 'section',
60
+ sectionName: typeof cfg.sectionName === 'string' && cfg.sectionName ? cfg.sectionName : DEFAULTS.sectionName,
61
+ sectionOrder: pickInt(cfg.sectionOrder, DEFAULTS.sectionOrder, -10000, 20000),
62
+ maxTokens: pickInt(cfg.maxTokens, DEFAULTS.maxTokens, 120, 100000),
63
+ pathLimit: pickInt(cfg.pathLimit, DEFAULTS.pathLimit, 1, 200),
64
+ artifactLimit: pickInt(cfg.artifactLimit, DEFAULTS.artifactLimit, 1, 100),
65
+ targetChars: pickInt(cfg.targetChars, DEFAULTS.targetChars, 12, 120),
66
+ manifestLines: pickInt(cfg.manifestLines, DEFAULTS.manifestLines, 1, 2000),
67
+ maxTrackedPaths: pickInt(cfg.maxTrackedPaths, DEFAULTS.maxTrackedPaths, 40, 2000),
68
+ tokenGuardManifest: path.resolve(String(cfg.tokenGuardManifest ?? DEFAULTS.tokenGuardManifest)),
69
+ auditManifest: path.resolve(String(cfg.auditManifest ?? DEFAULTS.auditManifest)),
70
+ cwd,
71
+ // 工作区根:工作区内的路径原样显示;工作区外 + 用户目录降级(B2)
72
+ workspaceRoot: typeof cfg.workspaceRoot === 'string' && cfg.workspaceRoot ? cfg.workspaceRoot : cwd,
73
+ }
74
+ }
75
+
76
+ // 可选依赖:拿不到 systemPrompt 服务时退化为"只记账"
77
+ function resolveSystemPrompt(ctx) {
78
+ try {
79
+ if (typeof ctx?.get === 'function') {
80
+ const viaGet = ctx.get('systemPrompt')
81
+ if (viaGet) return viaGet
82
+ }
83
+ } catch {}
84
+ try {
85
+ return ctx?.systemPrompt ?? null
86
+ } catch {
87
+ return null
88
+ }
89
+ }
90
+
91
+ export const name = 'dsh-context-index'
92
+ // systemPrompt 是可选依赖:主路径用全局 section;服务不在本层时退化到 agent.ctx(见 installInjection)
93
+ export const inject = ['tools', 'systemPrompt']
94
+
95
+ export function apply(ctx, config = {}) {
96
+ const cfg = normalizeConfig(config)
97
+ if (!cfg.enabled) return
98
+
99
+ // 路径:最近使用在前(索引即输出顺序)
100
+ const paths = []
101
+ const pathKeys = new Map()
102
+ const sections = new Map()
103
+
104
+ const state = {
105
+ text: '', // 当前对外文本;只在重建后改变,且"同值不更新"
106
+ step: 0,
107
+ compactions: 0,
108
+ reason: '',
109
+ rebuiltAt: 0,
110
+ // 实际走了哪条注入路径:'global' | 'agent' | 'none'(写进审计,便于诊断)
111
+ injection: 'none',
112
+ }
113
+ const stats = { rebuilds: 0, unchanged: 0, audits: 0, recordedPaths: 0 }
114
+ const seenCompactions = new Set()
115
+ const startedCompactions = new Set()
116
+ const seenSummaries = new Set()
117
+ let sawSessionEvent = false
118
+ let artifactCache = { key: null, value: [] }
119
+ let auditChain = Promise.resolve()
120
+
121
+ const on = (event, handler) => {
122
+ try {
123
+ if (typeof ctx?.on === 'function') ctx.on(event, handler)
124
+ } catch {}
125
+ }
126
+
127
+ // ---- 数据来源 1:路径(只更新内存,不重建文本) -------------------------
128
+
129
+ const touchPath = (raw) => {
130
+ try {
131
+ const abs = S.normalizePath(raw, { cwd: cfg.cwd, workspaceRoot: cfg.workspaceRoot })
132
+ if (!abs) return
133
+ const key = abs.toLowerCase()
134
+ const existing = pathKeys.get(key)
135
+ if (existing === 0) return // 已在最前
136
+ if (existing !== undefined) paths.splice(existing, 1)
137
+ paths.unshift(abs)
138
+ if (paths.length > cfg.maxTrackedPaths) paths.length = cfg.maxTrackedPaths
139
+ pathKeys.clear()
140
+ for (let i = 0; i < paths.length; i += 1) pathKeys.set(paths[i].toLowerCase(), i)
141
+ stats.recordedPaths += 1
142
+ } catch {}
143
+ }
144
+
145
+ const recordPaths = (values) => {
146
+ try {
147
+ if (!Array.isArray(values)) return
148
+ for (const value of values) touchPath(value)
149
+ } catch {}
150
+ }
151
+
152
+ // ---- 数据来源 2:token-guard artifact -----------------------------------
153
+
154
+ const readArtifacts = () => {
155
+ try {
156
+ const read = S.readManifestTail(cfg.tokenGuardManifest, cfg.manifestLines)
157
+ const key = `${read.size}:${read.mtimeMs}`
158
+ if (key === artifactCache.key) return artifactCache.value
159
+ // 不在这里截断:让 render 知道总条数,才能写出 "(+N more)"
160
+ const value = S.summarizeArtifacts(read.records)
161
+ artifactCache = { key, value }
162
+ return value
163
+ } catch {
164
+ return []
165
+ }
166
+ }
167
+
168
+ // ---- 审计 ---------------------------------------------------------------
169
+
170
+ const scheduleAudit = (entry) => {
171
+ stats.audits += 1
172
+ auditChain = auditChain
173
+ .then(async () => {
174
+ await mkdir(path.dirname(cfg.auditManifest), { recursive: true })
175
+ await appendFile(cfg.auditManifest, `${JSON.stringify({ ts: Date.now(), ...entry })}\n`, 'utf8')
176
+ })
177
+ .catch(() => {})
178
+ }
179
+
180
+ // ---- 重建(唯一入口;事件点调用) ---------------------------------------
181
+
182
+ const rebuild = (reason = 'manual') => {
183
+ try {
184
+ const artifacts = readArtifacts()
185
+ const built = R.buildIndex({ paths: paths.slice(), artifacts, step: state.step, compactions: state.compactions, limits: cfg })
186
+ const text = built.text || ''
187
+ stats.rebuilds += 1
188
+ // 关键:字符串没变就丢掉(同值 → 不产生新的 system 消息)
189
+ if (text === state.text) {
190
+ stats.unchanged += 1
191
+ return state.text
192
+ }
193
+ state.text = text
194
+ state.reason = reason
195
+ state.rebuiltAt = Date.now()
196
+ scheduleAudit({
197
+ reason,
198
+ step: state.step,
199
+ chars: built.chars,
200
+ estTokens: built.estTokens,
201
+ paths: built.pathLines,
202
+ artifacts: built.artifactLines,
203
+ injection: state.injection,
204
+ })
205
+ return state.text
206
+ } catch {
207
+ return state.text // 失败开放:保持上一次
208
+ }
209
+ }
210
+
211
+ // ---- 注入(封装在一处,便于替换注入方式) -------------------------------
212
+
213
+ const installInjection = () => {
214
+ if (cfg.injectMode === 'none') {
215
+ state.injection = 'none'
216
+ return
217
+ }
218
+ const section = {
219
+ name: cfg.sectionName,
220
+ order: cfg.sectionOrder,
221
+ interpolate: false,
222
+ text: () => state.text,
223
+ }
224
+ const systemPrompt = resolveSystemPrompt(ctx)
225
+ if (systemPrompt && typeof systemPrompt.section === 'function') {
226
+ try {
227
+ sections.set('global', systemPrompt.section(section))
228
+ state.injection = 'global'
229
+ return
230
+ } catch {
231
+ // 注册失败(例如重名)→ 落到 per-agent 路径,并在审计里可见
232
+ }
233
+ }
234
+ state.injection = 'agent'
235
+ // 退化:服务不在本层时,挂到每个 agent 的 scope 上(dsh-memory-local 的写法)
236
+ on('agent/created', (payload) => {
237
+ try {
238
+ const agent = payload?.agent
239
+ if (!agent?.id) return
240
+ const scoped = agent.ctx?.systemPrompt ?? agent.ctx?.get?.('systemPrompt')
241
+ if (!scoped || typeof scoped.section !== 'function') {
242
+ state.injection = 'none'
243
+ return
244
+ }
245
+ sections.set(agent.id, scoped.section(section))
246
+ } catch {
247
+ state.injection = 'none'
248
+ }
249
+ })
250
+ on('agent/disposed', (payload) => {
251
+ try {
252
+ sections.get(payload?.agent?.id)?.()
253
+ sections.delete(payload?.agent?.id)
254
+ } catch {}
255
+ })
256
+ }
257
+
258
+ // ---- 压缩事件 → 计数 + 重建 --------------------------------------------
259
+
260
+ const noteCompaction = (event) => {
261
+ try {
262
+ const type = E.eventType(event)
263
+ const key = E.compactionKey(event) || `type:${type}`
264
+ if (type === 'compaction/start') {
265
+ startedCompactions.add(key)
266
+ return
267
+ }
268
+ if (type === 'compaction/end') {
269
+ // 正常路径在 summary 就计过数;只有"有 start 没有 summary"时才补记
270
+ if (seenCompactions.has(key) || !startedCompactions.has(key)) return
271
+ }
272
+ if (seenCompactions.has(key)) return
273
+ seenCompactions.add(key)
274
+ state.compactions += 1
275
+ rebuild('compaction')
276
+ // 去重集合不无限增长
277
+ if (seenCompactions.size > 500) seenCompactions.delete(seenCompactions.values().next().value)
278
+ if (startedCompactions.size > 500) startedCompactions.delete(startedCompactions.values().next().value)
279
+ } catch {}
280
+ }
281
+
282
+ // ---- 事件接线 -----------------------------------------------------------
283
+
284
+ // 会话开始:首次装配时就有索引(内容为空时 rebuild 是 no-op,不写审计)
285
+ on('session/created', () => {
286
+ try {
287
+ rebuild('start')
288
+ } catch {}
289
+ })
290
+ // 子 agent 也会触发 agent/created:只在“还没有任何索引”时做首次构建,
291
+ // 避免子 agent 每次创建都白跑一次重建(字符串不变虽不产生事件,但没必要)。
292
+ on('agent/created', () => {
293
+ try {
294
+ if (!state.text) rebuild('start')
295
+ } catch {}
296
+ })
297
+
298
+ // 路径记录 + 步数跟踪:只更新内存,绝不重建文本
299
+ on('tools/post-execute', async (exec, result, next) => {
300
+ try {
301
+ const toolName = exec?.name ?? exec?.tool?.name
302
+ const found = S.extractPaths(toolName, exec?.arguments)
303
+ if (found.length) recordPaths(found)
304
+ } catch {}
305
+ return next()
306
+ })
307
+
308
+ on('agent/pre-step', (payload, next) => {
309
+ try {
310
+ const step = Number(payload?.step)
311
+ if (Number.isFinite(step)) state.step = Math.max(state.step, step)
312
+ // 退化路径:拿不到 session/event 时,从进入本步的消息里识别压缩总结
313
+ if (!sawSessionEvent) {
314
+ const key = E.detectSummaryText(payload?.messages)
315
+ if (key && !seenSummaries.has(key)) {
316
+ seenSummaries.add(key)
317
+ state.compactions += 1
318
+ rebuild('compaction')
319
+ }
320
+ }
321
+ } catch {}
322
+ return next()
323
+ })
324
+
325
+ // 主路径:session/event 的压缩事件(真实日志里是 compaction/start|summary|end)
326
+ // 兼容一参/两参签名(C3):真实签名可能是 (event) 或 (session, event)。
327
+ on('session/event', (a, b) => {
328
+ try {
329
+ const event = b ?? a
330
+ sawSessionEvent = true
331
+ if (E.isCompactionEvent(event)) noteCompaction(event)
332
+ } catch {}
333
+ })
334
+ // 若某个版本直接以命名事件广播压缩总结,也接住
335
+ on('compaction/summary', (payload) => {
336
+ try {
337
+ noteCompaction(payload?.event ?? payload)
338
+ } catch {}
339
+ })
340
+
341
+ installInjection()
342
+
343
+ // 插件卸载/作用域销毁时释放所有 section(全局注册与 agent 作用域注册都覆盖)
344
+ try {
345
+ if (typeof ctx?.effect === 'function') {
346
+ ctx.effect(() => () => {
347
+ for (const dispose of sections.values()) {
348
+ try {
349
+ dispose?.()
350
+ } catch {}
351
+ }
352
+ sections.clear()
353
+ })
354
+ }
355
+ } catch {}
356
+
357
+ // ---- 显式入口(手动重建 / 诊断) ---------------------------------------
358
+
359
+ const api = {
360
+ rebuild: (reason = 'manual') => rebuild(reason),
361
+ get text() {
362
+ return state.text
363
+ },
364
+ get stats() {
365
+ return {
366
+ ...stats,
367
+ paths: paths.length,
368
+ compactions: state.compactions,
369
+ reason: state.reason,
370
+ builtAt: state.rebuiltAt,
371
+ injection: state.injection,
372
+ }
373
+ },
374
+ }
375
+ try {
376
+ ctx.contextIndex = api
377
+ } catch {
378
+ try {
379
+ Object.defineProperty(ctx, 'contextIndex', { configurable: true, value: api })
380
+ } catch {}
381
+ }
382
+ }
383
+
384
+ // 供测试直接引用(测试用假的 ctx 驱动 apply)
385
+ export const __test = { normalizeConfig, DEFAULTS }