@ssamurias/dsh-fish 1.0.2 → 1.0.4
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/AGENTS.md +3 -3
- package/CHANGELOG.md +64 -0
- package/README.md +103 -14
- package/RELEASE-NOTES-1.0.3.md +91 -0
- package/RELEASE-NOTES-1.0.4.md +80 -0
- package/docs/composite-pressure-v0.1.md +23 -0
- package/docs/composite-pressure-v0.2.md +18 -0
- package/docs/pressure-backtest-v0.1.md +19 -0
- package/docs/session-capacity-advice-v0.1.md +17 -0
- package/docs/session-pressure-design-v1.1.md +1173 -0
- package/docs/session-pressure-ui-v0.3.md +28 -0
- package/docs/tool-retention-diagnostics-v2.md +13 -0
- package/lib/autobackup.js +14 -2
- package/lib/backup.js +141 -12
- package/lib/bili.js +4 -2
- package/lib/browse.js +55 -11
- package/lib/capture.js +41 -9
- package/lib/client.js +2260 -55
- package/lib/cloudbackup.js +24 -1
- package/lib/clouddrive.js +4 -1
- package/lib/compact.js +28 -11
- package/lib/cue.js +114 -0
- package/lib/derive.js +48 -5
- package/lib/desk.js +19 -1
- package/lib/doing.js +1 -1
- package/lib/dreamtable.js +5 -4
- package/lib/drive.js +72 -13
- package/lib/generator.js +1 -1
- package/lib/handoff.js +34 -16
- package/lib/home.js +3 -1
- package/lib/identity.js +15 -0
- package/lib/index.js +7 -1
- package/lib/interest.js +38 -0
- package/lib/look.js +7 -0
- package/lib/make.js +214 -0
- package/lib/note.js +163 -39
- package/lib/observe.js +202 -4
- package/lib/persona.js +66 -13
- package/lib/proactive.js +17 -1
- package/lib/restrict.js +9 -2
- package/lib/sametopic.js +94 -0
- package/lib/scheduler.js +301 -16
- package/lib/selfdoc.js +12 -3
- package/lib/session-pressure-analysis.js +296 -0
- package/lib/session-pressure-data.js +239 -0
- package/lib/session-pressure-formulas.js +280 -0
- package/lib/session-pressure-load.js +110 -0
- package/lib/session-pressure.js +706 -0
- package/lib/settings.js +8 -1
- package/lib/sleepfact.js +110 -0
- package/lib/sub.js +9 -7
- package/lib/turns.js +8 -1
- package/lib/video.js +75 -42
- package/lib/whatseen.js +24 -2
- package/lib/wiki.js +1677 -0
- package/lib/wikiserve.js +148 -0
- package/lib/works.js +526 -0
- package/media/feedback-qr.jpg +0 -0
- package/media/principle-drive.svg +2 -2
- package/media/principle-memory.svg +1 -1
- package/package.json +1 -1
- package/scripts/sync-pressure-formulas.mjs +17 -0
|
@@ -0,0 +1,706 @@
|
|
|
1
|
+
import { promises as fs } from 'node:fs'
|
|
2
|
+
import { createHash } from 'node:crypto'
|
|
3
|
+
import { setImmediate as yieldToHost } from 'node:timers/promises'
|
|
4
|
+
import { join, resolve } from 'node:path'
|
|
5
|
+
import { buildSessionLoad, sessionReferenceEligibility } from './session-pressure-load.js'
|
|
6
|
+
import { pressureDataDictionary, requestBurdenInputs, structurePressureInputs } from './session-pressure-data.js'
|
|
7
|
+
import { analyzePressureEvents, usageOf } from './session-pressure-analysis.js'
|
|
8
|
+
import { looksLikeSecret } from './guard.js'
|
|
9
|
+
import { mutateJson, writeAtomic } from './store.js'
|
|
10
|
+
import { capacityInputs, pressureDefaults, pressureVersions, scoreComposite, scoreDiagnostic } from './session-pressure-formulas.js'
|
|
11
|
+
|
|
12
|
+
export function pressureScore(tokens, threshold) {
|
|
13
|
+
if (!Number.isFinite(tokens) || tokens < 0 || !Number.isFinite(threshold) || threshold <= 0) return null
|
|
14
|
+
return Math.min(100, 100 * tokens / threshold)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function summarizePressure(records, home, observedSince, rotations = {}) {
|
|
18
|
+
const sessions = Object.entries(records).map(([id, turns]) => {
|
|
19
|
+
const rows = Object.values(turns).sort((a, b) => a.seq - b.seq)
|
|
20
|
+
.map(({ threshold, thresholdStatus, ...row }) => ({ ...row, score: pressureScore(row.tokens, row.contextWindow) }))
|
|
21
|
+
const rotatedAt = id === home.rotatedFrom ? home.rotatedAt : rotations[id]
|
|
22
|
+
const scores = rows.map(row => row.score).filter(Number.isFinite)
|
|
23
|
+
return { id, rows, rotatedAt: rotatedAt ?? null, peak: scores.length ? Math.max(...scores) : null,
|
|
24
|
+
endScore: null }
|
|
25
|
+
})
|
|
26
|
+
const current = sessions.find(session => session.id === home.sessionId)
|
|
27
|
+
const rows = (current?.rows ?? []).map((row, i) => {
|
|
28
|
+
const previous = current.rows[i - 1]
|
|
29
|
+
const comparable = previous && row.turn === previous.turn + 1 && row.route === previous.route
|
|
30
|
+
&& row.contextWindow === previous.contextWindow
|
|
31
|
+
&& !row.compacted
|
|
32
|
+
return { ...row, delta: comparable ? row.tokens - previous.tokens : null }
|
|
33
|
+
})
|
|
34
|
+
const tools = new Map()
|
|
35
|
+
for (const row of rows) for (const item of row.tools ?? []) {
|
|
36
|
+
const total = tools.get(item.name) ?? { name: item.name, tokens: 0, calls: 0 }
|
|
37
|
+
total.tokens += item.tokens
|
|
38
|
+
total.calls++
|
|
39
|
+
tools.set(item.name, total)
|
|
40
|
+
}
|
|
41
|
+
const growth = rows.filter(row => row.delta > 0).sort((a, b) => b.delta - a.delta)
|
|
42
|
+
return { observedSince, current: rows.at(-1) ?? null, rows, growth,
|
|
43
|
+
tools: [...tools.values()].sort((a, b) => b.tokens - a.tokens),
|
|
44
|
+
history: sessions.filter(session => session.id !== home.sessionId)
|
|
45
|
+
.map(({ rows: historyRows, ...summary }) => ({ ...summary, count: historyRows.length })) }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function readService(ctx, name) {
|
|
49
|
+
try { return ctx.get?.(name) } catch { return undefined }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function lastRecordedRequest(events, route, latest = null) {
|
|
53
|
+
for (const event of events) {
|
|
54
|
+
if (event.type === 'request/context') route = event.data
|
|
55
|
+
if (event.type !== 'assistant/message') continue
|
|
56
|
+
const usage = usageOf(event.data?.usage)
|
|
57
|
+
if (usage.input == null || usage.output == null) continue
|
|
58
|
+
latest = { seq: event.seq, turn: event.data?.turn ?? null, input: usage.input, output: usage.output,
|
|
59
|
+
total: usage.total,
|
|
60
|
+
contextWindow: route?.contextWindow ?? null, provider: route?.provider ?? null, model: route?.model ?? null, time: event.time }
|
|
61
|
+
}
|
|
62
|
+
return latest
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function* diagnosticRoundBoundaries(events) {
|
|
66
|
+
const completed = new Set()
|
|
67
|
+
for (const [index, event] of events.entries()) {
|
|
68
|
+
if (event.type !== 'turn/end' || event.data?.reason?.kind !== 'completed' || !Number.isSafeInteger(event.data.turn)) continue
|
|
69
|
+
if (completed.has(event.data.turn)) continue
|
|
70
|
+
completed.add(event.data.turn)
|
|
71
|
+
yield { index, event, round: completed.size }
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function diagnosticRoundBoundary(events, rounds) {
|
|
76
|
+
if (!Number.isSafeInteger(rounds) || rounds < 1) return null
|
|
77
|
+
for (const boundary of diagnosticRoundBoundaries(events)) {
|
|
78
|
+
if (boundary.round === rounds) return boundary
|
|
79
|
+
}
|
|
80
|
+
return null
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function registerSessionPressure(ctx, root) {
|
|
84
|
+
const dir = join(root, 'logs', 'session-pressure')
|
|
85
|
+
const file = join(dir, 'samples.json')
|
|
86
|
+
const selectionFile = join(root, 'session-pressure-selection.json')
|
|
87
|
+
|
|
88
|
+
const observedSince = Date.now()
|
|
89
|
+
async function read() {
|
|
90
|
+
try {
|
|
91
|
+
return JSON.parse(await fs.readFile(file, 'utf8'))
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (error.code !== 'ENOENT') throw error
|
|
94
|
+
return { observedSince, records: {} }
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function readHome() {
|
|
99
|
+
try {
|
|
100
|
+
return JSON.parse(await fs.readFile(join(root, 'home.json'), 'utf8'))
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (error.code !== 'ENOENT') throw error
|
|
103
|
+
return {}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function readSelection() {
|
|
108
|
+
try { return JSON.parse(await fs.readFile(selectionFile, 'utf8')) }
|
|
109
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; return {} }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function pathKey(value) {
|
|
113
|
+
if (!value) return ''
|
|
114
|
+
const path = resolve(value)
|
|
115
|
+
return process.platform === 'win32' ? path.toLowerCase() : path
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function discover(home, state) {
|
|
119
|
+
const expected = pathKey(join(root, 'home'))
|
|
120
|
+
const registry = readService(ctx, 'workspaceRegistry')
|
|
121
|
+
const registered = registry?.get?.(home.wsId)
|
|
122
|
+
const workspace = (registry?.list?.() ?? []).find(item => pathKey(item.path) === expected)
|
|
123
|
+
?? (registered && pathKey(registered.path) === expected ? registered : null)
|
|
124
|
+
// 只认「路径确实是她的房间」的那个工作区(2026-11-17 修正):以前直接拿
|
|
125
|
+
// workspaceRegistry.get(home.wsId) 的 sessionIds,一旦 home.wsId 指向的是别的
|
|
126
|
+
// 工作区(桌面版所有对话都在同一个工作区),房外的会话就会被当成她的房间统计进去。
|
|
127
|
+
const known = new Set(workspace?.sessionIds ?? [])
|
|
128
|
+
const query = readService(ctx, 'sessionQuery')
|
|
129
|
+
let discoveryPartial = typeof query?.listSessions !== 'function'
|
|
130
|
+
const cwdOf = new Map()
|
|
131
|
+
try {
|
|
132
|
+
for (const { header } of await query?.listSessions?.() ?? []) {
|
|
133
|
+
if (header?.id) cwdOf.set(header.id, header.cwd)
|
|
134
|
+
if (pathKey(header.cwd) === expected && header.origin !== 'subagent' && !(header.delegationDepth > 0)) known.add(header.id)
|
|
135
|
+
}
|
|
136
|
+
} catch { discoveryPartial = true }
|
|
137
|
+
const selections = await readSelection()
|
|
138
|
+
// 记过的房间也要能证明 cwd 是她的房间(或本来就在那个工作区的 sessionIds 里),
|
|
139
|
+
// 否则桌面版里别的对话会被旧记录带进来(2026-11-17,用户 m02888)。
|
|
140
|
+
const rooms = (home.pressureRoomIds ?? []).filter(id => known.has(id) || pathKey(cwdOf.get(id)) === expected)
|
|
141
|
+
const fish = new Set(rooms)
|
|
142
|
+
const matchingHome = known.has(home.sessionId) || Boolean(registered && pathKey(registered.path) === expected)
|
|
143
|
+
if (matchingHome) {
|
|
144
|
+
for (const id of [home.sessionId, home.rotatedFrom, home.rotatedTo]) {
|
|
145
|
+
if (id) { fish.add(id); known.add(id) }
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
for (const id of Object.keys(state.rotations ?? {})) if (known.has(id)) fish.add(id)
|
|
149
|
+
for (const id of rooms) known.add(id)
|
|
150
|
+
const archived = new Set(registry?.archivedSessionIds ?? [])
|
|
151
|
+
const rows = [...known].map(id => ({
|
|
152
|
+
id, current: id === home.sessionId, fish: fish.has(id), archived: archived.has(id),
|
|
153
|
+
selected: Object.hasOwn(selections, id) ? selections[id] : fish.has(id),
|
|
154
|
+
}))
|
|
155
|
+
return { rows, discoveryPartial }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const cacheDir = join(root, 'session-pressure-cache')
|
|
159
|
+
const snapshotDir = join(cacheDir, 'pressure-v0.3')
|
|
160
|
+
const roundCache = new Map()
|
|
161
|
+
const trendCache = new Map()
|
|
162
|
+
const batchSize = 4
|
|
163
|
+
const pending = new Map()
|
|
164
|
+
const dirty = new Map()
|
|
165
|
+
const failures = new Map()
|
|
166
|
+
const titles = new Map()
|
|
167
|
+
const checked = new Map()
|
|
168
|
+
let worker = null
|
|
169
|
+
let disposed = false
|
|
170
|
+
const idleWaiters = new Set()
|
|
171
|
+
|
|
172
|
+
function notifyIdle() {
|
|
173
|
+
if (!disposed && (worker || pending.size)) return
|
|
174
|
+
for (const notify of idleWaiters) notify()
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function waitForIdle() {
|
|
178
|
+
if (disposed || (!worker && !pending.size)) return
|
|
179
|
+
return new Promise(resolve => {
|
|
180
|
+
const done = () => {
|
|
181
|
+
clearTimeout(timeout)
|
|
182
|
+
idleWaiters.delete(done)
|
|
183
|
+
resolve()
|
|
184
|
+
}
|
|
185
|
+
const timeout = setTimeout(done, 10_000)
|
|
186
|
+
idleWaiters.add(done)
|
|
187
|
+
})
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function cachedAnalysis(id) {
|
|
191
|
+
try {
|
|
192
|
+
const value = JSON.parse(await fs.readFile(join(cacheDir, encodeURIComponent(id) + '.json'), 'utf8'))
|
|
193
|
+
return value.version === 10 ? value : null
|
|
194
|
+
} catch { return null }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async function analyzeSession(id, cached) {
|
|
198
|
+
const query = readService(ctx, 'sessionQuery')
|
|
199
|
+
if (typeof query?.observeSession !== 'function') return { status: 'unavailable' }
|
|
200
|
+
let snapshot
|
|
201
|
+
try {
|
|
202
|
+
snapshot = await query.observeSession(id, { projectionMode: 'none' })
|
|
203
|
+
if (snapshot.header?.origin === 'subagent' || snapshot.header?.delegationDepth > 0) return { status: 'excluded' }
|
|
204
|
+
if (snapshot.cursor > 20_000) return { status: 'too-large' }
|
|
205
|
+
const events = snapshot.events ?? []
|
|
206
|
+
const footer = event => event ? JSON.stringify([event.seq, event.time, event.type]) : null
|
|
207
|
+
const position = cached?.length ?? 0
|
|
208
|
+
const appendOnly = cached && position <= events.length && cached.cursor <= snapshot.cursor
|
|
209
|
+
&& cached.footer === footer(events[position - 1])
|
|
210
|
+
if (appendOnly && cached.cursor === snapshot.cursor && position === events.length) return cached.result
|
|
211
|
+
const added = appendOnly ? events.slice(position) : events
|
|
212
|
+
const prior = appendOnly ? cached : null
|
|
213
|
+
const { checkpoint, ...analysis } = analyzePressureEvents(added, prior?.checkpoint, true)
|
|
214
|
+
const title = added.findLast(event => event.type === 'session/title')?.data?.title ?? prior?.result.title
|
|
215
|
+
const result = { status: 'analyzed', title, ...analysis,
|
|
216
|
+
completedAt: added.findLast(event => event.type === 'turn/end' && event.data?.reason?.kind === 'completed')?.time
|
|
217
|
+
?? prior?.result.completedAt ?? null,
|
|
218
|
+
lastRequest: lastRecordedRequest(added, prior?.checkpoint.route, prior?.result.lastRequest) }
|
|
219
|
+
await fs.mkdir(cacheDir, { recursive: true })
|
|
220
|
+
await writeAtomic(join(cacheDir, encodeURIComponent(id) + '.json'), JSON.stringify({
|
|
221
|
+
version: 10, cursor: snapshot.cursor, length: events.length, footer: footer(events.at(-1)), checkpoint, result,
|
|
222
|
+
}))
|
|
223
|
+
return result
|
|
224
|
+
} catch {
|
|
225
|
+
return { status: 'unavailable' }
|
|
226
|
+
} finally {
|
|
227
|
+
snapshot?.[Symbol.dispose]?.()
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function historicalRound(id, rounds, samples) {
|
|
232
|
+
const key = JSON.stringify([id, rounds])
|
|
233
|
+
const sampleKey = JSON.stringify(samples)
|
|
234
|
+
const cached = roundCache.get(key)
|
|
235
|
+
if (cached && cached.sampleKey === sampleKey && cached.revision === dirty.get(id)) return cached.result
|
|
236
|
+
const query = readService(ctx, 'sessionQuery')
|
|
237
|
+
let snapshot
|
|
238
|
+
try {
|
|
239
|
+
snapshot = await query?.observeSession?.(id, { projectionMode: 'none' })
|
|
240
|
+
if (!snapshot || snapshot.cursor > 20_000 || snapshot.header?.origin === 'subagent' || snapshot.header?.delegationDepth > 0) return null
|
|
241
|
+
const events = snapshot.events ?? []
|
|
242
|
+
const boundary = diagnosticRoundBoundary(events, rounds)
|
|
243
|
+
if (!boundary) return null
|
|
244
|
+
const prefix = events.slice(0, boundary.index + 1)
|
|
245
|
+
const data = { ...analyzePressureEvents(prefix), lastRequest: lastRecordedRequest(prefix), completedAt: boundary.event.time }
|
|
246
|
+
const result = diagnostic(id, data, samples.filter(sample => sample.seq <= boundary.event.seq))
|
|
247
|
+
if (result) result.sourceFingerprint = createHash('sha256')
|
|
248
|
+
.update(JSON.stringify([prefix.map(({ seq, type, time }) => [seq, type, time]), result.inputs])).digest('hex')
|
|
249
|
+
if (roundCache.size >= 256) roundCache.delete(roundCache.keys().next().value)
|
|
250
|
+
roundCache.set(key, { sampleKey, revision: dirty.get(id), result })
|
|
251
|
+
return result
|
|
252
|
+
} catch {
|
|
253
|
+
return null
|
|
254
|
+
} finally {
|
|
255
|
+
snapshot?.[Symbol.dispose]?.()
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function diagnostic(id, data, samples, dictionary) {
|
|
260
|
+
const rows = data.rows ?? []
|
|
261
|
+
const latest = rows.at(-1)
|
|
262
|
+
const rounds = rows.filter(row => row.completed).length
|
|
263
|
+
if (!rounds || !latest.completed || latest.turn !== data.lastRequest?.turn) return null
|
|
264
|
+
const capacity = capacityInputs(dictionary ?? pressureDataDictionary(rows, samples, data.lastRequest, data, null, true))
|
|
265
|
+
const structure = structurePressureInputs(data)
|
|
266
|
+
const inputs = { capacity: { occupancy: capacity.occupancy, growth: capacity.growth, windows: capacity.windows },
|
|
267
|
+
request: requestBurdenInputs(rows, data.lastRequest.contextWindow),
|
|
268
|
+
structure: [structure.currentShare, structure.repeatedShare, structure.retryShare],
|
|
269
|
+
invalidStructure: structure.measurementStatus === 'invalid', structureMeasurementReason: structure.measurementReason }
|
|
270
|
+
const { provider, model, contextWindow } = data.lastRequest
|
|
271
|
+
const route = provider && model && contextWindow > 0 ? JSON.stringify([provider, model, contextWindow]) : null
|
|
272
|
+
const subScores = scoreDiagnostic(inputs, pressureDefaults)
|
|
273
|
+
const scores = scoreComposite(subScores, pressureDefaults.composite, inputs.invalidStructure)
|
|
274
|
+
const configurationChanged = rows.some(row => row.route && row.route !== route)
|
|
275
|
+
return { id, rounds, sampledAt: data.completedAt ?? null, route, configurationChanged,
|
|
276
|
+
versions: pressureVersions, diagnosticsVersion: 'diagnostics-v3', inputs, subScores,
|
|
277
|
+
scores: Object.fromEntries(Object.entries(scores).map(([key, value]) => [key, value.score])),
|
|
278
|
+
parameters: pressureDefaults, completeness: subScores.map(Number.isFinite) }
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
async function trend(id, includeDiagnostics = false) {
|
|
282
|
+
const state = await read()
|
|
283
|
+
const home = await readHome()
|
|
284
|
+
const { rows } = await discover(home, state)
|
|
285
|
+
if (!rows.some(row => row.id === id && (row.current || row.selected))) return null
|
|
286
|
+
const samples = Object.values(state.records[id] ?? {}).sort((a, b) => a.seq - b.seq)
|
|
287
|
+
const revision = dirty.get(id)
|
|
288
|
+
const sampleKey = JSON.stringify([samples, state.compactionPairs?.[id]])
|
|
289
|
+
const cacheKey = JSON.stringify([id, includeDiagnostics])
|
|
290
|
+
const cached = trendCache.get(cacheKey)
|
|
291
|
+
if (cached?.revision === revision && cached?.sampleKey === sampleKey) return cached.result
|
|
292
|
+
const query = readService(ctx, 'sessionQuery')
|
|
293
|
+
let snapshot
|
|
294
|
+
try {
|
|
295
|
+
snapshot = await query?.observeSession?.(id, { projectionMode: 'none' })
|
|
296
|
+
if (!snapshot || snapshot.header?.origin === 'subagent' || snapshot.header?.delegationDepth > 0) return null
|
|
297
|
+
if (snapshot.cursor > 20_000) return { id, status: 'too-large', points: [] }
|
|
298
|
+
const events = snapshot.events ?? []
|
|
299
|
+
const points = []
|
|
300
|
+
let start = 0
|
|
301
|
+
let checkpoint = null
|
|
302
|
+
let lastRequest = null
|
|
303
|
+
let sampleEnd = 0
|
|
304
|
+
let previousRoute = null
|
|
305
|
+
let switched = false
|
|
306
|
+
const fingerprint = createHash('sha256')
|
|
307
|
+
for (const { index, event, round } of diagnosticRoundBoundaries(events)) {
|
|
308
|
+
const chunk = events.slice(start, index + 1)
|
|
309
|
+
lastRequest = lastRecordedRequest(chunk, checkpoint?.route, lastRequest)
|
|
310
|
+
const analysis = analyzePressureEvents(chunk, checkpoint, true)
|
|
311
|
+
checkpoint = analysis.checkpoint
|
|
312
|
+
start = index + 1
|
|
313
|
+
while (sampleEnd < samples.length && samples[sampleEnd].seq <= event.seq) sampleEnd++
|
|
314
|
+
fingerprint.update(JSON.stringify(chunk.map(({ seq, type, time }) => [seq, type, time])))
|
|
315
|
+
const markers = chunk.flatMap(item => {
|
|
316
|
+
if (!['compaction/start', 'compaction/end', 'compaction/prune'].includes(item.type)) return []
|
|
317
|
+
const type = item.type === 'compaction/end'
|
|
318
|
+
? (item.data?.error ? '压缩失败' : '压缩成功')
|
|
319
|
+
: item.type === 'compaction/start' ? '压缩开始' : '裁剪'
|
|
320
|
+
const pair = state.compactionPairs?.[id]?.[item.seq]
|
|
321
|
+
return [{ type, time: item.time ?? null, seq: item.seq, ...(pair ? { tokenChange: pair.after - pair.before } : {}) }]
|
|
322
|
+
})
|
|
323
|
+
const data = { ...analysis, lastRequest, completedAt: event.time }
|
|
324
|
+
const roundSamples = samples.slice(0, sampleEnd)
|
|
325
|
+
const dictionary = pressureDataDictionary(analysis.rows, roundSamples, lastRequest, analysis, null, true)
|
|
326
|
+
const point = diagnostic(id, data, roundSamples, dictionary)
|
|
327
|
+
for (const item of chunk) {
|
|
328
|
+
if (item.type === 'assistant/attempt') markers.push({ type: '模型失败尝试', time: item.time, seq: item.seq })
|
|
329
|
+
if (item.type === 'tool/result' && (item.data?.message?.isError || item.data?.error)) {
|
|
330
|
+
markers.push({ type: '工具失败', time: item.time, seq: item.seq })
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
const completed = analysis.rows.find(row => row.turn === event.data?.turn)
|
|
334
|
+
if (completed?.retries > 0) markers.push({ type: '已匹配重试', time: event.time, count: completed.retries,
|
|
335
|
+
tokens: completed.metrics?.retryTokens })
|
|
336
|
+
for (const { type, data: config, time, seq } of chunk) {
|
|
337
|
+
if (type !== 'request/context' || !config?.provider || !config?.model || !(config.contextWindow > 0)) continue
|
|
338
|
+
const route = [config.provider, config.model, config.contextWindow]
|
|
339
|
+
if (previousRoute && (previousRoute[0] !== route[0] || previousRoute[1] !== route[1])) {
|
|
340
|
+
markers.push({ type: '模型切换', time, seq, from: previousRoute.slice(0, 2), to: route.slice(0, 2) })
|
|
341
|
+
switched = true
|
|
342
|
+
}
|
|
343
|
+
if (previousRoute && previousRoute[2] !== route[2]) {
|
|
344
|
+
markers.push({ type: '窗口切换', time, seq, from: [previousRoute[2]], to: [route[2]] })
|
|
345
|
+
switched = true
|
|
346
|
+
}
|
|
347
|
+
previousRoute = route
|
|
348
|
+
}
|
|
349
|
+
points.push({ round, timestamp: event.time ?? null, markers, switched,
|
|
350
|
+
diagnostics: point && includeDiagnostics ? dictionary.map(metric => ({ id: metric.id, title: metric.title,
|
|
351
|
+
rows: metric.rows.filter(row => !(metric.id === 'T' && row.raw_value?.seq != null))
|
|
352
|
+
.map(({ label, value, unit, source, scope }) => ({ label, value, unit, source, scope })) })) : null, snapshot: point ? {
|
|
353
|
+
id, rounds: round, route: point.route, configurationChanged: point.configurationChanged,
|
|
354
|
+
versions: point.versions, diagnosticsVersion: point.diagnosticsVersion,
|
|
355
|
+
inputs: point.inputs, completeness: point.completeness,
|
|
356
|
+
sourceFingerprint: fingerprint.copy().update(JSON.stringify([point.inputs, markers])).digest('hex'),
|
|
357
|
+
} : null })
|
|
358
|
+
if (round % 8 === 0) await yieldToHost()
|
|
359
|
+
}
|
|
360
|
+
const result = { id, status: 'analyzed', points }
|
|
361
|
+
if (trendCache.size >= 16) trendCache.delete(trendCache.keys().next().value)
|
|
362
|
+
trendCache.set(cacheKey, { revision, sampleKey, result })
|
|
363
|
+
return result
|
|
364
|
+
} catch {
|
|
365
|
+
return { id, status: 'unavailable', points: [] }
|
|
366
|
+
} finally {
|
|
367
|
+
snapshot?.[Symbol.dispose]?.()
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
async function saveDiagnostic(snapshot) {
|
|
372
|
+
if (!snapshot) return
|
|
373
|
+
const folder = join(snapshotDir, encodeURIComponent(snapshot.id))
|
|
374
|
+
const path = join(folder, snapshot.rounds + '.json')
|
|
375
|
+
await mutateJson(path, async () => {
|
|
376
|
+
const body = JSON.stringify(snapshot)
|
|
377
|
+
const previous = await fs.readFile(path, 'utf8').catch(error => {
|
|
378
|
+
if (error.code !== 'ENOENT') throw error
|
|
379
|
+
return null
|
|
380
|
+
})
|
|
381
|
+
if (previous === body) return
|
|
382
|
+
await fs.mkdir(folder, { recursive: true })
|
|
383
|
+
await writeAtomic(path, body)
|
|
384
|
+
})
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function work() {
|
|
388
|
+
if (worker || disposed || !pending.size) return
|
|
389
|
+
worker = setTimeout(async () => {
|
|
390
|
+
try {
|
|
391
|
+
for (const [id, job] of [...pending].slice(0, batchSize)) {
|
|
392
|
+
if (disposed || pending.get(id) !== job) continue
|
|
393
|
+
job.started = true
|
|
394
|
+
const revision = dirty.get(id) ?? 0
|
|
395
|
+
if (job.titleOnly) {
|
|
396
|
+
const query = readService(ctx, 'sessionQuery')
|
|
397
|
+
try {
|
|
398
|
+
const [item] = await query.readTitleSnapshots([id])
|
|
399
|
+
titles.set(id, { revision, title: item?.value?.title?.title ?? null })
|
|
400
|
+
} catch { titles.set(id, { revision, title: null }) }
|
|
401
|
+
if (pending.get(id) === job) pending.delete(id)
|
|
402
|
+
continue
|
|
403
|
+
}
|
|
404
|
+
const result = await analyzeSession(id, job.cached)
|
|
405
|
+
if (result.status !== 'analyzed') failures.set(id, result)
|
|
406
|
+
checked.set(id, revision)
|
|
407
|
+
if (pending.get(id) === job) pending.delete(id)
|
|
408
|
+
}
|
|
409
|
+
} finally {
|
|
410
|
+
worker = null
|
|
411
|
+
work()
|
|
412
|
+
notifyIdle()
|
|
413
|
+
}
|
|
414
|
+
}, 0)
|
|
415
|
+
worker.unref?.()
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async function resultFor(candidate) {
|
|
419
|
+
const { id } = candidate
|
|
420
|
+
if (!candidate.current && !candidate.selected) {
|
|
421
|
+
const cached = await cachedAnalysis(id)
|
|
422
|
+
const revision = dirty.get(id) ?? 0
|
|
423
|
+
const title = titles.get(id)
|
|
424
|
+
if (title?.revision === revision) return { status: 'unchecked', title: title.title }
|
|
425
|
+
if (cached?.result.title && !revision) return { status: 'unchecked', title: cached.result.title }
|
|
426
|
+
if (typeof readService(ctx, 'sessionQuery')?.readTitleSnapshots === 'function' && !pending.has(id)) {
|
|
427
|
+
pending.set(id, { titleOnly: true })
|
|
428
|
+
work()
|
|
429
|
+
}
|
|
430
|
+
return { status: 'unchecked', title: cached?.result.title }
|
|
431
|
+
}
|
|
432
|
+
if (pending.has(id) && !pending.get(id).titleOnly) return { status: 'pending' }
|
|
433
|
+
const cached = await cachedAnalysis(id)
|
|
434
|
+
if (pending.has(id) && !pending.get(id).titleOnly) return { status: 'pending', title: cached?.result.title }
|
|
435
|
+
const revision = dirty.get(id) ?? 0
|
|
436
|
+
if (revision === checked.get(id)) return failures.get(id) ?? cached?.result ?? { status: 'unavailable' }
|
|
437
|
+
if (cached && candidate.archived && !revision) return cached.result
|
|
438
|
+
failures.delete(id)
|
|
439
|
+
pending.set(id, { cached })
|
|
440
|
+
work()
|
|
441
|
+
return { status: 'pending', title: cached?.result.title }
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
const interruptedFile = join(dir, 'interrupted.json')
|
|
445
|
+
|
|
446
|
+
async function readInterrupted(id) {
|
|
447
|
+
try {
|
|
448
|
+
const all = JSON.parse(await fs.readFile(interruptedFile, 'utf8'))
|
|
449
|
+
return Array.isArray(all?.[id]) ? all[id] : []
|
|
450
|
+
} catch { return [] }
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// 被中断的轮不记用量,但留一条标记,界面能说清「这轮没数据」(2026-11-18 用户 m03880)。
|
|
454
|
+
async function recordInterrupted(session, event) {
|
|
455
|
+
const id = String(session?.header?.id ?? '')
|
|
456
|
+
const turn = event?.data?.turn
|
|
457
|
+
if (!id || !Number.isSafeInteger(turn)) return
|
|
458
|
+
const home = await readHome()
|
|
459
|
+
if (id !== home.sessionId) return
|
|
460
|
+
await mutateJson(interruptedFile, async () => {
|
|
461
|
+
let all = {}
|
|
462
|
+
try { all = JSON.parse(await fs.readFile(interruptedFile, 'utf8')) } catch (error) { if (error.code !== 'ENOENT') return }
|
|
463
|
+
const list = Array.isArray(all?.[id]) ? all[id] : []
|
|
464
|
+
if (list.some(rec => rec?.turn === turn)) return
|
|
465
|
+
all = { ...all, [id]: [...list, { turn, seq: event.seq, time: event.time }].slice(-200) }
|
|
466
|
+
await fs.mkdir(dir, { recursive: true })
|
|
467
|
+
await writeAtomic(interruptedFile, JSON.stringify(all))
|
|
468
|
+
})
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
async function record(session, event) {
|
|
472
|
+
const id = String(session?.header?.id ?? '')
|
|
473
|
+
const { seq, time } = event
|
|
474
|
+
const turn = event.data?.turn
|
|
475
|
+
if (!id || !Number.isSafeInteger(seq) || !Number.isSafeInteger(turn)) return
|
|
476
|
+
const home = await readHome()
|
|
477
|
+
if (id !== home.sessionId) return
|
|
478
|
+
const route = session.requestContext?.()
|
|
479
|
+
if (!route?.provider || !route?.model) return
|
|
480
|
+
const measurement = readService(ctx, 'tokenMeter')?.measure?.(session)
|
|
481
|
+
// 旧门槛要求 measurement.logRevision === seq + 1,实测大多轮次对不上(样本 103 轮只落了 1 条,
|
|
482
|
+
// 2026-11-18 用户反馈),这里放宽为「量测不能落后于本轮」;重复轮次由 turn 去重。
|
|
483
|
+
if (!Number.isFinite(measurement?.totalTokens)) return
|
|
484
|
+
if (Number.isFinite(measurement.logRevision) && measurement.logRevision < seq) return
|
|
485
|
+
const calls = new Map()
|
|
486
|
+
let compacted = false
|
|
487
|
+
for (let i = seq - 1; i >= 0; i--) {
|
|
488
|
+
const entry = session.eventAt?.(i)
|
|
489
|
+
if (!entry || entry.type === 'turn/end') break
|
|
490
|
+
if (['compaction/summary', 'compaction/prune'].includes(entry.type)
|
|
491
|
+
|| (entry.type === 'compaction/end' && !entry.data?.error)) compacted = true
|
|
492
|
+
}
|
|
493
|
+
for (let i = seq - 1; i >= 0; i--) {
|
|
494
|
+
const entry = session.eventAt?.(i)
|
|
495
|
+
if (!entry || entry.type === 'turn/start' || entry.type === 'turn/end') break
|
|
496
|
+
if (entry.type !== 'assistant/message') continue
|
|
497
|
+
for (const block of entry.data?.message?.content ?? []) {
|
|
498
|
+
if (block.type === 'tool-call' && typeof block.name === 'string' && !looksLikeSecret(block.name).hit) calls.set(block.id, block.name)
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
const tools = []
|
|
502
|
+
for (const node of measurement.nodes ?? []) {
|
|
503
|
+
const entry = session.eventAt?.(node.seq)
|
|
504
|
+
if (entry?.type !== 'tool/result' || entry.data?.turn !== turn) continue
|
|
505
|
+
const name = calls.get(entry.data?.message?.toolCallId)
|
|
506
|
+
if (name && Number.isFinite(node.tokens)) tools.push({ name, tokens: node.tokens })
|
|
507
|
+
}
|
|
508
|
+
const tokens = measurement.totalTokens
|
|
509
|
+
const row = { seq, time, turn, tokens, contextWindow: route.contextWindow ?? null,
|
|
510
|
+
route: JSON.stringify([route.provider, route.model]), compacted, tools }
|
|
511
|
+
await mutateJson(file, async () => {
|
|
512
|
+
const state = await read()
|
|
513
|
+
const existing = Object.hasOwn(state.records, id) ? state.records[id] : {}
|
|
514
|
+
if (Object.hasOwn(existing, seq)) return
|
|
515
|
+
// 同一轮只留一条(重放/重试会换 seq,但轮次相同),否则中位数会被同一轮重复计数。
|
|
516
|
+
if (Object.values(existing).some(rec => rec?.turn === turn)) return
|
|
517
|
+
state.records = { ...state.records, [id]: { ...existing, [seq]: row } }
|
|
518
|
+
if (home.rotatedFrom && home.rotatedAt) {
|
|
519
|
+
state.rotations = { ...state.rotations, [home.rotatedFrom]: home.rotatedAt }
|
|
520
|
+
}
|
|
521
|
+
await fs.mkdir(dir, { recursive: true })
|
|
522
|
+
await writeAtomic(file, JSON.stringify(state))
|
|
523
|
+
})
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
const compactionStarts = new Map()
|
|
527
|
+
function sampleCompaction(session, event) {
|
|
528
|
+
const id = session?.header?.id
|
|
529
|
+
const compactionId = event.data?.compactionId
|
|
530
|
+
if (!id || typeof compactionId !== 'string') return
|
|
531
|
+
const key = JSON.stringify([id, compactionId])
|
|
532
|
+
const opening = event.type === 'compaction/start'
|
|
533
|
+
const before = compactionStarts.get(key)
|
|
534
|
+
if (!opening) compactionStarts.delete(key)
|
|
535
|
+
if ((!opening && (!before || event.data.error)) || typeof session.requestContext !== 'function') return
|
|
536
|
+
const route = session.requestContext()
|
|
537
|
+
const meter = readService(ctx, 'tokenMeter')
|
|
538
|
+
const measurement = meter?.measure?.(session)
|
|
539
|
+
if (!route?.provider || !route?.model || !Number.isFinite(measurement?.totalTokens)
|
|
540
|
+
|| measurement.logRevision !== event.seq + 1) return
|
|
541
|
+
const point = { tokens: measurement.totalTokens, route: JSON.stringify([route.provider, route.model, route.contextWindow]) }
|
|
542
|
+
if (opening) {
|
|
543
|
+
compactionStarts.set(key, point)
|
|
544
|
+
if (compactionStarts.size > 64) compactionStarts.delete(compactionStarts.keys().next().value)
|
|
545
|
+
return
|
|
546
|
+
}
|
|
547
|
+
if (before.route !== point.route) return
|
|
548
|
+
return mutateJson(file, async () => {
|
|
549
|
+
if ((await readHome()).sessionId !== id) return
|
|
550
|
+
const state = await read()
|
|
551
|
+
state.compactions = { ...state.compactions, [id]: { before: before.tokens, after: point.tokens } }
|
|
552
|
+
state.compactionPairs ??= {}
|
|
553
|
+
state.compactionPairs[id] = { ...state.compactionPairs[id], [event.seq]: state.compactions[id] }
|
|
554
|
+
await fs.mkdir(dir, { recursive: true })
|
|
555
|
+
await writeAtomic(file, JSON.stringify(state))
|
|
556
|
+
})
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
const off = ctx.on?.('session/event', (session, event) => {
|
|
560
|
+
const id = session?.header?.id
|
|
561
|
+
if (['compaction/start', 'compaction/end'].includes(event?.type)) {
|
|
562
|
+
try { void sampleCompaction(session, event)?.catch(() => {}) } catch { /* Meter unavailable. */ }
|
|
563
|
+
}
|
|
564
|
+
if (id && ['turn/end', 'session/title', 'compaction/end', 'compaction/prune'].includes(event?.type)) dirty.set(id, (dirty.get(id) ?? 0) + 1)
|
|
565
|
+
if (event?.type === 'turn/end') {
|
|
566
|
+
const kind = event.data?.reason?.kind
|
|
567
|
+
if (kind && kind !== 'completed') void recordInterrupted(session, event).catch(() => {})
|
|
568
|
+
else void record(session, event).catch(() => {})
|
|
569
|
+
}
|
|
570
|
+
})
|
|
571
|
+
return {
|
|
572
|
+
trend,
|
|
573
|
+
dispose: () => { disposed = true; clearTimeout(worker); pending.clear(); notifyIdle(); off?.() },
|
|
574
|
+
waitForIdle,
|
|
575
|
+
async select(id, selected) {
|
|
576
|
+
if (typeof id !== 'string' || typeof selected !== 'boolean') return false
|
|
577
|
+
const { rows } = await discover(await readHome(), await read())
|
|
578
|
+
const candidate = rows.find(row => row.id === id && !row.current)
|
|
579
|
+
if (!candidate) return false
|
|
580
|
+
await mutateJson(selectionFile, async () => {
|
|
581
|
+
const choices = await readSelection()
|
|
582
|
+
await writeAtomic(selectionFile, JSON.stringify({ ...choices, [id]: selected }))
|
|
583
|
+
})
|
|
584
|
+
if (selected) await resultFor({ ...candidate, selected: true })
|
|
585
|
+
else if (!pending.get(id)?.started) pending.delete(id)
|
|
586
|
+
return true
|
|
587
|
+
},
|
|
588
|
+
async view(includeComposite = false, sessionId = null) {
|
|
589
|
+
const referenceRounds = 'end'
|
|
590
|
+
const state = await read()
|
|
591
|
+
const home = await readHome()
|
|
592
|
+
const view = summarizePressure(state.records, home, state.observedSince, state.rotations)
|
|
593
|
+
if (!home.sessionId) return { ...view, availability: 'no-session' }
|
|
594
|
+
// 对话页上的入口按会话取数(2026-11-17,用户 m02719):只认她这间房的会话,
|
|
595
|
+
// 房外的会话一律 not-fish,界面据此什么都不显示,也不参与历史对照。
|
|
596
|
+
const wanted = typeof sessionId === 'string' && sessionId ? sessionId : null
|
|
597
|
+
const { rows: candidates, discoveryPartial } = await discover(home, state)
|
|
598
|
+
const asked = wanted ? candidates.find(row => row.id === wanted) : null
|
|
599
|
+
if (wanted && !asked) return { availability: 'not-fish', sessionId: wanted }
|
|
600
|
+
const currentId = asked ? asked.id : home.sessionId
|
|
601
|
+
const live = readService(ctx, 'sessions')?.get?.(currentId)
|
|
602
|
+
const meter = readService(ctx, 'tokenMeter')
|
|
603
|
+
if (live && typeof meter?.measure === 'function' && live.requestHeader?.()) {
|
|
604
|
+
const contextWindow = live.requestContext?.()?.contextWindow ?? null
|
|
605
|
+
const { totalTokens } = meter.measure(live)
|
|
606
|
+
if (Number.isFinite(totalTokens)) view.live = { tokens: totalTokens,
|
|
607
|
+
score: pressureScore(totalTokens, contextWindow), contextWindow }
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
const current = asked
|
|
611
|
+
? await resultFor({ ...asked, current: true, selected: true })
|
|
612
|
+
: candidates.some(row => row.current)
|
|
613
|
+
? await resultFor({ current: true, id: home.sessionId })
|
|
614
|
+
: { status: 'unavailable' }
|
|
615
|
+
const dictionary = pressureDataDictionary(current.rows ?? [], view.rows, current.lastRequest, current, state.compactions?.[currentId])
|
|
616
|
+
const completedRounds = (current.rows ?? []).filter(row => row.completed).length
|
|
617
|
+
const composite = includeComposite && currentId === home.sessionId
|
|
618
|
+
const currentDiagnostic = composite && completedRounds
|
|
619
|
+
? await historicalRound(currentId, completedRounds, view.rows) : null
|
|
620
|
+
const comparison = composite ? { current: currentDiagnostic,
|
|
621
|
+
rounds: completedRounds, history: [], saveFailed: false } : null
|
|
622
|
+
const history = []
|
|
623
|
+
const amplificationHistory = []
|
|
624
|
+
const baseline = []
|
|
625
|
+
const loadHistory = []
|
|
626
|
+
// 轮询已经去掉(挂载/打开时各一次),这里保留全量历史,第一屏要用它算同轮中位数。
|
|
627
|
+
for (const candidate of candidates) {
|
|
628
|
+
const { id } = candidate
|
|
629
|
+
const data = candidate.current ? current : await resultFor(candidate)
|
|
630
|
+
const title = typeof data.title === 'string' && !looksLikeSecret(data.title).hit ? data.title : null
|
|
631
|
+
const rows = data.rows ?? []
|
|
632
|
+
const complete = rows.filter(row => row.completeUsage)
|
|
633
|
+
if (comparison && completedRounds && !candidate.current && candidate.selected) {
|
|
634
|
+
const samples = Object.values(state.records[id] ?? {}).sort((a, b) => a.seq - b.seq)
|
|
635
|
+
const hasRound = rows.filter(row => row.completed).length >= completedRounds
|
|
636
|
+
const snapshot = data.status === 'analyzed' && hasRound
|
|
637
|
+
? await historicalRound(id, completedRounds, samples) : null
|
|
638
|
+
comparison.history.push({ id, title, snapshot, reason: snapshot ? null
|
|
639
|
+
: data.status === 'pending' ? 'pending' : data.status !== 'analyzed' ? 'unavailable'
|
|
640
|
+
: !hasRound ? 'short' : 'missing' })
|
|
641
|
+
}
|
|
642
|
+
if (!candidate.current && data.status === 'analyzed' && rows.length) {
|
|
643
|
+
loadHistory.push(data)
|
|
644
|
+
amplificationHistory.push({ id, title, rows: rows.map(row => ({
|
|
645
|
+
turn: row.turn, requests: row.requests, attempts: row.attempts, first: row.metrics?.firstInput,
|
|
646
|
+
extra: row.load?.A ?? null,
|
|
647
|
+
})) })
|
|
648
|
+
for (const row of complete) if (row.completed) baseline.push(row.total.value)
|
|
649
|
+
}
|
|
650
|
+
history.push({ ...candidate, title, status: data.status, turns: rows.length, usageTurns: complete.length,
|
|
651
|
+
referenceEligibility: sessionReferenceEligibility(data, referenceRounds) })
|
|
652
|
+
}
|
|
653
|
+
// 历史同轮中位数(2026-11-18 用户 m03803):每个历史会话逐轮的「该轮总用量 ÷ 该轮窗口」,
|
|
654
|
+
// 按轮号取跨会话中位数;样本 <3 只作参考,>=10 才算基准。
|
|
655
|
+
const turnPoints = new Map()
|
|
656
|
+
for (const data of loadHistory) {
|
|
657
|
+
if (data === current) continue
|
|
658
|
+
const seen = new Map()
|
|
659
|
+
for (const row of data.rows ?? []) {
|
|
660
|
+
const total = Number(row.total?.value)
|
|
661
|
+
const win = Number(row.requestWindow)
|
|
662
|
+
if (!(win > 0) || !Number.isFinite(total)) continue
|
|
663
|
+
seen.set(row.turn, Math.min(160, 100 * total / win))
|
|
664
|
+
}
|
|
665
|
+
for (const [turn, pct] of seen) {
|
|
666
|
+
const list = turnPoints.get(turn) ?? []
|
|
667
|
+
list.push(pct)
|
|
668
|
+
turnPoints.set(turn, list)
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
const medianOf = values => {
|
|
672
|
+
const x = [...values].sort((a, b) => a - b)
|
|
673
|
+
const m = x.length >> 1
|
|
674
|
+
return x.length % 2 ? x[m] : (x[m - 1] + x[m]) / 2
|
|
675
|
+
}
|
|
676
|
+
const historyCurve = [...turnPoints.entries()].sort((a, b) => a[0] - b[0])
|
|
677
|
+
.map(([turn, values]) => ({ turn, pct: Math.round(medianOf(values) * 10) / 10, n: values.length }))
|
|
678
|
+
// 严格同轮(2026-11-18 用户 m03880):没有第 N 轮的样本就不给比较。
|
|
679
|
+
const nearestCurve = historyCurve.find(point => point.turn === completedRounds) ?? null
|
|
680
|
+
const medianPoint = nearestCurve ? { turn: nearestCurve.turn, pct: nearestCurve.pct, n: nearestCurve.n } : null
|
|
681
|
+
const interruptedRounds = (await readInterrupted(currentId)).length
|
|
682
|
+
// 压缩记录只来自宿主事件流;别的压缩插件不共享数据(2026-11-18 用户 m03969)。
|
|
683
|
+
const compactionCount = Object.keys(state.compactionPairs?.[currentId] ?? {}).length
|
|
684
|
+
const selectedHistory = history.filter(row => row.selected && !row.current)
|
|
685
|
+
const pendingCount = history.filter(row => row.status === 'pending' || pending.get(row.id)?.titleOnly).length
|
|
686
|
+
const analyzedCount = selectedHistory.filter(row => row.status === 'analyzed').length
|
|
687
|
+
const partial = discoveryPartial || analyzedCount < selectedHistory.length
|
|
688
|
+
const sorted = baseline.sort((a, b) => a - b)
|
|
689
|
+
const reference = sorted.length >= 10
|
|
690
|
+
? { count: sorted.length, p90: sorted[Math.ceil(sorted.length * .9) - 1] }
|
|
691
|
+
: { count: sorted.length, p90: null }
|
|
692
|
+
if (comparison) {
|
|
693
|
+
try { await saveDiagnostic(currentDiagnostic) } catch { comparison.saveFailed = true }
|
|
694
|
+
}
|
|
695
|
+
return { ...view, updatedAt: Date.now(), availability: current.status, historyCurve, medianPoint, interruptedRounds, compactionCount, lastRequest: current.lastRequest, load: buildSessionLoad(current, partial ? [] : loadHistory, null, referenceRounds),
|
|
696
|
+
usage: { structurePressure: structurePressureInputs(current), requestBurden: requestBurdenInputs(current.rows ?? [], current.lastRequest?.contextWindow ?? null),
|
|
697
|
+
amplificationHistory, dictionary, comparison, latest: current.latest, burden: current.burden?.slice(0, 10),
|
|
698
|
+
retentionComplete: current.retentionComplete, toolResults: current.toolResults ?? [],
|
|
699
|
+
roundDiagnostics: (current.rows ?? []).slice(-200).map(row => ({ turn: row.turn, window: row.requestWindow ?? null, first: row.metrics?.firstInput ?? null, input: row.input.value,
|
|
700
|
+
output: row.output.value, requests: row.requests, retained: row.metrics?.tools?.tokens,
|
|
701
|
+
cache: row.cache, attempts: row.attempts, toolErrors: row.toolErrors })),
|
|
702
|
+
reference: partial ? null : reference, history, discovered: candidates.length,
|
|
703
|
+
discoveryPartial, partial, pendingCount, analyzedCount, selectedCount: selectedHistory.length } }
|
|
704
|
+
},
|
|
705
|
+
}
|
|
706
|
+
}
|