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
55 changes: 55 additions & 0 deletions board/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,61 @@ qualified with `partial view (N legs unread)`, and a grey badge rather than a
green one — a green badge is only ever emitted by a render that read
everything and found nothing wrong.

### `--github-data`: handing the renderer what it cannot fetch

A remote session's GitHub access is the `mcp__github__*` tools, and those are
an **agent** capability — `_board.py` is a subprocess and cannot reach them,
however it is invoked. So the fetching moves to the only thing that can do it:
the `/board` skill gathers, writes a file, and passes it to the renderer, which
stays pure.

```
pyauto-brain board --github-data <file>
```

The file is a JSON object keyed by the endpoint **exactly as `gh_json()`
receives it** — the same string that would follow `gh api`:

```json
{
"repos/Org/PyAutoBrain/actions/workflows/nightly-release.yml/runs?per_page=1":
{ "workflow_runs": [ … ] },
"repos/Org/PyAutoBrain/actions/runs/42/jobs": { "jobs": [ … ] },
"repos/Org/PyAutoBrain/check-runs/98/annotations": [ … ]
}
```

Keying on the call site's own string is deliberate: injected and live data are
interchangeable by construction rather than by convention, and a key that
drifts simply misses.

Store each response **as GitHub returns it** — the renderer reads the API's own
field names, and a gatherer that reshapes them produces rows that look like a
render bug rather than a bad file. The overnight row needs `conclusion`,
`status`, `created_at` (the age; `updated_at` is *not* the field read) and
`html_url` per run, and `jobs[].conclusion` where the blocked-at-a-gate
refinement is wanted.

Three rules the seam does not get to bend:

1. **A miss is *could not ask*.** An endpoint absent from the file yields
`None`, exactly as an absent `gh` does, and the leg renders `could not
read`. It must never become an empty answer — that is the failure the
degraded-render work exists to prevent, and it is how a board goes green by
never looking.
2. **An explicit `null` means the gatherer's own fetch failed** — same
outcome, stated rather than implied. `{"workflow_runs": []}` is the
opposite: a real answer that happens to be empty.
3. **A malformed or missing file is fatal, not degrading.** Every leg reading
`could not read` renders as a GitHub outage; if the truth is that the
gatherer wrote a broken file, the board must say so instead.

The alternative to the seam is an org admin connecting the Claude GitHub App,
after which `$GH_TOKEN` would work from a subprocess and `gh_json()` could
become a plain REST helper on every surface. Probed 2026-08-27: 200 on `/user`
and `/rate_limit`, **403 on every repo-scoped path**. Re-probe before assuming
this seam is still needed — it is meant to be deletable.

To get a complete board in a remote session, the environment needs outbound
access to the Pages host. That is cloud-environment configuration on claude.ai,
not something this repo can set: open the environment selector at
Expand Down
63 changes: 62 additions & 1 deletion board/_board.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,62 @@ def derive_org(homes):
# --------------------------------------------------------------- collect ----


# ---------------------------------------------------------------------------
# The injection seam (--github-data)
#
# Eleven of this board's legs read GitHub through `gh api`, and a Claude Code
# remote session — the surface the board is actually read from on a phone — has
# no `gh` at all. Its GitHub access is the `mcp__github__*` tool surface, which
# is an AGENT capability: this file is a subprocess and cannot reach it, however
# it is invoked. That is the whole reason this is a seam and not a substitution.
#
# So the `/board` skill (which is the agent) fetches, writes the responses to a
# file, and passes it here; this stays a pure renderer. The map is keyed by the
# endpoint exactly as `gh_json` receives it, so injected and live data are
# interchangeable by construction rather than by convention — a key that drifts
# from its call site simply misses, and a miss is "could not ask", which is a
# state this board already renders honestly.
#
# The alternative — an org admin connecting the Claude GitHub App so the
# injected $GH_TOKEN works from a subprocess — was probed on 2026-08-27 and
# does not work: 200 on /user and /rate_limit, 403 on every repo-scoped path.
# If that changes, this seam becomes deletable; keep it small enough to delete.
# ---------------------------------------------------------------------------

_INJECTED = None


def load_github_data(path):
"""Load pre-fetched `gh api` responses ({endpoint: response}) for gh_json.

A missing or malformed file raises rather than degrading. An empty map
would make every leg render "could not read" — honest-looking, and wrong
for the wrong reason: the board would report a GitHub outage when what
actually happened is that the gatherer wrote a broken file.
"""
global _INJECTED
try:
data = json.loads(Path(path).read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise SystemExit(f"board: --github-data {path} is unreadable: {exc}")
if not isinstance(data, dict):
raise SystemExit(
f"board: --github-data {path} must be an object keyed by endpoint")
_INJECTED = data
return len(data)


def gh_json(args):
"""`gh api ...` -> parsed JSON; None on any failure (the surface degrades
honestly rather than inventing content). Read-only endpoints only."""
honestly rather than inventing content). Read-only endpoints only.

