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
91 changes: 62 additions & 29 deletions agents/conductors/cortex/_cortex.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,10 +481,9 @@ def run_line(r: dict) -> str:

# A project is one disclosure: the closed summary is everything a glance
# needs (name, purpose, the recorded run counts, the ledger's newest date);
# opening it shows the current position, the resume chip, the runs as an
# aligned table, and — each collapsed again — the recent history and the
# technical locations. Every field is the parsed ledger's own; nothing is
# read out of a run's prose.
# opening it shows registration and locations, then current position with
# an icon-only resume action, the runs table and collapsed recent history.
# Every field is the parsed ledger's own; nothing is read out of a run's prose.
LOG_SHOWN = 5


Expand All @@ -511,15 +510,38 @@ def _history_label(d: dict) -> str:
return f"Recent log — {shown} of {len(d['log'])} {noun}"


def _registration(d: dict) -> tuple[str, str]:
"""Display explicit registration facts without changing the source ledger."""
now = d["now"]
match = re.match(
r"Registered (\d{4}-\d{2}-\d{2})(?: \(PyAutoCortex#\d+\))?:\s*", now
)
if match:
try:
_dt.date.fromisoformat(match[1])
except ValueError:
pass # malformed metadata remains visible as source prose
else:
return match[1], now[match.end():]
opened = [e["date"] for e in d["log"]
if e["kind"] == "note" and e["text"].strip() == "ledger opened"]
return min(opened) if opened else "not recorded", now


def _card_md(d: dict, row: dict, blob: str) -> list[str]:
issue = (f"[{d['issue']}]({d['issue_url']})" if d["issue_url"]
else "no issue yet")
registered, now = _registration(d)
L = [f'<details id="project-{_attr(d["key"])}"><summary><b>{_esc(d["key"])}</b> — '
f"{_esc(d['summary'])} · {_esc(_overview_text(d))}</summary>", "",
f"{d['status']} · {d['partition']} · {issue}", "",
"**Current position**", "", _md_text(d["now"]) or "_(nothing yet)_", ""]
f"**Registered:** {registered}", "",
f"**Local:** `` {d['local_path']} ``", "",
f"**RAL:** `` {d['ral_root']} ``", "",
"**Current position**", "", _md_text(now) or "_(nothing yet)_", ""]
if d["status"] == "active":
L += [_task_row(f"resume {d['key']}", resume_payload(d["key"], row)), ""]
L += [_task_row("", resume_payload(d["key"], row)).replace(
"<summary>📋 </summary>",
f'<summary title="Copy resume prompt for {_attr(d["key"])}">📋</summary>'), ""]
L += [f"**Runs** ({len(d['runs'])})", ""]
if d["runs"]:
L += ["| Job | State | Partition | Date | Description |",
Expand All @@ -538,24 +560,26 @@ def _card_md(d: dict, row: dict, blob: str) -> list[str]:
L += ["", f"<details><summary>{_history_label(d)}</summary>", ""]
L += [f"- {e['date']} — *{e['kind']}* — {_md_text(e['text'])}"
for e in d["log"][:LOG_SHOWN]] or ["- _empty_"]
L += ["", f"[full log]({_ledger_link(d, blob)})", "", "</details>", "",
"<details><summary>Locations</summary>", "",
f"- Ledger: [{d['rel']}]({_ledger_link(d, blob)})",
f"- Local: `` {d['local_path']} ``",
f"- RAL: `` {d['ral_root']} ``", "", "</details>", "", "</details>", ""]
L += ["", f"[full log]({_ledger_link(d, blob)})", "",
f"{d['status']} · {d['partition']} · {issue}", "",
"</details>", "", "</details>", ""]
return L


def _full_text_html(text: str, clip: int) -> str:
def _full_text_html(text: str, clip: int, *, clauses: bool = False) -> str:
"""A description that fits is plain text; a longer one is a disclosure
whose summary is the clipped line and whose body is the whole text —
keyboard-reachable (`<summary>` is focusable) and never truncated away."""
def display(value: str) -> str:
# Split literal prose separators before escaping; never split entities.
return ";<br> ".join(_esc(part) for part in value.split("; ")) if clauses else _esc(value)

if not _clipped(text, clip):
return _esc(text)
return display(text)
short = _clip(text, clip)
return (f'<details class="full"><summary><span class="clip">{_esc(short)}</span>'
return (f'<details class="full"><summary><span class="clip">{display(short)}</span>'
f'<span class="less">show less</span></summary>'
f"<p>{_esc(text)}</p></details>")
f"<p>{display(text)}</p></details>")


def _runs_table_html(d: dict) -> list[str]:
Expand All @@ -571,26 +595,34 @@ def _runs_table_html(d: dict) -> list[str]:
f'<td class="state" data-label="State"><span class="pill {tone}">{_esc(r["state"])}</span></td>'
f'<td class="part" data-label="Partition">{_esc(r["partition"])}</td>'
f'<td class="date">{_esc(r["date"])}</td>'
f'<td class="what">{_full_text_html(r["what"], RUN_CLIP)}</td></tr>')
f'<td class="what">{_full_text_html(r["what"], RUN_CLIP, clauses=True)}</td></tr>')
H += ["</tbody>", "</table>"]
return H


