garage44.eu/jeroen/midas

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

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

raw

import type {Build, Deploys, Landing, Session, Take, Tally} from '@/lib/types'

/*
 * What the history pages draw, worked out from the hub's kept files. Pure, so
 * `stats.test.ts` pins it without a hub.
 */

export function quantile(values: number[], p: number): number | null {
    if (values.length === 0) return null
    const sorted = [...values].sort((a, b) => a - b)
    return sorted[Math.min(sorted.length - 1, Math.round((sorted.length - 1) * p))]!
}

export const median = (values: number[]) => quantile(values, 0.5)

/** Midnight (local) of a unix time, as the key of its day. */
export function dayKey(t: number): number {
    const d = new Date(t * 1000)
    d.setHours(0, 0, 0, 0)
    return d.getTime() / 1000
}

/** Every day from `from` to `to` (unix seconds), as day keys, oldest first. */
export function days(from: number, to: number): number[] {
    const out: number[] = []
    const d = new Date(dayKey(from) * 1000)
    while (d.getTime() / 1000 <= to) {
        out.push(d.getTime() / 1000)
        d.setDate(d.getDate() + 1)
    }
    return out
}

const ts = (s: string) => Date.parse(s) / 1000

/** The agents' cargo runs: the warmer keeps nodes warm and is nobody's wait. */
export function agentBuilds(builds: Build[]): Build[] {
    return builds.filter((b) => b.actor !== 'warmer' && b.shape.startsWith('cargo') && b.seconds != null)
}

/** Hours of building per day and machine. */
export function buildHoursByDay(builds: Build[], dayKeys: number[]): {machines: string[]; rows: Map<number, Map<string, number>>} {
    const rows = new Map(dayKeys.map((d) => [d, new Map<string, number>()]))
    const machines = new Set<string>()
    for (const b of agentBuilds(builds)) {
        const row = rows.get(dayKey(ts(b.ts)))
        if (!row) continue
        const machine = b.machine ?? '?'
        machines.add(machine)
        row.set(machine, (row.get(machine) ?? 0) + b.seconds! / 3600)
    }
    return {machines: [...machines].sort(), rows}
}

/** Per day: takes, how many waited, and the hours waited. */
export function waitsByDay(takes: Take[], dayKeys: number[]): Map<number, {takes: number; waited: number; hours: number}> {
    const out = new Map(dayKeys.map((d) => [d, {takes: 0, waited: 0, hours: 0}]))
    for (const t of takes) {
        const row = out.get(dayKey(ts(t.ts)))
        if (!row) continue
        if (!t.gave_up) row.takes++
        if (t.waited_s > 0 || t.gave_up) {
            row.waited++
            row.hours += t.waited_s / 3600
        }
    }
    return out
}

export interface CommandRow {
    shape: string
    machine: string
    runs: number
    okPct: number
    median: number
    p90: number
    cold: number | null
    warm: number | null
}

/** Like `midas stats`: per command and machine, where the time goes first. */
export function commandTable(builds: Build[]): CommandRow[] {
    const groups = new Map<string, Build[]>()
    for (const b of agentBuilds(builds)) {
        const key = `${b.shape}\u0000${b.machine ?? '?'}`
        groups.set(key, [...(groups.get(key) ?? []), b])
    }
    const rows: CommandRow[] = []
    for (const [key, list] of groups) {
        const [shape, machine] = key.split('\u0000') as [string, string]
        const secs = list.map((b) => b.seconds!)
        rows.push({
            shape,
            machine,
            runs: list.length,
            okPct: Math.round((100 * list.filter((b) => b.exit === 0).length) / list.length),
            median: median(secs)!,
            p90: quantile(secs, 0.9)!,
            cold: median(list.filter((b) => b.first_build_in_lease).map((b) => b.seconds!)),
            warm: median(list.filter((b) => !b.first_build_in_lease).map((b) => b.seconds!)),
        })
    }
    return rows.sort((a, b) => b.runs * b.median - a.runs * a.median)
}

export interface Headline {
    sessions: number
    landed: number
    timeToLand: number | null
    gate: number | null
    sessionLength: number | null
    buildHours: number
    waitHours: number
    waitedPct: number | null
}

