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
36 changes: 36 additions & 0 deletions board/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,3 +247,39 @@ The allowlist is per environment; there is no organization-level one, so an
environment you add later starts from the defaults again. And none of this
installs `gh` — that is not in the image at all, so GitHub still goes through
the MCP tools (`PyAutoBrain/skills/GITHUB_ACCESS.md`).

## Human-first, machine-readable cockpit evolution

Keep the cockpit a presentation of owner-published state. Extend the shared
`state.json` contract incrementally when it improves the human interface; do
not infer truth from rendered HTML or duplicate an organ's readiness policy.
The optional v1 additions in `state_schema.json` describe attention items with
stable `id`, canonical `state`, `reason`, `actions`, `recommended_action_id`,
and explicit `requires_human_decision` / `decision` when the source knows a
human choice is needed. Legacy producers and colour fields remain supported.

Canonical item states mean: `healthy` (checks satisfied), `active` (work in
progress), `stale` (evidence expired), `blocked` (a prerequisite prevents work),
`failed` (an operation failed), `action_required` (an explicit next intervention
is needed), and `unknown` (insufficient evidence). Severity is a separate fact.
Never map every red colour to failed or every blocked gate to human judgement.
Overnight workflow rows are the first producer: stable repo/workflow identity,
GitHub conclusion or gate annotation as reason, and run URL as evidence. This
is an attention list, not an inventory; successful unblocked runs are omitted.
Cancellation is unknown, not proof of failure or a request to restart.

Actions exist as descriptors independent of buttons: id, label, kind
(`link`, `command`, `prompt`) and target. Commands/prompts are copied for a human
to invoke through existing tools; a prompt is a manual handoff, not executable
shell. Safety is descriptive (`read_only`, `requires_approval`,
`scientific_judgement`, `never_automatic`, `unclassified`), never authorization.
Absent safety means unclassified. Detection, description and recommendation
execute nothing. No generic executor or new permissions infrastructure is added.

`updated` is the feed generation time, not last success or source-check time.
Optional `valid_until` is an owner-declared deadline at or after `updated`;
absence supplies no expiry policy. Preserve evidence URLs and do not invent
source timestamps. Stable identities and structured values can support later
comparisons without a message bus or persistent monitoring service. A future
executor must retain execution evidence; copied prompts do not claim an action
was run or succeeded.
66 changes: 48 additions & 18 deletions board/_board.py
Original file line number Diff line number Diff line change
Expand Up @@ -1061,6 +1061,51 @@ def _iso_generated(data):
return dt.strftime("%Y-%m-%dT%H:%M:%SZ")


def _overnight_state_item(r):
"""Describe an observation and existing next steps; never execute them.

Identity follows the workflow across runs. The run URL is evidence, not
identity, so future consumers can compare records without scraping text.
"""
where = f"{r['repo']}/{r['workflow']}"
item = {"id": f"overnight:{where}", "url": r.get("url"),
"actions": [], "prompt": None}
conclusion = r.get("conclusion")
if r.get("unreadable"):
item.update(severity="info", state="unknown",
text=f"overnight: could not read {where}",
reason="The workflow runs endpoint could not be read.")
elif r.get("blocked"):
item.update(severity="yellow", state="blocked",
text=f"overnight: {where} blocked at a gate",
reason=" ".join((r.get("blocked_reason") or
"A successful gate step reported that work was blocked.").split()))
elif conclusion in (None, "success"):
return None # This feed is an attention list, not a run inventory.
else:
canonical = {"failure": "failed", "timed_out": "failed",
"startup_failure": "failed", "action_required": "action_required",
"queued": "active", "in_progress": "active", "waiting": "active",
"pending": "active", "requested": "active"}.get(conclusion, "unknown")
prompt = (f"/bug overnight: {where} concluded "
f"{conclusion} — {r.get('url') or 'no run url'}")
item.update(severity="info" if canonical == "active" else "red",
state=canonical, text=f"overnight: {where} {conclusion}",
reason=f"GitHub reports the latest workflow run as {conclusion}.")
if canonical != "active":
item["prompt"] = prompt # Keep the legacy copy payload compatible.
item["actions"].append({"id": "investigate", "label": "Copy investigation prompt",
"kind": "prompt", "target": prompt,
"safety": "requires_approval"})
item["recommended_action_id"] = "investigate"
if r.get("url"):
item["actions"].append({"id": "view-run", "label": "View run",
"kind": "link", "target": r["url"], "safety": "read_only"})
item.setdefault("recommended_action_id", "view-run")
# A blocked gate alone does not prove a scientific/design decision is needed.
return item


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
Expand All @@ -1075,24 +1120,9 @@ def _state_items(data):
"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})
item = _overnight_state_item(r)
if item is not None:
items.append(item)
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 ""
Expand Down
71 changes: 70 additions & 1 deletion board/_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@
SCHEMA_VERSION = 1
STATUSES = ("green", "yellow", "red", "stale", "grey")
SEVERITIES = ("red", "yellow", "info")
ITEM_STATES = ("healthy", "active", "stale", "blocked", "failed",
"action_required", "unknown")
ACTION_KINDS = ("link", "command", "prompt")
ACTION_SAFETY = ("read_only", "requires_approval", "scientific_judgement",
"never_automatic", "unclassified")
REQUIRED = ("schema_version", "organ", "repo", "status", "headline",
"updated", "pages_url", "items")
ITEM_REQUIRED = ("severity", "text")
Expand Down Expand Up @@ -64,6 +69,54 @@ def _one_line(value):
and "\r" not in value


