@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.
Files changed (62) hide show
  1. package/AGENTS.md +3 -3
  2. package/CHANGELOG.md +64 -0
  3. package/README.md +103 -14
  4. package/RELEASE-NOTES-1.0.3.md +91 -0
  5. package/RELEASE-NOTES-1.0.4.md +80 -0
  6. package/docs/composite-pressure-v0.1.md +23 -0
  7. package/docs/composite-pressure-v0.2.md +18 -0
  8. package/docs/pressure-backtest-v0.1.md +19 -0
  9. package/docs/session-capacity-advice-v0.1.md +17 -0
  10. package/docs/session-pressure-design-v1.1.md +1173 -0
  11. package/docs/session-pressure-ui-v0.3.md +28 -0
  12. package/docs/tool-retention-diagnostics-v2.md +13 -0
  13. package/lib/autobackup.js +14 -2
  14. package/lib/backup.js +141 -12
  15. package/lib/bili.js +4 -2
  16. package/lib/browse.js +55 -11
  17. package/lib/capture.js +41 -9
  18. package/lib/client.js +2260 -55
  19. package/lib/cloudbackup.js +24 -1
  20. package/lib/clouddrive.js +4 -1
  21. package/lib/compact.js +28 -11
  22. package/lib/cue.js +114 -0
  23. package/lib/derive.js +48 -5
  24. package/lib/desk.js +19 -1
  25. package/lib/doing.js +1 -1
  26. package/lib/dreamtable.js +5 -4
  27. package/lib/drive.js +72 -13
  28. package/lib/generator.js +1 -1
  29. package/lib/handoff.js +34 -16
  30. package/lib/home.js +3 -1
  31. package/lib/identity.js +15 -0
  32. package/lib/index.js +7 -1
  33. package/lib/interest.js +38 -0
  34. package/lib/look.js +7 -0
  35. package/lib/make.js +214 -0
  36. package/lib/note.js +163 -39
  37. package/lib/observe.js +202 -4
  38. package/lib/persona.js +66 -13
  39. package/lib/proactive.js +17 -1
  40. package/lib/restrict.js +9 -2
  41. package/lib/sametopic.js +94 -0
  42. package/lib/scheduler.js +301 -16
  43. package/lib/selfdoc.js +12 -3
  44. package/lib/session-pressure-analysis.js +296 -0
  45. package/lib/session-pressure-data.js +239 -0
  46. package/lib/session-pressure-formulas.js +280 -0
  47. package/lib/session-pressure-load.js +110 -0
  48. package/lib/session-pressure.js +706 -0
  49. package/lib/settings.js +8 -1
  50. package/lib/sleepfact.js +110 -0
  51. package/lib/sub.js +9 -7
  52. package/lib/turns.js +8 -1
  53. package/lib/video.js +75 -42
  54. package/lib/whatseen.js +24 -2
  55. package/lib/wiki.js +1677 -0
  56. package/lib/wikiserve.js +148 -0
  57. package/lib/works.js +526 -0
  58. package/media/feedback-qr.jpg +0 -0
  59. package/media/principle-drive.svg +2 -2
  60. package/media/principle-memory.svg +1 -1
  61. package/package.json +1 -1
  62. package/scripts/sync-pressure-formulas.mjs +17 -0
