diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3647e7de..7a56a2e9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,27 +6,6 @@ on: pull_request: jobs: - lint: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: astral-sh/setup-uv@v5 - # Scoped to the tested template code; the personal-kit tree under - # claude/ is copy-paste material and not lint-enforced. - - name: ruff check - run: uvx ruff check tests templates/research/check_research_pins.py - - name: ruff format - run: uvx ruff format --check tests templates/research/check_research_pins.py - - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: astral-sh/setup-uv@v5 - - name: pytest - # pyyaml: templates/research/check_research_pins.py imports yaml - run: uvx --with pyyaml pytest tests -q - reporting-contract: # Enforce the bundled reporting lib's self-contained + injection-safe # contract shipped with the investment-research-dashboard skill. diff --git a/CLAUDE.md b/CLAUDE.md index 44c213fa..f882e3a1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,7 +2,8 @@ Tom's **personal skills & templates library** — reusable Claude Code components under `claude/` (skills, agents, settings, root-file starters) and -doc/pyproject templates under `templates/`. Browse and copy what you need into +doc/pyproject templates under `templates/`. The research scaffold (pin gate, +line template, research-workflow) is qute-research's, not the kit's. Browse and copy what you need into target repos; a copied skill carries a `PROVENANCE.yaml` stamp (source path, source commit, each file `tracked` or `forked from , reason: …`). @@ -25,10 +26,9 @@ guards, hooks, review/release regime, or plugin skills belong in qute-plugins. | `claude/agents/` | Personal-kit subagents | | `claude/settings/` | Claude Code project settings profiles | | `claude/root-files/` | Root-level CLAUDE.md / AGENTS.md starters | -| `templates/docs/`, `templates/pyproject/`, `templates/settings/`, `templates/research/` | Doc / pyproject / settings starters + the research pin gate | +| `templates/docs/`, `templates/pyproject/`, `templates/settings/` | Doc / pyproject / settings starters | | `docs/playbooks/`, `docs/cheatsheets/`, `docs/prompts/` | Workflows, references, reusable prompts | | `docs/adr/` | Pointer to the plugin ADRs (history in git) | -| `tests/` | Unit tests for `templates/research/check_research_pins.py` | ## Conventions diff --git a/INVENTORY.md b/INVENTORY.md index 106b575b..4edea570 100644 --- a/INVENTORY.md +++ b/INVENTORY.md @@ -98,7 +98,6 @@ them, and qute-essentials depends on it), `brand-sonte` (archived project). | Path | Use case | |---|---| | `templates/docs/adr-template.md` | ADR (architectural decision record) starter | -| `templates/docs/agents-research-workflow.md` | Standard research regime for lab repos (`docs/agents/research-workflow.md` starter) | | `templates/docs/agents-issue-tracker.md` | Tracker binding starter (`docs/agents/issue-tracker.md`; machine marker + Linear/GitHub division) | | `templates/WORKFLOW.md` | Symphony/Elixir-style orchestrator contract (frontmatter + agent prompt routing Matt + qute + docs/agents) | | `templates/docs/prd-template.md` | Product requirements doc starter | @@ -106,5 +105,4 @@ them, and qute-essentials depends on it), `brand-sonte` (archived project). | `templates/docs/user-flows-template.md` | User flows / journey starter | | `templates/pyproject/quant-uv.toml` | Quant `pyproject.toml` (uv + ruff + pyright + pytest, per [osquant 2025](https://osquant.com/papers/python-tooling-in-2025/)) | | `templates/pyproject/webdev-uv.toml` | Webdev `pyproject.toml` (same stack) | -| `templates/research/` | Canonical research pin gate `check_research_pins.py` (provenance-on-conclude; unit-tested in `tests/`) + research-line `_template/` | | `templates/settings/*.json` | Settings starters (mirror of `claude/settings/`) | diff --git a/README.md b/README.md index 7ce0b213..09c97b68 100644 --- a/README.md +++ b/README.md @@ -40,11 +40,11 @@ cp ~/workspace/projects/qute-code-kit/claude/settings/project-quant.json ~/proje ## Templates: `templates/` -Doc starters (ADR, PRD, tech spec, user flows, research-workflow and -issue-tracker bindings), `pyproject.toml` starters (quant / webdev, uv + ruff + -pyright + pytest), a `WORKFLOW.md` orchestrator contract, settings profiles, -and the canonical research gate `templates/research/check_research_pins.py` -(unit-tested in `tests/`). +Doc starters (ADR, PRD, tech spec, user flows, issue-tracker binding), +`pyproject.toml` starters (quant / webdev, uv + ruff + pyright + pytest), a +`WORKFLOW.md` orchestrator contract, and settings profiles. The research +scaffold — pin gate, line template, research-workflow — lives in the +qute-research plugin (`templates/research-scaffold/`), stamped by `onboard repo`. ## Browse diff --git a/conductor.yml b/conductor.yml index b407d456..0634b2fc 100644 --- a/conductor.yml +++ b/conductor.yml @@ -72,13 +72,12 @@ turns: # ── Auto-classification signals (consumed by the #159 classifier) ──────────── # The classifier reads these to bucket a change into a rigor tier. This repo's -# risky surfaces are the CI workflow and the tested research gate (the plugin + -# release tooling moved to qute-platform 2026-07-29). +# risky surface is the CI workflow (the plugins and the research gate live in +# qute-plugins: the gate moved to qute-research 2026-09-28, TOM-1221). classify: trivial_globs: ["**/*.md", "docs/**", "**/CHANGELOG*"] complex_globs: - ".github/workflows/**" - - "templates/research/check_research_pins.py" trivial_max_lines: 15 # ── Wave 1a workflow-policy fields (obsidian-vaults#162) ───────────────────── @@ -115,7 +114,6 @@ reviewEngine: multiRun: 1 riskyPaths: - ".github/workflows/**" - - "templates/research/check_research_pins.py" mode: auto dispatcherUrl: "" verdictPrefix: "" diff --git a/pyproject.toml b/pyproject.toml deleted file mode 100644 index baf5cbaf..00000000 --- a/pyproject.toml +++ /dev/null @@ -1,13 +0,0 @@ -# This repo is a personal skills + templates library, not a Python package -# and (since 2026-07-29) no longer a plugin marketplace — the qute-essentials -# plugin, its manifests, and its release tooling moved to tomlupo/qute-platform. -# This file exists only to pin the ruff config CI lints with. - -[tool.ruff.lint] -# Pin an explicit, conservative rule set. Without this, `uvx ruff` follows the -# floating ruff version's defaults, which drift and flip rules on/off across -# releases (that broke the CI gate). Core correctness (E/F) + import order (I). -select = ["E", "F", "I"] -# Line length is the formatter's job (`ruff format`); it intentionally leaves -# long strings/URLs/comments, so E501 on top is redundant noise. -ignore = ["E501"] diff --git a/templates/docs/agents-research-workflow.md b/templates/docs/agents-research-workflow.md deleted file mode 100644 index 06f1ec6d..00000000 --- a/templates/docs/agents-research-workflow.md +++ /dev/null @@ -1,97 +0,0 @@ -# Research workflow - - - -This repo uses one research regime. Agents: read this before any analysis work. - -## The atoms - -- **Research line** — `research//`: a continuous investigation (e.g. `selection`, - `taa`). Long-lived. Own `pyproject.toml` + lockfile pinned to an engine SHA where - applicable (Model C). Line status lives in the line's `README.md` frontmatter: - `status: active | paused | concluded | abandoned | superseded`, plus a - `reproducibility_class` (see below) that the gate enforces on conclude. -- **Finding** — `research//findings/YYYY-MM-DD--.md`: a discrete - result within a line. Verdict is in the filename and frontmatter: - `confirmed | refuted | inconclusive | superseded`. -- **Index** — `research/README.md`: generated from line/finding frontmatter by - `/research-status`. Never hand-edit it. - -## Reproducibility contract (ADR-0007) - -The engine SHA pin freezes the engine *package*. It does **not** freeze the -engine's generated `data/processed/*.parquet` or `config/reference/*.csv` — a lab -reads those live from the sibling checkout by path, so a rename or schema change -floats straight through the pin. Every line therefore declares a -`reproducibility_class` and (where applicable) a hashed data manifest. - -Set `reproducibility_class` in the line README frontmatter to one of four classes. -The gate (`check_research_pins.py`) enforces the "gate on conclude" column only at -`status: concluded` — active/paused lines iterate live; the contract binds at -conclusion. - -| Class | When to use | Gate on conclude | -|---|---|---| -| `pinned` | Default. Reproducible from the engine SHA + hashed data inputs. | `data_inputs.yaml` present with a non-null 64-hex `sha256` on every input, **and** the `provenance` block filled (no `TBD`). | -| `snapshot-frozen` | Inputs can't be re-derived, so they're force-added into the line's `data/` and hashed. | Snapshot input files present under the line **and** a `sha256` for each in `data_inputs.yaml`. | -| `live-data` | Reads an external API / live feed that can't be pinned. | Class set **and** a non-empty `repro_note` explaining why it can't be pinned. | -| `historical` | Concluded before the contract; inputs no longer recoverable. | Class set **and** a `repro_note` documenting the gap honestly. | - -Never fabricate hashes for a `historical`/`live-data` line — an honest `repro_note` -is the intended status, not a green-by-pretending one. - -The `pinned`/`snapshot-frozen` data plane lives in -[`data_inputs.yaml`](../../research/_template/data_inputs.yaml) (filled by -`/research-freeze` or by hand at conclude); read engine reference data through the -line's `ref_resolver.py` so an in-flight engine rename doesn't break it. - -## Finding frontmatter - -```yaml ---- -line: -date: YYYY-MM-DD -verdict: confirmed | refuted | inconclusive | superseded -question: "One sentence: what was tested" -evidence: [path/to/config.yaml, path/to/repro.py, path/to/results.parquet] -# optional gate metrics (autonomous pipeline + serious backtests) -backtest_sharpe: null -dsr_pvalue: null -correlation_max: null -# optional provenance — GATED on conclude for `pinned` lines (ADR-0007). One -# contract: no separate hash-bearing report.md alongside. -provenance: - engine_commit: <40-hex engine SHA> # what the result was produced against - data_inputs: [{path: config/reference/x.csv, sha256: <64-hex>}] - ran_at: YYYY-MM-DD -repro_note: null # required instead of hashes for historical / live-data -promoted_to: null # ADR / PR / wiki slug once promoted ---- -``` - -## Rules of engagement - -1. **No analysis outside a registered line.** Start or resume with `/research-line ` - — it stamps from `research/_template/` and registers the line. Scratch work lives only - in `/scratch/`, and is deletable at any time. -2. **Results are written only via `/finding`.** It forces a verdict and updates the line - rollup + root index in the same action. No loose dated `.md` files in the line root; - no `SESSION_*.md`; no parallel `FINDINGS.md` variants. -3. **Every line ends.** Abandoning is fine — record it (`status: abandoned`, or a final - `inconclusive` finding). Abandoning silently is how research gets lost. -4. **Ideas go to the tracker** declared in `docs/agents/issue-tracker.md` — never to - `RESEARCH_IDEAS.md`, `research-topics.md`, or notes inside line dirs. -5. **Deliverables are not research.** Audience-facing outputs (decks, one-pagers, - dashboards, one-off analyses) go to `reports//`, dated. - Machine run outputs go to `artifacts/`. App prototypes graduate to their own repo. -6. **Promotion is explicit.** A confirmed, material finding goes through `/promote`: - ADR in `docs/adr/` + production PR (or wiki concept / plugin), and the finding's - `promoted_to` is filled. - -## Health - -`/research-status` is the drift detector: index vs. dirs mismatch, lines silent for -N weeks, loose dated files, missing verdicts, non-research dirs under `research/`. -Run it when you feel lost; trust its regenerated index over memory. diff --git a/templates/research/.research-config.yaml b/templates/research/.research-config.yaml deleted file mode 100644 index 93f1a326..00000000 --- a/templates/research/.research-config.yaml +++ /dev/null @@ -1,40 +0,0 @@ -# Research workspace config — read by /research-line, /research-freeze, -# /research-repin, /research-status, and scripts/check_research_pins.py (the CI gate). -# -# Canonical template: qute-code-kit templates/research/.research-config.yaml -# (stamped into the repo root by /setup-qute-repo). Set pin_targets to your engine -# repo(s); the rest works out of the box for the Model C per-line-pinning pattern. - -research_root: research - -# Repos whose commits every research//pyproject.toml must pin to a 40-char SHA. -# `name` is the package (== Python distribution) name; `repo` is the GitHub source. -pin_targets: - - name: # e.g. dm-evo, quantbox - repo: https://github.com// - # extras: [full] # optional, applied as name[extras] - -# Default Python deps every line gets from the template. -default_deps: - - "pandas>=2.2" - - "numpy>=2.0" - - "pyyaml>=6.0" - -# Path to the per-line scaffolding template (resolved relative to this file). -template_dir: research/_template - -# Structural rules — checked by check_research_pins.py. -structural_rules: - forbidden_dirs: [] # production dirs that must not appear in the lab - required_per_research: - - pyproject.toml - - uv.lock - - README.md - require_sha_pins: true - -# Pin-staleness thresholds — reported by /research-status (ADR-0007 #4). A line's pin -# is flagged when it lags the engine default branch past either bound. -staleness: - max_commits: 200 - max_days: 60 - default_branch: main diff --git a/templates/research/_template/.gitignore b/templates/research/_template/.gitignore deleted file mode 100644 index 5c0e9fc4..00000000 --- a/templates/research/_template/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.venv/ -__pycache__/ -scratch/ -artifacts/ diff --git a/templates/research/_template/README.md b/templates/research/_template/README.md deleted file mode 100644 index 35ec3d83..00000000 --- a/templates/research/_template/README.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -line: {{NAME}} -status: active # active | paused | concluded | abandoned | superseded -reproducibility_class: pinned # pinned | snapshot-frozen | live-data | historical -question: "{{DESCRIPTION}}" -started: YYYY-MM-DD -tracker: null -# provenance — optional while active; GATED on conclude for `pinned` lines. -# check_research_pins.py requires engine_commit + ran_at filled (no TBD) at -# status: concluded, alongside hashed data_inputs.yaml. -provenance: - engine_commit: TBD # 40-hex engine SHA the conclusion was produced against - ran_at: TBD # YYYY-MM-DD the reproduction run was taken -# repro_note — REQUIRED on conclude for `historical` / `live-data` lines *instead of* -# hashes: one honest sentence on why this line cannot be pinned. -repro_note: null ---- - -# {{NAME}} - -{{DESCRIPTION}} - -## Reproducibility class - -Set `reproducibility_class` in the frontmatter above to one of: - -| Class | Meaning | Gate on conclude | -|---|---|---| -| `pinned` | Reproducible from the engine SHA + hashed data inputs. | `data_inputs.yaml` present with a non-null `sha256` on every input, **and** `provenance` filled (no `TBD`). | -| `snapshot-frozen` | Inputs can't be re-derived, so they're force-added into `data/` and hashed. | Snapshot input files present under the line **and** a `sha256` for each in `data_inputs.yaml`. | -| `live-data` | Reads an external API / live feed that can't be pinned. | Class set **and** a non-empty `repro_note` saying why it can't be pinned. | -| `historical` | Concluded before this contract; inputs no longer recoverable. | Class set **and** a `repro_note` documenting the gap honestly. | - -The gate (`check_research_pins.py`) enforces this only at `status: concluded`. -Active / paused lines are exempt — iterate live against the sibling checkout; the -contract binds at conclusion. Never fabricate hashes for a `historical`/`live-data` -line — document the gap in `repro_note` instead. - -## Data inputs - -[`data_inputs.yaml`](data_inputs.yaml) declares every engine file this line reads -and its `sha256` at pin time — the data plane the engine SHA pin does *not* cover. -Fill hashes with `/research-freeze` (or by hand at conclude). - -Read engine reference data through [`ref_resolver.py`](ref_resolver.py) so an -in-flight engine rename doesn't break the line: - -```python -from ref_resolver import resolve - -master = resolve( - engine_root, - "config/reference/instrument_master.csv", # new name first - "config/reference/fund_master.csv", # fallback during a rename -) -``` - -## Pinned dependencies - -`pyproject.toml` pins the engine to a 40-char SHA (Model C). `/research-line` -stamps the current SHA; `/research-repin` re-resolves it and refreshes the hashes. - -## Findings - -Results are written **only** via `/finding` → -`findings/YYYY-MM-DD--.md`. Scratch work lives in `scratch/` and is -deletable at any time. diff --git a/templates/research/_template/data_inputs.yaml b/templates/research/_template/data_inputs.yaml deleted file mode 100644 index 1c89f955..00000000 --- a/templates/research/_template/data_inputs.yaml +++ /dev/null @@ -1,20 +0,0 @@ -# data_inputs.yaml — the data plane of this line's reproducibility contract. -# -# The engine SHA pin (pyproject.toml) freezes the engine *package*. It does NOT -# freeze the engine's generated data/config — a lab reads those live from the -# sibling checkout by path, so a rename or schema change floats straight through -# the pin. Declare every engine file this line consumes and its sha256 at pin time -# here, so the data plane is part of the contract instead of an unpinned live read. -# -# Filled by `/research-freeze` (or by hand at conclude). The provenance-on-conclude -# gate (check_research_pins.py) REQUIRES a non-null 64-hex sha256 on every input for -# a concluded line whose reproducibility_class is `pinned` or `snapshot-frozen`. -# `historical` / `live-data` lines are exempt from hashes — they carry a repro_note -# in the line README instead. - -engine: # dm-evo, quantbox-datasets, … -inputs: - - path: config/reference/.csv - sha256: TBD # 64-hex; `/research-freeze` fills this - # - path: data/processed//.parquet - # sha256: TBD diff --git a/templates/research/_template/findings/.gitkeep b/templates/research/_template/findings/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/templates/research/_template/pyproject.toml b/templates/research/_template/pyproject.toml deleted file mode 100644 index f66a72f6..00000000 --- a/templates/research/_template/pyproject.toml +++ /dev/null @@ -1,18 +0,0 @@ -[project] -name = "{{NAME}}" -version = "1.0.0" -description = "{{DESCRIPTION}}" -requires-python = ">=3.11" -dependencies = [ - # PIN_TARGETS — /research-line stamps current SHAs; /research-repin re-resolves. -{{PIN_TARGETS}} -{{DEFAULT_DEPS}} -] - -[tool.uv] -package = false - -[tool.pytest.ini_options] -markers = [ - "reproduction: slow golden-manifest re-run; /research-repin runs exactly these", -] diff --git a/templates/research/_template/ref_resolver.py b/templates/research/_template/ref_resolver.py deleted file mode 100644 index d1fb39ba..00000000 --- a/templates/research/_template/ref_resolver.py +++ /dev/null @@ -1,34 +0,0 @@ -"""ref_resolver — new-name-first path resolver for engine reference data. - -A quant lab reads reference data (``config/reference/*.csv``, -``data/processed/*.parquet``) from a *live sibling checkout* of its engine repo. -When the engine renames a file (``fund_master.csv`` -> ``instrument_master.csv``) -every hard-coded path breaks even though the engine SHA is pinned — the data plane -is not in the pip package. - -Declare the candidate names new-first and this resolver returns whichever exists in -the given checkout, so a rename in flight doesn't break the line. Promote the winning -name into ``data_inputs.yaml`` once the rename settles. - -Proven pattern: dm-evo-lab ``research/selection-l2-taxonomy/ref_compat.py`` (TOM-132), -generalised here so no line reinvents it. -""" - -from __future__ import annotations - -from pathlib import Path - - -def resolve(engine_root: Path, *candidates: str) -> Path: - """Return the first candidate that exists under ``engine_root`` (new name first). - - Falls back to the last candidate when none exist, so a read fails with a clear - ``FileNotFoundError`` on a known path rather than a silent ``None``. - """ - if not candidates: - raise ValueError("resolve() needs at least one candidate path") - for rel in candidates: - p = engine_root / rel - if p.exists(): - return p - return engine_root / candidates[-1] diff --git a/templates/research/_template/tests/test_reproduces.py.template b/templates/research/_template/tests/test_reproduces.py.template deleted file mode 100644 index e98baae9..00000000 --- a/templates/research/_template/tests/test_reproduces.py.template +++ /dev/null @@ -1,16 +0,0 @@ -"""Reproduction test template — copy to research//tests/test_reproduces.py. - -Mark reproduction tests with ``@pytest.mark.reproduction`` so ``/research-repin`` -can re-run exactly them after moving the engine pin. Fill in the golden capture + -tolerance for your engine, and keep the set of headline metrics whose drift is -research-blocking small. -""" - -from __future__ import annotations - -import pytest - - -@pytest.mark.reproduction -def test_headline_metrics_match_golden() -> None: - pytest.skip("template — copy into research//tests/ and implement") diff --git a/templates/research/check_research_pins.py b/templates/research/check_research_pins.py deleted file mode 100644 index 5b7d22be..00000000 --- a/templates/research/check_research_pins.py +++ /dev/null @@ -1,235 +0,0 @@ -"""Validate research// Model C pins AND the ADR-0007 reproducibility contract. - -Two deterministic layers, no LLM and no network: - -1. **Structural (ADR-0002 / Model C).** Every ``research//pyproject.toml`` pins - each configured ``pin_target`` to a full 40-char git SHA; the required per-line - files exist; forbidden production dirs carry no tracked files. - -2. **Provenance-on-conclude (ADR-0007).** For any line whose README frontmatter is - ``status: concluded``, assert reproducibility keyed on ``reproducibility_class``: - - - ``pinned`` -> data_inputs.yaml exists with a non-null 64-hex sha256 on - every input, AND the provenance fields are filled (no TBD). - - ``snapshot-frozen`` -> declared snapshot inputs present on disk under the line - AND a sha256 for each. - - ``live-data`` / ``historical`` -> EXEMPT from hashes; require the class be set and - a non-empty ``repro_note`` explaining why it can't be pinned. - - Active / paused / abandoned / superseded lines are exempt — the contract binds at - conclusion, so live iteration against the sibling checkout stays allowed. - -Reads ``.research-config.yaml`` at the repo root. Exit 0 if all lines pass; exit 1 -with a precise per-violation report otherwise. - -USAGE: python scripts/check_research_pins.py - -Canonical source: qute-code-kit ``templates/research/check_research_pins.py``, stamped -into consumer repos by ``/setup-qute-repo``. Edit it there, not per-repo. -""" - -from __future__ import annotations - -import re -import subprocess -import sys -from pathlib import Path - -import yaml - -VALID_CLASSES = {"pinned", "snapshot-frozen", "live-data", "historical"} -HASH_CLASSES = {"pinned", "snapshot-frozen"} -NOTE_CLASSES = {"live-data", "historical"} -SHA256_RE = re.compile(r"^[0-9a-f]{64}$") -SHA40_RE = re.compile(r"^[0-9a-f]{40}$") - - -def _parse_frontmatter(md_path: Path) -> dict: - """Return the YAML frontmatter of a markdown file as a dict ({} if none/invalid).""" - if not md_path.exists(): - return {} - text = md_path.read_text() - if not text.startswith("---"): - return {} - parts = text.split("---", 2) - if len(parts) < 3: - return {} - try: - data = yaml.safe_load(parts[1]) - except yaml.YAMLError: - return {} - return data if isinstance(data, dict) else {} - - -def _is_tbd(value: object) -> bool: - """True if a provenance value is unfilled (None / empty / a ``TBD`` placeholder).""" - if value is None: - return True - s = str(value).strip() - return s == "" or s.upper() == "TBD" - - -def _check_provenance_on_conclude(line_dir: Path, fm: dict) -> list[str]: - """ADR-0007 checks for a concluded line, keyed on ``reproducibility_class``.""" - name = line_dir.name - errors: list[str] = [] - - cls = fm.get("reproducibility_class") - if cls is None: - return [ - f"{name}: status=concluded but reproducibility_class is not set " - f"(one of {sorted(VALID_CLASSES)})" - ] - if cls not in VALID_CLASSES: - return [ - f"{name}: invalid reproducibility_class {cls!r} (one of {sorted(VALID_CLASSES)})" - ] - - if cls in NOTE_CLASSES: - if _is_tbd(fm.get("repro_note")): - errors.append( - f"{name}: reproducibility_class={cls} requires a non-empty repro_note " - f"explaining why the line cannot be pinned (do not fabricate hashes)" - ) - return errors - - # HASH_CLASSES: pinned + snapshot-frozen both need data_inputs.yaml + hashes. - di_path = line_dir / "data_inputs.yaml" - if not di_path.exists(): - return [ - f"{name}: reproducibility_class={cls} requires data_inputs.yaml (missing)" - ] - try: - di = yaml.safe_load(di_path.read_text()) or {} - except yaml.YAMLError as exc: - return [f"{name}: data_inputs.yaml is not valid YAML ({exc})"] - - inputs = di.get("inputs") or [] - if not inputs: - errors.append(f"{name}: data_inputs.yaml declares no inputs") - for i, item in enumerate(inputs): - if not isinstance(item, dict): - errors.append(f"{name}: data_inputs.yaml inputs[{i}] is not a mapping") - continue - path = item.get("path", f"") - sha = item.get("sha256") - if _is_tbd(sha) or not SHA256_RE.match(str(sha).strip()): - errors.append( - f"{name}: data_inputs.yaml input {path!r} has no valid sha256 (got {sha!r})" - ) - if cls == "snapshot-frozen": - snap = line_dir / str(item.get("path", "")) - if not snap.exists(): - errors.append( - f"{name}: snapshot-frozen input {path!r} not present under the line " - f"(expected force-added snapshot at {line_dir.name}/{item.get('path', '')})" - ) - - if cls == "pinned": - prov = fm.get("provenance") - if not isinstance(prov, dict) or not prov: - errors.append( - f"{name}: reproducibility_class=pinned requires a filled provenance block " - f"(engine_commit, ran_at)" - ) - else: - if _is_tbd(prov.get("engine_commit")) or not SHA40_RE.match( - str(prov.get("engine_commit", "")).strip() - ): - errors.append( - f"{name}: provenance.engine_commit must be a 40-char engine SHA " - f"on a concluded pinned line (got {prov.get('engine_commit')!r})" - ) - if _is_tbd(prov.get("ran_at")): - errors.append( - f"{name}: provenance.ran_at is unfilled (TBD) on a concluded pinned line" - ) - - return errors - - -def check(root: Path) -> tuple[int, list[str]]: - """Run all checks against ``root``. Return (exit_code, violations).""" - config_path = root / ".research-config.yaml" - if not config_path.exists(): - return 1, [f"{config_path} not found"] - - cfg = yaml.safe_load(config_path.read_text()) or {} - research_root = root / cfg.get("research_root", "research") - pin_targets = {pt["name"] for pt in cfg.get("pin_targets", [])} - rules = cfg.get("structural_rules", {}) - forbidden_dirs = rules.get("forbidden_dirs", []) - required_files = rules.get("required_per_research", []) - require_sha = rules.get("require_sha_pins", True) - - errors: list[str] = [] - - # Rule 1: forbidden dirs at repo root — only count git-TRACKED files, so local - # untracked WIP does not fail CI. - try: - tracked = subprocess.check_output( - ["git", "ls-files"], cwd=root, text=True - ).splitlines() - except (subprocess.CalledProcessError, FileNotFoundError): - tracked = [] - for d in forbidden_dirs: - if any(t.startswith(f"{d}/") for t in tracked): - errors.append( - f"forbidden directory has tracked files: {d}/ (Model C violation — " - f"production code belongs in the engine repo, not the lab)" - ) - - if not research_root.is_dir(): - return (1 if errors else 0), errors - - for line_dir in sorted(research_root.iterdir()): - if not line_dir.is_dir() or line_dir.name.startswith("_"): - continue - - # Rule 2: structural pin + required-file checks (only frozen projects). - pyp = line_dir / "pyproject.toml" - if pyp.exists(): - text = pyp.read_text() - for req in required_files: - if not (line_dir / req).exists(): - errors.append(f"{line_dir.name}: missing required file {req}") - if require_sha: - for pkg in pin_targets: - pattern = re.compile( - rf"{re.escape(pkg)}(?:\[[^\]]+\])?\s*@\s*git\+[^@]+@(\S+?)\"" - ) - m = pattern.search(text) - if not m: - errors.append( - f"{line_dir.name}: pin for {pkg} not found in pyproject.toml" - ) - continue - sha = m.group(1) - if not SHA40_RE.match(sha): - errors.append( - f"{line_dir.name}: {pkg} pinned to {sha!r} — must be a 40-char git SHA" - ) - - # Rule 3 (ADR-0007): provenance-on-conclude, keyed on reproducibility_class. - fm = _parse_frontmatter(line_dir / "README.md") - if fm.get("status") == "concluded": - errors.extend(_check_provenance_on_conclude(line_dir, fm)) - - return (1 if errors else 0), errors - - -def main() -> int: - root = Path(__file__).resolve().parents[1] - code, errors = check(root) - if errors: - print(f"\n{len(errors)} research-contract violations:\n") - for e in errors: - print(f" - {e}") - print() - else: - print("All research lines pass Model C + ADR-0007 reproducibility checks.") - return code - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tests/test_check_research_pins.py b/tests/test_check_research_pins.py deleted file mode 100644 index c1720972..00000000 --- a/tests/test_check_research_pins.py +++ /dev/null @@ -1,210 +0,0 @@ -"""Unit tests for the canonical research gate (templates/research/check_research_pins.py). - -Exercises the ADR-0007 provenance-on-conclude branches with tmp-repo fixtures: -a concluded+pinned line missing hashes FAILS; concluded+historical with a repro_note -PASSES; an active line is exempt; snapshot-frozen requires the snapshot on disk. -""" - -from __future__ import annotations - -import importlib.util -from pathlib import Path - -import pytest - -GATE_PATH = ( - Path(__file__).resolve().parents[1] - / "templates" - / "research" - / "check_research_pins.py" -) - -_spec = importlib.util.spec_from_file_location("check_research_pins", GATE_PATH) -assert _spec and _spec.loader -gate = importlib.util.module_from_spec(_spec) -_spec.loader.exec_module(gate) - -VALID_SHA256 = "a" * 64 -VALID_SHA40 = "b" * 40 - -BASE_CONFIG = """\ -research_root: research -pin_targets: [] -structural_rules: - forbidden_dirs: [] - required_per_research: [] - require_sha_pins: false -""" - - -def _make_repo(tmp_path: Path) -> Path: - (tmp_path / ".research-config.yaml").write_text(BASE_CONFIG) - (tmp_path / "research").mkdir() - return tmp_path - - -def _line(tmp_path: Path, name: str, readme: str) -> Path: - d = tmp_path / "research" / name - d.mkdir(parents=True) - (d / "README.md").write_text(readme) - return d - - -def _run(tmp_path: Path) -> list[str]: - code, errors = gate.check(tmp_path) - assert code == (1 if errors else 0) - return errors - - -def test_active_line_is_exempt(tmp_path: Path) -> None: - _make_repo(tmp_path) - _line(tmp_path, "act", "---\nline: act\nstatus: active\n---\n# act\n") - assert _run(tmp_path) == [] - - -def test_concluded_pinned_missing_hashes_fails(tmp_path: Path) -> None: - _make_repo(tmp_path) - d = _line( - tmp_path, - "pin", - "---\nline: pin\nstatus: concluded\nreproducibility_class: pinned\n" - f"provenance:\n engine_commit: {VALID_SHA40}\n ran_at: 2026-07-24\n---\n# pin\n", - ) - (d / "data_inputs.yaml").write_text( - "engine: dm-evo\ninputs:\n - path: config/reference/x.csv\n sha256: TBD\n" - ) - errors = _run(tmp_path) - assert any("no valid sha256" in e for e in errors), errors - - -def test_concluded_pinned_full_provenance_passes(tmp_path: Path) -> None: - _make_repo(tmp_path) - d = _line( - tmp_path, - "pin", - "---\nline: pin\nstatus: concluded\nreproducibility_class: pinned\n" - f"provenance:\n engine_commit: {VALID_SHA40}\n ran_at: 2026-07-24\n---\n# pin\n", - ) - (d / "data_inputs.yaml").write_text( - f"engine: dm-evo\ninputs:\n - path: config/reference/x.csv\n sha256: {VALID_SHA256}\n" - ) - assert _run(tmp_path) == [] - - -def test_concluded_pinned_tbd_provenance_fails(tmp_path: Path) -> None: - _make_repo(tmp_path) - d = _line( - tmp_path, - "pin", - "---\nline: pin\nstatus: concluded\nreproducibility_class: pinned\n" - "provenance:\n engine_commit: TBD\n ran_at: TBD\n---\n# pin\n", - ) - (d / "data_inputs.yaml").write_text( - f"engine: dm-evo\ninputs:\n - path: config/reference/x.csv\n sha256: {VALID_SHA256}\n" - ) - errors = _run(tmp_path) - assert any("engine_commit" in e for e in errors), errors - - -def test_concluded_historical_with_note_passes(tmp_path: Path) -> None: - _make_repo(tmp_path) - _line( - tmp_path, - "hist", - "---\nline: hist\nstatus: concluded\nreproducibility_class: historical\n" - "repro_note: inputs predate the contract and are unrecoverable\n---\n# hist\n", - ) - assert _run(tmp_path) == [] - - -def test_concluded_historical_without_note_fails(tmp_path: Path) -> None: - _make_repo(tmp_path) - _line( - tmp_path, - "hist", - "---\nline: hist\nstatus: concluded\nreproducibility_class: historical\n" - "repro_note: null\n---\n# hist\n", - ) - errors = _run(tmp_path) - assert any("repro_note" in e for e in errors), errors - - -def test_concluded_live_data_with_note_passes(tmp_path: Path) -> None: - _make_repo(tmp_path) - _line( - tmp_path, - "live", - "---\nline: live\nstatus: concluded\nreproducibility_class: live-data\n" - "repro_note: reads a live external API that cannot be pinned\n---\n# live\n", - ) - assert _run(tmp_path) == [] - - -def test_concluded_without_class_fails(tmp_path: Path) -> None: - _make_repo(tmp_path) - _line( - tmp_path, "noclass", "---\nline: noclass\nstatus: concluded\n---\n# noclass\n" - ) - errors = _run(tmp_path) - assert any("reproducibility_class is not set" in e for e in errors), errors - - -def test_concluded_invalid_class_fails(tmp_path: Path) -> None: - _make_repo(tmp_path) - _line( - tmp_path, - "bad", - "---\nline: bad\nstatus: concluded\nreproducibility_class: whatever\n---\n# bad\n", - ) - errors = _run(tmp_path) - assert any("invalid reproducibility_class" in e for e in errors), errors - - -def test_snapshot_frozen_missing_file_fails(tmp_path: Path) -> None: - _make_repo(tmp_path) - d = _line( - tmp_path, - "snap", - "---\nline: snap\nstatus: concluded\nreproducibility_class: snapshot-frozen\n---\n# snap\n", - ) - (d / "data_inputs.yaml").write_text( - f"engine: dm-evo\ninputs:\n - path: data/frozen.csv\n sha256: {VALID_SHA256}\n" - ) - errors = _run(tmp_path) - assert any("not present under the line" in e for e in errors), errors - - -def test_snapshot_frozen_with_file_passes(tmp_path: Path) -> None: - _make_repo(tmp_path) - d = _line( - tmp_path, - "snap", - "---\nline: snap\nstatus: concluded\nreproducibility_class: snapshot-frozen\n---\n# snap\n", - ) - (d / "data").mkdir() - (d / "data" / "frozen.csv").write_text("col\n1\n") - (d / "data_inputs.yaml").write_text( - f"engine: dm-evo\ninputs:\n - path: data/frozen.csv\n sha256: {VALID_SHA256}\n" - ) - assert _run(tmp_path) == [] - - -def test_template_dir_is_skipped(tmp_path: Path) -> None: - _make_repo(tmp_path) - # A _template with a concluded-looking README must never be gated. - _line( - tmp_path, - "_template", - "---\nline: '{{NAME}}'\nstatus: concluded\n---\n# template\n", - ) - assert _run(tmp_path) == [] - - -def test_missing_config_fails(tmp_path: Path) -> None: - code, errors = gate.check(tmp_path) - assert code == 1 - assert any("not found" in e for e in errors) - - -if __name__ == "__main__": - raise SystemExit(pytest.main([__file__, "-q"])) diff --git a/uv.lock b/uv.lock deleted file mode 100644 index 9431a635..00000000 --- a/uv.lock +++ /dev/null @@ -1,3 +0,0 @@ -version = 1 -revision = 3 -requires-python = ">=3.11"