diff --git a/AGENTS.md b/AGENTS.md index 3f4c5a34..7193401b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -79,6 +79,7 @@ invoking it; `bin/pyauto-brain help ` exposes its full contract. | `bug` | Classify regressions and plan repairs | `bin/pyauto-brain bug` | | `refactor` | Plan behavior-preserving restructuring | `bin/pyauto-brain refactor` | | `workspace` | Plan or survey examples and tutorials | `bin/pyauto-brain workspace` | +| `docs` | Plan README, setup and Read the Docs pages; audit a page's style | `bin/pyauto-brain docs` | | `eyes` | Survey figures and route accepted critiques | `bin/pyauto-brain eyes` | | `profiling` | Plan campaigns; ingest results; triage profiling drift | `bin/pyauto-brain profiling` | | `cortex` | Pull science runs and record human checkins | `bin/pyauto-brain cortex` | diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 59ae4f1c..aaf30764 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -49,8 +49,9 @@ consulting a conductor. If a rule here starts needing to *judge* rather than | **Review-minute budget** | the human's hour is the binding resource; see above | | **One member per *library* repo per shift** | concurrent members do not collide at dispatch (separate worktrees) — they collide at **merge**, because the first `/prm` moves `main` and invalidates the others' test and smoke evidence. Workspace, docs and organ repos are exempt: two docs changes in one shift cost nothing. Work concentrates in four repos (PyAutoFit 118/332 August records, PyAutoArray 98, PyAutoGalaxy 82, PyAutoLens 78), so effective parallelism is two or three, not six. | | **One slice per epic per batch** | epic phases are ordered, so two members could not run in parallel anyway — and this is what interleaves small pieces of long programmes with standalone work | -| **`Unattended: ready` only** | `needs-slicing` goes to the decomposition pass; `never` never enters a batch | +| **`Unattended: ready` only** | `needs-slicing` goes to the decomposition pass (`batch slice`); `never` never enters a batch | | **Lane match** | a session detects its own lane and plans only that one | +| **Not `looks-shipped`** | a draft the close-out guard (`intake looks-shipped`) flagged with strong evidence that its work already shipped waits until a human closes it or lists it in `PyAutoMind/looks_shipped_dismissed.md`; the flags are read from `PyAutoMind/looks_shipped.json` at plan time, so a dismissal takes effect at once. The 2026-11-05-am batch proposed two shipped drafts. | | **Backpressure** | see below | | **Brief scope** | under a shift brief, only its named tasks and the backlog its dip policy covers run; anything else is a dispatch outside the launch, which "What a batch launch is" forbids (`AUTONOMY.md`, 2026-11-03) | | **Merge cap** | unattended `glance` merges stop at the brief's `merge-cap:`; each merge moves `main` and stales the next member's evidence, and the cap bounds what one unread shift can change | @@ -734,10 +735,51 @@ The extension point above (`KINDS`) is what made that possible and is kept: a member kind is a scorer plus a block builder plus a claim, and nothing about the record, the packet or the renderer has to learn its vocabulary. -## Not built yet +## Slicing a `needs-slicing` prompt (`slice`) -`slice` — the decomposition pass doctrine has named since inception — is the -conductor's one remaining verb; see the epic ledger, -`PyAutoMind/draft/feature/pyautomind/two_slot_batching_epic.md`. `plan` and -`collect` stand on their own in the meantime: plan a slot, dispatch by tapping -the dashboard's existing chips, collect what comes back. +``` +pyauto-brain batch slice # propose; writes nothing +pyauto-brain batch slice --slices plan.md # cut from a plan file +pyauto-brain batch slice --apply [--mind P] # write children + epics.md +``` + +A prompt too large for one unattended run is a decomposition problem, not a +scheduling one. `slice` proposes **two to four** children of a prompt grading +`Unattended: needs-slicing`, offline and stdlib-only. + +**The cut is declared, never invented.** Where work divides is a semantic +judgement no stdlib heuristic makes honestly, so the candidate slices come from +the parent's own `## Slices` (or `## Phases`) section, or from an +agent-authored plan file passed with `--slices` (the same numbered items; the +heading optional). One numbered item per slice: + +``` +1. **Library core.** What it does. *Repos:* PyAutoFit + *Witness:* `pytest test_autofit/thing` passes. *Consequence:* glance. +2. **Workspace example.** ... *Witness:* the example runs in smoke. *Depends:* 1 +``` + +`*Witness:*` is required; `*Repos:*`, `*Consequence:*`, `*Difficulty:*`, +`*Lane:*`, `*Review-minutes:*` and `*Depends:*` are optional (repos default to +the parent's repos the item names). The verb renders each child — the parent's +`Type`/`Autonomy`/`Priority`/`Themes`, `Epic:` + `Phase:`, and a `## Seam` +section naming what it owns and what comes before and after — and the sizing +faculty (`judge_slices`) judges it against the seam rules: + +1. **one unattended run** — the child must grade `Unattended: ready`; +2. **its own witness** — none is refused as *a smaller judge task, not a + slice*; +3. **independently revertible** — it names a repo, and depends on no later + slice; +4. **repo-boundary seams, library before workspace** — warnings, not refusals. + +Fewer than two or more than four slices is refused. Revertibility beyond rule 3 +is the human's to read off the proposal. + +Without `--apply` it only prints (`--json` too). `--apply` writes only a clean +proposal: the children beside the parent as `_s_.md`, never +overwriting, plus an `epics.md` entry with the parent as its **ledger** unless +the parent already is one. The parent is never renamed, retired or edited — +that is the human's call. `/intake` offers the verb when a freshly filed prompt +sizes `needs-slicing`. Exit: **0** proposed · **1** refused · **2** usage · +**4** no Mind. diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 8380101d..95679693 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -55,6 +55,14 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) from _status import PENDING_RE, RULING_WORDS, freeze_line # noqa: E402 import _brief # noqa: E402 +# The close-out guard's reader (intake `looks-shipped`): the live flags minus +# human dismissals. Loaded by path — a plain `import _shipped` would also work +# once intake's directory is on sys.path, but this keeps the batch planner from +# shadowing anything else of that name. +_shipped_spec = importlib.util.spec_from_file_location( + "_shipped_for_batch", BRAIN / "agents" / "conductors" / "intake" / "_shipped.py") +_shipped = importlib.util.module_from_spec(_shipped_spec) +_shipped_spec.loader.exec_module(_shipped) # One slot's worth of the human's attention, and only the DEFAULT: the human # sets it per slot with --budget, because they know whether the next one is a @@ -159,11 +167,16 @@ def survey(mind: Path) -> list[dict]: """Grade every backlog prompt. Epic membership rides along for the one-slice-per-epic rule.""" out = [] + # Backpressure from the close-out guard: a draft with strong evidence that + # its work already shipped waits for a human to close or dismiss it. The + # 2026-11-05-am batch proposed two shipped tasks; this is the stop. + flagged = _shipped.flagged_paths(mind) for f in sorted(mind.glob("draft/**/*.md")): if f.name == "README.md": continue text = f.read_text(encoding="utf-8", errors="replace") g = grade(f, mind) + g["looks_shipped"] = f.relative_to(mind).as_posix() in flagged g["epic"] = _epic_of(text) g["phase"] = _phase_of(text) g["done"] = _is_done(text) @@ -317,6 +330,9 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, # which is the failure the whole epic exists to remove. if r.get("done"): rejected.append((r["path"], "Status: says the work is already done")) + elif r.get("looks_shipped"): + rejected.append((r["path"], "looks shipped — confirm (close) or " + f"dismiss it ({_shipped.DISMISS_FILE}) first")) elif r.get("epic") and r.get("phase", float("inf")) > next_phase.get( r["epic"], float("inf")): rejected.append((r["path"], @@ -2787,8 +2803,10 @@ def organ_for(kind: str, root: Path, slot: str) -> dict: def main(argv=None) -> int: ap = argparse.ArgumentParser(prog="batch") - ap.add_argument("verb", choices=["plan", "collect", "brief", "digest", "watch"], nargs="?", - default="plan") + ap.add_argument("verb", choices=["plan", "collect", "brief", "digest", "watch", + "slice"], nargs="?", default="plan") + ap.add_argument("prompt", nargs="?", default="", + help="slice: the needs-slicing prompt to decompose") ap.add_argument("--mind", type=Path, default=BODY_MAP_PATH.parent) ap.add_argument("--budget", type=int, default=DEFAULT_REVIEW_BUDGET, help="review-minutes available in the slot") @@ -2805,6 +2823,11 @@ def main(argv=None) -> int: ap.add_argument("--brief", default="", metavar="FILE", help="plan: compose inside this shift brief (named tasks " "first, then its backlog policy)") + # slice + ap.add_argument("--slices", default="", metavar="FILE", + help="slice: an agent-authored slice plan (numbered items " + "with *Witness:* fields) instead of the parent's own " + "`## Slices`/`## Phases` section") # digest ap.add_argument("--record", default="", metavar="FILE", help="digest / watch: the shift brief record (read-only — " @@ -2845,7 +2868,15 @@ def main(argv=None) -> int: lane = a.lane or detect_lane() mind = a.mind.resolve() + if a.prompt and a.verb != "slice": + print(f"batch {a.verb}: unexpected argument {a.prompt!r}", file=sys.stderr) + return RC_USAGE + if a.slices and a.verb != "slice": + print("batch: --slices belongs to `batch slice`", file=sys.stderr) + return RC_USAGE try: + if a.verb == "slice": + return _main_slice(mind, a) if a.verb == "collect": return _main_collect(mind, a) if a.verb == "brief": @@ -2860,6 +2891,37 @@ def main(argv=None) -> int: return RC_USAGE +def _main_slice(mind: Path, a) -> int: + """`batch slice <prompt> [--slices FILE] [--apply] [--json]` — propose the + children of a needs-slicing prompt; only `--apply` writes (`_slice`).""" + import _slice + if not a.prompt: + print("batch slice: name the needs-slicing prompt to slice", + file=sys.stderr) + return RC_USAGE + used = [f"--{f}" for f in COLLECT_ONLY if f != "apply" and getattr(a, f)] + if used: + print(f"batch slice: {', '.join(used)} belong(s) to `batch collect`", + file=sys.stderr) + return RC_USAGE + if not (mind / "draft").is_dir(): + print(f"batch: no PyAutoMind backlog at {mind}", file=sys.stderr) + return RC_NO_MIND + try: + d = _slice.propose(mind, a.prompt, slices_file=a.slices) + written = _slice.apply(mind, d) if a.apply and d["ok"] else [] + except _slice.SliceError as e: + print(e, file=sys.stderr) + return RC_USAGE + if a.as_json: + print(json.dumps({**d, "written": written}, indent=2)) + else: + print(_slice.report(d, applied=written)) + if a.apply and not d["ok"]: + print("(--apply refused: the proposal has refusals)") + return RC_OK if d["ok"] else RC_FINDINGS + + def _main_digest(mind: Path, a) -> int: """`batch digest --record <file>` — print the shift's digest; writes nothing. diff --git a/agents/conductors/batch/_slice.py b/agents/conductors/batch/_slice.py new file mode 100644 index 00000000..727d4a5f --- /dev/null +++ b/agents/conductors/batch/_slice.py @@ -0,0 +1,413 @@ +"""agents/conductors/batch/_slice.py — `batch slice`, the decomposition pass. + +A `needs-slicing` prompt is too large to run unattended; this verb turns it +into two to four children that each are. It does NOT invent the cut: deciding +where a piece of work divides is a semantic judgement no stdlib heuristic can +make honestly. The candidate slices are DECLARED — by the parent prompt's own +`## Slices` (or `## Phases`) section, or by an agent-authored plan file passed +with `--slices FILE` — and this verb does the parts that are mechanical: + + * parse the declared slices (numbered items; `*Witness:*`, `*Repos:*`, + `*Consequence:*`, `*Difficulty:*`, `*Lane:*`, `*Depends:*` inline fields); + * render each as a child prompt with an explicit seam; + * have the sizing faculty judge every child against the seam rules + (`_sizing.judge_slices`) — a child with no witness is refused as "a smaller + judge task, not a slice"; + * under `--apply`, write the children beside the parent plus an `epics.md` + entry naming the parent as the ledger. + +The parent is never renamed, retired or edited: that is the human's call. +Stdlib-only and offline. +""" +from __future__ import annotations + +import datetime as _dt +import re +from pathlib import Path + +from _sizing import ( # noqa: E402 (sys.path set by _batch) + effective_difficulty, effective_unattended, judge_slices, normalise_repo, + parse_prompt, +) + +SECTION_RE = re.compile(r"^(#{2,3})\s+(Slices|Phases)\b", re.I) +HEADING_RE = re.compile(r"^(#{1,6})\s") +ITEM_RE = re.compile(r"^(\d+)[a-z]?[.)]\s+(.*)$") +FIELDS = ("witness", "repos", "consequence", "difficulty", "lane", "depends", + "review-minutes") +FIELD_RE = re.compile( + r"\*{1,2}(" + "|".join(FIELDS) + r"):\*{1,2}\s*", re.I) +# Header keys the parent passes down unchanged (after Difficulty). +INHERITED = ("Autonomy", "Priority") + + +class SliceError(Exception): + """A usage problem (no such prompt, no declared slices, ...).""" + + +# --- parse ------------------------------------------------------------------- +def _section(text: str) -> list[str] | None: + """The lines of the first `## Slices` / `## Phases` section, or None.""" + lines = text.splitlines() + for i, line in enumerate(lines): + m = SECTION_RE.match(line) + if not m: + continue + level, out = len(m.group(1)), [] + for nxt in lines[i + 1:]: + h = HEADING_RE.match(nxt) + if h and len(h.group(1)) <= level: + break + out.append(nxt) + return out + return None + + +def _fields(raw: str) -> tuple[str, dict]: + """Split an item's text into (prose, {field: value}).""" + parts = FIELD_RE.split(raw) + prose, found = parts[0], {} + for key, value in zip(parts[1::2], parts[2::2]): + found.setdefault(key.lower(), " ".join(value.split()).strip()) + return prose.strip(), found + + +def _word(value: str) -> str: + return (value.split() or [""])[0].strip(".,;").lower() + + +def parse_slices(text: str, *, whole_file: bool = False) -> list[dict]: + """Numbered items of the declared section -> [{index, title, body, ...}]. + + `whole_file`: a `--slices` plan file need not carry the heading; when it + has none, every numbered item in it is a slice.""" + lines = _section(text) + if lines is None: + if not whole_file: + return [] + lines = text.splitlines() + items, cur = [], None + for line in lines: + m = ITEM_RE.match(line) + if m: + cur = {"index": int(m.group(1)), "raw": [m.group(2)]} + items.append(cur) + elif cur is not None: + cur["raw"].append(line.strip()) + out = [] + for it in items: + raw = " ".join(x for x in it["raw"] if x) + prose, f = _fields(raw) + bold = re.match(r"^\*\*(.+?)\*\*\s*", prose) + if bold: + title, body = bold.group(1).strip().rstrip("."), prose[bold.end():] + else: + title = re.split(r"(?<=[.;:])\s", prose, 1)[0].rstrip(".;:") + body = prose + repos = [r.strip(" `.") for r in re.split(r"[,\s]+", f.get("repos", "")) + if r.strip(" `.")] + depends = [int(d) for d in re.findall(r"\d+", f.get("depends", ""))] + out.append({ + "index": it["index"], "title": title[:120] or f"slice {it['index']}", + "body": body.strip(), "witness": f.get("witness", "").rstrip(), + "repos": repos, "consequence": _word(f.get("consequence", "")), + "difficulty": _word(f.get("difficulty", "")), + "lane": _word(f.get("lane", "")), "depends": depends, + "review_minutes": _word(f.get("review-minutes", "")), + }) + return out + + +# --- the parent ---------------------------------------------------------------- +def _header(text: str, key: str) -> str: + for line in text.splitlines()[:40]: + if line.lower().startswith(f"{key.lower()}:"): + return line.split(":", 1)[1].strip() + return "" + + +def _list_header(text: str, key: str) -> list[str]: + m = re.search(rf"^{key}:\n((?:- .+\n?)+)", text, re.M) + return [ln[2:].strip() for ln in m.group(1).splitlines()] if m else [] + + +def _title(text: str, fallback: str) -> str: + for line in text.splitlines(): + if line.startswith("# "): + return line[2:].strip().strip("`") + return fallback + + +def read_epics(mind: Path) -> list[dict]: + """`epics.md` -> [{slug, ledger}] (the two fields slicing needs).""" + f = mind / "epics.md" + if not f.is_file(): + return [] + out = [] + for line in f.read_text(encoding="utf-8", errors="replace").splitlines(): + h = re.match(r"^## (\S+)\s*$", line) + if h: + out.append({"slug": h.group(1), "ledger": ""}) + elif out and line.startswith("- ledger:") and not out[-1]["ledger"]: + out[-1]["ledger"] = line.split(":", 1)[1].strip().strip("`") + return out + + +def _slugify(text: str) -> str: + return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") + + +def _file_slug(text: str, words: int = 5) -> str: + toks = re.findall(r"[a-z0-9]+", text.lower()) + return "_".join(toks[:words]) or "slice" + + +def resolve_prompt(mind: Path, prompt: str) -> Path: + for cand in (Path(prompt), mind / prompt): + if cand.is_file(): + return cand.resolve() + raise SliceError(f"batch slice: no such prompt {prompt}") + + +# --- render -------------------------------------------------------------------- +def _repo_spellings(parent_repos: list[str]) -> dict: + return {normalise_repo(r): r for r in parent_repos} + + +def _child_repos(s: dict, parent_text: str, parent_repos: list[str]) -> list: + """Declared `*Repos:*`, else the parent's repos the item names, else the + parent's one repo when it has exactly one.""" + if s["repos"]: + return s["repos"] + spell = _repo_spellings(parent_repos) + words = {normalise_repo(w) for w in re.findall(r"[A-Za-z0-9_]+", + s["title"] + " " + s["body"])} + named = [spell[k] for k in spell if k in words] + if named: + return named + return list(parent_repos) if len(parent_repos) == 1 else [] + + +def _seam(s: dict, slices: list, repos: list) -> str: + pos = slices.index(s) + before = slices[pos - 1] if pos else None + after = slices[pos + 1] if pos + 1 < len(slices) else None + parts = [f"owns {', '.join(repos) or '(no repo named)'}"] + parts.append(f"after slice {before['index']} ({before['title']})" if before + else "first — nothing before it") + parts.append(f"before slice {after['index']} ({after['title']})" if after + else "last") + if s["depends"]: + parts.append("needs slice(s) " + ", ".join(map(str, s["depends"])) + + " merged first") + return "; ".join(parts) + + +def render_child(s: dict, slices: list, *, parent_rel: str, parent_text: str, + epic: str, repos: list, filed: str) -> str: + lines = [f"# {s['title']}", ""] + kind = _header(parent_text, "Type") + if kind: + lines.append(f"Type: {kind}") + # The child's target is the parent's when the child still touches it, + # else the child's first repo — a workspace slice does not target a library. + target = _header(parent_text, "Target") + if repos and normalise_repo(target) not in {normalise_repo(r) for r in repos}: + target = repos[0] + if target: + lines.append(f"Target: {target}") + if repos: + lines.append("Repos:") + lines += [f"- {r}" for r in repos] + themes = _list_header(parent_text, "Themes") + if themes: + lines.append("Themes:") + lines += [f"- {t}" for t in themes] + if s["difficulty"]: + lines.append(f"Difficulty: {s['difficulty']}") + for key in INHERITED: + v = _header(parent_text, key) + if v: + lines.append(f"{key}: {v}") + lines.append("Status: draft") + lines.append(f"Epic: {epic}") + lines.append(f"Phase: {s['index']}") + if s["consequence"]: + lines.append(f"Consequence: {s['consequence']}") + if s["witness"]: + lines.append(f"Witness: {s['witness']}") + if s["review_minutes"]: + lines.append(f"Review-minutes: {s['review_minutes']}") + lane = s["lane"] or _header(parent_text, "Lane") + if lane: + lines.append(f"Lane: {lane}") + lines.append(f"Filed: {filed}") + lines += [ + "", s["body"] or s["title"], "", + "## Seam", "", + f"Slice {s['index']} of {len(slices)} of `{parent_rel}` (epic " + f"`{epic}`): {_seam(s, slices, repos)}. One unattended run; reviewed " + "against its own witness; revertible on its own PR(s).", "", + ] + return "\n".join(lines) + + +# --- propose ----------------------------------------------------------------- +def propose(mind: Path, prompt: str, *, slices_file: str = "", + filed: str = "") -> dict: + """Read the parent and its declared slices, render + judge the children. + + Writes nothing. The result carries every child's path and text, so + `apply` is a pure write of what was shown.""" + mind = mind.resolve() + parent = resolve_prompt(mind, prompt) + try: + parent_rel = parent.relative_to(mind).as_posix() + except ValueError: + raise SliceError(f"batch slice: {parent} is not inside the Mind at " + f"{mind} (pass --mind)") + text = parent.read_text(encoding="utf-8", errors="replace") + filed = filed or _dt.date.today().isoformat() + pp = parse_prompt(parent, mind) + level, _, factors, derived = effective_difficulty(pp) + grade, grade_why, _ = effective_unattended(pp, level, factors, derived) + + if slices_file: + sf = Path(slices_file) + if not sf.is_file(): + raise SliceError(f"batch slice: no such slices file {slices_file}") + slices = parse_slices(sf.read_text(encoding="utf-8"), whole_file=True) + source = f"--slices {slices_file}" + else: + slices = parse_slices(text) + source = f"the parent's `## Slices`/`## Phases` section" + + epics = read_epics(mind) + existing = next((e for e in epics if e["ledger"] == parent_rel), None) + epic = existing["slug"] if existing else _slugify(parent.stem) + epic_clash = (not existing + and any(e["slug"] == epic for e in epics)) + + parent_repos = _list_header(text, "Repos") + children = [] + for s in slices: + repos = _child_repos(s, text, parent_repos) + body = render_child(s, slices, parent_rel=parent_rel, parent_text=text, + epic=epic, repos=repos, filed=filed) + name = f"{parent.stem}_s{s['index']}_{_file_slug(s['title'])}.md" + dest = parent.parent / name + children.append({ + "index": s["index"], "title": s["title"], "witness": s["witness"], + "repos": repos, "depends": s["depends"], + "path": dest.relative_to(mind).as_posix(), "text": body, + "exists": dest.exists(), + "p": parse_prompt(dest, mind, text=body), + "seam": _seam(s, slices, repos), + }) + + verdict = judge_slices(children) + refusals = list(verdict["refusals"]) + if grade != "needs-slicing": + refusals.insert(0, f"the parent grades Unattended: {grade}, not " + "needs-slicing — declare `Unattended: needs-slicing` " + "if it is too large for one run") + if not slices: + refusals.insert(0, f"no slices declared in {source} — this verb renders " + "and judges a decomposition, it does not invent one; " + "author a `## Slices` section (or `--slices FILE`)") + if epic_clash: + refusals.append(f"epics.md already has an entry `{epic}` for a " + "different ledger — rename the parent's slug by hand") + dupes = sorted({c["index"] for c in children + if [x["index"] for x in children].count(c["index"]) > 1}) + if dupes: + refusals.append(f"slice number(s) {dupes} declared twice") + for c in children: + c.update({k: verdict["per"][c["index"]][k] for k in ( + "difficulty", "consequence", "review_minutes", "unattended")}) + c["refusals"] = verdict["per"][c["index"]]["refusals"] + c["warnings"] = verdict["per"][c["index"]]["warnings"] + if c["exists"]: + c["refusals"].append(f"{c['path']} already exists — never " + "overwritten") + del c["p"] + ok = not refusals and not any(c["refusals"] for c in children) + return { + "ok": ok, "parent": parent_rel, "parent_unattended": grade, + "parent_why": grade_why[0] if grade_why else "", "source": source, + "epic": epic, "epic_exists": bool(existing), "children": children, + "refusals": refusals, "warnings": verdict["warnings"], + "title": _title(text, parent.stem), "filed": filed, + } + + +def epic_entry(d: dict) -> str: + order = " → ".join(f"{c['index']} {c['title']} ({', '.join(c['repos'])})" + for c in d["children"]) + paths = ", ".join(c["path"] for c in d["children"]) + return (f"\n## {d['epic']}\n" + f"- title: {d['title']}\n" + f"- ledger: {d['parent']}\n" + f"- status: SLICED {d['filed']} by `batch slice` into " + f"{len(d['children'])} children ({paths}); the parent is unchanged " + "and stays the ledger\n" + f"- notes: phases in order: {order}\n") + + +def apply(mind: Path, d: dict) -> list[str]: + """Write the children and (when the parent is not already an epic) the + epics.md entry. Refuses unless the proposal was clean. Never touches the + parent file.""" + if not d["ok"]: + raise SliceError("batch slice: the proposal is refused — nothing written") + mind = mind.resolve() + written = [] + for c in d["children"]: + dest = mind / c["path"] + if dest.exists(): # re-checked at write time + raise SliceError(f"batch slice: {c['path']} appeared — nothing " + "more written") + for c in d["children"]: + (mind / c["path"]).write_text(c["text"], encoding="utf-8") + written.append(c["path"]) + if not d["epic_exists"]: + f = mind / "epics.md" + before = f.read_text(encoding="utf-8") if f.is_file() else "# Epics\n" + f.write_text(before.rstrip("\n") + "\n" + epic_entry(d), encoding="utf-8") + written.append("epics.md") + return written + + +# --- report -------------------------------------------------------------------- +def report(d: dict, *, applied: list | None = None) -> str: + head = "PROPOSED" if d["ok"] else "REFUSED" + out = [f"== Slice proposal: {d['parent']} — {head} ==", + f"Parent: Unattended: {d['parent_unattended']} — left untouched " + "(renaming or retiring it is the human's call)", + f"Source: {d['source']}", + f"Epic: {d['epic']} (" + + ("already in epics.md" if d["epic_exists"] + else "new epics.md entry, the parent as its ledger") + ")", ""] + for c in d["children"]: + out.append(f" {c['index']}. {c['title']}") + out.append(f" -> {c['path']}") + out.append(f" witness: {c['witness'] or '(none)'}") + out.append(f" {c['difficulty']} · {c['consequence']} · " + f"~{c['review_minutes']} review-min · unattended " + f"{c['unattended']}") + out.append(f" seam: {c['seam']}") + out += [f" ✗ {r}" for r in c["refusals"]] + out += [f" ! {w}" for w in c["warnings"]] + if d["refusals"]: + out.append("") + out += [f"✗ {r}" for r in d["refusals"]] + out.append("") + if applied: + out.append("Wrote: " + ", ".join(applied)) + elif d["ok"]: + out.append("Nothing written. Re-run with --apply to write the children" + + ("" if d["epic_exists"] else " and the epics.md entry") + + ".") + else: + out.append("Nothing written. Re-cut the refused slices and re-run.") + return "\n".join(out) diff --git a/agents/conductors/batch/batch.sh b/agents/conductors/batch/batch.sh index 8158f80a..55b6b77b 100755 --- a/agents/conductors/batch/batch.sh +++ b/agents/conductors/batch/batch.sh @@ -25,6 +25,11 @@ # batch.sh collect --evidence ev.json --apply [--stamp ISO] # the form that writes # batch.sh collect --out report.md --json # +# batch.sh slice <prompt> # propose 2-4 witnessed children of a +# # needs-slicing prompt; writes nothing +# batch.sh slice <prompt> --slices plan.md # slices from a plan file instead +# batch.sh slice <prompt> --apply # write children + epics.md entry +# # collect reads and prints; only --apply writes (the packet page and the # record's stamps). Exit: 0 all delivered, 1 a member needs the human, # 2 usage, 4 no Mind. diff --git a/agents/conductors/docs/AGENTS.md b/agents/conductors/docs/AGENTS.md new file mode 100644 index 00000000..c87ea559 --- /dev/null +++ b/agents/conductors/docs/AGENTS.md @@ -0,0 +1,110 @@ +# Documentation agent + +> **Tier: conductor** — a front-door agent you *drive*. It owns +> [`skills/WRITING_STYLE.md`](../../../skills/WRITING_STYLE.md): it reasons over +> a documentation request and emits a `DocsDecision` the `start_dev` flow +> consumes, and it can score a page against the guide. It never edits a page +> and never writes a file. + +Grown from demonstrated need: on 2026-10-23 the human approved the human-first +rewrite of the `autolens_assistant` README and asked for the style to become +the go-to for GitHub READMEs and Read the Docs pages. The style shipped as +`WRITING_STYLE.md`; this agent gives it an owner. Founding prompt: PyAutoMind +`feature/pyautobrain/docs_conductor.md`. + +## Five surfaces + +| Surface | Examples | Guide | +|---------|----------|-------| +| `readme` | a repo's `README.md` | `WRITING_STYLE.md` | +| `setup` | `docs/setup/<tool>.md`, how-to pages | `WRITING_STYLE.md` | +| `rtd` | Read the Docs / Sphinx pages | `WRITING_STYLE.md` | +| `tutorial` | workspace scripts, notebooks, HowTo chapters | deferred to the Workspace conductor | +| `agent` | `AGENTS.md`, `skills/`, `wiki/core/` | agent conventions, not the style guide | + +Surface signals are checked in that precedence (agent, readme, setup, rtd, +tutorial), so "rewrite the HowToLens README" is a README job and "a HowToLens +chapter" is a tutorial. With no surface named, a workspace or HowTo target +implies `tutorial` and any other repo defaults to its README (with a note). + +## Modes + +Both modes are read-only. + +- **plan** (default) — `pyauto-brain docs "<raw text>"` or + `pyauto-brain docs <PyAutoMind prompt path>` emits the `DocsDecision`: + surface, target repo (body map: `PyAutoMind/repos.yaml`, else a built-in + table), the page, whether `WRITING_STYLE.md` applies, the **page template** + parsed from the guide (README and setup templates; rule 9's journey order for + Read the Docs, which has no template of its own), where long material should + move, the **siblings to keep in step** (the four assistant READMEs + `autolens/autofit/autogalaxy/autocti_assistant`, the workspace READMEs, the + HowTo READMEs, the library READMEs), the guide's checklist, and routing. +- **audit** — `pyauto-brain docs audit <page> [--kind readme|setup|rtd]` + scores one Markdown page against the guide and lists concrete fixes with + line numbers. Agent-facing files and tutorial scripts are reported as not + scored. + +`--json` gives the machine-readable decision or audit. + +## Tutorial prose is deferred, not duplicated + +Science narrative in workspace and HowTo scripts belongs to the Workspace +conductor's `workspace`/`howto` registers. A `tutorial` decision names that +conductor, a register hint and the exact `pyauto-brain workspace "..."` +command, and points at `TUTORIAL_WRITING_STYLE.md`; the WorkspaceDecision is +authoritative for repo, register, placement and sibling. A *mixed* request +(a README with a walkthrough) keeps the people-facing surface and notes that +both guides apply in their sections. + +## Audit checks + +The guide is the single source: the README/setup templates, the jargon list +(rule 3) and the checklist are parsed from it at run time. Each check is +labelled honestly: + +- **mechanical** — title is an H1; image near the top; Getting Started + present; License last; setup-page sections present; the guide's jargon words + in reader-visible prose (code, inline code, comments, link targets and + `<details>` excluded); at most one exclamation mark; headings at most six + words with no brackets or colons; local links and same-page anchors resolve. +- **heuristic** — intro of one to four sentences before the first section; + first code block within 60 lines ("a screen"); hedging phrases; prices or + tiers restated; paragraphs over 110 words; sentences over 35 words; two or + more dashes or brackets in one sentence; the reader addressed as "you"; + agent-directed text outside a collapsed block at the bottom. +- **not checked** (listed in every report) — rule 1 (what the reader does, + not how it works), rule 6 (examples re-explained), full journey order, and + links from *other* pages into renamed sections. External links are not + fetched (the agent is offline). + +The score is the share of checks that pass; treat heuristic failures as +prompts for judgment. + +## Consult graph + +Like every conductor it consults faculties, never other conductors: it names +the Workspace conductor's command for tutorial work rather than calling it, +and may consult the **memory faculty** for prior decisions about a page. + +## Boundary + +- **Decides, audits and routes; never authors.** Writing happens in the dev + flow the decision points into (`start_dev`, work type `docs/`). +- **Never writes files, never mutates a repo.** The audit reads one page. +- Generated blocks (the AGENTS.md command surface, adapters) are regenerated + by their generators, never hand-edited; the decision says so for the + `agent` surface. + +## Running + +``` +bin/pyauto-brain docs "rewrite the autolens assistant README in the new style" +bin/pyauto-brain docs "new setup page for Codex in autofit_assistant" +bin/pyauto-brain docs "Read the Docs page on PyAutoFit samplers" --json +bin/pyauto-brain docs draft/docs/<target>/<prompt>.md +bin/pyauto-brain docs audit ../autolens_assistant/README.md +``` + +Repos resolve under `PYAUTO_ROOT`. Exit codes: 0 decision or audit · +4 inputs unresolvable · 5 bad usage. diff --git a/agents/conductors/docs/_docs.py b/agents/conductors/docs/_docs.py new file mode 100644 index 00000000..381a01e4 --- /dev/null +++ b/agents/conductors/docs/_docs.py @@ -0,0 +1,810 @@ +#!/usr/bin/env python3 +"""agents/conductors/docs/_docs.py — core for the Documentation Agent. + +DECISION + READ-ONLY AUDIT. It reads intent (raw text or a PyAutoMind prompt +file) and emits a DocsDecision, or reads one page and scores it against +skills/WRITING_STYLE.md. It never edits a page and never writes a file: +authoring runs through start_dev, like every other docs task. + +Five surfaces, two families: + + people-facing readme · setup · rtd -> skills/WRITING_STYLE.md applies + tutorial tutorial -> deferred to the Workspace conductor + (its workspace/howto registers own + the science prose) + agent-facing agent -> WRITING_STYLE.md does not apply + +The style guide is the single source: the README/setup templates, the jargon +list, the journey order and the checklist are parsed out of WRITING_STYLE.md +at run time, never restated here. + +Stdlib-only. Exit codes: 0 decision/audit · 4 inputs unresolvable · 5 bad usage. +""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +import _pyauto_root # noqa: E402 +from _repo_paths import repo_path # noqa: E402 + +PYAUTO_ROOT = _pyauto_root.pyauto_root() +BRAIN_HOME = Path(__file__).resolve().parents[3] +STYLE_GUIDE = BRAIN_HOME / "skills" / "WRITING_STYLE.md" +TUTORIAL_GUIDE = BRAIN_HOME / "skills" / "TUTORIAL_WRITING_STYLE.md" +STYLE_REL = "PyAutoBrain/skills/WRITING_STYLE.md" +TUTORIAL_REL = "PyAutoBrain/skills/TUTORIAL_WRITING_STYLE.md" + +PEOPLE_FACING = ("readme", "setup", "rtd") +SURFACE_LABELS = { + "readme": "GitHub README", + "setup": "setup / how-to page", + "rtd": "Read the Docs page", + "tutorial": "tutorial narrative", + "agent": "agent-facing file", +} + +# Surface signals, checked in this precedence order: an explicit agent file or +# README beats a generic "tutorial" word ("rewrite the <howto repo> README" is +# a README job; "a <howto repo> chapter" is a tutorial). +SURFACE_SIGNALS = ( + ("agent", ("agents.md", "claude.md", "skill.md", "skills/", "wiki/core", + "agent-facing", "agent facing", "agent instructions", + "agent-only", "command body")), + ("readme", ("readme", "front page", "landing page", "repo homepage")), + ("setup", ("setup page", "set-up page", "docs/setup", "install page", + "installation page", "how-to page", "howto page", + "getting started page", "setup guide", "install guide")), + ("rtd", ("read the docs", "readthedocs", "rtd", "sphinx", ".rst", + "docs site", "documentation site", "api docs", "api reference", + "docs page")), + ("tutorial", ("tutorial", "notebook", "chapter", "worked example", + "example script", "guided tour", "lesson", "docstring", + "howto", "how to lens", "walkthrough")), +) + +HOWTO_HINT_WORDS = ("howto", "chapter", "beginner", "undergrad", "first-time", + "first time", "lesson", "course", "learner") + +# Categories whose people-facing pages are kept in step: a structural change +# to one README (sections, order, template) is mirrored across the category. +# Membership is read from the body map (PyAutoMind/repos.yaml), never listed +# here — naming instance repos in organ code is what the tenant firewall +# catches. +STEP_CATEGORIES = ("assistant", "workspace", "howto", "library") + + +def fail(code, msg): + print(f"docs: {msg}", file=sys.stderr) + sys.exit(code) + + +# ------------------------------------------------------------ the guide ---- + + +def guide_text(): + try: + return STYLE_GUIDE.read_text(encoding="utf-8") + except OSError: + return "" + + +def guide_section(text, heading): + m = re.search(rf"^## {re.escape(heading)}\s*$(.*?)(?=^## |\Z)", text, re.M | re.S) + return m.group(1).strip() if m else "" + + +def _unwrap(s): + return re.sub(r"\s+", " ", s).strip() + + +def guide_templates(text): + """{"readme": [...], "setup": [...]} parsed from '## Page templates'.""" + sec = guide_section(text, "Page templates") + out = {} + m = re.search(r"\*\*A README\*\* should have:(.*?)(?:\n\n|\Z)", sec, re.S) + if m: + body = _unwrap(m.group(1)) + parts = re.split(r",\s*(?:then\s+)?|\.\s+|\bthen\b", body) + out["readme"] = [re.sub(r"^and\s+", "", p.strip(" .")) for p in parts + if p.strip(" .")] + m = re.search(r"\*\*A setup page\*\*.*?:\s*\n(.*?)(?:\n\n[^-]|\Z)", sec, re.S) + if m: + out["setup"] = [_unwrap(b).rstrip(";.").replace("**", "") for b in + re.findall(r"^- (.+?)(?=^- |\Z)", m.group(1), re.M | re.S)] + return out + + +def guide_rules(text): + """{number: (bold lead, full text)} from '## The rules'.""" + sec = guide_section(text, "The rules") + rules = {} + for m in re.finditer(r"^(\d+)\. \*\*(.+?)\*\*(.*?)(?=^\d+\. |\Z)", sec, re.M | re.S): + rules[int(m.group(1))] = (m.group(2).strip(), _unwrap(m.group(2) + m.group(3))) + return rules + + +def guide_journey(text): + rule = guide_rules(text).get(9) + if not rule: + return [] + m = re.search(r"journey\.\*?\*?\s*(.+)$", rule[1]) + tail = m.group(1) if m else "" + return [p.strip(" .") for p in tail.split(",") if p.strip(" .")] + + +def guide_jargon(text): + rule = guide_rules(text).get(3) + m = re.search(r"jargon such as (.+?) in people-facing", rule[1]) if rule else None + if not m: + return ["harness", "adapter", "leg", "gate", "card", "organ", "conductor"] + return [w.strip() for w in re.split(r",| or ", m.group(1)) if w.strip()] + + +def guide_checklist(text): + sec = guide_section(text, "Checklist before you finish") + return [_unwrap(b) for b in re.findall(r"^- (.+?)(?=^- |\Z)", sec, re.M | re.S)] + + +# ------------------------------------------------------------- decision ---- + + +def read_intent(arg): + for base in (Path(arg), repo_path(PYAUTO_ROOT, "PyAutoMind") / arg): + if base.is_file(): + return base.read_text(encoding="utf-8"), str(base) + return arg, None + + +def known_repos(): + """name -> category from the body map; empty when it is not on disk.""" + repos = {} + manifest = repo_path(PYAUTO_ROOT, "PyAutoMind") / "repos.yaml" + try: + text = manifest.read_text(encoding="utf-8") + except OSError: + return repos + for m in re.finditer(r"^ ([A-Za-z][\w.-]*):\s*\n(?: .*\n)*? category:\s*(\w+)", + text, re.M): + repos[m.group(1)] = m.group(2) + return repos + + +def step_groups(repos): + return {c: [r for r, cat in repos.items() if cat == c] for c in STEP_CATEGORIES} + + +def family_libraries(repos): + """Bare family word -> library repo ('PyAutoThing' -> 'autothing'), derived + from the body map's library entries.""" + out = {} + for r, cat in repos.items(): + if cat == "library": + m = re.match(r"(?i)py(auto\w+)$", r) + if m: + out[m.group(1).lower()] = r + return out + + +def _norm(s): + return re.sub(r"[\s\-]+", "_", s.lower()) + + +def detect_surface(text): + low = text.lower() + hits = [s for s, words in SURFACE_SIGNALS + if any(re.search(rf"(?<![a-z]){re.escape(w)}(?![a-z])", low) for w in words)] + return hits + + +def detect_repo(text, repos): + """Longest explicit repo mention wins (spaces/hyphens treated as _).""" + low = _norm(text) + found = [r for r in repos + if re.search(rf"(?<![a-z0-9]){re.escape(r.lower())}(?![a-z0-9])", low)] + if found: + return max(found, key=len), "explicit" + for fam, lib in family_libraries(repos).items(): + if re.search(rf"\b{fam}\b", low): + return lib, f"family word '{fam}'" + return None, None + + +def page_for(surface, target, text): + m = re.search(r"([\w./-]+\.(?:md|rst|py|ipynb))\b", text) + if m: + return m.group(1) + return { + "readme": "README.md", + "setup": "docs/setup/<tool>.md", + "rtd": "docs/<page>.rst (or .md)", + "agent": "AGENTS.md / skills/<name>/... (as named)", + "tutorial": "scripts/<package>/<example>.py", + }[surface] + + +def move_targets(surface, category): + if surface == "readme": + out = ["advanced examples, benchmarks and history -> their own pages " + "under docs/, linked by one-line bullets (rule 7)", + "install mechanics -> a setup page per tool, docs/setup/<tool>.md " + "(rule 1)"] + if category == "assistant": + out.append("prices, free tiers and supported agents -> link " + "the one shared AI-options page WRITING_STYLE.md rule 5 " + "names, never restate (rule 5)") + out.append("agent-only instructions -> a short collapsed <details> " + "block at the bottom (rule 10)") + return out + if surface == "setup": + return ["anything that changes (prices, tiers, support status) -> the " + "one shared page it lives on (rule 5)", + "deep troubleshooting -> its own page, linked from Next steps"] + if surface == "rtd": + return ["long reference material -> its own page in the toctree, " + "linked by a short bullet that says what it shows (rule 7)", + "agent-only notes -> AGENTS.md or a collapsed block (rule 10)"] + return [] + + +def build_decision(args): + text, prompt_path = read_intent(args.intent) + repos = known_repos() + surfaces = detect_surface(text) + target, how = detect_repo(text, repos) + category = repos.get(target) if target else None + notes = [] + + if surfaces: + surface = surfaces[0] + elif category in ("workspace", "howto"): + surface = "tutorial" + notes.append("no surface named — inferred 'tutorial' from the target " + f"repo's category ({category})") + elif target: + surface = "readme" + notes.append("no surface named — defaulted to the repo README; say " + "'setup page' or 'Read the Docs' if that is the page") + else: + fail(4, "cannot resolve a surface or a target repo from the intent — " + "name the page (README, setup page, Read the Docs, tutorial, " + "AGENTS.md) and the repo") + if target is None: + fail(4, f"surface '{surface}' resolved but no target repo — name the " + "repo by its name in PyAutoMind/repos.yaml") + if how and how.startswith("family word") and surface in ("readme", "setup"): + notes.append(f"resolved {how} to the library {target}; name the " + "*_assistant or *_workspace repo explicitly if you meant " + "that page") + mixed = surface in PEOPLE_FACING and "tutorial" in surfaces[1:] + if mixed: + notes.append("mixed document: WRITING_STYLE.md for the project " + "sections, TUTORIAL_WRITING_STYLE.md for the walkthrough " + "(skills/docs/docs.md)") + + gtext = guide_text() + templates = guide_templates(gtext) + applies = surface in PEOPLE_FACING + if surface == "readme": + template = templates.get("readme", []) + elif surface == "setup": + template = templates.get("setup", []) + elif surface == "rtd": + template = guide_journey(gtext) + notes.append("the guide has no Read the Docs template — the rule 9 " + "journey order is the page skeleton") + else: + template = [] + + siblings = [] + group = step_groups(repos).get(category or "") + if group and target in group and surface in ("readme", "setup"): + siblings = [r for r in group if r != target] + if category == "assistant" and surface == "readme": + notes.append("README.md is domain content in the clone partition — " + "`clone sync` will not carry it; mirror structural " + "changes to the sibling READMEs by hand") + + deferred = None + if surface == "tutorial": + low = text.lower() + register = ("howto" if category == "howto" + or any(w in low for w in HOWTO_HINT_WORDS) else "workspace") + deferred = { + "conductor": "workspace", + "register_hint": register, + "command": f'bin/pyauto-brain workspace "{text.strip().splitlines()[0][:80]}"', + "why": "tutorial science prose belongs to the Workspace conductor's " + "workspace/howto registers; its WorkspaceDecision is " + "authoritative for repo, register, placement and sibling", + } + + if applies: + style = STYLE_REL + (f" + {TUTORIAL_REL}" if mixed else "") + checklist = guide_checklist(gtext) + nxt = ("route into start_dev (work type docs/) → author against the " + "template → `pyauto-brain docs audit <page>` before review; " + "this decision writes nothing") + elif surface == "tutorial": + style = TUTORIAL_REL + checklist = [] + nxt = ("run the Workspace conductor (command above) → start_dev → " + "start_workspace → ship_workspace; this decision writes nothing") + else: + style = None + checklist = [ + "WRITING_STYLE.md does not apply — agent-facing files follow their " + "own conventions (see the guide's preamble)", + "keep primary skill files within budget: " + "bin/check_skill_line_counts.sh", + "registry-generated blocks (AGENTS.md command surface) are " + "regenerated with bin/install.sh --write-agents-surface, never " + "hand-edited", + ] + nxt = ("route into start_dev (work type docs/); this decision writes " + "nothing") + + title = text.strip().splitlines()[0].lstrip("# ").strip()[:88] + return { + "title": title, + "prompt_path": prompt_path, + "surface": surface, + "surface_label": SURFACE_LABELS[surface], + "target_repo": target, + "repo_category": category, + "page": page_for(surface, target, text), + "writing_style_applies": applies, + "style_guide": style, + "page_template": template, + "move_long_material_to": move_targets(surface, category), + "siblings_in_step": siblings, + "deferred_to": deferred, + "checklist": checklist, + "audit_command": (f"bin/pyauto-brain docs audit {target}/<page>" + if applies else None), + "notes": notes, + "next_action": nxt, + } + + +def print_decision(d): + print("== DocsDecision (decision only, writes nothing) ==") + print(f"Intent: {d['title']}") + if d["prompt_path"]: + print(f"Prompt file: {d['prompt_path']}") + print(f"Surface: {d['surface']} ({d['surface_label']})") + print(f"Target repo: {d['target_repo']}" + + (f" [{d['repo_category']}]" if d["repo_category"] else "")) + print(f"Page: {d['page']}") + print(f"WRITING_STYLE.md: {'applies' if d['writing_style_applies'] else 'does not apply'}") + print(f"Style guide: {d['style_guide'] or '(agent conventions)'}") + if d["page_template"]: + print("Page template (from the style guide):") + for i, s in enumerate(d["page_template"], 1): + print(f" {i}. {s}") + if d["move_long_material_to"]: + print("Move long material to:") + for s in d["move_long_material_to"]: + print(f" - {s}") + if d["siblings_in_step"]: + print(f"Siblings in step: {', '.join(d['siblings_in_step'])}") + if d["deferred_to"]: + df = d["deferred_to"] + print(f"Deferred to: {df['conductor']} conductor " + f"(register hint: {df['register_hint']})") + print(f" run: {df['command']}") + print(f" why: {df['why']}") + if d["checklist"]: + print("Checklist:") + for s in d["checklist"]: + print(f" - {s}") + if d["audit_command"]: + print(f"Audit: {d['audit_command']}") + for n in d["notes"]: + print(f"Note: {n}") + print(f"Next action: {d['next_action']}") + + +# ---------------------------------------------------------------- audit ---- + +SCREEN_LINES = 60 # "within a screen of scrolling" +DENSE_WORDS = 110 # a paragraph this long wants a list (rule 8) +LONG_SENTENCE_WORDS = 35 # rule 11 "keep sentences short" +HEADING_WORDS = 6 # rule 12 "plain headings" +HEDGES = ("rather than assuming", "treat it as", "rather than tested", + "check the provider", "it is worth noting", "please note", + "note that", "be aware", "may or may not", "as far as we know", + "should generally", "in most cases") +# Phrases that address an AI agent directly (a link to AGENTS.md, or "agents" +# as a topic word, is not agent-only text). +AGENT_MARKERS = re.compile(r"\b(notes? (for|to) (ai )?agents|for ai agents|" + r"agent instructions|instructions for (ai )?agents|" + r"if you are an? (ai|agent|llm)|ai agents?:|agents:)", re.I) +PRICE = re.compile(r"(?:[$£€]\s?\d|\b\d+\s?(?:usd|gbp)\b|\bper month\b|/month\b|" + r"\bfree tier\b)", re.I) +AGENT_FILES = ("AGENTS.md", "CLAUDE.md", "SKILL.md") + + +def strip_regions(lines): + """Per line: (kind, text) — kind in code/comment/details/prose, with + inline code and link targets removed from prose so jargon checks only see + words a reader reads.""" + out, fence, comment, details = [], False, False, 0 + for raw in lines: + s = raw.strip() + if s.startswith(("```", "~~~")): + fence = not fence + out.append(("code", "")) + continue + if fence: + out.append(("code", "")) + continue + if comment or s.startswith("<!--"): + comment = "-->" not in s + out.append(("comment", "")) + continue + if re.search(r"<details\b", s, re.I): + details += 1 + kind = "details" if details else "prose" + if re.search(r"</details>", s, re.I): + details = max(0, details - 1) + clean = re.sub(r"`[^`]*`", " ", raw) + clean = re.sub(r"\]\([^)]*\)", "]", clean) + clean = re.sub(r"<[^>]+>", " ", clean) + clean = re.sub(r"https?://\S+", " ", clean) + out.append((kind, clean)) + return out + + +def headings(lines, regions): + hs = [] + for i, (raw, (kind, _)) in enumerate(zip(lines, regions)): + if kind != "prose": + continue + m = re.match(r"^(#{1,6})\s+(.+?)\s*#*\s*$", raw) + if m: + hs.append({"line": i + 1, "level": len(m.group(1)), "text": m.group(2)}) + m = re.search(r"<h([1-6])[^>]*>(.*?)</h\1>", raw, re.I) + if m: + hs.append({"line": i + 1, "level": int(m.group(1)), + "text": re.sub(r"<[^>]+>", "", m.group(2))}) + return hs + + +def slug(text): + t = re.sub(r"[^\w\- ]", "", text.lower()).strip() + return re.sub(r" ", "-", t) + + +def paragraphs(regions): + """Prose paragraphs as (first line no, text), lists and headings excluded.""" + paras, buf, start = [], [], None + for i, (kind, text) in enumerate(regions): + s = text.strip() + is_block = (kind != "prose" or not s or s.startswith(("#", "-", "*", "|", ">")) + or re.match(r"^\d+\.", s)) + if is_block: + if buf: + paras.append((start, " ".join(buf))) + buf, start = [], None + continue + if start is None: + start = i + 1 + buf.append(s) + if buf: + paras.append((start, " ".join(buf))) + return paras + + +def sentences(text): + return [s for s in re.split(r"(?<=[.!?])\s+(?=[A-Z\"'(*])", text) if s.strip()] + + +def detect_page_kind(path): + name = path.name + if name in AGENT_FILES or "skills" in path.parts or ( + "wiki" in path.parts and "core" in path.parts): + return "agent" + if name.lower().startswith("readme"): + return "readme" + if "setup" in path.parts: + return "setup" + if path.suffix in (".py", ".ipynb"): + return "tutorial" + return "rtd" + + +def check(cid, rule, kind, ok, finding, fixes): + return {"id": cid, "rule": rule, "kind": kind, + "status": "pass" if ok else "fix", "finding": finding, + "fixes": [] if ok else fixes} + + +def audit_page(path, page_kind): + lines = path.read_text(encoding="utf-8").splitlines() + regions = strip_regions(lines) + hs = headings(lines, regions) + gtext = guide_text() + paras = paragraphs(regions) + prose_lines = [(i + 1, t) for i, (k, t) in enumerate(regions) if k == "prose"] + results = [] + + # 1. Title (README template) — mechanical. + first_h = hs[0] if hs else None + results.append(check( + "title", "README template", "mechanical", + bool(first_h and first_h["level"] == 1), + f"first heading: {first_h['text']!r} (h{first_h['level']}, line {first_h['line']})" + if first_h else "no heading at all", + ["start the page with one `# Title` heading"])) + + h2 = [h for h in hs if h["level"] == 2] + if page_kind == "readme": + # 2. Image near the top — mechanical. + top = "\n".join(lines[:20]) + has_img = bool(re.search(r"!\[|<img\b", top, re.I)) + results.append(check( + "image", "README template", "mechanical", has_img, + "image in the first 20 lines" if has_img else "no image in the first 20 lines", + ["add the project logo or a figure under the title"])) + # 3. Sections the template names — mechanical (heading text match). + names = [h["text"].lower() for h in h2] + gs = any("getting started" in n or "get started" in n or "install and start" in n + for n in names) + lic = [h for h in h2 if "licen" in h["text"].lower()] + results.append(check( + "getting_started", "README template / rule 2", "mechanical", gs, + "a Getting Started section is present" if gs else + "no 'Getting Started' (or 'Install and start') section", + ["add a short `## Getting Started` right after the introduction — a " + "paragraph or two that gets the reader to the first prompt or command"])) + lic_last = bool(lic) and h2[-1] in lic + results.append(check( + "license_last", "README template / rule 9", "mechanical", lic_last, + "License is the last section" if lic_last else + ("no License section" if not lic else + f"License is not last (last section: {h2[-1]['text']!r})"), + ["end the page with `## License` (only a collapsed agent note may follow)"])) + if page_kind == "setup": + want = [t for t in ("What it costs", "Install and start", "Next steps")] + names = [h["text"].lower() for h in hs] + missing = [w for w in want if not any(w.lower() in n for n in names)] + results.append(check( + "setup_sections", "setup-page template", "mechanical", not missing, + "all template sections present" if not missing else + f"missing: {', '.join(missing)}", + [f"add a `## {w}` section" for w in missing])) + + # 4. Intro: 2-3 sentences before the first H2 — heuristic sentence split. + first_h2_line = h2[0]["line"] if h2 else len(lines) + 1 + intro = [p for ln, p in paras if ln < first_h2_line] + n_sent = sum(len(sentences(p)) for p in intro) + results.append(check( + "intro_length", "README template / rule 2", "heuristic", 1 <= n_sent <= 4, + f"{n_sent} sentence(s) before the first section", + ["cut the opening to two or three sentences on what the project is and " + "who it is for; move the rest into a later section" if n_sent > 4 else + "add two or three sentences under the title on what this is"])) + + # 5. First command/prompt within a screen — heuristic (fixed 60-line screen). + first_code = next((i + 1 for i, (k, _) in enumerate(regions) if k == "code"), None) + reachable = first_code is not None and first_code <= SCREEN_LINES + results.append(check( + "first_command", "checklist 1 / rule 2", "heuristic", + reachable or page_kind == "rtd", + f"first code block at line {first_code}" if first_code else + "no code block or prompt on the page", + [f"bring the first prompt or command into the first {SCREEN_LINES} lines " + "— move explanation below it"])) + + # 6. Internal jargon in reader-visible prose — mechanical word match. + jargon = guide_jargon(gtext) + jhits = [] + for ln, t in prose_lines: + for w in jargon: + if re.search(rf"\b{re.escape(w)}s?\b", t, re.I): + jhits.append((ln, w)) + results.append(check( + "jargon", "rule 3 / checklist 2", "mechanical", not jhits, + f"{len(jhits)} hit(s) of the guide's jargon list ({', '.join(jargon)})", + [f"line {ln}: replace '{w}' with a plain word, or explain it" for ln, w in jhits[:12]] + + ([f"... and {len(jhits) - 12} more"] if len(jhits) > 12 else []))) + + # 7. Hedging phrases — heuristic phrase list. + hhits = [(ln, h) for ln, t in prose_lines for h in HEDGES if h in t.lower()] + results.append(check( + "hedging", "rule 4", "heuristic", not hhits, + f"{len(hhits)} hedging phrase(s)", + [f"line {ln}: drop the caveat '{h}' — say the useful thing plainly and link " + "the detail" for ln, h in hhits[:8]])) + + # 8. Changeable facts restated — heuristic price/tier pattern. + phits = [ln for ln, t in prose_lines if PRICE.search(t)] + results.append(check( + "changeable_facts", "rule 5 / checklist 3", "heuristic", not phits, + f"{len(phits)} line(s) state a price or tier" if phits else "no prices or tiers stated", + [f"line {ln}: link the one shared page (WRITING_STYLE.md rule 5) " + "instead of restating the price/tier" for ln in phits[:8]])) + + # 9. Dense paragraphs — heuristic word count. + dense = [(ln, len(p.split())) for ln, p in paras if len(p.split()) > DENSE_WORDS] + results.append(check( + "dense_paragraphs", "rule 8", "heuristic", not dense, + f"{len(dense)} paragraph(s) over {DENSE_WORDS} words", + [f"line {ln}: {n} words — break into a one-line intro and a bulleted list " + "with bold lead words" for ln, n in dense])) + + # 10. Long sentences — heuristic sentence split. + long_s = [(ln, len(s.split())) for ln, p in paras for s in sentences(p) + if len(s.split()) > LONG_SENTENCE_WORDS] + results.append(check( + "long_sentences", "rule 11", "heuristic", not long_s, + f"{len(long_s)} sentence(s) over {LONG_SENTENCE_WORDS} words", + [f"paragraph at line {ln}: a {n}-word sentence — split it" for ln, n in long_s[:8]])) + + # 11. Dash/bracket chains — heuristic: >=2 em dashes or >=2 brackets in one sentence. + chains = [ln for ln, p in paras for s in sentences(p) + if s.count("—") + s.count(" -- ") >= 2 or s.count("(") >= 2] + results.append(check( + "dash_chains", "rule 11", "heuristic", not chains, + f"{len(chains)} sentence(s) chain dashes or brackets", + [f"paragraph at line {ln}: rewrite the dashed/bracketed aside as its own " + "sentence" for ln in chains[:8]])) + + # 12. Exclamation marks — mechanical count in prose. + bangs = sum(len(re.findall(r"!(?=\s|$)", t)) for _, t in prose_lines) + results.append(check( + "exclamations", "rule 11", "mechanical", bangs <= 1, + f"{bangs} exclamation mark(s)", + ["keep at most one exclamation mark on the page"])) + + # 13. Addresses the reader — heuristic. + you = sum(len(re.findall(r"\byou(r|'re|'ll|'ve)?\b", t, re.I)) for _, t in prose_lines) + results.append(check( + "address_reader", "rule 11", "heuristic", you > 0, + f"'you' appears {you} time(s)", + ["address the reader as 'you' — say what they do"])) + + # 14. Plain headings — mechanical length/punctuation. + bad_h = [h for h in hs if len(h["text"].split()) > HEADING_WORDS + or re.search(r"[():]", h["text"])] + results.append(check( + "plain_headings", "rule 12", "mechanical", not bad_h, + f"{len(bad_h)} heading(s) over {HEADING_WORDS} words or with brackets/colons", + [f"line {h['line']}: shorten {h['text']!r}" for h in bad_h])) + + # 15. Agent-only text collapsed at the bottom — heuristic detection. + loose = [ln for ln, t in prose_lines if AGENT_MARKERS.search(t)] + det = [i + 1 for i, (k, _) in enumerate(regions) if k == "details"] + last_h2 = h2[-1]["line"] if h2 else 0 + det_high = bool(det) and det[0] < last_h2 + results.append(check( + "agent_text", "rule 10 / checklist 5", "heuristic", not loose and not det_high, + (f"{len(loose)} uncollapsed agent-directed line(s)" if loose else + "no uncollapsed agent-directed text") + ("; a <details> block sits above the last section" + if det_high else ""), + [f"line {ln}: move agent instructions into a short collapsed <details> block " + "at the very bottom" for ln in loose[:6]] + + (["move the <details> agent block below the last section"] if det_high else []))) + + # 16. Local links and anchors resolve — mechanical (offline: external links unchecked). + anchors = {slug(h["text"]) for h in hs} + broken, external = [], 0 + for i, raw in enumerate(lines): + if regions[i][0] in ("code", "comment"): + continue + for target in re.findall(r"\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)", raw) + \ + re.findall(r"(?:href|src)=\"([^\"]+)\"", raw): + if re.match(r"^[a-z]+:", target): + external += 1 + continue + file_part, _, anchor = target.partition("#") + if not file_part: + if anchor and anchor.lower() not in anchors: + broken.append((i + 1, target)) + continue + if not (path.parent / file_part).exists(): + broken.append((i + 1, target)) + results.append(check( + "links", "checklist 6", "mechanical", not broken, + f"{len(broken)} broken local link(s); {external} external link(s) not checked (offline)", + [f"line {ln}: '{t}' does not resolve" for ln, t in broken[:10]])) + + passed = sum(1 for r in results if r["status"] == "pass") + unchecked = [ + "rule 1 (says what the reader does, not how it works) — judgment", + "rule 6 (examples re-explained in the surrounding prose) — judgment", + "rule 9 (full journey order beyond Getting Started/License) — judgment", + "links from OTHER pages into sections renamed here — needs the repo's " + "other pages; grep them", + ] + return { + "page": str(path), + "page_kind": page_kind, + "style_guide": STYLE_REL, + "score": round(100 * passed / len(results)), + "passed": passed, + "total": len(results), + "checks": results, + "not_checked": unchecked, + } + + +def build_audit(args): + path = Path(args.page) + if not path.is_file(): + alt = Path(PYAUTO_ROOT) / args.page + if not alt.is_file(): + fail(4, f"no such page: {args.page}") + path = alt + kind = args.kind or detect_page_kind(path) + if kind in ("agent", "tutorial"): + return { + "page": str(path), "page_kind": kind, "style_guide": None, + "score": None, "passed": 0, "total": 0, "checks": [], + "not_checked": [], + "note": ("WRITING_STYLE.md does not apply to agent-facing files" + if kind == "agent" else + "tutorial prose follows TUTORIAL_WRITING_STYLE.md and the " + "Workspace conductor's format checklist; this audit scores " + "people-facing pages only"), + } + return audit_page(path, kind) + + +def print_audit(a): + print(f"== DocsAudit — {a['page']} ({a['page_kind']}) — read-only ==") + if a.get("note"): + print(f"Not scored: {a['note']}") + return + print(f"Against: {a['style_guide']}") + print(f"Score: {a['score']}/100 ({a['passed']}/{a['total']} checks pass)") + for r in a["checks"]: + mark = "ok " if r["status"] == "pass" else "FIX" + print(f" [{mark}] {r['id']:17s} {r['rule']:28s} ({r['kind']}) {r['finding']}") + fixes = [(r["id"], f) for r in a["checks"] for f in r["fixes"]] + if fixes: + print("Fixes:") + for cid, f in fixes: + print(f" - [{cid}] {f}") + print("Not checked (judgment — read the page):") + for s in a["not_checked"]: + print(f" - {s}") + + +# ----------------------------------------------------------------- main ---- + + +def main(): + argv = sys.argv[1:] + if argv and argv[0] == "audit": + parser = argparse.ArgumentParser(prog="docs audit") + parser.add_argument("page", help="the page to score (README.md, docs/...)") + parser.add_argument("--kind", choices=["readme", "setup", "rtd", "agent", "tutorial"], + default=None, help="override the page kind") + parser.add_argument("--json", action="store_true") + args = parser.parse_args(argv[1:]) + audit = build_audit(args) + print(json.dumps(audit, indent=2)) if args.json else print_audit(audit) + sys.exit(0) + + parser = argparse.ArgumentParser(prog="docs", description=__doc__) + parser.add_argument("intent", nargs="?", default=None, + help="raw intent text, or a PyAutoMind prompt path") + parser.add_argument("--json", action="store_true") + args = parser.parse_args(argv) + if not args.intent or not args.intent.strip(): + fail(5, "no intent given — pass raw text, a PyAutoMind prompt path, or " + "`audit <page>`") + decision = build_decision(args) + print(json.dumps(decision, indent=2)) if args.json else print_decision(decision) + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/agents/conductors/docs/docs.sh b/agents/conductors/docs/docs.sh new file mode 100755 index 00000000..cf07d590 --- /dev/null +++ b/agents/conductors/docs/docs.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# agents/conductors/docs/docs.sh — the Documentation Agent (a PyAutoBrain +# reasoning conductor). Owns skills/WRITING_STYLE.md: classifies a docs request +# by surface and emits a DocsDecision; audit mode scores one page against the +# style guide's checklist. Read-only — authoring runs through start_dev, and +# tutorial science prose is deferred to the Workspace conductor. +# +# Usage: +# docs.sh "<raw intent text>" # plan (default mode) +# docs.sh <PyAutoMind prompt path> # plan from a filed prompt +# docs.sh audit <page> [--kind K] # read-only style audit +# docs.sh --json ... # machine-readable output + +set -uo pipefail + +HERE="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)" +source "$HERE/../../_common.sh" + +exec python3 "$HERE/_docs.py" "$@" diff --git a/agents/conductors/intake/AGENTS.md b/agents/conductors/intake/AGENTS.md index 3cf96450..537ebbc1 100644 --- a/agents/conductors/intake/AGENTS.md +++ b/agents/conductors/intake/AGENTS.md @@ -84,6 +84,11 @@ becomes the series' tracker or is retired. Decomposition is planning judgment it stays with the strongest available model; the resulting phases are what the cheaper execution models run. +When a filed prompt sizes `Unattended: needs-slicing`, intake prints an +**offer** (never an act): author its `## Slices` and run +`pyauto-brain batch slice <prompt>`, which validates the cut against the seam +rules and, under `--apply`, writes the children (batch `AGENTS.md`). + ## The header — extend the blessed convention, never YAML Writes the light header PyAutoMind blesses (`README.md` "Prompt file format"), @@ -98,7 +103,11 @@ tasks, so intake consults it mechanically and the citations sit in front of the session that picks the prompt up. PyAutoMemory only — Mind history and the assistant are operational recall, not what the science says — and no hits (or no PyAutoMemory checkout) writes no line at all, because an empty `Memory:` -would claim nothing is known. +would claim nothing is known. A hit must clear a score floor on the query +terms it shares that are distinctive in PyAutoMemory (`MEMORY_FLOOR` in +`_intake.py`), so a page matching only generic vocabulary ("model", "profile", +"fit") is not cited; navigation pages (`index.md`, `log.md`, `reading-queue.md`, +...) never are. `Themes:` is written at formalisation, directly under `Repos:` and in the same list shape (`intake classify --themes mge,jax-gradient`, primary keyword @@ -118,6 +127,8 @@ with or without it. Unknown keywords are counted in the page's Hygiene section. | **dashboard** | `intake dashboard` | render the census as the Mind **task** page — picks, in flight, pending release, planned, backlog (including human review), recent, epics; `--apply` writes `PyAutoMind/dashboard.md` + `dashboard.html` + `state.json` (the organ-cockpit feed, `board/_state.py` v1: red when a task awaits input/is blocked or prompts drift, yellow when work waits on a merge/release/review or picks exist; items carry the page's own copy payloads), `--check` exits 1 on drift (ignoring the page date and the feed's `updated`) | | **formalise** | `intake formalise [prefix]` | retroactively header the prompts census flags — derive the missing fields, insert in place, prose untouched; `--apply` writes | | **reconcile** | `intake reconcile [prefix]` | rank backlog prompts that look already-shipped (vs the `complete/` records / `active/`), and pair live prompts that look like the same work filed twice; always read-only — retiring stays human | +| **looks-shipped** | `intake looks-shipped [prefix] [--root DIR] [--pr-cache F]` | the **close-out guard**: flag open drafts with *strong* evidence their work already shipped (see "Close-out guard" below); `--apply` writes `PyAutoMind/looks_shipped.json` only — never anything under `draft/` | +| **reconcile --strong** | `intake reconcile --strong [prefix]` | run the close-out guard's legs too and list them first, graded `looks-shipped` above every vocabulary band | | **reconcile --repo** | `intake reconcile --repo <target> [prefix]` | **also** read the target repo's source: identifiers the prompts name that exist upstream, and lines they quote that are **gone** — the two signals that see a prompt with no Mind-side trace. Opt-in; the default path is offline | **Recent** is the one section laid out by *date* rather than by state: the 50 @@ -242,6 +253,36 @@ prompts): **36 pairs → 2**. A pair is something to **read together**, never a verdict: two prompts can share files and still be different work. +## Close-out guard (`looks-shipped`) + +`reconcile` grades **vocabulary**; the 2026-11-05 sweep closed 27 shipped drafts +that it never ranked strongly, every one of which had bypassed `/prm` (fixed on +main with no issue, merged by a session that skipped the close-out, or re-filed +as a duplicate). `looks-shipped` (`_shipped.py`) flags only on facts someone can +re-check, each cited with its evidence line, a one-line close command and a +one-line dismissal: + +| Leg | Fires when | +|---|---| +| `witness-exists` | the draft's `Witness:` names a test/function now defined (`def`/`class`, or a `test_*.py` module) in a target checkout (folder target + `Repos:`), **and** git says it was added or edited after `Filed:` (pickaxe, then `git log -L`). Without readable history only a named `test_*` counts | +| `commit-names-draft` | a commit on a checkout's main since `Filed:` names the draft's path, filename or distinctive slug (3+ words, 15+ chars) on a line that claims shipping (`fix:`/`feat:`-style subject, a ship word, or the PR-merge branch line). Follow-up wording, ledger subjects (`prompt:`, `intake:` …), a message listing 3+ drafts, and Mind commits touching only the ledger never count | +| `pr-names-draft` | the same match over a merged-PR JSON cache (`--pr-cache`: `[{repo, number, merged_at, title, body}]`) — optional, offline; this session class has no GitHub API | +| `record-duplicates-draft` | a `complete/` record's `## Original prompt` matches an open draft by title (difflib ≥ 0.93, same numbers — a phase series is not a duplicate) or body (word-level ratio ≥ 0.80) | + +Checkouts are found under `--root` (default: the Mind's parent; flat or one +family deep) and absent ones are skipped silently. Measured 2026-11-05: on the +Mind as it stood **before** the sweep (295 drafts) it flagged 5, all genuinely +shipped (4 in the sweep's 27, the fifth closed the same day as PyAutoBrain#588) +with only Brain/Cortex/Memory/Mind checked out; on the post-sweep Mind it flags 0. + +Consumers read `active_flags` — the file minus `looks_shipped_dismissed.md` +bullets (`- draft/<…>.md — <date> — <why>`) and minus drafts already gone from +`draft/`: the dashboard's **Looks shipped — confirm** section and `state.json` +items, the Start-here pick lists (flagged drafts are left out), and `batch plan` +(rejects them). Confirm = close the draft; dismiss = add the bullet. Mind's +`looks_shipped.yml` runs it daily. A merge-time hook (warn on a PR whose +commits name a draft it does not retire) is a recorded follow-up. + ## Machine sources (one staging surface) Conception input increasingly arrives from the organism itself — research @@ -278,6 +319,8 @@ bin/pyauto-brain intake formalise # propose ret bin/pyauto-brain intake --apply formalise bug/ # write them, only under bug/ bin/pyauto-brain intake reconcile # rank shipped-but-stale suspects + duplicate pairs (read-only) bin/pyauto-brain intake reconcile --repo autolens_workspace_test # + upstream presence and quote-absence legs +bin/pyauto-brain intake looks-shipped --root ~/Code/PyAutoLabs # close-out guard: strong-evidence flags (read-only) +bin/pyauto-brain intake --apply looks-shipped # + write PyAutoMind/looks_shipped.json ``` **Writes only under `--apply`; dry-run is the default.** Exit codes: `0` produced diff --git a/agents/conductors/intake/_intake.py b/agents/conductors/intake/_intake.py index 2079fe5e..28871575 100755 --- a/agents/conductors/intake/_intake.py +++ b/agents/conductors/intake/_intake.py @@ -84,6 +84,11 @@ render_html as _status_box_html, render_md as _status_box_md, ) +# The close-out guard (strong-evidence `looks-shipped` flags): the detector and +# the one reader the dashboard and the batch planner share. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import _shipped # noqa: E402 + THEME_ORGAN = "mind" # whose logo this page wears # --- work-type classification ------------------------------------------------- @@ -635,6 +640,7 @@ def analyse(text: str, source: str, themes=None): estimated, witness=p["witness"], consequence=consequence), "next_action": _next_action(proposed, confidence, folder), + "slice_offer": slice_offer(proposed, unattended), } @@ -766,6 +772,21 @@ def _next_action(proposed, confidence, work_type=None): "afterwards `Use the start-dev skill. {}` routes it.".format(proposed)) +def slice_offer(path: str, unattended: str) -> str: + """The `batch slice` suggestion for a prompt that sizes `needs-slicing`. + + An offer, never an act: intake files prompts and stops. Slicing renders the + decomposition the prompt itself declares (`## Slices`), so the human — or + the agent that wrote the prompt — authors the cut first.""" + if unattended != "needs-slicing": + return "" + return ("This sizes as `Unattended: needs-slicing` — too large for one " + "unattended run. Add a `## Slices` section (2-4 numbered items, " + "each with its own `*Witness:*`), then " + f"`pyauto-brain batch slice {path}` proposes the children; it " + "writes nothing without `--apply`.") + + # --- apply (the only writing path) ------------------------------------------- # --- Memory citations --------------------------------------------------------- # The doctrine says every plan consults Memory. The record says it was consulted @@ -787,8 +808,33 @@ def _next_action(proposed, confidence, work_type=None): # organism's own machinery, so there is no science question to answer, and the # digest only ever matched on shared vocabulary ("profile", "model") — every # organ prompt filed got galaxy-wiki citations that had to be hand-removed. +# +# Nor does a page the prompt only shares vocabulary with. The digest's ranking +# is raw term counts, so a long page full of "model", "profile" and "fit" tops +# it for any prompt at all (a jax-compile tooling prompt was handed +# massive-ellipticals.md). A page is cited only when the query terms it shares +# that are DISTINCTIVE in PyAutoMemory — on at most MEMORY_DISTINCT_SHARE of its +# pages — carry enough weight: each scores log(N/df)/log(N) (1 for a term on a +# single page, ~0.6 at the share cut-off), and the page needs MEMORY_FLOOR, or +# MEMORY_FLOOR_PER_TERM per distinct query term when that is lower (a one-line +# idea cannot accumulate what a 200-word prompt does, and a long prompt's rare +# words hit dev-flavoured pages by chance). Calibrated on the 276 Mind drafts +# of 2026-11-05 against the live digest (158 pages): long EP prompts score +# 11.5-15 on expectation-propagation.md and jax-gradient bugs ~9.8 on +# autodiff-implicit-diff.md, while the jax-compile and numba-preset tooling +# prompts top out at 8.4 and 5.4 on any page; 67 of the 276 drafts clear the +# floor, against nearly all of them before it. A one-line EP idea (10 terms) +# scores 4.7 on the EP page against a 1.5 floor; a one-line jax-compile tooling +# idea (11 terms) scores 1.5 against 1.65. Navigation pages (index, log, +# AGENTS, README, reading-queue) are never cited: they list sources, they are +# not one. MEMORY_CITATIONS = 3 MEMORY_QUERY_WORDS = 200 +MEMORY_FLOOR = 9.0 +MEMORY_FLOOR_PER_TERM = 0.15 +MEMORY_DISTINCT_SHARE = 0.05 +MEMORY_NAV_PAGES = frozenset({"index.md", "log.md", "AGENTS.md", "README.md", + "reading-queue.md"}) def _memory_home(mind: Path) -> Path | None: @@ -804,17 +850,47 @@ def memory_citations(mind: Path, title: str, body_text: str, The query is the title plus the head of the body: a prompt's opening states the problem, while its tail is usually acceptance criteria and file paths - that match on vocabulary rather than subject. + that match on vocabulary rather than subject. Only pages that clear the + distinctive-term floor (see the block comment above) are returned, in the + faculty's ranking order; navigation pages never are. """ home = _memory_home(mind) if home is None: return [] query = " ".join(f"{title} {body_text}".split()[:MEMORY_QUERY_WORDS]) try: - d = _memory.digest(query, home, None, None, limit) + d = _memory.digest(query, home, None, None, 10 ** 6) + vocab = _memory_vocab(home) except (OSError, ValueError): return [] - return [page["page"] for page in d["pages"]][:limit] + n = len(vocab) + terms = {t for t in d["terms"] if not t.isdigit()} + df = {t: sum(t in words for words in vocab.values()) for t in terms} + scale = math.log(n) if n > 1 else 1.0 + rare = {t: (math.log(n / df[t]) / scale if n > 1 else 1.0) for t in terms + if 0 < df[t] <= max(1.0, n * MEMORY_DISTINCT_SHARE)} + floor = min(MEMORY_FLOOR, MEMORY_FLOOR_PER_TERM * len(terms)) + cites = [] + for page in d["pages"]: # the faculty's own order; the floor only filters + if Path(page["page"]).name in MEMORY_NAV_PAGES: + continue + words = vocab.get(page["page"], set()) + if rare and sum(w for t, w in rare.items() if t in words) >= floor: + cites.append(page["page"]) + if len(cites) >= limit: + break + return cites + + +def _memory_vocab(home: Path) -> dict: + """{repo-relative page: its whole-word vocabulary} over PyAutoMemory.""" + vocab = {} + for _name, base, f in _memory.surfaces(home, None, None): + if f.stat().st_size > _memory.MAX_FILE_BYTES: + continue + text = f.read_text(encoding="utf-8", errors="replace").lower() + vocab[str(f.relative_to(base))] = set(re.findall(r"[a-z0-9_]+", text)) + return vocab def _organs_dir_repos() -> frozenset: @@ -1546,6 +1622,9 @@ def _count(key): "hygiene": hygiene, "drift": drift, "batch": _batch_status(mind), + # Strong-evidence close-out flags (`intake looks-shipped`), minus what + # a human dismissed or already closed — the "Looks shipped" section. + "looks_shipped": _looks_shipped_rows(mind, records), } c["recent"] = recent_events(c) # Needs `in_flight` in place, so it is derived after the dict is built. @@ -1553,6 +1632,66 @@ def _count(key): return c +def _looks_shipped_rows(mind: Path, records: list) -> list: + """The live `looks-shipped` flags, each joined to its backlog record.""" + by_path = {r["path"]: r for r in records} + rows = [] + for f in _shipped.active_flags(mind): + r = by_path.get(f.get("path", "")) + if r is None: + continue + rows.append({"path": r["path"], "title": r["title"], + "target": r["target"], + "signals": [s for s in f.get("signals") or [] + if isinstance(s, dict)], + "close": f.get("close", ""), + "dismiss": f.get("dismiss", "")}) + return rows + + +LOOKS_SHIPPED_PAYLOAD = """\ +`{path}` looks already shipped — confirm or dismiss it. Work in the PyAutoMind checkout. + +Evidence (from `intake looks-shipped`): +{evidence} + +1. Check each cited line: open the commit / definition / record and confirm it + really is THIS draft's work, not a neighbour's. +2. If it shipped, close it (write the record body first; the command is a dry + run without --apply): + {close} +3. If it did not, dismiss the flag so the batch planner may pick it again: + {dismiss} +4. Regenerate the dashboard: `pyauto-brain intake --apply dashboard`. + +Report which you did and why.""" + + +def _looks_shipped_payload(f: dict) -> str: + ev = "\n".join(f"- {s.get('kind', '?')}: {s.get('evidence', '')}" + for s in f["signals"]) or "- (no evidence recorded)" + return LOOKS_SHIPPED_PAYLOAD.format(path=f["path"], evidence=ev, + close=f["close"], dismiss=f["dismiss"]) + + +def _looks_shipped_head(f: dict) -> str: + kinds = sorted({s.get("kind", "?") for s in f["signals"]}) + first = f["signals"][0].get("evidence", "") if f["signals"] else "" + head = (f"<a href=\"{f['path']}\">{_summary_label(f['title'])}</a>" + f" — {_summary_label(', '.join(kinds))}") + if first: + head += f" — {_summary_label(_clip(first))}" + return head + + +def _unflagged(c: dict, rows: list) -> list: + """Drop `looks-shipped` drafts from a pick list: offering work a human is + being asked to confirm as finished is how the 2026-11-05 batch proposed + two shipped tasks.""" + flagged = {f["path"] for f in c.get("looks_shipped") or []} + return [r for r in rows if r["path"] not in flagged] + + # `complete/` records carry `pending-release:` too — /prm copies the key over # from the active.md row at close-out, so the obligation outlives the row that # opened it. The ledger holds ~1300 records, so only the head of each file is @@ -2061,6 +2200,16 @@ def render_dashboard(c: dict) -> str: "prompt never advanced, so it still renders as backlog:", ""] L += [f"> - `{d}`" for d in c["drift"]] L += [""] + flags = c.get("looks_shipped") or [] + if flags: + L += ['<a id="looks-shipped"></a>', "## Looks shipped — confirm", "", + f"{len(flags)} draft(s) with strong evidence the work already " + "shipped (`intake looks-shipped`). Held out of the pick lists and " + "the batch planner until closed or dismissed in " + f"[`{_shipped.DISMISS_FILE}`]({_shipped.DISMISS_FILE}).", ""] + L += _items([_task_row(_looks_shipped_head(f), _looks_shipped_payload(f)) + for f in flags]) + L += [""] if c["batch"] is not None: L += [_status_box_md(c["batch"]), ""] L += ["## Start here", ""] @@ -2069,8 +2218,9 @@ def render_dashboard(c: dict) -> str: # they are worked in order through their epic below Start here. members = _epic_members(c) standalone = [r for r in records if not r.get("epic")] - high = [r for r in standalone if r["priority"] == "high"] - quick = _fits_a_slot(standalone) + pickable = _unflagged(c, standalone) + high = [r for r in pickable if r["priority"] == "high"] + quick = _fits_a_slot(pickable) for title, note, rows in ( ("Highest priority", "filed as `high`", high), ("Fits a slot", "ready to run unattended, cheapest to review first", @@ -2407,14 +2557,31 @@ def record_row(r): "whose body records a fix PR (done, never advanced):</p>", "<ul>"] H += [f"<li><code>{_attr(d)}</code></li>" for d in c["drift"]] H += ["</ul>"] + flags = c.get("looks_shipped") or [] + if flags: + H += ['<a id="looks-shipped"></a><h2>Looks shipped — confirm</h2>', + f'<p class="muted">{len(flags)} draft(s) with strong evidence the ' + "work already shipped. Held out of the pick lists and the batch " + "planner until closed or dismissed in " + f"<code>{_shipped.DISMISS_FILE}</code>.</p>"] + for f in flags: + kinds = ", ".join(sorted({s.get("kind", "?") for s in f["signals"]})) + text = link(f["path"], _summary_label(f["title"])) + text += f' — <span class="facets">{_summary_label(kinds)}</span>' + if f["signals"]: + text += (f'<br><span class="facets">' + f'{_summary_label(_clip(f["signals"][0].get("evidence", "")))}' + "</span>") + H.append(_html_task(text, _looks_shipped_payload(f))) if c["batch"] is not None: H.append(_status_box_html(c["batch"])) H += ['<a id="start-here"></a><h2>Start here</h2>'] members = _epic_members(c) standalone = [r for r in records if not r.get("epic")] - high = [r for r in standalone if r["priority"] == "high"] - quick = _fits_a_slot(standalone) + pickable = _unflagged(c, standalone) + high = [r for r in pickable if r["priority"] == "high"] + quick = _fits_a_slot(pickable) for title, note, rows in ( ("Highest priority", "filed as high", high), ("Fits a slot", "ready to run unattended, cheapest to review first", @@ -2627,7 +2794,7 @@ def _start_here_picks(c: dict) -> list: fits-a-slot — de-duplicated, epic members excluded, each list capped at PICK_LIST_MAX exactly as rendered.""" records = sorted(c["records"], key=_pick_key) - standalone = [r for r in records if not r.get("epic")] + standalone = _unflagged(c, [r for r in records if not r.get("epic")]) high = [r for r in standalone if r["priority"] == "high"][:PICK_LIST_MAX] quick = _fits_a_slot(standalone)[:PICK_LIST_MAX] out, seen = [], set() @@ -2646,7 +2813,8 @@ def _state_status(c: dict, picks: list) -> str: if c.get("drift") or any(k in s for s in statuses for k in _HUMAN_RED): return "red" if (any(k in s for s in statuses for k in _HUMAN_YELLOW) - or c.get("human_review") or c.get("pending_release") or picks): + or c.get("human_review") or c.get("pending_release") or picks + or c.get("looks_shipped")): return "yellow" return "green" @@ -2679,6 +2847,13 @@ def link(path): "url": prs[0]["url"] if prs else (r.get("issue") or None), # the row's own 📋 payload on the page "prompt": f"Use the start-dev skill. {r['path']}"}) + for f in c.get("looks_shipped") or []: + kinds = ", ".join(sorted({s.get("kind", "?") for s in f["signals"]})) + items.append({"severity": "yellow", + "text": _one(f"looks shipped — confirm: {f['title']} " + f"({kinds})"), + "url": link(f["path"]), + "prompt": _looks_shipped_payload(f)}) for r in c.get("human_review") or []: title = re.sub(r"^human review:\s*", "", r["title"], flags=re.I) items.append({"severity": "yellow", @@ -3908,6 +4083,8 @@ def emit_human(d: dict): for r in d["risks"]: print(f" - {r}") print(f"Next action: {d['next_action']}") + if d.get("slice_offer"): + print(f"Offer: {d['slice_offer']}") def main(argv=None): @@ -3956,9 +4133,47 @@ def main(argv=None): "no Mind-side trace). Opt-in: the default path makes no " "network access. Ranks for review; never says shipped.") + rc.add_argument("--strong", action="store_true", + help="ALSO run the close-out guard's strong-evidence legs " + "(see `looks-shipped`) and list them first, graded " + "`looks-shipped` above every vocabulary band") + rc.add_argument("--root", default="", + help="with --strong: the directory holding the organism " + "checkouts as siblings (default: the Mind's parent)") + rc.add_argument("--pr-cache", default="", + help="with --strong: a JSON list of merged PRs " + "({repo, number, merged_at, title, body}) to read") + + ls = sub.add_parser("looks-shipped", + help="the close-out guard: flag open drafts with " + "STRONG evidence they already shipped (witness " + "test now defined, a commit naming the draft, a " + "complete/ record duplicating it); --apply writes " + "looks_shipped.json — never anything under draft/") + ls.add_argument("prefix", nargs="?", default="", + help="only scan drafts under this path prefix") + ls.add_argument("--root", default="", + help="the directory holding the organism checkouts as " + "siblings (default: the Mind's parent); absent " + "checkouts are skipped") + ls.add_argument("--pr-cache", default="", + help="a JSON list of merged PRs ({repo, number, merged_at, " + "title, body}); optional, offline") + a = ap.parse_args(argv) mind = Path(a.mind) + if a.cmd == "looks-shipped": + root = Path(a.root) if a.root else mind.resolve().parent + res = _shipped.detect(mind, root, prefix=a.prefix, + pr_cache=Path(a.pr_cache) if a.pr_cache else None) + written = _shipped.write(mind, res) if a.apply else None + if a.as_json: + print(json.dumps({**res, "written": written}, indent=2)) + else: + _shipped.emit(res, written) + return 0 + if a.cmd == "formalise": res = formalise(mind, prefix=a.prefix, apply=a.apply) print(json.dumps(res, indent=2)) if a.as_json else emit_formalise(res) @@ -3978,7 +4193,23 @@ def main(argv=None): "when": _dt.date.today().isoformat()} res = reconcile(mind, prefix=a.prefix, source_reader=reader, upstream_meta=meta) - print(json.dumps(res, indent=2)) if a.as_json else emit_reconcile(res) + if a.strong: + root = Path(a.root) if a.root else mind.resolve().parent + strong = _shipped.detect( + mind, root, prefix=a.prefix, + pr_cache=Path(a.pr_cache) if a.pr_cache else None) + res["looks_shipped"] = strong + # A strong flag outranks every vocabulary band for the same prompt. + flagged = {f["path"] for f in strong["flags"]} + res["suspects"] = [s for s in res["suspects"] + if s["path"] not in flagged] + if a.as_json: + print(json.dumps(res, indent=2)) + else: + if a.strong: + _shipped.emit(res["looks_shipped"]) + print() + emit_reconcile(res) return 0 if a.cmd == "census": @@ -4048,6 +4279,8 @@ def main(argv=None): if a.apply: written = write_prompt(mind, decision, text, source) decision["written"] = written + decision["slice_offer"] = slice_offer(written, + decision["unattended"]) if a.as_json: print(json.dumps(decision, indent=2)) else: @@ -4068,6 +4301,7 @@ def main(argv=None): d = analyse(ctx_text, f"ideas.md ({ctx or 'top'})") if a.apply: d["written"] = write_prompt(mind, d, ctx_text, d["source"]) + d["slice_offer"] = slice_offer(d["written"], d["unattended"]) formalised[text] = d["written"] results.append(d) if a.apply and formalised: @@ -4081,6 +4315,8 @@ def main(argv=None): print(f" [{d['work_type']}/{d['target']}, {d['difficulty']}, " f"conf {d['classification_confidence']}] {d['title']}" f" => {d['proposed_path']}{mark}") + if d.get("slice_offer"): + print(f" offer: {d['slice_offer']}") if not a.apply: print("\n(dry-run — re-run `intake ideas --apply` to write these + " "mark the bullets in ideas.md)") diff --git a/agents/conductors/intake/_shipped.py b/agents/conductors/intake/_shipped.py new file mode 100644 index 00000000..57def917 --- /dev/null +++ b/agents/conductors/intake/_shipped.py @@ -0,0 +1,804 @@ +#!/usr/bin/env python3 +"""agents/conductors/intake/_shipped.py — the close-out guard (`looks-shipped`). + +`intake reconcile` ranks backlog prompts on VOCABULARY: words, rare identifiers +and record lines the prompt shares with the `complete/` archive. It is offline, +opt-in and weak by design (2026-08-25: 24 suspects of 138, mostly weak). The +2026-11-05 queue check-in found four of five picked tasks already shipped, and +a full sweep closed 27 drafts (PyAutoMind#539) — every one of which bypassed +`/prm`, the only path whose close-out runs reconcile at all: + + * fixed directly on main, with no issue or PR; + * merged by a session that never ran the close-out; + * re-filed as a duplicate of work a `complete/` record already holds. + +This module is the detector for those shapes, graded ABOVE every vocabulary +signal because each leg is a fact someone can re-check, not a resemblance: + + (i) **witness-exists** — the draft's `Witness:` names a test or function + that is now DEFINED in one of its target repos, and (where git history + is readable) the definition arrived in a commit after the draft's + `Filed:` date. A test named in a witness and written afterwards is the + witness being met. + (ii) **commit-names-draft** / **pr-names-draft** — a commit message on an + organism repo's main since `Filed:` (or a merged PR body, from an + optional JSON cache) names the draft's path, filename or distinctive + slug. A Mind commit only counts when it changed something besides the + ledger: filing, queueing and batching a draft name it all the time. + (iii) **record-duplicates-draft** — a `complete/` record's `## Original + prompt` is a near-copy of an open draft (title or body, stdlib difflib). + +It only FLAGS. Retiring stays a human act, exactly as for `reconcile`: every +flag carries its evidence line, a one-line close command and a one-line +dismissal. Nothing here writes under `draft/` — the one file the `--apply` path +writes is the Mind's generated `looks_shipped.json`. + +Dismissal: `looks_shipped_dismissed.md` in the Mind root, one bullet per draft a +human judged NOT shipped (`- draft/<…>.md — <date> — <why>`). A dismissed draft +is neither flagged nor held back from the batch planner. Confirming is just +closing the draft (`lifecycle.py close … --prompt <path>`): once it leaves +`draft/` it stops being flagged on its own. + +Stdlib only; every git read degrades to "no evidence" when a checkout or its +history is absent (CI shallow clones, a laptop with half the organs). +""" +from __future__ import annotations + +import datetime as _dt +import difflib +import json +import os +import re +import subprocess +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from _repo_paths import iter_checkouts # noqa: E402 + +FLAGS_FILE = "looks_shipped.json" +DISMISS_FILE = "looks_shipped_dismissed.md" +SCHEMA = 1 +GRADE = "looks-shipped" + +#: Work-type folders under draft/ that are not backlog (shipped work awaiting a +#: person) — the guard has nothing to say about them. +_SKIP_WORK_TYPES = ("human_review",) +_INDEX_NAMES = ("README.md", "index.md", "AGENTS.md") + +# --- header / prompt parsing --------------------------------------------------- +_HEADER_RE = re.compile(r"^([A-Z][A-Za-z-]*):\s*(.*)$") + + +def parse_header(text: str) -> dict: + """Top-of-file `Key: value` lines (first 40 lines), lower-cased keys, plus + the `Repos:` bullet list. Deliberately small: the guard needs four keys.""" + out: dict = {"repos": []} + in_repos = False + for line in text.splitlines()[:40]: + if in_repos: + m = re.match(r"^\s*-\s+@?([A-Za-z0-9_.-]+)", line) + if m: + out["repos"].append(m.group(1)) + continue + in_repos = False + m = _HEADER_RE.match(line) + if not m: + continue + key, value = m.group(1).lower(), m.group(2).strip() + if key == "repos": + in_repos = not value + if value: + out["repos"] += [v.strip().lstrip("@") for v in value.split(",") + if v.strip()] + continue + out.setdefault(key, value) + return out + + +def title_of(text: str) -> str: + for line in text.splitlines(): + if line.startswith("# "): + return line[2:].strip() + return "" + + +_ISO = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b") + + +def _git(repo: Path, *args, timeout: int = 120) -> str | None: + """`git -C repo …` stdout, or None on any failure (absent git, a timeout, + an unknown ref). Every caller treats None as "no evidence".""" + try: + r = subprocess.run(["git", "-C", str(repo), *args], capture_output=True, + text=True, timeout=timeout, + env={**os.environ, "GIT_TERMINAL_PROMPT": "0", + "GIT_OPTIONAL_LOCKS": "0"}) + except (OSError, subprocess.SubprocessError): + return None + return r.stdout if r.returncode == 0 else None + + +def filed_date(mind: Path, rel: str, header: dict) -> str: + """`Filed:` from the header; else the date git first saw the file; else "".""" + m = _ISO.search(header.get("filed", "")) + if m: + return m.group(1) + out = _git(mind, "log", "--diff-filter=A", "--follow", "--format=%as", + "--", rel) + dates = (out or "").split() + return dates[-1] if dates else "" + + +def slug_forms(rel: str) -> dict: + """The ways a commit can name a draft: its path, filename and slug.""" + name = rel.rsplit("/", 1)[-1] + stem = name[:-3] if name.endswith(".md") else name + sans_draft = rel[len("draft/"):] if rel.startswith("draft/") else rel + return {"path": rel, "sans_draft": sans_draft, "filename": name, "slug": stem} + + +def _slug_key(s: str) -> str: + return "-".join(re.findall(r"[a-z0-9]+", s.lower())) + + +def distinctive_slug(stem: str) -> bool: + """A bare slug only counts when it is specific: three or more words and + fifteen-plus characters. `dashboard_fix` names half the backlog; + `close_out_guard_catch_shipped_work_whose` names one prompt.""" + parts = re.findall(r"[a-z0-9]+", stem.lower()) + return len(parts) >= 3 and len(stem) >= 15 + + +def open_drafts(mind: Path, prefix: str = "") -> list: + """Every backlog prompt under draft/ (human_review and indexes excluded).""" + out = [] + root = mind / "draft" + if not root.is_dir(): + return out + for f in sorted(root.rglob("*.md")): + rel = f.relative_to(mind).as_posix() + parts = rel.split("/") + if f.name in _INDEX_NAMES or (len(parts) > 1 and parts[1] in _SKIP_WORK_TYPES): + continue + if prefix and not (rel.startswith(prefix) or + rel.startswith("draft/" + prefix.lstrip("/"))): + continue + text = f.read_text(encoding="utf-8", errors="replace") + header = parse_header(text) + out.append({ + "path": rel, + "title": title_of(text), + "text": text, + "header": header, + "target": parts[2] if len(parts) > 3 else "", + "filed": filed_date(mind, rel, header), + }) + return out + + +# --- dismissals and the reader every consumer shares ------------------------------ +_DISMISS_RE = re.compile(r"^\s*[-*]\s+`?((?:draft/)?[^\s`]+\.md)`?") + + +def read_dismissed(mind: Path) -> dict: + """`looks_shipped_dismissed.md` -> {draft path: the bullet's text}.""" + try: + text = (Path(mind) / DISMISS_FILE).read_text(encoding="utf-8", + errors="replace") + except OSError: + return {} + out, fenced = {}, False + for line in text.splitlines(): + if line.lstrip().startswith("```"): + fenced = not fenced + continue + if fenced: + continue + m = _DISMISS_RE.match(line) + if m: + path = m.group(1) + if not path.startswith("draft/"): + path = "draft/" + path + out[path] = line.strip()[2:].strip() + return out + + +def active_flags(mind: Path) -> list: + """The flags a human still has to answer: the generated file, minus drafts a + human dismissed and minus drafts that have since left `draft/` (confirmed + and closed). This is what the dashboard renders and the planner obeys — + reading it at use time means a dismissal or a close takes effect at once, + not at the next scheduled run.""" + mind = Path(mind) + try: + data = json.loads((mind / FLAGS_FILE).read_text(encoding="utf-8")) + except (OSError, ValueError): + return [] + dismissed = read_dismissed(mind) + out = [] + for f in (data.get("flags") or []) if isinstance(data, dict) else []: + path = f.get("path", "") if isinstance(f, dict) else "" + if not path or path in dismissed or not (mind / path).is_file(): + continue + out.append(f) + return out + + +def flagged_paths(mind: Path) -> set: + return {f["path"] for f in active_flags(mind)} + + +# --- organism checkouts ------------------------------------------------------------- +def _norm(name: str) -> str: + """Repo identity folding, aligned with the sizing faculty when it loads. + + `autothing`, `PyAutoThing` and `pyautothing` must meet: the draft folder is + the package name, the checkout directory is the repo name. + """ + try: + sys.path.insert(0, str(Path(__file__).resolve().parents[2] + / "faculties" / "sizing")) + from _sizing import normalise_repo # noqa: WPS433 + key = normalise_repo(name) + except Exception: # noqa: BLE001 — a missing body map must not break the guard + key = name.strip().lstrip("@").lower() + return key[len("pyauto"):] if key.startswith("pyauto") and len(key) > 6 else key + + +def local_repos(root: Path, mind: Path) -> dict: + """{repo name: checkout path} for every organism checkout under `root`. + + The Mind under scan is always included as `PyAutoMind` (it may be a + worktree elsewhere). Linked worktrees (`.git` is a file) and dot-dirs are + skipped: a worktree is a second view of a repo already listed, and scanning + it twice would double every piece of evidence. + """ + repos = {"PyAutoMind": Path(mind)} + try: + found = iter_checkouts(Path(root)) if root else [] + except (ValueError, OSError): + found = [] + for p in found: + if p.name.startswith(".") or p.name in repos or (p / ".git").is_file(): + continue + if p.resolve() == Path(mind).resolve(): + continue + repos[p.name] = p + return repos + + +def main_ref(repo: Path) -> str: + """The ref that is `main` here: origin/main, else main, else HEAD.""" + for ref in ("origin/main", "main", "origin/master", "master"): + if _git(repo, "rev-parse", "--verify", "--quiet", ref + "^{commit}") is not None: + return ref + return "HEAD" + + +# --- leg (i): the witness names something that now exists ---------------------------- +_TEST_NAME = re.compile(r"\b(test_[A-Za-z0-9_]{4,})\b") +_TICKED = re.compile(r"`([^`\n]{3,120})`") +_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") +_DEF_RE = re.compile(r"^\s*(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(" + r"|^\s*class\s+([A-Za-z_][A-Za-z0-9_]*)\b") +_SKIP_DIRS = {".git", "node_modules", "__pycache__", ".tox", ".venv", "venv", + "build", "dist", "site-packages", ".mypy_cache", ".pytest_cache", + "dataset", "datasets", "output", "data"} + + +def witness_names(witness: str) -> set: + """The tests and functions a witness names. + + Any `test_*` word, plus backticked callables: `fit_from()`, + `module.func`, `tests/x.py::test_y`, `CamelCase`, `snake_case_name`. + Paths, flags and prose in backticks are dropped. + """ + names = set(_TEST_NAME.findall(witness)) + for raw in _TICKED.findall(witness): + token = raw.strip() + if " " in token or token.startswith("-") or "=" in token: + continue + token = token.split("::")[-1] + token = re.sub(r"\(.*\)?$", "", token) + if "/" in token or token.endswith((".py", ".md", ".yml", ".yaml", + ".json", ".toml", ".txt", ".csv")): + continue + token = token.rsplit(".", 1)[-1] + if not _IDENT.match(token): + continue + snake = "_" in token.strip("_") and len(token) >= 8 + camel = bool(re.match(r"^[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]+)+$", token)) + called = raw.rstrip().endswith(")") + if snake or camel or (called and len(token) >= 6): + names.add(token) + return names + + +def definitions(repo: Path, names: set) -> dict: + """name -> ['relpath:line', …] for `def name(` / `class name` in .py files, + plus a test FILE whose stem is the name (`test_x` -> `tests/test_x.py:1`): + a witness says "test_repos_sync_standards_block passes" about a module as + often as about a function.""" + found: dict = {} + if not names: + return found + for dirpath, dirnames, filenames in os.walk(repo): + dirnames[:] = [d for d in dirnames + if d not in _SKIP_DIRS and not d.startswith(".")] + for fn in filenames: + if not fn.endswith(".py"): + continue + p = Path(dirpath) / fn + rel = p.relative_to(repo).as_posix() + if fn.startswith("test_") and fn[:-3] in names: + found.setdefault(fn[:-3], []).append(f"{rel}:1") + try: + with p.open(encoding="utf-8", errors="replace") as fh: + for i, line in enumerate(fh, 1): + if "def " not in line and "class " not in line: + continue + m = _DEF_RE.match(line) + if not m: + continue + name = m.group(1) or m.group(2) + if name in names: + found.setdefault(name, []).append(f"{rel}:{i}") + except OSError: + continue + return found + + +def _first(out: str | None) -> str: + for ln in (out or "").splitlines(): + if ln.strip(): + return ln.strip() + return "" + + +def changed_since(repo: Path, name: str, where: list, since: str, + ref: str) -> str | None: + """Did the thing the witness names arrive or change after `since`? + + Returns `"<added|changed> by <sha> <date> <subject>"`, "" when history is + readable and says no (it predates the draft, untouched since), or None + when there is no readable history at all. In order: + + * the definition line was added (pickaxe on `def name(` / `class name`); + * the named test FILE was created or edited; + * the function's body was edited (`git log -L :name:file`) — the + bug-witness shape, where the draft names the function it fixes. + """ + if _git(repo, "rev-parse", "--git-dir") is None: + return None + since_arg = f"--since={since}T00:00:00" + fmt = "--format=%h %as %s" + for needle in (f"def {name}(", f"class {name}"): + out = _git(repo, "log", ref, since_arg, "-S", needle, fmt, "--", + "*.py", timeout=300) + if out is None: + return None + if out.strip(): + return "added by " + out.splitlines()[0].strip() + files = [] + for w in where[:3]: + rel, _, line = w.rpartition(":") + files.append((rel, line)) + for rel, line in files: + if line == "1" and rel.rsplit("/", 1)[-1] == f"{name}.py": + out = _git(repo, "log", ref, since_arg, fmt, "--", rel) + if out and out.strip(): + return "changed by " + out.splitlines()[0].strip() + continue + for kw in ("def", "class"): + out = _git(repo, "log", ref, since_arg, fmt, "--no-patch", + f"-L:{kw} {name}:{rel}", timeout=300) + first = _first(out) + if first: + return "changed by " + first + return "" + + +def _draft_repos(d: dict, repos: dict) -> list: + """The local checkouts a draft targets: its folder target + `Repos:`.""" + want = {_norm(x) for x in [d["target"], *d["header"].get("repos", [])] if x} + return [(name, path) for name, path in repos.items() if _norm(name) in want] + + +def leg_witness(drafts: list, repos: dict) -> dict: + """(i) path -> [signal, …].""" + wanted: dict = {} + for d in drafts: + names = witness_names(d["header"].get("witness", "")) + if not names or not d["filed"]: + continue + for name, path in _draft_repos(d, repos): + wanted.setdefault(name, (path, set()))[1].update(names) + defs = {name: definitions(path, names) for name, (path, names) in wanted.items()} + refs: dict = {} + out: dict = {} + for d in drafts: + names = witness_names(d["header"].get("witness", "")) + if not names or not d["filed"]: + continue + for repo_name, path in _draft_repos(d, repos): + for name in sorted(names): + where = defs.get(repo_name, {}).get(name) + if not where: + continue + if repo_name not in refs: + refs[repo_name] = main_ref(path) + how = changed_since(path, name, where, d["filed"], refs[repo_name]) + if how == "": + continue # exists, untouched since the draft was filed + if how is None and not name.startswith("test_"): + continue # no history: only a named TEST is enough + ev = (f"Witness names `{name}`, defined in {repo_name} " + f"{where[0]}") + ev += (f"; {how} (Filed {d['filed']})" if how + else " (no git history to date it)") + out.setdefault(d["path"], []).append({ + "kind": "witness-exists", "repo": repo_name, + "evidence": ev}) + return out + + +# --- leg (ii): a commit / merged PR names the draft ------------------------------ +#: Words that make a mention a pointer to still-open work, not a claim it shipped. +_FOLLOWUP = ("follow-up", "follow up", "followup", "filed", "file ", "files ", + "deferred", "todo", "to do", "later", "remain", "next step", + "blocked", "parked", "queue", "re-scope", "rescope", "split", "not ", + "phase", "partial", "pending", "unrun", "duplicate", "same shape", + "not yet", "still") +#: Words that make a mention a claim the work landed. A message line merely +#: NAMING a draft is how audits, sweeps and status notes read — measured on the +#: live Mind (2026-11-05) that alone flagged 14 drafts, none of them shipped. +_SHIP_WORDS = ("fix", "implement", "ship", "close", "resolve", "land", + "complete", "done", "deliver", "retire", "finish", "add ") +#: A subject that says the commit CHANGED code — `fix(x): …`, `feat: …`. +_CODE_SUBJECT = re.compile(r"^(?:fix|feat|perf|refactor|test|tests|docs|build|ci)" + r"(?:\([^)]*\))?!?:", re.I) +#: A subject that says the commit RECORDED intent. Mind filings and status +#: notes name drafts constantly and ship none of them. +_LEDGER_SUBJECT = re.compile(r"^(?:prompt|intake|ledger|queue|batch|shift|sweep|" + r"mind|close|epic|registry|status)\b", re.I) +_MERGE_BRANCH = re.compile(r"^Merge pull request #\d+ from \S+?/(\S+)") +#: A message naming this many drafts is an audit list, not a ship. +_LIST_MAX = 2 +#: Mind paths that are bookkeeping: a commit touching only these is the Mind +#: recording intent (filing, queueing, batching), never shipping it. +_MIND_LEDGER_DIRS = ("draft/", "active/", "complete/", "batches/") + + +def _mind_ledger_only(files: list) -> bool: + for f in files: + if f.startswith(_MIND_LEDGER_DIRS): + continue + if "/" not in f and f.endswith((".md", ".json", ".html")): + continue + return False + return True + + +def _names(line: str, d: dict) -> bool: + forms = slug_forms(d["path"]) + if forms["sans_draft"] in line or forms["filename"] in line: + return True + # `-`/`_`/`/` all fold to `-`, so a branch `feature/close-out-guard-…` + # meets the slug `close_out_guard_…`. Only for a distinctive slug. + return (distinctive_slug(forms["slug"]) and + f"-{_slug_key(forms['slug'])}-" in f"-{_slug_key(line)}-") + + +def _mention(message: str, d: dict) -> str | None: + """The message line that claims draft `d` shipped, or None. + + A line qualifies when it names the draft and either carries a ship word, + or is the PR-merge line whose branch is the draft's slug, or sits in a + `fix:`/`feat:`-style commit. Follow-up wording on the line disqualifies it, + and a ledger subject (`prompt:`, `intake:`, …) disqualifies the commit. + """ + lines = message.splitlines() + subject = lines[0].strip() if lines else "" + if _LEDGER_SUBJECT.match(subject): + return None + code = bool(_CODE_SUBJECT.match(subject)) + for line in lines: + if not _names(line, d): + continue + low = line.lower() + if any(w in low for w in _FOLLOWUP): + continue + merge = _MERGE_BRANCH.match(line.strip()) + if merge and _names(merge.group(1), d): + return line.strip() + if code or any(w in low for w in _SHIP_WORDS): + return line.strip() + return None + + +def read_commits(repo: Path, since: str, ref: str, with_files: bool) -> list: + """[{sha, date, message, files}] on `ref` since `since`.""" + fmt = "%x1e%h%x1f%as%x1f%B%x1f" + args = ["log", ref, f"--since={since}T00:00:00", f"--format={fmt}"] + if with_files: + args.append("--name-only") + out = _git(repo, *args, timeout=300) + commits = [] + for chunk in (out or "").split("\x1e"): + if not chunk.strip(): + continue + parts = chunk.split("\x1f") + if len(parts) < 3: + continue + files = [f for f in (parts[3] if len(parts) > 3 else "").split("\n") if f.strip()] + commits.append({"sha": parts[0].strip(), "date": parts[1].strip(), + "message": parts[2], "files": files}) + return commits + + +def leg_commits(drafts: list, repos: dict, mind: Path) -> dict: + """(ii) path -> [signal, …] from commit messages on each checkout's main.""" + dated = [d for d in drafts if d["filed"]] + if not dated: + return {} + since = min(d["filed"] for d in dated) + out: dict = {} + mind_res = Path(mind).resolve() + for repo_name, path in sorted(repos.items()): + is_mind = Path(path).resolve() == mind_res + for c in read_commits(path, since, main_ref(path), with_files=is_mind): + if is_mind and _mind_ledger_only(c["files"]): + continue + named = [d for d in dated if c["date"] >= d["filed"] + and any(_names(ln, d) for ln in c["message"].splitlines())] + if len(named) > _LIST_MAX: + continue + for d in named: + line = _mention(c["message"], d) + if line is None: + continue + out.setdefault(d["path"], []).append({ + "kind": "commit-names-draft", "repo": repo_name, + "evidence": f"{repo_name}@{c['sha']} ({c['date']}): {line[:160]}"}) + return out + + +def leg_prs(drafts: list, cache: Path | None) -> dict: + """(ii, PR leg) path -> [signal, …] from a merged-PR JSON cache. + + The cache is a list of `{repo, number, merged_at, title, body, url}` — what + a networked job (or a human with the GitHub MCP tools) can dump. Absent or + unreadable cache: no evidence, never an error, so the offline path works. + """ + if not cache: + return {} + try: + prs = json.loads(Path(cache).read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + if isinstance(prs, dict): + prs = prs.get("prs") or [] + out: dict = {} + for pr in prs if isinstance(prs, list) else []: + if not isinstance(pr, dict) or not pr.get("merged_at"): + continue + merged = str(pr["merged_at"])[:10] + message = f"{pr.get('title', '')}\n{pr.get('body') or ''}" + for d in drafts: + if not d["filed"] or merged < d["filed"]: + continue + line = _mention(message, d) + if line is None: + continue + ref = f"{pr.get('repo', '?')}#{pr.get('number', '?')}" + out.setdefault(d["path"], []).append({ + "kind": "pr-names-draft", "repo": pr.get("repo", ""), + "evidence": f"{ref} merged {merged}: {line[:160]}"}) + return out + + +# --- leg (iii): a completion record already holds this prompt ------------------------- +_ORIGINAL = re.compile(r"^##\s+Original prompt\s*$", re.M | re.I) +TITLE_RATIO = 0.93 +BODY_RATIO = 0.80 +_BODY_PREFILTER = 0.45 +_BODY_MIN_WORDS = 40 + + +def _prompt_words(text: str) -> list: + """Prompt prose as words: header lines, comments and the title dropped.""" + keep = [] + for line in text.splitlines(): + s = line.strip() + if s.startswith("# ") or s.startswith("<!--") or _HEADER_RE.match(s): + continue + if re.match(r"^\s*-\s+\S+$", line) and len(s) < 40: + continue # header list bullets (Repos/Themes) + keep.append(s) + return re.findall(r"[a-z0-9_]+", " ".join(keep).lower()) + + +def _title_key(title: str) -> str: + return " ".join(re.findall(r"[a-z0-9]+", title.lower())) + + +def _numbers(title: str) -> set: + return set(re.findall(r"\d+", title)) + + +def records(mind: Path) -> list: + """[{path, title, words}] for every complete/ record with an Original prompt.""" + out = [] + root = Path(mind) / "complete" + if not root.is_dir(): + return out + for p in sorted(root.rglob("*.md")): + if p.name in _INDEX_NAMES: + continue + try: + text = p.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + m = _ORIGINAL.search(text) + if not m: + continue + prompt = text[m.end():] + out.append({"path": p.relative_to(mind).as_posix(), + "title": title_of(prompt), "words": _prompt_words(prompt)}) + return out + + +def leg_records(drafts: list, recs: list) -> dict: + """(iii) path -> [signal, …]: a record's Original prompt duplicates a draft. + + Title: near-identical (difflib >= TITLE_RATIO) with the same numbers — a + phased series differs ONLY in its numbers, and `Phase 2` is not a + duplicate of `Phase 1`. Body: a word-level difflib ratio >= BODY_RATIO + over prose of at least _BODY_MIN_WORDS words, behind a cheap set-overlap + prefilter. + """ + out: dict = {} + rec_keys = [(r, _title_key(r["title"]), set(r["words"])) for r in recs] + for d in drafts: + dkey = _title_key(d["title"]) + dwords = _prompt_words(d["text"]) + dset = set(dwords) + best = None + for r, rkey, rset in rec_keys: + ev = None + if (dkey and rkey and len(dkey.split()) >= 3 + and _numbers(d["title"]) == _numbers(r["title"])): + ratio = difflib.SequenceMatcher(None, dkey, rkey).ratio() + if ratio >= TITLE_RATIO: + ev = ("title", ratio) + if ev is None and len(dwords) >= _BODY_MIN_WORDS and len(r["words"]) >= _BODY_MIN_WORDS: + inter = len(dset & rset) + union = len(dset | rset) or 1 + if inter / union >= _BODY_PREFILTER: + sm = difflib.SequenceMatcher(None, dwords, r["words"], + autojunk=False) + if sm.quick_ratio() >= BODY_RATIO: + ratio = sm.ratio() + if ratio >= BODY_RATIO: + ev = ("body", ratio) + if ev and (best is None or ev[1] > best[1][1]): + best = (r, ev) + if best: + r, (what, ratio) = best + out.setdefault(d["path"], []).append({ + "kind": "record-duplicates-draft", "repo": "PyAutoMind", + "evidence": (f"{r['path']} `## Original prompt` matches this " + f"draft's {what} ({ratio:.2f}): " + f"\"{r['title'][:100]}\"")}) + return out + + +# --- the detector ---------------------------------------------------------------------- +def close_command(path: str, today: str) -> str: + slug = path.rsplit("/", 1)[-1][:-3].replace("_", "-") + return (f"python3 scripts/lifecycle.py close {slug} --date {today} " + f"--from-file <record-body.md> --prompt {path} --apply") + + +def dismiss_command(path: str, today: str) -> str: + return (f"echo '- {path} — {today} — <why it is not shipped>' " + f">> {DISMISS_FILE}") + + +def detect(mind: Path, root: Path | None = None, prefix: str = "", + pr_cache: Path | None = None, today: str | None = None) -> dict: + """Flag open drafts with strong evidence their work already shipped. + + Read-only. `root` is the directory holding the organism checkouts as + siblings (flat or one family deep); absent checkouts are skipped silently. + """ + mind = Path(mind) + today = today or _dt.date.today().isoformat() + dismissed = read_dismissed(mind) + drafts = [d for d in open_drafts(mind, prefix) if d["path"] not in dismissed] + repos = local_repos(root, mind) if root else {"PyAutoMind": mind} + legs = [leg_witness(drafts, repos), leg_commits(drafts, repos, mind), + leg_prs(drafts, pr_cache), leg_records(drafts, records(mind))] + flags = [] + for d in drafts: + signals = [s for leg in legs for s in leg.get(d["path"], [])] + if not signals: + continue + # One line per (kind, repo) is enough to judge; the rest is a count. + seen, shown = set(), [] + for s in signals: + k = (s["kind"], s.get("repo", "")) + if k in seen: + continue + seen.add(k) + n = sum(1 for x in signals if (x["kind"], x.get("repo", "")) == k) + if n > 1: + s = {**s, "evidence": s["evidence"] + f" (+{n - 1} more)"} + shown.append(s) + flags.append({ + "path": d["path"], "title": d["title"], "grade": GRADE, + "filed": d["filed"], + "signals": shown, + "close": close_command(d["path"], today), + "dismiss": dismiss_command(d["path"], today), + }) + flags.sort(key=lambda f: (-len({s["kind"] for s in f["signals"]}), f["path"])) + return {"schema": SCHEMA, "generated": today, "scanned": len(drafts), + "repos": sorted(repos), "dismissed": len(dismissed), + "flags": flags} + + +def _body(text: str) -> str: + """The file minus its `generated` stamp — what decides a rewrite.""" + try: + obj = json.loads(text) + except ValueError: + return text + if isinstance(obj, dict): + obj.pop("generated", None) + for f in obj.get("flags") or []: + # The close/dismiss commands embed today's date; a re-run on an + # unchanged Mind must not count as a change. + if isinstance(f, dict): + f.pop("close", None) + f.pop("dismiss", None) + return json.dumps(obj, sort_keys=True) + + +def write(mind: Path, res: dict) -> bool: + """Write `looks_shipped.json` when its content changed; True if written. + + The only write in this module, and never under `draft/`. Idempotent on an + unchanged Mind, so the daily job commits nothing on a quiet night. + """ + target = Path(mind) / FLAGS_FILE + new = json.dumps(res, indent=2) + "\n" + try: + old = target.read_text(encoding="utf-8") + except OSError: + old = "" + if old and _body(old) == _body(new): + return False + target.write_text(new, encoding="utf-8") + return True + + +def emit(res: dict, written: bool | None = None): + print(f"== Looks shipped (strong evidence): {len(res['flags'])} of " + f"{res['scanned']} open draft(s) ==") + print(f" checkouts read: {', '.join(res['repos']) or '(none)'}" + + (f" · {res['dismissed']} dismissed" if res.get("dismissed") else "")) + if not res["flags"]: + print(" no open draft carries strong evidence of having shipped.") + for f in res["flags"]: + print(f"[{GRADE}] {f['path']}") + for s in f["signals"]: + print(f" {s['kind']}: {s['evidence']}") + print(f" close: {f['close']}") + print(f" dismiss: {f['dismiss']}") + if written is not None: + print(f"\n{FLAGS_FILE}: " + ("written" if written else "unchanged")) + print("\nA flag is evidence for a human, not a verdict: read the cited " + "line, then close the\ndraft (confirm) or add it to " + f"{DISMISS_FILE} (dismiss). Nothing is retired here.") diff --git a/agents/conductors/intake/intake.sh b/agents/conductors/intake/intake.sh index 2c7755cb..7c012db6 100755 --- a/agents/conductors/intake/intake.sh +++ b/agents/conductors/intake/intake.sh @@ -34,6 +34,18 @@ # `needs-review` band; never says shipped. A target # that is not one repo (workspaces, priors, …) is # refused, not guessed. +# --strong ALSO run the close-out guard's strong legs +# (below) and list them first, graded above +# every vocabulary band +# intake looks-shipped [prefix] +# the close-out guard: flag open drafts with +# STRONG evidence they shipped — a witness test +# now defined, a commit on an organism main +# naming the draft, a complete/ record that +# duplicates it. --root DIR (sibling checkouts; +# default the Mind's parent), --pr-cache FILE. +# --apply writes looks_shipped.json (never +# draft/); dismiss in looks_shipped_dismissed.md # # Flags (place before the subcommand; both default OFF): # --apply write the formal prompt file(s) / dashboard.md; else dry-run only @@ -55,7 +67,7 @@ apply=0 forward=() while [[ $# -gt 0 ]]; do case "$1" in - -h|--help) sed -n '2,39p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;; + -h|--help) sed -n '2,58p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;; --json) as_json=1; shift ;; --apply) apply=1; shift ;; *) forward+=("$1"); shift ;; @@ -71,7 +83,7 @@ fi # A bare first token that is not a known subcommand -> classify mode on the rest, # so `intake "raw idea"` and `intake --file p.md` both work as the front door. case "${forward[0]}" in - classify|ideas|census|dashboard|formalise|reconcile) ;; + classify|ideas|census|dashboard|formalise|reconcile|looks-shipped) ;; *) forward=(classify "${forward[@]}") ;; esac diff --git a/agents/faculties/sizing/_sizing.py b/agents/faculties/sizing/_sizing.py index 48359838..a6120d02 100755 --- a/agents/faculties/sizing/_sizing.py +++ b/agents/faculties/sizing/_sizing.py @@ -687,9 +687,13 @@ def declared_blocked(p: dict): return None -def parse_prompt(path: Path, mind: Path): - """Read a prompt file and extract structure: work-type, target, repos, body.""" - text = path.read_text(encoding="utf-8", errors="replace") +def parse_prompt(path: Path, mind: Path, text: str | None = None): + """Read a prompt file and extract structure: work-type, target, repos, body. + + `text`, when given, is the prompt's content and `path` need not exist yet — + how `batch slice` sizes a proposed child before anything is written.""" + if text is None: + text = path.read_text(encoding="utf-8", errors="replace") try: rel = path.relative_to(mind) parts = rel.parts @@ -908,6 +912,81 @@ def estimate_unattended(p: dict, level: str, factors: dict | None = None): return "ready", ["fits one unattended run"] +# --- seam rules: is a proposed decomposition really a set of slices? --------- +# `batch slice` (the conductor) parses and renders; the judgement of whether a +# proposed child IS a slice is an opinion, so it lives here with the other +# grades. The rules, in priority order (PyAutoMind +# draft/feature/pyautobrain/batch_slice.md): +# 1. a slice is one unattended run -> the child grades `Unattended: ready` +# 2. a slice carries its own witness -> no `Witness:` = a smaller judge task +# 3. a slice is independently revertible -> it names a repo (a PR to revert) +# and depends on no LATER slice +# 4. prefer repo-boundary seams, library before workspace -> warnings only +SLICE_MIN, SLICE_MAX = 2, 4 + + +def judge_slices(children: list) -> dict: + """Judge a proposed decomposition against the seam rules -> verdict. + + `children` is ordered; each is `{"index": int, "p": parse_prompt(...) of + the rendered child, "depends": [int]}`. Returns `{"ok", "refusals", + "warnings", "per": {index: {refusals, warnings, difficulty, consequence, + review_minutes, unattended}}}`. Read-only: this judges, it never fixes — + a refused child is the author's to re-cut, not this faculty's. + """ + refusals, warnings, per = [], [], {} + n = len(children) + if not SLICE_MIN <= n <= SLICE_MAX: + refusals.append( + f"{n} slice(s) proposed — a decomposition is {SLICE_MIN} to " + f"{SLICE_MAX} children; fewer is not a split, more is a programme " + "that wants its own epic ledger") + indices = [c["index"] for c in children] + for pos, c in enumerate(children): + p, i = c["p"], c["index"] + mine, notes = [], [] + if not p.get("witness"): + why = p.get("witness_none_reason") + mine.append("no witness" + (f" ({why})" if why else "") + + " — a smaller judge task, not a slice") + level, _, factors, derived = effective_difficulty(p) + tier, _, _ = effective_consequence(p, factors) + ready, ready_why, _ = effective_unattended(p, level, factors, derived) + minutes, _ = effective_review_minutes(p, tier, level) + if ready != "ready": + mine.append(f"grades Unattended: {ready} ({ready_why[0]}) — a slice " + "is one unattended run") + if not p["repos"]: + mine.append("names no repo — nothing to review or revert on its own") + for dep in c.get("depends") or []: + if dep not in indices: + mine.append(f"depends on slice {dep}, which is not in this " + "decomposition") + elif indices.index(dep) >= pos: + mine.append(f"depends on slice {dep}, which is not before it — " + "it could not be reviewed or reverted in order") + lib = [r for r in p["repos"] if r in LIBRARY_REPOS] + wsp = [r for r in p["repos"] if r in WORKSPACE_REPOS] + if lib and wsp: + notes.append("spans library and workspace repos — prefer a seam at " + "that boundary (library slice first)") + per[i] = {"refusals": mine, "warnings": notes, "difficulty": level, + "consequence": tier, "review_minutes": minutes, + "unattended": ready, "library": bool(lib), + "workspace_only": bool(wsp) and not lib} + seen_ws = None + for c in children: + v = per[c["index"]] + if v["workspace_only"] and seen_ws is None: + seen_ws = c["index"] + elif v["library"] and seen_ws is not None: + v["warnings"].append( + f"a library slice ordered after workspace-only slice {seen_ws} — " + "library before workspace, as the merge gate works") + ok = not refusals and not any(v["refusals"] for v in per.values()) + return {"ok": ok, "refusals": refusals, "warnings": warnings, "per": per} + + def estimate_review_minutes(tier: str, level: str) -> int: """A SEED, not a measurement. diff --git a/bin/overnight_status.sh b/bin/overnight_status.sh index abacf024..47914e5e 100755 --- a/bin/overnight_status.sh +++ b/bin/overnight_status.sh @@ -20,9 +20,8 @@ have_gh || { echo "overnight_status: cannot fetch run status" >&2; require_gh ov # owner/repo:workflow-file (owner defaults to PyAutoLabs when omitted). The # passive morning webhooks (morning_health / morning_status) are excluded. -# The Brain board renders this same sweep on Pages (board/_board.py reads the -# list from config/policy.yaml `board: overnight_jobs`) — keep the two lists -# in step until this script reads that block too. +# This list is the only copy: the Brain board retired its overnight sweep (and +# `board: overnight_jobs` with it) when activity review moved to Scientist. JOBS=( "PyAutoBrain:nightly-release.yml" "PyAutoHeart:heart-health.yml" diff --git a/bin/pyauto-brain b/bin/pyauto-brain index d54eb95d..a2bfe16b 100755 --- a/bin/pyauto-brain +++ b/bin/pyauto-brain @@ -16,6 +16,7 @@ # pyauto-brain feature [args] (conductor) reason over PyAutoMind tasks, plan growth # pyauto-brain refactor [args] (conductor) plan behaviour-preserving restructuring (default-safe) # pyauto-brain workspace [args] (conductor) the Voice: plan/survey workspace + HowTo example authorship — WorkspaceDecision (writes nothing) +# pyauto-brain docs [args] (conductor) the documentation owner: classify a docs request by surface — DocsDecision; `docs audit <page>` scores a page against skills/WRITING_STYLE.md (writes nothing) # pyauto-brain eyes [args] (conductor) the Eyes: survey/review a visualization workspace's figure surface — EyesSurvey/EyesReviewSurface (writes nothing) # pyauto-brain profiling [args] (conductor) campaign/ingest/triage plans over the profiling workspace # pyauto-brain cortex [args] (conductor) the science check-in: pull/checkin/census/dashboard/issue @@ -64,6 +65,7 @@ declare -A AGENT_SCRIPT=( [bug]="$CONDUCTORS_DIR/bug/bug.sh" [refactor]="$CONDUCTORS_DIR/refactor/refactor.sh" [workspace]="$CONDUCTORS_DIR/workspace/workspace.sh" + [docs]="$CONDUCTORS_DIR/docs/docs.sh" [eyes]="$CONDUCTORS_DIR/eyes/eyes.sh" [profiling]="$CONDUCTORS_DIR/profiling/profiling.sh" [cortex]="$CONDUCTORS_DIR/cortex/cortex.sh" @@ -86,6 +88,7 @@ declare -A AGENT_DESC=( [bug]="Classify regressions and plan repairs" [refactor]="Plan behavior-preserving restructuring" [workspace]="Plan or survey examples and tutorials" + [docs]="Plan README, setup and Read the Docs pages; audit a page's style" [eyes]="Survey figures and route accepted critiques" [cortex]="Pull science runs and record human checkins" [profiling]="Plan campaigns; ingest results; triage profiling drift" @@ -102,7 +105,7 @@ declare -A AGENT_DESC=( ) # Conductors are the front doors a human drives; faculties are consulted (and # runnable read-only). Both are dispatchable, but the menu groups them by tier. -CONDUCTOR_ORDER=(intake batch community feature bug refactor workspace eyes profiling cortex hygiene clone build release health) +CONDUCTOR_ORDER=(intake batch community feature bug refactor workspace docs eyes profiling cortex hygiene clone build release health) FACULTY_ORDER=(vitals review memory samplers sizing) AGENT_ORDER=("${CONDUCTOR_ORDER[@]}" "${FACULTY_ORDER[@]}") diff --git a/bin/version_drift.sh b/bin/version_drift.sh index 52f248b5..9a9d57f0 100755 --- a/bin/version_drift.sh +++ b/bin/version_drift.sh @@ -43,10 +43,9 @@ else fi echo -# repo:path — the coupled release-train stamps (libraries only). The Brain -# board renders this same check on Pages (board/_board.py reads the list from -# the release contract) — keep this utility independent of the Brain page -# until this script reads that block too. The +# repo:path — the coupled release-train stamps (libraries only). This list is +# the only copy: the Brain board no longer collects versions (and +# `board: version_stamps` was retired with it). The # charge-transfer (CTI) calibration stack is intentionally excluded: it is # not on the coupled train and carries its own version line. Workspaces # carry no stamp since the floors-are-authoritative redesign dropped diff --git a/skills/COMMANDS.md b/skills/COMMANDS.md index 0aeb7225..1b0c86a8 100644 --- a/skills/COMMANDS.md +++ b/skills/COMMANDS.md @@ -37,6 +37,7 @@ readiness gate, or execution — those belong to the organs. | `/bug` | Bug Agent | `bin/pyauto-brain bug` → `start_dev` → `ship_*` (health mode → vitals + Heart issues) | | `/refactor` | Refactor Agent | `bin/pyauto-brain refactor` → `start_dev [--auto]` → `ship_*` (behaviour-preserving; default-safe) | | `/workspace` | Workspace Agent | `bin/pyauto-brain workspace` → WorkspaceDecision (plan/survey example authorship) → `start_dev` → `start_workspace` → `ship_workspace` | +| `/docs` | Documentation Agent | `bin/pyauto-brain docs` → DocsDecision (surface, target repo, WRITING_STYLE.md template, siblings in step; tutorial prose deferred to `/workspace`) → `start_dev` (work type `docs/`); `docs audit <page>` scores a page read-only | | `/eyes` | Eyes Agent | `bin/pyauto-brain eyes` → survey/review a visualization workspace's figures; render via its `gallery_run.sh`; accepted critiques → `/intake` → `start_dev` | | `/profiling` | Profiling Agent | `bin/pyauto-brain profiling` → campaign/ingest/triage plans over the autolens_profiling workspace | | `/cortex` | Cortex Agent | `bin/pyauto-brain cortex pull` (laptop) → every active project pulled through its own sync CLI, its `jobs` output verbatim; `bin/pyauto-brain cortex checkin` (anywhere) → stamp, re-render the board, push the ledger and read it back by project — Now, runs, the last entries (`census`/`dashboard`/`issue` are the verbs beside them); it records cluster facts and the human's words with `scripts/cortex.py`, never a verdict of its own; a run is submitted only on the human's ask | @@ -52,12 +53,11 @@ the Brain (via `start_dev` → Feature Agent), so nothing is bypassed: | Command | PyAutoMind work-type | |---------|----------------------| -| `/docs` | `docs/` | | `/research` | `research/` | -(`/docs` remains the generic docs work-type entry; workspace/HowTo *example -authorship* specifically now has a real conductor — the Workspace Agent, -tier 1 above.) +(`/docs` graduated to a real conductor — the Documentation Agent, +`agents/conductors/docs/` — and now sits in tier 1 above; it defers tutorial +science prose to the Workspace Agent.) (`/refactor` graduated to a real conductor — the Refactor Agent, `agents/conductors/refactor/` — and now sits in tier 1 above.) diff --git a/skills/docs/SKILL.md b/skills/docs/SKILL.md index b1f26fad..ce5b098c 100644 --- a/skills/docs/SKILL.md +++ b/skills/docs/SKILL.md @@ -1,9 +1,11 @@ --- name: docs -description: Start PyAutoLabs documentation, tutorial, notebook, example, or narrative-prose work through the Brain development workflow with the docs work type fixed. +description: Plan PyAutoLabs documentation through the PyAutoBrain Documentation Agent — README, setup, Read the Docs, tutorial or agent-file surface, target repo, WRITING_STYLE.md template, siblings in step — or audit a page's style. Authoring runs through start_dev. --- # Docs -Follow [`docs.md`](docs.md) exactly. Route the task through `start-dev`; this is -a work-type entry, not a separate documentation conductor. +Follow [`docs.md`](docs.md) exactly. The Documentation Agent +(`bin/pyauto-brain docs`) decides and audits; it writes nothing. Route the +agreed work through `start-dev` with the docs work type, and defer tutorial +science prose to the Workspace Agent as the decision says. diff --git a/skills/docs/docs.md b/skills/docs/docs.md index e8fca4a0..029f0b9c 100644 --- a/skills/docs/docs.md +++ b/skills/docs/docs.md @@ -1,33 +1,56 @@ -# /docs — documentation, examples, notebooks, tutorials +# /docs — READMEs, setup pages, Read the Docs pages and tutorials -A **work-type entry** into the Brain dev-flow. No dedicated Documentation -conductor exists yet, so this routes through the Feature Agent's classifier with -the PyAutoMind work-type fixed to `docs/`. (Follow-up: promote to a dedicated -Documentation conductor.) +Plan documentation work through PyAutoBrain's **Documentation Agent**, the +owner of [`../WRITING_STYLE.md`](../WRITING_STYLE.md). You never name the +Brain; this command is the door. -Shared routing context: `PyAutoBrain/skills/COMMANDS.md`. +Shared routing context: `PyAutoBrain/skills/COMMANDS.md`. The agent's full +docs: `bin/pyauto-brain help docs`. ## Do -Treat the request as PyAutoMind work-type **`docs/`** — documentation, examples, -notebooks, or tutorial prose. If no prompt path exists, create one under -`PyAutoMind/draft/docs/<target>/<name>.md` (original request verbatim), then run -**`/start_dev`** on it. `start_dev` routes through the Brain. +1. Run the agent on the request (raw text or a filed PyAutoMind prompt): -Once the plan is approved and the development worktree is ready, choose the -writing guide before drafting or reviewing prose: + ```bash + bin/pyauto-brain docs "<raw request text>" + bin/pyauto-brain docs <PyAutoMind prompt path> + ``` + + This emits a **DocsDecision**: the surface (GitHub README, setup page, Read + the Docs page, tutorial narrative or agent-facing file), the target repo, + whether `WRITING_STYLE.md` applies, the page template from the guide, where + long material should move, and the sibling repos to keep in step (for + example the four assistant READMEs). It writes nothing. +2. Review the decision with the user and correct the surface or repo in + conversation. +3. Route the agreed work into the dev flow. If no prompt path exists, create + one under `PyAutoMind/draft/docs/<target>/<name>.md` (original request + verbatim), then run **`/start_dev`** on it with work type **`docs/`**. +4. Before review, audit each people-facing page you changed: + + ```bash + bin/pyauto-brain docs audit <page> + ``` + + It scores the page against the guide's checklist and lists concrete fixes. + Checks marked `heuristic` are prompts for judgment, not verdicts. + +## Choose the writing guide + +Read the selected guide completely before drafting or reviewing prose: - **READMEs, setup pages and general Read the Docs pages** follow [`../WRITING_STYLE.md`](../WRITING_STYLE.md). - **Scientific Python scripts, notebooks, worked examples and HowTo lessons** follow - [`../TUTORIAL_WRITING_STYLE.md`](../TUTORIAL_WRITING_STYLE.md). + [`../TUTORIAL_WRITING_STYLE.md`](../TUTORIAL_WRITING_STYLE.md). The decision + defers these to `/workspace` (the Workspace Agent's `workspace`/`howto` + registers), which plans repo, placement and sibling. - **Mixed documents** follow both guides in their respective sections. -Read the selected guide completely before editing. For tutorial work, plan -approval establishes the development scope but does not authorise a bulk prose -rewrite: propose, review and apply one coherent block at a time as defined by -`TUTORIAL_WRITING_STYLE.md`. +For tutorial work, plan approval establishes the development scope but does not +authorise a bulk prose rewrite: propose, review and apply one coherent block at +a time as defined by `TUTORIAL_WRITING_STYLE.md`. The judgment/execution tier split in `../WORKFLOW.md` applies. Taxonomy: `PyAutoMind/ROUTING.md`. diff --git a/tests/test_batch_slice.py b/tests/test_batch_slice.py new file mode 100644 index 00000000..fba2725c --- /dev/null +++ b/tests/test_batch_slice.py @@ -0,0 +1,210 @@ +"""tests/test_batch_slice.py — `batch slice`, the decomposition pass. + +The verb renders and judges a DECLARED decomposition; these tests pin the seam +rules (witness, count, order), that the parent is never touched, and that only +`--apply` writes — the children and the epics.md entry. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import sys +from pathlib import Path + +import pytest + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) +_spec = importlib.util.spec_from_file_location( + "_batch_slice_under_test", BRAIN / "agents" / "conductors" / "batch" / "_batch.py") +_batch = importlib.util.module_from_spec(_spec) +sys.modules["_batch_slice_under_test"] = _batch +_spec.loader.exec_module(_batch) +import _slice # noqa: E402 (importable once _batch set sys.path) + +PARENT = "draft/feature/autofit/big_thing.md" + +HEADER = """# A big thing + +Type: feature +Target: PyAutoThing +Repos: +- PyAutoThing +- autothing_workspace +Themes: +- mind-workflow +Difficulty: too-large +Autonomy: supervised +Priority: normal +Status: draft +Unattended: needs-slicing + +Do a great deal of work. + +## Slices + +""" + +LIB = ("1. **Library core.** Add the thing. *Repos:* PyAutoThing\n" + " *Witness:* `pytest test_autofit/thing` passes. *Consequence:* glance.\n") +WS = ("2. **Workspace example.** Show it in autothing_workspace. *Witness:* the\n" + " example runs in smoke. *Depends:* 1\n") +DOCS = ("3. **Docs page.** Document it in autothing_workspace. *Witness:* the docs " + "build passes. *Depends:* 1\n") +NO_WITNESS = "3. **Tidy up.** Clean the rest of PyAutoThing. *Repos:* PyAutoThing\n" + + +def mind(tmp_path: Path, slices: str, *, epics: str = "# Epics\n") -> Path: + root = tmp_path / "PyAutoMind" + f = root / PARENT + f.parent.mkdir(parents=True) + f.write_text(HEADER + slices + "\n## After\n\nNot a slice.\n", encoding="utf-8") + (root / "epics.md").write_text(epics, encoding="utf-8") + return root + + +def run(root: Path, *extra, capsys): + rc = _batch.main(["slice", PARENT, "--mind", str(root), "--json", *extra]) + return rc, json.loads(capsys.readouterr().out) + + +def digest(root: Path) -> str: + return hashlib.sha256((root / PARENT).read_bytes()).hexdigest() + + +def test_two_children_with_explicit_seams(tmp_path, capsys): + root = mind(tmp_path, LIB + WS) + rc, d = run(root, capsys=capsys) + assert rc == 0 and d["ok"], d + assert [c["index"] for c in d["children"]] == [1, 2] + one, two = d["children"] + assert one["repos"] == ["PyAutoThing"] + assert two["repos"] == ["autothing_workspace"] # named in the item's text + assert "before slice 2" in one["seam"] + assert "after slice 1" in two["seam"] and "slice(s) 1 merged" in two["seam"] + assert "Witness: `pytest test_autofit/thing` passes." in one["text"] + assert "Epic: big-thing" in two["text"] and "Phase: 2" in two["text"] + assert "Target: autothing_workspace" in two["text"] + assert "## Seam" in one["text"] + assert d["written"] == [] + assert not (root / one["path"]).exists() # proposal writes nothing + + +def test_four_children_accepted(tmp_path, capsys): + four = LIB + WS + DOCS + ("4. **Second docs page.** In autothing_workspace. " + "*Witness:* the page renders.\n") + rc, d = run(mind(tmp_path, four), capsys=capsys) + assert rc == 0 and len(d["children"]) == 4 + + +def test_a_child_with_no_witness_is_refused(tmp_path, capsys): + root = mind(tmp_path, LIB + WS + NO_WITNESS) + rc, d = run(root, "--apply", capsys=capsys) + assert rc == 1 and not d["ok"] + bad = d["children"][2] + assert any("a smaller judge task, not a slice" in r for r in bad["refusals"]) + assert not d["children"][0]["refusals"] + assert d["written"] == [] + assert not any((root / c["path"]).exists() for c in d["children"]) + + +@pytest.mark.parametrize("slices", [LIB, LIB + WS + DOCS + ( + "4. **Four.** In PyAutoThing. *Witness:* a. \n" + "5. **Five.** In PyAutoThing. *Witness:* b.\n")]) +def test_fewer_than_two_or_more_than_four_is_refused(tmp_path, capsys, slices): + rc, d = run(mind(tmp_path, slices), capsys=capsys) + assert rc == 1 + assert any("2 to 4 children" in r for r in d["refusals"]) + + +def test_a_dependency_on_a_later_slice_is_refused(tmp_path, capsys): + early = LIB.replace("*Consequence:* glance.", "*Depends:* 2") + rc, d = run(mind(tmp_path, early + WS), capsys=capsys) + assert rc == 1 + assert any("not before it" in r for r in d["children"][0]["refusals"]) + + +def test_a_parent_that_declares_no_slices_is_refused_not_invented(tmp_path, capsys): + rc, d = run(mind(tmp_path, ""), capsys=capsys) + assert rc == 1 and d["children"] == [] + assert any("does not invent one" in r for r in d["refusals"]) + + +def test_only_a_needs_slicing_parent_is_sliced(tmp_path, capsys): + root = mind(tmp_path, LIB + WS) + f = root / PARENT + f.write_text(f.read_text().replace("Unattended: needs-slicing", + "Unattended: ready")) + rc, d = run(root, capsys=capsys) + assert rc == 1 + assert any("not needs-slicing" in r for r in d["refusals"]) + + +def test_slices_file_replaces_the_parents_section(tmp_path, capsys): + root = mind(tmp_path, NO_WITNESS) # the parent's own cut is bad + plan = tmp_path / "plan.md" + plan.write_text(LIB + WS) # no heading needed in a plan file + rc, d = run(root, "--slices", str(plan), capsys=capsys) + assert rc == 0 and len(d["children"]) == 2 + assert d["source"].startswith("--slices") + + +def test_apply_writes_children_and_epic_entry_and_leaves_the_parent(tmp_path, capsys): + root = mind(tmp_path, LIB + WS) + before = digest(root) + rc, d = run(root, "--apply", capsys=capsys) + assert rc == 0 + paths = [c["path"] for c in d["children"]] + assert d["written"] == paths + ["epics.md"] + for c in d["children"]: + assert (root / c["path"]).read_text() == c["text"] + assert Path(c["path"]).parent == Path(PARENT).parent # beside the parent + epics = (root / "epics.md").read_text() + assert "## big-thing" in epics + assert f"- ledger: {PARENT}" in epics + assert digest(root) == before # parent untouched + assert sorted(p.name for p in (root / PARENT).parent.iterdir()) == sorted( + [Path(PARENT).name] + [Path(p).name for p in paths]) + + # A second apply refuses rather than overwriting, and still leaves the parent. + rc, d = run(root, "--apply", capsys=capsys) + assert rc == 1 and d["written"] == [] + assert any("already exists" in r for r in d["children"][0]["refusals"]) + assert digest(root) == before + + +def test_a_parent_already_an_epic_gets_no_second_entry(tmp_path, capsys): + epics = f"# Epics\n\n## big\n- title: Big\n- ledger: {PARENT}\n" + root = mind(tmp_path, LIB + WS, epics=epics) + rc, d = run(root, "--apply", capsys=capsys) + assert rc == 0 and d["epic"] == "big" and d["epic_exists"] + assert "epics.md" not in d["written"] + assert (root / "epics.md").read_text() == epics + assert "Epic: big\n" in d["children"][0]["text"] + + +def test_the_human_report_says_nothing_was_written(tmp_path, capsys): + root = mind(tmp_path, LIB + WS) + rc = _batch.main(["slice", PARENT, "--mind", str(root)]) + out = capsys.readouterr().out + assert rc == 0 and "PROPOSED" in out and "Nothing written" in out + + +def test_slice_needs_a_prompt(tmp_path, capsys): + root = mind(tmp_path, LIB + WS) + assert _batch.main(["slice", "--mind", str(root)]) == _batch.RC_USAGE + + +def test_intake_offers_slice_only_for_needs_slicing(): + spec = importlib.util.spec_from_file_location( + "_intake_slice_offer", BRAIN / "agents" / "conductors" / "intake" / "_intake.py") + intake = importlib.util.module_from_spec(spec) + spec.loader.exec_module(intake) + offer = intake.slice_offer("draft/feature/x/y.md", "needs-slicing") + assert "pyauto-brain batch slice draft/feature/x/y.md" in offer + assert intake.slice_offer("draft/feature/x/y.md", "ready") == "" + d = intake.analyse("Type: feature\nTarget: PyAutoThing\nUnattended: needs-slicing" + "\n\nBuild a huge thing across PyAutoThing.\n", "test") + assert "batch slice" in d["slice_offer"] diff --git a/tests/test_docs_conductor.py b/tests/test_docs_conductor.py new file mode 100644 index 00000000..00a961f1 --- /dev/null +++ b/tests/test_docs_conductor.py @@ -0,0 +1,269 @@ +"""Contract tests for the Documentation conductor's CLI footing. + +Hermetic: PYAUTO_ROOT points at a temp root holding only a fixture body map +(invented repo names — the tenant firewall keeps instance facts out of organ +code, tests included), so no real checkout is read, and audits run on fabricated pages. The +conductor is read-only — test_never_writes asserts it explicitly. +""" + +import json +import os +import subprocess +from pathlib import Path + +BRAIN_HOME = Path(__file__).resolve().parents[1] +BRAIN = BRAIN_HOME / "bin" / "pyauto-brain" + +DECISION_KEYS = { + "title", "prompt_path", "surface", "surface_label", "target_repo", + "repo_category", "page", "writing_style_applies", "style_guide", + "page_template", "move_long_material_to", "siblings_in_step", + "deferred_to", "checklist", "audit_command", "notes", "next_action", +} + +GOOD_README = """\ +<p align="center"><img src="logo.png" alt="Logo"></p> + +# PyAutoThing + +PyAutoThing fits models to your data. You can use it from a notebook or a script. + +## Getting Started + +Install it and run your first fit: + +```bash +pip install autothing +``` + +## Your first fit + +See [Getting Started](#getting-started) and [the guide](docs/guide.md). + +## License + +MIT. +""" + +BAD_README = """\ +# Example Prompt 1 (Teacher Mode): Simulate, inspect and model a strong lens + +The conductor routes each request through the harness — then the gate checks +it — and finally the organ (the Heart) (or the Hands) acts. Check the provider's +current plans rather than assuming anything. It costs $20 per month. Wow! Great! +Also more text here. And more. And even more sentences in the intro. + +## Agents + +If you are an AI agent, read AGENTS.md first. + +[broken](missing.md) and [bad anchor](#nowhere) +""" + + +FIXTURE_REPOS = { + "PyAutoHeart": "organ", + "PyAutoAlpha": "library", "PyAutoBeta": "library", + "autoalpha_workspace": "workspace", "autobeta_workspace": "workspace", + "HowToAlpha": "howto", "HowToBeta": "howto", "HowToGamma": "howto", + "autoalpha_assistant": "assistant", "autobeta_assistant": "assistant", + "autogamma_assistant": "assistant", "autodelta_assistant": "assistant", +} + + +def _body_map(root): + manifest = root / "PyAutoMind" / "repos.yaml" + if not manifest.exists(): + manifest.parent.mkdir(parents=True, exist_ok=True) + manifest.write_text("repos:\n" + "".join( + f" {name}:\n github: Org/{name}\n category: {cat}\n" + for name, cat in FIXTURE_REPOS.items())) + + +def _run(args, root): + _body_map(root) + env = {**os.environ, "PYAUTO_ROOT": str(root)} + return subprocess.run( + [str(BRAIN), "docs", *args], capture_output=True, text=True, env=env, + ) + + +def _decide(text, root): + r = _run(["--json", text], root) + assert r.returncode == 0, r.stderr + return json.loads(r.stdout) + + +def test_assistant_readme_decision_is_complete(tmp_path): + d = _decide("rewrite the autoalpha assistant README in the new style", tmp_path) + assert set(d) == DECISION_KEYS + assert d["surface"] == "readme" + assert d["target_repo"] == "autoalpha_assistant" + assert d["writing_style_applies"] is True + assert d["style_guide"].endswith("skills/WRITING_STYLE.md") + # The template is parsed from the guide, not restated. + assert d["page_template"][:2] == ["a title", "an image"] + assert "License" in d["page_template"] + assert set(d["siblings_in_step"]) == { + "autobeta_assistant", "autogamma_assistant", "autodelta_assistant"} + assert any("rule 5" in m for m in d["move_long_material_to"]) + assert d["checklist"] + assert d["deferred_to"] is None + + +def test_setup_page_uses_setup_template(tmp_path): + d = _decide("new setup page for Codex in autobeta_assistant", tmp_path) + assert d["surface"] == "setup" + assert "What it costs" in d["page_template"] + assert any(s.startswith("Next steps") for s in d["page_template"]) + + +def test_rtd_page_uses_journey_order(tmp_path): + d = _decide("Read the Docs page on PyAutoBeta samplers", tmp_path) + assert d["surface"] == "rtd" + assert d["target_repo"] == "PyAutoBeta" + assert d["page_template"][0] == "What it is" + assert any("no Read the Docs template" in n for n in d["notes"]) + + +def test_tutorial_is_deferred_to_workspace_conductor(tmp_path): + d = _decide("a HowToAlpha chapter tutorial on mass profiles", tmp_path) + assert d["surface"] == "tutorial" + assert d["writing_style_applies"] is False + assert d["style_guide"].endswith("TUTORIAL_WRITING_STYLE.md") + assert d["deferred_to"]["conductor"] == "workspace" + assert d["deferred_to"]["register_hint"] == "howto" + assert d["deferred_to"]["command"].startswith("bin/pyauto-brain workspace ") + assert d["page_template"] == [] and d["siblings_in_step"] == [] + + +def test_workspace_register_hint_for_reference_examples(tmp_path): + d = _decide("an example script notebook for autoalpha_workspace", tmp_path) + assert d["deferred_to"]["register_hint"] == "workspace" + + +def test_readme_beats_tutorial_and_flags_mixed(tmp_path): + d = _decide("rewrite the HowToAlpha README with a tutorial walkthrough", tmp_path) + assert d["surface"] == "readme" + assert d["siblings_in_step"] == ["HowToBeta", "HowToGamma"] + assert "TUTORIAL_WRITING_STYLE.md" in d["style_guide"] + assert any("mixed document" in n for n in d["notes"]) + + +def test_agent_facing_file_does_not_apply_style(tmp_path): + d = _decide("tighten the AGENTS.md of PyAutoHeart", tmp_path) + assert d["surface"] == "agent" + assert d["writing_style_applies"] is False + assert d["style_guide"] is None + assert d["page"] == "AGENTS.md" + assert any("does not apply" in c for c in d["checklist"]) + + +def test_plan_reads_a_mind_prompt_path(tmp_path): + prompt = tmp_path / "PyAutoMind" / "draft" / "docs" / "assistants" / "x.md" + prompt.parent.mkdir(parents=True) + prompt.write_text("# Assistant README\n\nRewrite the autogamma_assistant README.\n") + d = _decide("draft/docs/assistants/x.md", tmp_path) + assert d["prompt_path"] == str(prompt) + assert d["target_repo"] == "autogamma_assistant" + + +def test_unresolvable_exits_4_and_no_intent_exits_5(tmp_path): + r = _run(["--json", "write some documentation please"], tmp_path) + assert r.returncode == 4 and "cannot resolve" in r.stderr + r = _run(["README for something"], tmp_path) + assert r.returncode == 4 and "no target repo" in r.stderr + assert _run([], tmp_path).returncode == 5 + + +def test_text_output_names_the_decision(tmp_path): + r = _run(["rewrite the autoalpha assistant README"], tmp_path) + assert r.returncode == 0 + assert "DocsDecision" in r.stdout + assert "Siblings in step:" in r.stdout + + +def _audit(page, root, *extra): + r = _run(["audit", str(page), "--json", *extra], root) + assert r.returncode == 0, r.stderr + return json.loads(r.stdout) + + +def test_audit_good_readme_passes(tmp_path): + (tmp_path / "docs").mkdir() + (tmp_path / "docs" / "guide.md").write_text("# Guide\n") + (tmp_path / "logo.png").write_bytes(b"") + page = tmp_path / "README.md" + page.write_text(GOOD_README) + a = _audit(page, tmp_path) + failing = {c["id"]: c["finding"] for c in a["checks"] if c["status"] != "pass"} + assert failing == {} + assert a["score"] == 100 + assert all(c["kind"] in ("mechanical", "heuristic") for c in a["checks"]) + assert a["not_checked"] + + +def test_audit_bad_readme_lists_concrete_fixes(tmp_path): + page = tmp_path / "README.md" + page.write_text(BAD_README) + a = _audit(page, tmp_path) + status = {c["id"]: c for c in a["checks"]} + for cid in ("image", "getting_started", "license_last", "jargon", "hedging", + "changeable_facts", "exclamations", "plain_headings", + "agent_text", "links", "dash_chains", "intro_length"): + assert status[cid]["status"] == "fix", cid + assert status[cid]["fixes"], cid + assert any("'conductor'" in f for f in status["jargon"]["fixes"]) + assert any("missing.md" in f for f in status["links"]["fixes"]) + assert any("#nowhere" in f for f in status["links"]["fixes"]) + assert a["score"] < 50 + + +def test_audit_ignores_jargon_in_code_and_details(tmp_path): + page = tmp_path / "README.md" + page.write_text(GOOD_README + "\n```\nconductor gate organ\n```\n" + "<details><summary>For agents</summary>\n\nthe conductor\n\n</details>\n" + "Use `the_gate` here.\n") + a = _audit(page, tmp_path) + jargon = next(c for c in a["checks"] if c["id"] == "jargon") + assert jargon["status"] == "pass", jargon + + +def test_audit_setup_page_template(tmp_path): + page = tmp_path / "docs" / "setup" / "codex.md" + page.parent.mkdir(parents=True) + page.write_text("# Codex\n\nCodex is an agent you run.\n\n## What it costs\n\nSee the page.\n") + a = _audit(page, tmp_path) + assert a["page_kind"] == "setup" + setup = next(c for c in a["checks"] if c["id"] == "setup_sections") + assert setup["status"] == "fix" + assert "Install and start" in setup["finding"] + + +def test_audit_agent_file_is_not_scored(tmp_path): + page = tmp_path / "AGENTS.md" + page.write_text("# Agents\n\nThe conductor gate.\n") + a = _audit(page, tmp_path) + assert a["score"] is None and "does not apply" in a["note"] + + +def test_audit_missing_page_exits_4(tmp_path): + assert _run(["audit", str(tmp_path / "nope.md")], tmp_path).returncode == 4 + + +def test_never_writes(tmp_path): + page = tmp_path / "README.md" + page.write_text(BAD_README) + _body_map(tmp_path) + before = sorted((str(p), p.stat().st_mtime_ns) for p in tmp_path.rglob("*")) + _run(["rewrite the autoalpha assistant README"], tmp_path) + _run(["audit", str(page)], tmp_path) + after = sorted((str(p), p.stat().st_mtime_ns) for p in tmp_path.rglob("*")) + assert before == after + + +def test_docs_entry_routes_through_the_conductor(): + entry = (BRAIN_HOME / "skills" / "docs" / "docs.md").read_text() + assert "bin/pyauto-brain docs" in entry + assert "docs audit" in entry + assert "No dedicated Documentation" not in entry diff --git a/tests/test_intake_looks_shipped.py b/tests/test_intake_looks_shipped.py new file mode 100644 index 00000000..1da5d424 --- /dev/null +++ b/tests/test_intake_looks_shipped.py @@ -0,0 +1,357 @@ +"""The close-out guard: `intake looks-shipped` and its consumers. + +Witness (PyAutoMind draft close_out_guard_catch_shipped_work_whose.md): a +fixture Mind plus fixture commit history where + + (i) a draft's Witness test now exists in its target repo, + (ii) a commit message (and a merged-PR body) names a draft's path or slug, + (iii) a completion record's `## Original prompt` duplicates an open draft, + +are each flagged `looks-shipped` with the evidence cited; a control set that +shares only vocabulary is not flagged; nothing under draft/ is written; and the +batch planner drops flagged drafts from its proposals. + +Hermetic: every repo is a git repo built in tmp_path with pinned dates. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) + + +def _load(name, rel): + spec = importlib.util.spec_from_file_location(name, BRAIN / rel) + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + spec.loader.exec_module(mod) + return mod + + +_shipped = _load("_shipped_under_test", "agents/conductors/intake/_shipped.py") +_intake = _load("_intake_ls_under_test", "agents/conductors/intake/_intake.py") +_batch = _load("_batch_ls_under_test", "agents/conductors/batch/_batch.py") +_state = _load("_state_ls_under_test", "board/_state.py") + + +# --------------------------------------------------------------------------- # +# fixture organism +# --------------------------------------------------------------------------- # +def _git(repo: Path, *args, date: str = "2026-01-01T12:00:00"): + env = {**os.environ, "GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date, + "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@example.com", + "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@example.com"} + subprocess.run(["git", "-C", str(repo), *args], check=True, env=env, + capture_output=True, text=True) + + +def _commit(repo: Path, files: dict, message: str, date: str): + for rel, body in files.items(): + p = repo / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(body, encoding="utf-8") + _git(repo, "add", "-A") + _git(repo, "commit", "-q", "--allow-empty", "-m", message, date=date) + + +def _init(repo: Path): + repo.mkdir(parents=True) + _git(repo, "init", "-q", "-b", "main") + + +HEADER = """Type: {wt} +Target: pyautowidget +Repos: +- PyAutoWidget +Difficulty: small +Autonomy: safe +Priority: normal +Status: formalised +Filed: 2026-01-10 +Consequence: notify +Review-minutes: 5 +Unattended: ready +Witness: {witness} +""" + + +def _draft(title, wt, witness, body): + return f"# {title}\n\n{HEADER.format(wt=wt, witness=witness)}\n{body}\n" + + +GEAR_BODY = ("The gear ratio dashboard should render one row per gearbox with " + "its measured ratio, the declared ratio and the drift between " + "them, sorted by drift so the worst gearbox is at the top. Each " + "row links the gearbox's calibration log and carries a copy " + "button for the recalibration command. The page is generated " + "nightly and never hand edited, and a stale page states its own " + "generation date so nobody trusts an old render by accident.") + +DRAFTS = { + # (i) witness test defined after Filed + "draft/feature/pyautowidget/sprocket_guard.md": _draft( + "Guard sprockets against overflow", "feature", + "`test_sprocket_guard_refuses_overflow` passes in PyAutoWidget", + "Sprockets overflow when the flange spins too fast."), + # (ii) a commit names the draft path + "draft/bug/pyautowidget/flange_rattle_under_load.md": _draft( + "Flange rattles under load", "bug", "the rattle test passes", + "The flange rattles under load; the sprocket shakes loose."), + # (ii, PR leg) a merged PR body names the slug + "draft/feature/pyautowidget/torque_limiter_for_spindles.md": _draft( + "Torque limiter for spindles", "feature", "spindles stop at the limit", + "Add a torque limiter so spindles stop before the gear strips."), + # (iii) a completion record duplicates it + "draft/feature/pyautowidget/gear_ratio_dashboard.md": _draft( + "Gear ratio dashboard for every gearbox", "feature", + "the dashboard renders", GEAR_BODY), + # --- controls: vocabulary only --------------------------------------- + # Witness names a helper that existed BEFORE the draft was filed. + "draft/feature/pyautowidget/sprocket_flange_gear_polish.md": _draft( + "Sprocket flange gear polish", "feature", + "`test_existing_sprocket_helper` still passes", + "Polish the sprocket, the flange and the gear ratio dashboard copy."), + # Named only by a follow-up line, a ledger-only Mind commit and a commit + # that predates its filing. + "draft/bug/pyautowidget/spindle_wobble_on_cold_start.md": _draft( + "Spindle wobble on cold start", "bug", "no wobble", + "Spindles wobble on a cold start; related to the torque limiter."), +} + +RECORD = ("## gear-ratio-dashboard\n- summary: shipped the gearbox board.\n\n" + "## Original prompt\n\n" + + _draft("Gear ratio dashboard for every gearbox", "feature", + "the dashboard renders", GEAR_BODY)) + +PRS = [{"repo": "PyAutoWidget", "number": 7, "merged_at": "2026-02-05T10:00:00Z", + "title": "Spindle torque limiter", + "body": "Implements torque-limiter-for-spindles (the Mind draft)."}, + {"repo": "PyAutoWidget", "number": 8, "merged_at": "2026-02-06T10:00:00Z", + "title": "Docs", "body": "Follow-up filed: spindle_wobble_on_cold_start.md"}] + + +@pytest.fixture() +def organism(tmp_path): + root = tmp_path / "root" + mind = root / "PyAutoMind" + widget = root / "PyAutoWidget" + _init(mind) + _commit(mind, {"README.md": "# Mind\n"}, "init", "2026-01-01T09:00:00") + _commit(mind, DRAFTS, "prompt: file six widget drafts", "2026-01-10T09:00:00") + _commit(mind, {"complete/2026/02/gear-ratio-dashboard.md": RECORD}, + "close: gear-ratio-dashboard", "2026-02-03T09:00:00") + # A ledger-only Mind commit naming a control by path: bookkeeping, not a ship. + _commit(mind, {"queue.md": "# Queue\n"}, + "fix: queue draft/bug/pyautowidget/spindle_wobble_on_cold_start.md", + "2026-02-04T09:00:00") + + _init(widget) + _commit(widget, {"widget/core.py": "def spin():\n return 1\n", + "tests/test_core.py": + "def test_existing_sprocket_helper():\n assert True\n"}, + "init", "2025-12-01T09:00:00") + # Names a control BEFORE it was filed — cannot be evidence of shipping it. + _commit(widget, {}, "fix: spindle_wobble_on_cold_start.md cured", + "2026-01-02T09:00:00") + _commit(widget, {"tests/test_guard.py": + "def test_sprocket_guard_refuses_overflow():\n assert True\n"}, + "feat: sprocket overflow guard", "2026-02-01T09:00:00") + _commit(widget, {"widget/core.py": "def spin():\n return 2\n"}, + "fix: flange rattle\n\nCloses draft/bug/pyautowidget/" + "flange_rattle_under_load.md.", "2026-02-02T09:00:00") + _commit(widget, {}, "docs: note\n\nFollow-up filed as " + "draft/bug/pyautowidget/spindle_wobble_on_cold_start.md", + "2026-02-03T09:00:00") + cache = tmp_path / "prs.json" + cache.write_text(json.dumps(PRS), encoding="utf-8") + return {"root": root, "mind": mind, "widget": widget, "cache": cache} + + +def _snapshot(folder: Path) -> dict: + return {p.relative_to(folder).as_posix(): + hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(folder.rglob("*")) if p.is_file()} + + +def _flags(res): + return {f["path"]: f for f in res["flags"]} + + +# --------------------------------------------------------------------------- # +# the three legs, and the controls +# --------------------------------------------------------------------------- # +def test_each_strong_leg_flags_its_draft_with_evidence(organism): + res = _shipped.detect(organism["mind"], organism["root"], + pr_cache=organism["cache"], today="2026-03-01") + flags = _flags(res) + kinds = {p: {s["kind"] for s in f["signals"]} for p, f in flags.items()} + + witness = "draft/feature/pyautowidget/sprocket_guard.md" + assert kinds[witness] == {"witness-exists"} + ev = flags[witness]["signals"][0]["evidence"] + assert "test_sprocket_guard_refuses_overflow" in ev + assert "tests/test_guard.py" in ev and "sprocket overflow guard" in ev + + commit = "draft/bug/pyautowidget/flange_rattle_under_load.md" + assert kinds[commit] == {"commit-names-draft"} + assert "PyAutoWidget@" in flags[commit]["signals"][0]["evidence"] + assert "Closes draft/bug" in flags[commit]["signals"][0]["evidence"] + + pr = "draft/feature/pyautowidget/torque_limiter_for_spindles.md" + assert kinds[pr] == {"pr-names-draft"} + assert "PyAutoWidget#7" in flags[pr]["signals"][0]["evidence"] + + dup = "draft/feature/pyautowidget/gear_ratio_dashboard.md" + assert kinds[dup] == {"record-duplicates-draft"} + assert "complete/2026/02/gear-ratio-dashboard.md" in flags[dup]["signals"][0]["evidence"] + + for f in flags.values(): + assert f["grade"] == "looks-shipped" + assert f["close"].startswith("python3 scripts/lifecycle.py close ") + assert f"--prompt {f['path']}" in f["close"] + assert _shipped.DISMISS_FILE in f["dismiss"] + + +def test_the_vocabulary_control_set_is_not_flagged(organism): + res = _shipped.detect(organism["mind"], organism["root"], + pr_cache=organism["cache"]) + flagged = set(_flags(res)) + assert "draft/feature/pyautowidget/sprocket_flange_gear_polish.md" not in flagged + assert "draft/bug/pyautowidget/spindle_wobble_on_cold_start.md" not in flagged + assert len(flagged) == 4 + # ...while the vocabulary ranker does see the shared words. The control is + # a control: it shares vocabulary, not evidence. + assert res["scanned"] == 6 + + +def test_absent_checkouts_and_cache_degrade_to_no_evidence(organism, tmp_path): + empty = tmp_path / "nowhere" + empty.mkdir() + res = _shipped.detect(organism["mind"], empty, + pr_cache=tmp_path / "missing.json") + # Only the Mind-local leg (iii) remains. + assert set(_flags(res)) == {"draft/feature/pyautowidget/gear_ratio_dashboard.md"} + + +def test_a_phase_series_title_is_not_a_duplicate(): + recs = [{"path": "complete/x.md", "title": "Widget rollout phase 1: gears", + "words": ["a"]}] + drafts = [{"path": "draft/feature/w/p2.md", + "title": "Widget rollout phase 2: gears", "text": "", "filed": ""}] + assert _shipped.leg_records(drafts, recs) == {} + + +def test_witness_names_tests_and_callables_not_paths(): + names = _shipped.witness_names( + "`tests/test_x.py::test_widget_spins` and test_other_thing pass; " + "`autowidget.fit_from()` works; `scripts/run.py` exists; `--flag`") + assert {"test_widget_spins", "test_other_thing", "fit_from"} <= names + assert not any("/" in n or n.endswith(".py") for n in names) + + +# --------------------------------------------------------------------------- # +# write path: only looks_shipped.json, never draft/ +# --------------------------------------------------------------------------- # +def test_apply_writes_only_the_flags_file_and_never_draft(organism, capsys): + mind = organism["mind"] + before = _snapshot(mind / "draft") + rc = _intake.main(["--mind", str(mind), "--apply", "looks-shipped", + "--root", str(organism["root"]), + "--pr-cache", str(organism["cache"])]) + assert rc == 0 + assert _snapshot(mind / "draft") == before + data = json.loads((mind / "looks_shipped.json").read_text()) + assert len(data["flags"]) == 4 + status = subprocess.run(["git", "-C", str(mind), "status", "--porcelain"], + capture_output=True, text=True).stdout.split("\n") + assert [ln for ln in status if ln.strip()] == ["?? looks_shipped.json"] + # A re-run on an unchanged Mind is not a change (the daily job commits + # nothing on a quiet night). + res = _shipped.detect(mind, organism["root"], pr_cache=organism["cache"], + today="2099-01-01") + assert _shipped.write(mind, res) is False + + +def test_reconcile_strong_lists_looks_shipped_above_vocabulary(organism, capsys): + rc = _intake.main(["--mind", str(organism["mind"]), "--json", "reconcile", + "--strong", "--root", str(organism["root"])]) + assert rc == 0 + res = json.loads(capsys.readouterr().out) + strong = {f["path"] for f in res["looks_shipped"]["flags"]} + assert "draft/feature/pyautowidget/sprocket_guard.md" in strong + assert not strong & {s["path"] for s in res["suspects"]} + + +# --------------------------------------------------------------------------- # +# consumers: dismissal, dashboard, state.json, batch plan +# --------------------------------------------------------------------------- # +def _apply(organism): + res = _shipped.detect(organism["mind"], organism["root"], + pr_cache=organism["cache"]) + _shipped.write(organism["mind"], res) + return res + + +def test_dismissed_and_closed_drafts_drop_out_at_once(organism): + mind = organism["mind"] + _apply(organism) + assert len(_shipped.active_flags(mind)) == 4 + (mind / _shipped.DISMISS_FILE).write_text( + "# Looks shipped — dismissed\n\n" + "- draft/bug/pyautowidget/flange_rattle_under_load.md — 2026-03-01 — " + "the commit fixed a different flange\n", encoding="utf-8") + (mind / "draft/feature/pyautowidget/sprocket_guard.md").unlink() # closed + left = {f["path"] for f in _shipped.active_flags(mind)} + assert left == {"draft/feature/pyautowidget/torque_limiter_for_spindles.md", + "draft/feature/pyautowidget/gear_ratio_dashboard.md"} + # and a fresh run does not re-flag the dismissed draft + res = _shipped.detect(mind, organism["root"], pr_cache=organism["cache"]) + assert "draft/bug/pyautowidget/flange_rattle_under_load.md" not in _flags(res) + + +def test_dashboard_renders_a_looks_shipped_section_and_feed(organism): + _apply(organism) + c = _intake.census(organism["mind"]) + assert len(c["looks_shipped"]) == 4 + md = _intake.render_dashboard(c) + assert "## Looks shipped — confirm" in md + assert "witness-exists" in md and "lifecycle.py close" in md + # flagged drafts are not offered as picks + start = md.split("## Start here", 1)[1].split("## Epics", 1)[0] + assert "sprocket_guard.md" not in start + assert "sprocket_flange_gear_polish.md" in start + html = _intake.render_dashboard_html(c) + assert "Looks shipped — confirm" in html + state = json.loads(_intake.render_state(c)) + assert _state.validate_state(state) == [] + texts = [i["text"] for i in state["items"]] + assert sum(t.startswith("looks shipped — confirm") for t in texts) == 4 + + +def test_batch_plan_drops_looks_shipped_drafts(organism): + mind = organism["mind"] + _apply(organism) + d = _batch.plan(_batch.survey(mind), budget=600, session_lane="local-dev") + rejected = dict(d["rejected"]) + planned = {m["path"] for m in d["members"]} + for path in _flags(_apply(organism)): + assert path not in planned + assert rejected[path].startswith("looks shipped") + assert "draft/feature/pyautowidget/sprocket_flange_gear_polish.md" in planned + # A dismissal returns the draft to the pool. + (mind / _shipped.DISMISS_FILE).write_text( + "- `draft/bug/pyautowidget/flange_rattle_under_load.md` — not it\n", + encoding="utf-8") + d = _batch.plan(_batch.survey(mind), budget=600, session_lane="local-dev") + assert "draft/bug/pyautowidget/flange_rattle_under_load.md" in { + m["path"] for m in d["members"]} diff --git a/tests/test_intake_memory.py b/tests/test_intake_memory.py index 56f3d71e..c3e99fe5 100644 --- a/tests/test_intake_memory.py +++ b/tests/test_intake_memory.py @@ -43,13 +43,24 @@ def _memory(tmp_path: Path) -> Path: (mem / "wiki" / "methods" / "sources").mkdir(parents=True) (mem / "wiki" / "lensing" / "concepts" / "subhalo.md").write_text( "# Subhalo\n\nsubhalo subhalo substructure lensing detection " - "sensitivity\n", encoding="utf-8") + "sensitivity function\n", encoding="utf-8") (mem / "wiki" / "methods" / "sources" / "sensitivity.md").write_text( "# Sensitivity mapping\n\nsensitivity mapping for substructure\n", encoding="utf-8") + # The rest of a real digest: many pages sharing the generic vocabulary of + # any modelling prompt, so those words are not distinctive of any page. + galaxies = mem / "wiki" / "galaxies" / "sources" + galaxies.mkdir(parents=True) + for i in range(20): + (galaxies / f"galaxy_{i}.md").write_text( + f"# Galaxy {i}\n\n" + GENERIC * 5, encoding="utf-8") return mem +GENERIC = ("model fit fitted profile light mass lens galaxy data cost report " + "from can add produced map write\n") + + def _file_one(mind: Path, raw: str = RAW) -> str: decision = _intake.analyse(raw, "test") rel = _intake.write_prompt(mind, decision, raw, "test") @@ -203,3 +214,84 @@ def test_organ_target_spellings_get_no_memory_line(tmp_path, monkeypatch): assert _intake._cites_memory(spelling), spelling assert _intake._with_memory("Priority: normal", ["wiki/x.md"], spelling).endswith("Memory: wiki/x.md") + + +# --- the score floor ------------------------------------------------------------ +# The digest ranks by raw term counts, so a long page dense in "model", +# "profile" and "fit" topped it for any prompt and got cited on tooling prompts +# with no science question. A page is now cited only when the query terms it +# shares are distinctive in PyAutoMemory (on few of its pages) and weigh enough. + +TOOLING = ("Write compile_repeats from the jax_compile tooling so the model " + "fit profile can report its compile cost.") + + +def _declared_raw(body: str) -> str: + library = sorted(_intake.LIBRARY_REPOS)[0] # any library, read from repos.yaml + return (f"# Library task\n\nType: feature\nTarget: {library}\n" + f"Repos:\n- {library}\n\n{body}\n") + + +def _floor_memory(tmp_path: Path) -> Path: + mem = _memory(tmp_path) + # the page that dominates raw counts for any modelling prompt + (mem / "wiki" / "galaxies" / "sources" / "massive-ellipticals.md").write_text( + "# Massive ellipticals\n\n" + GENERIC * 200, encoding="utf-8") + (mem / "wiki" / "methods" / "concepts").mkdir(parents=True) + (mem / "wiki" / "methods" / "concepts" / "expectation-propagation.md" + ).write_text("# Expectation propagation\n\nexpectation propagation " + "cavity moment matching loggaussian factor graphical\n" + + GENERIC, encoding="utf-8") + return mem + + +def test_vocabulary_only_overlap_gets_no_memory_line(tmp_path, monkeypatch): + """Witness: a library-targeted tooling prompt whose only overlap with the + digest is generic words is filed with no `Memory:` line, even though the + raw-count ranking has hits (massive-ellipticals.md tops it).""" + monkeypatch.delenv("PYAUTO_MEMORY", raising=False) + mind = _mind(tmp_path) + mem = _floor_memory(tmp_path) + raw = _declared_raw(TOOLING) + ranked = _intake._memory.digest(TOOLING, mem, None, None, 3)["pages"] + assert ranked[0]["page"].endswith("massive-ellipticals.md") + decision = _intake.analyse(raw, "test") + assert _intake._cites_memory(decision["target"]) + rel = _intake.write_prompt(mind, decision, raw, "test") + assert "Memory:" not in (mind / rel).read_text(encoding="utf-8") + assert decision["memory"] == [] + + +def test_distinctive_terms_still_get_memory_line(tmp_path, monkeypatch): + """...while a prompt naming a page's distinctive terms still cites it, and + only it: the generic-vocabulary pages stay below the floor.""" + monkeypatch.delenv("PYAUTO_MEMORY", raising=False) + mind = _mind(tmp_path) + _floor_memory(tmp_path) + raw = _declared_raw("Fix the expectation propagation cavity moment matching " + "for a loggaussian factor so the model fit converges.") + decision = _intake.analyse(raw, "test") + rel = _intake.write_prompt(mind, decision, raw, "test") + line = _memory_line((mind / rel).read_text(encoding="utf-8")) + assert line == "Memory: wiki/methods/concepts/expectation-propagation.md" + + +def test_navigation_pages_are_never_cited(tmp_path, monkeypatch): + """reading-queue.md, index.md and a wiki's log.md list sources; they are + not one, however many distinctive terms they share with the prompt.""" + monkeypatch.delenv("PYAUTO_MEMORY", raising=False) + mind = _mind(tmp_path) + mem = _memory(tmp_path) + query = "Einstein ring quasar microlensing caustic crossing" + navs = ("reading-queue.md", "index.md", "wiki/lensing/log.md") + for i, rel in enumerate(navs): + (mem / rel).write_text(f"# Nav {i}\n\n{query}\n" * 10, encoding="utf-8") + assert len(_intake._memory.digest(query, mem, None, None, 9)["pages"]) == 3 + assert _intake.memory_citations(mind, "", query) == [] + # the same text on a source page is cited + (mem / "wiki" / "lensing" / "concepts" / "caustics.md").write_text( + f"# Caustics\n\n{query}\n", encoding="utf-8") + for rel in navs: + (mem / rel).unlink() + assert _intake.memory_citations(mind, "", query) == [ + "wiki/lensing/concepts/caustics.md"]