main
Drew Owens Scrub internal hostnames, quota ledger, local paths, and private links for public release 09af481
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
#!/usr/bin/env python3
"""Deterministic active-time calculator and 2560x1440 headline graphic builder for Microgoose.

Outputs inside timeline/:
  - active_timeline_data.json
  - microgoose_build_timeline.html
  - microgoose_build_timeline.png (2560x1440)
"""

import argparse
import functools
import html
import http.server
import json
import os
import socketserver
import subprocess
import tempfile
import threading
from datetime import datetime, timezone, timedelta
from pathlib import Path
from PIL import Image

CST = timezone(timedelta(hours=-6))
IDLE_GAP_THRESHOLD_SEC = 1200  # 20 minutes with zero agent steps or running tools across all sessions

TIMELINE_DIR = Path(__file__).resolve().parent
REPO_ROOT = TIMELINE_DIR.parent
DATA_JSON_PATH = TIMELINE_DIR / "active_timeline_data.json"
HTML_OUT_PATH = TIMELINE_DIR / "microgoose_build_timeline.html"
PNG_OUT_PATH = TIMELINE_DIR / "microgoose_build_timeline.png"

T0_UTC = "2026-11-11T19:34:15Z"


def parse_utc(ts: str) -> datetime:
    return datetime.fromisoformat(ts.replace("Z", "+00:00")).astimezone(timezone.utc)


def fmt_cst(ts: str) -> str:
    dt = parse_utc(ts).astimezone(CST)
    return dt.strftime("%b %-d, %-I:%M:%S %p CST")


def fmt_active_hm(sec: float, plus: bool = True) -> str:
    s = int(round(sec))
    prefix = "+" if plus else ""
    if s < 60:
        return f"{prefix}0m"
    total_m = int(round(sec / 60.0))
    h = total_m // 60
    m = total_m % 60
    if h == 0:
        return f"{prefix}{m}m"
    return f"{prefix}{h}h {m:02d}m"


def fmt_hms(sec: float) -> str:
    s = int(round(sec))
    h = s // 3600
    m = (s % 3600) // 60
    rem = s % 60
    if h > 0:
        return f"{h}h {m:02d}m {rem:02d}s"
    return f"{m}m {rem:02d}s"


def derive_segments_from_transcripts(cutoff_utc: str | None = None):
    """Compute union of active execution intervals from raw Antigravity transcripts + AI Flow turns."""
    brain_root = Path.home() / ".gemini" / "antigravity" / "brain"
    session_ids = [
        "d1adcf0c-438a-4cbb-ad57-fa14157a36d9",
        "9a5348f3-7e9f-4ecb-904e-231d863eae4e",
        "28a27b8a-5e8f-463e-9827-612efb7ee4e8",
        "1b3af51d-794e-42f0-af3c-cc31c078ec58",
        "ad29f6ce-f12b-40ec-81e2-8347575f40bc",
        "65c690b1-a2df-4f93-842a-c97f6de729dd",
        "1ee83341-a109-46fd-aada-31a0245d2447",
    ]
    t0 = parse_utc(T0_UTC)
    cutoff = parse_utc(cutoff_utc) if cutoff_utc else None
    timestamps: list[datetime] = []

    for sid in session_ids:
        tp = brain_root / sid / ".system_generated" / "logs" / "transcript.jsonl"
        if not tp.is_file():
            return None
        with open(tp, encoding="utf-8") as f:
            for line in f:
                obj = json.loads(line)
                ca = obj.get("created_at")
                if not ca:
                    continue
                dt = parse_utc(ca)
                if dt >= t0 and (cutoff is None or dt <= cutoff):
                    timestamps.append(dt)

    run_json_path = REPO_ROOT / "aiflow" / "run" / "run.json"
    if run_json_path.is_file():
        rj = json.load(open(run_json_path, encoding="utf-8"))
        for turn in rj.get("turns", []):
            for k in ("startedAt", "endedAt", "at", "ts"):
                if turn.get(k):
                    dt = parse_utc(turn[k])
                    if dt >= t0 and (cutoff is None or dt <= cutoff):
                        timestamps.append(dt)

    if not timestamps:
        return None

    timestamps.sort()
    segments = []
    seg_start = timestamps[0]
    seg_end = timestamps[0]
    for dt in timestamps[1:]:
        if (dt - seg_end).total_seconds() <= IDLE_GAP_THRESHOLD_SEC:
            seg_end = dt
        else:
            segments.append((seg_start, seg_end))
            seg_start = dt
            seg_end = dt
    segments.append((seg_start, seg_end))

    out = []
    cum_sec = 0.0
    for idx, (s, e) in enumerate(segments, start=1):
        dur = (e - s).total_seconds()
        out.append(
            {
                "segment_index": idx,
                "phase": 1 if idx <= 2 else 2,
                "start_utc": s.strftime("%Y-%m-%dT%H:%M:%SZ"),
                "end_utc": e.strftime("%Y-%m-%dT%H:%M:%SZ"),
                "start_cst": fmt_cst(s.strftime("%Y-%m-%dT%H:%M:%SZ")),
                "end_cst": fmt_cst(e.strftime("%Y-%m-%dT%H:%M:%SZ")),
                "duration_sec": int(round(dur)),
                "duration_hms": fmt_hms(dur),
                "active_start_sec": int(round(cum_sec)),
                "active_end_sec": int(round(cum_sec + dur)),
            }
        )
        cum_sec += dur
    return out


def map_utc_to_active_sec(ts_utc: str, segments: list[dict]) -> float:
    dt = parse_utc(ts_utc)
    for seg in segments:
        s = parse_utc(seg["start_utc"])
        e = parse_utc(seg["end_utc"])
        if dt <= s:
            return float(seg["active_start_sec"])
        if s <= dt <= e:
            return float(seg["active_start_sec"]) + (dt - s).total_seconds()
    return float(segments[-1]["active_end_sec"])


