garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/lib/stats.test.ts

raw

import {describe, expect, test} from 'bun:test'

import {buckets, buildHoursByDay, deployTimes, typical, commandTable, days, dayKey, headline, median, narrow, saidByDay, saidByHour, talkHeadline, timeGoes, topCounts, waitsByDay} from '@/lib/stats'
import type {Build, Session, Take, Tally} from '@/lib/types'

const at = (s: string) => Date.parse(s) / 1000
const build = (ts: string, extra: Partial<Build>): Build => ({
    ts, node: 'vps-1', machine: 'vps', actor: 's1', shape: 'cargo test', seconds: 600, exit: 0, first_build_in_lease: false, ...extra,
})

describe('stats', () => {
    test('median of an even list takes the upper middle, as midas stats does', () => {
        expect(median([4, 1, 3, 2])).toBe(3)
        expect(median([])).toBeNull()
    })

    test('build hours are per day and machine, agents only, cargo only', () => {
        const d = days(at('2026-10-16T12:00:00'), at('2026-10-17T12:00:00'))
        expect(d.length).toBe(2)
        const {machines, rows} = buildHoursByDay(
            [
                build('2026-10-16T10:00:00', {seconds: 3600}),
                build('2026-10-17T10:00:00', {seconds: 1800, machine: 'deck'}),
                build('2026-10-17T11:00:00', {seconds: 3600, actor: 'warmer'}),
                build('2026-10-17T11:00:00', {seconds: 3600, shape: 'git'}),
            ],
            d,
        )
        expect(machines).toEqual(['deck', 'vps'])
        expect(rows.get(dayKey(at('2026-10-16T10:00:00')))!.get('vps')).toBe(1)
        expect(rows.get(dayKey(at('2026-10-17T10:00:00')))!.get('deck')).toBe(0.5)
    })

    test('a wait given up counts as a wait but not a take', () => {
        const d = days(at('2026-10-17T00:00:00'), at('2026-10-17T23:00:00'))
        const takes: Take[] = [
            {ts: '2026-10-17T10:00:00', actor: 'a', waited_s: 0},
            {ts: '2026-10-17T11:00:00', actor: 'b', waited_s: 1800},
            {ts: '2026-10-17T12:00:00', actor: 'c', waited_s: 1800, gave_up: true},
        ]
        expect([...waitsByDay(takes, d).values()][0]).toEqual({takes: 2, waited: 2, hours: 1})
    })

    test('the command table puts where the time goes first', () => {
        const rows = commandTable([
            build('2026-10-17T10:00:00', {shape: 'cargo check', seconds: 10}),
            build('2026-10-17T10:00:00', {seconds: 600, first_build_in_lease: true}),
            build('2026-10-17T10:00:00', {seconds: 200, exit: 101}),
        ])
        expect(rows.map((r) => r.shape)).toEqual(['cargo test', 'cargo check'])
        expect(rows[0]).toMatchObject({runs: 2, okPct: 50, cold: 600, warm: 200})
    })

    test('the headline reads only landed sessions for time to land', () => {
        const s = (extra: Partial<Session>): Session => ({
            actor: 'x', branch: null, start: 0, end: 0, span_s: 3600, builds: 0, failed_builds: 0, build_s: 0, takes: 1,
            waited_s: 0, nodes: [], landing_attempts: 0, outcome: null, landed_at: null, gate_s: null, land_wait_s: null,
            time_to_land_s: null, sha: null, start_from: 'workspace', open: false, label: null, link: null, ...extra,
        })
        const h = headline([s({landed_at: 1, time_to_land_s: 7200, gate_s: 400}), s({})], [], [])
        expect(h).toMatchObject({sessions: 2, landed: 1, timeToLand: 7200, gate: 400, sessionLength: 3600})
    })

    const tally = (extra: Partial<Tally>): Tally => ({
        id: 's1', title: 'a', repo: 'acme/cartopolis', imported: 'claude.ai/code', archived: false, start: 0, end: 0, active_s: 3600,
        said: [], replies: 0, tool_calls: 10, failed: 1, finished: false, tools: {}, commands: {}, cargo: {}, skills: {}, files: {}, ...extra,
    })

    test('the conversations add up, and their messages fall on their day and hour', () => {
        const ten = at('2026-10-17T10:15:00')
        const ts = [tally({said: [ten, ten + 60], finished: true}), tally({id: 's2', repo: null, imported: null, said: [ten], tools: {Bash: 3}})]
        expect(talkHeadline(ts)).toMatchObject({sessions: 2, imported: 1, said: 3, activeHours: 2, toolCalls: 20, failedPct: 10, finished: 1})
        const d = days(at('2026-10-17T00:00:00'), at('2026-10-17T23:00:00'))
        const by = saidByDay(ts, d)
        expect(by.projects).toEqual(['acme/cartopolis', ''])
        expect(by.rows.get(d[0]!)!.get('acme/cartopolis')).toBe(2)
        expect(saidByHour(ts)[10]).toBe(3)
    })

    test('counts sum over sessions, most first', () => {
        const rows = topCounts([tally({tools: {Bash: 5, Edit: 1}}), tally({tools: {Edit: 2}})], 'tools')
        expect(rows).toEqual([{name: 'Bash', count: 5, sessions: 1}, {name: 'Edit', count: 3, sessions: 2}])
    })

    test('one project is its sessions, their builds, and nothing of no known project', () => {
        const h = {
            builds: [build('2026-10-17T10:00:00', {actor: 'session-s1'}), build('2026-10-17T10:00:00', {actor: 'other'})],
            takes: [] as Take[],
            sessions: [] as Session[],
            landings: [],
            conversations: [tally({imported: null}), tally({id: 's2', repo: 'acme/midas'}), tally({id: 's3', repo: null})],
        }
        const one = narrow(h, (r) => r === 'acme/cartopolis')
        expect(one.conversations.map((t) => t.id)).toEqual(['s1'])
        expect(one.builds.map((b) => b.actor)).toEqual(['session-s1'])
    })
})

