File size: 13,856 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// Vitest for the Ask page's pure helpers (npm test). The real-data tests read the
// recorded examples the export committed (web/public/data).

import { readFileSync } from 'node:fs'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { activeStep, boxState } from './architecture'
import { chartRow } from './chart'
import { inForce, outcomeLabel, percent, seconds, usd } from './format'
import { pieces } from './highlight'
import { HISTORY_TURNS, historyOf } from './history'
import { replay } from './replay'
import { ENDED, ended, idle, reduce, running, type RunState } from './run'
import { ask, AskRefused, parseEvents } from './sse'
import type { ArchitectureFile, AskEvent, ExampleDetail, RecordedEvent } from './types'

describe('parseEvents', () => {
  it('returns complete events and keeps an unfinished tail', () => {
    const { events, rest } = parseEvents('data: {"type":"start"}\n\ndata: {"type":"st')
    expect(events).toEqual([{ type: 'start' }])
    expect(rest).toBe('data: {"type":"st')
  })

  it('skips keep-alive comments and accepts CRLF line ends', () => {
    const { events, rest } = parseEvents(': ping\n\ndata: {"type":"evidence"}\r\n\r\n')
    expect(events).toEqual([{ type: 'evidence' }])
    expect(rest).toBe('')
  })

  it('joins an event split across chunks', () => {
    const first = parseEvents('data: {"type":"ans')
    const second = parseEvents(first.rest + 'wer"}\n\n')
    expect(first.events).toEqual([])
    expect(second.events).toEqual([{ type: 'answer' }])
  })
})

describe('pieces', () => {
  it('alternates plain and marked text at the spans', () => {
    expect(pieces('one two three four', [[4, 7], [14, 18]])).toEqual([
      { text: 'one ', mark: false },
      { text: 'two', mark: true },
      { text: ' three ', mark: false },
      { text: 'four', mark: true },
    ])
  })

  it('never throws on spans out of range or overlapping', () => {
    expect(pieces('abc', [[1, 99]])).toEqual([
      { text: 'a', mark: false },
      { text: 'bc', mark: true },
    ])
    expect(pieces('abcdef', [[0, 4], [2, 5]])).toEqual([
      { text: 'abcd', mark: true },
      { text: 'e', mark: true },
      { text: 'f', mark: false },
    ])
    expect(pieces('abc', [])).toEqual([{ text: 'abc', mark: false }])
    // a span inside the previous one: the cursor never moves back (no repeated text)
    expect(pieces('abcdef', [[0, 5], [1, 3]])).toEqual([
      { text: 'abcde', mark: true },
      { text: 'f', mark: false },
    ])
  })
})

const C_STEPS = ['retrieve', 'judge', 'research', 'judge_new', 'select', 'answer', 'verify']
const start = (system: 'a' | 'c'): AskEvent => ({
  type: 'start',
  system,
  day: '2026-11-23',
  steps: system === 'c' ? C_STEPS : ['search', 'answer'],
})
const step = (name: string, detail = {}): AskEvent => ({ type: 'step', name, ms: 10, detail })
const statuses = (s: RunState) => Object.fromEntries(s.steps.map((x) => [x.name, x.status]))
const play = (events: AskEvent[]) => events.reduce(reduce, idle)

describe('reduce', () => {
  it('runs C one step at a time', () => {
    expect(statuses(play([start('c')]))).toMatchObject({ retrieve: 'running', judge: 'pending' })
    const s = play([start('c'), step('retrieve', { candidates: 20 })])
    expect(statuses(s)).toMatchObject({ retrieve: 'done', judge: 'running', research: 'pending' })
    expect(running(s)?.name).toBe('judge')
  })

  it('skips the second search as soon as the judge found every fact', () => {
    const s = play([start('c'), step('retrieve'), step('judge', { sufficient: true })])
    expect(statuses(s)).toMatchObject({ research: 'skipped', judge_new: 'skipped', select: 'running' })
  })

  it('skips the second judge when the second search found nothing new', () => {
    const s = play([start('c'), step('retrieve'), step('judge', { sufficient: false }), step('research', { new_candidates: 0 })])
    expect(statuses(s)).toMatchObject({ research: 'done', judge_new: 'skipped', select: 'running' })
  })

  it('marks a step that never reported before a later one as skipped', () => {
    const s = play([start('c'), step('retrieve', { candidates: 0 }), step('select')])
    expect(statuses(s)).toMatchObject({ judge: 'skipped', research: 'skipped', select: 'done', answer: 'running' })
  })

  it('marks a C step that never reported by the answer as not run, never done', () => {
    const s = play([start('c'), step('retrieve'), step('judge', { sufficient: true }), step('select'), { type: 'answer' } as AskEvent])
    expect(statuses(s)).toMatchObject({ select: 'done', answer: 'skipped', verify: 'skipped' })
  })

  it('shows A and B as one call: all running, then all done', () => {
    const s = play([start('a')])
    expect(s.live).toBe(false)
    expect(statuses(s)).toEqual({ search: 'running', answer: 'running' })
    const answer = { type: 'answer' } as AskEvent
    expect(statuses(reduce(s, answer))).toEqual({ search: 'done', answer: 'done' })
  })

  it('stops on an error with the message and nothing left running', () => {
    const s = play([start('c'), step('retrieve'), { type: 'error', kind: 'api', message: 'down' }])
    expect(s.phase).toBe('error')
    expect(s.error).toBe('down')
    expect(running(s)).toBeUndefined()
  })
})

