garage44.eu/jeroen/midas

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

.. /web/src/lib/tree.ts

raw

import type {Goal, Round, Tech, TreeState} from '@/lib/api'

/**
 * The research tree laid out for the page (tree.rs, docs/mockups/research-tree),
 * read left to right as Civilization's: what needs nothing in the first column,
 * each tech a column right of the deepest of what it needs, the goal at the far
 * right. Positions are worked out here, not measured, so the lines between the
 * cards can be drawn in one SVG under them.
 */

export const CARD_W = 188
export const CARD_H = 58
export const GAP_X = 52
export const GAP_Y = 10
/** Room above the cards for each column's heading. */
export const HEAD_H = 30
export const GOAL_W = 180
export const GOAL_H = 132

export interface Placed {
    tech: Tech
    x: number
    y: number
}

export interface Edge {
    /** The tech the line starts from: what is needed. */
    a: string
    /** The tech that needs it, or 'goal'. */
    b: string
    from: {x: number; y: number}
    to: {x: number; y: number}
    /** The line's look: the need of a tech on the way (path), a guess (fog), or plain. */
    kind: 'path' | 'fog' | 'plain'
}

/** A lane of one theme across the columns, when the tree is drawn by theme. */
export interface Lane {
    /** The theme's index in `themes().list`, or -1 for the techs of none. */
    band: number
    y: number
    h: number
}

/** Where a lane's “look further here” stands: the column after its deepest card still to build. */
export interface Ghost {
    band: number
    x: number
    y: number
}

export interface Layout {
    cards: Placed[]
    edges: Edge[]
    lanes: Lane[]
    ghosts: Ghost[]
    /** Each column's left edge, the goal's not among them. */
    cols: number[]
    goal: {x: number; y: number; w: number; h: number}
    width: number
    height: number
}

/** The goal and every goal under it: a tech leading to a concrete goal leads to the abstract one too. */
export function goalsUnder(goals: Goal[], id: string): string[] {
    const out = [id]
    for (let i = 0; i < out.length && out.length < 64; i++) {
        for (const g of goals) if (g.parent === out[i] && !out.includes(g.id)) out.push(g.id)
    }
    return out
}

/** The techs drawn for a goal: those leading to it or to a goal under it, and what they need. */
export function techsOf(tree: TreeState, goal: string, showDropped = false): Tech[] {
    const under = goalsUnder(tree.goals, goal)
    const byId = new Map(tree.techs.map((t) => [t.id, t]))
    const picked = new Map<string, Tech>()
    const add = (t: Tech | undefined) => {
        if (!t || picked.has(t.id) || (t.state === 'dropped' && !showDropped)) return
        picked.set(t.id, t)
        for (const n of t.needs) add(byId.get(n))
    }
    for (const t of tree.techs) if (t.goals.some((g) => under.includes(g))) add(t)
    return [...picked.values()]
}

const ORDER: Record<string, number> = {built: 0, available: 1, locked: 2, fog: 3, dropped: 4}

/** Each tech's row: one below the deepest of what it needs among those drawn. */
export function depths(techs: Tech[]): Map<string, number> {
    const ids = new Set(techs.map((t) => t.id))
    const byId = new Map(techs.map((t) => [t.id, t]))
    const memo = new Map<string, number>()
    const depth = (id: string, seen: Set<string>): number => {
        const known = memo.get(id)
        if (known !== undefined) return known
        if (seen.has(id)) return 0
        seen.add(id)
        const needs = (byId.get(id)?.needs ?? []).filter((n) => ids.has(n))
        const d = needs.length ? 1 + Math.max(...needs.map((n) => depth(n, seen))) : 0
        memo.set(id, d)
        return d
    }
    for (const t of techs) depth(t.id, new Set())
    // A guess with nothing before it stands at the far end, by the goal, where the fog is: not among what is built.
    const deepest = Math.max(0, ...techs.filter((t) => t.state !== 'fog').map((t) => memo.get(t.id) ?? 0))
    for (const t of techs) if (t.state === 'fog' && !t.needs.some((n) => ids.has(n))) memo.set(t.id, deepest)
    return memo
}

