feat(ci): kvb-ci-track keeps one fingerprinted list of CI failures until each is acked

New skill kvb-ci-track: track.py add/poll/wait/ack/known follows workflow runs, PR checks, code-scanning and secret alerts and issues, clusters each failing job by its failing line (ci_failures.failing, now split from signature without a change in behaviour), fingerprints every cluster, and prints only clusters nobody acked yet. A failing line that matches a hotfix register signature carries that hotfix as a hint. kvb-ci-observe and kvb-ci-triage poll through it instead of re-reading every log; kvb-ci-artifacts names failing().

Untrusted text never reaches the terminal raw: printable() drops every character str.isprintable() refuses (escape sequences, zero-width characters), a tab or other whitespace control becoming a space. masked() runs it before hiding URL credentials, assigned secrets and 24-character tokens, and report() cleans every cell, so a log line, title or job name cannot send a terminal sequence, forge a tab-separated cell or dodge an ack with an invisible character.

Tests: tests/test_ci_track.py, including test_control_and_zero_width_characters_never_reach_a_cell. Written, not run: the full suite runs once on master after all bundles (operator order). Both new expectations checked inline; ci_failures.signature() proven identical on every path, the empty-log sentinel included.

Security: MEDUSA over the staged tree on master: 100, 8 files covered, 0 findings. 6 low findings accepted as false positives after a skeptic review and the operator's accept on 2026-11-22: MP-SCAN-1781 at track.py 516, 557, 571, 572 and MP-SCAN-1878 at 557, 571, all on the word 'ack' in the CLI's own subcommand and messages.

🎯 Fix: 90 %
💥 Break: 4 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 86
🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 %

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-22 22:09:28 +00:00
1 parent 144dbf1941
commit f0d5eafcac
8 files changed
+946 -29

No files matched your search