describe('follow-ups', () => {
  const answered = (question: string, answer: string, understood?: string) => {
    let run = play([start('c')])
    if (understood) run = reduce(run, { type: 'rewrite', question: understood, changed: true, ms: 1 })
    return { question, run: reduce(run, { type: 'answer', answer, citations: [] } as unknown as AskEvent) }
  }

  it('keeps how the question was understood', () => {
    const run = reduce(play([start('c')]), { type: 'rewrite', question: 'Is a 70-year-old covered?', changed: true, ms: 5 })
    expect(run.rewrite).toEqual({ question: 'Is a 70-year-old covered?', changed: true })
    expect(statuses(run).retrieve).toBe('running') // the steps are untouched
  })

  it('sends only answered turns, as understood, and only the last few', () => {
    const turns = [
      answered('q1', 'a1'),
      answered('and if 70?', 'a2', 'Is a 70-year-old covered?'),
      { question: 'stopped', run: play([start('c'), { type: 'error', kind: 'stopped', message: 'Stopped.' }]) },
    ]
    expect(historyOf(turns)).toEqual([
      { question: 'q1', answer: 'a1' },
      { question: 'Is a 70-year-old covered?', answer: 'a2' },
    ])
    const many = Array.from({ length: HISTORY_TURNS + 2 }, (_, i) => answered('q' + i, 'a' + i))
    expect(historyOf(many).map((t) => t.question)).toEqual(many.slice(-HISTORY_TURNS).map((t) => t.question))
    expect(historyOf([])).toEqual([])
  })
})

describe('a finished run', () => {
  const answer = { type: 'answer', citations: [] } as unknown as AskEvent

  it('stays finished: an error after the answer changes nothing', () => {
    const done = play([start('c'), answer])
    expect(reduce(done, { type: 'error', kind: 'deadline', message: 'late' })).toBe(done)
    expect(reduce(done, start('a')).phase).toBe('running') // a new run starts fresh
  })

  it('ends in an error when the stream closes without an answer, never spinning', () => {
    const cut = ended(play([start('c'), step('retrieve')]))
    expect(cut.phase).toBe('error')
    expect(cut.error).toBe(ENDED)
    expect(running(cut)).toBeUndefined()
    const done = play([start('c'), answer])
    expect(ended(done)).toBe(done)
    expect(ended(idle)).toBe(idle) // nothing was running: nothing ended
  })
})

/** A fetch() stand-in answering with these body chunks (bytes, so a chunk can split a
 * character) and this status. */
function fakeFetch(chunks: Uint8Array[], status = 200) {
  return vi.fn(async () => {
    const body = new ReadableStream<Uint8Array>({
      start(controller) {
        chunks.forEach((c) => controller.enqueue(c))
        controller.close()
      },
    })
    return new Response(body, { status, headers: { 'content-type': 'text/event-stream' } })
  })
}

describe('ask', () => {
  afterEach(() => vi.unstubAllGlobals())
  const bytes = (s: string) => new TextEncoder().encode(s)

  it('reads events split across chunks, inside a character and inside a CRLF', async () => {
    const all = bytes('data: {"type":"start"}\r\n\r\n: ping\n\ndata: {"type":"answer","answer":"Oui, sécurité"}\n\n')
    const cut = all.indexOf(0xc3) + 1 // between the two bytes of "é"
    const crlf = all.indexOf(0x0d) + 1 // between \r and \n
    vi.stubGlobal('fetch', fakeFetch([all.slice(0, crlf), all.slice(crlf, cut), all.slice(cut)]))
    const seen: AskEvent[] = []
    await ask({ question: 'q?', system: 'c' }, (e) => seen.push(e))
    expect(seen.map((e) => e.type)).toEqual(['start', 'answer'])
    expect((seen[1] as { answer: string }).answer).toBe('Oui, sécurité')
  })

  it('delivers a last event that has no blank line after it', async () => {
    vi.stubGlobal('fetch', fakeFetch([bytes('data: {"type":"start"}\n\ndata: {"type":"answer"}')]))
    const seen: string[] = []
    await ask({ question: 'q?', system: 'a' }, (e) => seen.push(e.type))
    expect(seen).toEqual(['start', 'answer'])
  })

  it('turns a refusal into AskRefused with the server reason', async () => {
    vi.stubGlobal('fetch', fakeFetch([bytes('{"detail":"The demo is busy."}')], 429))
    await expect(ask({ question: 'q?', system: 'c' }, () => {})).rejects.toThrow(new AskRefused('The demo is busy.'))
    const fields = '{"detail":[{"msg":"question too long"},{"msg":"bad date"}]}'
    vi.stubGlobal('fetch', fakeFetch([bytes(fields)], 422))
    await expect(ask({ question: 'q?', system: 'c' }, () => {})).rejects.toThrow('question too long; bad date')
  })
})