/** Rows ordered so lines cross little: each card under the middle of what it needs, the first row over what needs it. */
function untangle(rows: Tech[][]): void {
    const pos = new Map<string, number>()
    const place = () => rows.forEach((row) => row?.forEach((t, j) => pos.set(t.id, j - (row.length - 1) / 2)))
    const mean = (xs: number[], or: number) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : or)
    place()
    for (let pass = 0; pass < 3; pass++) {
        for (let i = 1; i < rows.length; i++) {
            const row = rows[i]
            if (!row) continue
            row.sort((a, b) => mean(a.needs.filter((n) => pos.has(n)).map((n) => pos.get(n)!), pos.get(a.id)!) - mean(b.needs.filter((n) => pos.has(n)).map((n) => pos.get(n)!), pos.get(b.id)!))
            place()
        }
        const first = rows[0]
        if (!first) break
        const under = (t: Tech) => rows.slice(1).flat().filter((x) => x?.needs.includes(t.id)).map((x) => pos.get(x.id)!)
        first.sort((a, b) => mean(under(a), pos.get(a.id)!) - mean(under(b), pos.get(b.id)!))
        place()
    }
}

/** Room above a lane's cards for its theme's name, and between two lanes. */
export const LANE_HEAD = 22
export const LANE_GAP = 12
/** At most this much more between two cards when a tree is spread over the screen: further apart reads as unrelated. */
const SPREAD_MAX = 36

/**
 * Cards in rows, lines from each need to what needs it, and from the last techs to the goal. With `band`
 * (a tech's theme) the columns are cut into lanes, one theme each, stacked in the order of their bands,
 * and each lane with something still to build gets a “look further here” after its deepest card.
 * With `fill` (the height the screen has for it) a shorter tree is spread over that height.
 */
