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
16 changes: 15 additions & 1 deletion board/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,23 @@ bin/pyauto-brain board publish # dev-box leg: distill hygiene + worktree

Publishing is `.github/workflows/brain_board.yml`: a morning cron plus manual
dispatch renders `--apply` output and deploys it to GitHub Pages (page +
`badge.json` + `board.json` + `board.md`). Nothing is committed to the repo —
`badge.json` + `state.json` + `board.json` + `board.md`). Nothing is committed to the repo —
the board is served, not stored, so a daily refresh makes no commit noise.

## The cockpit feed (`state.json`)

`state.json` is the **cockpit feed** — the per-organ machine surface the
cockpit and the phone read: one `status` (green/yellow/red/stale/grey), one
`headline`, an ISO-8601 UTC `updated`, the `pages_url`, and the actionable
`items` (severity, text, GitHub `url`, copy-for-Claude `prompt`). It sits next
to `badge.json` (the one-line headline contract; the feed's status and
headline mirror it) and `board.json` (organ-specific detail, a different shape
per organ). The contract lives in `board/state_schema.json` and is enforced by
`board/_state.py` (stdlib only, `build_state` + `validate_state`); this board
emits it via `render_state` (`--state`, and `--apply` writes it). Other organs
emit the same shape and validate before publishing with
`python PyAutoBrain/board/_state.py _site/state.json` — runnable from any cwd.

## Look (`_theme.py`)

`board/_theme.py` is the one place that answers *what does a one-tap board
Expand Down
113 changes: 110 additions & 3 deletions board/_board.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@
from _theme import ( # noqa: E402
JS as _THEME_JS, boards_footer, css as _theme_css, hero, pills, stats,
)
# The organ cockpit feed contract (state.json) — the validator every organ
# shares, so this board cannot publish a feed the cockpit would reject.
from _state import build_state # noqa: E402

THEME_ORGAN = "brain" # whose logo this page wears

Expand Down Expand Up @@ -1010,6 +1013,103 @@ def render_badge(data):
}, indent=2) + "\n"


# badge_color speaks shields.io; the cockpit feed speaks its own small enum.
STATE_STATUS = {"red": "red", "orange": "yellow", "lightgrey": "grey",
"brightgreen": "green"}
# The phone shows a glance, not the whole board: past this many rows the
# pages_url is the door. Heart blockers are already capped at
# HEART_BLOCKER_CAP upstream; this bounds the sum of every section.
STATE_ITEM_CAP = 20


def _iso_generated(data):
"""The render time as ISO-8601 UTC.

The collect keeps its human display form ("%Y-%m-%d %H:%M UTC") — board.json
publishes it and must not change shape — so the feed re-reads that string
rather than adding a second field to the surface.
"""
try:
dt = datetime.strptime(data.get("generated", ""), "%Y-%m-%d %H:%M UTC")
except (TypeError, ValueError):
dt = datetime.now(timezone.utc).replace(second=0, microsecond=0)
return dt.strftime("%Y-%m-%dT%H:%M:%SZ")


def _state_items(data):
"""The rows the board already renders as asking something of a human —
composed, never re-derived: each prompt is the owning organ's own payload
(the Heart's /bug line, the Ears' triage ref), carried verbatim."""
items = []
for b in data.get("heart_blockers") or []:
sev = b.get("severity")
items.append({
"severity": "red" if sev == "red" else "yellow",
"text": " ".join(f"Heart: {b.get('text') or '?'}".split()),
"url": b.get("run_url") or b.get("repo_url"),
"prompt": b.get("prompt") or b.get("command"),
})
for r in data.get("overnight") or []:
where = f"{r['repo']}/{r['workflow']}"
if r.get("unreadable"):
items.append({"severity": "info",
"text": f"overnight: could not read {where}",
"url": None, "prompt": None})
elif r.get("conclusion") not in (None, "success"):
items.append({
"severity": "red",
"text": f"overnight: {where} {r['conclusion']}",
"url": r.get("url"),
# The same payload the page's 📋 chip carries for this row.
"prompt": (f"/bug overnight: {where} concluded "
f"{r['conclusion']} — {r['url'] or 'no run url'}"),
})
elif r.get("blocked"):
items.append({"severity": "yellow",
"text": f"overnight: {where} blocked at a gate",
"url": r.get("url"), "prompt": None})
for e in (data.get("community") or {}).get("awaiting_response") or []:
waited = e.get("waiting_days")
days = f" ({waited:.0f}d)" if waited is not None else ""
items.append({
"severity": ("yellow" if (waited or 0) >= COMMUNITY_STALE_DAYS
else "info"),
"text": " ".join(f"community: {e['repo']}#{e['number']} awaiting a "
f"reply{days}".split()),
"url": e.get("url"),
"prompt": f"/community triage {community_ref(e)}",
})
for d in data.get("degraded") or []:
items.append({"severity": "info",
"text": " ".join(f"degraded: {d}".split()),
"url": None, "prompt": None})
order = {"red": 0, "yellow": 1, "info": 2}
items.sort(key=lambda i: order[i["severity"]]) # stable: section order kept
return items[:STATE_ITEM_CAP]


