diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 073dcbbc..852fbae2 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -107,15 +107,15 @@ jobs: run: bash PyAutoBrain/bin/install.sh --check-project-discovery # A skill's SKILL.md + body is MANDATORY context every time the skill # loads, so line count is a per-invocation token cost, not a style - # preference. Report-only while `start_dev` and `prm` are over the - # 200-line budget: batch, cortex and Mind's create_issue were trimmed - # under it on 2026-11-07 and PyAutoBrain#597 brings the last two under. - # Once both are on main, drop `continue-on-error` to make this blocking - # (PyAutoMind draft/maintenance/organs/reduce_session_token_load.md). - - name: Skill line-count budget (report-only — known offenders) - continue-on-error: true + # preference. Blocking since 2026-11-07, when the last offenders (batch, + # cortex, Mind's create_issue, start_dev, prm) came under the 200-line + # budget (#597, #600). A skill that outgrows it moves detail verbatim + # into its reference.md; `pyauto-brain hygiene tokens` reports the same. + # Scoped to Brain's own skills: Mind's are checked out here too, and a + # Mind skill must not redden a Brain PR (the same rule as `--only` below). + - name: Skill line-count budget (200 lines of SKILL.md + body) working-directory: PyAutoBrain - run: bash bin/check_skill_line_counts.sh + run: bash bin/check_skill_line_counts.sh 200 PyAutoBrain # The token-load numbers the same Mind prompt targets (AGENTS.md tokens, # start_dev / prm procedure lines, completion-record median), printed on # every PR so the budget is measured rather than remembered. `report` diff --git a/agents/conductors/hygiene/AGENTS.md b/agents/conductors/hygiene/AGENTS.md index ef9709a0..c2736a1f 100644 --- a/agents/conductors/hygiene/AGENTS.md +++ b/agents/conductors/hygiene/AGENTS.md @@ -64,7 +64,7 @@ than its category — because category alone gets it wrong. The config layer is | ships api docs | has a `docs/api/` tree | `docs` | The helper-backed modes (`docstrings`, `escapes`, `refs`, `optdeps`, `extras`, -`config`) +`config`, `tokens`) are **not** on this list: they discover their own targets by walking the scan root for workspace-shaped directories, so they can find material the map never names — and they keep reporting even when the repo-array modes are `unscanned`. @@ -85,9 +85,10 @@ names — and they keep reporting even when the repo-array modes are `unscanned` | `optdeps` | smoke-listed workspace scripts that construct an optional-dependency-gated API (`TransformerNUFFT` → `nufftax`) without the house `find_spec` skip guard, so they hard-fail the CI matrices that omit the extras (**finding**). AST-confirmed — prose mentions don't count; scripts outside `smoke_tests.txt` are never flagged | `/refactor` (add the skip guard) | | `extras` | the complement of `optdeps`: an optional dependency a library **declares** (in the `[optional]` extra `mode=release` installs) that the `workspace-validation.yml` **`mode=smoke`** leg never installs (**finding**). The extras chain only reaches each library's own `[jax]`, never a sibling's `[optional]`, so those need hand-adding and silently drift — the symptom is a script red in smoke and **green in release** | `/bug` (add the install; fix the install set, **never** the script) | | `config` | library `config/*.yaml` keys missing from the matching workspace config — recursive diff (**surface**) | `/refactor` (mirror keys) | +| `tokens` | the organism's token-load budgets: PyAutoMind `scripts/token_load.py` violations (four-organ AGENTS.md tokens, start_dev / prm procedure lines) plus skills whose SKILL.md + body exceed 200 lines (`bin/check_skill_line_counts.sh`); a file the scan root lacks is listed, not counted (**finding**; advisory when no Mind checkout is present) | `/refactor` (move detail verbatim into the skill's `reference.md`; no rule removed) | | `artifacts` | tracked files that look like leaked run outputs / stray data (under `output/`, or data-ext outside fixtures) (**debris**) | `/repo_cleanup` (gitignore + `git rm --cached`) | | `packaging` | ignored, fully-untracked top-level `*.egg-info/` and `build/` directories in the managed code repos (**debris**) | preview then run `PyAutoBrain/bin/clean_slate.sh --packaging`; repo-set, exact-name, root-depth and tracked-file guards apply | -| *(default)* | all of the above (**perf timing deferred** — it spawns real imports) | a ranked `HygieneDecision` worklist — recommends the highest-count direct mode (`tidy`/`crlf`/`docstrings`/`escapes`/`refs`/`artifacts`/`packaging`), then `hygiene perf`, then the periodic surface audits | +| *(default)* | all of the above (**perf timing deferred** — it spawns real imports) | a ranked `HygieneDecision` worklist — recommends the highest-count direct mode (`tidy`/`crlf`/`docstrings`/`escapes`/`refs`/`tokens`/`artifacts`/`packaging`), then `hygiene perf`, then the periodic surface audits | ``` pyauto-brain hygiene # pre-scan across modes → ranked worklist @@ -106,6 +107,7 @@ pyauto-brain hygiene refs # folder-list drift in workspace prose → /re pyauto-brain hygiene optdeps # smoke-listed scripts missing an optional-dep skip guard → /refactor pyauto-brain hygiene extras # optional deps the smoke CI leg never installs → /bug pyauto-brain hygiene config # library→workspace config drift → /refactor +pyauto-brain hygiene tokens # token-load budgets (AGENTS.md, procedures, skill lines) → /refactor pyauto-brain hygiene artifacts # tracked leaked outputs/data → /repo_cleanup pyauto-brain hygiene packaging # ignored root packaging dirs → clean_slate.sh pyauto-brain hygiene --json diff --git a/agents/conductors/hygiene/_hygiene_tokens.py b/agents/conductors/hygiene/_hygiene_tokens.py new file mode 100644 index 00000000..044cb1a5 --- /dev/null +++ b/agents/conductors/hygiene/_hygiene_tokens.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""tokens: the organism's token-load budgets, read as a hygiene finding. + +Two measurements that already exist, composed into one `count|summary` row: + +- PyAutoMind `scripts/token_load.py report --json` — the four organs' + AGENTS.md tokens, the start_dev / prm procedure lines and the + completion-record median, with the budgets its `check` verb enforces; +- PyAutoBrain `bin/check_skill_line_counts.sh` — every skill's mandatory load + (SKILL.md + body) against the 200-line budget. + +The count is the number of budgets broken: token_load violations (a file the +scan root simply lacks is reported, not counted) plus skills over 200 lines. +Read-only and stdlib only; it never edits a skill. Route a breach to +/refactor (move detail verbatim into the skill's `reference.md`); the budget +history is PyAutoMind `draft/maintenance/organs/reduce_session_token_load.md`. + +Usage: _hygiene_tokens.py --root ROOT --mind MIND_CHECKOUT [--detail] +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +from pathlib import Path + +BRAIN = Path(__file__).resolve().parents[3] +SKILL_LINES = BRAIN / "bin" / "check_skill_line_counts.sh" + + +def token_load(root: Path, mind: Path) -> dict | None: + script = mind / "scripts" / "token_load.py" + if not script.is_file(): + return None + proc = subprocess.run( + [sys.executable, str(script), "report", "--json", "--root", str(root)], + capture_output=True, text=True, timeout=120, + ) + if proc.returncode != 0: + return None + try: + return json.loads(proc.stdout) + except json.JSONDecodeError: + return None + + +def skills_over(root: Path) -> list[str] | None: + env = {**os.environ, "PYAUTO_ROOT": str(root)} + try: + proc = subprocess.run( + ["bash", str(SKILL_LINES)], capture_output=True, text=True, + env=env, timeout=60, + ) + except (OSError, subprocess.TimeoutExpired): + return None + if "OK:" not in proc.stdout and "FAIL:" not in proc.stdout: + return None + return [ + " ".join(line.split()[1:3]) # " " + for line in proc.stdout.splitlines() if line.startswith("OVER") + ] + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--mind", type=Path, required=True) + parser.add_argument("--detail", action="store_true") + args = parser.parse_args(argv) + + load = token_load(args.root, args.mind) + if load is None: + print("-1|token_load.py unavailable (no PyAutoMind checkout under the " + "scan root) — nothing measured") + return 0 + breaches = [v for v in load.get("violations", []) + if not v.startswith("missing:")] + over = skills_over(args.root) + totals = load.get("totals", {}) + count = len(breaches) + len(over or []) + + parts = [ + f"start_dev {totals.get('start_dev_lines', '?')} / " + f"prm {totals.get('prm_lines', '?')} procedure lines", + f"organ AGENTS ~{totals.get('organ_agents_tokens_approx', '?')} tokens", + ] + records = totals.get("completion_records") + if records: + parts.append(f"record median {records['median_lines']} lines") + if over is None: + parts.append("skill line budget unmeasured") + else: + parts.append(f"{len(over)} skills over 200 lines") + print(f"{count}|{count} token-load budgets broken: " + "; ".join(parts) + + " (route breaches to /refactor)") + + if args.detail: + for breach in breaches: + print(f" budget {breach}") + for skill in over or []: + print(f" skill {skill} (SKILL.md + body > 200 lines)") + missing = [v for v in load.get("violations", []) if v.startswith("missing:")] + for item in missing: + print(f" absent {item[len('missing: '):]} (not counted)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/agents/conductors/hygiene/hygiene.sh b/agents/conductors/hygiene/hygiene.sh index 73e2e7f3..1a02dc8d 100755 --- a/agents/conductors/hygiene/hygiene.sh +++ b/agents/conductors/hygiene/hygiene.sh @@ -43,6 +43,7 @@ # hygiene.sh optdeps # smoke-listed scripts w/ a gated API but no skip guard -> /refactor # hygiene.sh extras # optional deps declared by a library but missing from the smoke CI install -> /bug # hygiene.sh config # library config keys missing downstream + orphan config files -> /refactor +# hygiene.sh tokens # token-load budgets (AGENTS.md, procedure lines, skills > 200 lines) -> /refactor # hygiene.sh artifacts # tracked leaked outputs/data -> /repo_cleanup # hygiene.sh packaging # ignored top-level *.egg-info/build dirs -> clean_slate.sh # hygiene.sh --json # machine-readable HygieneDecision @@ -164,7 +165,7 @@ PERF_PY="${HYGIENE_PYTHON:-python3}" PERF_THRESHOLD="${HYGIENE_PERF_THRESHOLD:-3.0}" read -r -a PERF_LIBS <<< "${HYGIENE_PERF_LIBS:-autonerves autofit autoarray autogalaxy autolens}" -MODE_ORDER=(perf tidy crlf docstrings escapes refs optdeps extras artifacts packaging noise deps docs config) +MODE_ORDER=(perf tidy crlf docstrings escapes refs optdeps extras artifacts packaging noise deps docs config tokens) declare -A MODE_DELEGATE=( [perf]="/refactor" [tidy]="condemn → condemned.md (async; 'hygiene sweep' voids)" @@ -180,6 +181,7 @@ declare -A MODE_DELEGATE=( [deps]="/dep_audit" [docs]="/audit_docs" [config]="/refactor" + [tokens]="/refactor" ) # A mode's pre-scan is one of a few kinds, which is what makes its count # comparable (or not): 'debris' finds directly-removable items, 'finding' @@ -190,7 +192,7 @@ declare -A MODE_DELEGATE=( # 'finding', and 'timing' counts drive the ranking. declare -A MODE_KIND=( [perf]="timing" [tidy]="debris" [crlf]="debris" [artifacts]="debris" [packaging]="debris" - [docstrings]="finding" [escapes]="finding" [refs]="finding" [optdeps]="finding" [extras]="finding" + [docstrings]="finding" [escapes]="finding" [refs]="finding" [optdeps]="finding" [extras]="finding" [tokens]="finding" [deps]="surface" [docs]="surface" [config]="surface" [noise]="advisory" ) @@ -392,6 +394,15 @@ prescan_config() { [[ -n "$out" ]] && echo "$out" || echo "0|config diff unavailable (PyYAML missing?)" } +# tokens: the token-load budgets — PyAutoMind scripts/token_load.py's +# violations plus skills over the 200-line mandatory-load budget. -1 (advisory) +# when no Mind checkout is under the scan root, so nothing was measured. +prescan_tokens() { + local out + out=$(python3 "$HERE/_hygiene_tokens.py" --root "$ROOT" --mind "$(repo_dir PyAutoMind)" 2>/dev/null | head -1) + [[ -n "$out" ]] && echo "$out" || echo "-1|token-load helper failed — run: pyauto-brain hygiene tokens" +} + # noise: no cheap local signal (needs running pytest + workspace scripts). prescan_noise() { echo "-1|no cheap local signal — runs pytest + workspace scripts (PYAUTO_TEST_MODE=2)" @@ -458,6 +469,7 @@ prescan() { optdeps) prescan_optdeps ;; extras) prescan_extras ;; artifacts) prescan_artifacts ;; packaging) prescan_packaging ;; config) prescan_config ;; + tokens) prescan_tokens ;; esac } @@ -470,7 +482,7 @@ for arg in "$@"; do # the helper verbatim, so they must not fall into the unknown-argument branch. if [[ "$mode" == "ci" && "$arg" != "--json" ]]; then ci_args+=("$arg"); continue; fi case "$arg" in - perf|tidy|sweep|noise|deps|docs|crlf|docstrings|escapes|refs|optdeps|extras|config|artifacts|packaging|ci) mode="$arg" ;; + perf|tidy|sweep|noise|deps|docs|crlf|docstrings|escapes|refs|optdeps|extras|config|tokens|artifacts|packaging|ci) mode="$arg" ;; default) mode="default" ;; --json) json=1 ;; --profile) mode="perf"; expect_script=1 ;; @@ -827,12 +839,19 @@ elif [[ "$mode" == "config" ]]; then echo " SURFACE signal — judge each item before acting: a workspace may omit a library" echo " key deliberately, and an orphan file may be read by something the library set" echo " does not encode (add its owner to ORPHAN_OWNERS rather than deleting it)." +elif [[ "$mode" == "tokens" ]]; then + echo "Token-load budgets (read-only measurement):" + python3 "$HERE/_hygiene_tokens.py" --root "$ROOT" --mind "$(repo_dir PyAutoMind)" --detail + echo + echo "→ route a breach to /refactor: move detail verbatim into the skill's reference.md;" + echo " no rule, gate or refusal is removed. History and targets: PyAutoMind" + echo " draft/maintenance/organs/reduce_session_token_load.md." elif [[ "$mode" == "default" ]]; then # 'debris' and 'finding' pre-scans yield directly-actionable counts (perf's # timing is deferred here — too slow for the fast scan). Rank across them and # recommend the mode with the largest confirmed workload. best=""; best_n=0 - for m in tidy crlf docstrings escapes refs optdeps extras artifacts packaging; do + for m in tidy crlf docstrings escapes refs optdeps extras tokens artifacts packaging; do local_n="$(prescan "$m")"; local_n="${local_n%%|*}" if [[ "$local_n" -gt "$best_n" ]]; then best_n="$local_n"; best="$m"; fi done diff --git a/bin/check_skill_line_counts.sh b/bin/check_skill_line_counts.sh index 50a5d4d2..d23742fe 100755 --- a/bin/check_skill_line_counts.sh +++ b/bin/check_skill_line_counts.sh @@ -10,11 +10,16 @@ # exit 1 = at least one primary file is over the limit. # # Usage: -# bash PyAutoBrain/bin/check_skill_line_counts.sh [limit] +# bash PyAutoBrain/bin/check_skill_line_counts.sh [limit] [repo ...] +# +# Naming repos limits the scan to their skills (Brain's CI passes PyAutoBrain, +# so a Mind skill can never redden a Brain PR it did not cause). set -euo pipefail LIMIT="${1:-200}" +shift || true +ONLY=("$@") SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" . "$SCRIPT_DIR/_pyauto_root.sh" . "$SCRIPT_DIR/_repo_paths.sh" @@ -36,6 +41,13 @@ checked=0 for root in "${ROOTS[@]}"; do [ -d "$root" ] || continue + if [ "${#ONLY[@]}" -gt 0 ]; then + keep=0 + for repo in "${ONLY[@]}"; do + [ "$root" = "$(pyauto_repo_path "$repo" "$PYAUTO_ROOT")/skills" ] && keep=1 + done + [ "$keep" -eq 1 ] || continue + fi for dir in "$root"/*/; do [ -d "$dir" ] || continue name="$(basename "$dir")" diff --git a/skills/hygiene/hygiene.md b/skills/hygiene/hygiene.md index 70a7ec61..e82e5f2d 100644 --- a/skills/hygiene/hygiene.md +++ b/skills/hygiene/hygiene.md @@ -10,14 +10,15 @@ Shared routing context: `PyAutoBrain/skills/COMMANDS.md`. ## Do 1. Run `bin/pyauto-brain hygiene [perf | ci | tidy | noise | deps | docs | crlf | - docstrings | escapes | refs | optdeps | extras | config | artifacts | packaging]` (no arg = pre-scan across modes → a ranked worklist; + docstrings | escapes | refs | optdeps | extras | config | tokens | artifacts | packaging]` (no arg = pre-scan across modes → a ranked worklist; perf's import timing and `ci` are deferred there — `ci` reads the Heart board's published CI timings and ranks the slowest smoke scripts, unit tests and gates, one 📋 each for `/ci_speedup`). This is a **dry run** — each mode does a cheap read-only pre-scan and emits a `HygieneDecision` naming the skill to run for the full audit. Nothing is executed or mutated. (`crlf` = executable scripts w/ CRLF that break on HPC — library `.py` CRLF reported as - cosmetic; `config` = library→workspace config-key drift; `artifacts` = + cosmetic; `config` = library→workspace config-key drift; `tokens` = + broken token-load budgets (AGENTS.md, start_dev/prm lines, skills > 200 lines); `artifacts` = tracked leaked outputs/data; `packaging` = ignored, fully-untracked top-level `*.egg-info/` and `build/` directories in managed library repositories; `docstrings` = exact adjacent module-level triple-quoted documentation diff --git a/tests/test_hygiene_conductor.py b/tests/test_hygiene_conductor.py index e9eda55f..64f35cbf 100644 --- a/tests/test_hygiene_conductor.py +++ b/tests/test_hygiene_conductor.py @@ -15,7 +15,7 @@ BRAIN = BRAIN_HOME / "bin" / "pyauto-brain" MODES = { "perf", "tidy", "noise", "deps", "docs", "crlf", "config", "artifacts", - "packaging", "docstrings", "escapes", "refs", "optdeps", "extras", + "packaging", "docstrings", "escapes", "refs", "optdeps", "extras", "tokens", } _PROFILE_TARGET = """ @@ -80,6 +80,7 @@ def test_default_json_is_a_hygiene_decision_with_all_modes(tmp_path): assert kinds["refs"] == "finding" assert kinds["optdeps"] == "finding" assert kinds["extras"] == "finding" + assert kinds["tokens"] == "finding" assert kinds["deps"] == "surface" and kinds["docs"] == "surface" assert kinds["config"] == "surface" assert kinds["noise"] == "advisory" @@ -1398,3 +1399,39 @@ def test_refs_treats_run_output_and_generated_folders_as_unresolvable(tmp_path): found = {f["reference"] for f in _refs_row(tmp_path)["findings"]} assert {"files/search_internal", "cache_root/crds/", "notebooks", "cache"}.isdisjoint(found) + + +def test_tokens_is_advisory_without_a_mind_checkout(tmp_path): + """No token_load.py under the scan root: nothing was measured, so the row + must not read `clean`.""" + r = _run(["tokens", "--json"], tmp_path) + assert r.returncode == 0, r.stderr + row = json.loads(r.stdout)["row"] + assert row["mode"] == "tokens" and row["kind"] == "finding" + assert row["status"] == "advisory" and row["count"] is None + assert row["delegate"] == "/refactor" + + +def test_tokens_counts_budget_breaches_not_absent_files(tmp_path): + """A stub token_load.py reports one real breach and one absent file: + the count is the breach alone, and --detail lists both.""" + scripts = tmp_path / "PyAutoMind" / "scripts" + scripts.mkdir(parents=True) + (scripts / "token_load.py").write_text( + "import json\n" + "print(json.dumps({'totals': {'start_dev_lines': 360, 'prm_lines': 460}," + " 'violations': ['missing: workspace AGENTS: /x/AGENTS.md'," + " 'prm_lines: 460 > 450 lines']}))\n" + ) + helper = BRAIN_HOME / "agents/conductors/hygiene/_hygiene_tokens.py" + out = subprocess.run( + [sys.executable, str(helper), "--root", str(tmp_path), + "--mind", str(tmp_path / "PyAutoMind"), "--detail"], + capture_output=True, text=True, + ) + assert out.returncode == 0, out.stderr + first, *detail = out.stdout.splitlines() + assert first.startswith("1|1 token-load budgets broken") + assert "prm 460" in first + assert any("budget prm_lines: 460 > 450" in line for line in detail) + assert any(line.strip().startswith("absent") for line in detail)