export function layout(techs: Tech[], band?: (t: Tech) => number, fill = 0): Layout {
    const d = depths(techs)
    const rows: Tech[][] = []
    for (const t of techs) (rows[d.get(t.id) ?? 0] ??= []).push(t)
    for (const row of rows) row?.sort((a, b) => (ORDER[a.state] ?? 9) - (ORDER[b.state] ?? 9) || a.name.localeCompare(b.name))
    const bandOf = (t: Tech) => (band ? band(t) : 0)
    // Lanes in their themes' order, the techs of none last.
    const bands = [...new Set(techs.map(bandOf))].sort((a, b) => (a < 0 ? 1e9 : a) - (b < 0 ? 1e9 : b))
    const laned = !!band && bands.length > 1
    const open = (t: Tech) => t.state !== 'built' && t.state !== 'dropped'
    // Each lane's “look further here”: the column after its deepest card still to build.
    const ghostCol = new Map<number, number>()
    for (const b of bands) {
        const deepest = Math.max(-1, ...techs.filter((t) => bandOf(t) === b && open(t)).map((t) => d.get(t.id) ?? 0))
        if (deepest >= 0) ghostCol.set(b, deepest + 1)
    }
    // Lanes may grow a column for a “look further here”; a tree without them keeps its shape and has one only where there is room.
    const ncols = laned ? Math.max(rows.length, ...[...ghostCol.values()].map((c) => c + 1)) : rows.length
    const cols = Array.from({length: ncols}, (_, i) => i * (CARD_W + GAP_X))
    const cards: Placed[] = []
    const lanes: Lane[] = []
    const ghosts: Ghost[] = []
    let inner: number
    // The gap between two cards in a column once a tree shorter than `fill` is spread over it.
    const spread = (room: number, n: number) => GAP_Y + Math.min(SPREAD_MAX, Math.max(0, room) / Math.max(1, n))
    if (laned) {
        const sized = bands.map((b) => {
            const sub = rows.map((row) => (row ?? []).filter((t) => bandOf(t) === b))
            untangle(sub)
            const ghost = ghostCol.get(b)
            const tallest = Math.max(1, ...sub.map((r, i) => r.length + (i === ghost ? 1 : 0)))
            return {b, sub, ghost, tallest, h: LANE_HEAD + tallest * (CARD_H + GAP_Y) - GAP_Y}
        })
        // Room left over on the screen goes to the lanes alike: their cards further apart, the rest around them.
        const natural = HEAD_H + sized.reduce((s, x) => s + x.h + LANE_GAP, 0) - LANE_GAP
        const extra = Math.max(0, fill - natural) / sized.length
        let y = HEAD_H
        for (const {b, sub, ghost, tallest, h} of sized) {
            const gap = spread(extra, tallest)
            const step = CARD_H + gap
            const top = y + LANE_HEAD + (extra - (tallest - 1) * (gap - GAP_Y)) / 2
            sub.forEach((row, i) => row.forEach((tech, j) => cards.push({tech, x: cols[i]!, y: top + j * step})))
            if (ghost !== undefined) ghosts.push({band: b, x: cols[ghost]!, y: top + (sub[ghost]?.length ?? 0) * step})
            lanes.push({band: b, y, h: h + extra})
            y += h + extra + LANE_GAP
        }
        inner = Math.max(GOAL_H, y - LANE_GAP - HEAD_H)
    } else {
        untangle(rows)
        const g = ghostCol.get(bands[0] ?? 0)
        const tallest = Math.max(1, ...rows.map((r) => r?.length ?? 0))
        const natural = tallest * (CARD_H + GAP_Y) - GAP_Y
        inner = Math.max(GOAL_H, natural, fill - HEAD_H)
        const gap = spread(inner - natural, tallest)
        const step = CARD_H + gap
        rows.forEach((row, i) => {
            const n = row?.length ?? 0
            // A short column is centred, as a tree's branches are.
            const top = HEAD_H + (inner - (n * step - gap)) / 2
            row?.forEach((tech, j) => cards.push({tech, x: cols[i]!, y: top + j * step}))
        })
        // Without lanes, one after the deepest card still to build, where its column has room.
        if (g !== undefined && g < rows.length && (rows[g]?.length ?? 0) * step + CARD_H <= inner) {
            const top = rows[g]?.length ? Math.max(...cards.filter((c) => c.x === cols[g]).map((c) => c.y)) + step : HEAD_H + (inner - CARD_H) / 2
            ghosts.push({band: bands[0] ?? 0, x: cols[g]!, y: top})
        }
    }
    const at = new Map(cards.map((c) => [c.tech.id, c]))
    const onPath = (t: Tech) => t.state !== 'built' && t.state !== 'dropped'
    const kind = (t: Tech): Edge['kind'] => (t.state === 'fog' ? 'fog' : onPath(t) ? 'path' : 'plain')
    const edges: Edge[] = []
    for (const c of cards) {
        for (const n of c.tech.needs) {
            const from = at.get(n)
            if (!from) continue
            edges.push({a: n, b: c.tech.id, from: {x: from.x + CARD_W, y: from.y + CARD_H / 2}, to: {x: c.x, y: c.y + CARD_H / 2}, kind: kind(c.tech)})
        }
    }
    const goal = {x: ncols * (CARD_W + GAP_X), y: HEAD_H + (inner - GOAL_H) / 2, w: GOAL_W, h: GOAL_H}
    // What nothing drawn needs and is not built yet is the path's open end: it leads to the goal. Every
    // tech on the tree serves the goal, so a line from each built one would only say that again, and
    // was most of the tangle.
    const needed = new Set(cards.flatMap((c) => c.tech.needs))
    for (const c of cards) {
        if (needed.has(c.tech.id) || !onPath(c.tech)) continue
        edges.push({a: c.tech.id, b: 'goal', from: {x: c.x + CARD_W, y: c.y + CARD_H / 2}, to: {x: goal.x, y: goal.y + GOAL_H / 2}, kind: kind(c.tech)})
    }
    return {cards, edges, lanes, ghosts, cols: cols.slice(0, rows.length), goal, width: goal.x + GOAL_W, height: HEAD_H + inner}
}

/** A line from the right of one card to the left of another, bending halfway. */
export function curve(e: Edge): string {
    const mid = (e.from.x + e.to.x) / 2
    return `M${e.from.x} ${e.from.y} C${mid} ${e.from.y} ${mid} ${e.to.y} ${e.to.x} ${e.to.y}`
}

