From 5024a512b320d2eb7e54c297bcae2f43d582667e Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 9 Oct 2026 15:33:57 +0100 Subject: [PATCH] feat: make Scientist the concise cross-organ home --- .github/workflows/board_tests.yml | 1 + AGENTS.md | 17 +- README.md | 15 +- REPORTING.md | 67 ++++++++ scripts/organism_board.py | 266 ++++++++++++------------------ scripts/overview.js | 194 ++++++++++++++++++++++ tests/overview.cjs | 47 ++++++ tests/test_organism_board.py | 135 ++++++--------- 8 files changed, 493 insertions(+), 249 deletions(-) create mode 100644 REPORTING.md create mode 100644 scripts/overview.js create mode 100644 tests/overview.cjs diff --git a/.github/workflows/board_tests.yml b/.github/workflows/board_tests.yml index a9fd644..89ee247 100644 --- a/.github/workflows/board_tests.yml +++ b/.github/workflows/board_tests.yml @@ -19,3 +19,4 @@ jobs: python-version: '3.12' - run: python -m pip install pytest pyyaml - run: python -m pytest tests -q + - run: node --test tests/overview.cjs diff --git a/AGENTS.md b/AGENTS.md index 94274f6..00d624c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,10 +9,25 @@ Code loads it via the `@AGENTS.md` import in `CLAUDE.md`. **PyAutoScientist is the umbrella landing repo for the PyAuto organism** — a human-led AI software-development system. It presents the organism (what it is, how to fork it) through the docs and links in `README.md`; it is not a framework -you install, and it holds no organism code of its own. The organs that do the +you install, and owns the Scientist overview renderer and reporting guidance. The organs that do the work are peer repositories — see the body map in `PyAutoMind/repos.yaml` and the canonical boundaries in `PyAutoBrain/ORGANISM.md`. +## Scientist home and reporting + +The cockpit Scientist tab embeds this repository's dashboard. It is the entry +point for cross-organ summaries and coordination; individual organs retain +their authoritative records and task procedures. For a high-level summary over +the last 24 hours or another requested period, follow [REPORTING.md](REPORTING.md). +The copyable dashboard prompt points here. Current status cards are not a +historical activity ledger. + +The dashboard uses Brain's shared hero/panel, registry and state validator. +Its organ disclosures stay visible as a grid, without another outer disclosure +or duplicate organ navigation. Each expanded organ has at most three concise +rows. `scripts/overview.js` is inlined at render time and refreshes published +feeds without replacing open disclosures or prompt controls. + ## Editing rules - **The organ table in `README.md` is generated** from `PyAutoMind/repos.yaml` diff --git a/README.md b/README.md index fed093e..c703a43 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ **PyAutoScientist enables human-led, natural-language software development** — an experimental reference implementation by James Nightingale. Humans describe what the software should do, why it is needed, and how success should be judged; specialist AI agents help plan, implement, test, and prepare releases. Humans remain responsible for scientific objectives, contributor communication, and consequential decisions. Using this ecosystem is optional: you do not need to adopt PyAutoScientist or use AI to contribute to PyAutoLabs. See the **[PyAutoScientist Dashboard](https://pyautolabs.github.io/PyAutoScientist/)** -to watch the organism live and know where to work: it shows each organ's own -dashboard headline, topped by a "where to work next" hint (if the Heart is -green, you go pick a task on the Mind): +to monitor work across the organism: expand an organ for a concise status and +evidence links, or copy the Scientist prompt for a summary or cross-organ task. +Detailed records remain with their owners, including: - **[PyAutoMind Dashboard](https://pyautolabs.github.io/PyAutoMind/)**: planned and active development tasks on the scientist's mind. - **[PyAutoHeart Dashboard](https://pyautolabs.github.io/PyAutoHeart/)**: the health of every repository, rolled into the authoritative GREEN/STALE/YELLOW/RED release verdict. @@ -109,3 +109,12 @@ Each project keeps a community page listing community-built tools, tutorials and ## License Released under the [MIT License](https://opensource.org/licenses/MIT). Copyright (c) 2026 Jammy2211. + +## Work with your Scientist + +Use the Scientist tab in the [cockpit](https://pyautolabs.github.io/cockpit/#scientist) +for the organism overview and its copyable check-in prompt. Ask for a high-level +summary across all organs over the last 24 hours, a chosen date range, or help +coordinating work across organs. [Reporting guidance](REPORTING.md) defines +source coverage, event dates and concise evidence-linked summaries. Detailed +work and authoritative records remain with each organ. diff --git a/REPORTING.md b/REPORTING.md new file mode 100644 index 0000000..693c5f0 --- /dev/null +++ b/REPORTING.md @@ -0,0 +1,67 @@ +# Reports across the organism + +Scientist is the place to ask “What happened across all organs in the last +24 hours?” or “Summarize this week's work.” It joins evidence and coordinates +follow-through; the organs keep their authoritative records. + +## Establish the period + +Default an unspecified overview to the previous 24 hours, ending now. Honor a +requested duration or date range. State the exact start, end and timezone; +use the user's known timezone, or explicitly use UTC if unknown. Resolve +ambiguous boundaries with the user only when they materially affect the answer. + +Distinguish events **during that period** from the **current position**. An +older blocker can still need attention, but it is not new work in the period. +A feed's generation time or dashboard refresh is not a completion timestamp. + +## Cover the organs without loading every repository + +Discover organ membership from Brain's board registry and Mind's body map. +Read their published summaries first, then inspect the relevant dated owner +records. For an all-organ report, account for every listed organ, including +ones whose evidence is missing. Ordinary focused requests still load only the +relevant organs; this guide does not authorize a repository-wide source scan. + +| Owner | Evidence for a report | +|---|---| +| Brain | Coordination decisions and workflow outcomes | +| Mind | Task progress, issued/completed records, linked issues and PRs | +| Cortex | Project ledgers, run records and the scientist's recorded conclusions | +| Memory | Dated knowledge additions or revisions | +| Eyes | Published figure reviews, galleries and render evidence | +| Ears | Collection receipts and conversations needing a response | +| Heart | Dated checks, readiness changes and unresolved findings | +| Hands | Release records, published versions and failed release attempts | +| Pulse / Insight | Profiling/inference receipts, campaign progress and measured results | +| DNA / Nerves | Environment/compatibility observations and configuration work | +| Broca | Assistant evaluation and upkeep evidence | +| Gut | Cleanup receipts and pending disposal decisions | + +Use each owner's entry guidance to locate its actual records; do not assume +all boards expose the same history endpoint. Current state feeds alone cannot +establish historical coverage. Git activity is supporting evidence, not proof +of completed work: distinguish proposed, committed, merged, published and +scientifically accepted outcomes. A release, a merged task and a successful +scientific run are different kinds of result. + +## Write the summary + +Lead with a few high-level outcomes, then active work/blockers and decisions +or useful next steps. Link each significant outcome to its owning evidence, +with an event date where available. Combine one task appearing in several +organs into one account; do not count its issue, PR and release as three tasks. +Keep domain judgments with their owner. Report scientific interpretations only +when requested, and distinguish them from the scientist's accepted conclusions. + +End with a short coverage note: organs checked, sources that cover the period, +and missing/stale/unavailable history. Say “no recorded activity” only when +records for the period were checked; otherwise say “history unavailable.” Do +not turn an unavailable source into an all-clear. Do not imply exhaustive +coverage when access or retention prevents it. Avoid a long row for every quiet +organ unless the user requests that detail. + +A requested summary is read-only. Follow-up work uses the owning workflow and +existing approval rules; the request does not authorize compute, replies, +merges or releases. Do not add recurring collection, a second task registry or +persistent monitoring to produce a one-off report. diff --git a/scripts/organism_board.py b/scripts/organism_board.py index 96dbc8d..8c7c695 100644 --- a/scripts/organism_board.py +++ b/scripts/organism_board.py @@ -1,17 +1,10 @@ """scripts/organism_board.py — the PyAutoScientist Dashboard. -The umbrella ROUTER over the organism's live dashboards: one row per organ -board — Brain (operations), Mind (tasks), Heart (health), Hands (releases), -Memory (knowledge) — each carrying that board's own live headline and link, -topped by a "where to work next" banner keyed off the Heart's verdict (Heart -red/yellow → start at the health board; green → pick a task on the Mind -board). A glance here tells you WHICH board to open; the work happens there. - -**Sources** (plain HTTPS, no tokens): the Heart/Hands/Memory boards each -publish a shields ``badge.json`` beside their page — their own headline in -their own words — and the Mind's counts are parsed from its committed -``dashboard.md``. Every row degrades to "unavailable" honestly; nothing is -recomputed here (each organ's board stays the authority on itself). +The Scientist home presents concise disclosures over owner-published state.json +feeds. Brain supplies the shared theme, organ registry and feed validator. +The browser refreshes feeds without resetting open cards or prompt controls; +the publication snapshot remains a labelled fallback without JavaScript. +Scientist coordinates and reports; the organs retain their records and work. **Identity** derives from ``git remote`` (an adopting fork gets its own URLs for free). Rendered fresh by ``.github/workflows/organism_board.yml`` into @@ -25,6 +18,7 @@ from __future__ import annotations +import concurrent.futures import datetime import html as _html import json @@ -46,12 +40,19 @@ # PyAuto tools resolve each other. CHECKIN_PROMPT = ( "Use this chat as an ongoing entry point to PyAutoLabs. Read PyAutoScientist/AGENTS.md " - "and use the board skill to inspect relevant operational evidence. Load other organs and " + "and PyAutoScientist/REPORTING.md. Use the board skill to inspect relevant operational evidence. Load other organs and " "project context as the request requires.\n\n" "When I give no particular direction, provide a concise overview of the organism’s " - "current position: significant progress, blockers, decisions needing my attention and " + "work across all organs over the last 24 hours, plus its current position: significant progress, blockers, decisions needing my attention and " "useful next steps. Check evidence freshness and coverage, linking to the owning boards " "rather than reproducing every queue.\n\n" + "For a summary over a given time period, use that period instead of the last 24 hours. " + "State the start, end and timezone. Check dated records in every organ, distinguish " + "completed outcomes from work still in progress and decisions awaiting me, and link " + "the evidence. Deduplicate work spanning organs. A dashboard refresh is not a completed " + "event; current snapshots alone cannot establish a historical summary. Report coverage " + "gaps separately from verified inactivity, and separate events within the period from " + "older blockers that remain open. Keep the summary high level.\n\n" "When I supply a question, idea or task, make that the main focus. Help me clarify what I " "want to achieve and identify the appropriate organ, project and workflow. Explain the " "routing briefly and continue through it in this conversation where possible. Do not " @@ -93,8 +94,8 @@ def _workspace_root() -> Path: def theme(): """The shared theme module, or a RuntimeError naming the fix. - Only the html path needs it; ``--md``/``--badge``/``--json`` never call - here, so the digest keeps working with no PyAutoBrain in reach. + The collector uses its canonical board registry and matching state validator; + the HTML renderer also uses its branding and orchestration controls. """ for cand in (os.environ.get("PYAUTO_BRAIN"), HOME / "PyAutoBrain", HOME.parent / "PyAutoBrain", @@ -113,21 +114,16 @@ def theme(): "— check PyAutoBrain out beside this repo or set PYAUTO_BRAIN") -# The five boards, in routing order. (name, repo, what the board is, -# the door command a 📋 chip copies.) Brain publishes the same badge.json -# headline contract as Heart/Hands/Memory (brain_board.yml). -BOARDS = ( - ("Brain", "PyAutoBrain", "operations — the morning door: what needs you", "Use the board skill."), - ("Mind", "PyAutoMind", "tasks — pick what to work on", "Use the start-dev skill. "), - ("Heart", "PyAutoHeart", "health — is the organism ok?", "Use the health skill."), - ("Hands", "PyAutoHands", "releases — what shipped", "Use the release skill."), - ("DNA", "PyAutoDNA", "software stacks — versions, compatibility and upgrades", - "Review PyAutoDNA software stacks and compatibility. Compare observed environments with recommended stacks, explain drift and propose validated upgrades. Read the repository AGENTS.md first."), - ("Memory", "PyAutoMemory", "knowledge — papers and wikis", "Use the memory skill. "), -) - -MIND_COUNT_RE = re.compile(r"^\|\s*\[([A-Za-z ]+)\]\([^)]*\)[^|]*\|\s*(\d+)\s*\|", - re.MULTILINE) +def boards(owner: str) -> list[dict]: + """Canonical membership/order from Brain; Scientist never summarizes itself.""" + t = theme() + links = t.board_links(f"https://{owner.lower()}.github.io", current=BOARD_KEY) + if not links: + raise RuntimeError("Brain board registry unavailable") + return [{"name": t.organ(key)["organ"], "key": key, + "repo": url.rstrip("/").rsplit("/", 1)[-1], "url": url, + "role": t.organ(key)["function"]} + for key, url in links.items()] def _owner() -> str: @@ -144,32 +140,28 @@ def _get(url: str) -> str: def collect(owner: str | None = None) -> dict: owner = owner if owner is not None else _owner() - low = owner.lower() - snapshot: dict = { - "generated": datetime.datetime.now(datetime.timezone.utc).isoformat(), - "owner": owner, - "boards": [], - } - for name, repo, role, door in BOARDS: - row = {"name": name, "repo": repo, "role": role, "door": door, - "url": f"https://{low}.github.io/{repo}/" if low else "", - "headline": None, "color": None} + if not owner: + raise ValueError("Cannot resolve the repository owner") + rows = boards(owner) + # theme() resolves the matching Brain checkout and its validator. + from _state import validate_state + + def read(row): + row = dict(row, headline=None, color=None, feed=None, error=None) try: - if name == "Mind": - md = _get(f"https://raw.githubusercontent.com/{owner}/{repo}/main/dashboard.md") - counts = {label: int(n) for label, n in MIND_COUNT_RE.findall(md)} - if counts: - row["headline"] = " · ".join( - f"{v} {k.lower()}" for k, v in counts.items()) - row["counts"] = counts - else: - badge = json.loads(_get(row["url"] + "badge.json")) - row["headline"] = str(badge.get("message") or "") - row["color"] = str(badge.get("color") or "") + feed = json.loads(_get(row["url"] + "state.json")) + errors = validate_state(feed) + if errors or feed["organ"] != row["key"] or feed["repo"] != row["repo"]: + raise ValueError("Invalid organ feed") + row.update(feed=feed, headline=feed["headline"], color=feed["status"]) except (urllib.error.URLError, TimeoutError, ValueError, OSError): - pass - snapshot["boards"].append(row) - return snapshot + row["error"] = "Evidence unavailable" + return row + + with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor: + collected = list(executor.map(read, rows)) + return {"generated": datetime.datetime.now(datetime.timezone.utc).isoformat(), + "owner": owner, "boards": collected} # --- pure helpers --------------------------------------------------------------- @@ -184,6 +176,8 @@ def heart_word(snapshot: dict) -> str: h = _heart(snapshot) if not h or not h.get("headline"): return "UNKNOWN" + if h.get("feed"): + return h["feed"]["status"].upper() return h["headline"].split()[0].upper().strip("·") @@ -194,7 +188,7 @@ def route_hint(snapshot: dict) -> str: return ("The Heart is " + word + " — start at the PyAutoHeart Dashboard and fix what's blocking.") if word == "STALE": - return ("Evidence gaps, nothing known-bad — re-run checks via Use the health skill., " + return ("Heart evidence is stale — re-run checks via Use the health skill., " "then pick a task on the PyAutoMind Dashboard.") if word == "GREEN": return "All clear — pick a task on the PyAutoMind Dashboard." @@ -221,126 +215,70 @@ def _render_md_brief(snapshot: dict) -> str: return " · ".join(bits) -def _copy_btn(payload: str, label: str = "copy") -> str: - """A one-tap payload chip. The behaviour is the family's shared script - (``_theme.JS``): a delegated click handler reading ``data-cmd``.""" - return (f"") - - -_HEART_CLS = {"RED": "fail", "YELLOW": "warn", "STALE": "info", "GREEN": "ok"} - -# The Heart's word in the theme's verdict vocabulary. Unknown stays neutral: -# "we could not read the Heart" is not a verdict, and colouring it as one -# would say something the page does not know. -_VERDICT_CLS = {"RED": "bad", "YELLOW": "warn", "STALE": "warn", "GREEN": "ok"} - -# The same word in the shared section-status vocabulary (Brain -# ``section_layout``). Anything the Heart did not say — an unreadable badge, an -# unfamiliar word — is "unknown", never green. -_SECTION_STATUS = {"RED": "red", "YELLOW": "yellow", "STALE": "stale", "GREEN": "green"} - -SECTION_ID = "dashboards" - - def _row_id(name: str) -> str: """The stable fragment of one organ row (``#board-heart``).""" return "board-" + re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") -def section_summaries(snapshot: dict) -> dict: - """Owner-computed header facts for the collapsed "Organ dashboards" section. - - The count is how many boards actually answered out of how many are listed, - so a missing headline reads as a gap ("4 of 5 reporting"), not as a quiet - zero. The status is the Heart's own word, labelled as such; it routes, it - does not restate release readiness. - """ - rows = snapshot.get("boards") or [] - word = heart_word(snapshot) - info: dict = { - "status": _SECTION_STATUS.get(word, "unknown"), - "label": "Heart " + (word if word in _SECTION_STATUS else "unknown"), - } - if rows: - live = sum(1 for b in rows if b.get("headline")) - info["count"] = f"{live} of {len(rows)} reporting" - return {SECTION_ID: info} - -# What the shared sheet has no opinion on: this board is a router, so its one -# page-specific shape is the organ row — a name, that board's own headline, -# and what it is for. Written against the theme's variables, so it follows the -# accent rather than setting a second palette. _EXTRA_CSS = """ -.organ{display:flex;gap:.6rem;align-items:flex-start;padding:.55rem .35rem; - margin:0 -.35rem;border-bottom:1px solid var(--line);border-radius:7px} -.organ:hover{background:var(--tint)} -.organ p{margin:0;flex:1} -.organ .name{display:inline-block;min-width:4.6rem;font-weight:700} -.organ .head{font-weight:600} -.organ .role{display:block;color:var(--muted);font-size:.88em} -footer{margin-top:2.4rem;padding-top:1rem;border-top:1px solid var(--line); - color:var(--muted);font-size:.82em} +.organ-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:.75rem;align-items:start;margin-top:1.25rem} +.organ-card{min-width:0;border:1px solid var(--line);border-radius:12px;background:var(--bg)} +.organ-card[open]{grid-column:1/-1} +.organ-card>summary{cursor:pointer;min-height:64px;padding:1rem;display:flex;gap:.65rem;align-items:center;font-weight:700;list-style:none} +.organ-card>summary::-webkit-details-marker{display:none} +.organ-card>summary::after{content:'⌄';margin-left:auto} +.organ-card[open]>summary::after{content:'⌃'} +.organ-icon svg{width:30px;height:30px;display:block} +.organ-status{font-size:.8rem;font-weight:500;color:var(--muted)} +.organ-status[data-status=red]{color:var(--bad)} +.organ-status[data-status=green]{color:var(--ok)} +.organ-content{padding:0 1rem 1rem} +.organ-content dl{margin:0;display:grid;gap:.6rem} +.organ-content .summary-row{display:grid;grid-template-columns:9rem 1fr;gap:.75rem} +.organ-content dt{font-size:.88rem;color:var(--muted)} +.organ-content dd{margin:0;overflow-wrap:anywhere} +.organ-content a{display:inline-block;min-height:44px} +.organ-foot{display:flex;justify-content:space-between;gap:1rem;align-items:center;margin:.8rem 0 0;font-size:.82rem;color:var(--muted);flex-wrap:wrap} +.organ-foot a{min-height:44px;display:inline-flex;align-items:center} +.organ-grid :focus-visible{outline:3px solid var(--accent);outline-offset:3px} +@media(max-width:64rem){.organ-grid{grid-template-columns:repeat(2,minmax(0,1fr))}} +@media(max-width:40rem){.organ-grid{grid-template-columns:1fr}.organ-content .summary-row{grid-template-columns:1fr;gap:.15rem}} """ def _render_html(snapshot: dict) -> str: t = theme() - work_links = [ - {"label": b["name"] + " repository", - "href": f"https://github.com/{snapshot['owner']}/{b['repo']}"} - for b in snapshot.get("boards") or [] - if snapshot.get("owner") and b.get("repo") - ] - panel = t.orchestration_panel("scientist", "", "", CHECKIN_PROMPT, - organ="scientist", work_links=work_links, - refreshed_at=(snapshot.get("generated") - if snapshot.get("boards") and all(row.get("headline") is not None - for row in snapshot["boards"]) - else None), - refresh_url=(f"https://github.com/{snapshot['owner']}/PyAutoScientist/actions/workflows/organism_board.yml" - if snapshot.get("owner") else None)) - word = heart_word(snapshot) + owner = snapshot.get("owner") + panel = t.orchestration_panel( + "scientist", "", "", CHECKIN_PROMPT, organ="scientist", + work_links=([{"label": "Scientist repository", "href": f"https://github.com/{owner}/PyAutoScientist"}] if owner else []), + refreshed_at=(snapshot.get("generated") if snapshot.get("boards") and + all(row.get("headline") is not None for row in snapshot["boards"]) else None), + refresh_url=(f"https://github.com/{owner}/PyAutoScientist/actions/workflows/organism_board.yml" if owner else None)) rows = [] - for b in snapshot.get("boards") or []: - head = _html.escape(b.get("headline") or "unavailable") - link = (f"" - f"{_html.escape(b['name'])}" if b.get("url") - else _html.escape(b["name"])) - rows.append( - f"
" - f"{_copy_btn(b['door'], 'copy the door command for an AI assistant chat')}" - f"