export function headline(sessions: Session[], builds: Build[], takes: Take[]): Headline {
    const landed = sessions.filter((s) => s.landed_at != null)
    const given = takes.filter((t) => !t.gave_up)
    return {
        sessions: sessions.length,
        landed: landed.length,
        timeToLand: median(landed.map((s) => s.time_to_land_s!)),
        gate: median(landed.map((s) => s.gate_s!).filter((g) => g != null)),
        sessionLength: median(sessions.map((s) => s.span_s)),
        buildHours: agentBuilds(builds).reduce((a, b) => a + b.seconds!, 0) / 3600,
        waitHours: takes.reduce((a, t) => a + t.waited_s, 0) / 3600,
        waitedPct: given.length ? Math.round((100 * given.filter((t) => t.waited_s > 0).length) / given.length) : null,
    }
}

/**
 * The history narrowed to the sessions `keep` takes by project: builds, takes
 * and landings by the session they were made in (its actor). A session of no
 * known project is in the whole workspace's view only, as on the board.
 */
export function narrow<H extends {builds: Build[]; takes: Take[]; sessions: Session[]; landings: Landing[]; conversations: Tally[]}>(
    h: H,
    keep: (repo: string | null | undefined) => boolean,
): H {
    const actors = new Set(h.sessions.filter((s) => keep(s.repo)).map((s) => s.actor))
    // A session midas ran works in a worktree named for it.
    for (const t of h.conversations) if (keep(t.repo) && !t.imported) actors.add(`session-${t.id}`)
    return {
        ...h,
        sessions: h.sessions.filter((s) => actors.has(s.actor)),
        builds: h.builds.filter((b) => actors.has(b.actor)),
        takes: h.takes.filter((t) => actors.has(t.actor)),
        landings: h.landings.filter((l) => actors.has(l.actor)),
        conversations: h.conversations.filter((t) => keep(t.repo)),
    }
}

export interface TalkHeadline {
    sessions: number
    imported: number
    said: number
    activeHours: number
    medianActive: number | null
    toolCalls: number
    failedPct: number | null
    finished: number
}

/** What the conversations in the range add up to. */
export function talkHeadline(ts: Tally[]): TalkHeadline {
    const calls = ts.reduce((a, t) => a + t.tool_calls, 0)
    const failed = ts.reduce((a, t) => a + t.failed, 0)
    return {
        sessions: ts.length,
        imported: ts.filter((t) => t.imported).length,
        said: ts.reduce((a, t) => a + t.said.length, 0),
        activeHours: ts.reduce((a, t) => a + t.active_s, 0) / 3600,
        medianActive: median(ts.map((t) => t.active_s)),
        toolCalls: calls,
        failedPct: calls ? Math.round((1000 * failed) / calls) / 10 : null,
        finished: ts.filter((t) => t.finished).length,
    }
}

/** The person's messages per day, per project (`''` for none known), in `projects`' order. */
export function saidByDay(ts: Tally[], dayKeys: number[]): {projects: string[]; rows: Map<number, Map<string, number>>} {
    const rows = new Map(dayKeys.map((d) => [d, new Map<string, number>()]))
    const totals = new Map<string, number>()
    for (const t of ts) {
        const p = t.repo ?? ''
        for (const at of t.said) {
            const row = rows.get(dayKey(at))
            if (!row) continue
            row.set(p, (row.get(p) ?? 0) + 1)
            totals.set(p, (totals.get(p) ?? 0) + 1)
        }
    }
    return {projects: [...totals.entries()].sort((a, b) => b[1] - a[1]).map(([p]) => p), rows}
}

/** The person's messages by the hour of the day they were sent (local), 0โ€“23. */
export function saidByHour(ts: Tally[]): number[] {
    const out = Array.from({length: 24}, () => 0)
    for (const t of ts) for (const at of t.said) out[new Date(at * 1000).getHours()]!++
    return out
}

export interface CountRow {
    name: string
    count: number
    /** How many sessions have it at all. */
    sessions: number
}

/** One of the tallies' counts summed over the sessions, most first. */
export function topCounts(ts: Tally[], key: 'tools' | 'commands' | 'cargo' | 'skills' | 'files', limit = 15): CountRow[] {
    const rows = new Map<string, CountRow>()
    for (const t of ts) {
        for (const [name, n] of Object.entries(t[key] ?? {})) {
            const r = rows.get(name) ?? {name, count: 0, sessions: 0}
            r.count += n
            r.sessions++
            rows.set(name, r)
        }
    }
    return [...rows.values()].sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)).slice(0, limit)
}