/** A tech and everything on its line: what it needs, all the way back, and what needs it, onward. */
export function lineOf(techs: Tech[], id: string): Set<string> {
    const byId = new Map(techs.map((t) => [t.id, t]))
    const back = new Set([id])
    for (const at of back) for (const n of byId.get(at)?.needs ?? []) if (byId.has(n)) back.add(n)
    const on = new Set([id])
    for (const at of on) for (const t of techs) if (t.needs.includes(at)) on.add(t.id)
    return new Set([...back, ...on])
}

/** What needs a tech, directly. */
export function leadsTo(techs: Tech[], id: string): Tech[] {
    return techs.filter((t) => t.needs.includes(id))
}

export interface Branch {
    tech: Tech
    /** What builds on it, each under the deepest of what it needs. */
    children: Branch[]
    /** What it needs besides its branch, and not already on the branch's line. */
    also: Tech[]
}

/**
 * The tree as branches, for a phone: each tech under the deepest of what it needs, so a
 * column of indented rows says what the wide picture's lines say. A tech needing two
 * branches stands in one and names the other.
 */
export function branches(techs: Tech[]): Branch[] {
    const d = depths(techs)
    const byId = new Map(techs.map((t) => [t.id, t]))
    const parent = new Map<string, string>()
    for (const t of techs) {
        const needs = t.needs.filter((n) => byId.has(n) && n !== t.id)
        // The deepest need is the branch: what it stands right after. A tie goes to the one named first.
        const deepest = needs.reduce<string | null>((best, n) => (best === null || (d.get(n) ?? 0) > (d.get(best) ?? 0) ? n : best), null)
        if (deepest) parent.set(t.id, deepest)
    }
    const nodes = new Map<string, Branch>(techs.map((t) => [t.id, {tech: t, children: [], also: []}]))
    const roots: Branch[] = []
    for (const t of techs) {
        const node = nodes.get(t.id)!
        const p = parent.get(t.id)
        // A circle in the needs would hide both: such a tech stands as a root of its own.
        const seen = new Set([t.id])
        let at = p
        while (at && !seen.has(at)) {
            seen.add(at)
            at = parent.get(at)
        }
        if (!p || at) {
            roots.push(node)
            continue
        }
        nodes.get(p)!.children.push(node)
        const line = new Set<string>()
        for (let up: string | undefined = p; up && !line.has(up); up = parent.get(up)) line.add(up)
        node.also = t.needs.filter((n) => byId.has(n) && !line.has(n)).map((n) => byId.get(n)!)
    }
    const order = (a: Branch, b: Branch) => (ORDER[a.tech.state] ?? 9) - (ORDER[b.tech.state] ?? 9) || a.tech.name.localeCompare(b.tech.name)
    const sort = (bs: Branch[]) => {
        bs.sort(order)
        for (const b of bs) sort(b.children)
    }
    sort(roots)
    return roots
}

/** How far a goal is: built of known, and what is in the fog. */
export function progress(techs: Tech[]): {built: number; known: number; fog: number; sizes: Record<string, number>} {
    const live = techs.filter((t) => t.state !== 'dropped')
    const sizes: Record<string, number> = {S: 0, M: 0, L: 0}
    for (const t of live) if (t.state === 'available' || t.state === 'locked') sizes[t.size] = (sizes[t.size] ?? 0) + 1
    return {
        built: live.filter((t) => t.state === 'built').length,
        known: live.filter((t) => t.state !== 'fog').length,
        fog: live.filter((t) => t.state === 'fog').length,
        sizes,
    }
}

/** How many themes have a colour of their own; a branch past them is drawn in the neutral one. */
export const THEMES = 5

export interface Theme {
    /** What it is called: the goal under this one, or the foundation the branch grows from. */
    name: string
    /** The goal under this one it is, when the tree has those; else the branch's foundation. */
    goal?: string
    root?: string
    /** Its colour, 0 to THEMES - 1, or -1 for the neutral one. */
    slot: number
    /** How many techs wear it. */
    count: number
}

