diff --git a/.github/workflows/colab-contexts.yml b/.github/workflows/colab-contexts.yml new file mode 100644 index 0000000..efc9850 --- /dev/null +++ b/.github/workflows/colab-contexts.yml @@ -0,0 +1,35 @@ +# Colab-contexts check — colab/contexts.yaml stays loadable by the release. +# +# At release time PyAutoHands stamps every autofit_workspace and HowToFit notebook +# with a Colab Gemini instruction assembled from colab/contexts.yaml (preface + core +# rules + the mapped skills), and fails generation if a mapped skill is missing or an +# instruction exceeds 20,000 characters. This job runs the same checks on every PR, so +# renaming a skill or growing one past the cap fails here, beside the change, rather +# than in the release. See autoassistant/colab_contexts.py. +name: colab-contexts + +on: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + colab-contexts: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install PyYAML + pytest + run: python -m pip install PyYAML pytest + + - name: Every mapped skill exists and every entry fits the cap + run: python -m autoassistant.colab_contexts check + + - name: Mapping tests + run: python -m pytest -q autoassistant/tests/test_colab_contexts.py diff --git a/Makefile b/Makefile index 5d13da9..dcb8304 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: validate-literature-citations audit test +.PHONY: validate-literature-citations audit test colab-contexts validate-literature-citations: python -m autoassistant.literature validate-citations @@ -10,3 +10,7 @@ audit: # Assistant tooling test suite (slow: the gate tests import autofit per case). test: python -m pytest autoassistant/tests -q + +# colab/contexts.yaml: mapped skills exist and every entry fits the 20k Gemini cap. +colab-contexts: + python -m autoassistant.colab_contexts check diff --git a/autoassistant/colab_contexts.py b/autoassistant/colab_contexts.py new file mode 100644 index 0000000..c00e34d --- /dev/null +++ b/autoassistant/colab_contexts.py @@ -0,0 +1,190 @@ +"""Check `colab/contexts.yaml` and stamp this repository's own Colab notebooks with it. + +`colab/contexts.yaml` maps workspace notebook paths to skills. At release time +PyAutoHands (`autohands/build_util.py`, `inject_gemini_instructions`) assembles, for each +generated notebook, the preface + core rules + mapped skills and writes them into the +notebook's metadata as its Colab Gemini instruction (`metadata.colab.aiContexts` + +`selectedAiContext`). Colab's Gemini cannot read this repository; the instruction is how +the skills reach it. + +This module is the assistant's side of that contract, self-contained (PyYAML + stdlib) +because the assistant does not depend on PyAutoHands: + +- ``check`` — every mapped skill exists, none is on the file's ``never_map`` list, and + every entry assembles to at most 20,000 characters. CI runs it on every PR + (``.github/workflows/colab-contexts.yml``), so a renamed skill or an over-long entry + fails here before it can fail a release. +- ``apply`` — stamps one notebook, for notebooks this repository ships itself, keeping the file's JSON layout so the diff touches metadata only. + +The assembly and the instruction id mirror PyAutoHands' ``assemble_gemini_context`` and +``gemini_context_id``; change both or neither. + +Usage: + + python -m autoassistant.colab_contexts check + python -m autoassistant.colab_contexts apply path/to/notebook.ipynb \\ + --name autofit_workspace/notebooks/cookbooks/model.ipynb +""" + +from __future__ import annotations + +import argparse +import fnmatch +import itertools +import json +import sys +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +CONTEXTS_FILE = Path("colab") / "contexts.yaml" +CAP = 20_000 +# A mapping may set its own `cap:` (its skills may be longer) up to this ceiling, the +# size verified in Colab. Mirrors PyAutoHands' GEMINI_CONTEXT_CAP / GEMINI_CONTEXT_CAP_MAX. +CAP_MAX = 50_000 +_ID_URL = "https://github.com/PyAutoLabs/colab-gemini/{project}" + +# ``check`` sizes each entry with this stand-in notebook name, not the entry's glob: the +# rules text embeds the real path, and a glob can be shorter than the paths it matches. +# 240 characters is longer than any workspace notebook path (the longest today is ~110), +# so an entry that passes here cannot fail the release's per-notebook cap on path length. +_PROBE_NAME = "repository/" + "p" * (240 - len("repository/") - len(".ipynb")) + ".ipynb" + + +def load(root: Path = ROOT) -> dict: + import yaml + + return yaml.safe_load((Path(root) / CONTEXTS_FILE).read_text(encoding="utf-8")) + + +def context_id(project: str) -> str: + return str(uuid.uuid5(uuid.NAMESPACE_URL, _ID_URL.format(project=project))) + + +def match(contexts: dict, notebook_name: str) -> tuple[str, list[str]]: + """First matching entry wins (most specific first); else ``default``.""" + for entry in contexts["contexts"]: + if fnmatch.fnmatchcase(notebook_name, entry["match"]): + return entry["match"], list(entry["skills"]) + return "default", list(contexts["default"]["skills"]) + + +def assemble(contexts: dict, notebook_name: str, root: Path = ROOT) -> tuple[str, str]: + """``(entry, text)`` for ``notebook_name`` ("/").""" + label, skills = match(contexts, notebook_name) + repo, _, relpath = notebook_name.partition("/") + sections = [ + contexts["preface"].strip(), + contexts["rules"].replace("{notebook}", relpath).replace("{repo}", repo).strip(), + "# Reference material: assistant skills", + ] + for skill in skills: + text = (Path(root) / "skills" / f"{skill}.md").read_text(encoding="utf-8").strip() + sections.append(f"## Skill: {skill}\n\n{text}") + return label, "\n\n".join(sections) + "\n" + + +def cap_of(contexts: dict) -> int: + """The cap in force: the mapping's `cap:`, else ``CAP``. Raises outside (0, CAP_MAX].""" + cap = contexts.get("cap", CAP) + if isinstance(cap, bool) or not isinstance(cap, int) or not 0 < cap <= CAP_MAX: + raise ValueError(f"cap {cap!r} must be a positive integer no larger than {CAP_MAX}") + return cap + + +def check(root: Path = ROOT) -> list[str]: + """Problems with the mapping; empty when it is sound.""" + contexts = load(root) + problems = [] + for key in ("name", "project", "preface", "rules", "default", "contexts"): + if key not in contexts: + problems.append(f"missing top-level '{key}'") + if problems: + return problems + try: + cap = cap_of(contexts) + except ValueError as exc: + return [str(exc)] + never_map = set(contexts.get("never_map") or []) + entries = [("default", contexts["default"].get("skills") or [])] + [ + (e.get("match"), e.get("skills") or []) for e in contexts["contexts"] + ] + seen = set() + for label, skills in entries: + if not label or not skills: + problems.append(f"entry {label!r} needs both 'match' and 'skills'") + continue + if label in seen: + problems.append(f"entry {label!r} appears twice (the second can never match)") + seen.add(label) + missing = [s for s in skills if not (Path(root) / "skills" / f"{s}.md").is_file()] + if missing: + problems.append(f"entry {label!r} maps missing skill(s): {', '.join(missing)}") + continue + banned = sorted(never_map.intersection(skills)) + if banned: + problems.append(f"entry {label!r} maps never_map skill(s): {', '.join(banned)}") + size = len(_assemble_skills(contexts, _PROBE_NAME, skills, root)) + if size > cap: + problems.append(f"entry {label!r} assembles to {size} characters, over the {cap} cap") + return problems + + +def _assemble_skills(contexts: dict, name: str, skills: list[str], root: Path) -> str: + probe = dict(contexts, contexts=[{"match": "*", "skills": skills}]) + return assemble(probe, name, root)[1] + + +def dump_like(original_text: str, notebook: dict) -> str: + """Serialise ``notebook`` in the JSON layout ``original_text`` uses (metadata-only diffs).""" + original = json.loads(original_text) + newline = "\n" if original_text.endswith("\n") else "" + for indent, ensure_ascii, sort_keys in itertools.product((1, 2, 4), (False, True), (False, True)): + kwargs = dict(indent=indent, ensure_ascii=ensure_ascii, sort_keys=sort_keys) + if json.dumps(original, **kwargs) + newline == original_text: + return json.dumps(notebook, **kwargs) + newline + return json.dumps(notebook, indent=1, ensure_ascii=False, sort_keys=True) + "\n" + + +def apply(notebook_path: Path, notebook_name: str, root: Path = ROOT) -> str: + """Write the instruction for ``notebook_name`` into ``notebook_path``; returns the entry.""" + contexts = load(root) + label, text = assemble(contexts, notebook_name, root) + cap = cap_of(contexts) + if len(text) > cap: + raise ValueError(f"{notebook_name}: entry {label!r} assembles to {len(text)} characters, over {cap}") + original_text = Path(notebook_path).read_text(encoding="utf-8") + notebook = json.loads(original_text) + cid = context_id(contexts["project"]) + colab = notebook.setdefault("metadata", {}).setdefault("colab", {}) + colab.setdefault("aiContexts", {})[cid] = {"id": cid, "name": contexts["name"], "context": text} + colab["selectedAiContext"] = cid + new_text = dump_like(original_text, notebook) + if new_text != original_text: + Path(notebook_path).write_text(new_text, encoding="utf-8") + return label + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="python -m autoassistant.colab_contexts") + sub = parser.add_subparsers(dest="command", required=True) + sub.add_parser("check", help="Validate colab/contexts.yaml") + p_apply = sub.add_parser("apply", help="Stamp one notebook") + p_apply.add_argument("notebook") + p_apply.add_argument("--name", required=True, help='"/"') + args = parser.parse_args(argv) + + if args.command == "check": + problems = check() + for problem in problems: + print(f"colab/contexts.yaml: {problem}", file=sys.stderr) + if not problems: + print(f"colab/contexts.yaml: OK ({len(load()['contexts'])} entries + default, cap {cap_of(load())})") + return 1 if problems else 0 + + print(f"{args.notebook}: {apply(Path(args.notebook), args.name)}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/autoassistant/tests/test_colab_contexts.py b/autoassistant/tests/test_colab_contexts.py new file mode 100644 index 0000000..3efb9db --- /dev/null +++ b/autoassistant/tests/test_colab_contexts.py @@ -0,0 +1,103 @@ +"""Pin `colab/contexts.yaml`: sound mapping, PyAutoHands-identical ids, metadata-only stamping. + +Stdlib + PyYAML, fast: nothing is executed. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from autoassistant import colab_contexts + +NOTEBOOK_NAME = "autofit_workspace/notebooks/cookbooks/model.ipynb" + + +def test_mapping_is_sound(): + assert colab_contexts.check() == [] + + +def test_project_and_name(): + contexts = colab_contexts.load() + assert contexts["project"] == "autofit" + assert contexts["default"]["skills"] + + +def test_context_id_matches_pyautohands(): + # PyAutoHands' build_util.gemini_context_id("autofit") — the id every generated + # autofit_workspace notebook carries. Literal, so a drift on either side fails here. + assert colab_contexts.context_id("autofit") == "745cea84-9c0a-587f-88dd-633d222ca3f3" + + +def test_check_flags_never_map_and_over_cap(tmp_path): + root = tmp_path / "assistant" + (root / "colab").mkdir(parents=True) + (root / "skills").mkdir() + (root / "skills" / "small.md").write_text("small") + (root / "skills" / "maint.md").write_text("maint") + (root / "skills" / "huge.md").write_text("x" * colab_contexts.CAP) + (root / "colab" / "contexts.yaml").write_text( + "name: T\nproject: autofit\npreface: P\nrules: R {notebook} {repo}\n" + "never_map: [maint]\ndefault: {skills: [small]}\ncontexts:\n" + " - {match: a/*, skills: [maint]}\n - {match: b/*, skills: [huge]}\n" + " - {match: c/*, skills: [missing]}\n" + ) + problems = "\n".join(colab_contexts.check(root)) + assert "never_map" in problems and "over the" in problems and "missing" in problems + + +def test_apply_changes_metadata_only(tmp_path): + notebook = { + "cells": [{"cell_type": "markdown", "id": "cell-0", "metadata": {}, "source": ["Hi é"]}], + "metadata": {"colab": {"provenance": []}, "kernelspec": {"name": "python3"}}, + "nbformat": 4, + "nbformat_minor": 5, + } + path = tmp_path / "x.ipynb" + path.write_text(json.dumps(notebook, indent=1, ensure_ascii=False, sort_keys=True) + "\n") + colab_contexts.apply(path, NOTEBOOK_NAME) + first = path.read_text() + colab_contexts.apply(path, NOTEBOOK_NAME) # idempotent + assert path.read_text() == first + stamped = json.loads(first) + assert stamped["cells"] == notebook["cells"] + assert stamped["metadata"]["kernelspec"] == {"name": "python3"} + colab = stamped["metadata"]["colab"] + assert colab["provenance"] == [] + assert colab["selectedAiContext"] == "745cea84-9c0a-587f-88dd-633d222ca3f3" + (entry,) = colab["aiContexts"].values() + assert NOTEBOOK_NAME.split("/", 1)[1] in entry["context"] + assert first.endswith("}\n") and "Hi é" in first + + +def _mini(tmp_path, cap_line=""): + root = tmp_path / "assistant" + (root / "colab").mkdir(parents=True) + (root / "skills").mkdir() + (root / "skills" / "mid.md").write_text("y" * 25_000) + (root / "colab" / "contexts.yaml").write_text( + f"{cap_line}\nname: T\nproject: p\npreface: P\nrules: R {{notebook}} {{repo}}\n" + "default: {skills: [mid]}\ncontexts: []\n" + ) + return root + + +def test_cap_defaults_to_20k(tmp_path): + root = _mini(tmp_path) + assert colab_contexts.cap_of(colab_contexts.load(root)) == colab_contexts.CAP == 20_000 + assert "over the 20000 cap" in "\n".join(colab_contexts.check(root)) + + +def test_custom_cap_honoured(tmp_path): + root = _mini(tmp_path, "cap: 30000") + assert colab_contexts.check(root) == [] + + +@pytest.mark.parametrize("cap", ["50001", "0", "-1", "lots", "true"]) +def test_cap_out_of_range_rejected(tmp_path, cap): + root = _mini(tmp_path, f"cap: {cap}") + assert "no larger than 50000" in "\n".join(colab_contexts.check(root)) + with pytest.raises(ValueError, match="no larger than 50000"): + colab_contexts.cap_of(colab_contexts.load(root)) diff --git a/colab/contexts.yaml b/colab/contexts.yaml new file mode 100644 index 0000000..d56338b --- /dev/null +++ b/colab/contexts.yaml @@ -0,0 +1,169 @@ +# Colab Gemini instructions — which assistant skills travel with which notebook. +# +# Colab's Gemini sidebar cannot read this repository, but it honours per-notebook +# instructions stored in the notebook's metadata (`metadata.colab.aiContexts` + +# `selectedAiContext`). At release time PyAutoHands (`autohands/build_util.py`, +# `inject_gemini_instructions`) writes one such instruction into every generated +# autofit_workspace and HowToFit notebook, assembled from this file: +# +# preface + rules (with {notebook} and {repo} filled in) + each mapped skill's text +# +# The skills stay here (single source); notebooks carry a release-time snapshot only. +# +# Matching +# Each notebook is named "/", e.g. +# "autofit_workspace/notebooks/cookbooks/model.ipynb" or +# "HowToFit/notebooks/chapter_1_introduction/tutorial_1_models.ipynb". +# `match` is an fnmatch glob over that name (`*` also crosses `/`). +# The FIRST entry in `contexts` whose glob matches wins, so entries are written +# most specific first. A notebook no entry matches gets `default`. +# +# Limits +# Every assembled context must stay within 20,000 characters. Generation fails, +# naming the entry, rather than truncating; `python -m autoassistant.colab_contexts +# check` (CI: .github/workflows/colab-contexts.yml) checks every entry here first. +# Skills listed under `never_map` (maintainer and agent-infrastructure skills that +# only make sense with the repository checked out) may not be mapped. +# +# Upkeep: when a skill is added or renamed, or the workspace gains a folder, update +# the entries here and rerun the check; `autohands gemini_context report` lists the +# notebooks that only reach `default`. + +name: PyAutoFit assistant + +# The project key this assistant's own notebooks would be stamped with. It sets the +# instruction's id, so it matches the id PyAutoHands gives autofit_workspace. +project: autofit + +preface: | + These instructions were prepared by the PyAutoFit assistant + (https://github.com/PyAutoLabs/autofit_assistant). The reference material at the + end was written for a coding agent working inside a checkout of that repository. + Here in Google Colab there is no checkout: ignore any step about repository files, + hooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the + PyAutoFit knowledge in that material to help with this notebook. + +rules: | + You are helping someone work through a PyAutoFit notebook ({notebook} in {repo}). + Explain what it does and help them adapt it to their own model and data. + + Core rules: + 1. Stay with this notebook's API. Only use PyAutoFit calls that appear in the + notebook or in the reference material below. Never invent class names, functions + or arguments. If you are unsure whether something exists, say so and suggest + checking with `dir()` or the PyAutoFit docs (https://pyautofit.readthedocs.io). + 2. Real data needs a look first. Before helping fit the user's real data, ask them to + plot it (or print a numerical summary when it cannot be plotted) and ask one + question about known artefacts, outliers or selection effects: unmodelled data + problems are the most common source of biased inference. Simulated data from the + workspace is exempt. + 3. Their likelihood code is theirs. When wrapping the user's likelihood or model code + in an `Analysis` class, never silently change its numerics (no re-parametrisation, + added guards or "fixes"). If it looks wrong, say so and let them decide. + 4. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs + tell you that; ask them to share what they see. + 5. When the answer depends on something you do not know (their data, their goal, what + a cell printed), ask one focused question rather than guessing. + 6. For multi-step projects (their own model and data, a sample of datasets, a paper's + analysis), point them to the PyAutoFit assistant + https://github.com/PyAutoLabs/autofit_assistant, which runs in Claude Code or Codex + with its full skills and safety checks. + +never_map: + - _bootstrap_skill + - _style + - af_audit_skill_apis + - af_ingest_paper + - af_inspect_results_mcp + - af_refresh_api_docs + - af_setup_environment + - af_to_notebook + - af_update_wiki + - contribute-upstream + - feedback + - start-new-project + +default: + skills: [af_wrap_likelihood, af_compose_model] + +contexts: + + # --- autofit_workspace: cookbooks ---------------------------------------------- + - match: autofit_workspace/notebooks/cookbooks/analysis* + skills: [af_wrap_likelihood, af_custom_analysis] + - match: autofit_workspace/notebooks/cookbooks/configs* + skills: [af_configure_search, af_run_search] + - match: autofit_workspace/notebooks/cookbooks/latent_variables* + skills: [af_custom_analysis, af_load_results] + - match: autofit_workspace/notebooks/cookbooks/multi_level_model* + skills: [af_compose_model, af_custom_analysis] + - match: autofit_workspace/notebooks/cookbooks/multiple_datasets* + skills: [af_custom_analysis, af_wrap_likelihood] + - match: autofit_workspace/notebooks/cookbooks/model* + skills: [af_compose_model, af_wrap_likelihood] + - match: autofit_workspace/notebooks/cookbooks/result* + skills: [af_load_results, af_plot_fit] + - match: autofit_workspace/notebooks/cookbooks/samples* + skills: [af_load_results, af_plot_fit] + - match: autofit_workspace/notebooks/cookbooks/search* + skills: [af_configure_search, af_run_search] + + # --- autofit_workspace: features ----------------------------------------------- + - match: autofit_workspace/notebooks/features/search_chaining* + skills: [af_chain_searches, af_run_search] + - match: autofit_workspace/notebooks/features/expectation_propagation* + skills: [af_compose_model, af_custom_analysis, af_chain_searches] + - match: autofit_workspace/notebooks/features/graphical_models* + skills: [af_compose_model, af_custom_analysis, af_chain_searches] + - match: autofit_workspace/notebooks/features/model_comparison* + skills: [af_load_results, af_configure_search] + - match: autofit_workspace/notebooks/features/search_grid_search* + skills: [af_configure_search, af_simulate_dataset] + - match: autofit_workspace/notebooks/features/sensitivity_mapping* + skills: [af_simulate_dataset, af_configure_search] + - match: autofit_workspace/notebooks/features/interpolate* + skills: [af_load_results, af_chain_searches] + - match: autofit_workspace/notebooks/features/shared_analysis_state* + skills: [af_custom_analysis, af_wrap_likelihood] + + # --- autofit_workspace: overview, plotting, searches, simulators, projects ------ + - match: autofit_workspace/notebooks/overview/overview_2_scientific_workflow* + skills: [af_adapt_to_domain, af_wrap_likelihood] + - match: autofit_workspace/notebooks/overview/overview_3_statistical_methods* + skills: [af_configure_search, af_chain_searches] + - match: autofit_workspace/notebooks/overview/* + skills: [af_wrap_likelihood, af_compose_model] + - match: autofit_workspace/notebooks/plot/* + skills: [af_plot_fit, af_load_results] + - match: autofit_workspace/notebooks/searches/start_point* + skills: [af_configure_search, af_chain_searches] + - match: autofit_workspace/notebooks/searches/* + skills: [af_configure_search, af_run_search] + - match: autofit_workspace/notebooks/simulators/* + skills: [af_simulate_dataset, af_compose_model] + - match: autofit_workspace/projects/* + skills: [af_wrap_likelihood, af_compose_model] + + # --- HowToFit ------------------------------------------------------------------ + - match: HowToFit/start_here.ipynb + skills: [af_wrap_likelihood, af_compose_model] + - match: HowToFit/notebooks/chapter_1_introduction/tutorial_1_models* + skills: [af_compose_model, af_simulate_dataset] + - match: HowToFit/notebooks/chapter_1_introduction/tutorial_2_fitting_data* + skills: [af_wrap_likelihood, af_compose_model] + - match: HowToFit/notebooks/chapter_1_introduction/tutorial_3_non_linear_search* + skills: [af_configure_search, af_run_search] + - match: HowToFit/notebooks/chapter_1_introduction/tutorial_4_why_modeling_is_hard* + skills: [af_debug_fit_failure, af_configure_search] + - match: HowToFit/notebooks/chapter_1_introduction/tutorial_5_results_and_samples* + skills: [af_load_results, af_plot_fit] + - match: HowToFit/notebooks/chapter_1_introduction/tutorial_6_gradients* + skills: [af_configure_search, af_run_search] + - match: HowToFit/notebooks/chapter_1_introduction/tutorial_8_scientific_workflow* + skills: [af_adapt_to_domain, af_wrap_likelihood] + - match: HowToFit/notebooks/chapter_1_introduction/* + skills: [af_wrap_likelihood, af_compose_model] + - match: HowToFit/notebooks/chapter_advanced/* + skills: [af_compose_model, af_custom_analysis, af_chain_searches] + - match: HowToFit/notebooks/simulators/* + skills: [af_simulate_dataset, af_compose_model] diff --git a/modes/maintainer.md b/modes/maintainer.md index e89cfbb..845c5d6 100644 --- a/modes/maintainer.md +++ b/modes/maintainer.md @@ -81,8 +81,9 @@ The embedded report template/invitation remain owned by Brain. + `benchmarks/RESULTS.md` (each domain writes its own prompt cards and regenerates the report from empty runs). - **Mixed** — copied then adapted (named substitutions, then domain tuning): `config/*`, - `llms.txt` / `llms-full.txt`, and `benchmarks/README.md` (generic protocol, domain - table). + `llms.txt` / `llms-full.txt`, `benchmarks/README.md` (generic protocol, domain + table), and `colab/contexts.yaml` (preface and rules shape generic, skill mapping + domain; a newborn remaps it to its own skills and workspace). Generated `.codex/skills/*/SKILL.md` wrappers are **domain** for cloning: their namespace and targets belong to this assistant, so they must never be copied