/**
 * Where a landed session's time goes, in seconds, from its start to its
 * landing: working, waiting on the person, waiting for a node, landing (in line
 * for the turn, and the gate). Only sessions that landed, and only up to the
 * landing: a session left open for days after it, or never landed, counted all
 * that as waiting on the person, which said nothing about what slows a change
 * down. Two records meet here, so it is an estimate: the conversations
 * (midas's own; an imported one never touched a node) say how long each was
 * open and how much of that was active โ€” the rest, gaps of over ten minutes,
 * is waiting on the person โ€” and the workspace's record of the same sessions
 * (its worktree is `session-<id>`) says when it landed, how long it waited for
 * nodes and spent landing, which is taken out of the active time. Active time
 * is counted for the whole conversation, so one that worked on after landing
 * is capped at its span to the landing. Sessions run elsewhere (a
 * workstation's CLI) are in neither.
 */
export function timeGoes(sessions: Session[], conversations: Tally[]): {working: number; you: number; node: number; landing: number} {
    const landed = new Map(sessions.filter((s) => s.landed_at != null).map((s) => [s.actor.replace(/^gate-/, '').replace(/^session-/, ''), s]))
    let open = 0
    let active = 0
    let node = 0
    let landing = 0
    for (const t of conversations) {
        const s = t.imported ? undefined : landed.get(t.id)
        if (!s) continue
        const span = Math.max(0, Math.min(t.end, s.landed_at!) - t.start)
        open += span
        active += Math.min(t.active_s, span)
        node += s.waited_s ?? 0
        landing += (s.land_wait_s ?? 0) + (s.gate_s ?? 0)
    }
    return {working: Math.max(0, active - node - landing), you: Math.max(0, open - active), node, landing}
}

/** Monday (local midnight) of a unix time's week, as the key of its week. */
export function weekKey(t: number): number {
    const d = new Date(dayKey(t) * 1000)
    d.setDate(d.getDate() - ((d.getDay() + 6) % 7))
    return d.getTime() / 1000
}

/**
 * The time axis a chart groups by: a bar per day up to a month, a bar per week
 * beyond it, where a day's bar would be a sliver holding one session.
 */
export function buckets(dayKeys: number[]): {keys: number[]; of: (t: number) => number; weekly: boolean} {
    if (dayKeys.length <= 31) return {keys: dayKeys, of: dayKey, weekly: false}
    return {keys: [...new Set(dayKeys.map(weekKey))], of: weekKey, weekly: true}
}

/** Items grouped by bucket, with the median of their values: the typical one that day or week. */
export function typical<T>(items: T[], at: (x: T) => number, value: (x: T) => number, keys: number[], of: (t: number) => number): Map<number, {items: T[]; median: number}> {
    const groups = new Map<number, T[]>(keys.map((k) => [k, []]))
    for (const x of items) groups.get(of(at(x)))?.push(x)
    return new Map([...groups].map(([k, xs]) => [k, {items: xs, median: median(xs.map(value)) ?? 0}]))
}

export interface TargetTime {
    target: string
    repo: string | null
    runs: number
    failed: number
    /** Seconds from asked for to published. */
    median: number
    p90: number
}

/** How long each target's deploys took, asked for to live, over what the hub still lists (about a week). */
export function deployTimes(d: Deploys): TargetTime[] {
    const asked = new Map<string, number>()
    const took = new Map<string, number[]>()
    const failed = new Map<string, number>()
    for (const e of d.recent) {
        const id = String(e.deploy ?? '')
        const target = String(e.target ?? '')
        if (!id || !target) continue
        if (e.kind === 'deploy_queued') asked.set(id, ts(e.ts))
        else if (e.kind === 'deploy_published' && asked.has(id)) took.set(target, [...(took.get(target) ?? []), ts(e.ts) - asked.get(id)!])
        else if (e.kind === 'deploy_failed') failed.set(target, (failed.get(target) ?? 0) + 1)
    }
    const repo = new Map(d.targets.map((t) => [t.target, t.repo]))
    return [...took]
        .map(([target, s]) => ({target, repo: repo.get(target) ?? null, runs: s.length, failed: failed.get(target) ?? 0, median: median(s)!, p90: quantile(s, 0.9)!}))
        .sort((a, b) => b.median - a.median)
}