/**
 * The tree's themes and the colour every tech wears. Where the goal has goals under it, those
 * are its themes (the scout's Group proposes them): a tech wears the first it leads to, and one
 * leading to none wears the neutral colour. Without them, each branch from a foundation is a
 * theme. Either way a colour stays with its theme, in the order they were made, so one made
 * later never repaints the others; a guess standing alone has no theme yet.
 */
export function themes(techs: Tech[], goals: Goal[] = [], goal = ''): {of: Map<string, number>; band: Map<string, number>; list: Theme[]} {
    const of = new Map<string, number>()
    // Which theme a tech is in, by its index in `list` (-1: none); `of` is only its colour, shared past THEMES.
    const band = new Map<string, number>()
    const list: Theme[] = []
    const under = goals.filter((g) => goal && g.parent === goal).sort((a, b) => a.at - b.at || a.id.localeCompare(b.id, undefined, {numeric: true}))
    if (under.length) {
        const reach = under.map((g) => goalsUnder(goals, g.id))
        under.forEach((g, i) => list.push({name: g.name, goal: g.id, slot: i < THEMES ? i : -1, count: 0}))
        for (const t of techs) {
            const i = reach.findIndex((ids) => t.goals.some((x) => ids.includes(x)))
            of.set(t.id, i < 0 ? -1 : list[i]!.slot)
            band.set(t.id, i)
            if (i >= 0) list[i]!.count++
        }
        return {of, band, list}
    }
    const roots = branches(techs)
    const founded = roots.filter((b) => b.tech.state !== 'fog').sort((a, b) => a.tech.at - b.tech.at || a.tech.id.localeCompare(b.tech.id, undefined, {numeric: true}))
    const paint = (b: Branch, slot: number, i: number): number => {
        of.set(b.tech.id, slot)
        band.set(b.tech.id, i)
        return 1 + b.children.reduce((n, c) => n + paint(c, slot, i), 0)
    }
    founded.forEach((b, i) => {
        const slot = i < THEMES ? i : -1
        list.push({name: b.tech.name, root: b.tech.id, slot, count: paint(b, slot, i)})
    })
    for (const b of roots) if (!of.has(b.tech.id)) paint(b, -1, -1)
    return {of, band, list}
}

/**
 * What a goal's frontier is: what is not built yet, and the built techs it stands on directly.
 * The rest of what is built is the past, and on a grown tree most of it.
 */
export function frontier(techs: Tech[]): Tech[] {
    const open = techs.filter((t) => t.state !== 'built')
    const base = new Set(open.flatMap((t) => t.needs))
    return techs.filter((t) => t.state !== 'built' || base.has(t.id))
}

/**
 * The techs on the way to a direction's target, as the hub reads it (tree.rs `path_of`): a tech and all it
 * needs, or a goal's techs (the goals under it included) and all they need; none it was told not this to.
 */
export function pathOf(tree: TreeState, target: string): Set<string> {
    const byId = new Map(tree.techs.map((t) => [t.id, t]))
    const under = new Set(goalsUnder(tree.goals, target))
    const out = new Set(tree.techs.filter((t) => t.id === target || t.goals.some((g) => under.has(g))).map((t) => t.id))
    for (const id of out) for (const n of byId.get(id)?.needs ?? []) if (byId.has(n)) out.add(n)
    for (const id of out) if (byId.get(id)?.state === 'dropped') out.delete(id)
    return out
}

/** One session on a tech, as its pip shows it: landed, going on, or ended without landing. */
export type Pip = 'ok' | 'on' | 'off'

/** The sessions a tech is expected to take, by its size (S one, M two or three, L more). */
const EXPECTED: Record<string, number> = {S: 1, M: 3, L: 4}

/**
 * A tech's sessions as pips, oldest first, and empty ones (`null`) for what its size still expects while
 * it is not built: "▬ ▬ ▭" is one landed, one going, about one to go.
 */
export function pips(done: Pip[], size: string | null | undefined, built: boolean): (Pip | null)[] {
    const want = built ? 0 : Math.max(0, (EXPECTED[size ?? 'M'] ?? 3) - done.length)
    // At least one still to go while it is not built, however many it took already.
    return [...done, ...Array<null>(built || done.some((p) => p === 'on') ? want : Math.max(1, want)).fill(null)]
}

