From d894248c7b087bfd860873b8a13a0fb78af6e1aa Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 24 Aug 2026 21:24:50 +0000 Subject: [PATCH] ci: gate --check-version on removals, and make its report diagnosable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `--check-version` compared a hash of the ENTIRE public surface of autonerves, autoarray, autofit, autocti and autocti.plot against a committed baseline. The assistant documents almost none of that surface, and the workflow installs those libraries from their `main` source clones — so the clock was every upstream merge that exported a name. The red that prompted this was 12 additions and 2 removals, and not one of the 14 symbols was cited anywhere in wiki/, skills/ or modes/. Two changes, and the second is why option 1 beat option 2 (demote the check and let --scope all be the only gate): 1. The baseline now records the sorted public names per module, not just a hash and a count. Previously a red printed exactly "public API surface changed: autoarray, autofit" — undiagnosable. Working out what moved meant creating worktrees at the baseline's own commits, installing the libraries from them, and diffing by hand. That is what the last investigation actually had to do. 449 names, 12 KB. 2. With names available, the gate distinguishes additions from removals. A symbol appearing cannot break a doc; a symbol disappearing can. Additions print and pass; any removal fails and names the symbol. It does NOT narrow further to "removals of cited symbols" — that is exactly what --scope all already computes, and two mechanisms answering one question is how they drift apart. A baseline predating symbol recording keeps the old all-or-nothing behaviour and says so: treating an undiagnosable change as additive would wave a real removal through. A module absent from the baseline entirely is reported distinctly, so adding one to BASELINE_MODULES does not read as "your baseline is old". The regenerated baseline is a pure schema upgrade — every per-module hash and every version is byte-identical to the one PR #23 wrote, so this records no API change, only the names behind the existing hashes. Also writes skills/ac_audit_skill_apis.md, which did not exist. It was an unfinished clone item in PENDING.md, and AGENTS.md, modes/maintainer.md and skills/ac_setup_environment.md all linked to it — five broken links. Written from audit_skill_apis.py itself rather than adapted from the lensing sibling, and it carries the thing the task asked to document: when regenerating the baseline is right and when it is papering over a real break. Verified against the real CTI stack (autonerves/autoarray/autofit 2026.8.17.1 from source main, autocti 2024.11.13.2, arcticpy 2.6) — all five wiki-currency checks pass: --check-version clean, --scope all 31/31 symbols, --lint-idioms 52 files clean, --check-provenance 0 errors, --check-citations 0 missing. Refs #25 Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_014wiN7R1yaeGj6k1Pa1FEq4 --- .claude/skills/ac_audit_skill_apis.md | 1 + AGENTS.md | 10 +- PENDING.md | 4 +- autoassistant/audit_skill_apis.py | 181 +++++++-- autoassistant/tests/test_check_version.py | 238 +++++++++-- skills/README.md | 5 + skills/ac_audit_skill_apis.md | 153 +++++++ wiki/core/api_audit_baseline.json | 469 +++++++++++++++++++++- 8 files changed, 995 insertions(+), 66 deletions(-) create mode 120000 .claude/skills/ac_audit_skill_apis.md create mode 100644 skills/ac_audit_skill_apis.md diff --git a/.claude/skills/ac_audit_skill_apis.md b/.claude/skills/ac_audit_skill_apis.md new file mode 120000 index 0000000..1796143 --- /dev/null +++ b/.claude/skills/ac_audit_skill_apis.md @@ -0,0 +1 @@ +../../skills/ac_audit_skill_apis.md \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index fc489e6..977077a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,9 +19,13 @@ ask one focused question — never default to the longest possible explanation. ```bash python autoassistant/audit_skill_apis.py --check-version ``` - Exit 0 = documented API matches the stack. Exit 1 = genuine drift: recommend the pinned - version or an audit. Exit 2/3 = absent/broken stack: report the interpreter and route to - [`ac_setup_environment`](./skills/ac_setup_environment.md). See + Exit 0 = nothing the docs can depend on has gone missing. It may still print an + `additions only (not gated)` diff — new upstream exports are reported, not failed, since + a symbol appearing cannot break a doc. Exit 1 = a symbol was **removed** from the public + surface: it names which, so run `--scope all` to see whether any is actually cited before + concluding anything. Exit 2/3 = absent/broken stack: report the interpreter and route to + [`ac_setup_environment`](./skills/ac_setup_environment.md). Full detail, and when + regenerating the baseline is right rather than papering over, in [`ac_audit_skill_apis`](./skills/ac_audit_skill_apis.md). Skip by default in maintainer mode. ## Safety invariants — default non-negotiable diff --git a/PENDING.md b/PENDING.md index e970b32..76b31d4 100644 --- a/PENDING.md +++ b/PENDING.md @@ -7,7 +7,7 @@ wiki page or dataset, in the reference's shape. - [ ] `.claude/skills/ac_adaptive_pixelization.md` — regenerate for this domain (reference: `.claude/skills/al_adaptive_pixelization.md`) - [ ] `.claude/skills/ac_aggregator_bulk_analysis.md` — regenerate for this domain (reference: `.claude/skills/al_aggregator_bulk_analysis.md`) -- [ ] `.claude/skills/ac_audit_skill_apis.md` — regenerate for this domain (reference: `.claude/skills/al_audit_skill_apis.md`) +- [x] `.claude/skills/ac_audit_skill_apis.md` — written 2026-08-24 (autocti_assistant#25); a symlink into `skills/`, per the repo's convention - [ ] `.claude/skills/ac_build_imaging_model.md` — regenerate for this domain (reference: `.claude/skills/al_build_imaging_model.md`) - [ ] `.claude/skills/ac_build_interferometer_model.md` — regenerate for this domain (reference: `.claude/skills/al_build_interferometer_model.md`) - [ ] `.claude/skills/ac_chain_searches.md` — regenerate for this domain (reference: `.claude/skills/al_chain_searches.md`) @@ -96,7 +96,7 @@ wiki page or dataset, in the reference's shape. - [ ] `scripts/prepare_cosmos_web_ring.py` — regenerate for this domain (reference: `scripts/prepare_cosmos_web_ring.py`) - [ ] `skills/ac_adaptive_pixelization.md` — regenerate for this domain (reference: `skills/al_adaptive_pixelization.md`) - [ ] `skills/ac_aggregator_bulk_analysis.md` — regenerate for this domain (reference: `skills/al_aggregator_bulk_analysis.md`) -- [ ] `skills/ac_audit_skill_apis.md` — regenerate for this domain (reference: `skills/al_audit_skill_apis.md`) +- [x] `skills/ac_audit_skill_apis.md` — written 2026-08-24 (autocti_assistant#25). Written from `audit_skill_apis.py` itself rather than adapted from the lensing sibling, so it describes this repo's actual checks. - [ ] `skills/ac_build_imaging_model.md` — regenerate for this domain (reference: `skills/al_build_imaging_model.md`) - [ ] `skills/ac_build_interferometer_model.md` — regenerate for this domain (reference: `skills/al_build_interferometer_model.md`) - [ ] `skills/ac_chain_searches.md` — regenerate for this domain (reference: `skills/al_chain_searches.md`) diff --git a/autoassistant/audit_skill_apis.py b/autoassistant/audit_skill_apis.py index 2dfae0b..03b3efc 100644 --- a/autoassistant/audit_skill_apis.py +++ b/autoassistant/audit_skill_apis.py @@ -38,7 +38,7 @@ from dataclasses import dataclass, field from pathlib import Path from types import ModuleType -from typing import Iterable, Optional +from typing import Iterable, Mapping, Optional try: import yaml @@ -753,8 +753,15 @@ def _public_names(mod: ModuleType) -> list[str]: return sorted(n for n in dir(mod) if not n.startswith("_")) +def _api_hash_from_names(names: Iterable[str]) -> str: + """Hash a public-name list. Split out from :func:`_api_hash` so the baseline's + ``hash`` and ``symbols`` provably describe the same list — a test can verify + the shipped baseline is internally consistent without importing the stack.""" + return hashlib.sha256("\n".join(names).encode("utf-8")).hexdigest() + + def _api_hash(mod: ModuleType) -> str: - return hashlib.sha256("\n".join(_public_names(mod)).encode("utf-8")).hexdigest() + return _api_hash_from_names(_public_names(mod)) def compute_baseline() -> dict: @@ -781,7 +788,19 @@ def compute_baseline() -> dict: name ) # already known importable (plot via autocti) names = _public_names(mod) - api_surface[name] = {"hash": _api_hash(mod), "n_symbols": len(names)} + # `symbols` is what makes a red diagnosable. Without it a drift report + # can only say "the surface changed", and reconstructing *what* changed + # means checking out the baseline's own commits, installing the + # libraries from them and diffing by hand — which is exactly what the + # 2026-08-24 investigation had to do. It is also what lets the gate + # distinguish an addition (harmless to a doc) from a removal (not). + # + # `_api_hash` hashes this same sorted list, so the two cannot disagree. + api_surface[name] = { + "hash": _api_hash(mod), + "n_symbols": len(names), + "symbols": names, + } return { "_comment": "API baseline for autocti_assistant - see autoassistant/audit_skill_apis.py " @@ -800,21 +819,61 @@ def write_baseline(root: Path) -> Path: return path +def _surface_diff( + baseline: Mapping, current: Mapping +) -> tuple[dict[str, tuple[list[str], list[str]]], bool]: + """Per-module (added, removed) symbol lists, plus whether names were usable. + + Returns ``({module: (added, removed)}, True)`` when every drifting module in + the baseline recorded its ``symbols`` list. A baseline written before symbol + recording carries only a hash, so no diff is possible; that case returns + ``({}, False)`` and the caller falls back to hash-only reporting rather than + pretending the change was additive. + """ + diffs: dict[str, tuple[list[str], list[str]]] = {} + for name in BASELINE_MODULES: + old_entry = baseline["api_surface"].get(name, {}) + new_entry = current["api_surface"][name] + if old_entry.get("hash") == new_entry["hash"]: + continue + old_symbols = old_entry.get("symbols") + if old_symbols is None: + return {}, False + old_set, new_set = set(old_symbols), set(new_entry["symbols"]) + diffs[name] = (sorted(new_set - old_set), sorted(old_set - new_set)) + return diffs, True + + def check_version(root: Path) -> int: """Compare the installed stack's public API surface against the committed baseline. - Returns 0 when the public-API-surface hashes match, 1 on any hash drift (or a - missing baseline). Prints a short human-readable summary. Intentionally cheap - — no Markdown scan — so it is safe to run at session start. + Returns 0 when nothing was **removed** from the surface, 1 on any removal (or + a missing baseline). Intentionally cheap — no Markdown scan — so it is safe + to run at session start. + + Why removals and not "any change" (autocti_assistant#25). This check used to + fail on any hash difference, i.e. on the entire public surface of autoarray + and autofit, almost none of which this assistant documents. Because the + workflow installs those libraries from their `main` source clones, the clock + was every merge upstream that exported a new name: the red that prompted this + was 12 additions and 2 removals, and **not one of the 14 symbols was cited + anywhere** in wiki/, skills/ or modes/. A gate that goes red on a schedule + nobody controls, for reasons that never affect what it gates, gets ignored — + and this repo's PRs opened red for over a month. + + A symbol *appearing* cannot break a doc; a symbol *disappearing* can. So + additions are reported and pass, removals fail. Note this does not narrow all + the way to "removals of *cited* symbols" — that question is exactly what + `--scope all` already answers, and two mechanisms answering one question is + how they drift apart. The per-module ``__version__`` equality this check used to *gate* on was - dropped (PyAutoMind build-chain #155 Phase 4 task 3). Since PyAutoConf#119 / - PyAutoBuild#121 a release no longer commits the ``__version__`` stamp back to - the library ``main``, so a source checkout reports a frozen stamp while the - baseline is wheel-derived — a structurally-permanent version mismatch, - independent of release cadence, that the API-surface hash already proves is - spurious (the public surface is byte-identical). Versions are still shown for - context; only the API-surface hash gates. + dropped earlier (PyAutoMind build-chain #155 Phase 4 task 3). Since + PyAutoConf#119 / PyAutoBuild#121 a release no longer commits the + ``__version__`` stamp back to the library ``main``, so a source checkout + reports a frozen stamp while the baseline is wheel-derived — a + structurally-permanent mismatch the surface comparison already proves + spurious. Versions are still shown for context. """ path = root / BASELINE_REL_PATH if not path.exists(): @@ -828,8 +887,8 @@ def check_version(root: Path) -> int: current = compute_baseline() # Informational only — a version-stamp difference no longer gates (frozen - # source stamps vs a wheel-derived baseline false-positive; the API-surface - # hash is the real signal). + # source stamps vs a wheel-derived baseline false-positive; the API surface + # is the real signal). version_changes = [ (m, baseline["versions"].get(m, "(absent)"), current["versions"][m]) for m in VERSIONED_MODULES @@ -842,31 +901,93 @@ def check_version(root: Path) -> int: != current["api_surface"][m]["hash"] ] + version_note = "" + if version_changes: + version_note = ( + " (version stamp differs but is not gated: " + + ", ".join(f"{m} {old}->{new}" for m, old, new in version_changes) + + ")" + ) + if not hash_drift: - note = "" - if version_changes: - note = ( - " (version stamp differs but public API surface is identical: " - + ", ".join(f"{m} {old}->{new}" for m, old, new in version_changes) - + ")" - ) print( f"[drift] clean — installed public API surface matches baseline " - f"(autocti {current['versions']['autocti']}, generated {baseline.get('generated')}){note}." + f"(autocti {current['versions']['autocti']}, " + f"generated {baseline.get('generated')}){version_note}." ) return 0 + diffs, have_symbols = _surface_diff(baseline, current) + + if not have_symbols: + # A pre-#25 baseline records only a hash, so additions and removals are + # indistinguishable. Fail — the old, noisy behaviour — rather than guess + # the change was additive and wave through a real removal. + print( + "[drift] API DRIFT vs baseline " + f"(baseline generated {baseline.get('generated')}):", + file=sys.stderr, + ) + print( + f" - public API surface changed: {', '.join(hash_drift)}", + file=sys.stderr, + ) + absent = [m for m in hash_drift if m not in baseline["api_surface"]] + if absent: + print( + f" - not in the baseline at all: {', '.join(absent)} " + "(a module was added to BASELINE_MODULES after it was written)", + file=sys.stderr, + ) + print( + " This baseline cannot support a symbol diff, so added vs removed " + "cannot be told apart and the whole change is treated as gating — " + "assuming it additive would wave a real removal through. Run " + "`--write-baseline` to upgrade it; future reports will name the " + "symbols.", + file=sys.stderr, + ) + return 1 + + removed_modules = [m for m, (_, removed) in diffs.items() if removed] + stream = sys.stderr if removed_modules else sys.stdout + + header = "REMOVALS" if removed_modules else "additions only (not gated)" print( - "[drift] API DRIFT vs baseline " + f"[drift] public API surface moved — {header} " f"(baseline generated {baseline.get('generated')}):", - file=sys.stderr, + file=stream, ) - print(f" - public API surface changed: {', '.join(hash_drift)}", file=sys.stderr) - for m, old, new in version_changes: - print(f" - {m} version: {old} -> {new} (informational)", file=sys.stderr) + for module in sorted(diffs): + added, removed = diffs[module] + counts = ( + f"{baseline['api_surface'][module]['n_symbols']} -> " + f"{current['api_surface'][module]['n_symbols']}" + ) + print(f" {module} {counts}", file=stream) + if removed: + print(f" - removed: {', '.join(removed)}", file=stream) + if added: + print(f" + added: {', '.join(added)}", file=stream) + if version_note: + print(f" {version_note.strip()}", file=stream) + + if not removed_modules: + # Nothing left the surface, so no documented symbol can have stopped + # resolving. `--scope all` remains the check that proves the cited + # symbols are fine. + print( + " Nothing was removed, so no cited symbol can have stopped " + "resolving. Not gating. Run `--write-baseline` to re-pin when " + "convenient — the baseline is stale, not wrong.", + file=stream, + ) + return 0 + print( - " The skills/wiki were validated against the baseline. Run `--scope all` to audit " - "drift and `--write-baseline` to re-pin once fixed.", + " A removed symbol can break a doc that cites it. Run `--scope all` to " + "find out whether any of the above is actually cited, fix or re-word " + "what is, then `--write-baseline` to re-pin.", file=sys.stderr, ) return 1 diff --git a/autoassistant/tests/test_check_version.py b/autoassistant/tests/test_check_version.py index 28fc78d..5326791 100644 --- a/autoassistant/tests/test_check_version.py +++ b/autoassistant/tests/test_check_version.py @@ -1,10 +1,18 @@ -"""test_check_version.py — --check-version gates on the API-surface hash only. +"""test_check_version.py — what --check-version gates on, and what it only reports. -The per-module ``__version__`` equality was dropped (PyAutoMind build-chain #155 -Phase 4 task 3): releases no longer commit the stamp back to library ``main``, so -a source checkout's frozen stamp vs a wheel-derived baseline is a permanent false -positive that the API-surface hash already proves spurious. These tests -monkeypatch ``compute_baseline`` so they need no installed stack. +Two things are deliberately NOT gated: + +* The per-module ``__version__`` equality, dropped in PyAutoMind build-chain #155 + Phase 4 task 3. Releases no longer commit the stamp back to library ``main``, + so a source checkout's frozen stamp vs a wheel-derived baseline is a permanent + false positive that the API-surface comparison already proves spurious. +* **Additions** to the public surface (autocti_assistant#25). The check hashes + the entire public surface of autoarray and autofit, almost none of which this + assistant documents, and the workflow installs those libraries from their + ``main`` source clones — so the clock was every upstream merge that exported a + name. A symbol appearing cannot break a doc; a symbol disappearing can. + +These tests monkeypatch ``compute_baseline`` so they need no installed stack. """ from __future__ import annotations @@ -15,7 +23,32 @@ from autoassistant import audit_skill_apis as a -def _bl(versions, hashes): +def _surface(symbols_by_module): + """Build an ``api_surface`` block whose hash follows from its symbols. + + The real ``compute_baseline`` derives both from one sorted list, so a + fixture that let them disagree would test a state that cannot occur. + """ + return { + module: { + "hash": "h:" + ",".join(sorted(symbols)), + "n_symbols": len(symbols), + "symbols": sorted(symbols), + } + for module, symbols in symbols_by_module.items() + } + + +def _bl(versions, symbols_by_module): + return { + "generated": "2026-08-24", + "versions": versions, + "api_surface": _surface(symbols_by_module), + } + + +def _legacy_bl(versions, hashes): + """A baseline written before symbol recording: hash and count only.""" return { "generated": "2026-07-09", "versions": versions, @@ -23,35 +56,188 @@ def _bl(versions, hashes): } -def _write_baseline(root, versions, hashes): +def _write(root, baseline): path = root / a.BASELINE_REL_PATH path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(_bl(versions, hashes)), encoding="utf-8") + path.write_text(json.dumps(baseline), encoding="utf-8") -def test_version_differs_but_api_surface_matches_is_clean(tmp_path, monkeypatch, capsys): - base_versions = {m: "2026.7.9.1" for m in a.VERSIONED_MODULES} - hashes = {m: "deadbeef" for m in a.BASELINE_MODULES} - _write_baseline(tmp_path, base_versions, hashes) - cur_versions = {m: "2026.7.15.1" for m in a.VERSIONED_MODULES} - monkeypatch.setattr(a, "compute_baseline", lambda: _bl(cur_versions, hashes)) - assert a.check_version(tmp_path) == 0 # was 1 before task 3 +VERSIONS = {m: "2026.8.24.1" for m in a.VERSIONED_MODULES} +MOVED = a.BASELINE_MODULES[-1] + + +def _symbols(**overrides): + base = {m: ["Alpha", "Beta"] for m in a.BASELINE_MODULES} + base.update(overrides) + return base + + +def test_identical_surface_is_clean(tmp_path, monkeypatch, capsys): + _write(tmp_path, _bl(VERSIONS, _symbols())) + monkeypatch.setattr(a, "compute_baseline", lambda: _bl(VERSIONS, _symbols())) + + assert a.check_version(tmp_path) == 0 + assert "clean" in capsys.readouterr().out + + +def test_version_stamp_differs_but_surface_matches_is_clean( + tmp_path, monkeypatch, capsys +): + _write(tmp_path, _bl({m: "2026.7.9.1" for m in a.VERSIONED_MODULES}, _symbols())) + monkeypatch.setattr(a, "compute_baseline", lambda: _bl(VERSIONS, _symbols())) + + assert a.check_version(tmp_path) == 0 # was 1 before build-chain #155 out = capsys.readouterr().out - assert "clean" in out and "public API surface is identical" in out + assert "clean" in out + assert "not gated" in out + + +def test_additions_alone_do_not_gate_and_are_named(tmp_path, monkeypatch, capsys): + """The whole point of #25: eleven new autofit exports must not go red. + + The red that prompted this was 12 additions and 2 removals, none of the 14 + cited anywhere in wiki/, skills/ or modes/. + """ + _write(tmp_path, _bl(VERSIONS, _symbols())) + monkeypatch.setattr( + a, + "compute_baseline", + lambda: _bl(VERSIONS, _symbols(**{MOVED: ["Alpha", "Beta", "Gamma"]})), + ) + + assert a.check_version(tmp_path) == 0 + captured = capsys.readouterr() + assert "additions only (not gated)" in captured.out + assert "+ added: Gamma" in captured.out + # Not gating must not mean not reporting — the drift is still real, and the + # baseline is still stale. + assert "--write-baseline" in captured.out + assert captured.err == "" + + +def test_a_removal_gates_and_names_the_symbol(tmp_path, monkeypatch, capsys): + _write(tmp_path, _bl(VERSIONS, _symbols())) + monkeypatch.setattr( + a, + "compute_baseline", + lambda: _bl(VERSIONS, _symbols(**{MOVED: ["Alpha"]})), + ) + + assert a.check_version(tmp_path) == 1 + err = capsys.readouterr().err + assert "REMOVALS" in err + assert "- removed: Beta" in err + # The old report said only "public API surface changed: ", which is + # why reconstructing the diff needed worktrees at the baseline's commits. + assert MOVED in err + assert "--scope all" in err + + +def test_a_removal_gates_even_alongside_additions(tmp_path, monkeypatch, capsys): + """A module that both gained and lost symbols must still fail.""" + _write(tmp_path, _bl(VERSIONS, _symbols())) + monkeypatch.setattr( + a, + "compute_baseline", + lambda: _bl(VERSIONS, _symbols(**{MOVED: ["Alpha", "Gamma", "Delta"]})), + ) + + assert a.check_version(tmp_path) == 1 + err = capsys.readouterr().err + assert "- removed: Beta" in err + assert "+ added: Delta, Gamma" in err -def test_api_surface_hash_drift_is_flagged(tmp_path, monkeypatch, capsys): - versions = {m: "2026.7.9.1" for m in a.VERSIONED_MODULES} +def test_removal_in_one_module_gates_despite_a_clean_addition_elsewhere( + tmp_path, monkeypatch, capsys +): + other = a.BASELINE_MODULES[0] + assert other != MOVED + _write(tmp_path, _bl(VERSIONS, _symbols())) + monkeypatch.setattr( + a, + "compute_baseline", + lambda: _bl( + VERSIONS, + _symbols(**{MOVED: ["Alpha"], other: ["Alpha", "Beta", "Gamma"]}), + ), + ) + + assert a.check_version(tmp_path) == 1 + err = capsys.readouterr().err + assert "- removed: Beta" in err + assert "+ added: Gamma" in err + + +def test_legacy_baseline_without_symbols_still_gates_on_any_drift( + tmp_path, monkeypatch, capsys +): + """A pre-#25 baseline cannot tell an addition from a removal. + + Treating an undiagnosable change as additive would wave a real removal + through, so the old, noisy behaviour is kept — with a line saying why and + how to upgrade. + """ base_hashes = {m: "deadbeef" for m in a.BASELINE_MODULES} - _write_baseline(tmp_path, versions, base_hashes) - moved = a.BASELINE_MODULES[-1] - cur_hashes = dict(base_hashes) - cur_hashes[moved] = "cafef00d" - monkeypatch.setattr(a, "compute_baseline", lambda: _bl(versions, cur_hashes)) + _write(tmp_path, _legacy_bl(VERSIONS, base_hashes)) + cur_hashes = dict(base_hashes, **{MOVED: "cafef00d"}) + monkeypatch.setattr( + a, "compute_baseline", lambda: _legacy_bl(VERSIONS, cur_hashes) + ) + assert a.check_version(tmp_path) == 1 err = capsys.readouterr().err - assert "public API surface changed" in err and moved in err + assert "public API surface changed" in err and MOVED in err + assert "cannot support a symbol diff" in err + assert "--write-baseline" in err + + +def test_legacy_baseline_with_no_drift_is_still_clean(tmp_path, monkeypatch): + hashes = {m: "deadbeef" for m in a.BASELINE_MODULES} + _write(tmp_path, _legacy_bl(VERSIONS, hashes)) + monkeypatch.setattr(a, "compute_baseline", lambda: _legacy_bl(VERSIONS, hashes)) + + assert a.check_version(tmp_path) == 0 def test_missing_baseline_is_drift(tmp_path): - assert a.check_version(tmp_path) == 1 \ No newline at end of file + assert a.check_version(tmp_path) == 1 + + +def test_shipped_baseline_records_symbols_for_every_module(): + """The committed baseline must be on the new schema, not the legacy path. + + Without this the repo could ship a hash-only baseline and quietly keep the + old all-or-nothing gate while the code claimed otherwise. + """ + root = Path(__file__).resolve().parents[2] + baseline = json.loads( + (root / a.BASELINE_REL_PATH).read_text(encoding="utf-8") + ) + for module in a.BASELINE_MODULES: + entry = baseline["api_surface"][module] + assert entry["symbols"], f"{module} records no symbols" + assert len(entry["symbols"]) == entry["n_symbols"] + assert entry["symbols"] == sorted(entry["symbols"]) + assert entry["hash"] == a._api_hash_from_names(entry["symbols"]) + + +def test_module_absent_from_the_baseline_gates_and_says_so( + tmp_path, monkeypatch, capsys +): + """Adding a module to BASELINE_MODULES must not read as "old baseline". + + It is a different situation with the same symptom — no symbols to diff — and + the report should not send the reader looking for a schema upgrade that is + already done. + """ + new_module = a.BASELINE_MODULES[-1] + partial = _bl(VERSIONS, _symbols()) + del partial["api_surface"][new_module] + _write(tmp_path, partial) + monkeypatch.setattr(a, "compute_baseline", lambda: _bl(VERSIONS, _symbols())) + + assert a.check_version(tmp_path) == 1 + err = capsys.readouterr().err + assert "not in the baseline at all" in err + assert new_module in err diff --git a/skills/README.md b/skills/README.md index d314073..5a526e4 100644 --- a/skills/README.md +++ b/skills/README.md @@ -42,6 +42,11 @@ grown in use. PyAutoCTI stack, **including arcticpy** (the C++ arctic clocking code `import autocti` needs but pip won't install). The #1 setup failure; covers the libgsl-dev + build-deps + arcticpy recipe and the numpy-downgrade trap. +- [`ac_audit_skill_apis.md`](./ac_audit_skill_apis.md) — the mechanical currency + checks that keep these skills and the wiki honest against the installed stack: + the symbol audit, the public-surface gate, the idiom deny-list, provenance and + citation paths. Read it before regenerating the API baseline — it is the + difference between a stale baseline and a genuinely stale doc. ### The CTI calibration pipeline diff --git a/skills/ac_audit_skill_apis.md b/skills/ac_audit_skill_apis.md new file mode 100644 index 0000000..3364ad7 --- /dev/null +++ b/skills/ac_audit_skill_apis.md @@ -0,0 +1,153 @@ +--- +name: ac_audit_skill_apis +description: Run the mechanical currency checks that keep this assistant's skills and wiki honest against the installed PyAutoCTI stack — the symbol audit (--scope), the public-surface gate (--check-version), the idiom deny-list, provenance and citation paths. Covers what wiki-currency runs in CI, and how to tell a stale baseline from a genuinely stale doc before regenerating anything. +--- + +# Auditing the documented API against the installed stack + +Everything in `skills/` and `wiki/core/` is a claim about a library that keeps +moving. `autoassistant/audit_skill_apis.py` is the machine that checks those +claims. It is what the `wiki-currency` workflow runs in CI, what the session-start +protocol in `AGENTS.md` runs locally, and what the PreToolUse code gate calls on +generated Python. + +All commands run from the repo root with the stack importable +(`source activate.sh`). If the stack is missing, fix that first — +[`ac_setup_environment`](./ac_setup_environment.md). + +## The five checks + +`wiki-currency` runs exactly these, in this order, and fails the job if any exits +non-zero: + +| command | what it proves | fails when | +|---|---|---| +| `--check-version` | the installed **public surface** still contains everything the baseline recorded | a symbol was **removed** from `autonerves`, `autoarray`, `autofit`, `autocti` or `autocti.plot` | +| `--scope all` | every symbol **cited** in `skills/`, `wiki/` and `scripts/` resolves in the installed stack | a cited symbol does not resolve | +| `--lint-idioms` | no page uses a construction from the deny-list | a retired idiom survives, even though its constituent symbols still exist | +| `--check-provenance` | each `wiki/core` page's `pinned_commit` is real and reachable, and its `content_sha256` matches its body | a pin is forged or rewritten out of history, or a page was edited after stamping | +| `--check-citations` | every `Project:path` citation resolves to a real file | a cited path moved or was deleted | + +`--scope` also takes `skills`, `wiki` or `scripts` on their own when you want a +narrower run, and `--out ` writes the report instead of printing it. + +Two more entrypoints exist that CI does not run: `--code ""` and +`--file ` validate generated PyAuto\* code against the installed +stack (the code gate — see `AGENTS.md` "Safety invariants"), and +`--install-check` reports whether the stack imports at all. + +## `--check-version`: what it gates on, and why not more + +It compares the installed stack's public API surface against +`wiki/core/api_audit_baseline.json`, which records, per module, the sorted list +of public names, a hash of that list, and a count. + +**It fails on removals only. Additions are reported and pass.** + +That narrowing is deliberate (autocti_assistant#25). The check covers the +*entire* public surface of `autoarray` and `autofit`, and this assistant +documents almost none of it. Worse, the workflow installs those libraries from +their **`main` source clones**, not a release — so the clock is every upstream +merge that exports a new name, which is fast. The red that forced this change +was 12 additions and 2 removals, and **not one of the 14 symbols was cited +anywhere** in `wiki/`, `skills/` or `modes/`. A gate that goes red on a schedule +nobody controls, for reasons that never touch what it gates, gets ignored — and +this repo's PRs opened red for over a month before anyone looked. + +A symbol *appearing* cannot break a doc. A symbol *disappearing* can. So that is +the line. + +It does **not** narrow further to "removals of *cited* symbols". That question is +precisely what `--scope all` already answers, against the real citation set, and +two mechanisms answering one question is how they drift apart. `--check-version` +is the cheap whole-surface tripwire; `--scope all` is the one with a direct +causal link to whether a doc is wrong. + +The per-module `__version__` equality is **not** gated either (it is printed for +context). Since PyAutoConf#119 / PyAutoBuild#121 a release no longer commits the +version stamp back to library `main`, so a source checkout reports a frozen stamp +against a wheel-derived baseline — a permanent mismatch the surface comparison +already proves spurious. + +## Reading a `--check-version` report + +The report names the symbols. A passing one: + +``` +[drift] public API surface moved — additions only (not gated) (baseline generated 2026-08-24): + autofit 160 -> 171 + + added: AbstractClipper, AbstractScaler, ApproxUpdater, ... + Nothing was removed, so no cited symbol can have stopped resolving. Not gating. + Run `--write-baseline` to re-pin when convenient — the baseline is stale, not wrong. +``` + +A failing one: + +``` +[drift] public API surface moved — REMOVALS (baseline generated 2026-08-24): + autoarray 122 -> 121 + - removed: TransformerNUFFTPyNUFFT + A removed symbol can break a doc that cites it. Run `--scope all` to find out + whether any of the above is actually cited, fix or re-word what is, then + `--write-baseline` to re-pin. +``` + +Before autocti_assistant#25 the baseline stored only a hash, so the entire report +was `public API surface changed: autoarray, autofit`. Working out *what* moved +meant creating worktrees at the baseline's own commits, installing the libraries +from them, and diffing the symbol sets by hand. If you see that older wording, the +baseline predates symbol recording — `--write-baseline` upgrades it, and the check +keeps its old all-or-nothing behaviour until you do (an undiagnosable change is +treated as gating rather than assumed additive). + +## Regenerating the baseline — the decision, not the reflex + +`--write-baseline` overwrites `wiki/core/api_audit_baseline.json` from whatever +is installed. It is the right response **only when the drift does not implicate a +documented claim**. Otherwise it converts a true finding into a green tick, which +is strictly worse than the red. + +Work through it in this order: + +1. **Read the diff.** The report names every added and removed symbol. +2. **Additions only?** Regenerating is bookkeeping. The gate already passed; + re-pin whenever convenient. +3. **Anything removed?** Run `--scope all`. If it is clean, no cited symbol + moved and the removal is genuinely irrelevant to this assistant — record + *which* symbols and that they were uncited in the commit message, then + regenerate. +4. **`--scope all` reports a missing symbol?** Stop. The docs are wrong, not the + baseline. Fix the page (or the idiom deny-list, if the construction was + retired rather than the symbol), re-run, and regenerate only once both are + clean. +5. **Regenerate against a stack you trust** — the same source clones CI builds + from. A baseline written against a half-installed stack bakes in placeholders + that read as drift forever. `compute_baseline` refuses to write if any library + fails to import, which catches the worst version of this. + +Say in the commit message which symbols moved and why regenerating was right. +"Regenerate baseline" alone is indistinguishable from papering over a real break. + +## Do not pin to a released stack + +The recurring suggestion is to make `wiki-currency` install a fixed PyPI version +so it stops moving. **Do not.** autocti's PyPI release is the pre-resurrection +`2024.11.13.2`; pinning would grade today's documentation against an API that +predates the work it describes — vacuously green, which is worse than noisily +red. The workflow's install step carries the same note. Considered and rejected +2026-08-24 (`PyAutoMind/complete/2026/08/wiki-currency-baseline-drift.md`). + +The `stack_version` input exists for the *release-time* `workflow_call` path, +where PyAutoHands passes the version actually being released. That is a different +question — "does the wiki match the thing we are about to ship?" — and there a +pin is exactly right. + +## Diagnosing a red run in CI + +The workflow redirects every check into `drift-report.md`, so the job log never +names the failure — read the job summary or the `wiki-drift-report` artifact. The +report header records what was actually installed, including each source tree's +short SHA, so a red is diagnosable after the fact without reproducing the run. + +If the artifact host is unreachable, reproduce locally: build the stack from the +`sources/` clones the way the workflow does and run the five commands above. diff --git a/wiki/core/api_audit_baseline.json b/wiki/core/api_audit_baseline.json index cfc27eb..1dc540d 100644 --- a/wiki/core/api_audit_baseline.json +++ b/wiki/core/api_audit_baseline.json @@ -10,23 +10,482 @@ "api_surface": { "autonerves": { "hash": "7bd5c3b0830f6a87158e90563cd2b65d3484482df75c125376506c160ce1074e", - "n_symbols": 32 + "n_symbols": 32, + "symbols": [ + "Config", + "JSONPriorConfig", + "Path", + "WorkspaceVersionMismatchError", + "cached_property", + "check_version", + "class_path", + "conf", + "default_prior", + "dictable", + "directory_config", + "exc", + "fitsable", + "for_autolens", + "instance", + "is_test_mode", + "jax_wrapper", + "json_prior", + "make_config_for_class", + "output", + "path_for_class", + "setup_colab", + "setup_notebook", + "skip_checks", + "skip_fit_output", + "skip_visualization", + "sys", + "test_mode", + "test_mode_level", + "tools", + "warnings", + "workspace" + ] }, "autoarray": { "hash": "5dfcc5e6825c4d7e53d454efd08e830ec107183c6cc93c06f73358721b7c97f7", - "n_symbols": 122 + "n_symbols": 122, + "symbols": [ + "AbstractDataset", + "AbstractFit", + "AbstractImageMesh", + "AbstractInversion", + "AbstractLinearObjFuncList", + "AbstractMesh", + "AbstractPreloads", + "AbstractRegularization", + "AbstractTriangles", + "Array1D", + "Array2D", + "Array2DRGB", + "ArrayIrregular", + "BorderRelocator", + "Circle", + "Convolver", + "DatasetInterface", + "DatasetModel", + "DeriveGrid1D", + "DeriveGrid2D", + "DeriveIndexes2D", + "DeriveMask1D", + "DeriveMask2D", + "FitDataset", + "FitImaging", + "FitInterferometer", + "Geometry2D", + "Grid1D", + "Grid2D", + "Grid2DContour", + "Grid2DIrregular", + "GridsInterface", + "Header", + "Imaging", + "ImagingSparseOperator", + "Interferometer", + "InterferometerSparseOperator", + "InterpolatorDelaunay", + "InterpolatorDelaunayNN", + "InterpolatorRectangular", + "Inversion", + "InversionImagingMapping", + "InversionImagingSparse", + "InversionInterferometerMapping", + "InversionInterferometerSparse", + "Layout1D", + "Layout2D", + "LinearObj", + "Mapper", + "Mask1D", + "Mask2D", + "MeshGeometryDelaunay", + "MeshGeometryRectangular", + "OverSampler", + "Pixelization", + "Polygon", + "PreloadsImaging", + "PreloadsInterferometer", + "Region1D", + "Region2D", + "Settings", + "SimulatorImaging", + "SimulatorInterferometer", + "Square", + "TransformerDFT", + "TransformerNUFFT", + "Triangle", + "VectorYX2D", + "VectorYX2DIrregular", + "Visibilities", + "VisibilitiesNoiseMap", + "Zoom2D", + "abstract_ndarray", + "conf", + "dataset", + "decorators", + "exc", + "fit", + "fitsable", + "fixtures", + "from_dict", + "from_json", + "geometry", + "grid_dec", + "hdu_list_for_output_from", + "header_obj_from", + "image_mesh", + "interp_2d", + "inversion", + "is_test_mode", + "jax_wrapper", + "layout", + "m", + "mask", + "mesh", + "mock", + "ndarray_via_fits_from", + "ndarray_via_hdu_from", + "numba_util", + "operators", + "output_to_fits", + "output_to_json", + "over_sample", + "plot", + "preloads", + "preprocess", + "reg", + "register_parser", + "settings", + "setup_colab", + "setup_notebook", + "skip_checks", + "skip_fit_output", + "skip_visualization", + "structures", + "test_mode_level", + "to_dict", + "type", + "util", + "validate", + "with_config", + "with_test_mode_segment" + ] }, "autofit": { "hash": "d540d084d0aaa0510332f41e1155217e4ac0e18ef1aad00606283eea187db342", - "n_symbols": 160 + "n_symbols": 160, + "symbols": [ + "Abs", + "AbsoluteWidthModifier", + "AbstractClipper", + "AbstractModel", + "AbstractPaths", + "AbstractPriorModel", + "AbstractScaler", + "Add", + "AggBase", + "AggregateCSV", + "AggregateFITS", + "AggregateImages", + "Aggregator", + "Analysis", + "AnalysisFactor", + "AnnotationPriorModel", + "ApproxUpdater", + "Array", + "AutoCorrelationsSettings", + "BFGS", + "BlackJAXNUTS", + "ClipperNone", + "ClipperPriorBox", + "Collection", + "ComparisonAssertion", + "Constant", + "CovarianceInterpolator", + "DatabasePaths", + "DeferredArgument", + "DeferredInstance", + "DiagonalMatrix", + "DirectoryPaths", + "Divide", + "Drawer", + "DynamicUpdater", + "DynestyDynamic", + "DynestyStatic", + "EPAnalysisFactor", + "EPHistory", + "Emcee", + "FactorGraphModel", + "FactorUpdater", + "Fit", + "GaussianPrior", + "GreaterThanLessThanAssertion", + "GreaterThanLessThanEqualAssertion", + "GridList", + "GridSearchAggregator", + "GridSearchResult", + "HierarchicalFactor", + "InitializerBall", + "InitializerParamBounds", + "InitializerParamStartPoints", + "InitializerPrior", + "Instance", + "LBFGS", + "LaplaceOptimiser", + "Latent", + "LinearInterpolator", + "LinearRelationship", + "Log", + "Log10", + "LogGaussianPrior", + "LogUniformPrior", + "Mapper", + "Mod", + "Model", + "ModelInstance", + "ModelMapper", + "ModelObject", + "MultiStartADABelief", + "MultiStartAdam", + "MultiStartGradientConvergence", + "MultiStartLion", + "MultiStartProdigy", + "Multiply", + "NSS", + "Nautilus", + "NonLinearSearch", + "Power", + "Prior", + "PriorVectorized", + "Query", + "RelativeWidthModifier", + "Result", + "ResultsCollection", + "Sample", + "Samples", + "SamplesMCMC", + "SamplesNest", + "SamplesPDF", + "SamplesStored", + "SamplesSummary", + "ScalerNone", + "ScalerPriorWidth", + "SearchGridSearch", + "SearchOutput", + "Sensitivity", + "SettingsSearch", + "SimplerUpdater", + "SplineInterpolator", + "TruncatedGaussianPrior", + "TuplePrior", + "UniformPrior", + "ValueType", + "VisualiseGraph", + "Visualizer", + "WidthModifier", + "Zeus", + "abc", + "aggregator", + "check_version", + "conf", + "database", + "db", + "ex", + "example", + "exc", + "fitsable", + "formatter", + "from_dict", + "from_json", + "graphical", + "hdu_list_for_output_from", + "header_obj_from", + "interpolator", + "is_test_mode", + "jax_wrapper", + "load_from_table", + "m", + "mapper", + "marginalize", + "messages", + "mock", + "ndarray_via_fits_from", + "ndarray_via_hdu_from", + "non_linear", + "output_to_fits", + "output_to_json", + "path_instances_of_class", + "pickle", + "prior", + "register", + "register_parser", + "samples_text", + "save_abc", + "setup_colab", + "setup_notebook", + "skip_checks", + "skip_fit_output", + "skip_visualization", + "test_mode_level", + "text", + "to_dict", + "tools", + "type_", + "util", + "visualise", + "with_config", + "with_test_mode_segment" + ] }, "autocti": { "hash": "32d9b246f2472e3a479cb2e5728e91e877c2cf472a9888cfd6632fc9947f8b7d", - "n_symbols": 103 + "n_symbols": 103, + "symbols": [ + "AnalysisCTI", + "AnalysisDataset1D", + "AnalysisImagingCI", + "Array1D", + "Array2D", + "ArrayIrregular", + "CCD", + "CCDPhase", + "CTI1D", + "CTI2D", + "Clocker1D", + "Clocker2D", + "Dataset1D", + "Extract1DEPER", + "Extract1DFPR", + "Extract1DMaster", + "Extract1DOverscan", + "Extract2DMaster", + "Extract2DParallelCalibration", + "Extract2DParallelEPER", + "Extract2DParallelFPR", + "Extract2DParallelOverscan", + "Extract2DParallelPedestal", + "Extract2DParallelPreInjection", + "Extract2DSerialCalibration", + "Extract2DSerialEPER", + "Extract2DSerialFPR", + "Extract2DSerialOverscan", + "Extract2DSerialOverscanNoEPER", + "Extract2DSerialPrescan", + "FitDataset1D", + "FitImagingCI", + "Header", + "HyperCINoiseCollection", + "HyperCINoiseScalar", + "Imaging", + "ImagingCI", + "Layout1D", + "Layout2DCI", + "Mask1D", + "Mask2D", + "PixelBounce", + "ROE", + "ROEChargeInjection", + "ReadoutPersistence", + "Region1D", + "Region2D", + "ResultDataset1D", + "ResultImagingCI", + "SettingsCTI1D", + "SettingsCTI2D", + "SettingsExtract", + "SettingsImagingCI", + "SettingsMask1D", + "SettingsMask2D", + "SimulatorCosmicRayMap", + "SimulatorDataset1D", + "SimulatorImagingCI", + "TrapInstantCapture", + "TrapInstantCaptureContinuum", + "TrapSlowCapture", + "TrapSlowCaptureContinuum", + "acs", + "agg", + "aggregator", + "charge_injection", + "clocker", + "conf", + "cosmics", + "dataset_1d", + "euclid", + "exc", + "extract", + "fitsable", + "from_dict", + "from_json", + "hdu_list_for_output_from", + "header_obj_from", + "instruments", + "is_test_mode", + "jax_wrapper", + "layout", + "m", + "mask", + "mock", + "model", + "ndarray_via_fits_from", + "ndarray_via_hdu_from", + "output_to_fits", + "output_to_json", + "plot", + "preloads", + "preprocess", + "setup_colab", + "setup_notebook", + "skip_checks", + "skip_fit_output", + "skip_visualization", + "test_mode_level", + "to_dict", + "util", + "with_config", + "with_test_mode_segment" + ] }, "autocti.plot": { "hash": "a589671b0d00039c63e4dcb6fb00465857bf090e5d86a2f142fe6ab3a188f0e4", - "n_symbols": 32 + "n_symbols": 32, + "symbols": [ + "PlotterDataset1D", + "PlotterImagingCI", + "corner_anesthetic", + "corner_cornerpy", + "figure_dataset_1d_data", + "figure_fit_ci_region", + "figure_fit_dataset_1d", + "figure_imaging_ci_data_region", + "figure_pre_cti_data_residual_map", + "fits_fit_ci", + "fits_fit_dataset_1d", + "log_likelihood_vs_iteration", + "output_figure", + "plot_array", + "plot_cti_1d", + "plot_yx", + "subplot_dataset_1d", + "subplot_dataset_1d_list", + "subplot_fit_ci", + "subplot_fit_ci_list", + "subplot_fit_ci_region", + "subplot_fit_ci_region_list", + "subplot_fit_dataset_1d", + "subplot_fit_dataset_1d_list", + "subplot_imaging_ci", + "subplot_imaging_ci_data_binned", + "subplot_imaging_ci_data_region_list", + "subplot_imaging_ci_list", + "subplot_imaging_ci_region", + "subplot_noise_scaling_map_dict", + "subplot_parameters", + "subplot_save" + ] } } }