dsh-session-matrix 0.0.0-stage → 0.16.2

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,740 @@
1
+ /**
2
+ * Host-half contract test. Runs the plugin against a fake Cordis context whose
3
+ * session records are derived from the real `workspace.json` + dsh-context
4
+ * cache shapes, so the aggregation logic is exercised on realistic topology
5
+ * without touching the running DSH.
6
+ *
7
+ * Run: node test/host.test.mjs
8
+ */
9
+
10
+ import assert from 'node:assert/strict'
11
+ import { readFileSync } from 'node:fs'
12
+ import { homedir, tmpdir } from 'node:os'
13
+ import { join } from 'node:path'
14
+ import { apply, costOfBuckets } from '../lib/index.js'
15
+
16
+ const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
17
+
18
+ /**
19
+ * Load real session ids and workspace membership; fall back to a synthetic
20
+ * fixture when the user's data is unavailable (e.g. CI).
21
+ * @returns {{records: object[], workspaces: object[], projections: Map<string, object>}}
22
+ */
23
+ function loadFixture() {
24
+ try {
25
+ const ws = JSON.parse(readFileSync(join(DSH_HOME, 'storages', 'workspace.json'), 'utf8'))
26
+ const ctxCache = JSON.parse(
27
+ readFileSync(join(DSH_HOME, 'storages', 'dsh-context', 'overview-cache.v1.json'), 'utf8'))
28
+
29
+ const workspaces = Object.entries(ws.tables.workspaces).map(([id, w]) => ({
30
+ id, title: w.title, path: w.path, sessionIds: w.sessionIds,
31
+ }))
32
+
33
+ const projections = new Map()
34
+ const records = []
35
+ for (const row of ctxCache.sessions) {
36
+ const s = row.session
37
+ records.push({
38
+ header: {
39
+ id: s.id,
40
+ createdAt: s.updatedAt,
41
+ cwd: s.cwd,
42
+ parentSession: s.parentSession,
43
+ isSeeded: false,
44
+ ...(s.origin === 'subagent' ? { origin: 'subagent' } : {}),
45
+ },
46
+ live: records.length % 3 === 0,
47
+ persisted: true,
48
+ })
49
+ projections.set(s.id, {
50
+ contextTimeline: s.timeline
51
+ ? {
52
+ model: s.timeline.model,
53
+ contextWindow: s.timeline.contextWindow,
54
+ maxOutputTokens: s.timeline.maxOutputTokens,
55
+ turns: s.timeline.turns,
56
+ steps: s.timeline.steps,
57
+ current: s.timeline.current,
58
+ }
59
+ : null,
60
+ contextActivity: s.activity ?? null,
61
+ title: s.title,
62
+ sessionListMetadata: { blank: s.blank, lastPromptAt: s.updatedAt },
63
+ })
64
+ }
65
+
66
+ // One synthetic cold session with no projection, to exercise degradation.
67
+ const ghostId = 'session-00000000-0000-4000-8000-000000000000'
68
+ records.push({
69
+ header: { id: ghostId, createdAt: Date.now(), cwd: '/tmp/ghost', isSeeded: false },
70
+ live: false,
71
+ persisted: true,
72
+ })
73
+
74
+ return { records, workspaces, projections }
75
+ } catch {
76
+ // Self-contained fixture: CI has no DSH home to read, so this path has to
77
+ // cover every shape the assertions rely on — a stub, a parent, a subagent,
78
+ // and a session with provider-reported usage.
79
+ const records = [
80
+ { header: { id: 'session-a', createdAt: 1, cwd: '/work/Alpha', isSeeded: false }, live: true, persisted: true },
81
+ { header: { id: 'session-b', createdAt: 2, cwd: '/work/Alpha', parentSession: 'session-a', isSeeded: false, origin: 'subagent' }, live: false, persisted: true },
82
+ { header: { id: 'session-stub', createdAt: 4, cwd: '/work/Alpha', isSeeded: false }, live: false, persisted: true },
83
+ { header: { id: 'session-wrapped', createdAt: 5, cwd: '/work/Alpha', isSeeded: false }, live: false, persisted: true },
84
+ ]
85
+ const projections = new Map([
86
+ ['session-a', {
87
+ contextTimeline: { model: 'deepseek-flash', contextWindow: 1_000_000, maxOutputTokens: 256_000, current: { system: 100, tools: 200, user: 50, inject: 0, skill: 0, assistant: 300, tool: 400, total: 1050 } },
88
+ contextActivity: {
89
+ days: {
90
+ '2026-11-15': {
91
+ tokens: 900,
92
+ requests: 3,
93
+ // Provider-reported buckets; usageOf() reads this shape when the
94
+ // host does not register the tokenUsage projection.
95
+ cost: { deepseek: { 'deepseek-flash': { offPeak: { uncached: 400, cacheRead: 1600, cacheWrite: 0, output: 250 } } } },
96
+ },
97
+ },
98
+ },
99
+ title: 'Alpha task',
100
+ sessionListMetadata: { blank: false, lastPromptAt: 3 },
101
+ }],
102
+ ['session-wrapped', {
103
+ contextTimeline: null,
104
+ // Real hosts wrap the projection value as { ver, seq, val }.
105
+ tokenUsage: { ver: 2, seq: 9, val: { totals: { uncachedInputTokens: 1200, outputTokens: 800, cacheReadTokens: 300, cacheWriteTokens: 0 } } },
106
+ contextActivity: null,
107
+ title: 'Wrapped usage',
108
+ sessionListMetadata: { blank: false, lastPromptAt: 5 },
109
+ }],
110
+ ['session-stub', {
111
+ contextTimeline: null,
112
+ contextActivity: null,
113
+ title: 'New session',
114
+ sessionListMetadata: { blank: true, lastPromptAt: 4 },
115
+ }],
116
+ ])
117
+ return {
118
+ records,
119
+ workspaces: [{ id: 'w1', title: 'Alpha', path: '/work/Alpha', sessionIds: ['session-a', 'session-b', 'session-stub', 'session-wrapped'] }],
120
+ projections,
121
+ }
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Build a fake Cordis context exposing only what the plugin injects.
127
+ * @param fixture - fixture data.
128
+ * @param opts - capability toggles.
129
+ * @returns {{ctx: object, routes: Map<string, object>, state: object}}
130
+ */
131
+ function makeCtx(fixture, opts = {}) {
132
+ const routes = new Map()
133
+ const state = { events: [], warnings: [], infos: [] }
134
+ const noIndexHome = join(tmpdir(), `sm-no-index-${process.pid}-${Math.random().toString(36).slice(2)}`)
135
+ const persistence = {
136
+ revision: 'r1',
137
+ sizeBytes: 2048,
138
+ opens: 0,
139
+ stats: 0,
140
+ closed: 0,
141
+ opened: [],
142
+ // One peak request and one off-peak request, so the split is non-trivial.
143
+ events: [
144
+ { seq: 1, type: 'assistant/message', time: Date.UTC(2026, 10, 16, 2, 0), data: { usage: { inputTokens: 100, outputTokens: 10 } } },
145
+ { seq: 2, type: 'assistant/attempt', time: Date.UTC(2026, 10, 16, 12, 0), data: { stream: [{ type: 'chunk', time: Date.UTC(2026, 10, 16, 12, 0), chunk: { type: 'usage', usage: { inputTokens: 200, outputTokens: 20 } } }] } },
146
+ ],
147
+ }
148
+ state.persistence = persistence
149
+
150
+ const sessionProjections = opts.withProjections === false ? undefined : {
151
+ snapshot: (session, keys) => {
152
+ const values = fixture.projections.get(session.id) ?? {}
153
+ const picked = {}
154
+ for (const k of keys) if (k in values) picked[k] = values[k]
155
+ return { asOfSeq: 0, values: picked }
156
+ },
157
+ summaryKeys: () => new Set(['contextTimeline', 'contextActivity', 'title', 'sessionListMetadata']),
158
+ }
159
+
160
+ const workspaceRegistry = opts.withWorkspaces === false ? undefined : {
161
+ list: () => fixture.workspaces,
162
+ }
163
+
164
+ // Connection is what makes the plugin's exact routes authenticated; the fake
165
+ // keeps the same shape so the contract test exercises the real registration
166
+ // path instead of the (removed) unauthenticated fallback.
167
+ const connection = opts.noConnection === true ? undefined : {
168
+ fetch: {
169
+ register: route => {
170
+ routes.set(route.path, { ...route, resource: route.fetch })
171
+ return () => routes.delete(route.path)
172
+ },
173
+ },
174
+ }
175
+
176
+ const services = {
177
+ sessionProjections,
178
+ workspaceRegistry,
179
+ appBoot: { version: '0.2.2-rc.3' },
180
+ connection,
181
+ }
182
+
183
+ const ctx = {
184
+ logger: {
185
+ info: m => state.infos.push(String(m)),
186
+ warn: m => state.warnings.push(String(m)),
187
+ debug: () => {},
188
+ },
189
+ get: key => services[key],
190
+ webServer: {
191
+ register: route => {
192
+ routes.set(route.path, route)
193
+ return () => routes.delete(route.path)
194
+ },
195
+ },
196
+ sessionQuery: {
197
+ listSessions: async () => fixture.records,
198
+ inspectSession: async (id, read) => {
199
+ const rec = fixture.records.find(r => r.header.id === id)
200
+ if (!rec) throw new Error(`unknown session ${id}`)
201
+ return read({ id, header: rec.header })
202
+ },
203
+ // Records carry no payload — this is the shape that made every pane say
204
+ // "还没有消息" when the route read from here instead of `readSession`.
205
+ listEvents: async id => {
206
+ if (id === 'unknown') throw new Error('not found')
207
+ return [{ seq: 0, type: 'user/message', time: 1 }, { seq: 1, type: 'assistant/message', time: 2 }]
208
+ },
209
+ readSession: async id => {
210
+ if (id === 'unknown') throw new Error('not found')
211
+ return {
212
+ session: { id, createdAt: 1, origin: 'user' },
213
+ inheritedEventCount: 0,
214
+ events: [
215
+ { seq: 0, type: 'turn/start', time: 1, data: { turn: 1 } },
216
+ { seq: 1, type: 'user/message', time: 2, data: { content: '检查这个模块' , source: 'user' } },
217
+ { seq: 2, type: 'tool/call', time: 3, data: { name: 'read' } },
218
+ { seq: 3, type: 'assistant/message', time: 4, data: { content: [{ type: 'text', text: '主要增长在工具返回。' }] } },
219
+ ],
220
+ }
221
+ },
222
+ },
223
+ sessions: { list: () => [] },
224
+ // Official persistence double. `revision` is the change token the plugin is
225
+ // supposed to trust; `opens` counts real reads so a stale-cache bug shows up
226
+ // as a missing open instead of a silently old number.
227
+ sessionPersistence: opts.persistence === false ? undefined : {
228
+ stat: async id => {
229
+ persistence.stats += 1
230
+ return { header: { id }, revision: persistence.revision, sizeBytes: persistence.sizeBytes }
231
+ },
232
+ open: async (id, access) => {
233
+ if (access !== 'read') throw new Error('unexpected access')
234
+ persistence.opens += 1
235
+ persistence.opened.push(persistence.revision)
236
+ return {
237
+ read: async () => ({ eventState: 'owned', events: persistence.events }),
238
+ close: async () => { persistence.closed += 1 },
239
+ }
240
+ },
241
+ },
242
+ // A home path with no sessions directory: the persistence path must not need
243
+ // the file index, and this proves it (indexSessionLogs returns an empty map).
244
+ dshHomePath: (...parts) => join(noIndexHome, ...parts),
245
+ effect: fn => { const d = fn(); return d },
246
+ on: (name, handler) => { state.events.push(name); return () => {} },
247
+ }
248
+ return { ctx, routes, state }
249
+ }
250
+
251
+ /**
252
+ * Invoke one registered resource route.
253
+ * @param routes - route map.
254
+ * @param path - pathname.
255
+ * @param query - query string.
256
+ * @returns parsed JSON body.
257
+ */
258
+ async function hit(routes, path, query = '') {
259
+ const route = routes.get(path)
260
+ assert.ok(route, `route ${path} not registered`)
261
+ assert.equal(typeof route.resource, 'function', `${path} must answer as a resource`)
262
+ const res = await route.resource(new Request(`http://localhost${path}${query ? `?${query}` : ''}`))
263
+ return { status: res.status, body: await res.json() }
264
+ }
265
+
266
+ async function main() {
267
+ const fixture = loadFixture()
268
+ const pass = []
269
+ const fail = []
270
+
271
+ const check = (label, fn) => {
272
+ try { fn(); pass.push(label) } catch (error) { fail.push(`${label}: ${error.message}`) }
273
+ }
274
+ /** Same, for checks that must await a request. */
275
+ const checkAsync = async (label, fn) => {
276
+ try { await fn(); pass.push(label) } catch (error) { fail.push(`${label}: ${error.message}`) }
277
+ }
278
+
279
+ // ── 1. Normal path ───────────────────────────────────────────────────────
280
+ const { ctx, routes, state } = makeCtx(fixture)
281
+ // `prices: false` keeps the contract test offline: the cost estimate needs
282
+ // models.dev, and a unit test must not depend on the network.
283
+ apply(ctx, { cacheTtlMs: 1000, coldBudgetMs: 5000, prices: false })
284
+
285
+ check('registers the three read routes', () => {
286
+ // The session-detail route was removed with the in-cell preview: panes host
287
+ // the real conversation now, so the host no longer needs to ship text.
288
+ assert.equal(routes.size, 3)
289
+ assert.ok(routes.has('/api/session-matrix/overview'))
290
+ assert.ok(routes.has('/api/session-matrix/capabilities'))
291
+ assert.ok(routes.has('/api/session-matrix/handoff'))
292
+ })
293
+
294
+ check('subscribes to session lifecycle events', () => {
295
+ assert.ok(state.events.includes('session/event'))
296
+ assert.ok(state.events.includes('session/created'))
297
+ assert.ok(state.events.includes('session/disposed'))
298
+ })
299
+
300
+ const handoff = await hit(routes, '/api/session-matrix/handoff')
301
+ check('handoff route serves the bundled prompt', () => {
302
+ assert.equal(handoff.status, 200)
303
+ assert.equal(handoff.body.version, 'v1')
304
+ assert.ok(handoff.body.bytes > 1000, 'prompt looks truncated')
305
+ assert.match(handoff.body.hash, /^[0-9a-f]{12}$/)
306
+ assert.ok(handoff.body.text.includes('{{SESSION_TITLE}}'), 'title placeholder missing')
307
+ assert.ok(handoff.body.text.includes('{{HANDOFF_ID}}'), 'file-name placeholder missing')
308
+ // The markers are what v2 will scrape; losing them silently breaks the plan.
309
+ assert.ok(handoff.body.text.includes('<<<HANDOFF-MSG'))
310
+ assert.ok(handoff.body.text.includes('HANDOFF-MSG>>>'))
311
+ assert.ok(handoff.body.text.includes('已否决'), 'rejected-approaches section missing')
312
+ assert.deepEqual(handoff.body.placeholders, ['SESSION_TITLE', 'HANDOFF_ID', 'DATE'])
313
+ })
314
+
315
+ const unknownVersion = await hit(routes, '/api/session-matrix/handoff', 'v=v9')
316
+ check('handoff route rejects unknown versions', () => {
317
+ assert.equal(unknownVersion.status, 404)
318
+ assert.deepEqual(unknownVersion.body.versions, ['v1'])
319
+ })
320
+
321
+ const caps = await hit(routes, '/api/session-matrix/capabilities')
322
+ check('capabilities reports projections + workspaces', () => {
323
+ assert.equal(caps.status, 200)
324
+ assert.equal(caps.body.contextProjections, true)
325
+ assert.equal(caps.body.workspaceRegistry, true)
326
+ assert.ok(caps.body.projectionKeys.includes('contextTimeline'))
327
+ })
328
+
329
+ const overview = await hit(routes, '/api/session-matrix/overview')
330
+ const body = overview.body
331
+ const byId = new Map(body.sessions.map(s => [s.id, s]))
332
+
333
+ check('overview lists every session except unused stubs', () => {
334
+ assert.equal(overview.status, 200)
335
+ const stubs = Number(body.capabilities.emptyStubs ?? 0)
336
+ assert.ok(stubs >= 1, 'fixture should contain an unused stub')
337
+ assert.equal(body.sessions.length, fixture.records.length - stubs)
338
+ })
339
+
340
+ check('a blank session with no turns is not listed', () => {
341
+ for (const s of body.sessions) {
342
+ assert.ok(!(s.blank === true && (s.turns ?? 0) === 0), `stub leaked: ${s.id}`)
343
+ }
344
+ assert.equal(body.totals.all, body.sessions.length)
345
+ })
346
+
347
+ check('dto carries the full contract', () => {
348
+ const sample = body.sessions.find(s => s.contextAvailable)
349
+ assert.ok(sample, 'expected at least one session with context')
350
+ for (const key of ['id', 'title', 'project', 'origin', 'model', 'contextWindow', 'total', 'ratio', 'parts', 'risk', 'activityDays']) {
351
+ assert.ok(key in sample, `missing field ${key}`)
352
+ }
353
+ assert.deepEqual(Object.keys(sample.parts).sort(), ['assistant', 'inject', 'skill', 'system', 'tool', 'tools', 'user'])
354
+ })
355
+
356
+ check('ratio equals total / contextWindow', () => {
357
+ const sample = body.sessions.find(s => s.total != null && s.contextWindow)
358
+ const expected = sample.total / sample.contextWindow
359
+ assert.ok(Math.abs(sample.ratio - expected) < 1e-9)
360
+ })
361
+
362
+ // Regression: an earlier version used `min(window × 0.8, window − output − 64K)`,
363
+ // which warned well before DSH actually compacts. The shipped policy is
364
+ // `window − reservedCompletionTokens − headroomTokens(4096)`.
365
+ check('compaction point mirrors dsh-compaction-basic', () => {
366
+ const sample = body.sessions.find(s => s.contextWindow === 1_000_000)
367
+ assert.ok(sample, 'fixture should carry a 1M-window session')
368
+ assert.equal(sample.compactTokens, 1_000_000 - 256_000 - 4096)
369
+ assert.ok(Math.abs(sample.compactRatio - (1_000_000 - 256_000 - 4096) / 1_000_000) < 1e-9)
370
+ // Compacted history keeps 16% of (window − output) verbatim; the client
371
+ // renders this, so it has to travel in the DTO.
372
+ assert.equal(sample.compactRetain, Math.round((1_000_000 - 256_000) * 0.16))
373
+ })
374
+
375
+ // Regression: the `title` projection folds to `string | null`. Reading
376
+ // `.title` off it produced `undefined` and every row fell back to the
377
+ // "Untitled session" label — the live panel showed a wall of Untitled.
378
+ check('title projection string is used verbatim', () => {
379
+ for (const s of body.sessions) {
380
+ assert.ok(!/^Untitled/.test(s.title), `session ${s.id} fell back to Untitled`)
381
+ assert.ok(typeof s.title === 'string' && s.title.trim().length > 0,
382
+ `session ${s.id} has an empty title`)
383
+ }
384
+ })
385
+
386
+ check('risk level follows the compaction point, not a flat percentage', () => {
387
+ assert.equal(body.thresholds.warnFactor, 0.8)
388
+ assert.equal(body.thresholds.criticalFactor, 0.92)
389
+ for (const s of body.sessions) {
390
+ if (s.ratio == null) { assert.equal(s.risk, 'unknown'); continue }
391
+ assert.ok(s.compactRatio > 0 && s.compactRatio <= 0.8,
392
+ `compactRatio out of range for ${s.id}: ${s.compactRatio}`)
393
+ if (s.ratio >= s.compactRatio * 0.92) assert.equal(s.risk, 'crit', `${s.id} @ ${s.ratio}`)
394
+ else if (s.ratio >= s.compactRatio * 0.8) assert.equal(s.risk, 'warn', `${s.id} @ ${s.ratio}`)
395
+ else assert.equal(s.risk, 'ok', `${s.id} @ ${s.ratio}`)
396
+ }
397
+ })
398
+
399
+ check('cost doubles the peak bucket and converts to CNY', () => {
400
+ const timeline = {
401
+ cost: {
402
+ 'deepseek-official': {
403
+ 'deepseek-flash': {
404
+ off: { uncached: 1_000_000, cacheRead: 0, cacheWrite: 0, output: 1_000_000 },
405
+ peak: { uncached: 1_000_000, cacheRead: 0, cacheWrite: 0, output: 0 },
406
+ },
407
+ },
408
+ },
409
+ }
410
+ const price = { input: 0.15, cacheRead: 0.003, cacheWrite: 0, output: 0.6 }
411
+ const result = costOfBuckets(timeline, () => price)
412
+ // off: 1M x 0.15 + 1M x 0.6 = 0.75 USD; peak: 1M x 0.15 x 2 = 0.30 USD.
413
+ assert.ok(Math.abs(result.usd - 1.05) < 1e-9, `usd ${result.usd}`)
414
+ assert.ok(Math.abs(result.cny - 1.05 / 0.15) < 1e-9, `cny ${result.cny}`)
415
+ assert.equal(result.peakBuckets, 1)
416
+ assert.equal(costOfBuckets({}, () => price), null, 'no buckets means no cost')
417
+
418
+ // Official DeepSeek table: quoted in CNY, so no exchange rate is involved.
419
+ const official = costOfBuckets(timeline, () => null, () => ({ hit: 0.02, miss: 1, out: 4 }))
420
+ // off: 1M x 1 + 1M x 4 = 5 CNY; peak: 1M x 1 x 2 = 2 CNY
421
+ assert.ok(Math.abs(official.cny - 7) < 1e-9, `cny ${official.cny}`)
422
+ assert.equal(official.officialModels, 1)
423
+ })
424
+
425
+ check('usage and cost are reported per session', () => {
426
+ const withUsage = body.sessions.filter(s => s.usage)
427
+ assert.ok(withUsage.length > 0, 'expected at least one session with provider usage')
428
+ for (const s of withUsage) {
429
+ for (const key of ['uncached', 'cacheRead', 'cacheWrite', 'output']) {
430
+ assert.equal(typeof s.usage[key], 'number', `${s.id} usage.${key}`)
431
+ }
432
+ }
433
+ // Pricing needs the network, so the test disables it: the field must exist
434
+ // and be null rather than missing or zero.
435
+ for (const s of body.sessions) {
436
+ assert.ok('costUsd' in s, `${s.id} has no costUsd field`)
437
+ assert.ok(s.costUsd === null || typeof s.costUsd === 'number')
438
+ }
439
+ // A wrapped { ver, seq, val } projection must still yield usage — that is what
440
+ // keeps cost working on a host without dsh-context.
441
+ const wrapped = byId.get('session-wrapped')
442
+ if (wrapped) {
443
+ assert.ok(wrapped.usage, 'wrapped tokenUsage should produce usage')
444
+ assert.equal(wrapped.usage.cacheRead, 300)
445
+ }
446
+
447
+ assert.equal(body.pricing.enabled, false, 'prices:false must reach the payload')
448
+ assert.equal(body.pricing.ready, false)
449
+ })
450
+
451
+ // The client used to carry its own COMPACT_RATIO/HEADROOM copy; it drifted
452
+ // from the host the moment the host was fixed. One formula, one place.
453
+ check('client consumes the compaction point instead of recomputing it', () => {
454
+ const code = readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
455
+ assert.ok(!/COMPACT_HEADROOM|COMPACT_RATIO/.test(code), 'client still defines compaction constants')
456
+ assert.ok(code.includes('session.compactTokens'), 'client should read the DTO field')
457
+ })
458
+
459
+ check('subagent project resolves through the parent chain', () => {
460
+ const sub = body.sessions.find(s => s.origin === 'subagent' && s.parentId)
461
+ if (!sub) return
462
+ const parent = byId.get(sub.parentId)
463
+ if (!parent) return
464
+ assert.equal(sub.project, parent.project,
465
+ `subagent project ${sub.project} should match parent ${parent.project}`)
466
+ })
467
+
468
+ // The chip row must mirror the workspaces the user actually has. A session
469
+ // outside every workspace path goes to the '' (unassigned) bucket instead of
470
+ // inventing a project from its cwd.
471
+ check('cwd near a workspace name folds into that workspace', () => {
472
+ const folded = body.sessions.filter(s => /AIVde/i.test(s.cwd ?? ''))
473
+ if (!folded.length) return
474
+ for (const s of folded) assert.equal(s.project, 'AIVideo', `not folded: ${s.cwd}`)
475
+ const titles = body.projects.map(p => p.title)
476
+ assert.ok(!titles.includes('AIVdeio'), 'typo folder still listed as its own project')
477
+ })
478
+
479
+ check('projects cover every resolved session project', () => {
480
+ const distinct = new Set(body.sessions.map(s => s.project))
481
+ const listed = new Set(body.projects.map(p => p.title))
482
+ for (const title of distinct) {
483
+ assert.ok(listed.has(title), `project "${title}" appears on sessions but not in the list`)
484
+ }
485
+ // '' is the deliberate "belongs to no workspace" bucket.
486
+ for (const p of body.projects) assert.equal(typeof p.title, 'string')
487
+ })
488
+
489
+ check('project counts sum to the session total', () => {
490
+ const sum = body.projects.reduce((n, p) => n + p.count, 0)
491
+ assert.equal(sum, body.sessions.length)
492
+ })
493
+
494
+ check('totals separate user and subagent sessions', () => {
495
+ const t = body.totals
496
+ assert.equal(t.all, body.sessions.length)
497
+ assert.equal(t.user + t.subagent, t.all)
498
+ })
499
+
500
+ check('session without projections degrades to unknown, not zero', () => {
501
+ const ghost = body.sessions.find(s => s.id.startsWith('session-00000000'))
502
+ if (!ghost) return
503
+ assert.equal(ghost.contextAvailable, false)
504
+ assert.equal(ghost.ratio, null)
505
+ assert.equal(ghost.risk, 'unknown')
506
+ assert.equal(ghost.parts, null)
507
+ assert.notEqual(ghost.total, 0, 'must not report 0 tokens for unknown context')
508
+ })
509
+
510
+ // ── 2. 上下文口径:provider 压力优先于逐事件估算 ──────────────────────────
511
+ // Real numbers from one live session: the event estimate said 387,554 while
512
+ // the provider reported a 665,491-token prompt. Getting this precedence wrong
513
+ // makes the panel report ~37% for a session that DSH's own footer calls 63%.
514
+ const pressureFixture = {
515
+ records: [{
516
+ header: { id: 'session-p', createdAt: 1, cwd: '/work/Alpha', isSeeded: false },
517
+ live: true,
518
+ persisted: true,
519
+ }],
520
+ workspaces: [{ id: 'w1', title: 'Alpha', path: '/work/Alpha', sessionIds: ['session-p'] }],
521
+ projections: new Map([['session-p', {
522
+ contextTimeline: {
523
+ model: 'deepseek-flash',
524
+ provider: 'deepseek-official',
525
+ contextWindow: 1_048_576,
526
+ maxOutputTokens: 256_000,
527
+ turns: 55,
528
+ steps: 406,
529
+ last: { seq: 10, total: 387_554, prompt: 665_491 },
530
+ current: {
531
+ system: 3_249, tools: 15_281, user: 20_000, inject: 30_000,
532
+ skill: 10_000, assistant: 120_000, tool: 189_000, total: 387_530,
533
+ },
534
+ },
535
+ contextPressure: {
536
+ pressureTokens: 665_491, projectedTokens: 665_767, contextWindow: 1_048_576,
537
+ },
538
+ contextBreakdown: { systemTokens: 3_249, toolsTokens: 15_281, messageTokens: 335_413 },
539
+ // Turns/steps live on sessionStats, not on the timeline wire view.
540
+ sessionStats: { turns: 55, steps: 406, llmMs: 1, toolMs: 1 },
541
+ contextActivity: { days: { '2026-11-16': { tokens: 1000, requests: 3 } } },
542
+ title: 'Pressure probe',
543
+ sessionListMetadata: { blank: false, lastPromptAt: 5 },
544
+ }]]),
545
+ }
546
+ const pressured = makeCtx(pressureFixture)
547
+ apply(pressured.ctx, { prices: false })
548
+ const pBody = (await hit(pressured.routes, '/api/session-matrix/overview')).body
549
+ const p = pBody.sessions[0]
550
+
551
+ check('provider-reported pressure beats the event estimate', () => {
552
+ assert.equal(p.contextSource, 'projected')
553
+ assert.equal(p.total, 665_767)
554
+ assert.equal(p.estimatedTotal, 387_530)
555
+ assert.ok(Math.abs(p.ratio - 665_767 / 1_048_576) < 1e-12)
556
+ // 63.5% real, and that lands between the warn (55.5%) and crit (63.8%) lines.
557
+ assert.equal(p.risk, 'warn')
558
+ // Regression: turns/steps are not on the timeline wire view. Reading them
559
+ // from there made every row show "— / —" while the footer said 55 轮 406 步.
560
+ assert.equal(p.turns, 55)
561
+ assert.equal(p.steps, 406)
562
+ })
563
+
564
+ check('composition sums to the measured total', () => {
565
+ const sum = Object.values(p.parts).reduce((n, v) => n + v, 0)
566
+ assert.ok(Math.abs(sum - p.total) <= 7, `parts sum ${sum} vs total ${p.total}`)
567
+ assert.deepEqual(Object.keys(p.parts).sort(),
568
+ ['assistant', 'inject', 'skill', 'system', 'tool', 'tools', 'user'])
569
+ })
570
+
571
+ const noPressure = {
572
+ ...pressureFixture,
573
+ projections: new Map([['session-p', {
574
+ // No contextPressure / contextBreakdown, but the timeline still carries
575
+ // the provider prompt of the last request.
576
+ contextTimeline: pressureFixture.projections.get('session-p').contextTimeline,
577
+ title: 'Prompt anchored',
578
+ sessionListMetadata: { blank: false, lastPromptAt: 5 },
579
+ }]]),
580
+ }
581
+ const estimateCtx = makeCtx(noPressure)
582
+ apply(estimateCtx.ctx, { prices: false })
583
+ const estBody = (await hit(estimateCtx.routes, '/api/session-matrix/overview')).body
584
+
585
+ check('falls back to the last request prompt when pressure is missing', () => {
586
+ const row = estBody.sessions[0]
587
+ assert.equal(row.contextSource, 'prompt+delta')
588
+ // 665_491 provider prompt + (387_530 - 387_554) heuristic delta.
589
+ assert.equal(row.total, 665_467)
590
+ })
591
+
592
+ const bareTimeline = { ...noPressure, projections: new Map([['session-p', {
593
+ contextTimeline: { ...noPressure.projections.get('session-p').contextTimeline, last: undefined },
594
+ title: 'Estimate only',
595
+ sessionListMetadata: { blank: false, lastPromptAt: 5 },
596
+ }]]) }
597
+ const bareCtx = makeCtx(bareTimeline)
598
+ apply(bareCtx.ctx, { prices: false })
599
+ const bareBody = (await hit(bareCtx.routes, '/api/session-matrix/overview')).body
600
+
601
+ check('last resort is the event estimate, labelled as such', () => {
602
+ const row = bareBody.sessions[0]
603
+ assert.equal(row.contextSource, 'estimate')
604
+ assert.equal(row.total, 387_530)
605
+ assert.equal(row.estimatedTotal, 387_530)
606
+ })
607
+
608
+ // ── 3. Degradation without dsh-context ───────────────────────────────────
609
+ const degraded = makeCtx(fixture, { withProjections: false })
610
+ apply(degraded.ctx, { prices: false })
611
+ const dCaps = await hit(degraded.routes, '/api/session-matrix/capabilities')
612
+ check('capabilities reports missing projections', () => {
613
+ assert.equal(dCaps.body.contextProjections, false)
614
+ assert.deepEqual(dCaps.body.projectionKeys, [])
615
+ })
616
+ const dOverview = await hit(degraded.routes, '/api/session-matrix/overview')
617
+ check('overview still answers without projections', () => {
618
+ assert.equal(dOverview.status, 200)
619
+ assert.equal(dOverview.body.sessions.length, fixture.records.length)
620
+ const s = dOverview.body.sessions.find(x => x.total === null)
621
+ assert.ok(s, 'expected sessions reported with null total')
622
+ assert.equal(s.risk, 'unknown')
623
+ })
624
+
625
+ // A session with no title source must still read like a session, never like
626
+ // the old placeholder string.
627
+ check('untitled sessions fall back to a readable label', () => {
628
+ for (const s of dOverview.body.sessions) {
629
+ assert.ok(/^(子代理|未命名会话|新会话)/.test(s.title), `bad fallback: ${s.title}`)
630
+ }
631
+ })
632
+
633
+ // ── 3. Degradation without workspaceRegistry ─────────────────────────────
634
+ const noWs = makeCtx(fixture, { withWorkspaces: false })
635
+ apply(noWs.ctx, { prices: false })
636
+ const wOverview = await hit(noWs.routes, '/api/session-matrix/overview')
637
+ check('without a registry every session is unassigned', () => {
638
+ assert.equal(wOverview.status, 200)
639
+ const withCwd = wOverview.body.sessions.find(s => s.cwd)
640
+ assert.ok(withCwd, 'expected a session with cwd')
641
+ // No registry means no workspace to attribute to: report the honest empty
642
+ // bucket instead of turning each cwd into a fake project.
643
+ assert.equal(withCwd.project, '')
644
+ })
645
+
646
+ // ── 4. Cache behavior ────────────────────────────────────────────────────
647
+ const first = await hit(routes, '/api/session-matrix/overview')
648
+ const second = await hit(routes, '/api/session-matrix/overview')
649
+ check('repeat read is served from the snapshot', () => {
650
+ assert.equal(first.body.generatedAt, second.body.generatedAt,
651
+ 'second read within TTL must reuse the collected snapshot')
652
+ })
653
+ const forced = await hit(routes, '/api/session-matrix/overview', 'refresh=1')
654
+ check('refresh=1 recollects', () => {
655
+ assert.ok(forced.body.generatedAt >= first.body.generatedAt)
656
+ })
657
+
658
+ // ── persistence: revision semantics ──────────────────────────────────────
659
+ // These run against the fake sessionPersistence in makeCtx; they would fail on
660
+ // the previous implementation, which ignored a revision bump under 256 KB and
661
+ // required the log-file index before it ever called persistence.
662
+
663
+ const persistence = state.persistence
664
+
665
+ check('persistence answers without a log-file index or zstd', () => {
666
+ assert.ok(persistence.opens > 0, 'no session was read through persistence')
667
+ const splitSession = body.sessions.find(s => s.costSource === 'log' || s.costSource === 'totals')
668
+ assert.ok(splitSession, 'expected a session priced from the split')
669
+ })
670
+
671
+ // Warm every session past the per-collect budget first; otherwise "opens"
672
+ // grows because more sessions are being visited, not because a cache missed.
673
+ for (let round = 0; round < 12; round += 1) {
674
+ const beforeWarm = persistence.opens
675
+ await hit(routes, '/api/session-matrix/overview', 'refresh=1')
676
+ if (persistence.opens === beforeWarm) break
677
+ }
678
+
679
+ await checkAsync('same revision is a cache hit, not a second read', async () => {
680
+ const before = persistence.opens
681
+ await hit(routes, '/api/session-matrix/overview', 'refresh=1')
682
+ assert.equal(persistence.opens, before, 'an unchanged revision must not reopen the handle')
683
+ })
684
+
685
+ await checkAsync('a revision bump re-reads even when the log barely grew', async () => {
686
+ const before = persistence.opens
687
+ persistence.revision = 'r2'
688
+ persistence.sizeBytes += 1024 // 1 KB, far below the old 256 KB throttle
689
+ await hit(routes, '/api/session-matrix/overview', 'refresh=1')
690
+ assert.ok(persistence.opens > before, 'a new revision must trigger a read')
691
+ })
692
+
693
+ await checkAsync('concurrent collects do not double-read one revision', async () => {
694
+ // Warm r3 on one collect, then fire two overlapping collects at r4.
695
+ persistence.revision = 'r3'
696
+ await hit(routes, '/api/session-matrix/overview', 'refresh=1')
697
+ persistence.revision = 'r4'
698
+ const before = persistence.opens
699
+ await Promise.all([
700
+ hit(routes, '/api/session-matrix/overview', 'refresh=1'),
701
+ hit(routes, '/api/session-matrix/overview', 'refresh=1'),
702
+ ])
703
+ const reads = persistence.opens - before
704
+ // Two collects run concurrently; without the in-flight map each would open
705
+ // its own handle for the same revision.
706
+ // Each collect may touch up to logBudget sessions (6). Without the in-flight
707
+ // map the two overlapping collects would open 12 handles; with it, one per
708
+ // session per revision.
709
+ assert.ok(reads > 0, 'a new revision must be read at least once')
710
+ assert.ok(reads <= 6, `overlapping collects opened ${reads} handles, expected <= 6`)
711
+ })
712
+
713
+ // ── security invariant: no Connection, no routes ─────────────────────────
714
+ // A route registered straight on the web server matches before the /api prefix
715
+ // and skips admission, which is exactly how session data used to leak. The
716
+ // plugin must therefore register nothing when Connection is unavailable.
717
+ {
718
+ const bare = makeCtx(fixture, { noConnection: true })
719
+ apply(bare.ctx, { prices: false })
720
+ check('without connection, no route is registered at all', () => {
721
+ assert.equal(bare.routes.size, 0, `expected 0 routes, got ${[...bare.routes.keys()].join(', ')}`)
722
+ })
723
+ }
724
+
725
+ // ── Report ───────────────────────────────────────────────────────────────
726
+ console.log(`\nhost.test.mjs — ${pass.length} passed, ${fail.length} failed`)
727
+ for (const label of pass) console.log(` ✓ ${label}`)
728
+ for (const label of fail) console.log(` ✗ ${label}`)
729
+ console.log(`\nfixture: ${fixture.records.length} sessions, ${fixture.workspaces.length} projects`)
730
+ console.log(`sample totals: ${JSON.stringify(body.totals)}`)
731
+ if (body.projects.length) {
732
+ console.log('projects:', body.projects.map(p => `${p.title}(${p.count})`).join(', '))
733
+ }
734
+ if (fail.length > 0) process.exitCode = 1
735
+ }
736
+
737
+ main().catch(error => {
738
+ console.error('FATAL', error)
739
+ process.exitCode = 1
740
+ })