def render_state(data):
"""state.json — the organ cockpit feed (board/_state.py, contract v1).

Same verdict as the badge (status mirrors badge_color, headline is the
badge message) plus the actionable rows, so the cockpit never disagrees
with the badge beside it.
"""
repo = data.get("repo") or "PyAutoBrain"
pages_url = (data.get("boards") or {}).get("brain") or \
f"https://{str(data.get('org', '')).lower()}.github.io/{repo}/"
state = build_state(
organ="brain",
repo=repo,
status=STATE_STATUS.get(badge_color(data), "grey"),
headline=headline(data),
updated=_iso_generated(data),
pages_url=pages_url,
items=_state_items(data),
)
return json.dumps(state, indent=2) + "\n"


def _overnight_line(r):
if r.get("unreadable"):
return f"? {r['repo']}/{r['workflow']} — could not read (see Degraded)"
Expand Down Expand Up @@ -1667,9 +1767,12 @@ def main():
parser.add_argument("--json", action="store_true", help="the raw surface")
parser.add_argument("--badge", action="store_true",
help="badge.json (the cross-board headline contract)")
parser.add_argument("--state", action="store_true",
help="state.json (the organ cockpit feed, "
"board/_state.py)")
parser.add_argument("--apply", action="store_true",
help="write index.html + badge.json + board.json + "
"board.md into --out")
help="write index.html + badge.json + state.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: "
Expand All @@ -1687,16 +1790,20 @@ def main():
out.mkdir(parents=True, exist_ok=True)
(out / "index.html").write_text(render_html(data), encoding="utf-8")
(out / "badge.json").write_text(render_badge(data), encoding="utf-8")
(out / "state.json").write_text(render_state(data), encoding="utf-8")
(out / "board.json").write_text(render_json(data), encoding="utf-8")
(out / "board.md").write_text(render_md(data), encoding="utf-8")
print(f"board: wrote {out}/index.html + badge.json + board.json + board.md")
print(f"board: wrote {out}/index.html + badge.json + state.json + "
"board.json + board.md")
return
if args.html:
print(render_html(data), end="")
elif args.json:
print(render_json(data), end="")
elif args.badge:
print(render_badge(data), end="")
elif args.state:
print(render_state(data), end="")
else:
print(render_md(data))

Expand Down
160 changes: 160 additions & 0 deletions board/_state.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
#!/usr/bin/env python3
"""board/_state.py — the organ cockpit feed contract (state.json, v1).

Every organ board already publishes two machine surfaces: badge.json (the
one-line headline the umbrella router reads) and board.json (the organ's own
detail, whose shape only that organ understands). Neither is enough for a
cockpit that shows ALL organs at once: badge.json has no rows to act on, and
board.json has a different shape per organ. state.json is the third surface —
one shape for every organ — carrying a status, a headline, a timestamp and the
actionable rows, each with its GitHub link and its copy-for-Claude payload.
The cockpit and the phone read it; nothing else is needed to render an organ.

The contract is documented in board/state_schema.json and enforced HERE.
Stdlib only and free of package-relative imports on purpose: sibling organ
workflows check PyAutoBrain out and run

python PyAutoBrain/board/_state.py _site/state.json

from their own cwd to validate what they are about to publish. A contract
whose validator needs an install is a contract nobody runs.

Exit codes (CLI): 0 valid · 1 invalid or unreadable.
"""