With `--github-data` loaded, the endpoint is looked up there first. A hit
is the answer; a miss falls through to `gh`, which on the gh-less surface
this exists for is absent, so the leg reports *could not ask* — never an
empty answer to an unasked question.
"""
if _INJECTED is not None and args and args[0] in _INJECTED:
return _INJECTED[args[0]]
try:
r = subprocess.run(
[GH, "api", *args], capture_output=True, text=True, timeout=120
Expand Down Expand Up @@ -1559,8 +1612,16 @@ def main():
help="write index.html + badge.json + board.json + "
"board.md into --out")
parser.add_argument("--out", default="_site", help="--apply output dir")
parser.add_argument("--github-data", metavar="FILE",
help="pre-fetched `gh api` responses ({endpoint: "
"response}) — for a session with no `gh`, where "
"the /board skill gathers them via the GitHub MCP "
"tools and this stays a pure renderer")
args = parser.parse_args()

if args.github_data:
load_github_data(args.github_data)

data = collect()
if args.apply:
out = Path(args.out)
Expand Down
32 changes: 27 additions & 5 deletions skills/board/board.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,33 @@ nothing; every chip on it routes back through the real doors.
`https://<org>.github.io/PyAutoBrain/` (refreshed each morning by
`brain_board.yml`; badge.json beside it is the headline). If the human just
wants the link or the headline, that is the answer — don't re-collect.
2. **Live digest on request** — run `bin/pyauto-brain board` (needs an
authenticated `gh`; add `--json` for the raw surface) and relay its
markdown digest faithfully, including the Degraded section. On a machine
with the local workspace, `PYAUTO_ROOT` is honoured; without one the
resume/community legs degrade honestly and say so.
2. **Live digest on request** — run `bin/pyauto-brain board` (add `--json` for
the raw surface) and relay its markdown digest faithfully, including the
Degraded section. On a machine with the local workspace, `PYAUTO_ROOT` is
honoured; without one the resume/community legs degrade honestly and say so.

**Without `gh` (mobile, web), gather first — you are the only thing that
can.** The `mcp__github__*` tools are an agent capability; `_board.py` is a
subprocess and cannot reach them. So fetch the overnight legs yourself,
write them to a scratch file keyed by endpoint, and hand it over:

```
bin/pyauto-brain board --github-data /tmp/board-github-data.json
```

For each `overnight_jobs` entry in `config/policy.yaml`
(`<repo>:<workflow>`), one `mcp__github__actions_list`
(`list_workflow_runs`, `resource_id` = the workflow file, `per_page` 1),
stored under `repos/<org>/<repo>/actions/workflows/<wf>/runs?per_page=1`.
Add `.../actions/runs/<id>/jobs` (`list_workflow_jobs`) where you want the
blocked-at-a-gate refinement. Store each response **verbatim**: the row
reads `conclusion`, `status`, `created_at` (**not** `updated_at` — that one
renders the age as `?`) and `html_url`. The file's shape, and the three rules a
gatherer must not bend — a miss is *could not ask*, an explicit `null` says
the fetch failed, a broken file is fatal rather than degrading — are the
contract in [`../../board/AGENTS.md`](../../board/AGENTS.md) → "Reading the
board in a remote session". Do not invent a second shape for a leg that is
not covered yet: leave it dark and let it say so.
3. **Never act from the digest.** Community replies stay `/community`'s
human-gated job; closing issues stays `/issue_cleanup`'s; deletion stays
`/repo_cleanup`'s. The board only names the door.
Expand Down
146 changes: 146 additions & 0 deletions tests/test_board_github_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
"""The board can be handed the GitHub data it cannot fetch itself.

`_board.py` reads GitHub through `gh api`, and the surface the board is
actually read from — a Claude Code session on a phone — has no `gh`. Its
GitHub access is the `mcp__github__*` tools, which are an **agent** capability:
this script is a subprocess and cannot reach them however it is invoked. So the
`/board` skill fetches and this file renders, and `--github-data` is the seam
between them.

The one invariant these tests exist to protect is the one the 2026-08-26
degraded-render work established, restated for the new path: an endpoint that
was not injected is *could not ask*, never *asked and found nothing*. A seam
that quietly turned a missing key into an empty answer would put the board back
where it started — green because it never looked.

