diff --git a/agents/conductors/cortex/_cortex.py b/agents/conductors/cortex/_cortex.py index db59ed56..2cc587a7 100644 --- a/agents/conductors/cortex/_cortex.py +++ b/agents/conductors/cortex/_cortex.py @@ -38,7 +38,9 @@ `birth --category active|development --assistant A --summary S [--apply] [--no-push]` (a scaffolded project's row and ledger, written by the Cortex's own `cortex.py birth` on `claude/birth-`) · -`dashboard --check|--apply` · `issue [--project KEY] [--apply]`. +`dashboard --check|--apply` (`--apply`, like the check-in, also mirrors +`dashboard.md` to `/STATE.md` when that root is on this +machine) · `issue [--project KEY] [--apply]`. Exit codes: 0 ok · 1 dashboard drift (the `dashboard_refresh.yml` contract), a failed pull, a tree that does not check, or an error-severity Science drift @@ -92,6 +94,7 @@ #: How much of a run's `what` and a log entry's text a card shows. RUN_CLIP, LOG_CLIP = 160, 240 +NOTE_CLIP = 120 # a retired note in the phone-width Summary table; the card keeps it whole class CortexUnavailable(Exception): @@ -296,6 +299,8 @@ def census(root: Path) -> dict: "running": sum(1 for d in rows for r in d["runs"] if r["state"] == "running"), "open": sum(1 for d in rows for r in d["runs"] if r["state"] == "open"), "active": sum(1 for row in projects.values() if row.get("status") == "active"), + "dormant": sum(1 for row in projects.values() if row.get("status") == "dormant"), + "retired": sum(1 for row in projects.values() if row.get("status") == "retired"), } return { "root": str(root), @@ -533,8 +538,56 @@ def _registration(d: dict) -> tuple[str, str]: return min(opened) if opened else "not recorded", now +def _run_key(r: dict) -> tuple: + """Newest-first sort key: the full date, then the job id — numerically + where it leads with digits (`3002_[0-3]` sorts as 3002).""" + m = re.match(r"\d+", r["ident"]) + job = (1, int(m.group()), r["ident"]) if m else (0, 0, r["ident"]) + return (r["date"] or "", job) + + +def runs_newest_first(d: dict) -> list[dict]: + """A card's runs, newest first (the ledger keeps them in recorded order).""" + return sorted(d["runs"], key=_run_key, reverse=True) + + +def _run_date(date: str) -> str: + """The runs table's Date cell: `MM-DD` — the year is the board's, and the + sort above still reads the full date.""" + return date[5:] if re.fullmatch(r"\d{4}-\d{2}-\d{2}", date or "") else date + + +#: The board's status sections, in page order. `planned` gets its own +#: section only when some project is planned. +STATUS_SECTIONS = ("active", "planned", "dormant", "retired") + + +def _section_of(status: str) -> str: + """The section a project's status lands in; an unknown status is not + hidden — it sits with the dormant ones, its status on the card.""" + return status if status in STATUS_SECTIONS else "dormant" + + +def _status_sections(c: dict) -> list[str]: + """The sections this board shows: always Active, Dormant, Retired; Planned + only when a row or ledger is planned.""" + planned = any(row.get("status") == "planned" for row in c["projects"].values()) \ + or any(d["status"] == "planned" for d in c["ledgers"]) + return [s for s in STATUS_SECTIONS if s != "planned" or planned] + + +def _summary_rows(c: dict, section: str) -> list[tuple[str, dict, dict | None]]: + """`(key, row, ledger-or-None)` for every projects.yaml row in a section.""" + return [(k, row, ledger_of(c, k)) for k, row in c["projects"].items() + if _section_of(row.get("status", "")) == section] + + +def _section_ledgers(c: dict, section: str) -> list[dict]: + return [d for d in c["ledgers"] if _section_of(d["status"]) == section] + + def _card_md(d: dict, row: dict, blob: str) -> list[str]: - issue = (f"[{d['issue']}]({d['issue_url']})" if d["issue_url"] + issue =(f"[{d['issue']}]({d['issue_url']})" if d["issue_url"] else "no issue yet") registered, now = _registration(d) L = [f'
{_esc(d["key"])} — ' @@ -551,10 +604,11 @@ def _card_md(d: dict, row: dict, blob: str) -> list[str]: if d["runs"]: L += ["| Job | State | Partition | Date | Description |", "|---|---|---|---|---|"] + runs = runs_newest_first(d) L += [f"| `{r['ident']}` | {r['state']} | {_cell(r['partition'])} | " - f"{r['date']} | {_cell(_md_text(_clip(r['what'], RUN_CLIP)))} |" - for r in d["runs"]] - clipped = [r for r in d["runs"] if _clipped(r["what"], RUN_CLIP)] + f"{_run_date(r['date'])} | {_cell(_md_text(_clip(r['what'], RUN_CLIP)))} |" + for r in runs] + clipped = [r for r in runs if _clipped(r["what"], RUN_CLIP)] if clipped: L += ["", f"
Full descriptions ({len(clipped)} " "shortened above)", ""] @@ -594,12 +648,12 @@ def _runs_table_html(d: dict) -> list[str]: 'JobState' 'PartitionDate' 'Description', ""] - for r in d["runs"]: + for r in runs_newest_first(d): tone = "y" if r["state"] == "running" else "n" H.append(f'{_esc(r["ident"])}' f'{_esc(r["state"])}' f'{_esc(r["partition"])}' - f'{_esc(r["date"])}' + f'{_esc(_run_date(r["date"]))}' f'{_full_text_html(r["what"], RUN_CLIP, clauses=True)}') H += ["", ""] return H @@ -662,7 +716,9 @@ def render_dashboard(c: dict) -> str: "| Where | Count |", "|-------|------:|", f"| [Running](#projects) | {n['running']} |", f"| [Open](#projects) | {n['open']} |", - f"| [Projects](#projects) | {n['active']} |", ""] + f"| [Active](#active) | {n['active']} |", + f"| [Dormant](#dormant) | {n['dormant']} |", + f"| [Retired](#retired) | {n['retired']} |", ""] if c["problems"]: L += ["> ⚠️ **The tree does not check** — `python3 scripts/cortex.py " "check` reports:", ""] @@ -671,30 +727,41 @@ def render_dashboard(c: dict) -> str: L += [_task_row(CHECKIN_LABEL, checkin_payload(c)), "", f"### Last check-in: {c.get('checkin') or CHECKIN_NEVER}", ""] - L += ["## Summary", "", "| Project | Running | Open | Last update |", - "|---|---:|---:|---|"] - active = [k for k, row in c["projects"].items() if row.get("status") == "active"] - for key in active: - d = ledger_of(c, key) - running = sum(1 for r in (d["runs"] if d else []) if r["state"] == "running") - open_ = sum(1 for r in (d["runs"] if d else []) if r["state"] == "open") - L.append(f"| {key} | {running} | {open_} | " - f"{(d['updated'] if d else '') or '-'} |") - if not active: - L.append("| _(no active project)_ | | | |") - L.append("") + sections = _status_sections(c) + L += ["## Summary", ""] + for section in sections: + rows = _summary_rows(c, section) + L += [f"### {section.title()}", ""] + if section == "retired": + L += ["| Project | Note | Last update |", "|---|---|---|"] + L += [f"| {key} | {_cell(_clip(row.get('note') or '-', NOTE_CLIP))} | " + f"{(d['updated'] if d else '') or '-'} |" for key, row, d in rows] + if not rows: + L.append("| _(no retired project)_ | | |") + else: + L += ["| Project | Running | Open | Last update |", "|---|---:|---:|---|"] + for key, row, d in rows: + running, open_, updated = _overview(d) if d else (0, 0, "-") + L.append(f"| {key} | {running} | {open_} | {updated} |") + if not rows: + L.append(f"| _(no {section} project)_ | | | |") + L.append("") L += ["## Projects", ""] - live = [d for d in c["ledgers"] if d["status"] != "retired"] - retired = [d for d in c["ledgers"] if d["status"] == "retired"] - for d in live: - L += _card_md(d, c["projects"].get(d["key"], {}), blob) - if retired: - L += [f"
{len(retired)} retired", ""] - L += [f"- [{d['key']}]({_ledger_link(d, blob)}) — {_cell(d['summary'])} — " - f"{_cell(c['projects'].get(d['key'], {}).get('note') or '-')}" - for d in retired] - L += ["", "
", ""] + for section in sections: + L += [f"### {section.title()}", ""] + ledgers = _section_ledgers(c, section) + if section == "retired": + L += [f"- [{d['key']}]({_ledger_link(d, blob)}) — {_cell(d['summary'])} — " + f"{_cell(c['projects'].get(d['key'], {}).get('note') or '-')} — " + f"updated {d['updated'] or '-'}" for d in ledgers] + else: + for d in ledgers: + L += _card_md(d, c["projects"].get(d["key"], {}), blob) + if section == "retired" or not ledgers: + if not ledgers: + L.append(f"_(no {section} project with a ledger)_") + L.append("") bare = no_ledger_rows(c) if bare: L += ["#### No ledger", "", "| Project | Status | Note |", "|---|---|---|"] @@ -757,7 +824,9 @@ def render_dashboard(c: dict) -> str: "table.runs td.what{flex:1 0 100%;margin-top:.15rem}}" ".pathchip{display:inline-block;background:var(--accent);color:#fff;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.88em;padding:.12em .5em;border-radius:.3rem;overflow-wrap:anywhere}" "@media(prefers-color-scheme:dark){.pathchip{background:color-mix(in srgb,var(--accent) 55%,#000)}}" - ".stale{color:var(--bad);font-weight:600}") + ".stale{color:var(--bad);font-weight:600}" + "h3.status-section{margin:1.4rem 0 .4rem}" + "ul.retired{margin:.3rem 0;padding-left:1.2rem}ul.retired li{margin:.3rem 0}") def render_dashboard_html(c: dict) -> str: @@ -786,7 +855,9 @@ def render_dashboard_html(c: dict) -> str: hero(THEME_ORGAN, "Dashboard", _esc(INTRO), navigation=[ {"label": "Running", "href": "#summary", "count": n["running"]}, {"label": "Open", "href": "#summary", "count": n["open"]}, - {"label": "Projects", "href": "#projects", "count": n["active"]}, + {"label": "Active", "href": "#active", "count": n["active"]}, + {"label": "Dormant", "href": "#dormant", "count": n["dormant"]}, + {"label": "Retired", "href": "#retired", "count": n["retired"]}, {"label": "Check in", "href": "#orchestration-cortex"}, ]), orchestration_panel( @@ -804,33 +875,49 @@ def render_dashboard_html(c: dict) -> str: "scripts/cortex.py check reports:

", "
    "] H += [f"
  • {_esc(p)}
  • " for p in c["problems"][:10]] H += ["
"] - H += ['

Summary

', '', - "" - ""] - active = [k for k, row in c["projects"].items() if row.get("status") == "active"] - for key in active: - d = ledger_of(c, key) - runs = d["runs"] if d else [] - H.append(f"" - f"" - f"" - f"") - if not active: - H.append('') - H.append("
ProjectRunningOpenLast update
{_esc(key)}{sum(1 for r in runs if r['state'] == 'running')}{sum(1 for r in runs if r['state'] == 'open')}{_esc((d['updated'] if d else '') or '-')}
(no active project)
") + sections = _status_sections(c) + H.append('

Summary

') + for section in sections: + rows = _summary_rows(c, section) + H += [f"

{section.title()}

", + f''] + if section == "retired": + H.append("") + H += [f"" + f"" + f"" + for key, row, d in rows] + if not rows: + H.append('') + else: + H.append("" + "") + for key, row, d in rows: + running, open_, updated = _overview(d) if d else (0, 0, "-") + H.append(f"" + f"") + if not rows: + H.append(f'') + H.append("
ProjectNoteLast update
{_esc(key)}{_esc(_clip(row.get('note') or '-', NOTE_CLIP))}{_esc((d['updated'] if d else '') or '-')}
(no retired project)
ProjectRunningOpenLast update
{_esc(key)}{running}{open_}{_esc(updated)}
(no {section} project)
") H.append('

Projects

') - live = [d for d in c["ledgers"] if d["status"] != "retired"] - retired = [d for d in c["ledgers"] if d["status"] == "retired"] - for d in live: - H += _card_html(d, c["projects"].get(d["key"], {}), blob) - if retired: - H += [f"
{len(retired)} retired
    "] - H += [f'
  • {_esc(d["key"])}' - f" — {_esc(d['summary'])} — " - f"{_esc(c['projects'].get(d['key'], {}).get('note') or '-')}
  • " - for d in retired] - H += ["
"] + for section in sections: + ledgers = _section_ledgers(c, section) + H.append(f'

{section.title()}

') + if section == "retired": + if ledgers: + H.append('
    ') + H += [f'
  • ' + f'{_esc(d["key"])} — {_esc(d["summary"])} — ' + f"{_esc(c['projects'].get(d['key'], {}).get('note') or '-')} " + f'· updated {_esc(d["updated"] or "-")}
  • ' + for d in ledgers] + H.append("
") + else: + for d in ledgers: + H += _card_html(d, c["projects"].get(d["key"], {}), blob) + if not ledgers: + H.append(f'

(no {section} project with a ledger)

') bare = no_ledger_rows(c) if bare: H += ["

No ledger

", '', @@ -981,6 +1068,37 @@ def render_pages(c: dict) -> dict: "state.json": render_state(c)} +#: The Science-side copy of the markdown board (PyAutoBrain#616): the same +#: page, read on the laptop in the Science folder's context. +SCIENCE_MIRROR = "STATE.md" + + +def mirror_header(c: dict) -> str: + pages = _pages_url(c.get("home", "")) + board = f"[PyAutoCortex board]({pages})" if pages else "PyAutoCortex board" + return (f"> **Generated** by `pyauto-brain cortex dashboard --apply` — a mirror " + f"of the {board} (`dashboard.md`). Do not edit this file: every " + "render overwrites it.\n\n") + + +def write_science_mirror(c: dict, page: str) -> Path | None: + """Write the markdown board to `/STATE.md`, where the root + is the one `projects.yaml` agrees on. Off the laptop (no root, or the + directory is not here) it is skipped silently; a failed write is one + line on stderr and never fails the render. Returns the path written.""" + science = science_root_from(c.get("projects") or {}) + if not science or not Path(science).is_dir(): + return None + target = Path(science) / SCIENCE_MIRROR + try: + target.write_text(mirror_header(c) + page, encoding="utf-8") + except OSError as exc: + print(f"note: could not write the Science mirror {target}: {exc}", + file=sys.stderr) + return None + return target + + def cmd_dashboard(root: Path, c: dict, a) -> int: pages = render_pages(c) if a.check: @@ -999,7 +1117,9 @@ def cmd_dashboard(root: Path, c: dict, a) -> int: if a.apply: for name, want in pages.items(): (root / name).write_text(want, encoding="utf-8") - print(f"Wrote: {' + '.join(pages)} ({len(c['ledgers'])} ledger(s), " + mirror = write_science_mirror(c, pages["dashboard.md"]) + wrote = list(pages) + ([str(mirror)] if mirror else []) + print(f"Wrote: {' + '.join(wrote)} ({len(c['ledgers'])} ledger(s), " f"{c['counts']['running']} running, {c['counts']['open']} open)") return RC_OK print(pages["dashboard.md"], end="") @@ -1882,8 +2002,10 @@ def cmd_checkin(root: Path, mod, a) -> int: stamp = _utc_now() write_checkin(root, stamp) c = census(root) - for name, page in render_pages(c).items(): + pages = render_pages(c) + for name, page in pages.items(): (root / name).write_text(page, encoding="utf-8") + mirror = write_science_mirror(c, pages["dashboard.md"]) push_lines = [push_note] if push_note else [] if push: @@ -1892,6 +2014,8 @@ def cmd_checkin(root: Path, mod, a) -> int: print(f"\n# The Cortex by project — check-in {stamp}\n") print(f"{len(keys)} project(s) · {c['counts']['running']} running · " f"{c['counts']['open']} open · pages re-rendered") + if mirror: + print(f"Wrote: {mirror}") for line in notes + push_lines: print(line) if c["problems"]: diff --git a/tests/test_cortex_conductor.py b/tests/test_cortex_conductor.py index 55ae2d30..cc79b5f1 100644 --- a/tests/test_cortex_conductor.py +++ b/tests/test_cortex_conductor.py @@ -118,7 +118,8 @@ def wire_cli(root: Path, tmp_path: Path, fail=(), jobs="3002_[0-3] ral RUNNI # --- the census ------------------------------------------------------------ def test_the_census_counts_runs_by_state_and_projects_by_status(skeleton): c = _cortex.census(skeleton) - assert c["counts"] == {"running": 1, "open": 1, "active": 2} + assert c["counts"] == {"running": 1, "open": 1, "active": 2, + "dormant": 1, "retired": 1} assert [d["key"] for d in c["ledgers"]] == ["example", "single", "wound_down"] assert c["checkin"] == "2026-09-02T09:00Z" assert c["problems"] == [] @@ -149,7 +150,8 @@ def test_census_json_is_the_same_dict(skeleton): r = _run(["census", "--json", "--cortex", str(skeleton)]) assert r.returncode == 0, r.stderr c = json.loads(r.stdout) - assert c["counts"] == {"running": 1, "open": 1, "active": 2} + assert c["counts"] == {"running": 1, "open": 1, "active": 2, + "dormant": 1, "retired": 1} assert {d["key"] for d in c["ledgers"]} == {"example", "single", "wound_down"} @@ -165,25 +167,61 @@ def test_census_text_names_every_ledger_and_the_stamp(skeleton): BOARD_ROW = re.compile(r"^\|\s*\[([^\]]+)\]\([^)]*\)[^|]*\|\s*(\d+)\s*\|", re.M) -def test_the_counts_table_is_the_shape_the_brain_board_parses(skeleton): - """`board/_board.py::collect_cortex` regex-parses this table; the three - rows are what its strip shows.""" +def test_the_counts_table_counts_runs_and_every_status_section(skeleton): + """Running · Open · Active · Dormant · Retired, each row linking to its + section.""" page = _cortex.render_dashboard(_cortex.census(skeleton)) assert "| Where | Count |\n|-------|------:|\n" in page assert dict((k, int(n)) for k, n in BOARD_ROW.findall(page)) == \ - {"Running": 1, "Open": 1, "Projects": 2} + {"Running": 1, "Open": 1, "Active": 2, "Dormant": 1, "Retired": 1} + for label in ("Active", "Dormant", "Retired"): + assert f"| [{label}](#{label.lower()}) |" in page assert page.startswith("# PyAutoCortex Dashboard\n\n