def _item_metadata(item, where):
"""Optional v1 additions; absence means unknown, never authorization."""
errors = []
for key in ("id", "reason", "decision", "recommended_action_id"):
if key in item and not _one_line(item[key]):
errors.append(f"{where}.{key} must be a non-empty single line")
if "state" in item and item["state"] not in ITEM_STATES:
errors.append(f"{where}.state must be one of {'|'.join(ITEM_STATES)}")
if "requires_human_decision" in item:
if not isinstance(item["requires_human_decision"], bool):
errors.append(f"{where}.requires_human_decision must be boolean")
elif item["requires_human_decision"] and not _one_line(item.get("decision")):
errors.append(f"{where}.decision is required for a human decision")
actions = item.get("actions", [])
if not isinstance(actions, list):
return errors + [f"{where}.actions must be a list"]
ids = []
for n, action in enumerate(actions):
loc = f"{where}.actions[{n}]"
if not isinstance(action, dict):
errors.append(f"{loc} must be an object")
continue
for key in ("id", "label", "target"):
if not _one_line(action.get(key)):
errors.append(f"{loc}.{key} must be a non-empty single line")
if action.get("kind") not in ACTION_KINDS:
errors.append(f"{loc}.kind must be one of {'|'.join(ACTION_KINDS)}")
if "safety" in action and action["safety"] not in ACTION_SAFETY:
errors.append(f"{loc}.safety must be one of {'|'.join(ACTION_SAFETY)}")
if action.get("kind") == "link":
from urllib.parse import urlsplit
try:
url = urlsplit(action.get("target", ""))
valid = url.scheme in ("http", "https") and bool(url.netloc)
except (ValueError, TypeError, AttributeError):
valid = False
if not valid:
errors.append(f"{loc}.target must be an HTTP(S) URL")
aid = action.get("id")
if isinstance(aid, str):
if aid in ids:
errors.append(f"{loc}.id must be unique within the item")
ids.append(aid)
if "recommended_action_id" in item and item["recommended_action_id"] not in ids:
errors.append(f"{where}.recommended_action_id must name an action")
return errors


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

Expand All @@ -89,11 +142,19 @@ def validate_state(obj):
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})")
if "valid_until" in obj:
if not _is_utc_iso(obj["valid_until"]):
errors.append("valid_until must be an ISO-8601 UTC timestamp")
elif _is_utc_iso(obj.get("updated")) and \
datetime.fromisoformat(obj["valid_until"].replace("Z", "+00:00")) < \
datetime.fromisoformat(obj["updated"].replace("Z", "+00:00")):
errors.append("valid_until must not precede updated")

items = obj.get("items")
if "items" in obj and not isinstance(items, list):
errors.append("items must be a list")
items = []
ids = []
for i, item in enumerate(items or []):
where = f"items[{i}]"
if not isinstance(item, dict):
Expand All @@ -109,10 +170,16 @@ def validate_state(obj):
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")
errors.extend(_item_metadata(item, where))
if isinstance(item.get("id"), str):
if item["id"] in ids:
errors.append(f"{where}.id must be unique within the feed")
ids.append(item["id"])
return errors


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

