From d01f8f484cb99a217b55be798a524044acfda924 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 19 Sep 2026 14:43:23 +0100 Subject: [PATCH 1/3] Slim Mind instructions and measure maintained context budgets --- AGENTS.md | 205 ++++++---------------------- REFERENCE.md | 157 +++++++++++++++++++++ scripts/repos_sync.py | 9 +- scripts/token_load.py | 130 ++++++++++++++++++ skills/create_issue/SKILL.md | 39 ++++-- tests/test_repos_sync_provenance.py | 17 +++ tests/test_token_load.py | 80 +++++++++++ 7 files changed, 458 insertions(+), 179 deletions(-) create mode 100644 scripts/token_load.py create mode 100644 tests/test_repos_sync_provenance.py create mode 100644 tests/test_token_load.py diff --git a/AGENTS.md b/AGENTS.md index 5ea57c717..a999a05e0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,129 +1,39 @@ # AGENTS.md -This file is for AI coding agents (Claude Code, Codex, Cursor, etc.) discovering -this repository. - -## What this repo is - -**PyAutoMind is the Mind of the PyAuto organism and the starting point of the -PyAuto workflow.** It holds the organism's ideas, intent, goals, priorities and -workflow state. Every task that ends up as a PR in PyAutoNerves, PyAutoFit, -PyAutoArray, PyAutoGalaxy, PyAutoLens, or any of the `*_workspace*` repos begins -as a markdown file here. - -PyAutoMind is the organism's Mind (intent and direction). The organs and their -boundaries are defined once in `PyAutoBrain/ORGANISM.md`; see -[README.md](README.md) for this repo's full picture. - -For the full workflow narrative, conventions, and registry schemas, read -[README.md](README.md). The summary below is just enough to operate. - -## Layout (operational) - -- **Prompt lifecycle (issue #71)** — a prompt file advances through three - top-level state folders, mirroring the task ledger: - - `draft///.md` — intaken, **not started**. The - first folder under `draft/` is the *kind of work*; the second is the - *target repo or domain*. Work-types: `feature/`, `bug/`, `refactor/`, - `docs/`, `test/`, `release/`, `maintenance/`, `research/` - (plus `triage/` for prompts whose classification is still unclear, and - `human_review/` for work that already shipped and a human wants to sign - off — declaration-only, see below). - PyAutoBrain routes by the work-type folder — see [README.md](README.md) - "Prompt taxonomy" and `ROUTING.md`. - - `active/.md` — **issued** (an open GitHub issue / in flight). The - ship skills advance the file to `complete/` on merge. - - `complete///.md` — **shipped**; the rich completion record - (see `complete/AGENTS.md`). Months are zero-padded so lexical order is - numerical order. `scripts/lifecycle.py` owns the moves and drift-checks - them. - - Retired non-record material lives in **`complete/archive/`** (skipped by - `lifecycle.py check`/`index`): `archive/epics/` (former `z_features/` - multi-task trackers) and `archive/shelved/` (former `z_vault/` deferred - prompts + dev notes). The old `z_features/`, `z_vault/` and `autoprompt/` - top-level folders were retired here on 2026-07-13. -- **Registry** — root-level markdown files, each with one job: `active.md` - (in-flight tasks), `planned.md` (scoped, not started), `parked.md` (started - but not in flight), `condemned.md` (self-material staged for the Gut's - transit-and-void lifecycle — see PyAutoGut), `epics.md` (long-running - multi-phase programmes and the ledger file that holds each one's state), - `ideas.md` (raw inbox swept by - `$intake`, `/intake` in Claude). Mutate these only via the skills in `skills/` so commit - messages stay consistent. - `dashboard.md` is the **generated** read-only view over all of it (the page - the README links): regenerate with `pyauto-brain intake --apply dashboard` - after any registry or `draft/` change you want reflected immediately — never - hand-edit it. `dashboard_refresh.yml` self-heals it on pushes to `main`, so a - missed regeneration is drift that fixes itself, not a broken page — but it - heals only the **render**. A prompt that shipped and was never retired to - `complete/` renders faithfully, as pickable backlog, and no workflow can tell - the difference; retiring it is a human/skill judgement. Per task that is - `/prm`'s close-out (it sweeps the shipped prompt's folder and regenerates the - page in the same commit); across the whole backlog it is - `pyauto-brain intake reconcile` plus the refresh payload on the dashboard - itself. - `parked.md` holds tasks that were started or scoped but are not currently - in flight (e.g. work parked in a stash, orphan worktrees); move back to - `active.md` (or `planned.md` if re-scoping) when resuming. -- **Body map** — `repos.yaml` is the single source of repo *identity* (GitHub - home, category, one-line role) and explicit generated-adapter rollout for - every repo in the workspace. The routing - table in the workspace-root `AGENTS.md` and the owner map in - `PyAutoBrain/skills/WORKFLOW.md` are generated from it, and the repo lists in - Heart/Build/admin scripts are drift-checked against it: - `python3 scripts/repos_sync.py --write`. -- **Policy** — `policy/` holds the universal rules single-sourced here and - generated verbatim into every repo's AGENTS.md by `repos_sync.py --write`: - `never_rewrite_history.md`, `remote_sessions.md`, `end_at_deliverable.md` - (plus the hooks that enforce them, `session_start_hook.sh` and - `end_at_deliverable_hook.sh`). Edit the canonical file, never a generated copy. - `repos_sync.py --write --only "generated Codex hooks"` renders opted-in - `.codex/hooks.json` adapters without touching the broader generated surface. - Codex users must review and trust the exact current hook hash with `/hooks`; - changed or untrusted project hooks are skipped. These adapters register the - reviewed PreToolUse safety guards only. The remote Python SessionStart - bootstrap remains Claude-specific and is not silently copied into Codex. - `community_surface.md` is the one policy page that is *not* generated - anywhere: it decides where users go (one Discussions hub) and where the - development flow stays (per-repo issues); the Ears and the README Support - sections read it as doctrine. -- **Skills** — `skills//` are agent skills and command bodies tightly - coupled to the registry. Claude and Codex discovery is installed by - PyAutoBrain; they source `scripts/prompt_sync.sh` for commit/push. -- **Ledger auto-merge** — a push to `claude/**` or `codex/**` whose whole diff is *ledger* - (`draft/`, `active/`, `complete/`, the root registry files, the dashboard - pages) is merged into `main` by `.github/workflows/mind_ledger_merge.yml` and - the branch deleted — no PR, no session step, no "please merge that" prompt. - Anything touching `scripts/`, `tests/`, `.github/`, `skills/`, `policy/`, - `docs/`, `repos.yaml` or the prose pages is left for a human, as is anything - unclassified (the gate is default deny). So: **push your Mind work and move - on** — do not leave a ledger branch hanging, and do not expect a code branch - to land by itself. `python3 scripts/ledger_merge.py classify --base - origin/main` tells you which side you are on before you push; the full - contract is in [REFERENCE.md](REFERENCE.md) "How the ledger lands". A - conflict on the registries or the generated pages is settled by the - ledger's own grammar (`ledger_merge.py resolve`: entries merge by slug, - renders take main and are regenerated); a branch that still cannot land - gets an issue labelled `ledger-merge`, never a silent red run. - Optional `active.md` session metadata records the actual harness and a known - resume command when available; existing `claude --resume` values remain valid. -- **Scripts** — `scripts/status.sh` (inventory), `scripts/prompt_sync.sh` - (commit/push helpers), `scripts/lifecycle.py` (state moves + drift checks; - `lifecycle.py dates [--write]` reports/backfills the date every registry - entry and issued prompt carries — see [REFERENCE.md](REFERENCE.md) "Task - dates"). +PyAutoMind holds task intent and workflow state. For registry schemas, prompt +conventions, and operational detail, read [REFERENCE.md](REFERENCE.md) only +when the task needs them. Read [README.md](README.md) for the public overview. + +## Where work lives + +- `draft///.md` holds unstarted prompts. Work types: + `feature`, `bug`, `refactor`, `docs`, `test`, `release`, `maintenance`, + `research`, and `triage` when genuinely unclear. `human_review` is reserved + for work a human explicitly asks to review after shipping. +- `active/.md` holds issued prompts; `complete///.md` + holds shipped records. `scripts/lifecycle.py` owns these moves. +- `repos.yaml` owns repository identity and generated adapter rollout. Change + it, then run `python3 scripts/repos_sync.py --write`; never edit generated + policy copies directly. Root routing and Brain owner maps come from it. +- Codex users must review and trust the current `.codex/hooks.json` hash with + `/hooks`; changed or untrusted project hooks are skipped. The remote Python + SessionStart bootstrap applies to Claude sessions only. +- Registry files (`active.md`, `planned.md`, `parked.md`, `condemned.md`, + `epics.md`, `ideas.md`, `bundles.md`) are changed through skills in `skills/`. + `dashboard.md` is generated: run `pyauto-brain intake --apply dashboard` + after registry or draft changes. Never hand-edit it. ## Hard rules 1. **Never rewrite history on any branch with a remote.** No `git init` over an - existing repo, no `git push --force` to `main`. (Motivated by the 2026-04-27 - drift incident.) + existing repo, no `git push --force` to `main`. 2. **Pull before edit.** `git fetch && git status` first, every time. If behind `origin/main`, `git pull --ff-only` before touching anything. -3. **One prompt = one task = one PR.** If a prompt outlines multiple - loosely-related changes, split into separate prompt files before issuing. +3. **One prompt = one task = one PR.** Split loosely related work before issuing. 4. **`tmp/` is scratch.** Never commit anything under it. +5. **A human review is explicit.** Only file `draft/human_review/` when a human + asks for it and declare `Type: human review`; neither intake nor close-out + may infer it. ## Remote sessions (Claude Code on web and mobile) @@ -145,52 +55,21 @@ nothing has set it up — this block is what does. `gh` operation onto its tool and is the one full page on the subject. -## When you are asked to add a new prompt - -Write the file under `draft///.md` — pick the work-type -from the list above (use `triage/` if genuinely unsure — never `human_review/`, -see below) and the target -repo/domain as the second folder, e.g. `draft/feature/autolens/potential_corrections.md` -or `draft/bug/autoarray/mask_edge_case.md`. Don't touch `active.md`, `active/` -or `complete/` directly — those are managed by `$start-dev`, `$create-issue` -and the ship skills (`/start_dev` and `/create_issue` in Claude). - -To skip the manual filing, run **`$intake`** (`/intake` in Claude), the -PyAutoBrain Intake/Conception Agent. It classifies a raw idea into the right -`draft///` folder, -writes the light header (incl. the optional `Difficulty:/Autonomy:/Priority:` -keys — see README "Prompt file format"), and files the prompt for you. It files a -prompt only; `$start-dev` (`/start_dev` in Claude) remains the separate next step. - -## When you are asked for a human review - -`draft/human_review//.md` holds work that has already **shipped** -and that a human wants to read and sign off before it counts as done. It is the -one work-type nothing may infer: file one only when a human asks for it, by -declaring `Type: human review` (`human-review`/`human_review` read the same) — -`/intake` will never choose it, and no completed task acquires it by default. -Review is opt-in, not a lifecycle stage: `/prm` and the ship skills close a task -out exactly as before and never file a review. - -It renders as its own **Human review** section on `dashboard.md`, directly under -*In flight*, and is deliberately not counted as backlog — a review is not work to -pick up, it is work waiting on a person. Its 📋 hands out a read-and-report -prompt, not a `/start_dev`. Sign one off by retiring the prompt the usual way -(`scripts/lifecycle.py record …`, then regenerate the dashboard); if it does not -pass, the follow-up is an ordinary `$intake`. - -## When you are asked to start work on an existing prompt - -Use `$start-dev draft///.md` (`/start_dev` in Claude). -Older `//.md` and bare `/.md` paths from -before the lifecycle migration still resolve. It -routes to `$start-library` or `$start-workspace` (`/start_library` or -`/start_workspace` in Claude) based on the repos referenced in the prompt body; -routing keys off `@RepoName` references in the content, not the folder. - -## When in doubt - -Read [README.md](README.md). It is current as of the last commit on this branch. +## Workflow entry points + +For a new prompt, write `draft///.md` or use `$intake`. +Do not move it into `active/` or edit completion records by hand. For existing +work, use `$start-dev draft///.md`; it routes from +`@RepoName` references in the body. Skill arguments are Mind-relative in both +grouped and flat layouts, e.g. `draft/bug/autoarray/mask_edge_case.md`. +Resolve the actual checkout once; set `PYAUTO_MIND` for an explicit location. + +Mind ledger-only pushes on `claude/**` or `codex/**` auto-merge under +`.github/workflows/mind_ledger_merge.yml`; code, skills, policy and prose +changes require a PR. Check with `python3 scripts/ledger_merge.py classify +--base origin/main` before pushing. Push ledger-only work and let the merge +workflow land it. Read [REFERENCE.md](REFERENCE.md) "How the +ledger lands" for conflict handling and classification details. ## Never rewrite history diff --git a/REFERENCE.md b/REFERENCE.md index 1bfcf2f7d..d8e2aa575 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -5,6 +5,16 @@ Moved verbatim from `README.md` on 2026-07-10 — agent docs that point at README sections ("Prompt taxonomy", "Prompt file format", the `active.md` / completion-record schemas) resolve here, one link from the README. +The read-only context check is `python3 scripts/token_load.py report --root +`; `check` applies the same measurement to the configured +budgets. It supports grouped main and flat bundle roots, and reports mandatory +AGENTS and core skill files separately from conditional references. In the +September 2026 context pass, Mind `AGENTS.md` fell from 12,507 bytes / 214 lines +to about 5,100 bytes / 94 lines. The broader +`draft/maintenance/organs/reduce_session_token_load.md` remains draft; this +measurement does not imply its Cortex, Memory, or completion-record goals are +done. + --- ## What a prompt looks like @@ -923,3 +933,150 @@ bash PyAutoBrain/bin/install.sh # symlinks skills + comma `PyAutoHeart/skills/`, `autolens_profiling/skills/`) and creates symlinks under `~/.claude/skills/` and `~/.claude/commands/`. Roots that aren't checked out are skipped. Re-run any time after pulling new skills from any of those repos. + +## Agent operational walkthrough + +This longer walkthrough is loaded when a Mind operation needs its detail; +`AGENTS.md` holds the immediately applicable rules. + +## Layout (operational) + +- **Prompt lifecycle (issue #71)** — a prompt file advances through three + top-level state folders, mirroring the task ledger: + - `draft///.md` — intaken, **not started**. The + first folder under `draft/` is the *kind of work*; the second is the + *target repo or domain*. Work-types: `feature/`, `bug/`, `refactor/`, + `docs/`, `test/`, `release/`, `maintenance/`, `research/` + (plus `triage/` for prompts whose classification is still unclear, and + `human_review/` for work that already shipped and a human wants to sign + off — declaration-only, see below). + PyAutoBrain routes by the work-type folder — see [Prompt taxonomy](#prompt-taxonomy) and `ROUTING.md`. + - `active/.md` — **issued** (an open GitHub issue / in flight). The + ship skills advance the file to `complete/` on merge. + - `complete///.md` — **shipped**; the rich completion record + (see `complete/AGENTS.md`). Months are zero-padded so lexical order is + numerical order. `scripts/lifecycle.py` owns the moves and drift-checks + them. + + Retired non-record material lives in **`complete/archive/`** (skipped by + `lifecycle.py check`/`index`): `archive/epics/` (former `z_features/` + multi-task trackers) and `archive/shelved/` (former `z_vault/` deferred + prompts + dev notes). The old `z_features/`, `z_vault/` and `autoprompt/` + top-level folders were retired here on 2026-07-13. +- **Registry** — root-level markdown files, each with one job: `active.md` + (in-flight tasks), `planned.md` (scoped, not started), `parked.md` (started + but not in flight), `condemned.md` (self-material staged for the Gut's + transit-and-void lifecycle — see PyAutoGut), `epics.md` (long-running + multi-phase programmes and the ledger file that holds each one's state), + `ideas.md` (raw inbox swept by + `$intake`, `/intake` in Claude). Mutate these only via the skills in `skills/` so commit + messages stay consistent. + `dashboard.md` is the **generated** read-only view over all of it (the page + the README links): regenerate with `pyauto-brain intake --apply dashboard` + after any registry or `draft/` change you want reflected immediately — never + hand-edit it. `dashboard_refresh.yml` self-heals it on pushes to `main`, so a + missed regeneration is drift that fixes itself, not a broken page — but it + heals only the **render**. A prompt that shipped and was never retired to + `complete/` renders faithfully, as pickable backlog, and no workflow can tell + the difference; retiring it is a human/skill judgement. Per task that is + `/prm`'s close-out (it sweeps the shipped prompt's folder and regenerates the + page in the same commit); across the whole backlog it is + `pyauto-brain intake reconcile` plus the refresh payload on the dashboard + itself. + `parked.md` holds tasks that were started or scoped but are not currently + in flight (e.g. work parked in a stash, orphan worktrees); move back to + `active.md` (or `planned.md` if re-scoping) when resuming. +- **Body map** — `repos.yaml` is the single source of repo *identity* (GitHub + home, category, one-line role) and explicit generated-adapter rollout for + every repo in the workspace. The routing + table in the workspace-root `AGENTS.md` and the owner map in + `PyAutoBrain/skills/WORKFLOW.md` are generated from it, and the repo lists in + Heart/Build/admin scripts are drift-checked against it: + `python3 scripts/repos_sync.py --write`. +- **Policy** — `policy/` holds the universal rules single-sourced here and + generated verbatim into every repo's AGENTS.md by `repos_sync.py --write`: + `never_rewrite_history.md`, `remote_sessions.md`, `end_at_deliverable.md` + (plus the hooks that enforce them, `session_start_hook.sh` and + `end_at_deliverable_hook.sh`). Edit the canonical file, never a generated copy. + `repos_sync.py --write --only "generated Codex hooks"` renders opted-in + `.codex/hooks.json` adapters without touching the broader generated surface. + Codex users must review and trust the exact current hook hash with `/hooks`; + changed or untrusted project hooks are skipped. These adapters register the + reviewed PreToolUse safety guards only. The remote Python SessionStart + bootstrap remains Claude-specific and is not silently copied into Codex. + `community_surface.md` is the one policy page that is *not* generated + anywhere: it decides where users go (one Discussions hub) and where the + development flow stays (per-repo issues); the Ears and the README Support + sections read it as doctrine. +- **Skills** — `skills//` are agent skills and command bodies tightly + coupled to the registry. Claude and Codex discovery is installed by + PyAutoBrain; they source `scripts/prompt_sync.sh` for commit/push. +- **Ledger auto-merge** — a push to `claude/**` or `codex/**` whose whole diff is *ledger* + (`draft/`, `active/`, `complete/`, the root registry files, the dashboard + pages) is merged into `main` by `.github/workflows/mind_ledger_merge.yml` and + the branch deleted — no PR, no session step, no "please merge that" prompt. + Anything touching `scripts/`, `tests/`, `.github/`, `skills/`, `policy/`, + `docs/`, `repos.yaml` or the prose pages is left for a human, as is anything + unclassified (the gate is default deny). So: **push your Mind work and move + on** — do not leave a ledger branch hanging, and do not expect a code branch + to land by itself. `python3 scripts/ledger_merge.py classify --base + origin/main` tells you which side you are on before you push; the full + contract is in [REFERENCE.md](REFERENCE.md) "How the ledger lands". A + conflict on the registries or the generated pages is settled by the + ledger's own grammar (`ledger_merge.py resolve`: entries merge by slug, + renders take main and are regenerated); a branch that still cannot land + gets an issue labelled `ledger-merge`, never a silent red run. + Optional `active.md` session metadata records the actual harness and a known + resume command when available; existing `claude --resume` values remain valid. +- **Scripts** — `scripts/status.sh` (inventory), `scripts/prompt_sync.sh` + (commit/push helpers), `scripts/lifecycle.py` (state moves + drift checks; + `lifecycle.py dates [--write]` reports/backfills the date every registry + entry and issued prompt carries — see [REFERENCE.md](REFERENCE.md) "Task + dates"). + +## When you are asked to add a new prompt + +Write the file under `draft///.md` — pick the work-type +from the list above (use `triage/` if genuinely unsure — never `human_review/`, +see below) and the target +repo/domain as the second folder, e.g. `draft/feature/autolens/potential_corrections.md` +or `draft/bug/autoarray/mask_edge_case.md`. Don't touch `active.md`, `active/` +or `complete/` directly — those are managed by `$start-dev`, `$create-issue` +and the ship skills (`/start_dev` and `/create_issue` in Claude). + +To skip the manual filing, run **`$intake`** (`/intake` in Claude), the +PyAutoBrain Intake/Conception Agent. It classifies a raw idea into the right +`draft///` folder, +writes the light header (incl. the optional `Difficulty:/Autonomy:/Priority:` +keys — see [Prompt file format](#prompt-file-format)), and files the prompt for you. It files a +prompt only; `$start-dev` (`/start_dev` in Claude) remains the separate next step. + +## When you are asked for a human review + +`draft/human_review//.md` holds work that has already **shipped** +and that a human wants to read and sign off before it counts as done. It is the +one work-type nothing may infer: file one only when a human asks for it, by +declaring `Type: human review` (`human-review`/`human_review` read the same) — +`/intake` will never choose it, and no completed task acquires it by default. +Review is opt-in, not a lifecycle stage: `/prm` and the ship skills close a task +out exactly as before and never file a review. + +It renders as its own **Human review** section on `dashboard.md`, directly under +*In flight*, and is deliberately not counted as backlog — a review is not work to +pick up, it is work waiting on a person. Its 📋 hands out a read-and-report +prompt, not a `/start_dev`. Sign one off by retiring the prompt the usual way +(`scripts/lifecycle.py record …`, then regenerate the dashboard); if it does not +pass, the follow-up is an ordinary `$intake`. + +## When you are asked to start work on an existing prompt + +Use `$start-dev draft///.md` (`/start_dev` in Claude). +Older `//.md` and bare `/.md` paths from +before the lifecycle migration still resolve. It +routes to `$start-library` or `$start-workspace` (`/start_library` or +`/start_workspace` in Claude) based on the repos referenced in the prompt body; +routing keys off `@RepoName` references in the content, not the folder. + +## When in doubt + +Read [README.md](README.md). It is current as of the last commit on this branch. diff --git a/scripts/repos_sync.py b/scripts/repos_sync.py index bf08bc904..1aeefbb43 100644 --- a/scripts/repos_sync.py +++ b/scripts/repos_sync.py @@ -495,8 +495,8 @@ def routing_table(categories, repos): lines.append(f"| **{name}** | `{location}` | {repo['role']} |") provenance = ( "Generated from `PyAutoMind/repos.yaml` (the body map — the single " - "source of repo identity). Edit that file, then run " - "`python3 PyAutoMind/scripts/repos_sync.py --write`." + "source of repo identity). From the resolved Mind checkout, edit " + "`repos.yaml`, then run `python3 scripts/repos_sync.py --write`." ) return "\n".join(lines) + "\n\n" + provenance @@ -522,8 +522,9 @@ def owner_map(categories, repos): "**Library repos:** " + ", ".join(libraries) + ".", "**Workspace repos:** " + ", ".join(workspaces) + ".", "", - "Generated from `PyAutoMind/repos.yaml`; edit there, then run " - "`python3 PyAutoMind/scripts/repos_sync.py --write`.", + "Generated from `PyAutoMind/repos.yaml`; from the resolved Mind " + "checkout, edit `repos.yaml`, then run " + "`python3 scripts/repos_sync.py --write`.", ] return "\n".join(lines) diff --git a/scripts/token_load.py b/scripts/token_load.py new file mode 100644 index 000000000..bd246d4f8 --- /dev/null +++ b/scripts/token_load.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Measure the context paid by every PyAuto session and core dev procedures. + +Approximate tokens are UTF-8 bytes / 4, rounded up. Report is read-only; +``check`` exits nonzero when a required file is missing or a budget is exceeded. +The root may be grouped or flat. Repository placement uses Brain's resolver. +""" +from __future__ import annotations + +import argparse +import importlib.util +import json +import math +import os +from pathlib import Path +import sys + +CORE = { + "workspace AGENTS": (None, "AGENTS.md"), + "Brain AGENTS": ("PyAutoBrain", "AGENTS.md"), + "Mind AGENTS": ("PyAutoMind", "AGENTS.md"), + "start_dev entry": ("PyAutoBrain", "skills/start_dev/SKILL.md"), + "start_dev body": ("PyAutoBrain", "skills/start_dev/start_dev.md"), + "prm entry": ("PyAutoBrain", "skills/prm/SKILL.md"), + "prm body": ("PyAutoBrain", "skills/prm/prm.md"), + "context guide": ("PyAutoBrain", "skills/CONTEXT.md"), + "workflow guide": ("PyAutoBrain", "skills/WORKFLOW.md"), +} +CONDITIONAL = { + "start_dev reference": ("PyAutoBrain", "skills/start_dev/reference.md"), + "prm reference": ("PyAutoBrain", "skills/prm/reference.md"), + "prm postmerge": ("PyAutoBrain", "skills/prm/closeout.md"), + "prm MCP lane": ("PyAutoBrain", "skills/prm/mcp.md"), + "prm freeze gate": ("PyAutoBrain", "skills/prm/freeze.md"), + "GitHub reference": ("PyAutoBrain", "skills/GITHUB_ACCESS.md"), + "Mind reference": ("PyAutoMind", "REFERENCE.md"), +} + + +def resolver(): + # This script lives in the Mind checkout. Brain is its sibling in both the + # grouped main tree and flat bundles; use its canonical placement logic. + module_path = Path(__file__).resolve().parents[2] / "PyAutoBrain/agents/_repo_paths.py" + if not module_path.is_file(): + raise FileNotFoundError(f"Brain repository resolver missing: {module_path}") + spec = importlib.util.spec_from_file_location("pyauto_repo_paths", module_path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module.repo_path + + +def measure(path: Path) -> dict: + if not path.is_file(): + return {"path": str(path), "missing": True} + data = path.read_bytes() + return {"path": str(path), "bytes": len(data), + "lines": len(data.splitlines()), "tokens_approx": math.ceil(len(data) / 4)} + + +def collect(root: Path) -> dict: + locate = resolver() + paths = {} + for name, (repo, relative) in (CORE | CONDITIONAL).items(): + base = root if repo is None else locate(root, repo) + paths[name] = measure(base / relative) + agents = ("workspace AGENTS", "Brain AGENTS", "Mind AGENTS") + totals = {} + if all("missing" not in paths[name] for name in agents): + totals["agents_tokens_approx"] = sum(paths[name]["tokens_approx"] for name in agents) + shared = ("context guide", "workflow guide") + start = ("start_dev entry", "start_dev body", *shared) + prm = ("prm entry", "prm body", *shared) + for label, names in (("start_dev_lines", start), ("prm_lines", prm), + ("core_union_lines", tuple(dict.fromkeys((*start, *prm))))): + if all("missing" not in paths[name] for name in names): + totals[label] = sum(paths[name]["lines"] for name in names) + return {"root": str(root), "files": paths, "totals": totals} + + +def violations(result: dict, args: argparse.Namespace) -> list[str]: + files = result["files"] + errors = [f"missing: {name}: {row['path']}" for name, row in files.items() + if "missing" in row] + total = result["totals"].get("agents_tokens_approx") + if total is not None and total > args.agents_budget: + errors.append(f"AGENTS total: {total} > {args.agents_budget} approximate tokens") + for name, budget in (("start_dev_lines", args.start_dev_budget), + ("prm_lines", args.prm_budget)): + lines = result["totals"].get(name) + if lines is not None and lines > budget: + errors.append(f"{name}: {lines} > {budget} lines") + return errors + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("command", choices=("report", "check")) + parser.add_argument("--root", type=Path, default=Path(os.environ.get("PYAUTO_ROOT", ".")), + help="workspace root (grouped main or flat bundle)") + parser.add_argument("--agents-budget", type=int, default=7500) + parser.add_argument("--start-dev-budget", type=int, default=400) + parser.add_argument("--prm-budget", type=int, default=450) + parser.add_argument("--json", action="store_true") + args = parser.parse_args(argv) + try: + result = collect(args.root.resolve()) + except (OSError, ValueError) as error: + print(f"token load: {error}", file=sys.stderr) + return 2 + issues = violations(result, args) + result["violations"] = issues + if args.json: + print(json.dumps(result, indent=2)) + else: + for name, row in result["files"].items(): + if "missing" in row: + print(f"{name}: MISSING {row['path']}") + else: + print(f"{name}: {row['bytes']} bytes, {row['lines']} lines, " + f"~{row['tokens_approx']} tokens") + print(f"AGENTS total: ~{result['totals'].get('agents_tokens_approx', 'unknown')} tokens") + for name in ("start_dev_lines", "prm_lines", "core_union_lines"): + print(f"{name}: {result['totals'].get(name, 'unknown')} lines") + for issue in issues: + print(f"FAIL: {issue}", file=sys.stderr) + return 1 if args.command == "check" and issues else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/skills/create_issue/SKILL.md b/skills/create_issue/SKILL.md index 7c357e91f..a5a6100e1 100755 --- a/skills/create_issue/SKILL.md +++ b/skills/create_issue/SKILL.md @@ -34,10 +34,20 @@ Organ boundary and the execution-environment model: PyAutoBrain `skills/WORKFLOW $create-issue # /create_issue in Claude ``` -Path relative to `PyAutoMind/`. Prompts live under `//` (see -README "Prompt taxonomy"); pre-migration `/.md` paths still resolve. -Examples: `bug/autofit/factor_graph_instance_iteration.md`, -`feature/autoarray/oversampling.md`. +Pass a path relative to the Mind checkout. Prompts live under +`draft///` (see REFERENCE.md "Prompt taxonomy"); +pre-migration `/.md` paths still resolve. Examples: +`draft/bug/autofit/factor_graph_instance_iteration.md` and +`draft/feature/autoarray/oversampling.md`. The skill argument stays Mind-relative +in grouped and flat layouts. Use `PYAUTO_MIND` when the checkout is elsewhere. + +From either workspace root, resolve the checkout once for the shell examples +below (an existing `PYAUTO_MIND` override takes precedence): + +```bash +brain_dir="${PYAUTO_BRAIN:-$(test -d organs/PyAutoBrain && echo organs/PyAutoBrain || echo PyAutoBrain)}" +export PYAUTO_MIND="${PYAUTO_MIND:-$(python3 "$brain_dir/agents/_repo_paths.py" path PyAutoMind --root .)}" +``` ## Inputs @@ -51,7 +61,7 @@ These come from the **caller** (Brain/`$start-dev`) when delegated, or from a | plan (high + detailed) | caller | brief plan from a quick read of the prompt + referenced files | | suggested branch | caller (`plan_branches`) | `feature/` kebab-case, <50 chars | -Resolve repository owners from `PyAutoMind/repos.yaml`; the generated summary +Resolve repository owners from `$PYAUTO_MIND/repos.yaml`; the generated summary in `WORKFLOW.md` is the readable mapping. Do not reuse legacy owner defaults. ## Steps @@ -59,13 +69,18 @@ in `WORKFLOW.md` is the readable mapping. Do not reuse legacy owner defaults. ### 0. Sync new prompt ideas (Mind) ```bash -source PyAutoMind/scripts/prompt_sync.sh +source "$PYAUTO_MIND/scripts/prompt_sync.sh" prompt_sync_new_prompts # no-op if nothing untracked; else commits + pushes new ideas ``` ### 1. Read the prompt -Read `PyAutoMind/`. If missing, report and list prompts in that folder. +Read `/`. Resolve the checkout with `PYAUTO_MIND` when +set; otherwise use the existing Brain repository resolver for the active +workspace layout. If given an absolute path or a workspace-relative prefix +(`organs/PyAutoMind/` or `PyAutoMind/`), strip that resolved checkout prefix +exactly once; never prepend Mind twice. If missing, report and list prompts +in that folder. ### 2. Resolve the inputs @@ -125,7 +140,7 @@ ISSUE_EOF ### 4. Register the task in active.md (Mind) -Add the task entry to `PyAutoMind/active.md` with the issue URL and today's +Add the task entry to `$PYAUTO_MIND/active.md` with the issue URL and today's date (schema in [REFERENCE.md](../../REFERENCE.md) → "`active.md` schema"): ```markdown @@ -150,8 +165,8 @@ flight) — the second of the three lifecycle states (`draft/ → active/ → complete/`; issue #71). Use `git mv` to preserve history: ```bash -mkdir -p PyAutoMind/active -git -C PyAutoMind mv active/ +mkdir -p "$PYAUTO_MIND/active" +git -C "$PYAUTO_MIND" mv active/ ``` The `mkdir -p` matters on a **freshly-spawned** Mind, where `active/` does not @@ -169,13 +184,13 @@ Issued: Confirm both landed before pushing: ```bash -python3 PyAutoMind/scripts/lifecycle.py dates # OK when nothing is undated +python3 "$PYAUTO_MIND/scripts/lifecycle.py" dates # OK when nothing is undated ``` ### 6. Push Mind ```bash -source PyAutoMind/scripts/prompt_sync.sh +source "$PYAUTO_MIND/scripts/prompt_sync.sh" prompt_sync_push "prompt: file issue for (#)" ``` diff --git a/tests/test_repos_sync_provenance.py b/tests/test_repos_sync_provenance.py new file mode 100644 index 000000000..94a8f14a3 --- /dev/null +++ b/tests/test_repos_sync_provenance.py @@ -0,0 +1,17 @@ +"""Generated provenance must work from either workspace checkout layout.""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) +import repos_sync # noqa: E402 + + +def test_routing_and_owner_provenance_use_mind_checkout(): + categories = {"organ": {"label": "Organ", "role": "example"}} + repos = {"OrganOne": {"category": "organ", "path": "organs/OrganOne", + "github": "Example/OrganOne", "role": "example"}} + for render in (repos_sync.routing_table, repos_sync.owner_map): + text = render(categories, repos) + assert "from the resolved mind checkout" in text.lower() + assert "python3 scripts/repos_sync.py --write" in text + assert "python3 PyAutoMind/scripts/repos_sync.py --write" not in text diff --git a/tests/test_token_load.py b/tests/test_token_load.py new file mode 100644 index 000000000..28ff07f55 --- /dev/null +++ b/tests/test_token_load.py @@ -0,0 +1,80 @@ +"""The token report handles both workspace layouts and fails visibly on drift.""" +import json +import subprocess +import sys +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/token_load.py" + + +def workspace(tmp_path, grouped): + root = tmp_path / "workspace" + root.mkdir(parents=True) + (root / "AGENTS.md").write_text("root\n") + organ_dir = root / "organs" if grouped else root + brain = organ_dir / "PyAutoBrain" + mind = organ_dir / "PyAutoMind" + for repo in (brain, mind): + (repo / ".git").mkdir(parents=True) + (repo / "AGENTS.md").write_text("rules\n") + for path in ( + brain / "skills/start_dev/start_dev.md", + brain / "skills/start_dev/SKILL.md", + brain / "skills/prm/prm.md", + brain / "skills/prm/SKILL.md", + brain / "skills/prm/closeout.md", + brain / "skills/prm/mcp.md", + brain / "skills/prm/freeze.md", + brain / "skills/start_dev/reference.md", + brain / "skills/prm/reference.md", + brain / "skills/CONTEXT.md", + brain / "skills/WORKFLOW.md", + brain / "skills/GITHUB_ACCESS.md", + mind / "REFERENCE.md", + ): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("one\ntwo\n") + return root, brain, mind + + +def run(root, *options): + return subprocess.run([sys.executable, str(SCRIPT), *options, "--root", str(root), "--json"], + text=True, capture_output=True) + + +def test_report_resolves_grouped_and_flat(tmp_path): + for grouped in (True, False): + root, brain, mind = workspace(tmp_path / str(grouped), grouped) + proc = run(root, "report") + assert proc.returncode == 0, proc.stderr + report = json.loads(proc.stdout) + assert report["files"]["Brain AGENTS"]["path"] == str(brain / "AGENTS.md") + assert report["files"]["Mind AGENTS"]["path"] == str(mind / "AGENTS.md") + assert report["files"]["start_dev body"]["lines"] == 2 + assert report["totals"]["start_dev_lines"] == 8 + assert report["totals"]["prm_lines"] == 8 + assert report["totals"]["core_union_lines"] == 12 + assert report["totals"]["agents_tokens_approx"] == 6 + assert not report["violations"] + + +def test_missing_paths_are_reported_and_check_fails(tmp_path): + root, brain, _ = workspace(tmp_path, False) + (brain / "skills/prm/reference.md").unlink() + report = run(root, "report") + assert report.returncode == 0 + assert "missing" in json.loads(report.stdout)["files"]["prm reference"] + check = run(root, "check") + assert check.returncode == 1 + assert "missing: prm reference" in json.loads(check.stdout)["violations"][0] + + +def test_budgets_cover_agents_and_both_core_procedures(tmp_path): + root, _, _ = workspace(tmp_path, True) + check = run(root, "check", "--agents-budget", "4", "--start-dev-budget", "1", + "--prm-budget", "1") + assert check.returncode == 1 + violations = json.loads(check.stdout)["violations"] + assert any("AGENTS total" in item for item in violations) + assert any("start_dev_lines" in item for item in violations) + assert any("prm_lines" in item for item in violations) From 401c2cbce38d9c4a1e6fc4d16507dafbc38042cc Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 19 Sep 2026 14:43:49 +0100 Subject: [PATCH 2/3] Keep issue skill within the core reading budget --- skills/create_issue/SKILL.md | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/skills/create_issue/SKILL.md b/skills/create_issue/SKILL.md index a5a6100e1..093f5821f 100755 --- a/skills/create_issue/SKILL.md +++ b/skills/create_issue/SKILL.md @@ -12,19 +12,10 @@ Turn a `PyAutoMind/` prompt into a tracked GitHub issue and register it. > via `PyAutoBrain/skills/GITHUB_ACCESS.md`. Do not install `gh` to close the > gap — that page records why an installed one still fails. -A **PyAutoMind** primitive — it owns the mechanical **issue + registry write**: -assemble the issue body, create the issue, register the task in `active.md`, move -the prompt to `active/`, and push Mind state. The *reasoning* (classify repos, -explore code, generate the plan) belongs to **PyAutoBrain**: - -- **Called by Brain.** `$start-dev` (`/start_dev` in Claude) does the triage/planning via the - Feature Agent and then **delegates the issue write to this skill**, passing the - primary repo, title, plan and suggested branch. Brain does not re-implement - issue creation. -- **Runnable standalone.** You can run `$create-issue` (`/create_issue` in Claude) by itself when you just - want an issue from a prompt without full triage or worktree routing — it does a - *light* pass to fill any inputs the caller didn't supply. For deep - classification + dev-environment setup, use `$start-dev` instead. +Mind owns the issue/registry write, prompt lifecycle move and push. Brain owns +classification and planning. When called by start-dev, use its supplied repo, +title, plan and branch verbatim; standalone, fill missing inputs with a light +pass. Deep triage and environment setup still go through start-dev. Organ boundary and the execution-environment model: PyAutoBrain `skills/WORKFLOW.md`. From 335d0b3fb1ad8241ea448168f9e9e4fbb983ff88 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 19 Sep 2026 14:52:20 +0100 Subject: [PATCH 3/3] Resolve measured checkouts without an installed sibling Brain --- scripts/token_load.py | 22 +++++----------------- tests/test_token_load.py | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/scripts/token_load.py b/scripts/token_load.py index bd246d4f8..da160c4f0 100644 --- a/scripts/token_load.py +++ b/scripts/token_load.py @@ -3,18 +3,19 @@ Approximate tokens are UTF-8 bytes / 4, rounded up. Report is read-only; ``check`` exits nonzero when a required file is missing or a budget is exceeded. -The root may be grouped or flat. Repository placement uses Brain's resolver. +The root may be grouped or flat. Repository placement uses Mind's checkout helper (Brain's resolver when present). """ from __future__ import annotations import argparse -import importlib.util import json import math import os from pathlib import Path import sys +from repos_sync import repo_checkout + CORE = { "workspace AGENTS": (None, "AGENTS.md"), "Brain AGENTS": ("PyAutoBrain", "AGENTS.md"), @@ -37,18 +38,6 @@ } -def resolver(): - # This script lives in the Mind checkout. Brain is its sibling in both the - # grouped main tree and flat bundles; use its canonical placement logic. - module_path = Path(__file__).resolve().parents[2] / "PyAutoBrain/agents/_repo_paths.py" - if not module_path.is_file(): - raise FileNotFoundError(f"Brain repository resolver missing: {module_path}") - spec = importlib.util.spec_from_file_location("pyauto_repo_paths", module_path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module.repo_path - - def measure(path: Path) -> dict: if not path.is_file(): return {"path": str(path), "missing": True} @@ -58,10 +47,9 @@ def measure(path: Path) -> dict: def collect(root: Path) -> dict: - locate = resolver() paths = {} for name, (repo, relative) in (CORE | CONDITIONAL).items(): - base = root if repo is None else locate(root, repo) + base = root if repo is None else repo_checkout(root, repo) paths[name] = measure(base / relative) agents = ("workspace AGENTS", "Brain AGENTS", "Mind AGENTS") totals = {} @@ -104,7 +92,7 @@ def main(argv=None) -> int: args = parser.parse_args(argv) try: result = collect(args.root.resolve()) - except (OSError, ValueError) as error: + except (OSError, ValueError, RuntimeError) as error: print(f"token load: {error}", file=sys.stderr) return 2 issues = violations(result, args) diff --git a/tests/test_token_load.py b/tests/test_token_load.py index 28ff07f55..ebc93402c 100644 --- a/tests/test_token_load.py +++ b/tests/test_token_load.py @@ -78,3 +78,26 @@ def test_budgets_cover_agents_and_both_core_procedures(tmp_path): assert any("AGENTS total" in item for item in violations) assert any("start_dev_lines" in item for item in violations) assert any("prm_lines" in item for item in violations) + + +def test_script_runs_without_a_brain_checkout_beside_it(tmp_path): + # Match Mind-only CI: no installed workspace or sibling Brain can help. + import shutil + isolated = tmp_path / "isolated_mind/scripts" + isolated.mkdir(parents=True) + for name in ("token_load.py", "repos_sync.py", "smoke_bootstrap_sync.py"): + shutil.copyfile(SCRIPT.parent / name, isolated / name) + root, _, _ = workspace(tmp_path / "measured", True) + proc = subprocess.run([sys.executable, str(isolated / "token_load.py"), + "check", "--root", str(root), "--json"], + text=True, capture_output=True) + assert proc.returncode == 0, proc.stderr + assert json.loads(proc.stdout)["totals"]["agents_tokens_approx"] == 6 + + +def test_ambiguous_grouped_and_flat_checkout_fails_closed(tmp_path): + root, _, _ = workspace(tmp_path, True) + (root / "PyAutoBrain").mkdir() + proc = run(root, "report") + assert proc.returncode == 2 + assert "ambiguous flat and grouped" in proc.stderr