from __future__ import annotations

import json
import sys
from datetime import datetime

SCHEMA_VERSION = 1
STATUSES = ("green", "yellow", "red", "stale", "grey")
SEVERITIES = ("red", "yellow", "info")
REQUIRED = ("schema_version", "organ", "repo", "status", "headline",
"updated", "pages_url", "items")
ITEM_REQUIRED = ("severity", "text")
ITEM_OPTIONAL = ("url", "prompt")


def _is_utc_iso(value):
"""True for an ISO-8601 timestamp that says, explicitly, it is UTC.

A naive timestamp is ambiguous across the dev box, CI runners and the
phone; a cockpit comparing ages across organs needs one clock, so only a
`Z` or `+00:00` suffix passes.
"""
if not isinstance(value, str):
return False
if value.endswith("Z"):
text = value[:-1] + "+00:00"
elif value.endswith("+00:00"):
text = value
else:
return False
try:
parsed = datetime.fromisoformat(text)
except ValueError:
return False
return parsed.utcoffset() is not None and parsed.utcoffset().total_seconds() == 0


def _one_line(value):
return isinstance(value, str) and value.strip() != "" and "\n" not in value \
and "\r" not in value


def validate_state(obj):
"""Every way `obj` breaks the v1 contract, as readable strings.

An empty list means valid. Errors are collected rather than raised one at
a time so a publishing workflow can show the whole problem in one run.
"""
if not isinstance(obj, dict):
return ["top level must be a JSON object"]
errors = [f"missing required key: {k}" for k in REQUIRED if k not in obj]

if "schema_version" in obj:
sv = obj["schema_version"]
if isinstance(sv, bool) or sv != SCHEMA_VERSION:
errors.append(f"schema_version must be {SCHEMA_VERSION} (got {sv!r})")
for key in ("organ", "repo", "pages_url"):
if key in obj and not (isinstance(obj[key], str) and obj[key].strip()):
errors.append(f"{key} must be a non-empty string")
if "status" in obj and obj["status"] not in STATUSES:
errors.append(f"status must be one of {'|'.join(STATUSES)} "
f"(got {obj['status']!r})")
if "headline" in obj and not _one_line(obj["headline"]):
errors.append("headline must be a single non-empty line")
if "updated" in obj and not _is_utc_iso(obj["updated"]):
errors.append("updated must be an ISO-8601 UTC timestamp ending in Z "
f"or +00:00 (got {obj['updated']!r})")

items = obj.get("items")
if "items" in obj and not isinstance(items, list):
errors.append("items must be a list")
items = []
for i, item in enumerate(items or []):
where = f"items[{i}]"
if not isinstance(item, dict):
errors.append(f"{where} must be an object")
continue
errors += [f"{where} missing required key: {k}"
for k in ITEM_REQUIRED if k not in item]
if "severity" in item and item["severity"] not in SEVERITIES:
errors.append(f"{where}.severity must be one of "
f"{'|'.join(SEVERITIES)} (got {item['severity']!r})")
if "text" in item and not _one_line(item["text"]):
errors.append(f"{where}.text must be a single non-empty line")
for k in ITEM_OPTIONAL:
if item.get(k) is not None and not isinstance(item[k], str):
errors.append(f"{where}.{k} must be a string or null")
return errors


def build_state(organ, repo, status, headline, updated, pages_url, items=()):
"""A validated v1 state dict — the one constructor organs should use.

Raises ValueError listing every contract break, so a renderer cannot
publish a feed the cockpit would reject.
"""
state = {
"schema_version": SCHEMA_VERSION,
"organ": organ,
"repo": repo,
"status": status,
"headline": headline,
"updated": updated,
"pages_url": pages_url,
"items": [dict(item) for item in items],
}
errors = validate_state(state)
if errors:
raise ValueError("invalid state: " + "; ".join(errors))
return state