def build_data(cutoff_utc: str, skillpack_done_utc: str | None = None) -> dict:
    effective_cutoff = skillpack_done_utc if (skillpack_done_utc and skillpack_done_utc > cutoff_utc) else cutoff_utc
    segments = derive_segments_from_transcripts(cutoff_utc=effective_cutoff)
    if segments is None and DATA_JSON_PATH.is_file():
        existing = json.load(open(DATA_JSON_PATH, encoding="utf-8"))
        segments = existing["active_segments"]
    assert segments is not None, "No transcript logs or cached active_timeline_data.json found"

    # Ensure last segment extends at least to effective_cutoff if within active window
    last_end = parse_utc(segments[-1]["end_utc"])
    eff_dt = parse_utc(effective_cutoff)
    if eff_dt > last_end and (eff_dt - last_end).total_seconds() <= IDLE_GAP_THRESHOLD_SEC:
        extra = (eff_dt - last_end).total_seconds()
        segments[-1]["end_utc"] = eff_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
        segments[-1]["end_cst"] = fmt_cst(segments[-1]["end_utc"])
        segments[-1]["duration_sec"] = int(round(segments[-1]["duration_sec"] + extra))
        segments[-1]["duration_hms"] = fmt_hms(segments[-1]["duration_sec"])
        segments[-1]["active_end_sec"] = int(round(segments[-1]["active_end_sec"] + extra))

    p1_sec = sum(s["duration_sec"] for s in segments if s["phase"] == 1)
    p2_sec = sum(s["duration_sec"] for s in segments if s["phase"] == 2)
    tot_sec = p1_sec + p2_sec

    lanes_spec = [
        {
            "id": "coordinator",
            "title": "Coordinator & Architecture",
            "subtitle": "d1adcf0c · system integration & skillpack",
            "bars": [
                ("2026-11-11T19:34:15Z", "2026-11-11T21:18:28Z", 1, "done"),
                ("2026-11-11T22:41:50Z", "2026-11-11T22:45:33Z", 1, "done"),
                ("2026-11-12T18:42:26Z", "2026-11-12T18:46:04Z", 1, "done"),
                ("2026-11-12T21:16:51Z", "2026-11-12T21:46:36Z", 1, "done"),
                ("2026-11-12T22:13:16Z", "2026-11-12T22:28:31Z", 1, "done"),
                ("2026-11-13T19:42:03Z", "2026-11-13T21:27:17Z", 2, "done"),
                (
                    "2026-11-13T21:27:17Z",
                    segments[-1]["end_utc"],
                    2,
                    "done" if skillpack_done_utc else "in_progress",
                ),
            ],
        },
        {
            "id": "electronics",
            "title": "Electronics PCB (adom-aiflow)",
            "subtitle": "9a5348f3 · 25-stage Spine rev A & STEP audit",
            "bars": [
                ("2026-11-11T20:00:48Z", "2026-11-11T20:43:58Z", 1, "done"),
                ("2026-11-11T20:47:03Z", "2026-11-11T23:07:32Z", 1, "done"),
                ("2026-11-12T18:45:42Z", "2026-11-12T21:16:51Z", 1, "done"),
                ("2026-11-12T21:36:49Z", "2026-11-12T22:13:16Z", 1, "done"),
                ("2026-11-13T21:05:00Z", "2026-11-13T21:15:59Z", 2, "done"),
            ],
        },
        {
            "id": "rl_sim",
            "title": "RL & Dual-Engine Sim",
            "subtitle": "1b3af51d · RTX 4090 PPO, MuJoCo 4.0 & Drake 1.58",
            "bars": [
                ("2026-11-11T20:02:19Z", "2026-11-11T20:53:01Z", 1, "done"),
                ("2026-11-11T21:15:21Z", "2026-11-11T21:16:24Z", 1, "done"),
                ("2026-11-11T22:42:24Z", "2026-11-11T22:45:24Z", 1, "done"),
                ("2026-11-13T19:42:30Z", "2026-11-13T20:12:18Z", 2, "done"),
                ("2026-11-13T20:07:00Z", "2026-11-13T21:24:39Z", 2, "done"),
            ],
        },
        {
            "id": "firmware",
            "title": "Firmware & goosectl Runtime",
            "subtitle": "ad29f6ce · STM32G431 200 Hz C11 & 50 Hz ONNX",
            "bars": [
                ("2026-11-11T20:02:20Z", "2026-11-11T20:31:10Z", 1, "done"),
                ("2026-11-11T20:44:44Z", "2026-11-11T21:17:56Z", 1, "done"),
            ],
        },
        {
            "id": "mechanical",
            "title": "Mechanical CAD & Bambu Slice",
            "subtitle": "28a27b8a · 15-DoF OCCT CAD, wiring & 3 plates",
            "bars": [
                ("2026-11-11T20:47:04Z", "2026-11-11T22:41:51Z", 1, "done"),
                ("2026-11-12T21:17:18Z", "2026-11-12T21:35:01Z", 1, "done"),
            ],
        },
        {
            "id": "validation",
            "title": "Validation, FEA/SPICE & Docs",
            "subtitle": "65c690b1 + 1ee83341 · 3D FEA, ngspice & timeline",
            "bars": [
                ("2026-11-11T20:47:07Z", "2026-11-11T21:14:25Z", 1, "done"),
                ("2026-11-12T21:35:01Z", "2026-11-12T21:45:35Z", 1, "done"),
                ("2026-11-13T20:35:55Z", "2026-11-13T20:57:31Z", 2, "done"),
                ("2026-11-13T21:16:00Z", "2026-11-13T21:27:17Z", 2, "done"),
                ("2026-11-13T21:30:39Z", segments[-1]["end_utc"], 2, "done"),
            ],
        },
    ]

    lanes_out = []
    for lspec in lanes_spec:
        bars_out = []
        for s_u, e_u, ph, st in lspec["bars"]:
            a_s = map_utc_to_active_sec(s_u, segments)
            a_e = map_utc_to_active_sec(e_u, segments)
            bars_out.append(
                {
                    "start_utc": s_u,
                    "end_utc": e_u,
                    "active_start_sec": round(a_s, 1),
                    "active_end_sec": round(a_e, 1),
                    "phase": ph,
                    "status": st,
                }
            )
        lanes_out.append(
            {
                "id": lspec["id"],
                "title": lspec["title"],
                "subtitle": lspec["subtitle"],
                "bars": bars_out,
            }
        )

    sk_utc = skillpack_done_utc or segments[-1]["end_utc"]
    sk_status = "done" if skillpack_done_utc else "in_progress"

    milestones_raw = [
        # (id, lane_id, slot, align, utc, short_label, card_group, card_title, phase, status)
        ("t0", "coordinator", "above", "left", "2026-11-11T19:34:15Z", "Prompt T0", 1, "Initial Microgoose prompt (T0)", 1, "done"),
        ("intake", "electronics", "above", "left", "2026-11-11T20:00:48Z", "AI Flow intake", 1, "AI Flow intake & circuit design", 1, "done"),
        ("bam", "rl_sim", "above", "left", "2026-11-11T20:08:40Z", "BAM actuator ID", 1, "BAM XL330 actuator ID (0.036 deg)", 1, "done"),
        ("fw", "firmware", "above", "left", "2026-11-11T20:30:09Z", "Firmware + goosectl", 1, "STM32G431 C11 + 50 Hz goosectl", 1, "done"),
        ("rev1", "electronics", "below", "left", "2026-11-11T20:37:40Z", "1st page publish", 1, "First wiki page publish (Rev 1)", 1, "done"),
        ("ppo1", "rl_sim", "below", "left", "2026-11-11T20:43:16Z", "Stage 1 PPO (2.02M)", 1, "Stage 1 CUDA PPO (2.02M steps)", 1, "done"),
        ("r20", "firmware", "below", "left", "2026-11-11T21:17:42Z", "0.30 mOhm R20 lock", 1, "Datasheet v1 & 0.30 mOhm shunt lock", 1, "done"),
        ("spice1", "electronics", "above", "center", "2026-11-11T22:04:39Z", "Sch (0 ERC) + SPICE", 2, "Schematic (0 ERC) & ngspice-42", 1, "done"),
        ("cad1", "mechanical", "above", "center", "2026-11-11T22:41:14Z", "15-DoF CAD + Bambu slice", 2, "15-DoF CAD (23 parts) + 3-plate slice", 1, "done"),
        ("drc", "electronics", "above", "center", "2026-11-12T20:54:27Z", "Rev A DRC/ERC clean", 2, "Spine rev A DRC/ERC clean (board-9)", 1, "done"),
        ("rebind", "mechanical", "above", "center", "2026-11-12T21:34:40Z", "STEP CAD re-bind", 2, "Routed PCB STEP re-bind (0 collisions)", 1, "done"),
        ("gate32", "validation", "below", "center", "2026-11-12T21:45:14Z", "32/32 gate + PDF", 2, "32/32 integration gate & 8-page PDF", 1, "done"),
        ("fguard", "electronics", "below", "right", "2026-11-12T22:13:00Z", "finish-guard pass", 2, "120 s build film & finish-guard pass", 1, "done"),
        ("p1_pub", "coordinator", "above", "right", "2026-11-12T22:16:32Z", "Phase 1 delivery", 2, "Phase 1 full-stack wiki delivery", 1, "done"),
        ("em_mod", "rl_sim", "above", "right", "2026-11-13T19:53:55Z", "XL330+Spine", 3, "Coupled XL330 + Spine model", 2, "done"),
        ("ppo2", "rl_sim", "below", "left", "2026-11-13T20:12:18Z", "Stage 2/3 PPO", 3, "Stage 2/3 full-DR + slope CUDA PPO", 2, "done"),
        ("step_aud", "electronics", "above", "right", "2026-11-13T21:15:59Z", "STEP C2/C3 audit", 3, "STEP C2/C3/MC2 copper audit", 2, "done"),
        ("sim2sim", "rl_sim", "above", "right", "2026-11-13T21:24:39Z", "MuJoCo + Drake", 3, "MuJoCo 4.0.1 + Drake 1.58.0 sim2sim", 2, "done"),
        ("mech_val", "validation", "above", "right", "2026-11-13T21:25:41Z", "Mech FEA & ZMP", 3, "10-min thermal, CoM/ZMP & 3D FEA", 2, "done"),
        ("elec_val", "validation", "below", "right", "2026-11-13T21:27:17Z", "Elec SPICE & Fields", 3, "ngspice-42, Fields & Physical Test Plan", 2, "done"),
        ("skillpack", "coordinator", "above", "right", sk_utc, "Sim skillpack", 3, "Team sim skillpack (Adom internal)", 2, sk_status),
    ]

    milestones_out = []
    for mid, lid, slot, align, u_ts, s_lbl, c_grp, c_title, ph, st in milestones_raw:
        act_s = map_utc_to_active_sec(u_ts, segments)
        act_lbl = fmt_active_hm(act_s, plus=True)
        if st == "in_progress":
            act_lbl = act_lbl + "+"
        milestones_out.append(
            {
                "id": mid,
                "lane_id": lid,
                "slot": slot,
                "align": align,
                "utc": u_ts,
                "cst": fmt_cst(u_ts),
                "active_sec": round(act_s, 1),
                "active_label": act_lbl,
                "short_label": s_lbl,
                "card_group": c_grp,
                "card_title": c_title,
                "phase": ph,
                "status": st,
            }
        )

    return {
        "schema": "microgoose-active-timeline/v1",
        "title": "Microgoose build timeline",
        "idle_gap_threshold_sec": IDLE_GAP_THRESHOLD_SEC,
        "method_one_sentence": (
            "Active build time is the union of continuous execution intervals across all seven "
            "gemini-4-carbon agent transcripts and background EDA, slicer, and GPU jobs, collapsing "
            "any global inactivity gap over 20 minutes with zero agent steps or running tools into a "
            "thin axis break (//)."
        ),
        "totals": {
            "total_active_sec": tot_sec,
            "total_active_hm": fmt_active_hm(tot_sec, plus=False),
            "total_active_hms": fmt_hms(tot_sec),
            "phase1_active_sec": p1_sec,
            "phase1_active_hm": fmt_active_hm(p1_sec, plus=False),
            "phase1_active_hms": fmt_hms(p1_sec),
            "phase2_active_sec": p2_sec,
            "phase2_active_hm": fmt_active_hm(p2_sec, plus=False),
            "phase2_active_hms": fmt_hms(p2_sec),
        },
        "active_segments": segments,
        "lanes": lanes_out,
        "milestones": milestones_out,
    }