Fixtures only. Nothing here calls GitHub, and `BOARD_GH` is pointed at a
command that does not exist so a leak would fail loudly rather than answer.
"""

import json
import sys
from pathlib import Path

import pytest

BRAIN_HOME = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(BRAIN_HOME / "board"))

import _board # noqa: E402

RUNS = "repos/Org/Repo/actions/workflows/nightly.yml/runs?per_page=1"


@pytest.fixture(autouse=True)
def _no_live_gh(monkeypatch):
"""No test here may reach a real `gh`, injected data or not."""
monkeypatch.setattr(_board, "GH", "gh-does-not-exist-in-tests")
monkeypatch.setattr(_board, "_INJECTED", None)


def _write(tmp_path, mapping):
path = tmp_path / "github-data.json"
path.write_text(json.dumps(mapping), encoding="utf-8")
return path


def test_an_injected_endpoint_is_answered_without_gh(tmp_path):
payload = {"workflow_runs": [{"id": 1, "conclusion": "success"}]}
_board.load_github_data(_write(tmp_path, {RUNS: payload}))
assert _board.gh_json([RUNS]) == payload


def test_an_endpoint_that_was_not_injected_is_could_not_ask(tmp_path):
"""The invariant: a miss must not become an empty answer.

`None` is what the callers read as *could not ask* — it is why a workflow
row carries `unreadable` rather than "no runs". An injected map that
answered `{}` or `[]` for a key it does not hold would hand the board a
confident wrong answer, which is the failure this whole surface was
rebuilt to stop.
"""
_board.load_github_data(_write(tmp_path, {RUNS: {"workflow_runs": []}}))
assert _board.gh_json(["repos/Org/Other/actions/runs"]) is None


def test_an_injected_null_is_still_could_not_ask(tmp_path):
"""The gatherer says so explicitly when its own fetch failed."""
_board.load_github_data(_write(tmp_path, {RUNS: None}))
assert _board.gh_json([RUNS]) is None


def test_an_injected_empty_result_is_a_real_answer(tmp_path):
"""And the other half of the distinction: asked, and there was nothing."""
_board.load_github_data(_write(tmp_path, {RUNS: {"workflow_runs": []}}))
assert _board.gh_json([RUNS]) == {"workflow_runs": []}


def test_without_the_flag_nothing_changes(tmp_path):
"""The dev-box path is untouched: no injected map, so `gh` is consulted —
here a command that does not exist, which is exactly the honest `None`."""
assert _board._INJECTED is None
assert _board.gh_json([RUNS]) is None


def test_a_malformed_file_fails_loudly_rather_than_degrading(tmp_path):
"""An unreadable map would make every leg read "could not read".

That renders as a GitHub outage. What actually happened is that the
gatherer wrote a broken file, and the difference matters to whoever reads
the board at 8am.
"""
bad = tmp_path / "bad.json"
bad.write_text("{not json", encoding="utf-8")
with pytest.raises(SystemExit):
_board.load_github_data(bad)

with pytest.raises(SystemExit):
_board.load_github_data(tmp_path / "absent.json")

listy = tmp_path / "listy.json"
listy.write_text("[]", encoding="utf-8")
with pytest.raises(SystemExit):
_board.load_github_data(listy)


def test_the_overnight_leg_renders_live_from_injected_data(tmp_path):
"""End to end on the leg this phase exists for.

Seven `overnight: could not read …` rows are the largest block of the
board's eleven dark legs; one injected endpoint turns one of them into a
real row, with no `gh` anywhere in the process.
"""
_board.load_github_data(_write(tmp_path, {
RUNS: {"workflow_runs": [{
"id": 42,
"conclusion": "success",
"status": "completed",
# `created_at`, not `updated_at`: the row's age comes from this
# field, and a gatherer that stores the wrong one renders "?" —
# which reads as a render bug rather than a bad file. Pinned here
# because the first hand-written fixture got it wrong.
"created_at": "2026-01-01T00:00:00Z",
"html_url": "https://example.invalid/run/42",
}]},
"repos/Org/Repo/actions/runs/42/jobs": {"jobs": []},
}))

degraded = []
rows = _board.collect_overnight(["Org/Repo:nightly.yml"], "Org", degraded)

assert len(rows) == 1
assert rows[0]["unreadable"] is False
assert rows[0]["conclusion"] == "success"
assert rows[0]["age_h"] is not None, "the age field the row reads is unset"
assert not degraded, degraded


def test_an_uninjected_workflow_stays_unreadable_and_degrades(tmp_path):
"""The same call with the endpoint absent: honest, and still degraded."""
_board.load_github_data(_write(tmp_path, {}))

degraded = []
rows = _board.collect_overnight(["Org/Repo:nightly.yml"], "Org", degraded)

assert rows[0]["unreadable"] is True
assert degraded, "a leg that could not be read must degrade the render"
Loading