def main(argv=None):
argv = sys.argv[1:] if argv is None else argv
if len(argv) != 1 or argv[0] in ("-h", "--help"):
print("usage: _state.py <state.json | ->", file=sys.stderr)
return 1
source = argv[0]
try:
text = sys.stdin.read() if source == "-" else \
open(source, encoding="utf-8").read()
obj = json.loads(text)
except (OSError, ValueError) as e:
print(f"state: unreadable ({e})")
return 1
errors = validate_state(obj)
for err in errors:
print(f"state: {err}")
if errors:
return 1
print("state: ok")
return 0


if __name__ == "__main__":
sys.exit(main())
3 changes: 2 additions & 1 deletion board/board.sh
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
# board.sh --html # the one-tap html page
# board.sh --json # the raw surface
# board.sh --badge # badge.json (the cross-board headline contract)
# board.sh --apply [--out DIR] # write index.html + badge.json +
# board.sh --state # state.json (the organ cockpit feed, _state.py)
# board.sh --apply [--out DIR] # write index.html + badge.json + state.json +
# # board.json + board.md (default _site/)
# board.sh publish [--dry-run] [--no-hygiene]
# # dev-box leg (_publish.py): distill hygiene +
Expand Down
43 changes: 43 additions & 0 deletions board/state_schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"$comment": "The organ cockpit feed, contract v1 (PyAutoBrain#416). Every organ board publishes state.json beside its badge.json (the one-line headline contract) and its board.json (organ-specific detail). state.json is the per-organ MACHINE surface the cockpit and the phone read: one status, one headline, and the rows that ask something of a human. This file documents the contract; board/_state.py is the executable validator (stdlib only, no jsonschema) — `python PyAutoBrain/board/_state.py _site/state.json` from any cwd.",
"description": "Organ cockpit state feed (schema_version 1).",
"schema_version": 1,
"fields": {
"schema_version": "integer, always 1 for this contract; a breaking change bumps it and the validator refuses unknown versions",
"organ": "string, the organ key (brain, heart, hands, mind, memory, ...) — the same key board/_theme.py ORGANS uses",
"repo": "string, the organ's repository name (e.g. PyAutoBrain)",
"status": "one of green | yellow | red | stale | grey. green = read everything, found nothing; yellow = needs attention; red = blocking; stale = the evidence is too old to trust; grey = could not read enough to say",
"headline": "string, one non-empty line — the sentence a reader acts on",
"updated": "string, ISO-8601 UTC timestamp of the render, ending in Z or +00:00 (e.g. 2026-09-26T05:31:00Z)",
"pages_url": "string, the organ's published board page",
"items": "array of objects, the actionable rows, most urgent first; may be empty",
"items[].severity": "one of red | yellow | info",
"items[].text": "string, one non-empty line describing the row",
"items[].url": "optional string or null — the GitHub link that evidences the row (run, issue, PR)",
"items[].prompt": "optional string or null — the copy-for-Claude payload, verbatim from the organ that owns the signal"
},
"required": ["schema_version", "organ", "repo", "status", "headline", "updated", "pages_url", "items"],
"example": {
"schema_version": 1,
"organ": "brain",
"repo": "PyAutoBrain",
"status": "red",
"headline": "2 need you",
"updated": "2026-09-26T05:31:00Z",
"pages_url": "https://pyautolabs.github.io/PyAutoBrain/",
"items": [
{
"severity": "red",
"text": "Heart: PyAutoLens nightly smoke red",
"url": "https://github.com/PyAutoLabs/PyAutoHeart/actions/runs/123",
"prompt": "/bug Heart board: PyAutoLens nightly smoke red — https://github.com/PyAutoLabs/PyAutoHeart/actions/runs/123"
},
{
"severity": "yellow",
"text": "community: PyAutoLabs/PyAutoLens#1 awaiting a reply (3d)",
"url": "https://github.com/PyAutoLabs/PyAutoLens/issues/1",
"prompt": "/community triage PyAutoLabs/PyAutoLens#1"
}
]
}
}
Loading
Loading