dsh-context-kit 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +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 }
@@ -0,0 +1,90 @@
1
+ // events.cjs — 索引重建的触发条件(事件驱动,不做步数节流)
2
+ //
3
+ // 依据(sp-index-api,2026-11-14):deepseek-flash 的 systemPromptUpdate 是 "in-history",
4
+ // 即 system prompt 每变一次就 append 一条新的 system 消息,之后每个请求都要重发。
5
+ // 所以索引**只能在事件点重建**:会话开始、每次 compaction/summary 之后、手动调用。
6
+ //
7
+ // 真实会话日志(~/.dsh/sessions/**/session.v4.jsonl.zstd)里的压缩事件类型:
8
+ // compaction/start → { compactionId, turn }
9
+ // compaction/summary→ { compactionId, summary: [{type:'text', text:'## Primary Request …'}] }
10
+ // compaction/end → { compactionId, turn }
11
+ // compaction/prune → 历史裁剪(不是压缩总结,不触发重建)
12
+
13
+ const COMPACTION_TYPES = new Set(['compaction/start', 'compaction/summary', 'compaction/end'])
14
+
15
+ // 压缩总结模板的标题(来自真实 compaction/summary 内容)
16
+ const SUMMARY_MARKERS = [/##\s*Primary Request and Intent/i, /##\s*Key Technical Concepts/i, /##\s*Pending Tasks/i, /##\s*Optional Next Step/i]
17
+
18
+ function eventType(event) {
19
+ try {
20
+ const t = event?.type ?? event?.name ?? event?.kind
21
+ return typeof t === 'string' ? t : ''
22
+ } catch {
23
+ return ''
24
+ }
25
+ }
26
+
27
+ /** 是否是压缩相关事件(不改变任何状态,纯判定)。 */
28
+ function isCompactionEvent(event) {
29
+ const type = eventType(event)
30
+ if (!type) return false
31
+ // 只认 start/summary/end。compaction/prune 是历史裁剪(一次会话几十次),
32
+ // 拿它触发重建会退化成"频繁重建",必须排除。
33
+ if (COMPACTION_TYPES.has(type)) return true
34
+ // 兼容别的命名(例如 compaction/complete),但排除 prune/error 这类非触发事件
35
+ if (/compaction\//i.test(type) && !/prune|error/i.test(type)) return true
36
+ return false
37
+ }
38
+
39
+ /** 同一次压缩的稳定 key,用来去重(start/summary/end 属于同一次)。 */
40
+ function compactionKey(event) {
41
+ try {
42
+ const id = event?.data?.compactionId ?? event?.compactionId
43
+ if (typeof id === 'string' && id) return id
44
+ const seq = event?.seq ?? event?.time
45
+ if (seq !== undefined && seq !== null) return `seq:${seq}`
46
+ return ''
47
+ } catch {
48
+ return ''
49
+ }
50
+ }
51
+
52
+ /** 32 位字符串哈希(用于给"压缩总结文本"去重)。 */
53
+ function hashText(text) {
54
+ let hash = 2166136261
55
+ const s = String(text ?? '')
56
+ for (let i = 0; i < s.length && i < 4096; i += 1) {
57
+ hash ^= s.charCodeAt(i)
58
+ hash = Math.imul(hash, 16777619)
59
+ }
60
+ return (hash >>> 0).toString(16)
61
+ }
62
+
63
+ /**
64
+ * 退化路径:拿不到 session 事件时,从 agent/pre-step 进入本步的消息里识别
65
+ * "压缩总结"(DSH 的总结模板标题)。识别成功返回稳定 key,否则 null。
66
+ */
67
+ function detectSummaryText(messages) {
68
+ try {
69
+ if (!Array.isArray(messages)) return null
70
+ for (const message of messages) {
71
+ const blocks = message?.content
72
+ const text = typeof blocks === 'string' ? blocks : Array.isArray(blocks) ? blocks.filter((b) => b?.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n') : ''
73
+ if (!text || text.length < 200) continue
74
+ if (SUMMARY_MARKERS.some((re) => re.test(text))) return hashText(text)
75
+ }
76
+ return null
77
+ } catch {
78
+ return null
79
+ }
80
+ }
81
+
82
+ module.exports = {
83
+ COMPACTION_TYPES,
84
+ SUMMARY_MARKERS,
85
+ eventType,
86
+ isCompactionEvent,
87
+ compactionKey,
88
+ hashText,
89
+ detectSummaryText,
90
+ }
@@ -0,0 +1,177 @@
1
+ // render.cjs — 把"路径 + artifact"渲染成一段稳定的索引文本,并裁剪到 token 上限。
2
+ //
3
+ // 格式(设计草案 §3 + 2026-11-14 评审修正):
4
+ // [context index · 2 compactions]
5
+ // artifacts:
6
+ // a1b2c3 pwsh test/run.mjs 4.1K trunc
7
+ // 7a7644 read 99 / full 12.6K need
8
+ // d4e5f6 read src/serialize.mjs 11.9K need ×3
9
+ // … (+3 more)
10
+ // paths:
11
+ // E:\dsh的工作区\reports\eviction-plan.md
12
+ // … (+12 more)
13
+ // ↳ 原文:guard_query(id, pattern) 或 read ~/.dsh/token-guard/artifacts/<id>.txt
14
+ //
15
+ // 头部**不带 step**(A2):step 每步都变,会让"同值零事件"保护失效;
16
+ // step 只进审计。compactions 在一个压缩周期内是稳定的。
17
+ //
18
+ // 渲染是纯函数:同样的输入 → 同样的输出(可单测、可回放)。
19
+ const { estimateTokens } = require('./tokens.cjs')
20
+
21
+ function clampInt(value, fallback, min, max) {
22
+ const n = Number(value)
23
+ if (!Number.isFinite(n)) return fallback
24
+ return Math.max(min, Math.min(max, Math.floor(n)))
25
+ }
26
+
27
+ // 把过长的目标列从"头部"压缩,保留尾部(文件名/级别更有信息)
28
+ function shorten(text, maxChars) {
29
+ if (typeof text !== 'string') return ''
30
+ if (text.length <= maxChars) return text
31
+ return `…${text.slice(-(maxChars - 1))}`
32
+ }
33
+
34
+ function emptyResult(step, compactions) {
35
+ return {
36
+ text: '',
37
+ chars: 0,
38
+ estTokens: 0,
39
+ step,
40
+ compactions,
41
+ pathLines: 0,
42
+ artifactLines: 0,
43
+ droppedPaths: 0,
44
+ droppedArtifacts: 0,
45
+ totalPaths: 0,
46
+ totalArtifacts: 0,
47
+ overBudget: false,
48
+ }
49
+ }
50
+
51
+ function renderBody({ paths, artifacts, totalPaths, totalArtifacts, compactions, targetChars, hint = true }) {
52
+ const lines = [`[context index · ${compactions} compaction${compactions === 1 ? '' : 's'}]`]
53
+
54
+ if (totalArtifacts > 0) {
55
+ lines.push('artifacts:')
56
+ if (artifacts.length === 0) {
57
+ lines.push(` … (+${totalArtifacts} more)`)
58
+ } else {
59
+ const targetWidth = artifacts.reduce((w, a) => Math.max(w, shorten(a.target, targetChars).length), 4)
60
+ for (const artifact of artifacts) {
61
+ const id = String(artifact.id).padEnd(6)
62
+ const tool = String(artifact.tool).slice(0, 6).padEnd(6)
63
+ const target = shorten(artifact.target ?? '', targetChars).padEnd(targetWidth)
64
+ const size = String(artifact.size ?? '—')
65
+ const dup = Number(artifact.dup) > 1 ? ` ×${artifact.dup}` : ''
66
+ const status = `${artifact.status ?? '—'}${dup}`
67
+ lines.push(` ${id} ${tool} ${target} ${size} ${status}`)
68
+ }
69
+ const dropped = totalArtifacts - artifacts.length
70
+ if (dropped > 0) lines.push(` … (+${dropped} more)`)
71
+ }
72
+ }
73
+
74
+ if (totalPaths > 0) {
75
+ lines.push('paths:')
76
+ if (paths.length === 0) {
77
+ lines.push(` … (+${totalPaths} more)`)
78
+ } else {
79
+ for (const p of paths) lines.push(` ${p}`)
80
+ const dropped = totalPaths - paths.length
81
+ if (dropped > 0) lines.push(` … (+${dropped} more)`)
82
+ }
83
+ }
84
+
85
+ // 取回提示:没有它,id 对模型就是一串无意义的字符。
86
+ if (totalArtifacts > 0 && hint) {
87
+ lines.push('↳ 原文:guard_query(id, pattern) 或 read ~/.dsh/token-guard/artifacts/<id>.txt')
88
+ }
89
+
90
+ return lines.join('\n')
91
+ }
92
+
93
+ /**
94
+ * 生成索引文本。
95
+ * @param {object} opts
96
+ * @param {string[]} opts.paths 最近使用在前,已归一化、已脱敏
97
+ * @param {object[]} opts.artifacts 最近在前 {id,tool,target,size,status,dup}
98
+ * @param {number} opts.step 只进审计,不进文本(A2)
99
+ * @param {number} opts.compactions
100
+ * @param {object} opts.limits {maxTokens, pathLimit, artifactLimit, targetChars, hint}
101
+ */
102
+ function buildIndex(opts = {}) {
103
+ const { paths = [], artifacts = [], step = 0, compactions = 0 } = opts
104
+ const limits = opts.limits ?? {}
105
+ const maxTokens = clampInt(limits.maxTokens, 1000, 120, 100000)
106
+ const pathLimit = clampInt(limits.pathLimit, 40, 1, 200)
107
+ const artifactLimit = clampInt(limits.artifactLimit, 20, 1, 100)
108
+ const targetChars = clampInt(limits.targetChars, 48, 12, 120)
109
+
110
+ const safePaths = Array.isArray(paths) ? paths.filter((p) => typeof p === 'string' && p) : []
111
+ const safeArtifacts = Array.isArray(artifacts) ? artifacts.filter((a) => a && typeof a === 'object') : []
112
+ const totalPaths = safePaths.length
113
+ const totalArtifacts = safeArtifacts.length
114
+
115
+ if (totalPaths === 0 && totalArtifacts === 0) return emptyResult(step, compactions)
116
+
117
+ // 1) 条数上限(硬约束:paths ≤ pathLimit、artifacts ≤ artifactLimit)
118
+ let shownPaths = safePaths.slice(0, pathLimit)
119
+ let shownArtifacts = safeArtifacts.slice(0, artifactLimit)
120
+
121
+ // 2) token 上限:先裁路径(最不常用在尾部),再裁 artifact,直到放得下
122
+ for (;;) {
123
+ const text = renderBody({
124
+ paths: shownPaths,
125
+ artifacts: shownArtifacts,
126
+ totalPaths,
127
+ totalArtifacts,
128
+ compactions,
129
+ targetChars,
130
+ hint: limits.hint !== false,
131
+ })
132
+ const estTokens = estimateTokens(text)
133
+ if (estTokens <= maxTokens) {
134
+ return {
135
+ text,
136
+ chars: text.length,
137
+ estTokens,
138
+ step,
139
+ compactions,
140
+ pathLines: shownPaths.length,
141
+ artifactLines: shownArtifacts.length,
142
+ droppedPaths: totalPaths - shownPaths.length,
143
+ droppedArtifacts: totalArtifacts - shownArtifacts.length,
144
+ totalPaths,
145
+ totalArtifacts,
146
+ overBudget: false,
147
+ }
148
+ }
149
+ if (shownPaths.length > 0) {
150
+ const drop = Math.max(1, Math.ceil(shownPaths.length * 0.2))
151
+ shownPaths = shownPaths.slice(0, Math.max(0, shownPaths.length - drop))
152
+ continue
153
+ }
154
+ if (shownArtifacts.length > 0) {
155
+ const drop = Math.max(1, Math.ceil(shownArtifacts.length * 0.2))
156
+ shownArtifacts = shownArtifacts.slice(0, Math.max(0, shownArtifacts.length - drop))
157
+ continue
158
+ }
159
+ // 只剩两个 "(+N more)" 标记还是超预算:说明上限配得过小,硬性返回
160
+ return {
161
+ text,
162
+ chars: text.length,
163
+ estTokens,
164
+ step,
165
+ compactions,
166
+ pathLines: 0,
167
+ artifactLines: 0,
168
+ droppedPaths: totalPaths,
169
+ droppedArtifacts: totalArtifacts,
170
+ totalPaths,
171
+ totalArtifacts,
172
+ overBudget: true,
173
+ }
174
+ }
175
+ }
176
+
177
+ module.exports = { buildIndex, renderBody, shorten }