Hi all,

To help preparing the agenda for the weekly kernel team meeting, I wrote
a small script, "debian-kernel-meet.py" (attached), that summarises the
last week of mailing list traffic as a Markdown file.

This script reads local mbox files fetched with nntp-pull from news.gmane.io,
so it does not scrape any website for the mail itself.

  Sources:

     gmane.linux.debian.devel.kernel  -> linux
     gmane.linux.kernel.initramfs     -> dracut
     gmane.linux.network              -> iproute2
     gmane.linux.nfs                  -> nfs-utils

You can check the "sample-output.md" (attached) from below command I got:

  python3 debian-kernel-meet.py -r --from 20261119

If people find it useful, I'd be happy to submit a merge request to add it to
the kernel-team repository. If there are any comparable tools available,
I'd also like to learn from it and see what can be improved.

Best regards,
Yunseong
### Mailing list activity

Threads from 2026-11-19 to 2026-11-24 (UTC) on `gmane.linux.debian.devel.kernel`, `gmane.linux.kernel.initramfs`, `gmane.linux.network`, `gmane.linux.nfs`.

#### linux

|Last activity|Source|Thread|Tags|Msgs|Reporter|Participants|Comment|
|-|-|-|-|-|-|-|-|
|2026-11-19|debian-kernel|[Bug#1154472: linux-base-7.3.5+deb14-amd64: missing changelog for 7.1.x with x \> 3](https://bugs.debian.org/1154472)|(n, )|1|Vincent Lefevre|||
|2026-11-19|debian-kernel|[\[PATCH v1 02/10\] kconfig-checker: Introduce PREEMPT\_RT configuration rules](https://lists.debian.org/msgid-search/av8tMAE3LXz8QwH5@lx-t490)||5 (1 new)||Ahmed S. Darwish|Last reply: Ahmed S. Darwish, 2026-11-19.|
|2026-11-19|debian-kernel|[Bug#1153810: linux-image-7.3.3+deb14-amd64: nouveau: gsp: mmu fault queued](https://bugs.debian.org/1153810) (forwarded: [gitlab.freedesktop.org](https://gitlab.freedesktop.org/drm/nouveau/-/work_items/521))|(*i*, u)|9 (4 new)|Vincent Lefevre||Last reply: Vincent Lefevre (submitter), 2026-11-19; no team reply yet.|
|2026-11-19|debian-kernel|[Bug#1054514: Suddenly works for me](https://bugs.debian.org/1054514) (forwarded: [regressions](https://lore.kernel.org/regressions/[email protected]/T/#u))|(n, Mu)|21 (1 new)|Timo Lindfors|Salvatore Bonaccorso, Bagas Sanjaya, Linux regression tracking (Thorsten Leemhuis), +8|Closed by Salvatore Bonaccorso, fixed in 6.1.90-1. Last reply: gisl, 2026-11-19.|
|2026-11-19|debian-kernel|[Bug#1154436: linux-image-6.1.0-56-amd64: NULL pointer dereference in xas\_load (filemap\_map\_pages) still locks up system with 6.1.192-2](https://bugs.debian.org/1154436)|(**C**, M)|4|MAXIME CARON|Salvatore Bonaccorso|Submitter answered the moreinfo request, needs follow-up. Last reply: MAXIME CARON (submitter), 2026-11-19. Mentions: regression.|
|2026-11-19|debian-kernel|[Bug#1154513: linux-modules-7.3.4+deb14-rt-amd64: i915 module nonexistent](https://bugs.debian.org/1154513) (merged with [\#1108324](https://bugs.debian.org/1108324), [\#1113788](https://bugs.debian.org/1113788))|(*i*, u)|1|Ludy||Won't fix, upstream issue.|
|2026-11-20|debian-kernel|[Bug#1153514: radeon driver fails to find installed firmware due to Debian-specific patch](https://bugs.debian.org/1153514) (forwarded: [linux!2162](https://salsa.debian.org/kernel-team/linux/-/merge_requests/2162))|(n, )|4 (1 new)|Santiago García Mantiñán|Uwe Kleine-König, epp, Caracole|Last reply: Caracole, 2026-11-20.|
|2026-11-21|debian-kernel|[Bug#1154648: linux-image-6.1.0-56-amd64: Kernel Oops in hci\_chan\_del / l2cap\_sock\_release on Intel AX201 (regression from 6.1.0-54)](https://bugs.debian.org/1154648) (merged with [\#1154123](https://bugs.debian.org/1154123), [\#1154206](https://bugs.debian.org/1154206), [\#1154212](https://bugs.debian.org/1154212), [\#1154673](https://bugs.debian.org/1154673), [\#1154866](https://bugs.debian.org/1154866), [\#1154879](https://bugs.debian.org/1154879))|(*i*, M)|5|tycho673|Salvatore Bonaccorso, skiwithme, Mael Bras, +1|Waiting for submitter. Last reply: Péter Bátori, 2026-11-23. Mentions: bisect.|
|2026-11-21|debian-kernel|[Bug#1154658: e1000e: Intel I219-LM (8086:0d4c) transmit hang during bridged VM traffic with TSO enabled](https://bugs.debian.org/1154658)|(*i*, )|1|Robert|||
|2026-11-21|debian-kernel|[Bug#1154673: linux: Bluetooth regression in 6.1.0-56-686-pae: controller disappears](https://bugs.debian.org/1154673) (merged with [\#1154123](https://bugs.debian.org/1154123), [\#1154206](https://bugs.debian.org/1154206), [\#1154212](https://bugs.debian.org/1154212), [\#1154648](https://bugs.debian.org/1154648), [\#1154866](https://bugs.debian.org/1154866), [\#1154879](https://bugs.debian.org/1154879))|(*i*, M)|5|hanta|Salvatore Bonaccorso, skiwithme, Mael Bras, +1|Waiting for submitter. Last reply: Péter Bátori, 2026-11-23. Mentions: bisect.|
|2026-11-21|debian-kernel|[Bug#1153938: linux-image-7.3.4+deb14-amd64: Kernel panic on linux-image-7.3.4-amd64](https://bugs.debian.org/1153938)|(*i*, M)|2 (1 new)|Alana Queer|Alana Queer \| they/them - elle, Salvatore Bonaccorso|Waiting for submitter. Last reply: Salvatore Bonaccorso, 2026-11-21. Mentions: test request.|
|2026-11-21|debian-kernel|[Bug#1154686: linux-image-7.3.4+deb13-amd64: CPA detected W^X violation warning on kernel 7.3.4, absent on 7.2.12](https://bugs.debian.org/1154686)|(n, )|2|matte.mb2006.9990|Salvatore Bonaccorso|Closed by Salvatore Bonaccorso. Last reply: Salvatore Bonaccorso, 2026-11-21. Mentions: regression.|
|2026-11-22|debian-kernel|[Bug#1154877: linux-image-7.3.4+deb14-amd64: brcmfmac BCM43602 Wi-Fi broken by IOMMU DMAR faults (regression from 7.2.15)](https://bugs.debian.org/1154877)|(*i*, )|1|Ryan LaBarre|||
|2026-11-22|debian-kernel|[Bug#1154879: linux-image-6.1.0-56-amd64: Bluetooth regression, kernel BUG list\_del corruption in hci\_chan\_del from l2cap\_sock\_release](https://bugs.debian.org/1154879) (merged with [\#1154123](https://bugs.debian.org/1154123), [\#1154206](https://bugs.debian.org/1154206), [\#1154212](https://bugs.debian.org/1154212), [\#1154648](https://bugs.debian.org/1154648), [\#1154673](https://bugs.debian.org/1154673), [\#1154866](https://bugs.debian.org/1154866))|(*i*, M)|1|Suvam Sen||Waiting for submitter.|
|2026-11-22|debian-kernel|[Bug#1154888: sc8280xp: ThinkPad X13s 5G WWAN (X55) intermittently fails PCIe link up on pcie@1c10000](https://bugs.debian.org/1154888)|(*i*, )|1|Oliver Mueller|||
|2026-11-22|debian-kernel|[Bug#1152418: linux-base-7.2.11+deb14-amd64: Nouveau doesn't get recognized for hardware acceleration](https://bugs.debian.org/1152418)|(n, M)|7 (2 new)|Tim McConnell|Bastian Blank, Daniel Echeverri|Submitter answered the moreinfo request, needs follow-up. Last reply: Tim McConnell (submitter), 2026-11-22.|
|2026-11-23|debian-kernel|[ARM64 build and signing provenance for Debian linux 6.12.117-1](https://lists.debian.org/msgid-search/cacofqaackgnkl-dg7co18_vrp0euszmj7qdkvo28f5kueoq...@mail.gmail.com)||1|Richard McLane|||
|2026-11-23|debian-kernel|[Bug#1153147: NFS client: mkdir on existing, uncached dir returns EROFS instead of EEXIST under ro bind mount](https://bugs.debian.org/1153147) (forwarded: [linux-nfs](https://lore.kernel.org/linux-nfs/[email protected]/T/#t))|(n, u)|4 (1 new)|Marco|Bastian Blank|Last reply: Marco (submitter), 2026-11-23.|
|2026-11-23|debian-kernel|[Bug#1154866: bluetooth service restart - a kernel issue no question (amd and intel, multiple generations)](https://bugs.debian.org/1154866) (merged with [\#1154123](https://bugs.debian.org/1154123), [\#1154206](https://bugs.debian.org/1154206), [\#1154212](https://bugs.debian.org/1154212), [\#1154648](https://bugs.debian.org/1154648), [\#1154673](https://bugs.debian.org/1154673), [\#1154879](https://bugs.debian.org/1154879))|(*i*, M)|5|skiwithme|Salvatore Bonaccorso, Mael Bras, Péter Bátori|Waiting for submitter. Last reply: Péter Bátori, 2026-11-23. Mentions: bisect.|
|2026-11-23|debian-kernel|[Bug#1155040: linux-image-6.12.118+deb13-amd64: Boot hangs with nouveau GPU faults and DMAR errors; 6.12.117 works](https://bugs.debian.org/1155040)|(*i*, )|1|David Dodson|||
|2026-11-23|debian-kernel|[Bug#1155044: src:linux: amdgpu fails to initialise on Haswell (DMAR fault reason 0x0c) in 7.3.4-1~bpo13+1](https://bugs.debian.org/1155044)|(*i*, u)|2|Aigeus||Upstream issue. Last reply: Aigeus (submitter), 2026-11-23; no team reply yet.|
|2026-11-23|debian-kernel|[Bug#1154206: Bluetooth L2CAP regression causing repeated kernel oops in hci\_chan\_del](https://bugs.debian.org/1154206) (merged with [\#1154123](https://bugs.debian.org/1154123), [\#1154212](https://bugs.debian.org/1154212), [\#1154648](https://bugs.debian.org/1154648), [\#1154673](https://bugs.debian.org/1154673), [\#1154866](https://bugs.debian.org/1154866), [\#1154879](https://bugs.debian.org/1154879))|(*i*, M)|10 (7 new)|Péter Bátori|xtem, Gustav H Meyer, Salvatore Bonaccorso, +4|Submitter answered the moreinfo request, needs follow-up. Last reply: Péter Bátori (submitter), 2026-11-23. Mentions: bisect.|
|2026-11-23|debian-kernel|[Bug#1154201: linux-image-6.1.0-55/56-armmp-lpae: crash on bringing up network](https://bugs.debian.org/1154201) (forwarded: [lore.kernel.org](https://lore.kernel.org/all/[email protected]/))|(*i*, u)|6 (3 new)|Vincent Tondellier|Christoph Weber, Christoph Weber|Last reply: Vincent Tondellier (submitter), 2026-11-23. Mentions: regression, backport.|
|2026-11-24|debian-kernel|[Bug#1155092: linux-image-7.3.5+deb14-amd64: 7.3.5 (+7.3.4) fail to find the radeon firmware. 7.2.15 works.](https://bugs.debian.org/1155092)|(*i*, )|1|Fred Korz|||
|2026-11-24|debian-kernel|[Bug#1155095: linux-image-6.12.118+deb13-amd64: kernel oops in nouveau (gp102\_acr\_wpr\_patch -\> ioread32) at boot on Quadro P520 (GP108)](https://bugs.debian.org/1155095)|(*i*, )|1|Nathan García|||
|2026-11-24|debian-kernel|[Uploading linux (7.3.6-1)](https://lists.debian.org/msgid-search/[email protected])||1|Salvatore Bonaccorso||Announcement.|
|2026-11-24|debian-kernel|[Bug#1146033: \[PATCH\] Revert "nouveau: pci: quiesce GPU on shutdown"](https://bugs.debian.org/1146033) (forwarded: [lore.kernel.org](https://lore.kernel.org/[email protected]))|(n, u)|17 (2 new)|Ole Carlsen|Bastian Blank, Uwe Kleine-König, Salvatore Bonaccorso|Last reply: ole.carlsen (submitter), 2026-11-24.|
|2026-11-24|debian-kernel|[Bug#1154123: same hci\_chan\_del oops on Realtek RTL8822CU (6.1.192-2)](https://bugs.debian.org/1154123) (merged with [\#1154206](https://bugs.debian.org/1154206), [\#1154212](https://bugs.debian.org/1154212), [\#1154648](https://bugs.debian.org/1154648), [\#1154673](https://bugs.debian.org/1154673), [\#1154866](https://bugs.debian.org/1154866), [\#1154879](https://bugs.debian.org/1154879))|(*i*, M)|8 (6 new)|W. John White|Burkhard Cruse, Salvatore Bonaccorso, skiwithme, +3|Waiting for submitter. Last reply: Oleksandr Gnitko, 2026-11-24.|

#### dracut

_No threads in this period._

#### iproute2

_No threads in this period._

#### nfs-utils

_No threads in this period._
#!/usr/bin/env python3
"""
Generate the "Mailing list activity" part of a Debian Kernel Team meeting
agenda (GitLab/Salsa wiki Markdown) from local mbox files fetched with
nntp-pull from news.gmane.io.

Sources (one mbox per group, named after the group, in --dir):

  gmane.linux.debian.devel.kernel  debian-kernel list   -> linux (+ others by subject)
  gmane.linux.kernel.initramfs     initramfs list       -> dracut
  gmane.linux.network              netdev list          -> iproute2 (subject filter)
  gmane.linux.nfs                  linux-nfs list       -> nfs-utils (subject filter)

The team meets on Wednesdays, so e.g. `--to 20261125` covers 2026-11-18 ..
2026-11-25 (both days inclusive, UTC).

Typical use:

  ./debian-kernel-meet.py --sync --to 20261125 -o /tmp/agenda.md
"""

from __future__ import annotations

import argparse
import email
import email.policy
import html
import mailbox
import os
import re
import subprocess
import sys
import time as time_mod
import urllib.error
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from datetime import date, datetime, time, timedelta, timezone
from email.utils import parseaddr, parsedate_to_datetime
from pathlib import Path

NNTP_SERVER = "news.gmane.io"

# Package sections, in output order.
PACKAGES = ["linux", "dracut", "iproute2", "nfs-utils"]

LISTS_DEBIAN_URL = "https://lists.debian.org/msgid-search/";
LORE_URL = "https://lore.kernel.org/r/";
BTS_URL = "https://bugs.debian.org/";


@dataclass(frozen=True)
class Source:
    group: str  # NNTP group == mbox file name
    label: str  # short name shown in the "Source" column
    package: str | None  # fixed package section, None = classify by subject
    link_base: str  # message-id based permalink prefix
    limit: int  # nntp-pull --limit used on the first pull of the group
    # Keep only threads where some subject matches (None = keep everything).
    subject_filter: re.Pattern | None = None


SOURCES = [
    Source(
        "gmane.linux.debian.devel.kernel", "debian-kernel", None,
        LISTS_DEBIAN_URL, 500,
    ),
    # Low volume, mostly kernel-side initramfs work plus the odd dracut mail.
    Source(
        "gmane.linux.kernel.initramfs", "initramfs", "dracut",
        LORE_URL, 300,
    ),
    # This is the whole netdev feed (~150-200 articles/day), so the first pull
    # needs a big --limit to cover a week, and we only keep iproute2 threads.
    Source(
        "gmane.linux.network", "netdev", "iproute2",
        LORE_URL, 3000,
        re.compile(r"\biproute2?\b|\bdebian\b", re.IGNORECASE),
    ),
    Source(
        "gmane.linux.nfs", "linux-nfs", "nfs-utils",
        LORE_URL, 800,
        re.compile(r"\bnfs-utils\b|\bnfs-common\b|\bdebian\b", re.IGNORECASE),
    ),
]

# Used to sort debian-kernel threads into the package sections.
PACKAGE_SUBJECT_RES = {
    "dracut": re.compile(r"\bdracut\b", re.IGNORECASE),
    "iproute2": re.compile(r"\biproute2?\b", re.IGNORECASE),
    "nfs-utils": re.compile(
        r"\bnfs-utils\b|\bnfs-common\b|\bnfs-kernel-server\b", re.IGNORECASE
    ),
}

# Automated mail on debian-kernel (BTS / DAK bookkeeping).
NOISE_SUBJECT_RE = re.compile(
    r"marked as done|^Processed\b|^Processing of |ACCEPTED into|"
    r"^Bug#\d+: (Acknowledgement|Info received|.*Pending|.*forwarded)|"
    r"\[bts-link\]|^Accepted ",
    re.IGNORECASE,
)
NOISE_SENDER_RE = re.compile(
    r"^(owner|ftpmaster|dak|bts-link-upstream)@|@(ftp-master|bugs|tracker)\.debian\.org$",
    re.IGNORECASE,
)

# gmane rewrites Message-IDs: <orig__123.456$789$gmane$org@host>
GMANE_MANGLE_RE = re.compile(r"__\d+\.\d+\$\d+\$gmane\$org(?=@)")
MSGID_RE = re.compile(r"<([^<>\s]+)>")
BUG_RE = re.compile(r"Bug#(\d+)")
REPLY_PREFIX_RE = re.compile(r"^\s*(re|fwd?|aw)\s*:\s*", re.IGNORECASE)


@dataclass
class Msg:
    mid: str
    root: str  # first Message-ID in References (or own id)
    subject: str  # without Re:/Fwd:
    author: str
    date: datetime  # aware, UTC
    is_reply: bool = False  # subject started with Re:
    body: str = ""  # unquoted plain-text excerpt (only for in-window messages)


@dataclass
class Thread:
    source: Source
    package: str
    subject: str
    link: str
    first: datetime
    last: datetime
    bug: int | None = None
    root: str = ""  # thread root Message-ID (lists)
    authors: list[str] = field(default_factory=list)
    messages: list[Msg] = field(default_factory=list)
    count: int = 0  # messages inside the window
    total: int = 0  # all messages of the thread, first message included
    reporter: str = ""  # who started the thread / submitted the bug
    tags: str = ""  # "(*i*, Uu)" severity + tag letters (bugs only)
    extra: str = ""  # " (merged with ...) (forwarded: ...)" (bugs only)
    comment: str = ""  # Markdown, empty = nothing worth saying


def clean_msgid(raw: str) -> str:
    return GMANE_MANGLE_RE.sub("", raw.strip().strip("<>").strip())


def normalize_subject(subject: str) -> str:
    subject = re.sub(r"\s+", " ", subject).strip()
    while True:
        new = REPLY_PREFIX_RE.sub("", subject)
        if new == subject:
            return subject
        subject = new


def author_name(from_hdr: str) -> str:
    name, addr = parseaddr(from_hdr)
    return name or addr.split("@")[0] or "unknown"


def sender_addr(from_hdr: str) -> str:
    return parseaddr(from_hdr)[1]


def strip_quotes(text: str, limit: int = 4000) -> str:
    """Drop quoted lines, 'wrote:' attributions and the signature."""
    text = text.split("\n-- \n", 1)[0]
    keep = [
        ln
        for ln in text.splitlines()
        if not ln.lstrip().startswith(">") and not re.match(r"^On .* wrote:\s*$", ln)
    ]
    return "\n".join(keep)[:limit]


def plain_body(msg: email.message.EmailMessage) -> str:
    try:
        part = msg.get_body(preferencelist=("plain",))
        return strip_quotes(part.get_content()) if part else ""
    except (LookupError, ValueError, AttributeError, KeyError):
        return ""


def load_mbox(
    path: Path, start: datetime, end: datetime
) -> tuple[list[tuple[Msg, str]], datetime | None, dict[str, int], dict[str, str]]:
    """Scan one mbox.

    Returns ([(Msg, sender address)] inside [start, end), oldest article date,
    messages per thread root up to `end`, author per Message-ID).
    """
    box = mailbox.mbox(
        str(path),
        factory=lambda f: email.message_from_binary_file(f, policy=email.policy.default),
        create=False,
    )
    out: list[tuple[Msg, str]] = []
    oldest: datetime | None = None
    sizes: dict[str, int] = {}
    starters: dict[str, str] = {}
    for idx, msg in enumerate(box):
        try:
            dt = parsedate_to_datetime(str(msg["date"]))
            if dt.tzinfo is None:
                dt = dt.replace(tzinfo=timezone.utc)
            dt = dt.astimezone(timezone.utc)
            if oldest is None or dt < oldest:
                oldest = dt
            mid = clean_msgid(str(msg["message-id"])) if msg["message-id"] else f"nomid-{idx}"
            refs = MSGID_RE.findall(str(msg["references"] or "")) or MSGID_RE.findall(
                str(msg["in-reply-to"] or "")
            )
            root = clean_msgid(refs[0]) if refs else mid
            raw_subject = str(msg["subject"] or "(no subject)")
            subject = normalize_subject(raw_subject)
            is_reply = bool(REPLY_PREFIX_RE.match(raw_subject))
            from_hdr = str(msg["from"] or "")
            if dt < end:
                sizes[root] = sizes.get(root, 0) + 1
                starters[mid] = author_name(from_hdr)
            if not (start <= dt < end):
                continue
            body = plain_body(msg)
        except (TypeError, ValueError, IndexError, AttributeError):
            continue  # unparsable date / headers
        out.append(
            (Msg(mid, root, subject, author_name(from_hdr), dt, is_reply, body),
             sender_addr(from_hdr))
        )
    return out, oldest, sizes, starters


def classify(source: Source, subject: str) -> str:
    if source.package:
        return source.package
    for pkg, rx in PACKAGE_SUBJECT_RES.items():
        if rx.search(subject):
            return pkg
    return "linux"


def collect(
    source: Source, path: Path, start: datetime, end: datetime, include_bots: bool
) -> list[Thread]:
    """Group the messages of one mbox inside [start, end) into threads."""
    loaded, oldest, sizes, starters = load_mbox(path, start, end)
    if oldest and oldest > start:
        print(
            f"[WARN] {path.name}: oldest article is {oldest:%Y-%m-%d}, after window "
            f"start {start:%Y-%m-%d}; results may be incomplete "
            f"(re-pull with a bigger --limit or --reget).",
            file=sys.stderr,
        )

    msgs = sorted(loaded, key=lambda x: x[0].date)
    threads: dict[str, Thread] = {}
    matched: set[str] = set()  # thread keys passing the subject filter

    for msg, sender in msgs:
        if source.label == "debian-kernel" and not include_bots:
            if NOISE_SUBJECT_RE.search(msg.subject) or NOISE_SENDER_RE.search(sender):
                continue

        bug = BUG_RE.search(msg.subject)
        key = f"bug{bug.group(1)}" if bug else msg.root
        if source.subject_filter is None or source.subject_filter.search(msg.subject):
            matched.add(key)

        th = threads.get(key)
        if th is None:
            link = (
                BTS_URL + bug.group(1)
                if bug
                else source.link_base + urllib.parse.quote(msg.mid, safe="@")
            )
            th = threads[key] = Thread(
                source=source,
                package=classify(source, msg.subject),
                subject=msg.subject,
                link=link,
                first=msg.date,
                last=msg.date,
                bug=int(bug.group(1)) if bug else None,
                root=msg.root,
            )
        th.messages.append(msg)
        th.count += 1
        th.last = max(th.last, msg.date)
        if msg.author not in th.authors:
            th.authors.append(msg.author)

    result = [t for k, t in threads.items() if k in matched]
    for t in result:
        t.total = max(sizes.get(t.root, 0), t.count)
        t.reporter = starters.get(t.root, "")
    return result


# --------------------------------------------------------------------------
# Comments: plain keyword parsing (no AI).  Mirrors the manual routine:
#   fetch the bug page -> who replied last -> which tags -> short summary.
# Nothing concrete to say (no reply, vague) -> empty comment.
# --------------------------------------------------------------------------

RC_SEVERITIES = {"critical", "grave", "serious"}

# BTS tag -> wording; every matching tag is listed, in this order.
TAG_PHRASES = [
    ("pending", "fix pending upload"),
    ("fixed-upstream", "fixed upstream"),
    ("patch", "patch available"),
    ("confirmed", "confirmed"),
    ("unreproducible", "unreproducible"),
    ("wontfix", "won't fix"),
    ("security", "security related"),
    ("upstream", "upstream issue"),
]

# Keywords looked up in the top of the last (unquoted) reply only.
HINT_RES = [
    ("regression", re.compile(r"\bregress", re.IGNORECASE)),
    ("bisect", re.compile(r"\bbisect", re.IGNORECASE)),
    ("revert", re.compile(r"\brevert", re.IGNORECASE)),
    ("backport", re.compile(r"\b(back-?port|cherry-?pick)", re.IGNORECASE)),
    ("upstream commit", re.compile(r"\bcommit [0-9a-f]{8,}", re.IGNORECASE)),
    ("duplicate", re.compile(r"\b(duplicate|dup of|same as #\d+)", re.IGNORECASE)),
    ("test request", re.compile(r"\b(please|can you|could you) (test|try)\b", re.IGNORECASE)),
    ("CVE", re.compile(r"\bCVE-\d{4}-\d+")),
]

# Mailing-list (non-BTS) thread state words, matched in the top of replies.
APPLIED_RE = re.compile(r"\b(applied|queued|merged|committed|pushed out)\b", re.IGNORECASE)
REJECT_RE = re.compile(r"\bNAK\b|\bnacked\b|\brejected\b|won'?t (be )?(apply|applied|fix)", re.IGNORECASE)
REVIEWED_RE = re.compile(r"\b(Reviewed|Acked|Tested)-by:|\bLGTM\b")
PATCH_RE = re.compile(r"\[(RFC )?PATCH", re.IGNORECASE)
ANNOUNCE_RE = re.compile(r"^(Uploading|ANNOUNCE)\b|\breleased\b", re.IGNORECASE)

BTS_CACHE_TTL = 3600  # seconds


@dataclass
class BugReply:
    name: str
    addr: str
    date: datetime | None
    text: str


@dataclass
class BugInfo:
    reporter: str = ""  # lower-case address
    reporter_name: str = ""
    severity: str = ""
    tags: list[str] = field(default_factory=list)
    fixed: list[str] = field(default_factory=list)
    done_by: str = ""
    forwarded: list[str] = field(default_factory=list)
    merged: list[str] = field(default_factory=list)
    messages: list[BugReply] = field(default_factory=list)  # [0] is the report


def _plain(fragment: str) -> str:
    return html.unescape(re.sub(r"<[^>]+>", "", fragment)).strip()


def parse_bug_html(page: str) -> BugInfo:
    """Extract state and message list from a bugs.debian.org/N page."""
    head = page.split("<hr>", 1)[0]

    def head_field(rx: str) -> str:
        m = re.search(rx, head, re.DOTALL)
        return _plain(m.group(1)) if m else ""

    info = BugInfo(
        reporter=parseaddr(head_field(r"Reported by:\s*(.*?)</p>"))[1].lower(),
        reporter_name=author_name(head_field(r"Reported by:\s*(.*?)</p>")),
        severity=head_field(r"Severity:\s*(.*?)</p>").lower(),
        tags=[t.strip() for t in head_field(r"<p>Tags:\s*(.*?)</p>").split(",") if t.strip()],
        fixed=[v.strip().split("/")[-1]
               for v in head_field(r"Fixed in versions?\s*(.*?)</p>").split(",") if v.strip()],
        done_by=head_field(r"<strong>Done:</strong>\s*(.*?)</p>"),
        merged=re.findall(r"\d+", head_field(r"Merged with\s*(.*?)</p>")),
    )
    fwd = re.search(r"Forwarded to(.*?)</p>", head, re.DOTALL)
    if fwd:
        info.forwarded = [html.unescape(u) for u in re.findall(r'href="([^"]+)"', fwd.group(1))]

    for chunk in page.split("<hr>")[1:]:
        if not re.search(r"Message #\d+(?:</a>)? received at", chunk):
            continue  # info / control-command blocks
        frm = re.search(r'headerfield">From:</span>\s*(.*?)</div>', chunk, re.DOTALL)
        dat = re.search(r'headerfield">Date:</span>\s*(.*?)</div>', chunk, re.DOTALL)
        bodies = re.findall(r'<pre class="message">(.*?)</pre>', chunk, re.DOTALL)
        from_hdr = _plain(frm.group(1)) if frm else ""
        when = None
        if dat:
            try:
                when = parsedate_to_datetime(_plain(dat.group(1))).astimezone(timezone.utc)
            except (TypeError, ValueError):
                when = None
        text = strip_quotes(_plain("\n".join(bodies)))
        info.messages.append(
            BugReply(author_name(from_hdr), sender_addr(from_hdr).lower(), when, text)
        )
    return info


def fetch_bug(number: int, cache_dir: Path | None) -> str | None:
    """Download https://bugs.debian.org/N (cached for an hour)."""
    cache = cache_dir / f"{number}.html" if cache_dir else None
    if cache and cache.exists() and time_mod.time() - cache.stat().st_mtime < BTS_CACHE_TTL:
        return cache.read_text(encoding="utf-8")
    req = urllib.request.Request(
        f"{BTS_URL}{number}", headers={"User-Agent": "debian-kernel-meet/2.0"}
    )
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            page = resp.read().decode("utf-8", errors="replace")
    except (urllib.error.URLError, TimeoutError, OSError) as exc:
        print(f"[WARN] bug #{number}: fetch failed: {exc}", file=sys.stderr)
        return None
    if cache:
        cache.parent.mkdir(parents=True, exist_ok=True)
        cache.write_text(page, encoding="utf-8")
    return page


# Severity / tag markers as used in the wiki bug tables, e.g. "(*i*, Uu)".
SEVERITY_MARK = {
    "critical": "**C**", "grave": "**G**", "serious": "*S*", "important": "*i*",
    "normal": "n", "minor": "m", "wishlist": "w",
}
# Verified against the BTS tags of bugs listed in earlier meeting pages.
TAG_LETTERS = [
    ("fixed-upstream", "U"), ("moreinfo", "M"), ("patch", "+"),
    ("unreproducible", "R"), ("upstream", "u"),
]


def tag_marker(info: BugInfo) -> str:
    sev = SEVERITY_MARK.get(info.severity, info.severity)
    letters = "".join(c for t, c in TAG_LETTERS if t in info.tags)
    return f"({sev}, {letters})"


def forward_label(url: str) -> str:
    """lore list name, salsa 'project!N', else the host name."""
    u = urllib.parse.urlparse(url)
    if u.netloc == "lore.kernel.org":
        first = u.path.strip("/").split("/")[0]
        return first if re.fullmatch(r"[a-z0-9-]+", first) and first not in ("r", "all") else u.netloc
    if u.netloc == "salsa.debian.org":
        m = re.match(r"/(?:.+/)?([^/]+)/-/(merge_requests|issues)/(\d+)", u.path)
        if m:
            return f"{m.group(1)}{'!' if m.group(2) == 'merge_requests' else '#'}{m.group(3)}"
    return u.netloc


def bug_extra(info: BugInfo) -> str:
    out = ""
    if info.merged:
        out += " (merged with " + ", ".join(
            f"[\\#{n}]({BTS_URL}{n})" for n in info.merged
        ) + ")"
    if info.forwarded:
        out += " (forwarded: " + ", ".join(
            f"[{md_escape(forward_label(u))}]({u})" for u in info.forwarded
        ) + ")"
    return out


def join_sentences(parts: list[str]) -> str:
    parts = [p[0].upper() + p[1:] for p in parts if p]
    return ". ".join(parts) + "." if parts else ""


def hints_from(last_reply_text: str) -> str:
    """Keywords in the top of the most recent reply (older text is mostly noise)."""
    blob = "\n".join(last_reply_text.splitlines()[:30])
    found = [label for label, rx in HINT_RES if rx.search(blob)]
    return f"Mentions: {', '.join(found)}" if found else ""


def bug_comment(info: BugInfo) -> str:
    replies = info.messages[1:]
    last = replies[-1] if replies else None
    by_reporter = bool(last and info.reporter and last.addr == info.reporter)
    only_reporter = bool(replies) and all(r.addr == info.reporter for r in replies)
    tags = set(info.tags)
    out: list[str] = []

    if info.done_by:
        s = f"Closed by {md_escape(parseaddr(info.done_by)[0] or info.done_by)}"
        if info.fixed:
            s += f", fixed in {md_escape(', '.join(info.fixed))}"
        out.append(s)
    else:
        if "moreinfo" in tags:
            out.append(
                "Submitter answered the moreinfo request, needs follow-up"
                if by_reporter
                else "Waiting for submitter"
            )
        phrases = [
            p for t, p in TAG_PHRASES
            if t in tags and not (t == "upstream" and info.forwarded)
        ]
        if phrases:
            joined = ", ".join(phrases)
            out.append(joined[0].upper() + joined[1:])
        if not replies and info.severity in RC_SEVERITIES:
            out.append("No reply yet")

    if last:
        when = f"{last.date:%Y-%m-%d}" if last.date else "?"
        s = f"Last reply: {md_escape(last.name)}{' (submitter)' if by_reporter else ''}, {when}"
        if only_reporter and not info.done_by:
            s += "; no team reply yet"
        out.append(s)
        hint = hints_from(last.text)
        if hint:
            out.append(hint)

    return join_sentences(out)


def list_comment(th: Thread) -> str:
    """Comment for a thread that has no BTS page (patches, announcements...)."""
    msgs = th.messages
    replies = [m for m in msgs if m.is_reply]
    out: list[str] = []

    if replies:
        tops = ["\n".join(m.body.strip().splitlines()[:8]) for m in replies]
        states = []
        if any(APPLIED_RE.search(t) for t in tops):
            states.append("applied/merged mentioned")
        if any(REJECT_RE.search(t) for t in tops):
            states.append("NAK/rejected mentioned")
        if any(REVIEWED_RE.search(t) for t in tops):
            states.append("reviewed/acked/tested")
        if states:
            joined = ", ".join(states)
            out.append(joined[0].upper() + joined[1:])
        last = msgs[-1]
        out.append(f"Last reply: {md_escape(last.author)}, {last.date:%Y-%m-%d}")
        hint = hints_from(last.body)
        if hint:
            out.append(hint)
    elif PATCH_RE.search(th.subject):
        out.append("Patch posted, no review yet")
    elif ANNOUNCE_RE.search(th.subject):
        out.append("Announcement")

    return join_sentences(out)


def annotate(
    threads: list[Thread], use_bts: bool, cache_dir: Path | None,
    start: datetime, end: datetime,
) -> None:
    """Fill Thread.comment for every thread."""
    bug_threads = [t for t in threads if t.bug and use_bts]
    if bug_threads:
        print(f"[bts] fetching {len(bug_threads)} bug page(s)...", file=sys.stderr)
    with ThreadPoolExecutor(max_workers=4) as pool:
        pages = list(pool.map(lambda t: fetch_bug(t.bug, cache_dir), bug_threads))
    from_bts = set()
    for t, page in zip(bug_threads, pages):
        if page is None:
            continue
        try:
            info = parse_bug_html(page)
            t.comment = bug_comment(info)
            t.tags = tag_marker(info)
            t.extra = bug_extra(info)
            t.reporter = info.reporter_name
            t.total = len(info.messages)  # report + every reply
            t.count = sum(1 for m in info.messages if m.date and start <= m.date < end)
            # one entry per address, so "ole.carlsen" and "Ole Carlsen" are one person
            by_addr = {m.addr: m.name for m in reversed(info.messages)}
            t.authors = [
                n for a, n in dict(
                    (m.addr, by_addr[m.addr]) for m in info.messages
                ).items() if a != info.reporter
            ]
        except (ValueError, AttributeError, IndexError) as exc:
            print(f"[WARN] bug #{t.bug}: cannot parse page: {exc}", file=sys.stderr)
            continue
        from_bts.add(id(t))
    for t in threads:
        if id(t) not in from_bts:
            t.comment = list_comment(t)


def md_escape(text: str) -> str:
    return re.sub(r"([\\|\[\]_*`<>])", r"\\\1", text).strip()


def render(
    grouped: dict[str, list[Thread]], start: date, end: date, reverse: bool = False
) -> str:
    lines = [
        "### Mailing list activity",
        "",
        f"Threads from {start:%Y-%m-%d} to {end:%Y-%m-%d} (UTC) on "
        + ", ".join(f"`{s.group}`" for s in SOURCES)
        + ".",
        "",
    ]
    for pkg in PACKAGES:
        lines += [f"#### {pkg}", ""]
        items = sorted(grouped.get(pkg, []), key=lambda t: t.last, reverse=not reverse)
        if not items:
            lines += ["_No threads in this period._", ""]
            continue
        lines += [
            "|Last activity|Source|Thread|Tags|Msgs|Reporter|Participants|Comment|",
            "|-|-|-|-|-|-|-|-|",
        ]
        for t in items:
            others = [a for a in t.authors if a != t.reporter]
            people = [md_escape(a) for a in others[:3]]
            if len(others) > 3:
                people.append(f"+{len(others) - 3}")
            total = max(t.total, t.count)
            msgs = f"{total} ({t.count} new)" if 0 < t.count < total else str(total)
            lines.append(
                f"|{t.last:%Y-%m-%d}|{t.source.label}"
                f"|[{md_escape(t.subject)}]({t.link}){t.extra}"
                f"|{t.tags}|{msgs}|{md_escape(t.reporter)}|{', '.join(people)}|{t.comment}|"
            )
        lines.append("")
    return "\n".join(lines).rstrip()


def sync(directory: Path) -> None:
    """Run nntp-pull for every source (incremental after the first pull)."""
    env = dict(os.environ, PYTHONWARNINGS="ignore")
    for s in SOURCES:
        cmd = ["nntp-pull", f"--server={NNTP_SERVER}", f"--limit={s.limit}", s.group]
        print(f"[sync] {' '.join(cmd)}", file=sys.stderr)
        try:
            rc = subprocess.run(cmd, cwd=directory, env=env).returncode
        except FileNotFoundError:
            sys.exit("nntp-pull not found (apt install sinntp)")
        if rc != 0:
            print(f"[WARN] nntp-pull failed for {s.group} (exit {rc})", file=sys.stderr)


def parse_date(value: str) -> date:
    for fmt in ("%Y%m%d", "%Y-%m-%d"):
        try:
            return datetime.strptime(value, fmt).date()
        except ValueError:
            pass
    raise argparse.ArgumentTypeError(f"invalid date {value!r}, expected YYYYMMDD")


def main() -> None:
    p = argparse.ArgumentParser(
        description="Generate Debian Kernel Team meeting agenda mailing-list notes."
    )
    p.add_argument("--to", dest="to", type=parse_date, default=None,
                   help="last day, inclusive, YYYYMMDD (default: today; use the meeting date)")
    p.add_argument("--from", dest="from_", type=parse_date, default=None,
                   help="first day, inclusive, YYYYMMDD (default: 7 days before --to)")
    p.add_argument("--dir", type=Path, default=Path(__file__).resolve().parent,
                   help="directory holding the mbox files (default: script directory)")
    p.add_argument("--sync", action="store_true",
                   help="run nntp-pull for all groups before generating")
    p.add_argument("-r", "--reverse", action="store_true",
                   help="order threads old to new by last activity (default: new to old)")
    p.add_argument("--include-bots", action="store_true",
                   help="keep automated BTS/DAK mail on debian-kernel")
    p.add_argument("--no-bts", action="store_true",
                   help="do not fetch bug pages; comments for bugs then come from the list only")
    p.add_argument("--cache-dir", type=Path,
                   default=Path.home() / ".cache" / "debian-kernel-meet",
                   help="cache for fetched bug pages, valid 1h (default: %(default)s)")
    p.add_argument("-o", "--output", default="-", help="output file (default: stdout)")
    args = p.parse_args()

    to_day = args.to or date.today()
    from_day = args.from_ or (to_day - timedelta(days=7))
    if from_day > to_day:
        p.error("--from must not be after --to")
    if to_day.weekday() != 2:
        print(f"[note] {to_day:%Y-%m-%d} is a {to_day:%A}, not a Wednesday.", file=sys.stderr)

    start = datetime.combine(from_day, time.min, tzinfo=timezone.utc)
    end = datetime.combine(to_day + timedelta(days=1), time.min, tzinfo=timezone.utc)

    if args.sync:
        sync(args.dir)

    grouped: dict[str, list[Thread]] = {pkg: [] for pkg in PACKAGES}
    all_threads: list[Thread] = []
    for s in SOURCES:
        path = args.dir / s.group
        if not path.exists():
            print(f"[WARN] {path} missing, skipping (use --sync)", file=sys.stderr)
            continue
        all_threads += collect(s, path, start, end, args.include_bots)

    annotate(all_threads, use_bts=not args.no_bts, cache_dir=args.cache_dir,
             start=start, end=end)
    for t in all_threads:
        grouped[t.package].append(t)

    md = render(grouped, from_day, to_day, reverse=args.reverse)
    if args.output == "-":
        print(md)
    else:
        Path(args.output).write_text(md + "\n", encoding="utf-8")
        print(f"Wrote {args.output}", file=sys.stderr)


if __name__ == "__main__":
    main()

Reply via email to