/** A session's pip from how it ended (tree.rs `outcome_of`): none yet is going on. */
export function pipOf(outcome: string | null | undefined): Pip {
    return !outcome ? 'on' : outcome === 'landed' ? 'ok' : 'off'
}

export interface Step {
    tech: Tech
    /** Its number on the way, from 1. */
    n: number
    /** The steps before it that it still waits for, by number: none when it can start now. */
    after: number[]
}

/**
 * What is left to build, as a numbered way in the order the hub starts it (tree.rs `next_of`, `next_key`):
 * what is being built first, then again and again the first whose needs are built or on the way before it,
 * guesses last, small before large, older before newer. A tech a direction would start next is step 1 of
 * what waits, so the numbers say what is built when.
 */
export function wayOf(techs: Tech[]): Step[] {
    const byId = new Map(techs.map((t) => [t.id, t]))
    const open = techs.filter((t) => t.state !== 'built' && t.state !== 'dropped')
    const size = (t: Tech) => ({S: 0, M: 1, L: 2})[t.size] ?? 1
    const num = (t: Tech) => Number(t.id.slice(1)) || 0
    const key = (a: Tech, b: Tech) => Number(a.state === 'fog') - Number(b.state === 'fog') || size(a) - size(b) || num(a) - num(b)
    const steps: Step[] = []
    const at = new Map<string, number>()
    const place = (t: Tech) => {
        const n = steps.length + 1
        const after = t.needs.map((id) => at.get(id)).filter((x): x is number => x !== undefined && byId.get(steps[x - 1]!.tech.id)?.state !== 'built')
        steps.push({tech: t, n, after: t.state === 'researching' ? [] : after.sort((a, b) => a - b)})
        at.set(t.id, n)
    }
    for (const t of open.filter((x) => x.state === 'researching').sort(key)) place(t)
    let rest = open.filter((x) => x.state !== 'researching').sort(key)
    // A need that is built, or not on this tree at all, is met; one on the way, once its step is placed.
    const met = (id: string) => at.has(id) || !byId.has(id) || byId.get(id)!.state === 'built' || byId.get(id)!.state === 'dropped'
    while (rest.length) {
        const t = rest.find((x) => x.needs.every(met)) ?? rest[0]!
        place(t)
        rest = rest.filter((x) => x !== t)
    }
    return steps
}

/** One look of the scout: the moves it ran on one goal, one after another, and what they brought together. */
export interface Look {
    id: string
    goal: string
    rounds: Round[]
    /** A move of it still queued or running. */
    going: boolean
    at: number
    ended?: number
    about?: string | null
    focus?: string | null
    /** `talk`: asked in a voice conversation. */
    via?: string | null
    /** Every id it changed, by kind, without repeats. */
    changed: {added: string[]; confirmed: string[]; built: string[]; drawn: string[]; insights: string[]}
    counts: {added: number; confirmed: number; built: number; insights: number; themes: number; mockups: number}
    seen: string[]
    failed: boolean
}

/** The scout's rounds as looks, oldest first: a round before looks were is a look of its own. */
export function looksOf(rounds: Round[]): Look[] {
    const by = new Map<string, Look>()
    for (const r of rounds) {
        const id = r.look ?? r.id
        let l = by.get(id)
        if (!l) {
            l = {
                id, goal: r.goal, rounds: [], going: false, at: r.at, about: r.about, focus: r.focus, via: r.via, seen: [], failed: false,
                changed: {added: [], confirmed: [], built: [], drawn: [], insights: []},
                counts: {added: 0, confirmed: 0, built: 0, insights: 0, themes: 0, mockups: 0},
            }
            by.set(id, l)
        }
        l.rounds.push(r)
        if (r.state === 'queued' || r.state === 'asked') l.going = true
        if (r.ended) l.ended = Math.max(l.ended ?? 0, r.ended)
        for (const k of ['added', 'confirmed', 'built', 'drawn', 'insights'] as const) for (const x of r.changed?.[k] ?? []) if (!l.changed[k].includes(x)) l.changed[k].push(x)
        for (const k of ['added', 'confirmed', 'built', 'insights', 'themes', 'mockups'] as const) l.counts[k] += r.counts?.[k] ?? 0
        for (const p of r.seen ?? []) if (!l.seen.includes(p)) l.seen.push(p)
        if (r.state === 'failed') l.failed = true
    }
    for (const l of by.values()) if (l.going) l.ended = undefined
    return [...by.values()]
}