Raises ValueError listing every contract break, so a renderer cannot
Expand All @@ -128,6 +195,8 @@ def build_state(organ, repo, status, headline, updated, pages_url, items=()):
"pages_url": pages_url,
"items": [dict(item) for item in items],
}
if valid_until is not None:
state["valid_until"] = valid_until
errors = validate_state(state)
if errors:
raise ValueError("invalid state: " + "; ".join(errors))
Expand Down
22 changes: 20 additions & 2 deletions board/state_schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,27 @@
"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"
"items[].prompt": "optional string or null — the copy-for-Claude payload, verbatim from the organ that owns the signal",
"valid_until": "optional ISO-8601 UTC timestamp >= updated; producer-declared freshness deadline. Missing means no declared age policy, never a guessed global TTL.",
"items[].id": "optional non-empty single line, unique within feed; stable workstream identity across runs, independent of text and order",
"items[].state": "optional canonical workflow state: healthy | active | stale | blocked | failed | action_required | unknown. Separate from severity and the legacy organ status; no generic colour-to-workflow mapping.",
"items[].reason": "optional non-empty single line explaining the observed evidence; url retains its evidence link role",
"items[].actions": "optional list of action descriptors: id (unique within item), label, kind (link | command | prompt), target (non-empty single line), optional safety. link targets must be HTTP(S). A prompt is a manual handoff, not an executable command.",
"items[].actions[].safety": "optional read_only | requires_approval | scientific_judgement | never_automatic | unclassified; absent means unclassified. Descriptive metadata, never authorization. No action is executed by detection or rendering.",
"items[].recommended_action_id": "optional id naming one of this item’s actions",
"items[].requires_human_decision": "optional boolean; absence means unspecified, not false. true requires decision text; a blocked workflow alone does not imply human judgement.",
"items[].decision": "optional non-empty single line naming the human choice; required when requires_human_decision is true"
},
"required": ["schema_version", "organ", "repo", "status", "headline", "updated", "pages_url", "items"],
"required": [
"schema_version",
"organ",
"repo",
"status",
"headline",
"updated",
"pages_url",
"items"
],
"example": {
"schema_version": 1,
"organ": "brain",
Expand Down
73 changes: 73 additions & 0 deletions tests/test_state_feed.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,76 @@ def test_apply_writes_a_valid_state_json_beside_the_badge(tmp_path):
assert _state.validate_state(state) == []
cli = _cli(str(out / "state.json"), tmp_path)
assert cli.returncode == 0 and cli.stdout.strip() == "state: ok"


@pytest.mark.parametrize('metadata', [
{'state': 'purple'}, {'id': ''}, {'reason': 'two\nlines'},
{'requires_human_decision': 'yes'}, {'requires_human_decision': True},
{'actions': None}, {'actions': [None]},
{'actions': [{'id': 'x', 'label': 'Run', 'kind': 'shell', 'target': 'echo x'}]},
{'actions': [{'id': 'x', 'label': 'Run', 'kind': 'prompt', 'target': 'x', 'safety': True}]},
{'actions': [{'id': 'x', 'label': 'Run', 'kind': 'link', 'target': 'javascript:alert(1)'}]},
{'recommended_action_id': 'missing'},
])
def test_optional_metadata_is_validated_when_present(metadata):
assert _broken(lambda s: s['items'][0].update(metadata))


def test_decision_and_action_round_trip_without_invented_safety():
s = _fixture('brain')
s['items'][0].update(id='decision:strategy', state='action_required',
requires_human_decision=True, decision='Which strategy should we use?',
actions=[{'id': 'context', 'label': 'Read context', 'kind': 'link',
'target': 'https://example.invalid/context'}], recommended_action_id='context')
assert _state.validate_state(s) == []
assert 'safety' not in s['items'][0]['actions'][0]
s['items'].append(copy.deepcopy(s['items'][0]))
assert any('unique within the feed' in e for e in _state.validate_state(s))
s['items'].pop()
s['items'][0]['actions'] *= 2
assert any('unique within the item' in e for e in _state.validate_state(s))


def test_producer_declared_freshness_deadline():
s = _fixture('brain')
s['valid_until'] = '2026-10-01T00:00:00Z'
assert _state.validate_state(s) == []
s['valid_until'] = '2020-01-01T00:00:00Z'
assert any('precede' in e for e in _state.validate_state(s))
s['valid_until'] = 'not a time'
assert any('valid_until' in e for e in _state.validate_state(s))


@pytest.mark.parametrize('conclusion,blocked,unreadable,expected', [
('failure', False, False, 'failed'), ('timed_out', False, False, 'failed'),
('success', True, False, 'blocked'), (None, False, True, 'unknown'),
('cancelled', False, False, 'unknown'), ('in_progress', False, False, 'active'),
('queued', False, False, 'active'), ('action_required', False, False, 'action_required'),
])
def test_overnight_state_preserves_evidence_and_distinguishes_outcomes(conclusion, blocked, unreadable, expected):
import _board
row = dict(repo='Example/Engine', workflow='nightly.yml', conclusion=conclusion,
blocked=blocked, unreadable=unreadable, blocked_reason='Gate blocked: approval missing',
url=None if unreadable else 'https://example.invalid/runs/1')
item = _board._overnight_state_item(row)
assert item['state'] == expected
assert item['url'] == row['url']
assert item['reason']
assert 'requires_human_decision' not in item
state = _fixture('brain')
state['items'] = [item]
assert _state.validate_state(state) == []
if blocked:
assert item['reason'] == row['blocked_reason']
assert item['recommended_action_id'] == 'view-run'
if expected == 'failed':
action = item['actions'][0]
assert action['kind'] == 'prompt' and action['target'] == item['prompt']
assert action['safety'] == 'requires_approval'
row['url'] = 'https://example.invalid/runs/2'
assert _board._overnight_state_item(row)['id'] == item['id']


def test_successful_overnight_work_adds_no_attention_noise():
import _board
assert _board._overnight_state_item(dict(repo='Example/Engine', workflow='nightly.yml', conclusion='success')) is None
Loading