From 340a26e6057795573023591a46d11f11cb16c757 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 26 Sep 2026 12:09:02 +0100 Subject: [PATCH] feat(board): organ cockpit state.json feed contract (#416) Add the v1 cockpit feed: board/state_schema.json documents the contract, board/_state.py enforces it (validate_state, build_state, and a stdlib CLI runnable from any cwd so sibling organ workflows can validate before publishing). The Brain board emits it via render_state (--state), and --apply now writes state.json beside badge.json; badge.json and board.json are unchanged. Status and headline mirror the badge; items compose the rows the board already renders (Heart blockers, failed/blocked/unreadable overnight runs, community waits, degraded legs) with their own prompts. Co-Authored-By: Claude Fable 5.1 --- board/AGENTS.md | 16 ++- board/_board.py | 113 ++++++++++++++++- board/_state.py | 160 ++++++++++++++++++++++++ board/board.sh | 3 +- board/state_schema.json | 43 +++++++ tests/fixtures/state/brain.json | 23 ++++ tests/fixtures/state/heart.json | 23 ++++ tests/test_state_feed.py | 215 ++++++++++++++++++++++++++++++++ 8 files changed, 591 insertions(+), 5 deletions(-) create mode 100644 board/_state.py create mode 100644 board/state_schema.json create mode 100644 tests/fixtures/state/brain.json create mode 100644 tests/fixtures/state/heart.json create mode 100644 tests/test_state_feed.py diff --git a/board/AGENTS.md b/board/AGENTS.md index 5532b22e..287a335c 100644 --- a/board/AGENTS.md +++ b/board/AGENTS.md @@ -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 diff --git a/board/_board.py b/board/_board.py index c8bc78b0..ea6c4552 100755 --- a/board/_board.py +++ b/board/_board.py @@ -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 @@ -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)" @@ -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: " @@ -1687,9 +1790,11 @@ 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="") @@ -1697,6 +1802,8 @@ def main(): 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)) diff --git a/board/_state.py b/board/_state.py new file mode 100644 index 00000000..0ded70f7 --- /dev/null +++ b/board/_state.py @@ -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 ", 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()) diff --git a/board/board.sh b/board/board.sh index 0d5b6ac9..93fe5234 100755 --- a/board/board.sh +++ b/board/board.sh @@ -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 + diff --git a/board/state_schema.json b/board/state_schema.json new file mode 100644 index 00000000..e49b9200 --- /dev/null +++ b/board/state_schema.json @@ -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" + } + ] + } +} diff --git a/tests/fixtures/state/brain.json b/tests/fixtures/state/brain.json new file mode 100644 index 00000000..3e7f933e --- /dev/null +++ b/tests/fixtures/state/brain.json @@ -0,0 +1,23 @@ +{ + "schema_version": 1, + "organ": "brain", + "repo": "PyAutoBrain", + "status": "yellow", + "headline": "2 need you", + "updated": "2026-09-26T05:31:00Z", + "pages_url": "https://pyautolabs.github.io/PyAutoBrain/", + "items": [ + { + "severity": "yellow", + "text": "overnight: PyAutoLabs/PyAutoBrain/nightly-release.yml blocked at a gate", + "url": "https://github.com/PyAutoLabs/PyAutoBrain/actions/runs/18012345678", + "prompt": null + }, + { + "severity": "info", + "text": "community: PyAutoLabs/PyAutoLens#512 awaiting a reply (2d)", + "url": "https://github.com/PyAutoLabs/PyAutoLens/issues/512", + "prompt": "/community triage PyAutoLabs/PyAutoLens#512" + } + ] +} diff --git a/tests/fixtures/state/heart.json b/tests/fixtures/state/heart.json new file mode 100644 index 00000000..a8c50485 --- /dev/null +++ b/tests/fixtures/state/heart.json @@ -0,0 +1,23 @@ +{ + "schema_version": 1, + "organ": "heart", + "repo": "PyAutoHeart", + "status": "red", + "headline": "RED — 2 blockers", + "updated": "2026-09-26T04:12:00+00:00", + "pages_url": "https://pyautolabs.github.io/PyAutoHeart/", + "items": [ + { + "severity": "red", + "text": "PyAutoLens: workspace smoke red (3 scripts failed)", + "url": "https://github.com/PyAutoLabs/PyAutoHeart/actions/runs/18011111111", + "prompt": "/bug Heart board: PyAutoLens workspace smoke red — https://github.com/PyAutoLabs/PyAutoHeart/actions/runs/18011111111" + }, + { + "severity": "yellow", + "text": "PyAutoGalaxy: python matrix 3.13 leg failed", + "url": "https://github.com/PyAutoLabs/PyAutoHands/actions/runs/18011122222", + "prompt": "/bug Heart board: PyAutoGalaxy python matrix 3.13 leg failed — https://github.com/PyAutoLabs/PyAutoHands/actions/runs/18011122222" + } + ] +} diff --git a/tests/test_state_feed.py b/tests/test_state_feed.py new file mode 100644 index 00000000..69f269d7 --- /dev/null +++ b/tests/test_state_feed.py @@ -0,0 +1,215 @@ +"""Contract tests for the organ cockpit feed (board/_state.py, state.json v1). + +state.json is the one shape every organ board publishes for the cockpit and +the phone. These tests pin the contract from both ends: the validator accepts +the realistic fixtures and refuses each way a feed can break, the CLI works +from any cwd (sibling organ workflows run it from their own checkout), and the +Brain board's own render_state output passes the same validator. + +Hermetic: the board legs reuse test_board.py's fabricated workspace and stub +`gh` — no network, no real checkouts, fake org names per the tenant firewall. +""" + +import copy +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +BRAIN_HOME = Path(__file__).resolve().parents[1] +STATE_CLI = BRAIN_HOME / "board" / "_state.py" +FIXTURES = Path(__file__).resolve().parent / "fixtures" / "state" +sys.path.insert(0, str(BRAIN_HOME / "board")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import _state # noqa: E402 +from test_board import ( # noqa: E402 + HEART_BOARD_JSON, _default_fixtures, _fabricate, _run, +) + + +def _fixture(name): + return json.loads((FIXTURES / f"{name}.json").read_text()) + + +# ------------------------------------------------------------- validator ---- + + +@pytest.mark.parametrize("name", ["brain", "heart"]) +def test_the_fixtures_satisfy_the_contract(name): + assert _state.validate_state(_fixture(name)) == [] + + +def test_the_schema_example_satisfies_the_contract(): + schema = json.loads((BRAIN_HOME / "board" / "state_schema.json").read_text()) + assert schema["schema_version"] == _state.SCHEMA_VERSION + assert tuple(schema["required"]) == _state.REQUIRED + assert _state.validate_state(schema["example"]) == [] + + +def test_the_heart_fixture_carries_linked_rows_with_a_bug_prompt(): + heart = _fixture("heart") + assert (heart["organ"], heart["repo"], heart["status"]) == \ + ("heart", "PyAutoHeart", "red") + assert len(heart["items"]) == 2 + for item in heart["items"]: + assert item["url"].startswith("https://github.com/") + assert "/actions/runs/" in item["url"] + assert item["prompt"].startswith("/bug ") + + +def _broken(mutate): + state = copy.deepcopy(_fixture("brain")) + mutate(state) + return _state.validate_state(state) + + +def test_an_unknown_status_is_refused(): + errors = _broken(lambda s: s.update(status="amber")) + assert any("status" in e for e in errors) + + +def test_a_missing_required_key_is_refused(): + errors = _broken(lambda s: s.pop("pages_url")) + assert "missing required key: pages_url" in errors + + +@pytest.mark.parametrize("updated", [ + "2026-09-26T05:31:00", # naive — which clock? + "2026-09-26T06:31:00+01:00", # a real instant, but not UTC + "yesterday morning", # not a timestamp at all + "2026-13-40T99:00:00Z", # UTC-shaped but unparseable +]) +def test_updated_must_be_parseable_utc(updated): + errors = _broken(lambda s: s.update(updated=updated)) + assert any(e.startswith("updated") for e in errors), updated + + +def test_an_item_with_an_unknown_severity_is_refused(): + errors = _broken(lambda s: s["items"][0].update(severity="critical")) + assert any("items[0].severity" in e for e in errors) + + +def test_a_multi_line_headline_is_refused(): + errors = _broken(lambda s: s.update(headline="2 need you\nand more")) + assert any("headline" in e for e in errors) + + +def test_a_wrong_schema_version_is_refused(): + errors = _broken(lambda s: s.update(schema_version=2)) + assert any("schema_version" in e for e in errors) + + +def test_build_state_round_trips(): + src = _fixture("heart") + built = _state.build_state( + src["organ"], src["repo"], src["status"], src["headline"], + src["updated"], src["pages_url"], src["items"]) + assert built == src + assert json.loads(json.dumps(built)) == src + + +def test_build_state_refuses_what_it_cannot_publish(): + with pytest.raises(ValueError) as exc: + _state.build_state("brain", "PyAutoBrain", "purple", "x", + "2026-09-26T05:31:00Z", "https://example.invalid/") + assert "status" in str(exc.value) + + +# ------------------------------------------------------------------- CLI ---- + + +def _cli(arg, cwd, stdin=None): + return subprocess.run([sys.executable, str(STATE_CLI), arg], cwd=cwd, + capture_output=True, text=True, input=stdin) + + +def test_cli_accepts_the_fixture_from_any_cwd(tmp_path): + r = _cli(str(FIXTURES / "heart.json"), tmp_path) + assert r.returncode == 0, r.stdout + r.stderr + assert r.stdout.strip() == "state: ok" + + +def test_cli_reads_stdin(tmp_path): + r = _cli("-", tmp_path, stdin=(FIXTURES / "brain.json").read_text()) + assert r.returncode == 0 and r.stdout.strip() == "state: ok" + + +def test_cli_names_every_break_and_exits_1(tmp_path): + broken = _fixture("brain") + broken["status"] = "amber" + del broken["updated"] + path = tmp_path / "state.json" + path.write_text(json.dumps(broken)) + r = _cli("state.json", tmp_path) + assert r.returncode == 1 + lines = r.stdout.strip().splitlines() + assert len(lines) == 2 and all(line.startswith("state: ") for line in lines) + assert "ok" not in r.stdout + + +def test_cli_refuses_unreadable_json(tmp_path): + (tmp_path / "state.json").write_text("{not json") + r = _cli("state.json", tmp_path) + assert r.returncode == 1 and r.stdout.startswith("state: unreadable") + + +# ------------------------------------------------------ the Brain's feed ---- + + +def test_the_brain_board_state_satisfies_the_contract(tmp_path): + stub = _fabricate(tmp_path, _default_fixtures()) + r = _run(["--state"], tmp_path, stub) + assert r.returncode == 0, r.stderr + state = json.loads(r.stdout) + assert _state.validate_state(state) == [] + assert state["organ"] == "brain" + # The feed agrees with the badge beside it — one verdict, two shapes. + badge = json.loads(_run(["--badge"], tmp_path, stub).stdout) + assert state["headline"] == badge["message"] + assert state["status"] == {"red": "red", "orange": "yellow", + "lightgrey": "grey", + "brightgreen": "green"}[badge["color"]] + + +def test_a_red_heart_blocker_is_a_red_item_with_its_link_and_prompt(tmp_path): + stub = _fabricate(tmp_path, _default_fixtures()) + state = json.loads(_run(["--state"], tmp_path, stub).stdout) + blocker = HEART_BOARD_JSON["blockers"][0] + matches = [i for i in state["items"] if blocker["text"] in i["text"]] + assert matches, state["items"] + item = matches[0] + assert item["severity"] == "red" + assert item["url"] == blocker["run_url"] + assert item["prompt"] == blocker["prompt"] # verbatim, never re-derived + assert state["items"][0]["severity"] == "red" # most urgent first + + +def test_a_failed_overnight_run_is_a_red_item_with_its_run_url(tmp_path): + from test_board import _run_json + stub = _fabricate(tmp_path, _default_fixtures(**{ + "runs.json": _run_json("failure")})) + state = json.loads(_run(["--state"], tmp_path, stub).stdout) + assert _state.validate_state(state) == [] + assert state["status"] == "red" + overnight = [i for i in state["items"] if i["text"].startswith("overnight:")] + assert overnight and all(i["severity"] == "red" for i in overnight) + assert overnight[0]["url"] == "https://example.invalid/run/1" + # The page's own 📋 payload for the row, not a second phrasing of it. + page = _run(["--html"], tmp_path, stub).stdout + assert f'data-cmd="{overnight[0]["prompt"]}"' in page + + +def test_apply_writes_a_valid_state_json_beside_the_badge(tmp_path): + stub = _fabricate(tmp_path, _default_fixtures()) + out = tmp_path / "site" + r = _run(["--apply", "--out", str(out)], tmp_path, stub) + assert r.returncode == 0, r.stderr + assert "state.json" in r.stdout + assert (out / "badge.json").is_file() + state = json.loads((out / "state.json").read_text()) + assert _state.validate_state(state) == [] + cli = _cli(str(out / "state.json"), tmp_path) + assert cli.returncode == 0 and cli.stdout.strip() == "state: ok"