Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 106 additions & 14 deletions agents/conductors/cortex/_cortex.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@
`birth <key> --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-<key>`) ·
`dashboard --check|--apply` (`--apply`, like the check-in, also mirrors
`dashboard.md` to `<science_root>/STATE.md` when that root is on this
`dashboard --check|--apply` (`--apply`, like the check-in, also writes
the status tables to `<science_root>/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),
Expand Down Expand Up @@ -1068,30 +1068,122 @@ 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.
#: The Science-side status page (PyAutoBrain#616, #618): not a copy of the
#: board but a few tables to eyeball on the laptop in the Science folder —
#: no check-in prompt, no cards, no logs.
SCIENCE_MIRROR = "STATE.md"

#: A STATE.md Now/Note cell: its first sentence, capped at this many chars.
STATE_CLIP = 120

def mirror_header(c: dict) -> str:
#: Sentence ends: `.`, `!` or `?` followed by whitespace or the end of the
#: text — so the period inside `0.089` or `v1.2` never cuts. A short
#: abbreviation (`e.g.`, `i.e.`, `cf.`, `vs.`) is not an end either.
_SENTENCE_END = re.compile(r"(?<!\be\.g)(?<!\bi\.e)(?<!\bcf)(?<!\bvs)[.!?](?=\s|$)")

def first_sentence(text: str, n: int = STATE_CLIP) -> str:
"""Whitespace collapsed, cut after the first sentence end, capped at `n`
characters with `…`."""
text = " ".join((text or "").split())
m = _SENTENCE_END.search(text)
if m:
text = text[:m.end()]
return _clip(text, n)


def state_note(note: str) -> str:
"""A projects.yaml note for STATE.md: the history from `; previously:` on
dropped, then its first sentence."""
note = re.split(r";\s*previously:", note or "", maxsplit=1)[0]
return first_sentence(note.rstrip(" ;,"))


def _code_roots() -> list[str]:
"""The workspace (code) root from the one resolver — and, when this
Brain runs from a task worktree (`<root>-wt/<task>/…`), the canonical
root that worktree sits beside, where the rows' paths point."""
root = _norm(str(_pyauto_root.pyauto_root()))
roots = [root] if root else []
for parent in Path(root).parents if root else ():
if parent.name.endswith("-wt") and len(parent.name) > 3:
roots.append(str(parent.with_name(parent.name[:-3])))
break
return roots


def state_where(path: str, science: str | None) -> str:
"""A row's tree for STATE.md: relative to the Science root when under it,
`Code/<rest>` under the workspace (code) root, else the path as written."""
path = _norm(path)
if not path:
return "-"
for root, prefix in [(science, "")] + [(r, "Code/") for r in _code_roots()]:
root = _norm(root or "")
if root and path.startswith(root + os.sep):
return prefix + path[len(root) + 1:]
return path


def _state_runs(d: dict | None) -> str:
if not d or not d["runs"]:
return "-"
running, open_, _ = _overview(d)
return f"{running} running · {open_} open"


#: STATE.md's sections, in page order: the ones to look at least, last.
STATE_SECTIONS = ("active", "dormant", "planned", "retired")


def render_science_state(c: dict) -> str:
"""`<science_root>/STATE.md`: a title line, then one table per status —
Active, Dormant, Planned (only when any), Retired."""
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")
checkin = (f"last check-in {c['checkin']}" if c.get("checkin")
else CHECKIN_NEVER)
science = science_root_from(c.get("projects") or {})
L = ["# Science projects", "",
f"Generated from the {board} on {c['generated']} · {checkin}. "
"Do not edit — changes go through `cortex.py`."]
for section in STATE_SECTIONS:
rows = _summary_rows(c, section)
if section == "planned" and not rows:
continue
retired = section == "retired"
third = "Note" if retired else "Now"
L += ["", f"## {section.capitalize()} ({len(rows)})", ""]
if retired:
L += [f"| Project | Where | {third} | Last update |", "|---|---|---|---|"]
else:
L += [f"| Project | Where | {third} | Runs | Last update |",
"|---|---|---|---|---|"]
if not rows:
L.append(f"| _none_ | | | |{'' if retired else ' |'}")
for key, row, d in rows:
where = state_where(local_root(row), science)
where = f"`{_cell(where)}`" if where != "-" else "-"
text = state_note(row.get("note") or "") if retired \
else first_sentence(d["now"] if d else (row.get("note") or ""))
cells = [_cell(key), where, _cell(text or "-")]
if not retired:
cells.append(_state_runs(d))
cells.append((d or {}).get("updated") or "-")
L.append("| " + " | ".join(cells) + " |")
return "\n".join(L) + "\n"


def write_science_mirror(c: dict, page: str) -> Path | None:
"""Write the markdown board to `<science_root>/STATE.md`, where the root
is the one `projects.yaml` agrees on. Off the laptop (no root, or the
def write_science_mirror(c: dict) -> Path | None:
"""Write `render_science_state(c)` to `<science_root>/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")
target.write_text(render_science_state(c), encoding="utf-8")
except OSError as exc:
print(f"note: could not write the Science mirror {target}: {exc}",
file=sys.stderr)
Expand All @@ -1117,7 +1209,7 @@ 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")
mirror = write_science_mirror(c, pages["dashboard.md"])
mirror = write_science_mirror(c)
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)")
Expand Down Expand Up @@ -2005,7 +2097,7 @@ def cmd_checkin(root: Path, mod, a) -> int:
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"])
mirror = write_science_mirror(c)

push_lines = [push_note] if push_note else []
if push:
Expand Down
123 changes: 118 additions & 5 deletions tests/test_cortex_conductor.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,10 +562,11 @@ def test_apply_mirrors_the_markdown_board_into_the_science_root(tmp_skeleton, tm
mirror = science / "STATE.md"
assert mirror.is_file() and str(mirror) in r.stdout.splitlines()[0]
text = mirror.read_text(encoding="utf-8")
assert text.startswith("> **Generated** by `pyauto-brain cortex dashboard --apply` "
"— a mirror of the PyAutoCortex board")
assert "Do not edit this file" in text
assert text.endswith((tmp_skeleton / "dashboard.md").read_text(encoding="utf-8"))
assert text.startswith("# Science projects\n")
assert "Do not edit — changes go through `cortex.py`." in text
# its own status tables, not a copy of the board
assert text == _cortex.render_science_state(_cortex.census(tmp_skeleton))
assert "| example | `active/example` |" in text
# --check is about the Cortex's own pages; the mirror is not one of them
mirror.write_text("hand edit", encoding="utf-8")
r = _run(["dashboard", "--cortex", str(tmp_skeleton), "--check"])
Expand All @@ -590,7 +591,7 @@ def test_rows_in_no_science_category_derive_no_root_and_no_mirror(skeleton):
"""The fixture's own `/tmp/<key>` rows sit in no category at all."""
c = _cortex.census(skeleton)
assert _cortex.science_root_from(c["projects"]) is None
assert _cortex.write_science_mirror(c, "x") is None
assert _cortex.write_science_mirror(c) is None


def test_a_failed_mirror_write_is_one_line_and_never_fails_the_render(
Expand All @@ -605,6 +606,118 @@ def test_a_failed_mirror_write_is_one_line_and_never_fails_the_render(
assert "STATE.md" not in r.stdout


# --- STATE.md: the status tables ------------------------------------------
def _state_census(projects, ledgers=(), checkin="2026-09-02T09:00Z", home=""):
def led(key, now="Doing the thing.", runs=(), updated="2026-09-01"):
return {"key": key, "now": now, "updated": updated,
"runs": [{"state": s} for s in runs],
"status": projects[key]["status"]}
return {"home": home, "generated": "2026-09-03", "checkin": checkin,
"projects": projects,
"ledgers": [led(**kw) for kw in ledgers]}


def _sections(text):
return re.findall(r"^## (\w+) \((\d+)\)$", text, re.M)


def test_state_md_is_tables_in_status_order_with_counts(skeleton):
text = _cortex.render_science_state(_cortex.census(skeleton))
assert _sections(text) == [("Active", "2"), ("Dormant", "1"), ("Retired", "1")]
assert text.startswith("# Science projects\n\nGenerated from the PyAutoCortex "
"board on ")
assert "· last check-in 2026-09-02T09:00Z. Do not edit" in text
# tables only: no check-in prompt, no folds, no cards, no logs
assert "<details>" not in text and "📋" not in text
assert _cortex.CHECKIN_LABEL not in text and "Recent log" not in text
assert [line for line in text.splitlines()[4:]
if line and not line.startswith(("## ", "|"))] == []
assert "| Project | Where | Now | Runs | Last update |" in text
assert "| Project | Where | Note | Last update |" in text
# a run count where there are runs, `-` where there are none
assert re.search(r"^\| example \|.*\| 1 running · 1 open \| \S+ \|$", text, re.M)
assert re.search(r"^\| single \|.*\| - \| \S+ \|$", text, re.M)
# a row with no ledger still shows
assert re.search(r"^\| sleeping \|.*\| - \| - \|$", text, re.M)


def test_state_md_shows_planned_only_when_present_and_a_placeholder_when_empty():
projects = {"a": {"status": "active", "local_path": "/x/a"},
"r": {"status": "retired", "local_path": "/x/r", "note": "done"}}
text = _cortex.render_science_state(_state_census(projects, [{"key": "a"}]))
assert _sections(text) == [("Active", "1"), ("Dormant", "0"), ("Retired", "1")]
assert "| _none_ | | | | |" in text
projects["p"] = {"status": "planned", "local_path": "/x/p", "note": "Soon."}
text = _cortex.render_science_state(_state_census(projects, [{"key": "a"}]))
assert _sections(text) == [("Active", "1"), ("Dormant", "0"),
("Planned", "1"), ("Retired", "1")]
assert "| p | `/x/p` | Soon. | - | - |" in text


def test_state_md_links_the_pages_board_and_says_never_checked_in():
projects = {"a": {"status": "active", "local_path": "/x/a"}}
text = _cortex.render_science_state(_state_census(
projects, [{"key": "a"}], checkin="",
home="https://github.com/SomeOrg/PyAutoCortex"))
assert ("Generated from the [PyAutoCortex board]"
"(https://someorg.github.io/PyAutoCortex/) on 2026-09-03 · "
f"{_cortex.CHECKIN_NEVER}. Do not edit") in text


@pytest.mark.parametrize("text, want", [
("Fit gives 1.999 / 0.089 here. Then more.", "Fit gives 1.999 / 0.089 here."),
("Fixed by SomeLib#1632/#1634 in v2.1. Next", "Fixed by SomeLib#1632/#1634 in v2.1."),
("See #123, then #124.", "See #123, then #124."),
("It works, e.g. on N=5. Next", "It works, e.g. on N=5."),
("Done! And more", "Done!"),
("no sentence\n end at all", "no sentence end at all"),
("", ""),
])
def test_state_md_cuts_at_the_first_sentence_end(text, want):
assert _cortex.first_sentence(text) == want


def test_state_md_caps_a_cell_at_120_characters():
long = "word " * 60
got = _cortex.first_sentence(long)
assert len(got) == 120 and got.endswith("…")
assert _cortex.first_sentence("a" * 120) == "a" * 120
assert len(_cortex.first_sentence("b" * 130 + ". Two.")) == 120


def test_state_md_note_drops_the_history():
note = ("retired 2026-11-13: Complete, on the human's decision; "
"previously: dormant 2026-10-29: waiting. More.")
assert _cortex.state_note(note) == ("retired 2026-11-13: Complete, on the "
"human's decision")
assert _cortex.state_note("retired 2026-10-14: moved. Then x.") == \
"retired 2026-10-14: moved."


def test_state_md_where_paths(tmp_path, monkeypatch):
science = "/w/Science"
assert _cortex.state_where("/w/Science/active/p", science) == "active/p"
assert _cortex.state_where("/w/Science/development/q/", science) == "development/q"
code = tmp_path / "ws"
monkeypatch.setenv("PYAUTO_ROOT", str(code))
assert _cortex.state_where(f"{code}/lib/toy_bench",
science) == "Code/lib/toy_bench"
# from a task worktree, the canonical root beside `<root>-wt` counts too
monkeypatch.setenv("PYAUTO_ROOT", str(tmp_path / "ws-wt" / "task"))
assert _cortex.state_where(f"{code}/lens/x", science) == "Code/lens/x"
assert _cortex.state_where("/old/Science/active/s", science) == "/old/Science/active/s"
assert _cortex.state_where("/w/ScienceX/active/s", science) == "/w/ScienceX/active/s"
assert _cortex.state_where("/w/Science/active/p", None) == "/w/Science/active/p"
assert _cortex.state_where("", science) == "-"


def test_state_md_escapes_pipes_in_cells():
projects = {"a": {"status": "active", "local_path": "/x/a"}}
text = _cortex.render_science_state(_state_census(
projects, [{"key": "a", "now": "x | y."}]))
assert "| x \\| y. |" in text


def test_a_date_only_rerender_is_not_drift(skeleton):
c = _cortex.census(skeleton)
today = dict(c, generated="2026-01-01")
Expand Down
Loading