From 4f3e498b08ae598ade4f16c9abd029bebe2bea8d Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 1 Sep 2026 19:21:48 -0400 Subject: [PATCH 1/2] =?UTF-8?q?cortex=20conductor:=20census,=20dashboard,?= =?UTF-8?q?=20plan,=20gates=20=E2=80=94=20the=20Brain=20side=20of=20the=20?= =?UTF-8?q?Cortex,=20part=20A=20(PyAutoMind#380)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Cortex holds the science state; this is the conductor that reasons over it — the same split as Heart ↔ vitals and Gut ↔ hygiene. It renders the Cortex board, grades the gates and admits ready phases into a laptop slot. It never submits a run and never writes a ruling. - `agents/conductors/cortex/` — the conductor. `_cortex.py` is stdlib-only and Mind-free (the renderer runs bare inside the Cortex's own `dashboard_refresh.yml`, which installs nothing and checks out no Mind, so `_sizing`/`_intake` — which hard-fail without a body map — are copied from, never imported). `/scripts/cortex.py` is imported at runtime as the schema API, so the conductor always reasons with the schema the checkout it is pointed at implements. No path is named in the code: every science path the board prints comes from a `projects.yaml` row. - Verbs: `census [--json]`, `dashboard --check|--apply`, `plan [--budget N] [--lane L]`, `gates [--grade] [--apply]` (a thin wrapper over the Cortex script's own `gates_report`, so the daily grading job needs no Brain), and `collect`, which slice B fills in. - The board's `--check` strips the generation comment **and** the visible `Last updated` banner, so a re-render on a new date is not drift — the Mind's normaliser strips only the comment, which is why its refresh self-heals with an empty commit most nights. - Board family: `policy.yaml boards:` gains the Cortex, `_theme` gains its palette (`#a5177d` / `#ff7ad9`, 6.96:1 and 8.14:1) and its mark, and `_board.collect_cortex()` composes the Cortex's own counts into the morning Resume strip (silently absent when no Cortex is checked out). - `resolve_cortex()` in `agents/_common.sh`; `bin/_pyauto_root.sh` learns PyAutoCortex (it had drifted from `agents/_pyauto_root.py`). - `tests.yml` checks out a third repo: the conductor's tests render against PyAutoCortex's own `tests/fixtures/skeleton`, the fixture that IS the schema's witness, and skip cleanly when it is absent. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01SESCzU1FcwktEAdTZfmf3j --- .github/workflows/tests.yml | 21 +- AGENTS.md | 1 + agents/_common.sh | 5 + agents/conductors/cortex/AGENTS.md | 96 +++ agents/conductors/cortex/_cortex.py | 1179 +++++++++++++++++++++++++++ agents/conductors/cortex/cortex.sh | 27 + bin/_pyauto_root.sh | 3 +- bin/pyauto-brain | 5 +- board/_board.py | 37 + board/_theme.py | 25 + config/policy.yaml | 1 + docs/organs/cortex.md | 25 + skills/COMMANDS.md | 3 +- skills/cortex/SKILL.md | 10 + skills/cortex/cortex.md | 46 ++ tests/test_board.py | 35 + tests/test_cortex_conductor.py | 403 +++++++++ 17 files changed, 1915 insertions(+), 7 deletions(-) create mode 100644 agents/conductors/cortex/AGENTS.md create mode 100644 agents/conductors/cortex/_cortex.py create mode 100755 agents/conductors/cortex/cortex.sh create mode 100644 skills/cortex/SKILL.md create mode 100644 skills/cortex/cortex.md create mode 100644 tests/test_cortex_conductor.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 21f68d92..a0ad5517 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -18,15 +18,20 @@ name: Brain Tests # PRs on drift Brain cannot cause; organs not checked out (Heart, Hands) are # skipped by the check itself, so this gates exactly Brain. # -# TWO repos are checked out on purpose. PyAutoBrain alone cannot even COLLECT +# THREE repos are checked out on purpose. PyAutoBrain alone cannot even COLLECT # the suite: `agents/faculties/sizing/_sizing.py` reads the body map # (`BRAIN_HOME.parent / "PyAutoMind" / "repos.yaml"`) at import time and is # deliberately strict, so `test_policy_seams.py` and `test_sizing_paths.py` # error out before a single test runs. Checking PyAutoMind out as a sibling # reproduces the workspace layout the code assumes — the same layout the -# firewall gate's `--root` needs. Both repos are public, so the default -# GITHUB_TOKEN suffices — no PAT. No other sibling repo is needed (verified by -# running the suite against exactly this two-repo layout). +# firewall gate's `--root` needs. PyAutoCortex is the third: the cortex +# conductor imports the Cortex's own `scripts/cortex.py` at runtime and its +# tests render the board against that repo's `tests/fixtures/skeleton`, the +# fixture that IS the schema's witness — a copied fixture here would drift +# from the schema it claims to test (the tests skip cleanly when the checkout +# is absent, so a local run without it still passes). All three repos are +# public, so the default GITHUB_TOKEN suffices — no PAT. No other sibling repo +# is needed (verified by running the suite against exactly this layout). # One run per commit: PR events carry the CI; pushes only build main. # Superseded runs are cancelled on PR refs only — a cancelled main run would @@ -60,6 +65,14 @@ jobs: with: repository: PyAutoLabs/PyAutoMind path: PyAutoMind + # The science organ the cortex conductor reasons over: its + # `scripts/cortex.py` is the schema API and its skeleton fixture is + # what `test_cortex_conductor.py` renders. + - name: Checkout PyAutoCortex (the Cortex schema + fixture) + uses: actions/checkout@v4 + with: + repository: PyAutoLabs/PyAutoCortex + path: PyAutoCortex - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: diff --git a/AGENTS.md b/AGENTS.md index 561b9a20..9b7109d7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -141,6 +141,7 @@ the `/` slash commands. | `workspace` | The voice — the organism's expressive function: plan/survey workspace + HowTo example authorship (workspace\|howto registers) — WorkspaceDecision (never writes) | `bin/pyauto-brain workspace` | | `eyes` | The perceptive function — the organism's sense of its own appearance: survey/review a visualization workspace's figure surface, critiques route to intake/start_dev — EyesSurvey/EyesReviewSurface (never renders, never edits) | `bin/pyauto-brain eyes` | | `profiling` | The proprioceptive function — the organism's sense of its own effort: campaign/ingest/triage plans over the autolens_profiling workspace — ProfilingDecision | `bin/pyauto-brain profiling` | +| `cortex` | The learning function — where the organism finds out what is true: reason over PyAutoCortex (phases, gates, rulings), render its board, grade the gates, admit ready phases into a slot — never submits a run, never writes a ruling | `bin/pyauto-brain cortex` | | `hygiene` | The maintenance function — the organism's sense of its own upkeep: code-quality debt (dev-loop cost + tidiness), delegating fixes — HygieneDecision | `bin/pyauto-brain hygiene` | | `clone` | The Mitosis Agent: partition the reference assistant, analyze the domain, emit the CloneDecision; --apply --mode lightweight-seed delegates the seed birth to Build; 'clone sync' patches the reference's generic-file diff onto the born siblings (dry run by default; rejected hunks are a human decision) | `bin/pyauto-brain clone` | | `build` | Coordinate execution: consult the vitals faculty, then delegate to PyAutoHands | `bin/pyauto-brain build` | diff --git a/agents/_common.sh b/agents/_common.sh index d7eda85f..27c7f996 100755 --- a/agents/_common.sh +++ b/agents/_common.sh @@ -68,6 +68,11 @@ _resolve_dir() { # resolve_mind — locate the PyAutoMind checkout (the organism's intent store). resolve_mind() { _resolve_dir PYAUTO_MIND PyAutoMind; } +# resolve_cortex — locate the PyAutoCortex checkout (the organism's science +# state: phases, gates, runs, rulings of record). Resolved independently of the +# Mind so a session holding one organ and not the other still works. +resolve_cortex() { _resolve_dir PYAUTO_CORTEX PyAutoCortex; } + # resolve_memory — locate the PyAutoMemory checkout (the organism's long-term # scientific/architectural knowledge). Optional: the Feature Agent degrades # gracefully when memory is absent rather than inventing context. diff --git a/agents/conductors/cortex/AGENTS.md b/agents/conductors/cortex/AGENTS.md new file mode 100644 index 00000000..afdc1e02 --- /dev/null +++ b/agents/conductors/cortex/AGENTS.md @@ -0,0 +1,96 @@ +# Cortex agent + +> **Tier: conductor** — a front-door agent you *drive*. The *learning +> function* — where the organism finds out what is true: it reasons over +> PyAutoCortex (the science body map, the pre-registered phases, the rulings +> of record), renders the Cortex board, grades the gates and admits ready +> phases into a laptop slot. It **never submits a run and never writes a +> ruling**: the run is the human's act, the verdict is the human's word, and +> the ruling file is the Cortex script's to write. + +The same split the organism already uses twice — **Heart ↔ vitals**, **Gut ↔ +hygiene**: the organ keeps the state, the conductor reasons over it. The +Cortex holds runs and rulings the way the Mind holds prompts and PRs; this is +the Cortex's intake-and-dashboard conductor. + +## Verbs + +| Verb | Question | Emits | +|------|----------|-------| +| `census` | What is the Cortex holding? | phase counts by state, the board's section counts, rulings, projects, batches, epics (`--json` for the lot) | +| `dashboard --check` | Are the committed pages current? | exit 0 current · **1 stale** · 2 no checkout · 3 unreadable tree | +| `dashboard --apply` | — | writes `dashboard.md` + `dashboard.html` | +| `gates [--grade] [--apply]` | What is each gated phase waiting on, and has it cleared? | the refs, a verdict per phase, and with `--apply` the `gated → ready` flips | +| `plan [--budget N]` | Which ready phases fit the slot? | `== CortexPlan ==` — members against the review-minute budget, plus the launch lines | +| `collect` | (phase 2b) score a pulled run into a packet member | — | + +``` +pyauto-brain cortex # census +pyauto-brain cortex dashboard --apply +pyauto-brain cortex gates --grade +pyauto-brain cortex plan --budget 30 +pyauto-brain cortex --cortex # another checkout +``` + +## Where the Cortex is + +`--cortex ` → `$PYAUTO_CORTEX` → beside this PyAutoBrain checkout → +`$PYAUTO_ROOT/PyAutoCortex`. Its own resolver (`resolve_cortex` in +`agents/_common.sh`, mirrored in `_cortex.py`), never an extension of the +Mind's: a session holding one organ and not the other still works. + +## What it reads, and what it refuses to read + +- `/scripts/cortex.py` is imported at runtime and is the schema + API: `load_phases`, `load_rulings`, `load_projects`, `gates_report`, + `batch_records`, `move_phase`. The conductor always reasons with the schema + the checkout it is pointed at implements. +- **Stdlib only, and Mind-free.** The renderer runs bare inside the Cortex's + own `dashboard_refresh.yml`, which installs nothing and checks out no + PyAutoMind — so `_cortex.py` imports neither `_sizing` nor `_intake` (both + hard-fail without a Mind checkout). The Mind's renderer helpers are copied, + not imported; that duplication is the price of a one-repo render. +- **No path is named in this code.** Science projects live outside the + workspace; the one place carrying such a path is the Cortex's own + `projects.yaml`, and every path the board prints is read from a row of it. + +## The board + +Sections, in the reading order of a slot: **Awaiting ruling** (pulled and +awaiting-ruling phases, ordered failures → a ruling is required → clean) → +**Running / submitted** (job ids, wall against the phase's budget, the last +`refreshed:` line) → **Ready** → **Gated** (the open refs) → **Recent +rulings** → **Epics** (each card links its Mind half) → **Projects** (the +where-to-look table straight from `projects.yaml`). A counts table near the +top is what `board/_board.py` reads for the Brain board's Cortex strip. + +`--check` compares the pages with the generation comment **and** the visible +`Last updated` banner stripped, so a re-render on a new date is not drift — +the Mind's normaliser strips only the comment, which is why its refresh +workflow self-heals with an empty commit most nights. + +## The admission rule (`plan`) + +A phase is plannable when its `State:` is `ready`, its `Witness:` is +registered, its `Budget:` is set and its lane is the session's — detected the +way the batch conductor detects it (`gh` on PATH ⇒ `local-dev`). Cheapest +first against `--budget` (default 45 review-minutes). **No autonomy cap is +consulted**: science members are supervised by definition, and the ruling is +the human's. A cloud session reports the ready count and plans nothing — a +science run is launched from the machine that can reach the queue. + +## Gate grading + +`gates --grade [--apply]` is a thin wrapper over the Cortex script's own +`gates_report(root, grade=…, write=…)`. The grading rule (a PR clears when it +merged; an issue when it closed as `completed`; anything unreadable fails +closed) and the writes live there, so the Cortex's daily `gates_grade.yml` +runs them with no Brain checkout at all. `--apply` is this surface's spelling +of the script's `--write`, and it may only ever move `gated → ready` (and +demote a `ready` phase whose gate reopened). + +## What it never does + +Submits a job · writes or edits a ruling · reads `sacct` as health · touches +RAL · consults an autonomy cap · edits a phase except through the Cortex +script's own `move`. diff --git a/agents/conductors/cortex/_cortex.py b/agents/conductors/cortex/_cortex.py new file mode 100644 index 00000000..4d09fb8b --- /dev/null +++ b/agents/conductors/cortex/_cortex.py @@ -0,0 +1,1179 @@ +#!/usr/bin/env python3 +"""agents/conductors/cortex/_cortex.py — core for the Cortex Agent. + +The Cortex Agent is the *learning function* of PyAutoBrain: the conductor that +reasons over PyAutoCortex, the organ where the organism learns what is true. +The Cortex holds the state — science phases, their pre-registered witnesses, +their runs and the rulings of record; this conductor holds the reasoning: it +renders the Cortex board, grades the gates, admits ready phases into a laptop +slot and (phase 2b) scores what a pull brought back. It **never submits** and +never edits a ruling: the run is the human's act and the verdict is theirs. + +The same split as Heart ↔ vitals and Gut ↔ hygiene — the organ keeps the +state, the conductor reasons over it. + +Three constraints shape this module: + +- **Stdlib only, and Mind-free.** The Cortex renderer runs bare inside the + Cortex's own `dashboard_refresh.yml`, which installs nothing and checks out + no PyAutoMind. So this module imports neither `_sizing` nor `_intake` (both + hard-fail without a Mind checkout: `_sizing.py` reads the body map at + import). The renderer helpers the Mind's page uses are *copied* here rather + than imported, deliberately — the duplication is the price of a page that + renders with one repo checked out. +- **The Cortex script is the API.** `/scripts/cortex.py` is + stdlib-only, has no import-time side effects and exposes pure functions + (`load_phases`, `load_rulings`, `load_projects`, `gates_report`, …). It is + imported at runtime from the resolved root, so this conductor always reasons + with the schema the checkout it is pointed at actually implements. +- **No path is named here.** Science projects live outside the workspace; the + one place that carries such a path is the Cortex's own `projects.yaml`, and + every path this module prints is read from a row of it at runtime. + +Verbs: `census [--json]` · `dashboard --check|--apply` · `plan [--budget N] +[--lane L]` · `gates [--grade] [--apply]` · `collect` (phase 2b). + +Exit codes: 0 ok · 1 dashboard drift (the `dashboard_refresh.yml` contract) · +2 bad args / no Cortex checkout · 3 the Cortex tree could not be read. +`gates` passes the Cortex script's own rc through (1 = an unreadable ref, +which fails closed). +""" + +from __future__ import annotations + +import argparse +import datetime as _dt +import html as _html +import importlib.util +import json +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path + +BRAIN_HOME = Path(__file__).resolve().parents[3] + +# The one workspace-root resolver (agents/_pyauto_root.py, mirrored by +# bin/_pyauto_root.sh) — never a literal path. +sys.path.insert(0, str(BRAIN_HOME / "agents")) +import _pyauto_root # noqa: E402 + +# The shared board theme: the one place that answers "what does a one-tap +# board look like". Presentation only — stylesheet, hero, pills, stats — so +# this page is visibly the same family as the Mind's and the Brain's. +sys.path.insert(0, str(BRAIN_HOME / "board")) +from _theme import ( # noqa: E402 + JS as _THEME_JS, boards_footer, css as _theme_css, hero, pills, stats, +) + +THEME_ORGAN = "cortex" # whose logo this page wears +CORTEX_REPO = "PyAutoCortex" # an organ name, not an instance fact + +# Exit codes — the `dashboard_refresh.yml` contract lives on these. +RC_OK, RC_DRIFT, RC_USAGE, RC_UNREADABLE = 0, 1, 2, 3 + +DEFAULT_REVIEW_BUDGET = 45 # one laptop slot's review-minutes (batch's default) +LOCAL_LANE = "local-dev" +RECENT_RULINGS = 12 + + +class CortexUnavailable(Exception): + """No usable PyAutoCortex checkout at the resolved root.""" + + +# ----------------------------------------------------------------- roots --- +def resolve_root(explicit: str | None = None) -> Path: + """Where the Cortex is: `--cortex` → `$PYAUTO_CORTEX` → beside this + Brain checkout → `$PYAUTO_ROOT/`. + + Deliberately its own resolver rather than an extension of the Mind's: + the two organs are resolved independently, so a session holding one and + not the other still works. + """ + if explicit: + return Path(explicit).expanduser() + env = os.environ.get("PYAUTO_CORTEX") + if env: + return Path(env).expanduser() + sibling = BRAIN_HOME.parent / CORTEX_REPO + if sibling.is_dir(): + return sibling + return _pyauto_root.pyauto_root() / CORTEX_REPO + + +_SCRIPTS: dict[str, object] = {} + + +def find_script(root: Path) -> Path | None: + """The `scripts/cortex.py` that governs the tree at `root`. + + A *data root* need not be a checkout: every verb in the Cortex's own + script takes `root: Path`, so a fixture tree (`tests/fixtures/skeleton`) + is a legitimate root with no `scripts/` of its own. So look in the root, + then in its ancestors (the checkout the fixture lives in), then in the + resolved checkout — the schema that reads a tree is the one shipped + beside it. + """ + for candidate in (root, *root.resolve().parents): + script = candidate / "scripts" / "cortex.py" + if script.is_file(): + return script + fallback = resolve_root() / "scripts" / "cortex.py" + return fallback if fallback.is_file() else None + + +def load_cortex(root: Path): + """Import the Cortex's own schema module for the tree at `root`. + + Loaded by file location under a per-path module name so two checkouts can + be read in one process without the first import shadowing the second. The + script's directory also goes on `sys.path`, as the Cortex's own tooling + expects. + """ + if not root.is_dir(): + raise CortexUnavailable( + f"no Cortex tree at {root}. Set PYAUTO_CORTEX, clone " + f"{CORTEX_REPO} beside PyAutoBrain, or pass --cortex .") + script = find_script(root) + if script is None: + raise CortexUnavailable( + f"no Cortex checkout at {root} (expected " + f"{root / 'scripts' / 'cortex.py'}). Set PYAUTO_CORTEX, clone " + f"{CORTEX_REPO} beside PyAutoBrain, or pass --cortex .") + key = str(script.resolve()) + if key in _SCRIPTS: + return _SCRIPTS[key] + parent = str(script.parent) + if parent not in sys.path: + sys.path.insert(0, parent) + spec = importlib.util.spec_from_file_location( + f"_cortex_script_{abs(hash(key))}", script) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + _SCRIPTS[key] = mod + return mod + + +OWNER_IN_DOCS = re.compile(r"https://github\.com/([\w.-]+)/PyAuto[\w.-]*") + + +def _home(root: Path) -> str: + """`https://github.com//` for this checkout, `''` if unknown. + + The renderer must produce byte-identical pages on a laptop and inside the + Cortex's own refresh workflow, or `--check` would report permanent drift + and the self-heal would commit a page every night. So the owner is read + from a **file that travels with the repo** — its own README/AGENTS links, + the same declared surface the Mind's renderer reads out of `repos.yaml` — + and only falls back to the git remote, which is not guaranteed readable in + every CI container. No org is named here; a fork's Cortex carries its own. + """ + for name in ("README.md", "AGENTS.md"): + f = root / name + if f.is_file(): + m = OWNER_IN_DOCS.search(f.read_text(encoding="utf-8", + errors="replace")) + if m: + return f"https://github.com/{m.group(1)}/{CORTEX_REPO}" + return _home_from_git(root) + + +def _home_from_git(root: Path) -> str: + """The fallback: the checkout's own `origin`. The toplevel guard keeps a + fixture tree *inside* another repo from borrowing that repo's remote.""" + try: + top = subprocess.run(["git", "-C", str(root), "rev-parse", + "--show-toplevel"], capture_output=True, + text=True, timeout=20) + if top.returncode != 0: + return "" + if Path(top.stdout.strip()).resolve() != root.resolve(): + return "" + r = subprocess.run(["git", "-C", str(root), "remote", "get-url", + "origin"], capture_output=True, text=True, + timeout=20) + except (OSError, subprocess.SubprocessError): + return "" + if r.returncode != 0: + return "" + url = r.stdout.strip() + m = re.match(r"^(?:https://github\.com/|git@github\.com:)" + r"([\w.-]+)/([\w.-]+?)(?:\.git)?$", url) + return f"https://github.com/{m.group(1)}/{m.group(2)}" if m else "" + + +# ------------------------------------------------------------- the census --- +# Phase states, grouped into the sections the board shows. A state that is in +# no group renders in no section (planned phases are scope, not work; dropped +# and accepted phases are history the rulings section carries). +AWAITING_STATES = ("pulled", "awaiting-ruling") +LIVE_STATES = ("submitted", "running") +FAILED_RUN_STATES = ("failed", "timeout", "void", "legacy_wrong") + +# One section: (key, title, source path in the repo, blurb). +SECTIONS = ( + ("awaiting", "Awaiting ruling", "phases/", + "Results are in and nothing is running — the human's verdict is the only " + "thing outstanding. Ordered failures first, then the phases a ruling is " + "required for, then the clean ones."), + ("live", "Running / submitted", "phases/", + "On the queue or on the machine. Wall is what the run lines record at the " + "last refresh, against the phase's own budget."), + ("ready", "Ready", "phases/", + "Gate cleared, witness registered — these are what `cortex plan` admits " + "into a laptop slot."), + ("gated", "Gated", "phases/", + "Waiting on development work. The daily grading job flips a phase to " + "ready when every reference it names has closed."), + ("rulings", "Recent rulings", "rulings/", + "The ledger of record, newest first. A verdict recorded only outside the " + "Cortex does not exist."), + ("epics", "Epics", "epics.md", + "Long-running programmes whose science half lives here; each card links " + "its development half in the Mind."), + ("projects", "Projects", "projects.yaml", + "The science body map — where each project lives, what syncs it and " + "where its witness lands."), +) + +REFRESH_BLURB = ( + "generated from `phases/`, `rulings/`, `batches/`, `epics.md` and " + "`projects.yaml`, so it is only as current as they are. " + "`dashboard_refresh.yml` re-renders it on every push to `main`, and the " + "daily gate grading flips cleared gates before it runs." +) + + +def _mins(value: str) -> int | None: + """`H+:MM` → minutes, or None.""" + m = re.fullmatch(r"(\d+):(\d{2})", (value or "").strip()) + return int(m.group(1)) * 60 + int(m.group(2)) if m else None + + +def _int(value: str) -> int | None: + v = (value or "").strip() + return int(v) if v.isdigit() else None + + +# The batch record's own grammar, read here rather than through the Cortex +# script's `_record_members`: that helper keeps only the FIRST value of a +# repeated key, and `- refreshed:` is repeated once per pull — which is +# exactly the live-progress signal this board wants. +RECORD_KEY = re.compile(r"^- ([a-z][a-z0-9-]*):(?:\s+(.*?))?\s*$") +REFRESHED = re.compile(r"^(?P\S+)(?:\s+[—-]+\s+(?P.*))?$") + + +def read_record(text: str, member_re=None) -> dict: + """One batch record as `{"keys": {k: [v, …]}, "members": [row, …]}`. + + Every value of every key is kept, in file order — the lossless reader the + live-progress strip and (phase 2b) `collect` both need. + """ + keys: dict[str, list[str]] = {} + members: list[dict] = [] + in_members = False + for lineno, raw in enumerate(text.split("\n"), 1): + m = RECORD_KEY.match(raw) + if m: + in_members = m.group(1) == "members" + keys.setdefault(m.group(1), []).append((m.group(2) or "").strip()) + continue + if in_members and raw.startswith(" - "): + row = {"lineno": lineno, "raw": raw} + mm = member_re.match(raw.replace("--", "—")) if member_re else None + if mm: + row.update({k: (mm.groupdict().get(k) or "").strip() + for k in ("slug", "path", "runs", "minutes", "state") + if k in mm.groupdict()}) + members.append(row) + elif raw.strip() and not raw.startswith(" ") and in_members: + in_members = False + return {"keys": keys, "members": members} + + +def _refresh_index(root: Path, mod) -> dict: + """`{slug: {"at": …, "note": …, "slot": …}}` — the newest `refreshed:` + line naming each phase slug, across every batch record.""" + index: dict[str, dict] = {} + for path in mod.batch_records(root): + slot = path.stem + rec = read_record(path.read_text(encoding="utf-8"), mod.MEMBER_RE) + slugs = [m.get("slug", "") for m in rec["members"] if m.get("slug")] + for value in rec["keys"].get("refreshed", []): + m = REFRESHED.match(value.strip()) + if not m: + continue + at, note = m.group("at"), (m.group("note") or "").strip() + for slug in slugs: + if slug and slug in note: + prev = index.get(slug) + if prev is None or at >= prev["at"]: + index[slug] = {"at": at, "note": note, "slot": slot} + return index + + +def _phase_row(mod, ph, refreshed: dict) -> dict: + refs, bad_refs = mod.gate_refs(ph.get("Gates")) + runs = [{"ident": r.ident, "state": r.state, "partition": r.partition, + "date": r.date, "wall": r.wall, "note": r.note} + for r in ph.runs] + walls = [_mins(r["wall"]) or 0 for r in runs] + budget = ph.get("Budget") + return { + "rel": ph.rel, + "slug": ph.slug, + "title": ph.title or ph.slug, + "project": ph.get("Project") or ph.project_dir, + "phase": _int(ph.get("Phase")), + "state": ph.state, + "gates": refs, + "bad_gates": bad_refs, + "gates_cleared": ph.get("Gates-cleared"), + "gate_override": ph.get("Gate-override"), + "witness": ph.get("Witness"), + "budget": budget, + "budget_minutes": _mins(budget), + "runs": runs, + "wall_minutes": max(walls) if walls else 0, + "ruling": ph.get("Ruling"), + "epic": ph.get("Epic"), + "lane": ph.get("Lane") or LOCAL_LANE, + "review_minutes": _int(ph.get("Review-minutes")), + "refreshed": refreshed.get(ph.slug), + "failed_runs": [r["ident"] for r in runs + if r["state"] in FAILED_RUN_STATES], + } + + +def _ruling_row(mod, r) -> dict: + return { + "id": r.id, + "rel": r.rel, + "title": (r.title or r.id).split(" — ", 1)[-1] if r.title else r.id, + "verb": r.get("Ruling"), + "phase": r.get("Phase"), + "project": r.get("Project"), + "batch": r.get("Batch"), + "reviewed_at": r.get("Reviewed-at"), + "supersedes": r.get("Supersedes"), + } + + +EPIC_HEAD = re.compile(r"^## (\S+)\s*$") +EPIC_FIELD = re.compile(r"^- ([a-z-]+):\s*(.*?)\s*$") + + +def parse_epics(path: Path) -> list[dict]: + """`epics.md` entries — `## ` then `- key: value` lines. The Cortex + half additionally carries `- mind-half:`, the slug of the Mind's entry.""" + if not path.is_file(): + return [] + entries: list[dict] = [] + cur: dict | None = None + fenced = False + for line in path.read_text(encoding="utf-8").splitlines(): + # `epics.md` documents its own schema in a fenced block whose body is + # a `## ` template — reading that as an entry would put a ghost + # card on the board of an empty Cortex. + if line.startswith("```"): + fenced = not fenced + continue + if fenced: + continue + head = EPIC_HEAD.match(line) + if head: + cur = {"slug": head.group(1)} + entries.append(cur) + continue + field = EPIC_FIELD.match(line) + if field and cur is not None: + cur[field.group(1)] = field.group(2) + return entries + + +def census(root: Path) -> dict: + """Everything the board, the plan and the counts need, in one read.""" + mod = load_cortex(root) + projects, project_problems = mod.load_projects(root) + phases, phase_problems = mod.load_phases(root) + rulings, ruling_problems = mod.load_rulings(root) + refreshed = _refresh_index(root, mod) + + rows = [_phase_row(mod, ph, refreshed) for ph in phases] + by_state: dict[str, int] = {} + for r in rows: + by_state[r["state"] or "?"] = by_state.get(r["state"] or "?", 0) + 1 + + # A ruling that another ruling supersedes is not the standing verdict. + successors = {r.get("Supersedes") for r in rulings if r.get("Supersedes")} + ruling_rows = [_ruling_row(mod, r) for r in rulings] + for row in ruling_rows: + row["head"] = row["id"] not in successors + ruling_rows.sort(key=lambda r: r["id"], reverse=True) + + awaiting = [r for r in rows if r["state"] in AWAITING_STATES] + # failures → a ruling is required → clean, per the section's own promise. + awaiting.sort(key=lambda r: (0 if r["failed_runs"] else + 1 if r["state"] == "awaiting-ruling" else 2, + r["project"], r["phase"] or 0, r["rel"])) + live = sorted([r for r in rows if r["state"] in LIVE_STATES], + key=lambda r: (r["project"], r["phase"] or 0, r["rel"])) + ready = sorted([r for r in rows if r["state"] == "ready"], + key=lambda r: (r["review_minutes"] or 999, r["project"], + r["phase"] or 0, r["rel"])) + gated = sorted([r for r in rows if r["state"] == "gated"], + key=lambda r: (r["project"], r["phase"] or 0, r["rel"])) + + return { + "root": str(root), + "home": _home(root), + "generated": _dt.date.today().isoformat(), + "phases": rows, + "by_state": by_state, + "awaiting": awaiting, + "live": live, + "ready": ready, + "gated": gated, + "rulings": ruling_rows, + "projects": projects, + "epics": parse_epics(root / "epics.md"), + "batches": [p.stem for p in mod.batch_records(root)], + "reviews": [p.stem for p in mod.batch_reviews(root)], + "problems": project_problems + phase_problems + ruling_problems, + } + + +def section_counts(c: dict) -> list[tuple[str, str, int]]: + """`(key, title, count)` for the counts table — the four live sections + plus the ruling ledger. `board/_board.py` reads this table.""" + sizes = {"awaiting": len(c["awaiting"]), "live": len(c["live"]), + "ready": len(c["ready"]), "gated": len(c["gated"]), + "rulings": len(c["rulings"])} + return [(key, title, sizes[key]) for key, title, _src, _blurb in SECTIONS + if key in sizes] + + +# --------------------------------------------------------- render helpers --- +# Copied from the Mind's renderer rather than imported: `_intake.py` cannot be +# imported without a PyAutoMind checkout, and this page renders with only the +# Cortex and the Brain present. +def _cell(value: str) -> str: + return str(value).replace("|", "\\|") + + +def _attr(value: str) -> str: + """Escape a string for a double-quoted HTML attribute.""" + return (str(value).replace("&", "&").replace('"', """) + .replace("<", "<").replace(">", ">")) + + +def _summary_label(value: str) -> str: + """Text rendered inside a `` — HTML, not markdown.""" + value = str(value).replace("", "").strip() + value = _html.escape(value, quote=False) or "Untitled" + return re.sub(r"`([^`]+)`", r"\1", value) + + +def _md_inline(text: str) -> str: + """The two inline markdown constructs this module authors, as HTML.""" + text = re.sub(r"`([^`]+)`", r"\1", text) + return re.sub(r"\*\*([^*]+)\*\*", r"\1", text) + + +def _task_row(summary: str, payload: str) -> str: + """One row as a collapsed `
` whose 📋 summary IS the line and + whose body is the fenced payload GitHub renders a copy button on.""" + return "\n".join([f"
📋 {summary}", + "", + "```", + payload, + "```", + "", + "
"]) + + +def _items(chunks: list) -> list: + out = [] + for chunk in chunks: + out += [chunk, ""] + return out[:-1] if out else [] + + +def _html_task(text_html: str, payload: str) -> str: + """One row on the HTML page: a real copy button, then the text.""" + return (f'

{text_html}

') + + +def _pages_url(home: str) -> str: + """The GitHub Pages site URL for a repo home, `''` when underivable.""" + m = re.match(r"https://github\.com/([^/]+)/([^/]+)$", home) + return f"https://{m.group(1).lower()}.github.io/{m.group(2)}/" if m else "" + + +def _board_links(home: str, current: str) -> list: + """The cross-board footer nav, from PyAutoBrain's declared config surface + (`config/policy.yaml` `board: boards:`), skipping this page's own entry. + + Stdlib regex on the one-pair-per-line block, not yaml — this renderer + runs bare in the Cortex's refresh workflow, which installs nothing. + """ + m = re.match(r"https://github\.com/([^/]+)/", home or "") + policy = BRAIN_HOME / "config" / "policy.yaml" + if not m or not policy.is_file(): + return [] + owner = m.group(1).lower() + block = re.search(r"^ boards:\n((?: \w+: \S+\n)+)", + policy.read_text(encoding="utf-8"), re.M) + if not block: + return [] + pairs = re.findall(r"^ (\w+): (\S+)$", block.group(1), re.M) + return [(name, f"https://{owner}.github.io/{repo}/") + for name, repo in pairs if name != current] + + +def _anchor(title: str) -> str: + """GitHub's heading anchor for a section title.""" + slug = re.sub(r"[^a-z0-9 -]", "", title.lower()) + return slug.replace(" ", "-") + + +def _src_url(blob: str, src: str) -> str: + """The GitHub URL of a section's source — `tree` for a directory.""" + if not blob: + return src + return (blob.replace("/blob/main/", "/tree/main/") + src) if src.endswith("/") \ + else blob + src + + +# ------------------------------------------------------------- the payloads --- +# Every row hands the reader the next command rather than a decision. The +# science verbs stay the Cortex script's and the run stays the human's. +def _ruling_payload(r: dict) -> str: + return (f"Review the PyAutoCortex phase {r['rel']} and help me rule on it: " + f"read its `## Witness` and the pulled evidence under its " + f"`## Where to look`, score the witness, then draft the ruling " + f"body for my approval and run `python3 scripts/cortex.py rule " + f"{r['rel']} --body `.") + + +def _live_payload(r: dict, projects: dict) -> str: + row = projects.get(r["project"], {}) + cli, path = row.get("sync_cli", ""), row.get("local_path", "") + if cli and path and "jobs" in (row.get("sync_verbs") or []): + return f"cd {path} && {cli} jobs" + return (f"Report where the runs of the PyAutoCortex phase {r['rel']} " + f"({', '.join(x['ident'] for x in r['runs']) or 'no runs'}) stand.") + + +def launch_payload(r: dict, projects: dict) -> list[str]: + """The launch lines for a ready phase: the phase, the project's own + submit verb, and the move that records the job id. No decision rides + here — everything decided was decided when the plan was approved.""" + row = projects.get(r["project"], {}) + cli, path = row.get("sync_cli", ""), row.get("local_path", "") + lines = [r["rel"]] + if cli and path and "submit" in (row.get("sync_verbs") or []): + lines.append(f"cd {path} && {cli} submit ", "", ""] + return "\n".join(H) + "\n" + + +# The two lines that change on a re-render without the page changing: the +# generation comment and the visible freshness banner. The Mind's normaliser +# strips only the comment, which is why its `--check` drifts every day and +# self-heals with an empty commit; the Cortex strips both. +def dashboard_body(page: str) -> str: + """The page minus every stamp `--check` must not read as drift.""" + def keep(line: str) -> bool: + return not (line.startswith("