test('a landed session’s time to its landing: active less its waits for nodes and landing, the rest waiting on the person', () => {
    const tally = (start: number, end: number, active_s: number, imported: string | null = null) =>
        ({id: 's', title: null, repo: null, imported, archived: false, start, end, active_s, said: [], replies: 0, tool_calls: 0, failed: 0, finished: false, tools: {}, commands: {}, cargo: {}, skills: {}, files: {}}) as Tally
    const session = (actor: string, waited_s: number, land_wait_s: number | null, gate_s: number | null, landed_at: number | null = 10_000) =>
        ({actor, waited_s, land_wait_s, gate_s, landed_at}) as Session
    // A workstation's session (`ws`) has no conversation here: its waits are not taken out of these.
    const t = timeGoes([session('session-s', 600, 300, 900), session('ws', 99_000, 0, 0)], [tally(0, 10_000, 6000), tally(0, 99_999, 50_000, 'claude.ai/code')])
    expect(t).toEqual({working: 6000 - 600 - 1200, you: 4000, node: 600, landing: 1200})
    // Open for days after its landing: only the time to the landing counts.
    expect(timeGoes([session('session-s', 0, 0, 0)], [tally(0, 500_000, 6000)])).toEqual({working: 6000, you: 4000, node: 0, landing: 0})
    // Never landed: not in it.
    expect(timeGoes([session('session-s', 0, 0, 0, null)], [tally(0, 10_000, 6000)])).toEqual({working: 0, you: 0, node: 0, landing: 0})
})

describe('typical and deploy times', () => {
    test('a month is a bar a day, a longer range a bar a week from Monday', () => {
        const month = days(at('2026-10-01T12:00:00'), at('2026-10-30T12:00:00'))
        expect(buckets(month).weekly).toBe(false)
        const quarter = days(at('2026-08-01T12:00:00'), at('2026-10-29T12:00:00'))
        const b = buckets(quarter)
        expect(b.weekly).toBe(true)
        expect(new Date(b.of(at('2026-10-29T12:00:00')) * 1000).getDay()).toBe(1)
    })

    test('typical is the median of what fell in each bucket', () => {
        const d = days(at('2026-10-16T12:00:00'), at('2026-10-17T12:00:00'))
        const g = typical([at('2026-10-16T09:00:00'), at('2026-10-16T10:00:00'), at('2026-10-16T11:00:00')], (t) => t, (t) => t % 7200, d, dayKey)
        expect(g.get(d[0]!)!.items.length).toBe(3)
        expect(g.get(d[1]!)!.median).toBe(0)
    })

    test('a deploy takes from asked for to published; failures count per target', () => {
        const ev = (kind: string, deploy: string, target: string, ts: string) => ({kind, deploy, target, ts})
        const t = deployTimes({
            targets: [{target: 'web', repo: 'a/b', machine: 'mini', after_landing: true, publishes: []}],
            recent: [
                ev('deploy_queued', 'd1', 'web', '2026-10-29T10:00:00Z'),
                ev('deploy_published', 'd1', 'web', '2026-10-29T10:30:00Z'),
                ev('deploy_queued', 'd2', 'web', '2026-10-29T11:00:00Z'),
                ev('deploy_failed', 'd2', 'web', '2026-10-29T11:05:00Z'),
            ],
        })
        expect(t).toEqual([{target: 'web', repo: 'a/b', runs: 1, failed: 1, median: 1800, p90: 1800}])
    })
})