def generate_html(data: dict) -> str:
    segs = data["active_segments"]
    tot_sec = data["totals"]["total_active_sec"]

    # Track geometry inside 2560x1440 canvas
    track_x0 = 540.0
    track_x1 = 2504.0
    break_w = 28.0
    usable_w = (track_x1 - track_x0) - break_w * (len(segs) - 1)
    px_per_sec = usable_w / float(tot_sec)

    seg_px = []
    cur_x = track_x0
    for s in segs:
        w = s["duration_sec"] * px_per_sec
        seg_px.append(
            {
                "active_start_sec": s["active_start_sec"],
                "active_end_sec": s["active_end_sec"],
                "x0": cur_x,
                "x1": cur_x + w,
                "phase": s["phase"],
            }
        )
        cur_x += w + break_w

    def active_sec_to_x(a_sec: float) -> float:
        for sp in seg_px:
            if a_sec <= sp["active_end_sec"] + 0.5:
                clamped = max(sp["active_start_sec"], min(sp["active_end_sec"], a_sec))
                return sp["x0"] + (clamped - sp["active_start_sec"]) * px_per_sec
        return seg_px[-1]["x1"]

    # Build SVG chart region (width=2560, height=760, y=164..924)
    svg_parts = [
        '<svg class="chart-svg" width="2560" height="772" viewBox="0 0 2560 772" xmlns="http://www.w3.org/2000/svg">'
    ]
    svg_parts.append(
        """
      <defs>
        <linearGradient id="tealBar" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stop-color="#00e6dc" stop-opacity="0.34"/>
          <stop offset="100%" stop-color="#00e6dc" stop-opacity="0.20"/>
        </linearGradient>
        <linearGradient id="purpleBar" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stop-color="#8c6bf7" stop-opacity="0.42"/>
          <stop offset="100%" stop-color="#8c6bf7" stop-opacity="0.24"/>
        </linearGradient>
        <pattern id="inProgHatch" width="12" height="12" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
          <line x1="0" y1="0" x2="0" y2="12" stroke="#00e6dc" stroke-width="4" stroke-opacity="0.30"/>
        </pattern>
      </defs>
    """
    )

    # Legend on left of axis header (y=0..56)
    has_in_prog = any(m["status"] == "in_progress" for m in data["milestones"])
    in_prog_legend = (
        """
        <rect x="314" y="4" width="22" height="14" rx="4" fill="url(#inProgHatch)" stroke="#00e6dc" stroke-width="2" stroke-dasharray="5,3"/>
        <text x="343" y="17" class="legend-txt">In progress</text>"""
        if has_in_prog
        else ""
    )
    svg_parts.append(
        f"""
      <g transform="translate(52, 14)">
        <rect x="0" y="4" width="20" height="14" rx="4" fill="url(#tealBar)" stroke="#00e6dc" stroke-width="2"/>
        <text x="27" y="17" class="legend-txt">Phase 1 Done</text>

        <rect x="156" y="4" width="20" height="14" rx="4" fill="url(#purpleBar)" stroke="#8c6bf7" stroke-width="2"/>
        <text x="183" y="17" class="legend-txt">Phase 2 Done</text>{in_prog_legend}
      </g>
    """
    )

    # Axis baseline segments & hour ticks
    axis_y = 44.0
    lane_top0 = 64.0
    lane_h = 110.0
    lane_gap = 6.0
    lanes_bottom = lane_top0 + len(data["lanes"]) * lane_h + (len(data["lanes"]) - 1) * lane_gap

    for sp in seg_px:
        stroke_col = "#2a3c4a" if sp["phase"] == 1 else "#3c3563"
        svg_parts.append(
            f'<line x1="{sp["x0"]:.1f}" y1="{axis_y}" x2="{sp["x1"]:.1f}" y2="{axis_y}" stroke="{stroke_col}" stroke-width="2.5"/>'
        )

    max_hours = int(tot_sec // 3600)
    for hr in range(0, max_hours + 1):
        sec_h = hr * 3600.0
        xh = active_sec_to_x(sec_h)
        svg_parts.append(
            f'<line x1="{xh:.1f}" y1="{axis_y - 8}" x2="{xh:.1f}" y2="{axis_y}" stroke="#5f788a" stroke-width="2"/>'
        )
        svg_parts.append(
            f'<line x1="{xh:.1f}" y1="{lane_top0}" x2="{xh:.1f}" y2="{lanes_bottom:.1f}" stroke="#192530" stroke-width="1.5"/>'
        )
        lbl = f"+{hr}h"
        svg_parts.append(
            f'<text x="{xh:.1f}" y="{axis_y - 15}" text-anchor="middle" class="axis-tick">{lbl}</text>'
        )

    # End tick at exact total active time
    x_end = seg_px[-1]["x1"]
    svg_parts.append(
        f'<line x1="{x_end:.1f}" y1="{axis_y - 8}" x2="{x_end:.1f}" y2="{lanes_bottom:.1f}" stroke="#2f4354" stroke-width="1.5" stroke-dasharray="4,4"/>'
    )

    # Thin break markers (//) between segments — NO sleep/pause labels
    for i in range(len(seg_px) - 1):
        bx0 = seg_px[i]["x1"]
        bx1 = seg_px[i + 1]["x0"]
        bmid = 0.5 * (bx0 + bx1)
        # Subtle break corridor lines
        svg_parts.append(
            f'<line x1="{bmid - 4:.1f}" y1="{lane_top0}" x2="{bmid - 4:.1f}" y2="{lanes_bottom:.1f}" stroke="#263847" stroke-width="1.5" stroke-dasharray="4,5"/>'
        )
        svg_parts.append(
            f'<line x1="{bmid + 4:.1f}" y1="{lane_top0}" x2="{bmid + 4:.1f}" y2="{lanes_bottom:.1f}" stroke="#263847" stroke-width="1.5" stroke-dasharray="4,5"/>'
        )
        # Crisp // slash ticks on the top axis
        svg_parts.append(
            f'<line x1="{bmid - 8:.1f}" y1="{axis_y + 9}" x2="{bmid - 1:.1f}" y2="{axis_y - 9}" stroke="#00e6dc" stroke-width="2.6" stroke-linecap="round"/>'
        )
        svg_parts.append(
            f'<line x1="{bmid + 1:.1f}" y1="{axis_y + 9}" x2="{bmid + 8:.1f}" y2="{axis_y - 9}" stroke="#00e6dc" stroke-width="2.6" stroke-linecap="round"/>'
        )

    # Draw 6 lane backgrounds, headers, and bars
    lane_y_map = {}
    for idx, lane in enumerate(data["lanes"]):
        ly = lane_top0 + idx * (lane_h + lane_gap)
        lane_y_map[lane["id"]] = ly
        svg_parts.append(
            f'<rect x="48" y="{ly:.1f}" width="2464" height="{lane_h:.1f}" rx="12" fill="#111820" stroke="#1c2936" stroke-width="1.5"/>'
        )
        svg_parts.append(
            f'<line x1="518" y1="{ly + 12:.1f}" x2="518" y2="{ly + lane_h - 12:.1f}" stroke="#1e2d3b" stroke-width="1.5"/>'
        )
        svg_parts.append(
            f'<text x="70" y="{ly + 48:.1f}" class="lane-title">{html.escape(lane["title"])}</text>'
        )
        svg_parts.append(
            f'<text x="70" y="{ly + 76:.1f}" class="lane-sub">{html.escape(lane["subtitle"])}</text>'
        )

        # Center track line
        cy = ly + 55.0
        for sp in seg_px:
            svg_parts.append(
                f'<line x1="{sp["x0"]:.1f}" y1="{cy:.1f}" x2="{sp["x1"]:.1f}" y2="{cy:.1f}" stroke="#1a2632" stroke-width="2"/>'
            )

        bar_h = 24.0
        by = cy - bar_h / 2.0
        for bar in lane["bars"]:
            # Split bar if it crosses a segment boundary (bars here are within single segments)
            bx0 = active_sec_to_x(bar["active_start_sec"])
            bx1 = active_sec_to_x(bar["active_end_sec"])
            bw = max(10.0, bx1 - bx0)
            if bar["status"] == "in_progress":
                svg_parts.append(
                    f'<rect x="{bx0:.1f}" y="{by:.1f}" width="{bw:.1f}" height="{bar_h:.1f}" rx="6" fill="url(#inProgHatch)" stroke="#00e6dc" stroke-width="2.4" stroke-dasharray="6,4"/>'
                )
            elif bar["phase"] == 1:
                svg_parts.append(
                    f'<rect x="{bx0:.1f}" y="{by:.1f}" width="{bw:.1f}" height="{bar_h:.1f}" rx="6" fill="url(#tealBar)" stroke="#00e6dc" stroke-width="2.2"/>'
                )
            else:
                svg_parts.append(
                    f'<rect x="{bx0:.1f}" y="{by:.1f}" width="{bw:.1f}" height="{bar_h:.1f}" rx="6" fill="url(#purpleBar)" stroke="#8c6bf7" stroke-width="2.2"/>'
                )

    # Draw milestone pins & callout pills (with non-overlap assertion)
    placed_boxes: dict[tuple[str, str], list[tuple[float, float, str]]] = {}
    for m in data["milestones"]:
        ly = lane_y_map[m["lane_id"]]
        cy = ly + 55.0
        mx = active_sec_to_x(m["active_sec"])
        is_prog = m["status"] == "in_progress"
        accent = "#00e6dc" if (m["phase"] == 1 or is_prog) else "#b197fc"
        dot_stroke = "#00e6dc" if m["phase"] == 1 else "#8c6bf7"

        if m["slot"] == "above":
            pill_y = ly + 7.0
            stem_y1 = pill_y + 27.0
            stem_y2 = cy - 7.0
        else:
            pill_y = ly + 76.0
            stem_y1 = cy + 7.0
            stem_y2 = pill_y

        full_txt = f'{m["active_label"]}  {m["short_label"]}'
        est_w = max(132.0, len(full_txt) * 9.5 + 22.0)
        if m["align"] == "left":
            px = max(track_x0 - 12.0, min(mx - 12.0, 2500.0 - est_w))
        elif m["align"] == "right":
            px = min(2500.0 - est_w, max(track_x0 - 12.0, mx - est_w + 12.0))
        else:
            px = max(track_x0 - 12.0, min(2500.0 - est_w, mx - est_w / 2.0))

        key = (m["lane_id"], m["slot"])
        for ox0, ox1, oid in placed_boxes.get(key, []):
            if not (px + est_w + 6.0 <= ox0 or px >= ox1 + 6.0):
                px = ox1 + 8.0
        placed_boxes.setdefault(key, []).append((px, px + est_w, m["id"]))

        svg_parts.append(
            f'<line x1="{mx:.1f}" y1="{stem_y1:.1f}" x2="{mx:.1f}" y2="{stem_y2:.1f}" stroke="{dot_stroke}" stroke-width="2" stroke-opacity="0.85"/>'
        )
        if is_prog:
            svg_parts.append(
                f'<circle cx="{mx:.1f}" cy="{cy:.1f}" r="7.5" fill="#0d1317" stroke="#00e6dc" stroke-width="2.8" stroke-dasharray="4,2"/>'
            )
            svg_parts.append(
                f'<rect x="{px:.1f}" y="{pill_y:.1f}" width="{est_w:.1f}" height="27" rx="6" fill="#13242b" stroke="#00e6dc" stroke-width="1.8" stroke-dasharray="5,3"/>'
            )
        else:
            svg_parts.append(
                f'<circle cx="{mx:.1f}" cy="{cy:.1f}" r="6.5" fill="{dot_stroke}" stroke="#0d1317" stroke-width="2.2"/>'
            )
            pill_bg = "#122129" if m["phase"] == 1 else "#1c1930"
            pill_bd = "#1f4d53" if m["phase"] == 1 else "#473878"
            svg_parts.append(
                f'<rect x="{px:.1f}" y="{pill_y:.1f}" width="{est_w:.1f}" height="27" rx="6" fill="{pill_bg}" stroke="{pill_bd}" stroke-width="1.5"/>'
            )

        svg_parts.append(
            f'<text x="{px + 10:.1f}" y="{pill_y + 18.5:.1f}" class="pin-lbl">'
            f'<tspan fill="{accent}" font-family="var(--font-mono)" font-weight="500">{html.escape(m["active_label"])}</tspan>'
            f'<tspan dx="6" fill="#e9f1f7">{html.escape(m["short_label"])}</tspan>'
            f"</text>"
        )

    svg_parts.append("</svg>")
    svg_block = "\n".join(svg_parts)

    # Group milestones into 3 bottom summary cards
    cards_meta = [
        (1, "Phase 1 · Intake, Firmware & Stage 1 RL", "Active +0m to +1h 43m", "teal"),
        (2, "Phase 1 · CAD, Spine Rev A & Delivery", "Active +2h 30m to +7h 19m", "teal"),
        (3, "Phase 2 · Dual-Engine Sim & Design Validation", f'Active +7h 31m to +{data["totals"]["total_active_hm"]}', "purple"),
    ]
    cards_html = []
    for grp_id, c_head, c_range, theme in cards_meta:
        rows = [m for m in data["milestones"] if m["card_group"] == grp_id]
        row_items = []
        for r in rows:
            is_p = r["status"] == "in_progress"
            badge_cls = "status-prog" if is_p else ("status-done-p1" if r["phase"] == 1 else "status-done-p2")
            badge_txt = "in progress" if is_p else "Done"
            time_cls = "m-time-p1" if (r["phase"] == 1 or is_p) else "m-time-p2"
            row_items.append(
                f"""
                <div class="m-row">
                  <span class="m-time {time_cls}">{html.escape(r["active_label"])}</span>
                  <span class="m-title">{html.escape(r["card_title"])}</span>
                  <span class="m-badge {badge_cls}">{badge_txt}</span>
                </div>
                """
            )
        head_cls = "card-head-teal" if theme == "teal" else "card-head-purple"
        cards_html.append(
            f"""
            <div class="m-card">
              <div class="m-card-header {head_cls}">
                <span class="m-card-title">{html.escape(c_head)}</span>
                <span class="m-card-sub">{html.escape(c_range)}</span>
              </div>
              <div class="m-card-body">
                {''.join(row_items)}
              </div>
            </div>
            """
        )

    return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Microgoose build timeline</title>
<style>
  @font-face {{ font-family: 'Familjen Grotesk'; src: url('/fonts/familjen-grotesk-700.woff2') format('woff2'); font-weight: 700; font-display: block; }}
  @font-face {{ font-family: 'Familjen Grotesk'; src: url('/fonts/familjen-grotesk-500.woff2') format('woff2'); font-weight: 500; font-display: block; }}
  @font-face {{ font-family: 'Satoshi'; src: url('/fonts/satoshi-400.woff2') format('woff2'); font-weight: 400; font-display: block; }}
  @font-face {{ font-family: 'Satoshi'; src: url('/fonts/satoshi-500.woff2') format('woff2'); font-weight: 500; font-display: block; }}
  @font-face {{ font-family: 'JetBrains Mono'; src: url('/fonts/jetbrains-mono-400.woff2') format('woff2'); font-weight: 400; font-display: block; }}
  @font-face {{ font-family: 'JetBrains Mono'; src: url('/fonts/jetbrains-mono-500.woff2') format('woff2'); font-weight: 500; font-display: block; }}

  :root {{
    --bg: #0d1317;
    --panel: #111820;
    --border: #1d2a36;
    --teal: #00e6dc;
    --purple: #8c6bf7;
    --text: #f0f6fa;
    --muted: #8da2b2;
    --font-display: 'Familjen Grotesk', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    --font-body: 'Satoshi', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    --font-mono: 'JetBrains Mono', 'SFMono-Regular', Consolas, monospace;
  }}

  * {{ box-sizing: border-box; margin: 0; padding: 0; }}
  html, body {{
    width: 2560px;
    height: 1440px;
    overflow: hidden;
    background: radial-gradient(circle at 18% 0%, #13212b 0%, #0d1317 52%);
    color: var(--text);
    font-family: var(--font-body);
    -webkit-font-smoothing: antialiased;
  }}

  .canvas {{
    width: 2560px;
    height: 1440px;
    display: flex;
    flex-direction: column;
    padding: 34px 0 32px 0;
  }}

  .header {{
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 48px 18px 48px;
  }}

  .page-title {{
    font-family: var(--font-display);
    font-weight: 700;
    font-size: 62px;
    letter-spacing: -0.02em;
    color: #f4f9fc;
    line-height: 1.05;
  }}

  .kpi-strip {{
    display: flex;
    gap: 20px;
  }}

  .kpi-card {{
    background: #111820;
    border: 1.5px solid #223241;
    border-radius: 14px;
    padding: 14px 28px;
    min-width: 270px;
    display: flex;
    flex-direction: column;
    gap: 4px;
  }}

  .kpi-card.primary {{
    background: linear-gradient(135deg, rgba(0, 230, 220, 0.13) 0%, rgba(17, 24, 32, 0.96) 100%);
    border-color: #00e6dc;
    box-shadow: 0 0 28px rgba(0, 230, 220, 0.12);
  }}

  .kpi-card.phase2 {{
    background: linear-gradient(135deg, rgba(140, 107, 247, 0.15) 0%, rgba(17, 24, 32, 0.96) 100%);
    border-color: #6d52c9;
  }}

  .kpi-label {{
    font-family: var(--font-body);
    font-weight: 500;
    font-size: 16px;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: var(--muted);
  }}

  .kpi-val {{
    font-family: var(--font-display);
    font-weight: 700;
    font-size: 46px;
    line-height: 1.05;
    color: #f3f8fb;
  }}

  .kpi-card.primary .kpi-val {{ color: var(--teal); }}
  .kpi-card.phase2 .kpi-val {{ color: #b7a2ff; }}

  .chart-svg {{
    display: block;
    flex-shrink: 0;
  }}

  .legend-txt {{
    font-family: var(--font-body);
    font-weight: 500;
    font-size: 19px;
    fill: #b8cad8;
  }}

  .axis-tick {{
    font-family: var(--font-mono);
    font-weight: 500;
    font-size: 20px;
    fill: #9bb0c1;
  }}

  .lane-title {{
    font-family: var(--font-display);
    font-weight: 700;
    font-size: 24px;
    fill: #eff6fa;
  }}

  .lane-sub {{
    font-family: var(--font-mono);
    font-weight: 400;
    font-size: 16px;
    fill: #7e96a8;
  }}

  .pin-lbl {{
    font-family: var(--font-body);
    font-weight: 500;
    font-size: 17.5px;
  }}

  .bottom-grid {{
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 22px;
    padding: 14px 48px 0 48px;
    flex: 1;
  }}

  .m-card {{
    background: #111820;
    border: 1.5px solid #1d2a36;
    border-radius: 14px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }}

  .m-card-header {{
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    padding: 14px 22px;
    border-bottom: 1px solid #1d2a36;
  }}

  .card-head-teal {{
    background: linear-gradient(90deg, rgba(0, 230, 220, 0.11) 0%, rgba(17, 24, 32, 0) 100%);
    border-top: 3px solid var(--teal);
  }}

  .card-head-purple {{
    background: linear-gradient(90deg, rgba(140, 107, 247, 0.16) 0%, rgba(17, 24, 32, 0) 100%);
    border-top: 3px solid var(--purple);
  }}

  .m-card-title {{
    font-family: var(--font-display);
    font-weight: 700;
    font-size: 23px;
    color: #f2f7fa;
  }}

  .m-card-sub {{
    font-family: var(--font-mono);
    font-weight: 400;
    font-size: 16px;
    color: #8fa5b5;
  }}

  .m-card-body {{
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    flex: 1;
    padding: 8px 22px 10px 22px;
  }}

  .m-row {{
    display: grid;
    grid-template-columns: 108px 1fr auto;
    align-items: center;
    gap: 12px;
    padding: 4px 0;
    border-bottom: 1px solid rgba(35, 50, 64, 0.55);
  }}

  .m-row:last-child {{ border-bottom: none; }}

  .m-time {{
    font-family: var(--font-mono);
    font-weight: 500;
    font-size: 18px;
  }}

  .m-time-p1 {{ color: var(--teal); }}
  .m-time-p2 {{ color: #b9a4ff; }}

  .m-title {{
    font-family: var(--font-body);
    font-weight: 500;
    font-size: 19.5px;
    color: #e4eef5;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }}

  .m-badge {{
    font-family: var(--font-mono);
    font-weight: 500;
    font-size: 15px;
    padding: 3px 10px;
    border-radius: 6px;
  }}

  .status-done-p1 {{
    color: var(--teal);
    background: rgba(0, 230, 220, 0.12);
    border: 1px solid rgba(0, 230, 220, 0.35);
  }}

  .status-done-p2 {{
    color: #cbbaff;
    background: rgba(140, 107, 247, 0.16);
    border: 1px solid rgba(140, 107, 247, 0.45);
  }}

  .status-prog {{
    color: var(--teal);
    background: rgba(0, 230, 220, 0.10);
    border: 1.5px dashed var(--teal);
  }}
</style>
</head>
<body>
  <div class="canvas">
    <div class="header">
      <h1 class="page-title">Microgoose build timeline</h1>
      <div class="kpi-strip">
        <div class="kpi-card primary">
          <span class="kpi-label">Total Active Build Time</span>
          <span class="kpi-val">{html.escape(data["totals"]["total_active_hm"])}</span>
        </div>
        <div class="kpi-card">
          <span class="kpi-label">Phase 1 Active Time</span>
          <span class="kpi-val">{html.escape(data["totals"]["phase1_active_hm"])}</span>
        </div>
        <div class="kpi-card phase2">
          <span class="kpi-label">{'Phase 2 Active Time' if all(m['status'] == 'done' for m in data['milestones']) else 'Phase 2 Active So Far'}</span>
          <span class="kpi-val">{html.escape(data["totals"]["phase2_active_hm"])}</span>
        </div>
      </div>
    </div>

    {svg_block}

    <div class="bottom-grid">
      {''.join(cards_html)}
    </div>
  </div>
</body>
</html>
"""


def find_chrome_binary() -> Path:
    cache_dir = Path.home() / ".cache" / "puppeteer" / "chrome"
    if cache_dir.is_dir():
        candidates = sorted(cache_dir.glob("**/chrome"), reverse=True)
        for c in candidates:
            if c.is_file() and os.access(c, os.X_OK):
                return c
    raise FileNotFoundError("Headless Chrome binary not found under ~/.cache/puppeteer/chrome")


def find_fonts_dir() -> Path:
    candidates = [
        Path.home() / "project" / "adom_modules" / "adom" / "fonts" / "fonts",
        Path.home() / ".gemini" / "config" / "skills" / "fonts" / "fonts",
        Path.home() / ".claude" / "skills" / "fonts" / "fonts",
    ]
    for c in candidates:
        if c.is_dir() and (c / "familjen-grotesk-700.woff2").is_file():
            return c
    raise FileNotFoundError("Adom brand woff2 fonts directory not found")


def render_png_2560x1440(html_path: Path, png_path: Path) -> None:
    chrome_bin = find_chrome_binary()
    fonts_dir = find_fonts_dir()

    class Handler(http.server.SimpleHTTPRequestHandler):
        def translate_path(self, path: str) -> str:
            clean = path.split("?", 1)[0].split("#", 1)[0]
            if clean.startswith("/fonts/"):
                fn = clean[len("/fonts/") :]
                return str(fonts_dir / fn)
            if clean in ("/", "/index.html"):
                return str(html_path)
            return str(html_path.parent / clean.lstrip("/"))

        def log_message(self, format: str, *args) -> None:
            pass

    with socketserver.TCPServer(("127.0.0.1", 0), Handler) as httpd:
        port = httpd.server_address[1]
        th = threading.Thread(target=httpd.serve_forever, daemon=True)
        th.start()
        try:
            with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
                raw_shot = Path(tmp.name)
            cmd = [
                str(chrome_bin),
                "--headless=new",
                "--no-sandbox",
                "--disable-gpu",
                "--hide-scrollbars",
                "--force-device-scale-factor=1",
                "--default-background-color=0d1317",
                "--window-size=2560,1600",
                "--virtual-time-budget=2000",
                f"--screenshot={raw_shot}",
                f"http://127.0.0.1:{port}/index.html",
            ]
            subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            im = Image.open(raw_shot)
            cropped = im.crop((0, 0, 2560, 1440))
            assert cropped.size == (2560, 1440), f"Unexpected size {cropped.size}"
            cropped.save(png_path, format="PNG", optimize=True)
            raw_shot.unlink(missing_ok=True)
        finally:
            httpd.shutdown()


def main():
    parser = argparse.ArgumentParser(description="Build active-time Microgoose headline timeline graphic")
    parser.add_argument(
        "--cutoff-utc",
        default="2026-11-13T21:45:26Z",
        help="UTC timestamp cutoff for deterministic active-time snapshot",
    )
    parser.add_argument(
        "--skillpack-done-utc",
        default="2026-11-13T21:45:26Z",
        help="Optional UTC timestamp when internal team sim skillpack completed",
    )
    args = parser.parse_args()

    data = build_data(cutoff_utc=args.cutoff_utc, skillpack_done_utc=args.skillpack_done_utc)
    DATA_JSON_PATH.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
    html_str = generate_html(data)
    HTML_OUT_PATH.write_text(html_str, encoding="utf-8")
    render_png_2560x1440(HTML_OUT_PATH, PNG_OUT_PATH)
    print(f"Wrote {DATA_JSON_PATH} ({DATA_JSON_PATH.stat().st_size} bytes)")
    print(f"Wrote {HTML_OUT_PATH} ({HTML_OUT_PATH.stat().st_size} bytes)")
    print(f"Wrote {PNG_OUT_PATH} ({PNG_OUT_PATH.stat().st_size} bytes, 2560x1440)")
    print(
        f"Totals: Total Active={data['totals']['total_active_hm']} ({data['totals']['total_active_hms']}), "
        f"Phase 1={data['totals']['phase1_active_hm']}, Phase 2={data['totals']['phase2_active_hm']}"
    )


if __name__ == "__main__":
    main()