{link} " - f"{head}" - f"{_html.escape(b['role'])}

") - hero = t.hero(BOARD_KEY, "Dashboard", navigation=[ - {"href": b["url"], "label": b["name"]} - for b in snapshot.get("boards") or [] if b.get("url") - ]) - # Brain's shared layout puts the slogan panel above the navigation cards - # and folds the titled section into a collapsed native disclosure; the - # verdict banner stays outside it so the routing answer is always visible. - return t.section_layout(f""" - - -PyAutoScientist Dashboard - - - -{hero} -{panel} -

{_html.escape(route_hint(snapshot))}

-
-

Organ dashboards

-{''.join(rows)} -
-

markdown version

-
Rendered by scripts/organism_board.py from the boards' -own published headlines · generated {_html.escape(str(snapshot.get('generated') or '?'))}.
- - -""", section_summaries(snapshot)) + for row in snapshot.get("boards") or []: + key = row.get("key", row["name"].lower()) + name = _html.escape(row["name"]) + ident = _row_id(row["name"]) + # Server fallback is explicitly a publication snapshot, not a live check. + head = _html.escape(row.get("headline") or "Evidence unavailable") + url = _html.escape(row["url"], quote=True) + rows.append(f"""
+{name}Snapshot +
Published status
{head}
+
Published {_html.escape(str(snapshot.get('generated') or 'unknown'))}Open {name} →
""") + data = json.dumps(snapshot, ensure_ascii=False).replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026") + script = (HOME / "scripts" / "overview.js").read_text(encoding="utf-8") + # Native per-organ disclosures keep the overview visible; do not put the + # whole grid inside section_layout's extra collapsed H2 group. + return f""" + +PyAutoScientist Dashboard +{t.hero(BOARD_KEY, "Dashboard")}{panel} +
{''.join(rows)}
+ + +""" def badge_endpoint(snapshot: dict) -> dict: diff --git a/scripts/overview.js b/scripts/overview.js new file mode 100644 index 0000000..21fa5fb --- /dev/null +++ b/scripts/overview.js @@ -0,0 +1,194 @@ +// Owner state stays authoritative. Validation/observation follow the cockpit v1 contract. +const STATUSES = ["green", "yellow", "red", "stale", "grey"]; +const SEVERITIES = ["red", "yellow", "info"]; +function esc(s) { + return String(s == null ? "" : s).replace(/[&<>"']/g, c => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); +} +function safeUrl(u) { + if (typeof u !== "string" || !/^https?:\/\//i.test(u)) return null; + try { const url = new URL(u); return url.hostname ? url.href : null; } catch (e) { return null; } +} +function age(iso) { + const t = Date.parse(iso); + if (isNaN(t)) return "unknown age"; + let s = Math.max(0, Math.round((Date.now() - t) / 1000)); + if (s < 60) return s + "s ago"; + const m = Math.round(s / 60); if (m < 60) return m + "m ago"; + const h = Math.round(m / 60); if (h < 48) return h + "h ago"; + return Math.round(h / 24) + "d ago"; +} + +// Additive v1 metadata: older producers need no migration. +const ITEM_STATES = ["healthy", "active", "stale", "blocked", "failed", "action_required", "unknown"]; +const ACTION_SAFETY = ["read_only", "requires_approval", "scientific_judgement", "never_automatic", "unclassified"]; +const oneLine = v => typeof v === "string" && v.trim() !== "" && !/[\r\n]/.test(v); +function utcTime(v) { + if (typeof v !== "string" || !/T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|\+00:00)$/.test(v)) return NaN; + const t = Date.parse(v); + // Date.parse normalizes impossible dates such as February 30. + return Number.isFinite(t) && new Date(t).toISOString().slice(0, 19) === v.slice(0, 19) ? t : NaN; +} +function validate(d, organ = null) { + if (!d || typeof d !== "object" || Array.isArray(d)) return "not an object"; + if (d.schema_version !== 1) return "schema_version " + d.schema_version; + if (!STATUSES.includes(d.status)) return "invalid status"; + if (![d.organ, d.repo, d.pages_url, d.headline].every(oneLine)) return "missing identity or headline"; + if (organ && (d.organ !== organ.organ.toLowerCase() || d.repo !== organ.repo)) return "wrong organ"; + if (!Number.isFinite(utcTime(d.updated))) return "invalid updated timestamp"; + if ("valid_until" in d && (!Number.isFinite(utcTime(d.valid_until)) || utcTime(d.valid_until) < utcTime(d.updated))) return "invalid valid_until"; + if (!Array.isArray(d.items)) return "no items"; + const ids = new Set(); + for (const it of d.items) { + if (!it || !SEVERITIES.includes(it.severity) || !oneLine(it.text)) return "bad item"; + for (const key of ["url", "prompt"]) if (it[key] != null && typeof it[key] !== "string") return "bad " + key; + for (const key of ["id", "reason", "decision", "recommended_action_id"]) if (key in it && !oneLine(it[key])) return "bad " + key; + if ("id" in it) { if (ids.has(it.id)) return "duplicate item id"; ids.add(it.id); } + if ("state" in it && !ITEM_STATES.includes(it.state)) return "bad item state"; + if ("requires_human_decision" in it && typeof it.requires_human_decision !== "boolean") return "bad decision flag"; + if (it.requires_human_decision && !oneLine(it.decision)) return "missing decision"; + if ("actions" in it && !Array.isArray(it.actions)) return "bad actions"; + const actions = new Set(); + for (const action of it.actions || []) { + if (!action || ![action.id, action.label, action.target].every(oneLine)) return "bad action"; + if (!["link", "command", "prompt"].includes(action.kind)) return "bad action kind"; + if ("safety" in action && !ACTION_SAFETY.includes(action.safety)) return "bad action safety"; + if (action.kind === "link" && !safeUrl(action.target)) return "bad action URL"; + if (actions.has(action.id)) return "duplicate action id"; + actions.add(action.id); + } + if ("recommended_action_id" in it && !actions.has(it.recommended_action_id)) return "missing recommended action"; + } + return null; +} + +// Pure observation model. Source health and transport/freshness are separate +// facts. Missing expiry means no declared age policy, not infinite freshness. +function observation(st = {}, now = Date.now()) { + const d = st.feed || st.lastGood || null; + const base = { feed: d, sourceStatus: d ? d.status : null, lastChecked: st.lastChecked || null }; + if (!d) return { ...base, status: "grey", current: false, freshness: "unknown", reason: st.error || "waiting for first check" }; + if (st.error || !st.feed) return { ...base, status: "stale", current: false, freshness: "unavailable", reason: st.error || "not checked this session" }; + if (!Number.isFinite(utcTime(d.updated)) || utcTime(d.updated) > now) return { ...base, status: "grey", current: false, freshness: "unknown", reason: "source timestamp is invalid or in the future" }; + if (d.valid_until && utcTime(d.valid_until) <= now) return { ...base, status: "stale", current: false, freshness: "expired", reason: "source freshness deadline passed" }; + if (d.status === "stale") return { ...base, status: "stale", current: false, freshness: "expired", reason: "source reports stale evidence" }; + if (d.status === "grey") return { ...base, status: "grey", current: false, freshness: "unknown", reason: "source reports insufficient evidence" }; + return { ...base, status: d.status, current: true, freshness: d.valid_until ? "within_policy" : "unspecified", reason: null }; +} + + +const DOMAIN_LABELS = { + brain: 'Coordination', mind: 'Tasks', cortex: 'Science', memory: 'Knowledge', + eyes: 'Figures', ears: 'Conversations', heart: 'Checks', hands: 'Releases', + pulse: 'Profiling', insight: 'Inference', dna: 'Compatibility', nerves: 'Configuration', + broca: 'Assistants', gut: 'Cleanup' +}; +function concise(text) { + const words = String(text).trim().split(/\s+/); + const short = words.slice(0, 12).join(' '); + return short.slice(0, 130) + (words.length > 12 || short.length > 130 ? '…' : ''); +} +function itemUrl(item, fallback) { + const action = (item.actions || []).find(a => a.kind === 'link' && a.id === item.recommended_action_id) + || (item.actions || []).find(a => a.kind === 'link'); + return safeUrl(item.url) || safeUrl(action && action.target) || fallback; +} +function needsAttention(item) { + return item.requires_human_decision || ['failed', 'blocked', 'action_required', 'stale', 'unknown'].includes(item.state) + || (!item.state && ['red', 'yellow'].includes(item.severity)); +} +function summaries(organ, view) { + const feed = view.feed; + const url = organ.url; + if (!feed) return [{ label: 'Evidence', text: 'Unavailable', url }]; + if (!view.current) return [ + { label: 'Evidence', text: view.reason || 'Not verified', url }, + { label: 'Last known', text: feed.headline, url } + ]; + const rows = []; + const attention = feed.items.filter(needsAttention).sort((a,b) => + Number(!!b.requires_human_decision) - Number(!!a.requires_human_decision) + || (a.severity === 'red' ? -1 : 0) - (b.severity === 'red' ? -1 : 0)); + if (attention.length) { + const item = attention[0]; + rows.push({ label: item.requires_human_decision ? 'Your decision' : 'Needs attention', + text: item.requires_human_decision ? item.decision : item.text, url: itemUrl(item, url) }); + } else { + rows.push({ label: 'Attention', text: feed.status === 'green' ? 'No action reported' : + feed.status === 'red' ? 'Review failing status' : 'Review current status', url }); + } + const active = feed.items.find(item => item.state === 'active' && !attention.includes(item)); + if (active) rows.push({ label: 'In progress', text: active.text, url: itemUrl(active, url) }); + // The release owner already includes the version and event age in its headline. + // No other headline is promoted to "completed"; updated is never an event date. + if (!rows.some(row => row.text === feed.headline)) rows.push({ + label: organ.key === 'hands' && /^v?\d{4}\.\d{1,2}\.\d{1,2}\.\d+\s*·/.test(feed.headline) + ? 'Latest release' : DOMAIN_LABELS[organ.key] || 'Current position', text: feed.headline, url + }); + return rows.slice(0, 3); +} +function statusLabel(view) { + if (!view.current) return view.feed ? 'Not verified' : 'Unavailable'; + if (view.feed.items.some(needsAttention)) return 'Needs attention'; + if (view.feed.items.some(item => item.state === 'active')) return 'In progress'; + return { green: 'No action reported', yellow: 'Review', red: 'Needs attention' }[view.status] || 'Unknown'; +} +function summaryHtml(rows) { + return rows.map(row => `
${esc(row.label)}
${esc(concise(row.text))}
`).join(''); +} + +// ---- browser startup ---- +const snapshot = JSON.parse(document.getElementById('scientist-snapshot').textContent); +const organStates = new Map(); +for (const organ of snapshot.boards) { + const identity = { organ: organ.name, repo: organ.repo }; + let saved = null; + try { saved = JSON.parse(localStorage.getItem('pyauto-cockpit:last-good:' + organ.repo)); } catch (_) {} + const lastGood = saved && !validate(saved.feed, identity) ? saved.feed : + organ.feed && !validate(organ.feed, identity) ? organ.feed : null; + organStates.set(organ.key, { lastGood }); +} +function paint(organ) { + const view = observation(organStates.get(organ.key)); + const card = document.getElementById('board-' + organ.key); + const badge = card.querySelector('.organ-status'); + badge.textContent = statusLabel(view); + badge.dataset.status = view.status; + const list = card.querySelector('dl'); + const markup = summaryHtml(summaries(organ, view)); + if (list.innerHTML !== markup) { + // Keep a focused evidence link in place even when its text changes. + const links = [...list.querySelectorAll('a')]; + const focused = links.indexOf(document.activeElement); + list.innerHTML = markup; + if (focused >= 0) (list.querySelectorAll('a')[focused] || card.querySelector('summary')).focus({ preventScroll: true }); + } + const stamp = card.querySelector('[data-freshness]'); + stamp.textContent = view.feed ? `${view.current ? 'Source updated' : 'Last known source'} ${age(view.feed.updated)}` : 'No verified evidence'; + stamp.title = view.feed ? view.feed.updated : ''; +} +let refreshing = false; +async function refresh() { + if (refreshing) return; + refreshing = true; + try { + await Promise.all(snapshot.boards.map(async organ => { + const st = organStates.get(organ.key); + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 15000); + try { + const response = await fetch(organ.url + 'state.json?t=' + Date.now(), { cache: 'no-store', signal: controller.signal }); + if (!response.ok) throw new Error('Evidence unavailable'); + const feed = await response.json(); + if (validate(feed, { organ: organ.name, repo: organ.repo })) throw new Error('Invalid evidence'); + st.feed = feed; st.lastGood = feed; st.error = null; + try { localStorage.setItem('pyauto-cockpit:last-good:' + organ.repo, JSON.stringify({ feed, at: new Date().toISOString() })); } catch (_) {} + } catch (_) { st.feed = null; st.error = 'Evidence unavailable'; } + finally { clearTimeout(timeout); paint(organ); } + })); + } finally { refreshing = false; } +} +for (const organ of snapshot.boards) paint(organ); +refresh(); +setInterval(refresh, 60000); +document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') refresh(); }); diff --git a/tests/overview.cjs b/tests/overview.cjs new file mode 100644 index 0000000..a67d6f6 --- /dev/null +++ b/tests/overview.cjs @@ -0,0 +1,47 @@ +const {test} = require('node:test'); +const assert = require('node:assert/strict'); +const vm = require('node:vm'); +const fs = require('node:fs'); +const script = fs.readFileSync(require('node:path').join(__dirname, '../scripts/overview.js'), 'utf8'); +new vm.Script(script); +const ctx = vm.createContext({ URL, Date: class extends Date { static now() { return Date.parse('2026-10-09T12:00:00Z'); } } }); +vm.runInContext(script.split('// ---- browser startup ----')[0], ctx); +function run(expr, vars = {}) { Object.assign(ctx, vars); return vm.runInContext(expr, ctx); } +function feed(overrides={}) { return { schema_version:1, organ:'mind',repo:'PyAutoMind',status:'green',headline:'2 active · 1 awaiting review',updated:'2026-10-09T10:00:00Z',pages_url:'https://example.test/PyAutoMind/',items:[],...overrides }; } +const organ = { key:'mind',url:'https://example.test/PyAutoMind/' }; +function rows(d, st={}) {return run('summaries(organ, observation(st))', {organ,st:{feed:d,...st}});} +test('a decision outranks a failure and active work has its own row; hard cap three', () => { + const result=rows(feed({items:[{severity:'red',text:'Failure'}, {severity:'yellow',text:'Choice',requires_human_decision:true,decision:'Choose a release date'}, {severity:'info',state:'active',text:'Implementing the dashboard'}]})); + assert.equal(result.length,3);assert.equal(result[0].text,'Choose a release date');assert.equal(result[1].label,'In progress'); +}); +test('quiet, non-green, unavailable, expired and future evidence remain distinct', () => { + assert.equal(rows(feed())[0].text,'No action reported'); + assert.equal(rows(feed({status:'red'}))[0].text,'Review failing status'); + assert.equal(rows(null)[0].text,'Unavailable'); + const expired=rows(feed({valid_until:'2026-10-09T10:01:00Z'}));assert.equal(expired[0].label,'Evidence'); + const future=rows(feed({updated:'2099-01-01T00:00:00Z'}));assert.equal(future[0].label,'Evidence'); + const cached=rows(null,{lastGood:feed(),error:'offline'});assert.equal(cached[1].label,'Last known'); +}); +test('active or healthy items are not reclassified as failures from their colour', () => { + const result=rows(feed({items:[{severity:'red',state:'active',text:'A run in progress'}]})); + assert.equal(result[0].text,'No action reported');assert.equal(result[1].label,'In progress'); +}); +test('ordinary headlines and feed timestamps never become completion history', () => { + const result=rows(feed());assert.ok(result.every(r=>!r.label.includes('Latest'))); + assert.ok(result.every(r=>!r.text.includes('2026-10-09'))); + const release=run('summaries(hands, observation({feed:d}))',{hands:{key:'hands',url:'https://example.test/'},d:feed({headline:'2026.10.7.1 · 2d ago'})}); + assert.equal(release.at(-1).label,'Latest release');assert.equal(release.at(-1).text,'2026.10.7.1 · 2d ago'); + const failed=run('summaries(hands, observation({feed:d}))',{d:feed({status:'red',headline:'Build failed'})}); + assert.equal(failed.at(-1).label,'Releases'); +}); +test('summary links escape HTML, reject active URLs and stay concise', () => { + const html=run('summaryHtml(rows)',{rows:[{label:'&' + out = ob.render(snap, 'html') + payload = re.search(r'id="scientist-snapshot">(.*?)', out, re.S)[1] + assert '<' not in payload + assert json.loads(payload)['boards'][0]['headline'] == snap['boards'][0]['headline'] -def test_dna_headline_is_owned_by_dna_and_unavailable_stays_unknown(monkeypatch): +def test_collection_validates_identity_and_degrades_per_organ(monkeypatch): def get(url): - if "/PyAutoDNA/" in url: - return json.dumps({"message": "2 observed · 4 unknown", "color": "lightgrey"}) - raise OSError("unavailable") - monkeypatch.setattr(ob, "_get", get) - snapshot = ob.collect("Example") - dna = next(row for row in snapshot["boards"] if row["name"] == "DNA") - assert dna["headline"] == "2 observed · 4 unknown" - assert dna["url"] == "https://example.github.io/PyAutoDNA/" - assert "PyAutoDNA" in dna["door"] - assert "2 observed" in ob.render(snapshot, "html") - monkeypatch.setattr(ob, "_get", lambda url: (_ for _ in ()).throw(OSError("offline"))) - missing = next(row for row in ob.collect("Example")["boards"] if row["name"] == "DNA") - assert missing["headline"] is None + if '/PyAutoDNA/' in url: + return json.dumps({'schema_version': 1, 'organ': 'dna', 'repo': 'PyAutoDNA', + 'status': 'grey', 'headline': '2 observed · 4 unknown', + 'updated': '2026-10-09T10:00:00Z', 'pages_url': 'https://example.github.io/PyAutoDNA/', 'items': []}) + raise OSError('unavailable') + monkeypatch.setattr(ob, '_get', get) + snapshot = ob.collect('Example') + dna = next(row for row in snapshot['boards'] if row['name'] == 'DNA') + assert dna['headline'] == '2 observed · 4 unknown' + assert dna['url'] == 'https://example.github.io/PyAutoDNA/' + assert len(snapshot['boards']) == len(ob.theme().board_links('https://example.github.io', current='organism')) + assert all(row['name'] != 'Scientist' for row in snapshot['boards']) + assert all(row['feed'] is None for row in snapshot['boards'] if row['name'] != 'DNA') + monkeypatch.setattr(ob, '_get', lambda url: get('https://example.github.io/PyAutoDNA/state.json')) + mismatched = ob.collect('Example') + assert all(row['feed'] is None for row in mismatched['boards'] if row['name'] != 'DNA') + + +def test_structured_heart_status_does_not_parse_the_headline(): + snap = _snap('Monitoring RED · release STALE') + next(row for row in snap['boards'] if row['name'] == 'Heart')['feed'] = {'status': 'red'} + assert ob.heart_word(snap) == 'RED'