@@ -0,0 +1,280 @@
1
+ const pressureVersions = { capacity: 'capacity_v0.1', request: 'request_v0.1', structure: 'structure_v0.1', composite: 'composite_v0.1' }
2
+ const compositeDefaults = { A: { wc: .5, wr: .3, wq: .2 }, B: { wc: .5, wr: .3, wq: .2 }, C: { wr: .6, wq: .4, mu: .35 } }
3
+
4
+ function scoreCapacity(c, g, gamma, horizon, lambda) {
5
+ const bounded = value => Math.min(1, Math.max(0, value))
6
+ const capacity = Number.isFinite(c) ? bounded(c / 100) : null
7
+ const cScore = capacity == null ? null : 100 * capacity ** gamma
8
+ const remainingUse = capacity == null || capacity >= 1 || !Number.isFinite(g)
9
+ ? null : bounded(horizon * Math.max(g, 0) / (100 * (1 - capacity)))
10
+ const score = capacity === 1 ? 100 : remainingUse == null ? null
11
+ : 100 * (1 - (1 - capacity ** gamma) * (1 - lambda * remainingUse))
12
+ const forecast = capacity != null && Number.isFinite(g) ? bounded(capacity + horizon * g / 100) : null
13
+ return { capacity, cScore, remainingUse, score, forecast }
14
+ }
15
+
16
+ function sessionCapacityAdvice(occupancy, growth) {
17
+ if (!Number.isFinite(occupancy) || occupancy < 0) return { level: 'unknown', five: null, ten: null }
18
+ const { gamma, lambda } = pressureDefaults.capacity
19
+ const forecast = horizon => {
20
+ const value = scoreCapacity(occupancy, growth, gamma, horizon, lambda).forecast
21
+ return Number.isFinite(value) ? 100 * value : null
22
+ }
23
+ const five = forecast(5)
24
+ const ten = forecast(10)
25
+ const reaches = (value, threshold) => Number.isFinite(value) && value >= threshold - 1e-10
26
+ const level = reaches(occupancy, 95) ? 'switch'
27
+ : reaches(occupancy, 85) || reaches(five, 95) ? 'prepare'
28
+ : reaches(occupancy, 70) || reaches(ten, 85) ? 'watch' : 'continue'
29
+ return { level, five, ten }
30
+ }
31
+
32
+ function scoreRequestBurden(data, rho, beta, tau, recentWeight) {
33
+ function bounds(sample) {
34
+ if (!(sample?.rounds > 0) || ![sample.knownMiss, sample.cached, sample.unknownInput, sample.output].every(Number.isFinite)) return null
35
+ const known = sample.knownMiss + rho * sample.cached + beta * sample.output
36
+ return [(known + rho * sample.unknownInput) / sample.rounds, (known + sample.unknownInput) / sample.rounds]
37
+ }
38
+ const all = bounds(data?.all)
39
+ const recent = bounds(data?.recent)
40
+ const ratios = data?.window > 0 && all && recent
41
+ ? all.map((value, i) => recentWeight === 0 ? value / data.window : recentWeight === 1 ? recent[i] / data.window
42
+ : ((1 - recentWeight) * value + recentWeight * recent[i]) / data.window) : null
43
+ return { all, recent, ratios, scores: ratios?.map(value => -100 * Math.expm1(-value / tau)) }
44
+ }
45
+
46
+ function scoreStructure(current, repeated, retry, toolWeight, epsilon, eta) {
47
+ const valid = value => Number.isFinite(value) && value >= 0 && value <= 100
48
+ const tool = valid(current) && valid(repeated) ? toolWeight * (current / 100) + (1 - toolWeight) * (repeated / 100) : null
49
+ const failure = Number.isFinite(retry) ? -Math.expm1(-retry / (100 * epsilon)) : null
50
+ const score = tool != null && (failure != null || eta === 0)
51
+ ? 100 * (1 - (1 - tool) * (1 - eta * (failure ?? 0))) : null
52
+ return { tool, failure, score }
53
+ }
54
+
55
+ function capacityInputs(dictionary) {
56
+ const occupancy = dictionary.find(metric => metric.id === 'C')?.rows.find(row => row.label === '窗口占用率')?.value
57
+ const growth = dictionary.find(metric => metric.id === 'G')?.rows ?? []
58
+ const windows = [[5, .5], [10, .3], [20, .2]].map(([rounds, weight]) => {
59
+ const row = growth.find(item => item.label === '平均净增长' && item.scope === '最近 ' + rounds + ' 轮')
60
+ return { rounds, weight, value: row?.value, pairs: row?.raw_value?.comparablePairs ?? 0,
61
+ requestPairs: row?.raw_value?.requestPairs ?? 0, compacted: row?.raw_value?.compacted }
62
+ })
63
+ const available = windows.filter(window => Number.isFinite(window.value) && window.pairs > 0)
64
+ return { occupancy: Number.isFinite(occupancy) ? 100 * occupancy : null, windows,
65
+ growth: available.length ? 100 * available.reduce((sum, window) => sum + window.value * window.weight, 0)
66
+ / available.reduce((sum, window) => sum + window.weight, 0) : null }
67
+ }
68
+
69
+ function scoreComposite(scores, parameters, invalidStructure = false) {
70
+ if (invalidStructure) return {
71
+ A: { score: null, contributions: null }, B: { score: null, factors: [null, null, null], product: null, disabled: false },
72
+ C: { score: null, base: null, mix: null, correction: null },
73
+ }
74
+ const normalized = scores.map(value => Number.isFinite(value) && value >= 0 && value <= 100 ? value / 100 : null)
75
+ const [c, r, q] = normalized
76
+ const { A, B, C } = parameters
77
+ const weightsA = [A.wc, A.wr, A.wq]
78
+ const weightsB = [B.wc, B.wr, B.wq]
79
+ const sumA = A.wc + A.wr + A.wq
80
+ const valid = weights => normalized.every((value, i) => weights[i] === 0 || value != null)
81
+ const contributions = sumA > 0 && valid(weightsA)
82
+ ? weightsA.map((weight, i) => weight === 0 ? 0 : weight / sumA * normalized[i]) : null
83
+ const factors = weightsB.map((weight, i) => weight === 0 ? 1 : normalized[i] == null ? null : (1 - normalized[i]) ** weight)
84
+ const product = factors.every(Number.isFinite) ? factors.reduce((a, b) => a * b, 1) : null
85
+ const sumC = C.wr + C.wq
86
+ const mix = sumC === 0 ? 0 : valid([0, C.wr, C.wq]) ? ((r ?? 0) * C.wr + (q ?? 0) * C.wq) / sumC : null
87
+ const correction = c == null ? null : c === 1 || C.mu === 0 ? 0 : mix == null ? null : C.mu * (1 - c) * mix
88
+ const points = value => Math.min(100, Math.max(0, 100 * value))
89
+ return {
90
+ A: { score: contributions ? points(contributions.reduce((a, b) => a + b, 0)) : null, contributions },
91
+ B: { score: factors.includes(0) ? 100 : product == null ? null : points(1 - product), factors, product,
92
+ disabled: weightsB.every(weight => weight === 0) },
93
+ C: { score: correction == null ? null : points(c + correction), base: c, mix, correction },
94
+ }
95
+ }
96
+
97
+ function pressureStatistics(current, values) {
98
+ const scores = values.filter(Number.isFinite).sort((a, b) => a - b)
99
+ const count = scores.length
100
+ const middle = Math.floor(count / 2)
101
+ const median = count === 0 ? null : count % 2 ? scores[middle] : (scores[middle - 1] + scores[middle]) / 2
102
+ const comparable = median != null && Number.isFinite(current)
103
+ const percentile = comparable ? 100 * scores.reduce((rank, score) => rank + (score < current ? 1 : score === current ? .5 : 0), 0) / count : null
104
+ return { count, median, percentile, difference: comparable ? current - median : null }
105
+ }
106
+
107
+ function scoreDiagnostic(inputs, parameters) {
108
+ const { capacity, request, structure } = parameters
109
+ const [current, repeated, retry] = inputs.structure.map(value => Number.isFinite(value) ? 100 * value : null)
110
+ return [
111
+ scoreCapacity(inputs.capacity.occupancy, inputs.capacity.growth, capacity.gamma, capacity.horizon, capacity.lambda).score,
112
+ scoreRequestBurden(inputs.request, request.rho, request.beta, request.tau, request.recentWeight).scores?.[1] ?? null,
113
+ inputs.invalidStructure ? null : scoreStructure(current, repeated, retry, structure.toolWeight, structure.epsilon, structure.eta).score,
114
+ ]
115
+ }
116
+
117
+ const pressureDefaults = {
118
+ capacity: { gamma: 2, horizon: 10, lambda: .35 },
119
+ request: { rho: 1, beta: 1, tau: 1, recentWeight: .6 },
120
+ structure: { toolWeight: .7, epsilon: .05, eta: .3 },
121
+ composite: compositeDefaults,
122
+ }
123
+
124
+ function sameRoundDiagnostic(current, historical, strict = false) {
125
+ return current?.rounds > 0 && current.id !== historical.id && current.rounds === historical.rounds
126
+ && (!strict || (current.route != null && current.route === historical.route))
127
+ && current.diagnosticsVersion === historical.diagnosticsVersion
128
+ && JSON.stringify(current.versions) === JSON.stringify(historical.versions)
129
+ }
130
+
131
+ function trendSegments(points) {
132
+ const segments = []
133
+ let previous = null
134
+ for (const point of points) {
135
+ if (!Number.isFinite(point.score)) {
136
+ previous = null
137
+ continue
138
+ }
139
+ if (previous !== point.round - 1) segments.push([])
140
+ segments.at(-1).push(point)
141
+ previous = point.round
142
+ }
143
+ return segments
144
+ }
145
+
146
+ const backtestMethods = ['linear5', 'linear10', 'weighted']
147
+ const backtestHorizons = [5, 10, 20]
148
+
149
+ function forecastChildren(prefix, origin, horizon, method) {
150
+ const windows = method === 'linear5' ? [[5, 1]] : method === 'linear10' ? [[10, 1]]
151
+ : [[5, .5], [10, .3], [20, .2]]
152
+ const last = prefix.get(origin)
153
+ if (!last?.children?.every(Number.isFinite)) return null
154
+ const slopes = [0, 0, 0]
155
+ for (const [width, weight] of windows) {
156
+ const middle = (width - 1) / 2
157
+ const denominator = width * (width ** 2 - 1) / 12
158
+ for (let i = 0; i < width; i++) {
159
+ const point = prefix.get(origin - width + 1 + i)
160
+ if (!point?.children?.every(Number.isFinite)) return null
161
+ for (let dimension = 0; dimension < 3; dimension++) {
162
+ slopes[dimension] += weight * (i - middle) * point.children[dimension] / denominator
163
+ }
164
+ }
165
+ }
166
+ return last.children.map((score, dimension) => Math.max(0, Math.min(100, score + horizon * slopes[dimension])))
167
+ }
168
+
169
+ function forecastPressure(prefix, origin, horizon, method, parameters) {
170
+ const children = forecastChildren(prefix, origin, horizon, method)
171
+ return children ? scoreComposite(children, parameters) : null
172
+ }
173
+
174
+ function pressureContributions(start, end, plan, parameters) {
175
+ if (!start?.every(Number.isFinite) || !end?.every(Number.isFinite)) return null
176
+ const score = values => scoreComposite(values, parameters)[plan]?.score
177
+ if (!Number.isFinite(score(start)) || !Number.isFinite(score(end))) return null
178
+ if (plan === 'A') {
179
+ const { wc, wr, wq } = parameters.A
180
+ const weights = [wc, wr, wq]
181
+ const total = wc + wr + wq
182
+ return weights.map((weight, i) => (end[i] - start[i]) * weight / total)
183
+ }
184
+ const contributions = [0, 0, 0]
185
+ for (const order of [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]) {
186
+ const values = [...start]
187
+ let before = score(values)
188
+ for (const index of order) {
189
+ values[index] = end[index]
190
+ const after = score(values)
191
+ contributions[index] += (after - before) / 6
192
+ before = after
193
+ }
194
+ }
195
+ return contributions
196
+ }
197
+
198
+ function pressureBacktestRecords(sessions, parameters) {
199
+ const records = []
200
+ for (const [sessionId, points] of sessions) {
201
+ const observed = new Map(points.map(point => [point.round, point]))
202
+ const prefix = new Map()
203
+ const lastRound = points.at(-1)?.round ?? 0
204
+ const compactions = points.filter(point => point.markers?.some(marker =>
205
+ ['压缩成功', '裁剪'].includes(marker.type))).map(point => point.round)
206
+ let index = 0
207
+ for (let origin = 20; origin + 5 <= lastRound; origin += 5) {
208
+ while (index < points.length && points[index].round <= origin) {
209
+ prefix.set(points[index].round, points[index])
210
+ index++
211
+ }
212
+ for (const horizon of backtestHorizons) {
213
+ const target = origin + horizon
214
+ const actual = observed.get(target)?.scores
215
+ if (!actual) continue
216
+ const before = compactions.some(round => round > origin && round <= target)
217
+ const after = compactions.some(round => round > origin - 5 && round <= origin)
218
+ const groups = ['overall', ...(before ? ['before'] : []), ...(after ? ['after'] : []),
219
+ ...(!before && !after ? ['neither'] : [])]
220
+ for (const method of backtestMethods) {
221
+ const predictedChildren = forecastChildren(prefix, origin, horizon, method)
222
+ if (!predictedChildren) continue
223
+ const predicted = scoreComposite(predictedChildren, parameters)
224
+ for (const plan of ['A', 'B', 'C']) {
225
+ const estimate = predicted[plan]?.score
226
+ const observedScore = actual[plan]?.score
227
+ if (Number.isFinite(estimate) && Number.isFinite(observedScore)) {
228
+ records.push({ sessionId, origin, target, horizon, method, plan, estimate, actual: observedScore, predictedChildren, groups })
229
+ }
230
+ }
231
+ }
232
+ }
233
+ }
234
+ }
235
+ return records
236
+ }
237
+
238
+ function commonPressureBacktestRecords(records, methods) {
239
+ const key = row => JSON.stringify([row.sessionId, row.origin, row.horizon, row.plan])
240
+ const availability = new Map()
241
+ for (const row of records) {
242
+ if (!methods.includes(row.method)) continue
243
+ const id = key(row)
244
+ if (!availability.has(id)) availability.set(id, new Set())
245
+ availability.get(id).add(row.method)
246
+ }
247
+ return records.filter(row => methods.includes(row.method) && availability.get(key(row))?.size === methods.length)
248
+ }
249
+
250
+ function summarizePressureBacktest(records) {
251
+ const groups = ['overall', 'before', 'after', 'neither']
252
+ const rows = backtestMethods.flatMap(method => backtestHorizons.flatMap(horizon => ['A', 'B', 'C'].map(plan => ({
253
+ method, horizon, plan, groups: Object.fromEntries(groups.map(group => [group,
254
+ { count: 0, absolute: 0, signed: 0, sessions: new Set() }])),
255
+ }))))
256
+ const byKey = new Map(rows.map(row => [[row.method, row.horizon, row.plan].join(':'), row]))
257
+ for (const record of records) {
258
+ const row = byKey.get([record.method, record.horizon, record.plan].join(':'))
259
+ const error = record.estimate - record.actual
260
+ for (const stratum of record.groups) {
261
+ const group = row.groups[stratum]
262
+ group.count++
263
+ group.absolute += Math.abs(error)
264
+ group.signed += error
265
+ group.sessions.add(record.sessionId)
266
+ }
267
+ }
268
+ return rows.map(row => ({ ...row, groups: Object.fromEntries(Object.entries(row.groups).map(([key, group]) => [
269
+ key, { count: group.count, sessions: group.sessions.size, mae: group.count ? group.absolute / group.count : null,
270
+ bias: group.count ? group.signed / group.count : null },
271
+ ])) }))
272
+ }
273
+
274
+ function runPressureBacktest(sessions, parameters) {
275
+ return summarizePressureBacktest(pressureBacktestRecords(sessions, parameters))
276
+ }
277
+
278
+ export { pressureVersions, pressureDefaults, compositeDefaults, scoreCapacity, sessionCapacityAdvice, scoreRequestBurden,
279
+ scoreStructure, capacityInputs, scoreComposite, pressureStatistics, scoreDiagnostic, sameRoundDiagnostic, trendSegments,
280
+ forecastPressure, runPressureBacktest, pressureBacktestRecords, commonPressureBacktestRecords, summarizePressureBacktest, pressureContributions }
@@ -0,0 +1,110 @@
1
+ export const LOAD_VERSION = 6
2
+ export const LOAD_FACTORS = [
3
+ { id: 'C', label: '上下文容量', weight: 15, unit: '', threshold: true },
4
+ { id: 'G', label: '增长负担', weight: 15, unit: '', threshold: true },
5
+ { id: 'U', label: 'Token 总消耗', weight: 15, unit: 'Token' },
6
+ { id: 'A', label: '请求放大', weight: 15, unit: 'Token' },
7
+ { id: 'T', label: '工具结果残留', weight: 15, unit: 'Token·请求' },
8
+ { id: 'K', label: '缓存复用负担', weight: 10, unit: 'Token' },
9
+ { id: 'E', label: '失败与恢复', weight: 15, unit: 'Token' },
10
+ ]
11
+
12
+ export const DEFAULT_REFERENCE_ROUNDS = 40
13
+
14
+ export function normalizeReferenceRounds(value) {
15
+ if (value === 'end') return value
16
+ const rounds = Number(value)
17
+ return Number.isInteger(rounds) && rounds >= 1 && rounds <= 500 ? rounds : DEFAULT_REFERENCE_ROUNDS
18
+ }
19
+ const MIN_SESSIONS = 3
20
+ const MIN_PROVISIONAL_SESSIONS = 1
21
+
22
+ function quantile(values, p) {
23
+ if (!values.length) return null
24
+ const sorted = values.slice().sort((a, b) => a - b)
25
+ const i = (sorted.length - 1) * p
26
+ const lower = Math.floor(i)
27
+ return sorted[lower] + (sorted[Math.ceil(i)] - sorted[lower]) * (i - lower)
28
+ }
29
+
30
+ function cumulative(analysis) {
31
+ const running = Object.fromEntries(LOAD_FACTORS.map(({ id }) => [id, null]))
32
+ return (analysis?.rows ?? []).map(row => {
33
+ for (const { id } of LOAD_FACTORS) {
34
+ const observed = row.load?.[id] ?? row.observedLoad?.[id]
35
+ if (Number.isFinite(observed)) running[id] = (running[id] ?? 0) + observed
36
+ }
37
+ return { turn: row.turn, values: { ...running } }
38
+ })
39
+ }
40
+
41
+ export function sessionReferenceEligibility(analysis, referenceRounds = DEFAULT_REFERENCE_ROUNDS) {
42
+ if (analysis?.status !== 'analyzed') return analysis?.status ?? 'unavailable'
43
+ const points = cumulative(analysis)
44
+ const target = referenceRounds === 'end' ? points.at(-1) : points.find(row => row.turn === referenceRounds)
45
+ return target ? 'eligible' : 'no-reference-round'
46
+ }
47
+
48
+ export function buildSessionLoad(current, history, fixed = null, referenceRounds = DEFAULT_REFERENCE_ROUNDS) {
49
+ const points = cumulative(current)
50
+ const latest = points.at(-1)
51
+ const comparable = Boolean(latest)
52
+ const sessions = history.map(cumulative).filter(rows => rows.length)
53
+ const references = sessions.map(rows => referenceRounds === 'end' ? rows.at(-1)
54
+ : rows.find(row => row.turn === referenceRounds)).filter(Boolean)
55
+ const saved = fixed?.version === LOAD_VERSION && fixed.referenceRounds === referenceRounds ? fixed : null
56
+ const freshFactors = LOAD_FACTORS.map(factor => {
57
+ const values = references.map(row => row.values[factor.id]).filter(Number.isFinite)
58
+ const baseline = values.length ? quantile(values, .5) : null
59
+ const currentValue = comparable ? latest.values[factor.id] : null
60
+ return { ...factor, current: currentValue, samples: values.length, baseline, provisional: values.length < MIN_SESSIONS,
61
+ available: Number.isFinite(currentValue) && baseline > 0 }
62
+ })
63
+ const currentRows = current?.rows ?? []
64
+ for (const factor of freshFactors) {
65
+ const exact = currentRows.map(row => row.load?.[factor.id]).filter(Number.isFinite)
66
+ const partial = currentRows.filter(row => !Number.isFinite(row.load?.[factor.id]))
67
+ .map(row => row.observedLoad?.[factor.id]).filter(Number.isFinite)
68
+ const observed = [...exact, ...partial]
69
+ factor.coverage = { complete: exact.length, partial: partial.length, rounds: currentRows.length,
70
+ observed: observed.length ? observed.reduce((sum, value) => sum + value, 0) : null }
71
+ }
72
+ const factors = saved ? freshFactors.map(factor => {
73
+ const baseline = saved.factors[factor.id]?.baseline ?? null
74
+ const samples = saved.factors[factor.id]?.samples ?? 0
75
+ return { ...factor, baseline, samples, provisional: samples < MIN_SESSIONS, available: Number.isFinite(factor.current) && baseline > 0 }
76
+ }) : freshFactors
77
+ const distributions = saved?.distributions ?? [...new Set([20, 30, 40, 45, 50, referenceRounds].filter(Number.isInteger))].sort((a, b) => a - b).map(turn => ({
78
+ turn,
79
+ samples: sessions.map(rows => rows.find(row => row.turn === turn))
80
+ .filter(Boolean).map(row => row.values),
81
+ below: sessions.filter(rows => rows.at(-1).turn < turn).length,
82
+ }))
83
+ const trend = saved?.trend ?? (() => {
84
+ const byTurn = new Map()
85
+ for (const rows of sessions) {
86
+ for (const row of rows) {
87
+ if (row.turn > 500) continue
88
+ const values = byTurn.get(row.turn) ?? []
89
+ values.push(row.values)
90
+ byTurn.set(row.turn, values)
91
+ }
92
+ }
93
+ return [...byTurn].sort(([a], [b]) => a - b).map(([turn, samples]) => ({ turn, samples }))
94
+ })()
95
+ const rows = current?.rows ?? []
96
+ const observedUsage = rows.map(row => row.total.value).filter(Number.isFinite)
97
+ return { version: LOAD_VERSION, comparisons: saved?.comparisons ?? references.map(row => row.values), referenceCreatedAt: saved?.createdAt ?? null, referenceRounds, minSessions: MIN_SESSIONS, provisionalMin: MIN_PROVISIONAL_SESSIONS,
98
+ candidateCount: saved?.candidateCount ?? sessions.length, referenceCount: saved?.referenceCount ?? references.length, comparable, factors,
99
+ points: comparable ? points.map(({ turn, values }) => ({ turn, values })) : [], distributions, trend,
100
+ usage: { total: observedUsage.length ? observedUsage.reduce((sum, n) => sum + n, 0) : null,
101
+ complete: rows.filter(row => row.completeUsage).length, turns: rows.length },
102
+ }
103
+ }
104
+
105
+ export function freezeSessionLoadReference(view, createdAt) {
106
+ if (!view.factors.some(factor => factor.baseline > 0 && !factor.provisional)) return null
107
+ return { version: LOAD_VERSION, comparisons: view.comparisons, referenceRounds: view.referenceRounds, createdAt, referenceCount: view.referenceCount,
108
+ candidateCount: view.candidateCount, distributions: view.distributions, trend: view.trend,
109
+ factors: Object.fromEntries(view.factors.map(({ id, samples, baseline }) => [id, { samples, baseline }])) }
110
+ }