def _card_html(d: dict, row: dict, blob: str) -> list[str]:
issue = (f'<a href="{_attr(d["issue_url"])}">{_esc(d["issue"])}</a>'
if d["issue_url"] else "no issue yet")
registered, now = _registration(d)
H = [f'<details class="project" id="project-{_attr(d["key"])}">',
f'<summary><h3>{_esc(d["key"])}</h3>'
f'<span class="purpose">{_esc(d["summary"])}</span>'
f'<span class="meta">{_esc(_overview_text(d))}</span></summary>',
'<div class="project-body">',
f'<p class="muted">{_esc(d["status"])} · {_esc(d["partition"])} · {issue}</p>',
'<dl class="where">',
f'<dt>Registered:</dt><dd>{_esc(registered)}</dd>',
f'<dt>Local:</dt><dd>{_esc(d["local_path"])}</dd>',
f'<dt>RAL:</dt><dd>{_esc(d["ral_root"])}</dd>',
'</dl><div class="position"><div class="position-text">',
"<h4>Current position</h4>",
"<p>" + ("<br>".join(_esc(x) for x in d["now"].split("\n"))
if d["now"] else '<span class="muted">(nothing yet)</span>')
+ "</p>"]
"<p>" + ("<br>".join(_esc(x) for x in now.split("\n"))
if now else '<span class="muted">(nothing yet)</span>')
+ "</p></div>"]
if d["status"] == "active":
H.append(_html_task(f"resume {_esc(d['key'])}", resume_payload(d["key"], row)))
label = _attr(f"Copy resume prompt for {d['key']}")
H.append(f'<button class="copy resume" aria-label="{label}" title="{label}" '
f'data-cmd="{_attr(resume_payload(d["key"], row))}">📋</button>')
H.append("</div>")
H.append(f"<h4>Runs ({len(d['runs'])})</h4>")
H += _runs_table_html(d)
H.append(f'<details class="sub"><summary>{_esc(_history_label(d))}</summary>')
Expand All @@ -602,12 +634,8 @@ def _card_html(d: dict, row: dict, blob: str) -> list[str]:
else:
H.append('<p class="muted">empty</p>')
H += [f'<p class="muted"><a href="{_attr(_ledger_link(d, blob))}">full log</a></p>',
"</details>",
'<details class="sub"><summary>Locations</summary><dl class="where">',
f'<dt>Ledger</dt><dd><a href="{_attr(_ledger_link(d, blob))}">{_esc(d["rel"])}</a></dd>',
f'<dt>Local</dt><dd><span class="pathchip">{_esc(d["local_path"])}</span></dd>',
f'<dt>RAL</dt><dd><span class="pathchip">{_esc(d["ral_root"])}</span></dd>',
"</dl></details>", "</div>", "</details>"]
f'<p class="muted">{_esc(d["status"])} · {_esc(d["partition"])} · {issue}</p>',
"</details>", "</div>", "</details>"]
return H