/**
 * Whether this person has seen what a look brought. The hub records who as `caller:account`
 * (`web:ana` from the page), so the bare account never matched and “Seen it” never stuck.
 */
export function seenBy(l: Look, account: string | null): boolean {
    return account ? l.seen.some((s) => s === account || s.endsWith(`:${account}`)) : l.seen.length > 0
}

/** How long a move usually takes on a runner, in seconds: the middle of the last ones that ended. */
export function moveTime(rounds: Round[], move: string): number | null {
    const took = rounds.filter((r) => r.move === move && r.state === 'done' && r.ended != null && r.taken_at != null).map((r) => r.ended! - r.taken_at!).slice(-9).sort((a, b) => a - b)
    return took.length ? took[Math.floor(took.length / 2)]! : null
}

/**
 * Whether a tech is about a file the scout reads: a piece of its evidence names it (`crates/calls/src/sfu.rs`,
 * `crates/calls/src/sfu.rs:40`, `the SFU in crates/calls/src/sfu.rs`), or a folder it is in. Only paths with a
 * folder in them count, so a bare `README.md` lights nothing.
 */
export function evidenceNames(t: Tech, file: string): boolean {
    if (!file.includes('/')) return false
    return t.evidence.some((e) =>
        e.split(/[\s,;()]+/).some((w) => {
            const p = w.replace(/[:#].*$/, '').replace(/^\.?\//, '').replace(/\/$/, '')
            return p.includes('/') && (file === p || file.endsWith(`/${p}`) || file.startsWith(`${p}/`))
        }),
    )
}

/** One research session in a goal's history: its tech, when it started and ended, how, and what it cost. */
export interface Run {
    tech: Tech
    id: string
    at: number
    ended: number | null
    outcome: string | null
    cost: number | null
}

/**
 * How a goal's work went: techs built a week by a session or the person (`built`) and found built already by the scout
 * (`found`: what a first look over an old project finds is no work of that week), oldest first, the last `weeks` up to
 * `now`; and its research sessions newest first, with what they add up to.
 */
export function history(techs: Tech[], now: number, weeks = 8): {
    built: number[]
    found: number[]
    runs: Run[]
    landed: number
    ended: number
    hours: number | null
    cost: number
    costed: number
} {
    const WEEK = 7 * 86400
    const built = Array.from({length: weeks}, () => 0)
    const found = Array.from({length: weeks}, () => 0)
    for (const t of techs) {
        if (t.state !== 'built' || !t.built_at) continue
        const ago = Math.floor((now - t.built_at) / WEEK)
        if (ago >= 0 && ago < weeks) (t.built_by === 'scout' ? found : built)[weeks - 1 - ago]! += 1
    }
    const runs: Run[] = techs
        .flatMap((t) => (t.sessions ?? []).map((s) => ({tech: t, id: s.id, at: s.at ?? 0, ended: s.ended ?? null, outcome: s.outcome, cost: s.cost ?? null})))
        .sort((a, b) => b.at - a.at)
    const done = runs.filter((r) => r.outcome && r.ended && r.at)
    const took = done.map((r) => (r.ended! - r.at) / 3600).sort((a, b) => a - b)
    const costs = runs.filter((r) => r.cost != null)
    return {
        built,
        found,
        runs,
        landed: runs.filter((r) => r.outcome === 'landed').length,
        ended: runs.filter((r) => r.outcome).length,
        // The median: one session left open over a weekend does not make every one look slow.
        hours: took.length ? took[Math.floor((took.length - 1) / 2)]! : null,
        cost: costs.reduce((s, r) => s + r.cost!, 0),
        costed: costs.length,
    }
}