@linxin666/dsh-liangshen 0.1.13

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.
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Analyze one or more DSH session JSONL exports and report the LiangShen
3
+ * trajectory markers: first-turn surface, promotion boundary, reasoning-block
4
+ * word markers (`we` / `let me` / `let's` / `I`), the first reasoning line,
5
+ * and per-step drift points.
6
+ *
7
+ * Usage:
8
+ * node tools/analyze-session.mjs <session.jsonl> [more.jsonl ...]
9
+ */
10
+
11
+ import { createReadStream } from 'node:fs'
12
+ import readline from 'node:readline'
13
+
14
+ import { classifyReasoning } from '../presets/liangshen/tool-bootstrap.mjs'
15
+
16
+ const WORD = {
17
+ we: /\bwe\b/gi,
18
+ letMe: /\blet me\b/gi,
19
+ lets: /\blet's\b/gi,
20
+ i: /\bi\b/gi,
21
+ }
22
+
23
+ export function countMarkers(text) {
24
+ return {
25
+ we: countWord(text, WORD.we),
26
+ letMe: countWord(text, WORD.letMe),
27
+ lets: countWord(text, WORD.lets),
28
+ i: countWord(text, WORD.i),
29
+ }
30
+ }
31
+
32
+ function countWord(text, regex) {
33
+ return [...text.matchAll(regex)].length
34
+ }
35
+
36
+ /** Legacy helper: materialize every parsed event (kept for callers that need the array). */
37
+ export async function readEvents(path) {
38
+ const events = []
39
+ const input = createReadStream(path)
40
+ const lines = readline.createInterface({ input, crlfDelay: Infinity })
41
+ for await (const line of lines) {
42
+ const trimmed = line.trim()
43
+ if (trimmed.length === 0) continue
44
+ try {
45
+ events.push(JSON.parse(trimmed))
46
+ } catch {
47
+ // Ignore malformed tail lines from a partially flushed export.
48
+ }
49
+ }
50
+ return events
51
+ }
52
+
53
+ /**
54
+ * Incremental session accumulator shared by the array and streaming paths so
55
+ * both report exactly the same facts. It never retains parsed events or full
56
+ * reasoning text: only the first session/header event, one-line header
57
+ * summaries, per-step counters/first lines, marker totals, and the first
58
+ * reasoning line plus its classification are kept.
59
+ */
60
+ function createSessionAccumulator() {
61
+ return {
62
+ eventCount: 0,
63
+ hasSession: false,
64
+ session: undefined,
65
+ hasFirstHeader: false,
66
+ firstHeader: undefined,
67
+ firstHeaderSeq: Number.POSITIVE_INFINITY,
68
+ pendingFirstMessages: [],
69
+ firstMessages: [],
70
+ headers: [],
71
+ toolCalls: new Map(),
72
+ steps: new Map(),
73
+ current: null,
74
+ reasoningBlocks: 0,
75
+ markers: zeroMarkers(),
76
+ hasFirstReasoning: false,
77
+ firstReasoningLine: null,
78
+ firstClassification: null,
79
+ }
80
+ }
81
+
82
+ function accumulateSessionEvent(acc, event) {
83
+ if (!acc.hasSession && event.type === 'session') {
84
+ acc.session = event
85
+ acc.hasSession = true
86
+ }
87
+ if (event.type === 'user/message') {
88
+ const kind = event.data?.source?.kind ?? 'unknown'
89
+ if (acc.hasFirstHeader) {
90
+ if (event.seq < acc.firstHeaderSeq) acc.firstMessages.push(kind)
91
+ } else {
92
+ acc.pendingFirstMessages.push({ seq: event.seq, kind })
93
+ }
94
+ }
95
+ if (event.type === 'request/header') {
96
+ if (!acc.hasFirstHeader) {
97
+ acc.firstHeader = event
98
+ acc.hasFirstHeader = true
99
+ acc.firstHeaderSeq = event.seq ?? Number.POSITIVE_INFINITY
100
+ acc.firstMessages = acc.pendingFirstMessages
101
+ .filter(entry => entry.seq < acc.firstHeaderSeq)
102
+ .map(entry => entry.kind)
103
+ acc.pendingFirstMessages.length = 0
104
+ }
105
+ acc.headers.push({
106
+ seq: event.seq,
107
+ reason: event.data?.reason,
108
+ tools: (event.data?.header?.tools ?? []).map(tool => tool.name),
109
+ })
110
+ }
111
+ if (event.type === 'step/start') {
112
+ acc.current = { turn: event.data?.turn, step: event.data?.step }
113
+ const key = stepKey(acc.current)
114
+ if (!acc.steps.has(key)) {
115
+ acc.steps.set(key, { turn: acc.current.turn, step: acc.current.step, blocks: 0, ...zeroMarkers(), text: 0, firstLine: null })
116
+ }
117
+ }
118
+ if (event.type === 'assistant/message' && acc.current !== null) {
119
+ const step = acc.steps.get(stepKey(acc.current))
120
+ for (const block of event.data?.message?.content ?? []) {
121
+ if (block.type === 'reasoning') {
122
+ const text = String(block.text ?? '')
123
+ const markers = countMarkers(text)
124
+ acc.reasoningBlocks += 1
125
+ for (const key of markerKeys()) acc.markers[key] += markers[key]
126
+ if (!acc.hasFirstReasoning) {
127
+ acc.hasFirstReasoning = true
128
+ acc.firstReasoningLine = text.trim().split(/\r?\n/, 1)[0] ?? ''
129
+ acc.firstClassification = classifyReasoning(text)
130
+ }
131
+ step.blocks += 1
132
+ for (const key of markerKeys()) step[key] += markers[key]
133
+ if (step.firstLine === null && text.trim().length > 0) {
134
+ step.firstLine = text.trim().split(/\r?\n/, 1)[0] ?? ''
135
+ }
136
+ } else if (block.type === 'text' && String(block.text ?? '').trim().length > 0) {
137
+ step.text += 1
138
+ }
139
+ }
140
+ }
141
+ if (event.type === 'tool/call') {
142
+ const name = event.data?.name ?? 'unknown'
143
+ acc.toolCalls.set(name, (acc.toolCalls.get(name) ?? 0) + 1)
144
+ }
145
+ acc.eventCount += 1
146
+ }
147
+
148
+ function finalizeSessionReport(acc, droppedLines) {
149
+ if (!acc.hasFirstHeader) {
150
+ acc.firstMessages = acc.pendingFirstMessages
151
+ .filter(entry => entry.seq < Number.POSITIVE_INFINITY)
152
+ .map(entry => entry.kind)
153
+ acc.pendingFirstMessages.length = 0
154
+ }
155
+ const markers = { ...acc.markers }
156
+ const totalMarkers = markers.we + markers.letMe
157
+ const driftSteps = [...acc.steps.values()]
158
+ .filter(step => step.letMe > 0 || (step.firstLine !== null && classifyReasoning(step.firstLine).label === 'standard-like'))
159
+ .map(step => ({
160
+ turn: step.turn,
161
+ step: step.step,
162
+ letMe: step.letMe,
163
+ we: step.we,
164
+ text: step.text,
165
+ firstLine: step.firstLine,
166
+ }))
167
+ const visibleReplies = [...acc.steps.values()].reduce((sum, step) => sum + step.text, 0)
168
+
169
+ return {
170
+ sessionId: acc.session?.id,
171
+ preset: acc.session?.agentPreset,
172
+ cwd: acc.session?.cwd,
173
+ createdAt: acc.session?.createdAt,
174
+ firstMessages: acc.firstMessages,
175
+ firstHeader: !acc.hasFirstHeader ? null : {
176
+ system: acc.firstHeader.data?.header?.system,
177
+ tools: (acc.firstHeader.data?.header?.tools ?? []).map(tool => tool.name),
178
+ config: acc.firstHeader.data?.header?.config,
179
+ },
180
+ headers: acc.headers,
181
+ reasoningBlocks: acc.reasoningBlocks,
182
+ markers,
183
+ ratio: totalMarkers === 0 ? null : markers.we / totalMarkers,
184
+ firstReasoningLine: acc.firstReasoningLine,
185
+ firstClassification: acc.firstClassification,
186
+ visibleReplies,
187
+ toolCalls: [...acc.toolCalls.entries()].sort((a, b) => b[1] - a[1]),
188
+ driftSteps,
189
+ droppedLines,
190
+ }
191
+ }
192
+
193
+ /** Aggregate one session's model-visible trajectory facts from an event array. */
194
+ export function analyzeSession(events) {
195
+ const acc = createSessionAccumulator()
196
+ for (const event of events) accumulateSessionEvent(acc, event)
197
+ return finalizeSessionReport(acc, 0)
198
+ }
199
+
200
+ /**
201
+ * Incrementally aggregate a JSONL line stream without materializing events.
202
+ * Returns null when no line yielded a processable event, preserving the
203
+ * historical empty/all-bad file behavior of the CLI.
204
+ */
205
+ export async function analyzeSessionStream(lines) {
206
+ const acc = createSessionAccumulator()
207
+ let droppedLines = 0
208
+ for await (const line of lines) {
209
+ const trimmed = String(line).trim()
210
+ if (trimmed.length === 0) continue
211
+ try {
212
+ accumulateSessionEvent(acc, JSON.parse(trimmed))
213
+ } catch {
214
+ droppedLines += 1
215
+ }
216
+ }
217
+ if (acc.eventCount === 0) return null
218
+ return finalizeSessionReport(acc, droppedLines)
219
+ }
220
+
221
+ /** Stream one session JSONL file through the incremental accumulator. */
222
+ export async function analyzeSessionFile(path) {
223
+ const input = createReadStream(path)
224
+ const lines = readline.createInterface({ input, crlfDelay: Infinity })
225
+ return analyzeSessionStream(lines)
226
+ }
227
+
228
+ function stepKey(step) {
229
+ return `${step.turn}:${step.step}`
230
+ }
231
+
232
+ function markerKeys() {
233
+ return ['we', 'letMe', 'lets', 'i']
234
+ }
235
+
236
+ function zeroMarkers() {
237
+ return { we: 0, letMe: 0, lets: 0, i: 0 }
238
+ }
239
+
240
+ export function renderSessionReport(report) {
241
+ const lines = []
242
+ lines.push(`session ${report.sessionId ?? '(unknown)'}`)
243
+ lines.push(` preset=${report.preset ?? '(none)'} cwd=${report.cwd ?? '(none)'}`)
244
+ if ((report.droppedLines ?? 0) > 0) {
245
+ lines.push(` dropped lines: ${report.droppedLines} (unparseable JSONL lines skipped)`)
246
+ }
247
+ lines.push(` first messages: ${report.firstMessages.join(', ')}`)
248
+ lines.push(` first header: ${report.firstHeader?.tools.join('/') ?? '(none)'} | system=${JSON.stringify(report.firstHeader?.system ?? '')}`)
249
+ for (const header of report.headers) {
250
+ lines.push(` header seq=${header.seq} reason=${header.reason ?? '?'} tools=${header.tools.length} [${header.tools.slice(0, 6).join(', ')}${header.tools.length > 6 ? ', ...' : ''}]`)
251
+ }
252
+ lines.push(` reasoning blocks=${report.reasoningBlocks} we=${report.markers.we} let_me=${report.markers.letMe} let's=${report.markers.lets} I=${report.markers.i}`)
253
+ lines.push(` we/(we+let_me)=${report.ratio === null ? 'n/a' : report.ratio.toFixed(2)} visible replies=${report.visibleReplies}`)
254
+ if (report.firstReasoningLine !== null) {
255
+ lines.push(` first reasoning: ${report.firstReasoningLine}`)
256
+ lines.push(` first block label: ${report.firstClassification?.label ?? 'n/a'} (score ${report.firstClassification?.score ?? '-'})`)
257
+ }
258
+ if (report.toolCalls.length > 0) {
259
+ lines.push(` top tools: ${report.toolCalls.slice(0, 6).map(([name, count]) => `${name}=${count}`).join(' ')}`)
260
+ }
261
+ if (report.driftSteps.length > 0) {
262
+ lines.push(` drift steps: ${report.driftSteps.slice(0, 12).map(step => `(${step.turn},${step.step}) lm=${step.letMe} we=${step.we} vis=${step.text}`).join(' | ')}`)
263
+ } else {
264
+ lines.push(' drift steps: none')
265
+ }
266
+ return lines.join('\n')
267
+ }
268
+
269
+ const isMain = process.argv[1] !== undefined
270
+ && (await import('node:url')).pathToFileURL(process.argv[1]).href === import.meta.url
271
+
272
+ if (isMain) {
273
+ const files = process.argv.slice(2)
274
+ if (files.length === 0) {
275
+ console.error('usage: node tools/analyze-session.mjs <session.jsonl> [more.jsonl ...]')
276
+ process.exitCode = 1
277
+ } else {
278
+ for (const file of files) {
279
+ const report = await analyzeSessionFile(file)
280
+ if (report === null) {
281
+ console.error(`no events read from ${file}`)
282
+ process.exitCode = 1
283
+ continue
284
+ }
285
+ console.log(renderSessionReport(report))
286
+ console.log()
287
+ }
288
+ }
289
+ }