Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 23 additions & 10 deletions read_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,27 +476,40 @@ async def github_ci_runs(repo: str = "", branch: str = "", limit: int = 15) -> s
return f"{repo} — {len(runs)} recent run(s):\n" + "\n".join(lines)

@tool
async def github_run_failure(run_id: int, repo: str = "", max_lines: int = 40) -> str:
"""Explain why an Actions run failed: the error lines from its failed steps. run_id = databaseId from github_ci_runs; max_lines up to 80."""
async def github_run_failure(
run_id: int, repo: str = "", max_lines: int = 40, context: int = 5, grep: str = ""
) -> str:
"""Explain why an Actions run failed: error lines plus context preceding lines (default 5, clamped 0..20); optional case-insensitive regex grep replaces the error filter. run_id = databaseId from github_ci_runs; max_lines clamped 5..80, keeping the latest lines."""
repo = resolve_repo(repo, default_repo) or ""
if err := bad_repo(repo):
return err
cap = max(5, min(int(max_lines), 80))
context = max(0, min(int(context), 20))
try:
pattern = re.compile(grep, re.IGNORECASE) if grep else _CI_ERR_RE
except re.error as exc:
return f"Error: invalid grep regex: {exc}"
result = await fetch_failure_log(repo, run_id)
if "error" in result:
return result["error"]
out = result["log"]
raw = [ln.rstrip() for ln in out.splitlines() if ln.strip()]
messages = [ln.split("\t")[-1] for ln in raw]
selected: set[int] = set()
for i, msg in enumerate(messages):
if pattern.search(msg):
selected.update(range(max(0, i - context), i + 1))
seen: set = set()
uniq: list[str] = []
for ln in raw:
msg = ln.split("\t")[-1]
if _CI_ERR_RE.search(msg):
key = msg[:120]
if key not in seen:
seen.add(key)
uniq.append(msg[:200])
picked = uniq[-cap:] if uniq else [ln.split("\t")[-1][:200] for ln in raw[-cap:]]
for i in sorted(selected):
msg = messages[i]
key = msg[:120]
if key not in seen:
seen.add(key)
uniq.append(msg[:200])
if grep and not selected:
return f"Run {run_id} in {repo}: no failed-step log lines matched grep."
picked = uniq[-cap:] if uniq else [msg[:200] for msg in messages[-cap:]]
if not picked:
return f"Run {run_id} in {repo}: no failed-step log lines (run may not have failed, or its logs expired)."
return f"{repo} run {run_id} — failure log ({len(picked)} line(s)):\n" + "\n".join(picked)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_detail_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ async def test_failure_tool_keeps_error_filtering_with_shared_fetcher():
tool = next(t for t in get_read_tools() if t.name == "github_run_failure")
log = "step\tsetup\nstep\terror: bad\nstep\terror: bad\nstep\tdone\n"
with patch("ghplugin.read_tools.run_gh", AsyncMock(return_value=(0, log, ""))):
result = await tool.ainvoke({"repo": "o/n", "run_id": 9})
result = await tool.ainvoke({"repo": "o/n", "run_id": 9, "context": 0})
assert result == "o/n run 9 — failure log (1 line(s)):\nerror: bad"


Expand Down
80 changes: 80 additions & 0 deletions tests/test_read_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1256,3 +1256,83 @@ async def test_get_body_unexpected_shape_never_raises(kind, body):
with patch("ghplugin.read_tools.run_gh", AsyncMock(return_value=(0, json.dumps({"body": body}), ""))):
result = await tool.ainvoke({"repo": "owner/name", "number": 1})
assert isinstance(result, str)


# ── github_run_failure: preserve diagnostics before retry warnings ──────────────


async def _failure(log, **kwargs):
mock = AsyncMock(return_value=(0, log, ""))
with patch("ghplugin.read_tools.run_gh", mock):
result = await _tool("github_run_failure").ainvoke({"repo": "owner/name", "run_id": 62, **kwargs})
mock.assert_awaited_once_with(["run", "view", "62", "--repo", "owner/name", "--log-failed"], timeout=60)
return result


def _retry_lines():
return [
line
for attempt in range(1, 5)
for line in (
f"codesign: signature {attempt}",
f"spctl: assessment {attempt}",
f"stapler: ticket {attempt}",
f"::warning:: macOS artifact check failed (attempt {attempt}/4)",
)
]


async def test_run_failure_default_context_keeps_retry_diagnostics():
lines = _retry_lines()
log = "\n".join(f"job\tstep\t{line}" for line in lines)
out = await _failure(log)
assert out.splitlines()[1:] == lines


async def test_run_failure_zero_context_preserves_error_only_deduplication():
lines = _retry_lines()
out = await _failure("\n".join(lines + [lines[-1]]), context=0)
assert out.splitlines()[1:] == lines[3::4]


@pytest.mark.parametrize("context", [0, 1])
async def test_run_failure_grep_replaces_default_filter_case_insensitively(context):
lines = ["setup", "SPCTL: assessment", "stapler: ticket", "error: unrelated"]
out = await _failure("\n".join(lines), grep="spctl|stapler", context=context)
assert out.splitlines()[1:] == lines[1 - context : 3]


async def test_run_failure_invalid_grep_returns_error_before_fetch():
mock = AsyncMock()
with patch("ghplugin.read_tools.run_gh", mock):
out = await _tool("github_run_failure").ainvoke({"repo": "owner/name", "run_id": 62, "grep": "["})
assert out.startswith("Error: invalid grep regex:")
mock.assert_not_called()


@pytest.mark.parametrize("cap", [5, 8, 12])
async def test_run_failure_budget_keeps_latest_context_and_matches(cap):
lines = _retry_lines()
out = await _failure("\n".join(lines), context=3, max_lines=cap)
assert out.splitlines()[1:] == lines[-cap:]


@pytest.mark.parametrize("context, count", [(-1, 1), (0, 1), (5, 6), (20, 21), (99, 21)])
async def test_run_failure_context_is_clamped(context, count):
lines = [f"diagnostic {i}" for i in range(30)] + ["failed"]
out = await _failure("\n".join(lines), context=context)
assert out.splitlines()[1:] == lines[-count:]


async def test_run_failure_default_no_match_falls_back_but_grep_does_not():
lines = [f"diagnostic {i}" for i in range(10)]
log = "\n".join(lines)
assert (await _failure(log, max_lines=5)).splitlines()[1:] == lines[-5:]
assert await _failure(log, grep="spctl") == "Run 62 in owner/name: no failed-step log lines matched grep."
assert "no failed-step log lines (run may not have failed" in await _failure("")


async def test_run_failure_retains_line_length_and_upper_budget_limits():
lines = [f"error {i}: " + "x" * 250 for i in range(100)]
out = await _failure("\n".join(lines), max_lines=100)
assert out.splitlines()[1:] == [line[:200] for line in lines[-80:]]
Loading