Expand Down Expand Up @@ -708,8 +736,13 @@ def render_dashboard(c: dict) -> str:
"details.full>p{margin:.2rem 0 0}"
"details.sub{margin:.6rem 0}"
"ul.log{margin:.3rem 0;padding-left:1.2rem}"
"dl.where{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:.3rem .8rem;margin:.4rem 0}"
"dl.where{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:.3rem .8rem;margin:1rem 0;color:var(--accent)}"
"dl.where dd{margin:0;min-width:0}"
".position{display:flex;align-items:flex-start;gap:.8rem}"
".position-text{flex:1;min-width:0}"
".position-text h4{margin-top:.3rem}"
".position .resume{flex:none;min-width:44px;min-height:44px;margin-top:.2rem}"
"table.runs td.what{line-height:1.6}"
"@media(max-width:34rem){"
"table.runs,table.runs tbody{display:block}"
"table.runs thead{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}"
Expand Down
76 changes: 61 additions & 15 deletions tests/test_cortex_conductor.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,8 @@ def test_the_summary_table_has_four_narrow_columns_and_active_rows_only(skeleton
def test_one_resume_chip_per_active_project_and_no_other_chips(skeleton):
page = _cortex.render_dashboard(_cortex.census(skeleton))
chips = re.findall(r"<summary>📋 ([^<]+)</summary>", page)
assert chips == ["check in since last time", "resume example", "resume single"]
assert chips == ["check in since last time"]
assert page.count('<summary title="Copy resume prompt for ') == 2
# the paste, verbatim
assert ("Use the cortex skill. — resume example: read PyAutoCortex projects/example.md "
"(Now, Runs, Log) and then /tmp/example/wiki/project/state.md and "
Expand All @@ -211,9 +212,7 @@ def test_one_resume_chip_per_active_project_and_no_other_chips(skeleton):
def _md_card(page: str, key: str) -> str:
"""One project's disclosure in dashboard.md, opening tag to its close."""
start = page.index(f'<details id="project-{key}">')
# the card's own close is the `</details>` that ends a blank-line block
# after the Locations fold
loc = page.index("<details><summary>Locations</summary>", start)
loc = page.index("[full log]", start)
close = "</details>\n\n</details>"
return page[start:page.index(close, loc) + len(close)]

Expand All @@ -240,17 +239,17 @@ def test_an_expanded_card_shows_position_runs_table_history_and_locations(skelet
assert "| `3002_[0-3]` | running | ral | 2026-09-01 | wave 2, four seeds on the corrected settings |" in card
assert ("| `3003` | open | gpu | 2026-09-02 | joint fit on the same four seeds "
"chained after 3002 with afterok |") in card
# the order is resume chip → runs → history → locations
assert (card.index("📋 resume example") < card.index("**Runs**")
< card.index("<summary>Recent log — 5 of 7 entries</summary>")
< card.index("<summary>Locations</summary>"))
assert (card.index("**Registered:**") < card.index("**Local:**")
< card.index("**RAL:**") < card.index("**Current position**")
< card.index('title="Copy resume prompt for example"') < card.index("**Runs**")
< card.index("<summary>Recent log — 5 of 7 entries</summary>"))
assert "<summary>Locations</summary>" not in card
last = card.split("Recent log — 5 of 7 entries")[1].split("[full log]")[0]
assert len([ln for ln in last.splitlines() if ln.startswith("- ")]) == 5
assert "- 2026-09-01 — *lesson* — the adapt image" in last
assert "3001_[0-3] submitted" not in last # the sixth entry
where = card.split("<summary>Locations</summary>")[1]
assert "- Ledger: [projects/example.md](projects/example.md)" in where
assert "- Local: `` /tmp/example ``" in where and "- RAL: `` /mnt/ral/example ``" in where
assert "[full log](projects/example.md)" in card
assert "**Local:** `` /tmp/example ``" in card and "**RAL:** `` /mnt/ral/example ``" in card
single = _md_card(page, "single")
assert "no issue yet" in single and "**Runs** (0)\n\n_nothing on the cluster_" in single
assert "<summary>Recent log — 1 of 1 entry</summary>" in single
Expand Down Expand Up @@ -343,7 +342,7 @@ def test_the_html_twin_wears_the_theme_with_real_copy_buttons(skeleton):
nav = re.search(r'<nav class="board-nav".*?</nav>', html, re.S).group()
for target in re.findall(r'href="#([^"]+)"', nav):
assert f'id="{target}"' in html
assert html.count('<button class="copy"') == 2
assert html.count('<button class="copy resume"') == 2
assert html.count('<button type="button" class="orchestration-copy"') == 1
assert 'data-cmd="Use the cortex skill. — resume example:' in html
assert 'data-orchestration-prompt readonly' in html
Expand All @@ -365,7 +364,7 @@ def test_the_html_twin_wears_the_theme_with_real_copy_buttons(skeleton):
assert '<details class="project" id="project-example" open' not in html
assert "<details><summary>1 retired</summary>" in html
assert "<h4>No ledger</h4>" in html
assert 'class="pathchip">/tmp/example</span>' in html
assert '<dt>Local:</dt><dd>/tmp/example</dd>' in html


def test_the_html_escapes_the_ledgers_text(tmp_skeleton):
Expand Down Expand Up @@ -396,8 +395,9 @@ def test_the_html_card_is_a_keyboard_disclosure_with_an_aligned_runs_table(skele
# the resume chip stays on the card, before the runs; history and paths fold
assert card.index('data-cmd="Use the cortex skill. — resume example:') < card.index("<h4>Runs (2)</h4>")
assert '<details class="sub"><summary>Recent log — 5 of 7 entries</summary>' in card
assert '<details class="sub"><summary>Locations</summary><dl class="where">' in card
assert '<dd><span class="pathchip">/mnt/ral/example</span></dd>' in card
assert '<summary>Locations</summary>' not in card
assert '<dt>RAL:</dt><dd>/mnt/ral/example</dd>' in card
assert card.index('<dl class="where">') < card.index('<h4>Current position</h4>')
# keyboard focus is visible; the table stacks under the shared phone breakpoint
assert "details.project>summary:focus-visible" in html
assert "@media(max-width:34rem){table.runs,table.runs tbody{display:block}" in html
Expand Down Expand Up @@ -941,3 +941,49 @@ def test_the_dispatcher_lists_the_verb():
for verb in ("census", "dashboard", "pull", "checkin", "issue"):
assert verb in r.stdout
assert "collect" not in r.stdout and "gates" not in r.stdout


@pytest.mark.parametrize("prefix,date", [
("Registered 2026-10-15 (PyAutoCortex#67): ", "2026-10-15"),
("Registered 2026-10-15: ", "2026-10-15"),
("", "2026-09-01"),
])
def test_registration_metadata_preserves_ledger_and_copy_payload(skeleton, prefix, date):
from copy import deepcopy
from html import unescape
c = _cortex.census(skeleton)
d = next(d for d in c["ledgers"] if d["key"] == "single")
d["now"] = prefix + "SLACS sample <ready> & no runs yet."
original = deepcopy(c)
html = _cortex.render_dashboard_html(c)
card = html.split('id="project-single"')[1]
assert f'<dt>Registered:</dt><dd>{date}</dd>' in card
assert "PyAutoCortex#67" not in card
assert "SLACS sample &lt;ready&gt; &amp; no runs yet." in card
button = re.search(r'<button class="copy resume"([^>]+)>📋</button>', card)
assert button and 'aria-label="Copy resume prompt for single"' in button[1]
payload = unescape(re.search(r'data-cmd="([^"]+)"', button[1])[1])
assert payload == _cortex.resume_payload("single", c["projects"]["single"])
assert c == original
md = _md_card(_cortex.render_dashboard(c), "single")
assert f"**Registered:** {date}" in md and "PyAutoCortex#67" not in md


def test_registration_missing_or_malformed_never_uses_updated_date(skeleton):
c = _cortex.census(skeleton)
d = next(d for d in c["ledgers"] if d["key"] == "single")
d["log"] = []
d["now"] = "Registered 2026-99-99 (PyAutoCortex#67): keep this text"
assert _cortex._registration(d) == ("not recorded", d["now"])
assert '<dt>Registered:</dt><dd>not recorded</dd>' in _cortex.render_dashboard_html(c)


def test_run_clauses_wrap_without_changing_scientific_text_or_escaping():
from html import unescape
text = "job B <test>; 1250-pixel mesh (8c / 96gb / 48 h); reloads A & keeps settings"
for clip in (20, 200):
result = _cortex._full_text_html(text, clip, clauses=True)
full = re.search(r"<p>(.*?)</p>", result)[1] if clip == 20 else result
assert ";<br> " in full and "<test>" not in full
assert unescape(full.replace("<br>", "")) == text
assert "<br>" not in _cortex._full_text_html(text, 200)
Loading