+6
View File
@@ -47,6 +47,7 @@ flowchart LR
ci --> ci_triage[kvb-ci-triage]
ci --> ci_artifacts[kvb-ci-artifacts]
ci --> ci_observe[kvb-ci-observe]
ci --> ci_track[kvb-ci-track]
git --> git_commit_next[kvb-git-commit-next]
git --> git_commit_no_verify[kvb-git-commit-no-verify]
git --> git_merge_fix[kvb-git-merge-fix]
@@ -160,6 +161,7 @@ flowchart LR
triage[kvb-ci-triage]
ci_artifacts[kvb-ci-artifacts]
observe[kvb-ci-observe]
track[kvb-ci-track]
end
subgraph cat_git [git]
commit_next[kvb-git-commit-next]
@@ -339,6 +341,10 @@ flowchart LR
observe --> triage
observe --> ci_artifacts
observe --> track
triage --> track
track --> ci_artifacts
track --> hotfix
triage --> ci_artifacts
triage --> democracy
triage --> dialectic
+2 -2
View File
@@ -1,8 +1,8 @@
---
name: kvb-ci-artifacts
description: >
Pull failed CI job logs (also mid-run), clustered by error line, and
cause-holding artifacts. Trigger to explain a CI failure, and from triage.
Pull failed CI job logs, clustered by error line, and cause-holding
artifacts. Trigger to explain a CI failure.
---
A job log tells you what broke. An artifact tells you why.
+12 -3
View File
@@ -92,7 +92,12 @@ def is_lint(lines: list[tuple[str, str]], index: int) -> bool:
return bool(LINT_CODE.match(line) and LINT_ARROW.match(following))
def signature(text: str) -> str:
def failing(text: str) -> str:
"""Returns:
The line that ended the job, as the log holds it: the last annotation,
else the last fatal line after its task, lint finding or error word,
else the last kept line.
"""
lines = output_lines(text)
tiers = (
(lambda i: ANNOTATION.search(lines[i][1]), False),
@@ -105,8 +110,12 @@ def signature(text: str) -> str:
if matches(index):
task, line = lines[index]
found = ANNOTATION.sub("", line).strip()
return normalise(f"{task} {found}" if with_task and task else found)
return normalise(lines[-1][1]) if lines else "<empty log>"
return f"{task} {found}" if with_task and task else found
return lines[-1][1] if lines else "<empty log>"
def signature(text: str) -> str:
return normalise(failing(text))
def cluster(jobs: list[tuple[str, str]]) -> dict[str, list[str]]:
+26 -20
View File
@@ -1,8 +1,8 @@
---
name: kvb-ci-observe
description: >
Watch a CI run, pipeline, build or log on a cadence, triaging and fixing
new failures. Trigger when asked to keep monitoring.
Watch a CI run, pipeline, build or log, triaging and fixing new failures.
Trigger when asked to keep monitoring.
---
Keep a target under watch and act only when it degrades: the loop watches,
@@ -19,37 +19,43 @@ re-triages solved failures.
## The loop
Drive it with `/loop` in dynamic mode (no fixed interval unless the operator
gave one): after each observation, schedule the next wake-up and pass this
skill's prompt back unchanged.
A GitHub Actions run, a pull request's checks, scanning alerts and issues
run on the `kvb-ci-track` skill: `track.py add` the target, then
`track.py wait` as a background task; its end is the wake-up and its lines
are the new clusters, already diffed against what any agent saw or acked.
Any other target (another CI system, a build, a log file) runs on `/loop`
in dynamic mode (no fixed interval unless the operator gave one): after each
observation, schedule the next wake-up and pass this skill's prompt back
unchanged.
1. **Poll the target**: its job list, check conclusions or log tail; for a
GitHub Actions run, the `kvb-ci-artifacts` skill's `ci_failures.py <run>`.
Enumerate failures as the `kvb-ci-triage` skill's step 1 does: failure,
cancelled, timed-out; a downstream aggregate that fails only because an
upstream did is not its own failure.
1. **Poll the target**: the lines `wait` printed; elsewhere its job list,
check conclusions or log tail. Enumerate failures as the `kvb-ci-triage`
skill's step 1 does: failure, cancelled, timed-out; a downstream
aggregate that fails only because an upstream did is not its own failure.
2. **Diff against the baseline.** A failure is new only if it is neither in
the baseline nor triaged this session. Nothing new: log one short line
("still green" / "N known failures, no change") and reschedule.
the baseline nor triaged this session; `track.py` keeps that baseline
for its targets. Nothing new: log one short line ("still green" / "N
known failures, no change") and wait again.
3. **Triage each new failure** with the `kvb-ci-triage` skill on the new set
only; it applies `kvb-think-dialectic` per failing job to a ~99% root
cause and a real fix. Never mask (no retry-until-pass, disabled check or
soft skip). A new failure and its verdict go to peers by radio, never with
a wake: `${CLAUDE_SKILL_DIR}/../kvb-org-radio/scripts/radio.py post
"<target>: <job> <failing line> -> <verdict>"`. Fold each newly fixed
failure into the baseline.
4. **Reschedule** by what you wait on: an active run that changes every few
minutes gets a check matched to its cadence, a quiet or long-running
target a long fallback (1200s+). Stop once the target reaches a terminal
state (run completed, pipeline finished) AND every failure it produced
failure into the baseline: `track.py ack <fingerprint> --verdict
'<verdict>'`.
4. **Wait again** by what you wait on: an active run that changes every few
minutes gets an interval matched to its cadence, a quiet or long-running
target a long one (1200s+). Stop once the target reaches a terminal
state (`wait` exit 20, a pipeline finished) AND every failure it produced
has a verified fix.
## Rules
- The loop is a fallback timer, not a busy-wait: for tracked work the
harness reports (a background task, a spawned agent), wait for that
notification; reserve the timed wake-up for state the harness cannot see
(a remote CI run, a deploy queue).
harness reports (a background task, a spawned agent, `track.py wait`),
wait for that notification; reserve the timed wake-up for state neither
the harness nor `track.py` can see (another CI system, a deploy queue).
- Executed evidence beats reasoning: read the failing log line and the
artifact, not the job title.
- One baseline, updated in place: dedup every observation against all
+57
View File
@@ -0,0 +1,57 @@
---
name: kvb-ci-track
description: >
Track CI runs, PR checks, alerts, issues; wake on new failures.
---
`${CLAUDE_SKILL_DIR}/scripts/track.py` keeps one JSON file per target in the
shared council directory, so every agent sees what was already reported and
triaged. Its docstring holds the full contract.
```bash
track.py add run <owner/repo> <run id> [--rules <file>]
track.py add pr <owner/repo> <number> [--rules <file>]
track.py add alerts <owner/repo> --codeql --secrets
track.py add issues <owner/repo> [--label <name> ...]
track.py poll <target> [<target> ...]
track.py wait <target> [<target> ...] --interval <s> --timeout <s>
track.py ack <fingerprint> --verdict '<root cause or fix>'
```
## Watch
1. `add` prints the target id. Pass `--rules` the repository's own rules
file when it has one: failing-line regexes such as Ansible's `fatal:` with
its last `TASK`, or Playwright's `✘ <spec>:<line>:<col>` with its first
`Error:`.
2. Start `wait` as a background task (Claude Code: `run_in_background`;
elsewhere the runtime's equivalent), the interval matched to how fast the
target changes: about 300 s for a running matrix, 1800 s for alerts or
issues. Its end is the wake-up; never `/loop`, cron or a shell loop over
`poll`.
3. On its end, read the exit code:
- **10**: each printed line is one new cluster: fingerprint, target,
label, job count, failing line and any matching hotfix. Triage it with
the `kvb-ci-triage` skill, then start `wait` again.
- **20**: every target terminal, every cluster acked: the watch is done.
- **30**: every target terminal, a cluster still unacked: finish its
triage and ack it.
- **3**: gh failed (auth, network, a broken rules file); the reason is on
stderr. **0**: timeout, nothing new: start `wait` again.
## Ack
Once a cluster has its verdict (fixed, flake proven transient, fixed by a
later commit), `ack` it. The ack silences that fingerprint in every target,
so the same failure in the next run stays quiet. Never ack a cluster just to
quiet it; an ack without a verdict is refused.
## Rules
- One line per new cluster; alerts carry the rule id or secret type and
path:line, never a secret value. Every line is masked, but treat it like a
log line: quote it, never widen it with the raw log.
- The failing line is a lead. The log and artifacts (`kvb-ci-artifacts`)
stay the evidence.
- A hotfix hint lists every repository's hotfixes; confirm it with
`hotfix.py match --repo <worktree>` before you sync.
+587
View File
@@ -0,0 +1,587 @@
#!/usr/bin/env python3
"""Track CI runs, pull request checks, scanning alerts and issues; report only what is new.
Environment:
AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the council directory the
kvb-org-organize councilroot.py resolves; each target is one JSON file
in its track/ directory, the acks are track/acks.json.
Args:
add run <owner/repo> <run id> [--rules <file>]: one Actions run.
add pr <owner/repo> <number> [--rules <file>]: every Actions run of the
pull request's current head commit.
add alerts <owner/repo> [--codeql] [--secrets]: the open code scanning
and secret scanning alerts; at least one flag.
add issues <owner/repo> [--label <name> ...]: the open issues carrying
every label given.
add prints the target id; adding a tracked target again keeps its
clusters, sets the rules anew and polls it again after it ended.
--rules is a JSON file of the calling repository: {"job_name":
[<regex>, ...], "lines": [{"id": <text>, "match": <regex>, "pick":
"first"|"last", "context": <regex>, "side": "before"|"after"}, ...]}.
Each job_name regex is cut from a job name after the matrix list
" (...)"; the first lines rule whose match hits a kept output line
of ci_failures.py makes the failing line, joined with the nearest
context line on its side when one is given; without a hit
ci_failures.py's failing line stands. Every regex passes
kvb-git-hotfix's backtracking check.
poll <target> [<target> ...]: one pass over the targets.
wait <target> [<target> ...] --interval <s> --timeout <s>: poll every
interval seconds inside this process until a poll exits 10, 20 or
30, ERRORS polls in a row exit 3, or the next poll would start after
the timeout; run it as a background task, its end wakes the agent.
ack <fingerprint> --verdict <text>: silence a triaged cluster in every
target, as an Alertmanager silence does.
Output:
poll and wait print one line per cluster no earlier poll of the target
saw and no ack silences:
`<fingerprint>\\t<target>\\t<label>\\t<count>\\t<text>[\\t<hotfix> (<stage>)]`.
For a run or pull request the label is the job name without its variant
decorations, the count its failed jobs and the text the masked,
normalised failing line, followed by the first kvb-git-hotfix signature
that matches the masked line; for an alert the rule id or secret type
and path:line, never a secret value; for an issue `#<n>` and its masked
title. Logs are fetched with --allow-escape-sequences and never printed
whole; every cell keeps only printable characters, whitespace controls
becoming a space, so no log line, title or name sends a terminal
sequence, forges a cell or dodges an ack with invisible characters.
Errors go to stderr as `track: <target>: <message>`.
Exit codes:
0 nothing new; 10 new clusters printed; 20 every target terminal (the
run completed, the pull request closed or every run of its head
completed) and every cluster acked; 30 every target terminal, a cluster
not acked; 2 usage error, unknown target or fingerprint, bad rules
file; 3 a target failed (gh, its answer or its rules) and nothing new.
"""
from __future__ import annotations
import argparse
import contextlib
import fcntl
import functools
import hashlib
import importlib.util
import json
import os
import re
import subprocess
import sys
import time
from collections import Counter
from collections.abc import Callable, Iterator, Sequence
from pathlib import Path
from types import ModuleType
from typing import NamedTuple
SKILLS = Path(__file__).resolve().parents[2]
HOTFIX = SKILLS / "kvb-git-hotfix" / "scripts" / "hotfix.py"
NEW, TERMINAL, STUCK, USAGE, BROKEN = 10, 20, 30, 2, 3
ENDS = (NEW, TERMINAL, STUCK)
ERRORS = 3
ACKS = "acks.json"
NUMBERED = ("run", "pr")
ALERTS = ("codeql", "secrets")
PICKS = ("first", "last")
SIDES = ("before", "after")
TEXT = 200
LINE = 400
PAGE = "per_page=30"
ISSUES = "1000"
GONE = ("HTTP 404", "HTTP 410")
JOBS = ".jobs[] | {id, name, status, conclusion}"
RUNS = ".workflow_runs[] | {id, status}"
CODEQL = ".[] | {number, rule: .rule.id, path: .most_recent_instance.location.path, line: .most_recent_instance.location.start_line}"
SECRETS = ".[] | {number, type: .secret_type}"
LOCATION = ".[0].details | {path, line: .start_line}"
REPO = re.compile(r"[A-Za-z0-9._-]+/[A-Za-z0-9._-]+")
NUMBER = re.compile(r"[1-9][0-9]*")
SHA = re.compile(r"[0-9a-f]{40}")
FINGERPRINT = re.compile(r"[0-9a-f]{12}")
TARGET = re.compile(r"(?:run|pr|alerts|issues)-[A-Za-z0-9._+-]+")
SLUG = re.compile(r"[^A-Za-z0-9._-]+")
MATRIX = re.compile(r" \([^()]*\)")
URL_AUTH = re.compile(r"://[^/@\s]+@")
ASSIGNED = re.compile(r"""(?i)\b(password|passwd|token|secret|api[_-]?key)(["']?\s*[:=]\s*["']?)[^\s"',}]+""")
TOKEN = re.compile(r"[A-Za-z0-9_+=]{24,}")
LETTER = re.compile(r"[A-Za-z]")
DIGIT = re.compile(r"[0-9]")
def load(name: str, path: Path) -> ModuleType:
spec = importlib.util.spec_from_file_location(f"kvb_track_{name}", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
CI = load("ci_failures", SKILLS / "kvb-ci-artifacts" / "scripts" / "ci_failures.py")
COUNCIL = load("councilroot", SKILLS / "kvb-org-organize" / "scripts" / "councilroot.py")
@functools.cache
def hotfix() -> ModuleType:
return load("hotfix", HOTFIX)
class Failed(Exception):
"""Args:
message: the first stderr line of the gh call that failed.
"""
class Clients(NamedTuple):
"""Args:
gh: runs gh with the argv after `gh`; returns (exit code, stdout,
stderr).
hint: `<task> (<stage>)` of the first hotfix whose signature matches
a failing line, None without one.
"""
gh: Callable[[list[str]], tuple[int, str, str]]
hint: Callable[[str], str | None]
def spawn(command: list[str]) -> tuple[int, str, str]:
done = subprocess.run(command, capture_output=True, check=False)
return done.returncode, done.stdout.decode("utf-8", "replace"), done.stderr.decode("utf-8", "replace")
def gh(argv: list[str]) -> tuple[int, str, str]:
return spawn(["gh", *argv])
def hotfix_hint(line: str) -> str | None:
code, stdout, _ = spawn([sys.executable, "-I", str(HOTFIX), "match", "--line", line])
lines = stdout.splitlines()
cells = lines[0].split("\t") if lines else []
return f"{cells[0]} ({cells[1]})" if code == 0 and len(cells) > 1 else None
def out(clients: Clients, argv: list[str]) -> str:
code, stdout, stderr = clients.gh(argv)
if code:
messages = stderr.strip().splitlines()
raise Failed((messages[0] if messages else f"gh {argv[0]} exited {code}")[:TEXT])
return stdout
def rows(text: str) -> list[dict]:
return [json.loads(line) for line in text.splitlines() if line.strip()]
def hidden(match: re.Match) -> str:
word = match.group()
return "<token>" if LETTER.search(word) and DIGIT.search(word) else word
def printable(text: str) -> str:
"""Returns:
text with every character str.isprintable() refuses dropped (control
and format characters, zero-width ones included), a whitespace one
such as a tab becoming a space.
"""
return "".join(char if char.isprintable() else " " if char.isspace() else "" for char in text)
def masked(line: str) -> str:
"""Returns:
line, printable() first, with URL credentials, the value after a
password, token, secret or api key word and every run of 24 letters
and digits that holds both replaced.
"""
return TOKEN.sub(hidden, ASSIGNED.sub(r"\1\2<masked>", URL_AUTH.sub("://<auth>@", printable(line))))
def fingerprint(*parts: str) -> str:
return hashlib.sha256("\n".join(parts).encode("utf-8")).hexdigest()[:12]
def pattern(text: object, where: str) -> str:
if not isinstance(text, str) or not text:
raise ValueError(f"rules {where} must be a non-empty regex")
try:
re.compile(text)
except re.error as error:
raise ValueError(f"rules {where} {text!r}: {error}") from error
found = hotfix().risk(text)
if found is not None:
raise ValueError(f"rules {where} {text!r} {found}")
return text
def rule(entry: object, index: int) -> dict:
where = f"lines[{index}]"
if not isinstance(entry, dict) or not isinstance(entry.get("id"), str) or entry.get("pick") not in PICKS:
raise ValueError(f"rules {where} needs an id and a pick of {', '.join(PICKS)}")
pattern(entry.get("match"), f"{where}.match")
if ("context" in entry) != ("side" in entry) or ("side" in entry and entry["side"] not in SIDES):
raise ValueError(f"rules {where} needs context and a side of {', '.join(SIDES)} together")
if "context" in entry:
pattern(entry["context"], f"{where}.context")
return entry
def rules_of(path: str | None) -> dict:
"""Returns:
{job_name, lines} of the rules file at path, every entry checked;
both empty for None; ValueError naming what is wrong.
"""
if path is None:
return {"job_name": [], "lines": []}
try:
data = json.loads(Path(path).read_text(encoding="utf-8"))
except (OSError, ValueError) as error:
raise ValueError(f"rules {path}: {error}") from error
if not isinstance(data, dict) or not all(isinstance(data.get(key, []), list) for key in ("job_name", "lines")):
raise ValueError(f"rules {path} must be an object whose job_name and lines are lists")
names = [pattern(item, f"job_name[{index}]") for index, item in enumerate(data.get("job_name", []))]
return {"job_name": names, "lines": [rule(entry, index) for index, entry in enumerate(data.get("lines", []))]}
def flat(text: str) -> list[str]:
"""Returns:
The output_lines() of ci_failures.py as lines, each task's TASK line
before its first kept line.
"""
lines, last = [], None
for task, line in CI.output_lines(text):
if task and task != last:
lines.append(task)
last = task
lines.append(line)
return lines
def nearest(lines: list[str], index: int, entry: dict) -> str | None:
span = range(index - 1, -1, -1) if entry["side"] == "before" else range(index + 1, len(lines))
return next((lines[at] for at in span if re.search(entry["context"], lines[at])), None)
def ruled(lines: list[str], entry: dict) -> str | None:
hits = [index for index, line in enumerate(lines) if re.search(entry["match"], line)]
if not hits:
return None
index = hits[0] if entry["pick"] == "first" else hits[-1]
extra = nearest(lines, index, entry) if "context" in entry else None
if extra is None:
return lines[index]
return f"{extra} {lines[index]}" if entry["side"] == "before" else f"{lines[index]} {extra}"
def failing_line(text: str, rules: dict) -> str:
lines = flat(text)
for entry in rules["lines"]:
found = ruled(lines, entry)
if found is not None:
return found
return CI.failing(text)
def job_label(name: str, rules: dict) -> str:
label = MATRIX.sub("", name)
for cut in rules["job_name"]:
label = re.sub(cut, "", label)
return label.strip()
def job_line(clients: Clients, repo: str, job: dict, rules: dict) -> str:
if job["conclusion"] == "cancelled":
return "cancelled"
try:
log = out(clients, ["api", "--allow-escape-sequences", f"/repos/{repo}/actions/jobs/{int(job['id'])}/logs"])
except Failed as error:
if any(code in str(error) for code in GONE):
return "no log"
raise
return failing_line(log, rules)
def run_jobs(clients: Clients, state: dict, run_id: str, rules: dict) -> None:
"""Args:
clients: the gh and hotfix callables.
state: the target; every failed job of the run not yet in its jobs
is added there with fingerprint, label, text and masked line.
run_id: the Actions run.
rules: rules_of() the target's rules file.
"""
listing = out(clients, ["api", "--paginate", f"/repos/{state['repo']}/actions/runs/{run_id}/jobs?{PAGE}", "--jq", JOBS])
for job in rows(listing):
key = str(job["id"])
if key in state["jobs"] or job["status"] != "completed" or job["conclusion"] not in CI.FAILED:
continue
line = masked(job_line(clients, state["repo"], job, rules))[:LINE]
label = job_label(job["name"], rules)
text = CI.normalise(line)
state["jobs"][key] = {"fp": fingerprint(label, text), "label": label, "text": text, "line": line}
def scan_run(clients: Clients, state: dict) -> tuple[list[dict], bool]:
rules = rules_of(state["rules"])
meta = json.loads(out(clients, ["api", f"/repos/{state['repo']}/actions/runs/{state['ref']}"]))
run_jobs(clients, state, state["ref"], rules)
return list(state["jobs"].values()), meta["status"] == "completed"
def scan_pr(clients: Clients, state: dict) -> tuple[list[dict], bool]:
rules = rules_of(state["rules"])
pull = json.loads(out(clients, ["api", f"/repos/{state['repo']}/pulls/{state['ref']}"]))
head = pull["head"]["sha"]
if not SHA.fullmatch(head):
raise ValueError(f"pull request head {head!r} is no commit id")
runs = rows(out(clients, ["api", f"/repos/{state['repo']}/actions/runs?head_sha={head}&per_page=100", "--jq", RUNS]))
for item in runs:
run_jobs(clients, state, str(int(item["id"])), rules)
finished = pull["state"] == "closed" or (bool(runs) and all(item["status"] == "completed" for item in runs))
return list(state["jobs"].values()), finished
def place(item: dict) -> str:
path, line = item.get("path"), item.get("line")
if not path:
return "-"
return path if line is None else f"{path}:{line}"
def secret_alerts(clients: Clients, state: dict) -> list[dict]:
repo, found = state["repo"], []
for item in rows(out(clients, ["api", "--paginate", f"/repos/{repo}/secret-scanning/alerts?state=open&{PAGE}", "--jq", SECRETS])):
number = int(item["number"])
fp = fingerprint("secret", repo, str(number))
seen = state["clusters"].get(fp)
if seen is None:
where = out(clients, ["api", f"/repos/{repo}/secret-scanning/alerts/{number}/locations", "--jq", LOCATION]).strip()
seen = {"label": f"secret {item['type']}", "text": place(json.loads(where)) if where else "-"}
found.append({"fp": fp, "label": seen["label"], "text": seen["text"], "line": None})
return found
def scan_alerts(clients: Clients, state: dict) -> tuple[list[dict], bool]:
repo, found = state["repo"], []
if "codeql" in state["flags"]:
listing = out(clients, ["api", "--paginate", f"/repos/{repo}/code-scanning/alerts?state=open&{PAGE}", "--jq", CODEQL])
found += [
{"fp": fingerprint("codeql", repo, str(int(item["number"]))), "label": f"codeql {item['rule']}", "text": place(item), "line": None}
for item in rows(listing)
]
if "secrets" in state["flags"]:
found += secret_alerts(clients, state)
return found, False
def scan_issues(clients: Clients, state: dict) -> tuple[list[dict], bool]:
argv = ["issue", "list", "--repo", state["repo"], "--state", "open", "--limit", ISSUES, "--json", "number,title"]
for label in state["flags"]:
argv += ["--label", label]
found = [
{"fp": fingerprint("issue", state["repo"], str(int(item["number"]))), "label": f"#{int(item['number'])}", "text": masked(item["title"])[:TEXT], "line": None}
for item in json.loads(out(clients, argv))
]
return found, False
SCANS = {"run": scan_run, "pr": scan_pr, "alerts": scan_alerts, "issues": scan_issues}
def report(clients: Clients, target: str, finding: dict, count: int) -> str:
cells = [finding["fp"], target, finding["label"], str(count), finding["text"]]
hint = None if finding["line"] is None else clients.hint(finding["line"])
return "\t".join(printable(cell) for cell in (cells if hint is None else [*cells, hint]))
def settled(state: dict, acks: dict) -> bool:
return state["terminal"] and all(fp in acks for fp in state["clusters"])
def poll_target(clients: Clients, state: dict, acks: dict) -> list[str]:
"""Returns:
The report() line of every cluster state had not seen that no ack
silences; state takes every cluster with its current count and
whether the target is terminal.
"""
findings, terminal = SCANS[state["kind"]](clients, state)
counts, first = Counter(finding["fp"] for finding in findings), {}
for finding in findings:
first.setdefault(finding["fp"], finding)
lines = []
for finding in first.values():
fp = finding["fp"]
if fp not in state["clusters"] and fp not in acks:
lines.append(report(clients, state["id"], finding, counts[fp]))
state["clusters"][fp] = {"label": finding["label"], "text": finding["text"], "count": counts[fp]}
state["terminal"] = terminal
return lines
@contextlib.contextmanager
def locked(folder: Path, name: str) -> Iterator[None]:
with open(folder / f"{name}.lock", "a", encoding="utf-8") as handle:
fcntl.flock(handle, fcntl.LOCK_EX)
yield
def read(path: Path) -> dict:
try:
return json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
return {}
def write(path: Path, data: dict) -> None:
temp = path.with_name(f".{path.name}.{os.getpid()}")
temp.write_text(json.dumps(data, indent=1, sort_keys=True) + "\n", encoding="utf-8")
os.replace(temp, path)
def outcome(lines: list[str], broken: bool, states: list[dict], acks: dict) -> int:
if lines:
return NEW
if broken:
return BROKEN
if not all(state["terminal"] for state in states):
return 0
return TERMINAL if all(settled(state, acks) for state in states) else STUCK
def poll(folder: Path, targets: list[str], clients: Clients) -> int:
acks, lines, states, broken = read(folder / ACKS), [], [], False
for target in targets:
with locked(folder, target):
state = read(folder / f"{target}.json")
if not state["terminal"]:
try:
lines += poll_target(clients, state, acks)
except (Failed, ValueError, KeyError, TypeError) as error:
print(f"track: {target}: {error}", file=sys.stderr)
broken = True
continue
write(folder / f"{target}.json", state)
states.append(state)
for line in lines:
print(line, flush=True)
return outcome(lines, broken, states, acks)
def wait(folder: Path, targets: list[str], clients: Clients, interval: int, timeout: int) -> int:
end, errors = time.monotonic() + timeout, 0
while True:
code = poll(folder, targets, clients)
errors = errors + 1 if code == BROKEN else 0
if code in ENDS or errors >= ERRORS or time.monotonic() + interval > end:
return code
time.sleep(interval)
def identity(args: argparse.Namespace) -> tuple[str, list[str]]:
"""Returns:
(ref, flags) of the target args name: the number of a run or pull
request, the alert kinds or the sorted labels; ValueError for a
malformed number or no alert kind.
"""
if args.kind in NUMBERED:
if not NUMBER.fullmatch(args.ref):
raise ValueError(f"add {args.kind} needs a number, not {args.ref!r}")
return args.ref, []
if args.kind == "alerts":
flags = [name for name in ALERTS if getattr(args, name)]
if not flags:
raise ValueError("add alerts needs --codeql, --secrets or both")
return "+".join(flags), flags
if args.label is None:
return "open", []
labels = sorted(set(args.label))
return "+".join(SLUG.sub("_", label) for label in labels), labels
def add(folder: Path, args: argparse.Namespace) -> str:
if not REPO.fullmatch(args.repo):
raise ValueError(f"{args.repo!r} is no owner/repo")
ref, flags = identity(args)
rules = None if args.rules is None else str(Path(args.rules).resolve())
rules_of(rules)
target = f"{args.kind}-{args.repo.replace('/', '_')}-{ref}"
with locked(folder, target):
path = folder / f"{target}.json"
state = read(path)
if not state:
state = {"id": target, "kind": args.kind, "repo": args.repo, "ref": ref, "flags": flags, "jobs": {}, "clusters": {}}
if state["repo"] != args.repo or state["flags"] != flags:
raise ValueError(f"{target} already tracks {state['repo']} with {state['flags']}")
write(path, {**state, "rules": rules, "terminal": False})
return target
def ack(folder: Path, fp: str, verdict: str) -> None:
targets = [path for path in folder.glob("*.json") if path.name != ACKS]
if not FINGERPRINT.fullmatch(fp) or not any(fp in read(path).get("clusters", {}) for path in targets):
raise ValueError(f"no tracked cluster has the fingerprint {fp!r}")
if not verdict.strip():
raise ValueError("--verdict must say what triage found")
with locked(folder, "acks"):
acks = read(folder / ACKS)
acks[fp] = {"verdict": verdict, "ts": time.time()}
write(folder / ACKS, acks)
def known(folder: Path, targets: list[str]) -> None:
for target in targets:
if not TARGET.fullmatch(target) or not (folder / f"{target}.json").is_file():
raise ValueError(f"unknown target {target!r}; add prints the id")
def parser() -> argparse.ArgumentParser:
top = argparse.ArgumentParser(prog="track.py", description=__doc__.splitlines()[0])
commands = top.add_subparsers(dest="command", required=True)
kinds = commands.add_parser("add").add_subparsers(dest="kind", required=True)
for kind in NUMBERED:
sub = kinds.add_parser(kind)
sub.add_argument("repo")
sub.add_argument("ref")
sub.add_argument("--rules")
sub = kinds.add_parser("alerts")
sub.add_argument("repo")
for name in ALERTS:
sub.add_argument(f"--{name}", action="store_true")
sub.set_defaults(rules=None)
sub = kinds.add_parser("issues")
sub.add_argument("repo")
sub.add_argument("--label", action="append")
sub.set_defaults(rules=None)
commands.add_parser("poll").add_argument("targets", nargs="+")
sub = commands.add_parser("wait")
sub.add_argument("targets", nargs="+")
sub.add_argument("--interval", type=int, required=True)
sub.add_argument("--timeout", type=int, required=True)
sub = commands.add_parser("ack")
sub.add_argument("fingerprint")
sub.add_argument("--verdict", required=True)
return top
def main(argv: Sequence[str] | None = None) -> int:
args = parser().parse_args(argv)
clients = Clients(gh, hotfix_hint)
try:
folder = COUNCIL.directory(COUNCIL.root(), "track")
if args.command == "add":
print(add(folder, args))
return 0
if args.command == "ack":
ack(folder, args.fingerprint, args.verdict)
print(f"acked {args.fingerprint}")
return 0
known(folder, args.targets)
if args.command == "poll":
return poll(folder, args.targets, clients)
if args.interval < 1 or args.timeout < args.interval:
raise ValueError("wait needs --interval of at least 1 and a --timeout no shorter than it")
return wait(folder, args.targets, clients, args.interval, args.timeout)
except (OSError, ValueError) as error:
print(f"track: {error}", file=sys.stderr)
return USAGE
if __name__ == "__main__":
sys.exit(main())
+5 -4
View File
@@ -1,8 +1,8 @@
---
name: kvb-ci-triage
description: >
Triage a failing CI run or build, test or deploy pipeline to verified root
causes and real fixes, one cluster per worktree.
Triage a failing CI run or pipeline to verified root causes and real
fixes, one cluster per worktree.
---
Drive a red pipeline green by root cause. Every failing job is its own
@@ -47,8 +47,9 @@ steps 0 to 2; the judgement stays yours.
6. **Timeouts**: only for a cluster whose jobs died on their time budget, or
on operator request, hand the furthest-running job log to `kvb-code-tune`;
its candidates get funnels of their own and never delay the fix.
7. **Follow** a run still in progress and triage each newly failed job; done
when the run finished and every failure has a verified fix.
7. **Follow** a running run through the `kvb-ci-track` skill, triage each
new cluster it prints and ack it once fixed; done when the run finished
and every failure has a verified fix.
## Rules
+251
View File
@@ -0,0 +1,251 @@
from __future__ import annotations
import importlib.util
import io
import itertools
import json
import os
import tempfile
import unittest
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path
from unittest import mock
REPO_ROOT = Path(__file__).resolve().parents[1]
TRACK = REPO_ROOT / "skills" / "kvb-ci-track" / "scripts" / "track.py"
REPO = "owner/core"
ANSIBLE = 'TASK [web-app-a : Wait for health] ***\nfatal: [localhost]: FAILED! => {"msg": "timeout 120"}\n##[error]Process completed with exit code 2.\n'
PLAYWRIGHT = (
" ✘ 3 [chromium] › roles/web-app-a/playwright/login.spec.js:98:5 › logs in (30.0s)\n"
" 1) [chromium] › roles/web-app-a/playwright/login.spec.js:98:5 › logs in\n"
" Error: expect(locator).toBeVisible() failed\n"
"##[error]Process completed with exit code 1.\n"
)
RULES = {
"job_name": ["^roles / "],
"lines": [
{"id": "playwright", "match": r"✘ .*\.spec\.js:\d+:\d+", "pick": "first", "context": "^Error:", "side": "after"},
{"id": "ansible", "match": r"fatal: \[[^]]*\]: FAILED!", "pick": "last", "context": r"^TASK \[", "side": "before"},
],
}
def _load():
spec = importlib.util.spec_from_file_location("track", TRACK)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
track = _load()
def job(number: int, name: str, conclusion: str) -> str:
return json.dumps({"id": number, "name": name, "status": "completed", "conclusion": conclusion})
class FakeGh:
def __init__(self, answers: dict[str, tuple[int, str, str]]):
self.answers, self.calls = answers, []
def __call__(self, argv: list[str]) -> tuple[int, str, str]:
self.calls.append(argv)
key = next((item for item in argv if item.startswith("/repos/")), " ".join(argv[:2]))
return self.answers[key]
def logs(self) -> int:
return sum(any(item.endswith("/logs") for item in argv) for argv in self.calls)
class Base(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.folder = Path(tmp.name)
self.hints = []
def hint(self, line: str) -> str | None:
self.hints.append(line)
return "hotfix/wait-health (merged)" if "timeout" in line else None
def add(self, *argv: str) -> str:
return track.add(self.folder, track.parser().parse_args(["add", *argv]))
def poll(self, gh: FakeGh, *targets: str) -> tuple[int, list[str], str]:
stdout, stderr = io.StringIO(), io.StringIO()
with redirect_stdout(stdout), redirect_stderr(stderr):
code = track.poll(self.folder, list(targets), track.Clients(gh, self.hint))
return code, stdout.getvalue().splitlines(), stderr.getvalue()
def run_answers(self, status: str, jobs: list[str]) -> dict[str, tuple[int, str, str]]:
return {
f"/repos/{REPO}/actions/runs/7": (0, json.dumps({"status": status}), ""),
f"/repos/{REPO}/actions/runs/7/jobs?per_page=30": (0, "\n".join(jobs), ""),
f"/repos/{REPO}/actions/jobs/1/logs": (0, ANSIBLE, ""),
f"/repos/{REPO}/actions/jobs/2/logs": (0, ANSIBLE.replace("120", "121"), ""),
}
class TestRun(Base):
def test_matrix_jobs_with_one_failing_line_are_one_cluster_reported_once(self):
target = self.add("run", REPO, "7")
jobs = [job(1, "deploy (web-app-a, compose)", "failure"), job(2, "deploy (web-app-a, swarm)", "failure"), job(3, "lint", "success")]
gh = FakeGh(self.run_answers("in_progress", jobs))
code, lines, _ = self.poll(gh, target)
self.assertEqual(code, track.NEW)
self.assertEqual(len(lines), 1)
fp, name, label, count, text, hint = lines[0].split("\t")
self.assertEqual((name, label, count, hint), (target, "deploy", "2", "hotfix/wait-health (merged)"))
self.assertEqual(text, 'TASK [web-app-a : Wait for health] *** fatal: [localhost]: FAILED! => {"msg": "timeout <n>"}')
self.assertIn("timeout 120", self.hints[0])
self.assertEqual((self.poll(gh, target)[:2], gh.logs()), ((0, []), 2))
gh.answers[f"/repos/{REPO}/actions/runs/7"] = (0, json.dumps({"status": "completed"}), "")
self.assertEqual(self.poll(gh, target)[0], track.STUCK)
track.ack(self.folder, fp, "fixed by hotfix/wait-health")
calls = len(gh.calls)
self.assertEqual(self.poll(gh, target)[0], track.TERMINAL)
self.assertEqual(len(gh.calls), calls)
def test_an_ack_silences_the_cluster_in_the_next_run_and_needs_a_known_fingerprint(self):
first = self.add("run", REPO, "7")
gh = FakeGh(self.run_answers("completed", [job(1, "deploy (web-app-a, compose)", "failure")]))
fp = self.poll(gh, first)[1][0].split("\t")[0]
with self.assertRaises(ValueError):
track.ack(self.folder, "0" * 12, "nothing")
with self.assertRaises(ValueError):
track.ack(self.folder, fp, " ")
track.ack(self.folder, fp, "flake, proven transient")
second = self.add("run", "owner/fork", "7")
answers = {key.replace(REPO, "owner/fork"): value for key, value in gh.answers.items()}
self.assertEqual(self.poll(FakeGh(answers), second)[:2], (track.TERMINAL, []))
def test_cancelled_jobs_are_not_fetched_and_a_gone_log_is_its_own_cluster(self):
target = self.add("run", REPO, "7")
answers = self.run_answers("in_progress", [job(1, "build", "cancelled"), job(2, "test", "timed_out")])
answers[f"/repos/{REPO}/actions/jobs/2/logs"] = (1, "", "gh: Not Found (HTTP 404)")
gh = FakeGh(answers)
lines = self.poll(gh, target)[1]
self.assertEqual(sorted(line.split("\t")[4] for line in lines), ["cancelled", "no log"])
self.assertEqual(gh.logs(), 1)
def test_a_gh_failure_is_exit_3_and_retried_on_the_next_poll(self):
target = self.add("run", REPO, "7")
answers = self.run_answers("in_progress", [job(1, "deploy", "failure")])
answers[f"/repos/{REPO}/actions/jobs/1/logs"] = (1, "", "gh: Server Error (HTTP 502)\nmore")
gh = FakeGh(answers)
code, lines, stderr = self.poll(gh, target)
self.assertEqual((code, lines, stderr.strip()), (track.BROKEN, [], f"track: {target}: gh: Server Error (HTTP 502)"))
answers[f"/repos/{REPO}/actions/jobs/1/logs"] = (0, ANSIBLE, "")
self.assertEqual(self.poll(gh, target)[0], track.NEW)
class TestPullRequest(Base):
def test_every_run_of_the_head_counts_and_a_closed_pull_request_is_terminal(self):
target = self.add("pr", REPO, "42")
head = "a" * 40
answers = self.run_answers("completed", [job(1, "deploy (web-app-a, compose)", "failure")])
answers[f"/repos/{REPO}/pulls/42"] = (0, json.dumps({"state": "open", "head": {"sha": head}}), "")
answers[f"/repos/{REPO}/actions/runs?head_sha={head}&per_page=100"] = (0, '{"id": 7, "status": "in_progress"}\n', "")
gh = FakeGh(answers)
self.assertEqual(self.poll(gh, target)[0], track.NEW)
answers[f"/repos/{REPO}/pulls/42"] = (0, json.dumps({"state": "closed", "head": {"sha": head}}), "")
self.assertEqual(self.poll(gh, target)[0], track.STUCK)
class TestRules(Base):
def test_rules_pick_the_playwright_and_ansible_lines_and_cut_job_names(self):
rules = dict(RULES)
self.assertEqual(
track.failing_line(PLAYWRIGHT, rules),
"✘ 3 [chromium] › roles/web-app-a/playwright/login.spec.js:98:5 › logs in (30.0s) Error: expect(locator).toBeVisible() failed",
)
self.assertEqual(track.failing_line(ANSIBLE, rules), 'TASK [web-app-a : Wait for health] *** fatal: [localhost]: FAILED! => {"msg": "timeout 120"}')
self.assertEqual(track.failing_line("ok\nError: disk full\n", rules), track.CI.failing("ok\nError: disk full\n"))
self.assertEqual(track.job_label("roles / deploy (web-app-a, compose) (debian)", rules), "deploy")
def test_a_rules_file_is_checked_when_added(self):
path = self.folder / "rules.json"
path.write_text(json.dumps(RULES), encoding="utf-8")
target = self.add("run", REPO, "7", "--rules", str(path))
self.assertEqual(track.read(self.folder / f"{target}.json")["rules"], str(path.resolve()))
for broken in ({"lines": [{"id": "x", "match": "(a+)+", "pick": "last"}]}, {"lines": [{"id": "x", "match": "a", "pick": "any"}]},
{"lines": [{"id": "x", "match": "a", "pick": "last", "context": "b"}]}, {"job_name": ["("]}, []):
with self.subTest(rules=broken):
path.write_text(json.dumps(broken), encoding="utf-8")
with self.assertRaises(ValueError):
self.add("run", REPO, "8", "--rules", str(path))
def test_secrets_in_a_failing_line_are_masked_and_paths_kept(self):
line = "curl https://bot:pa55@host/x token=abc123 ghp_ABCDEFGHIJKLMNOPQRSTUVWX1234 roles/web-app-a2/tasks/main.yml"
self.assertEqual(track.masked(line), "curl https://<auth>@host/x token=<masked> <token> roles/web-app-a2/tasks/main.yml")
def test_control_and_zero_width_characters_never_reach_a_cell(self):
line = "fail\tfake\x1b]0;title\x07 ghp_ABCDEFGHIJKL\u200bMNOPQRSTUVWX1234"
self.assertEqual(track.masked(line), "fail fake]0;title <token>")
self.assertEqual(track.report(track.Clients(None, lambda _: None), "run:1", {"fp": "a" * 12, "label": "job\tforged", "text": "x\u200by", "line": None}, 1), "\t".join(["a" * 12, "run:1", "job forged", "1", "xy"]))
def test_failing_keeps_the_raw_line_that_signature_normalises(self):
self.assertEqual(track.CI.failing(ANSIBLE), 'TASK [web-app-a : Wait for health] *** fatal: [localhost]: FAILED! => {"msg": "timeout 120"}')
self.assertEqual(track.CI.signature(ANSIBLE), track.CI.normalise(track.CI.failing(ANSIBLE)))
class TestAlertsAndIssues(Base):
def test_alerts_carry_rule_type_and_place_and_secret_locations_are_read_once(self):
target = self.add("alerts", REPO, "--codeql", "--secrets")
gh = FakeGh({
f"/repos/{REPO}/code-scanning/alerts?state=open&per_page=30": (0, '{"number": 5, "rule": "py/sql-injection", "path": "app.py", "line": 12}\n', ""),
f"/repos/{REPO}/secret-scanning/alerts?state=open&per_page=30": (0, '{"number": 9, "type": "github_personal_access_token"}\n', ""),
f"/repos/{REPO}/secret-scanning/alerts/9/locations": (0, '{"path": "config/.env", "line": 3}\n', ""),
})
code, lines, _ = self.poll(gh, target)
self.assertEqual(code, track.NEW)
self.assertEqual(sorted(line.split("\t", 2)[2] for line in lines), ["codeql py/sql-injection\t1\tapp.py:12", "secret github_personal_access_token\t1\tconfig/.env:3"])
self.assertEqual(self.poll(gh, target)[:2], (0, []))
self.assertEqual(sum(argv[1].endswith("/locations") for argv in gh.calls), 1)
self.assertEqual(self.hints, [])
def test_issues_pass_the_labels_and_mask_the_title(self):
target = self.add("issues", REPO, "--label", "bug", "--label", "ci")
gh = FakeGh({"issue list": (0, json.dumps([{"number": 12, "title": "Leak token=abc in log"}]), "")})
code, lines, _ = self.poll(gh, target)
self.assertEqual((code, lines[0].split("\t")[1:]), (track.NEW, [target, "#12", "1", "Leak token=<masked> in log"]))
self.assertEqual(gh.calls[0][-4:], ["--label", "bug", "--label", "ci"])
self.assertTrue(target.endswith("-bug+ci"))
class TestWait(Base):
def test_wait_returns_on_news_after_repeated_errors_or_at_the_timeout(self):
target = self.add("run", REPO, "7")
quiet = FakeGh(self.run_answers("in_progress", []))
with mock.patch.object(track.time, "monotonic", side_effect=itertools.count()), mock.patch.object(track.time, "sleep") as sleep:
self.assertEqual(track.wait(self.folder, [target], track.Clients(quiet, self.hint), 1, 3), 0)
self.assertEqual((len(quiet.calls), sleep.call_count), (6, 2))
broken = FakeGh({f"/repos/{REPO}/actions/runs/7": (1, "", "HTTP 502")})
with mock.patch.object(track.time, "sleep"), redirect_stderr(io.StringIO()):
self.assertEqual(track.wait(self.folder, [target], track.Clients(broken, self.hint), 1, 3600), track.BROKEN)
self.assertEqual(len(broken.calls), track.ERRORS)
news = FakeGh(self.run_answers("in_progress", [job(1, "deploy", "failure")]))
with redirect_stdout(io.StringIO()):
self.assertEqual(track.wait(self.folder, [target], track.Clients(news, self.hint), 1, 3600), track.NEW)
class TestCommandLine(Base):
def test_add_refuses_malformed_targets_and_unknown_targets_exit_2(self):
for argv in (["run", "owner", "7"], ["pr", REPO, "x"], ["alerts", REPO]):
with self.subTest(argv=argv), self.assertRaises(ValueError):
self.add(*argv)
with mock.patch.dict(os.environ, {"AGENTS_COUNCIL_ROOT": str(self.folder / "council")}), redirect_stderr(io.StringIO()) as stderr:
self.assertEqual(track.main(["poll", "run-owner_core-7"]), track.USAGE)
self.assertEqual(track.main(["poll", "../acks"]), track.USAGE)
self.assertIn("unknown target", stderr.getvalue())
def test_adding_again_keeps_the_clusters_and_polls_an_ended_target_again(self):
target = self.add("run", REPO, "7")
self.poll(FakeGh(self.run_answers("completed", [job(1, "deploy", "failure")])), target)
self.assertEqual(self.add("run", REPO, "7"), target)
state = track.read(self.folder / f"{target}.json")
self.assertEqual((len(state["clusters"]), state["terminal"]), (1, False))
if __name__ == "__main__":
unittest.main()