const example = (id: string): ExampleDetail =>
  JSON.parse(readFileSync(new URL(`../../public/data/examples/${id}.json`, import.meta.url), 'utf8'))

describe('a recorded example through the reducer', () => {
  it('H016 C: second search ran, every step done, evidence before the answer', () => {
    const events = example('H016').runs.c.events
    const s = play(events)
    expect(s.phase).toBe('done')
    expect(statuses(s)).toEqual(Object.fromEntries(C_STEPS.map((n) => [n, 'done'])))
    const evidenceAt = events.findIndex((e) => e.type === 'evidence')
    const answerStep = events.findIndex((e) => e.type === 'step' && e.name === 'answer')
    expect(evidenceAt).toBeLessThan(answerStep)
    expect(s.answer?.citations.length).toBeGreaterThan(0)
  })

  it('H013 C: the judge found every fact, so the second search is skipped', () => {
    const s = play(example('H013').runs.c.events)
    expect(statuses(s)).toMatchObject({ research: 'skipped', judge_new: 'skipped', verify: 'done' })
  })
})

describe('replay', () => {
  afterEach(() => vi.useRealTimers())
  const events = [
    { type: 'start', at_ms: 0 },
    { type: 'step', at_ms: 1000 },
    { type: 'answer', at_ms: 3000 },
  ] as RecordedEvent[]

  it('delivers each event at its recorded time, scaled by speed', () => {
    vi.useFakeTimers()
    const seen: string[] = []
    replay(events, (e) => seen.push(e.type), 2)
    vi.advanceTimersByTime(499)
    expect(seen).toEqual(['start'])
    vi.advanceTimersByTime(1)
    expect(seen).toEqual(['start', 'step'])
    vi.advanceTimersByTime(1000)
    expect(seen).toEqual(['start', 'step', 'answer'])
  })

  it('finish() delivers the rest at once, in order, and only once', () => {
    vi.useFakeTimers()
    const seen: string[] = []
    const r = replay(events, (e) => seen.push(e.type))
    vi.advanceTimersByTime(0)
    r.finish()
    vi.advanceTimersByTime(5000)
    expect(seen).toEqual(['start', 'step', 'answer'])
  })
})

describe('format', () => {
  it('says numbers the same way everywhere', () => {
    expect([seconds(4400), seconds(37668), seconds(20), seconds(null)]).toEqual(['4.4 s', '38 s', '<0.1 s', ''])
    expect([usd(0.00426), usd(0.5)]).toEqual(['$0.0043', '$0.50'])
    expect(percent(0.835)).toBe('84%')
    expect(inForce('2026-07-01', null)).toBe('in force from 2026-07-01')
    expect(inForce(null, null)).toBe('no in-force dates stated')
    expect(outcomeLabel('correct_abstain')).toBe('correctly declined')
  })
})

describe('chartRow', () => {
  it('turns each interval into the distances below and above the bar', () => {
    const row = chartRow({ group: '2', n: 76, a: { accuracy: 0.145, ci: [0.066, 0.224] }, c: { accuracy: 0.724, ci: [0.618, 0.816] } }, '2 documents')
    expect(row.name).toBe('2 documents')
    expect(row.n).toBe(76)
    expect(row.c).toBe(0.724)
    expect((row.c_err as number[]).map((v) => Number(v.toFixed(3)))).toEqual([0.106, 0.092])
    expect(row.c_ci).toEqual([0.618, 0.816])
    expect('b' in row).toBe(false) // a system without the group draws nothing
  })

  it('draws no whisker when an interval is missing', () => {
    const row = chartRow({ group: 'x', n: 1, c: { accuracy: 1, ci: [null, null] } }, 'x')
    expect(row.c_err).toEqual([0, 0])
  })
})

describe('the architecture page', () => {
  it('activates the last step whose top has passed the reading line', () => {
    expect(activeStep([500, 900], 1000)).toBe(-1) // nothing reached the line (450) yet
    expect(activeStep([300, 900], 1000)).toBe(0)
    expect(activeStep([-200, 440, 800], 1000)).toBe(1)
    expect(activeStep([], 1000)).toBe(-1)
  })

  it('lights the boxes a step names, dims the rest, and dims nothing without a step', () => {
    expect(boxState('x', ['x', 'y'])).toBe('lit')
    expect(boxState('z', ['x'])).toBe('dim')
    expect(boxState('x', null)).toBe('plain')
  })

  it('has a diagram layout for every chapter of the committed page', () => {
    const page: ArchitectureFile = JSON.parse(readFileSync(new URL('../../public/data/architecture.json', import.meta.url), 'utf8'))
    expect(page.chapters.map((c) => c.diagram.kind)).toEqual(['documents', 'prepare', 'grid', 'answer', 'measure'])
  })
})