diff --git a/.agents/context.md b/.agents/context.md new file mode 100644 index 0000000..3d3b3fa --- /dev/null +++ b/.agents/context.md @@ -0,0 +1,348 @@ + + +# AGENTS.md — OpenProblems Spatial Transcriptomics Co-pilot + +> Canonical, provider-neutral instructions for any AI coding agent working in this +> repository (Claude Code, OpenAI Codex, Cursor, GitHub Copilot, and others). +> This is the single source of truth. Tool-specific files (`CLAUDE.md`, +> `.cursor/rules/`, `.github/copilot-instructions.md`) are **generated** from this +> file and the `skills/` directory by `installer/` — do not edit them by hand. + +## What this project is + +A co-pilot for computational biologists working on the +[OpenProblems](https://openproblems.bio) spatial transcriptomics benchmarks. It +ships two things: + +1. **An MCP server** (`src/openproblems_mcp/`) — domain-aware validation and + analysis tools for spatial data and bioinformatics workflows, exposed over the + Model Context Protocol so any MCP-capable agent can call them. +2. **A provider-agnostic skill installer** (`skills/`, `context/`, `installer/`) — + author rules/skills/context once here, then project them into whichever agent + the user runs. + +## Ground truth: which MCP tools actually exist + +Only call tools that are registered. As of now the server is **read-only +analysis** — it validates and inspects, it does **not** execute pipelines. + +**Available now:** +`health_check`, `list_tools_status`, `get_server_info`, +`validate_spatial_data`, `validate_multiple_spatial_files`, +`analyze_spatial_metadata`, `check_spatial_data_compatibility`, +`extract_bioinformatics_metadata`, `analyze_workflow_configuration`, +`assess_data_quality`, `analyze_workflow_dependencies`. + +**Roadmap — NOT implemented, do not call:** +`run_nextflow_workflow`, `run_viash_component`, `build_docker_image`, +`run_nf_test`, `analyze_nextflow_log`, `create_spatial_component`, +`setup_spatial_environment`, and the OpenProblems build/benchmark/submission +tools. For these actions, drive the user's local `nextflow` / `viash` / `docker` +CLIs directly via the terminal instead, and say so plainly. + +## Domain rules (spatial transcriptomics) + +- **Validate before processing.** Run `validate_spatial_data` on any input before + reasoning about it. Distinguish raw counts vs. normalized/log-transformed data — + methods have explicit expectations. +- **Prefer SpatialData/zarr.** The current OpenProblems imaging-based spatial + transcriptomics (iST) benchmark is built on the `SpatialData` (zarr) format; + `.h5ad` AnnData is still used for some tables. See + `context/data-formats.md`. +- **Know the pipeline stages.** The `task_ist_preprocessing` benchmark is a + pipeline: preprocessing → segmentation → transcript assignment → cell-type + annotation → expression correction → normalization → QC filtering → count + aggregation → metrics. See `context/ist-preprocessing-pipeline.md`. +- **Components are Viash.** Methods are packaged as Viash components with a + `config.vsh.yaml` and a script; the namespace is built with `viash ns build`. + See `skills/viash-component-authoring/SKILL.md`. + +## Coding standards + +- **Python**: target 3.10+ (the `fastmcp` dependency requires ≥3.10), format with + `black` (line length 88), lint with `ruff`, type-check with `mypy`. Match + existing module style. +- **Viash components (OpenProblems conventions)**: use the modern flat config + (top-level `name`, `arguments`, `resources`, `engines`, `runners`) — not the + legacy `functionality:` / `platforms:` blocks. Conform to the task's component + API via `__merge__: /src/api/comp_.yaml`. Build on the shared base + images (e.g. `openproblems/base_python:1`) with `__merge__`-ed setup partials, + not raw `python:*` images. Include the standard metadata (`label`, `summary`, + `description`, `links`, `references`). In scripts, keep the + `## VIASH START` / `## VIASH END` block, use `SpatialData` objects for I/O, + handle coordinate systems explicitly, and fail loudly with a non-zero exit. +- **Reproducibility & verification**: pin package versions and base-image tags + (no unpinned `latest`); add a `viash test` unit test (`test_resources`) per + component; document parameters with biological rationale. See + `skills/viash-component-authoring/SKILL.md` and + `skills/openproblems-submission/SKILL.md`. + +## Working in this repo + +- Install dev environment: `pip install -e ".[dev]"` (add `[spatial]` for the + heavy scientific stack: spatialdata, zarr, anndata, h5py). +- Run tests: `python -m pytest` (config lives in `pyproject.toml`; there is no + separate `pytest.ini` or `setup.py`). +- Lint/format/type-check: `ruff check src/`, `black src/`, `mypy src/`. +- Health check the server: `openproblems-mcp check`. +- Run the server (normally launched by the agent host over stdio): + `openproblems-mcp-server`. + +## Skills + +Task-specific playbooks live in `skills//SKILL.md` (shared Claude/Codex +format: YAML frontmatter + markdown). Load the one matching the task: + +- `spatial-data-validation` — validating and inspecting spatial data files. +- `viash-component-authoring` — writing a new Viash method component. +- `nextflow-debugging` — diagnosing Nextflow pipeline failures. +- `openproblems-submission` — preparing a method for an OpenProblems benchmark. + +## Conventions for changes + +- Keep `README.md` and this file honest about what is actually implemented. If + you add or remove a tool, update both (and the tool lists above). +- Do not advertise execution tools as available until they have code and tests. +- New skills go in `skills/` and are surfaced everywhere by re-running the + installer; do not hand-edit the generated provider files. + + +# Skill playbooks + +Load the one matching your task; full text follows. + +--- + + +# Nextflow debugging + +The server does not yet parse logs for you (`analyze_nextflow_log` is roadmap), so +triage the logs directly. Be systematic. + +## Steps + +1. **Find the failing task.** From the run output, note the process name and the + work directory hash (`work/ab/cdef...`). The per-task files there are the + ground truth: + - `.command.sh` — the exact command run. + - `.command.err` / `.command.out` — stderr/stdout. + - `.command.log`, `.exitcode` — exit status. + +2. **Classify the error by exit code / message:** + - **137 / OOM-killed** → memory limit. Increase the process `memory` directive + or add a dynamic retry (`memory { 8.GB * task.attempt }`). + - **127 / "command not found"** → tool missing in the container; fix the + component's engine/setup or the image. + - **126 / permission denied** → executable bit / entrypoint issue. + - **File/path errors** → check channel wiring and input staging; confirm the + input file actually exists and matches the expected format + (run `validate_spatial_data`). + - **Config/DSL errors** → confirm DSL2 syntax; OpenProblems pipelines are DSL2. + +3. **Add resilience** where appropriate: `errorStrategy 'retry'`, `maxRetries`, + and dynamic resources by `task.attempt`. Don't paper over a real bug with + retries. + +4. **Reproduce in isolation.** Re-run a single component with `viash run` on the + test data before re-running the whole pipeline. Use `-resume` to avoid + recomputing successful tasks. + +5. **Validate inputs** with `validate_spatial_data` / `analyze_spatial_metadata` + when the failure looks data-shaped (wrong format, missing elements, + raw-vs-normalized mismatch). + +## Output + +Report: the failing process, the root-cause class, the evidence (the log line), +and the specific fix — plus whether it's a data problem, an environment problem, +or a code problem. + +--- + + +# OpenProblems submission + +Goal: a Viash component that conforms to a task's API, builds cleanly, passes the +test profile, and is reproducible — ready for a PR. + +## Checklist + +1. **Repo setup.** Clone the target `task_*` repo and initialize the `common/` + git submodule (`git submodule update --init --recursive`). Read the repo's + `CONTRIBUTING` / `README` for current conventions. + +2. **Conform to the component API.** Your `config.vsh.yaml` must `__merge__` the + correct `comp_.yaml` interface and match its inputs/outputs and + `info`/metadata fields. Run `analyze_workflow_configuration` on the config. + +3. **Data contract.** Inputs/outputs are SpatialData (zarr) / AnnData as the stage + requires. Validate test data with `validate_spatial_data` and confirm the + elements the stage needs are present (`check_spatial_data_compatibility` for + multi-file). State raw-vs-normalized expectations explicitly. + +4. **Reproducibility.** Build on the shared base images + (`openproblems/base_python:1` / `base_r:1`) with `__merge__`-ed setup + partials rather than raw `python:*`/`r-base` images. Pin base-image tags and + package versions — no unpinned `latest`. Provide the standard metadata + (`label`, `summary`, `description`, `links`, `references`/doi) and document + every parameter with a default and biological rationale. + +5. **Build & test locally** (server doesn't run these — use the terminal): + - `viash ns build` + - `viash run config.vsh.yaml -- --input .zarr --output tmp/out.zarr` + - `viash test config.vsh.yaml` — a unit test (`test_resources`) is expected + for every component + - `nextflow run main.nf -profile test,docker` + +6. **Dependency sanity.** Run `analyze_workflow_dependencies` across the workflow + files to catch missing/conflicting containers or libraries. + +7. **PR hygiene.** Include test data + expected output, document parameter + choices, and confirm CI (GitHub Actions) builds and runs the component. + +## Don't + +- Don't claim the server can build/benchmark/validate-submission automatically — + `build_openproblems_method`, `run_openproblems_benchmark`, and + `validate_openproblems_submission` are roadmap. Use the validation/analysis + tools that exist, and run the build/benchmark steps via local CLIs. + +--- + + +# Spatial data validation + +Validate first, reason second. Never assume a file's format or contents from its +extension. + +## Steps + +1. **Detect & validate format.** Call the MCP tool `validate_spatial_data` with + the file path. Choose `validation_level`: + - `basic` — extension/existence only. + - `structure` (default) — format + structural integrity. + - `integrity` — deeper content checks. + - `domain` — spatial-biology-specific expectations. + For several files, use `validate_multiple_spatial_files`. + +2. **Read the metadata.** Call `analyze_spatial_metadata` to extract dimensions, + spatial coordinates, and gene/feature info. Confirm `obsm['spatial']` (AnnData) + or coordinate systems (SpatialData) are present when spatial analysis is + intended. + +3. **Check raw vs. processed.** Integer-valued matrices are likely raw counts; + non-integer/log-scaled values are processed. State which the downstream method + expects and flag a mismatch. + +4. **Check compatibility** when combining files: `check_spatial_data_compatibility` + (coordinate systems + gene overlap). + +## Key facts (see `context/data-formats.md`) + +- A `.zarr` store is SpatialData **only** if it has SpatialData markers or ≥2 of + `images/ labels/ points/ shapes/ tables/`. Otherwise it's a plain zarr array. +- iST datasets can be terabytes. Default to lightweight structural checks; avoid + loading whole objects. The heavy scientific stack (`pip install -e ".[spatial]"`) + is optional — the validators degrade gracefully without it. + +## Don't + +- Don't claim a file is valid SpatialData without inspecting contents. +- Don't call execution tools (e.g. `run_nextflow_workflow`) — they aren't + implemented. Drive local CLIs directly if execution is needed. + +--- + + +# Viash component authoring + +A Viash component = a `config.vsh.yaml` (metadata: arguments, resources, engines) ++ a script (Python/R/Bash). Viash compiles it into a CLI, a Docker image, and a +Nextflow module. + +## Steps + +1. **Identify the stage and its interface.** OpenProblems components conform to a + `comp_*` API merged in via `__merge__: /src/api/comp_.yaml`. Find the + right interface for the pipeline stage you're implementing (see + `context/ist-preprocessing-pipeline.md`) and match its inputs/outputs exactly. + +2. **Write `config.vsh.yaml`.** Use the modern **flat** config (no + `functionality:` wrapper) with `engines:` / `runners:` (not the legacy + `platforms:`). Follow OpenProblems conventions: merge the stage API, build on + the shared base image with a setup partial, include the standard metadata + block, and label the nextflow runner with resource directives. This mirrors a + real `task_ist_preprocessing` component: + + ```yaml + __merge__: /src/api/comp_.yaml + + name: my_method + label: "My Method" + summary: "One-line biological purpose." + description: "Longer description with method context." + links: + documentation: "https://github.com/openproblems-bio/task_ist_preprocessing" + repository: "https://github.com/openproblems-bio/task_ist_preprocessing" + references: + doi: "10.xxxx/xxxxx" # the method's paper + + arguments: + - name: "--some_param" + type: double + default: 1.0 + description: "Biologically meaningful parameter." + # Note: --input/--output are usually inherited from the merged comp_ API. + + resources: + - type: python_script + path: script.py + + engines: + - type: docker + image: openproblems/base_python:1 # shared base, not raw python:* + __merge__: + - /src/base/setup_spatialdata_partial.yaml # extra deps via setup partial + - type: native + + runners: + - type: executable + - type: nextflow + directives: + label: [ midtime, lowcpu, lowmem ] # resource labels + ``` + + Confirm the exact `__merge__` paths (the stage API and the base setup partial) + and the current Viash schema against the live repo before building — keys + evolve between major Viash versions. + +3. **Write the script** with the dev parameter block: + + ```python + import spatialdata as sd + + ## VIASH START + par = {"input": "resources_test/.../dataset.zarr", "output": "output.zarr", "some_param": 1.0} + ## VIASH END + + sdata = sd.read_zarr(par["input"]) + # ... implement; keep coordinate systems consistent ... + result.write(par["output"]) + ``` + + Fail loudly: log the error and `sys.exit(1)` on failure. + +4. **Validate before building.** Run `analyze_workflow_configuration` on the + `config.vsh.yaml` to catch structural/dependency issues. + +5. **Build & test** with the user's local Viash (the server does not run it): + - `viash ns build` + - `viash run config.vsh.yaml -- --input .zarr --output tmp/out.zarr` + - unit test: add a `test_resources` script (e.g. `test.py`) to the config and + run `viash test config.vsh.yaml` — every OpenProblems component ships a test. + - integration: `nextflow run main.nf -profile test,docker` + +## Don't + +- Don't invent `create_spatial_component` / `build_viash_component` tool calls — + they're roadmap, not implemented. Generate files and run `viash` in the terminal. diff --git a/.agents/mcp_config.json b/.agents/mcp_config.json new file mode 100644 index 0000000..c6989c9 --- /dev/null +++ b/.agents/mcp_config.json @@ -0,0 +1,11 @@ +{ + "mcpServers": { + "openproblems-spatial": { + "command": "openproblems-mcp-server", + "args": [], + "env": { + "OPENPROBLEMS_MCP_LOG_LEVEL": "INFO" + } + } + } +} diff --git a/.agents/skills/nextflow-debugging/SKILL.md b/.agents/skills/nextflow-debugging/SKILL.md new file mode 100644 index 0000000..b091e25 --- /dev/null +++ b/.agents/skills/nextflow-debugging/SKILL.md @@ -0,0 +1,47 @@ +--- +name: nextflow-debugging +description: Diagnose a failing Nextflow pipeline run in an OpenProblems benchmark. Use when a `nextflow run` fails, a process errors out, or the user shares a .nextflow.log / .command.err and asks why it broke. +--- + +# Nextflow debugging + +The server does not yet parse logs for you (`analyze_nextflow_log` is roadmap), so +triage the logs directly. Be systematic. + +## Steps + +1. **Find the failing task.** From the run output, note the process name and the + work directory hash (`work/ab/cdef...`). The per-task files there are the + ground truth: + - `.command.sh` — the exact command run. + - `.command.err` / `.command.out` — stderr/stdout. + - `.command.log`, `.exitcode` — exit status. + +2. **Classify the error by exit code / message:** + - **137 / OOM-killed** → memory limit. Increase the process `memory` directive + or add a dynamic retry (`memory { 8.GB * task.attempt }`). + - **127 / "command not found"** → tool missing in the container; fix the + component's engine/setup or the image. + - **126 / permission denied** → executable bit / entrypoint issue. + - **File/path errors** → check channel wiring and input staging; confirm the + input file actually exists and matches the expected format + (run `validate_spatial_data`). + - **Config/DSL errors** → confirm DSL2 syntax; OpenProblems pipelines are DSL2. + +3. **Add resilience** where appropriate: `errorStrategy 'retry'`, `maxRetries`, + and dynamic resources by `task.attempt`. Don't paper over a real bug with + retries. + +4. **Reproduce in isolation.** Re-run a single component with `viash run` on the + test data before re-running the whole pipeline. Use `-resume` to avoid + recomputing successful tasks. + +5. **Validate inputs** with `validate_spatial_data` / `analyze_spatial_metadata` + when the failure looks data-shaped (wrong format, missing elements, + raw-vs-normalized mismatch). + +## Output + +Report: the failing process, the root-cause class, the evidence (the log line), +and the specific fix — plus whether it's a data problem, an environment problem, +or a code problem. diff --git a/.agents/skills/openproblems-submission/SKILL.md b/.agents/skills/openproblems-submission/SKILL.md new file mode 100644 index 0000000..2ea4e84 --- /dev/null +++ b/.agents/skills/openproblems-submission/SKILL.md @@ -0,0 +1,51 @@ +--- +name: openproblems-submission +description: Prepare a spatial transcriptomics method for contribution to an OpenProblems benchmark (e.g. task_ist_preprocessing). Use when the user wants to submit/contribute a method, open a PR to a task_* repo, or check submission readiness. +--- + +# OpenProblems submission + +Goal: a Viash component that conforms to a task's API, builds cleanly, passes the +test profile, and is reproducible — ready for a PR. + +## Checklist + +1. **Repo setup.** Clone the target `task_*` repo and initialize the `common/` + git submodule (`git submodule update --init --recursive`). Read the repo's + `CONTRIBUTING` / `README` for current conventions. + +2. **Conform to the component API.** Your `config.vsh.yaml` must `__merge__` the + correct `comp_.yaml` interface and match its inputs/outputs and + `info`/metadata fields. Run `analyze_workflow_configuration` on the config. + +3. **Data contract.** Inputs/outputs are SpatialData (zarr) / AnnData as the stage + requires. Validate test data with `validate_spatial_data` and confirm the + elements the stage needs are present (`check_spatial_data_compatibility` for + multi-file). State raw-vs-normalized expectations explicitly. + +4. **Reproducibility.** Build on the shared base images + (`openproblems/base_python:1` / `base_r:1`) with `__merge__`-ed setup + partials rather than raw `python:*`/`r-base` images. Pin base-image tags and + package versions — no unpinned `latest`. Provide the standard metadata + (`label`, `summary`, `description`, `links`, `references`/doi) and document + every parameter with a default and biological rationale. + +5. **Build & test locally** (server doesn't run these — use the terminal): + - `viash ns build` + - `viash run config.vsh.yaml -- --input .zarr --output tmp/out.zarr` + - `viash test config.vsh.yaml` — a unit test (`test_resources`) is expected + for every component + - `nextflow run main.nf -profile test,docker` + +6. **Dependency sanity.** Run `analyze_workflow_dependencies` across the workflow + files to catch missing/conflicting containers or libraries. + +7. **PR hygiene.** Include test data + expected output, document parameter + choices, and confirm CI (GitHub Actions) builds and runs the component. + +## Don't + +- Don't claim the server can build/benchmark/validate-submission automatically — + `build_openproblems_method`, `run_openproblems_benchmark`, and + `validate_openproblems_submission` are roadmap. Use the validation/analysis + tools that exist, and run the build/benchmark steps via local CLIs. diff --git a/.agents/skills/spatial-data-validation/SKILL.md b/.agents/skills/spatial-data-validation/SKILL.md new file mode 100644 index 0000000..d14cc7c --- /dev/null +++ b/.agents/skills/spatial-data-validation/SKILL.md @@ -0,0 +1,45 @@ +--- +name: spatial-data-validation +description: Validate and inspect spatial transcriptomics data files (SpatialData/zarr/AnnData) before any analysis. Use when the user points at a spatial data file, reports a loading/format error, or asks whether data is suitable for a method. +--- + +# Spatial data validation + +Validate first, reason second. Never assume a file's format or contents from its +extension. + +## Steps + +1. **Detect & validate format.** Call the MCP tool `validate_spatial_data` with + the file path. Choose `validation_level`: + - `basic` — extension/existence only. + - `structure` (default) — format + structural integrity. + - `integrity` — deeper content checks. + - `domain` — spatial-biology-specific expectations. + For several files, use `validate_multiple_spatial_files`. + +2. **Read the metadata.** Call `analyze_spatial_metadata` to extract dimensions, + spatial coordinates, and gene/feature info. Confirm `obsm['spatial']` (AnnData) + or coordinate systems (SpatialData) are present when spatial analysis is + intended. + +3. **Check raw vs. processed.** Integer-valued matrices are likely raw counts; + non-integer/log-scaled values are processed. State which the downstream method + expects and flag a mismatch. + +4. **Check compatibility** when combining files: `check_spatial_data_compatibility` + (coordinate systems + gene overlap). + +## Key facts (see `context/data-formats.md`) + +- A `.zarr` store is SpatialData **only** if it has SpatialData markers or ≥2 of + `images/ labels/ points/ shapes/ tables/`. Otherwise it's a plain zarr array. +- iST datasets can be terabytes. Default to lightweight structural checks; avoid + loading whole objects. The heavy scientific stack (`pip install -e ".[spatial]"`) + is optional — the validators degrade gracefully without it. + +## Don't + +- Don't claim a file is valid SpatialData without inspecting contents. +- Don't call execution tools (e.g. `run_nextflow_workflow`) — they aren't + implemented. Drive local CLIs directly if execution is needed. diff --git a/.agents/skills/viash-component-authoring/SKILL.md b/.agents/skills/viash-component-authoring/SKILL.md new file mode 100644 index 0000000..ad80e4d --- /dev/null +++ b/.agents/skills/viash-component-authoring/SKILL.md @@ -0,0 +1,97 @@ +--- +name: viash-component-authoring +description: Author or modify a Viash component (config.vsh.yaml + script) for an OpenProblems method, especially a task_ist_preprocessing stage. Use when the user wants to add/implement a spatial method, scaffold a component, or fix a config.vsh.yaml. +--- + +# Viash component authoring + +A Viash component = a `config.vsh.yaml` (metadata: arguments, resources, engines) ++ a script (Python/R/Bash). Viash compiles it into a CLI, a Docker image, and a +Nextflow module. + +## Steps + +1. **Identify the stage and its interface.** OpenProblems components conform to a + `comp_*` API merged in via `__merge__: /src/api/comp_.yaml`. Find the + right interface for the pipeline stage you're implementing (see + `context/ist-preprocessing-pipeline.md`) and match its inputs/outputs exactly. + +2. **Write `config.vsh.yaml`.** Use the modern **flat** config (no + `functionality:` wrapper) with `engines:` / `runners:` (not the legacy + `platforms:`). Follow OpenProblems conventions: merge the stage API, build on + the shared base image with a setup partial, include the standard metadata + block, and label the nextflow runner with resource directives. This mirrors a + real `task_ist_preprocessing` component: + + ```yaml + __merge__: /src/api/comp_.yaml + + name: my_method + label: "My Method" + summary: "One-line biological purpose." + description: "Longer description with method context." + links: + documentation: "https://github.com/openproblems-bio/task_ist_preprocessing" + repository: "https://github.com/openproblems-bio/task_ist_preprocessing" + references: + doi: "10.xxxx/xxxxx" # the method's paper + + arguments: + - name: "--some_param" + type: double + default: 1.0 + description: "Biologically meaningful parameter." + # Note: --input/--output are usually inherited from the merged comp_ API. + + resources: + - type: python_script + path: script.py + + engines: + - type: docker + image: openproblems/base_python:1 # shared base, not raw python:* + __merge__: + - /src/base/setup_spatialdata_partial.yaml # extra deps via setup partial + - type: native + + runners: + - type: executable + - type: nextflow + directives: + label: [ midtime, lowcpu, lowmem ] # resource labels + ``` + + Confirm the exact `__merge__` paths (the stage API and the base setup partial) + and the current Viash schema against the live repo before building — keys + evolve between major Viash versions. + +3. **Write the script** with the dev parameter block: + + ```python + import spatialdata as sd + + ## VIASH START + par = {"input": "resources_test/.../dataset.zarr", "output": "output.zarr", "some_param": 1.0} + ## VIASH END + + sdata = sd.read_zarr(par["input"]) + # ... implement; keep coordinate systems consistent ... + result.write(par["output"]) + ``` + + Fail loudly: log the error and `sys.exit(1)` on failure. + +4. **Validate before building.** Run `analyze_workflow_configuration` on the + `config.vsh.yaml` to catch structural/dependency issues. + +5. **Build & test** with the user's local Viash (the server does not run it): + - `viash ns build` + - `viash run config.vsh.yaml -- --input .zarr --output tmp/out.zarr` + - unit test: add a `test_resources` script (e.g. `test.py`) to the config and + run `viash test config.vsh.yaml` — every OpenProblems component ships a test. + - integration: `nextflow run main.nf -profile test,docker` + +## Don't + +- Don't invent `create_spatial_component` / `build_viash_component` tool calls — + they're roadmap, not implemented. Generate files and run `viash` in the terminal. diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 10aac90..3d3b3fa 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -107,9 +107,242 @@ format: YAML frontmatter + markdown). Load the one matching the task: installer; do not hand-edit the generated provider files. -## Skill playbooks (in `skills/`) +# Skill playbooks -- **nextflow-debugging**: Diagnose a failing Nextflow pipeline run in an OpenProblems benchmark. Use when a `nextflow run` fails, a process errors out, or the user shares a .nextflow.log / .command.err and asks why it broke. -- **openproblems-submission**: Prepare a spatial transcriptomics method for contribution to an OpenProblems benchmark (e.g. task_ist_preprocessing). Use when the user wants to submit/contribute a method, open a PR to a task_* repo, or check submission readiness. -- **spatial-data-validation**: Validate and inspect spatial transcriptomics data files (SpatialData/zarr/AnnData) before any analysis. Use when the user points at a spatial data file, reports a loading/format error, or asks whether data is suitable for a method. -- **viash-component-authoring**: Author or modify a Viash component (config.vsh.yaml + script) for an OpenProblems method, especially a task_ist_preprocessing stage. Use when the user wants to add/implement a spatial method, scaffold a component, or fix a config.vsh.yaml. +Load the one matching your task; full text follows. + +--- + + +# Nextflow debugging + +The server does not yet parse logs for you (`analyze_nextflow_log` is roadmap), so +triage the logs directly. Be systematic. + +## Steps + +1. **Find the failing task.** From the run output, note the process name and the + work directory hash (`work/ab/cdef...`). The per-task files there are the + ground truth: + - `.command.sh` — the exact command run. + - `.command.err` / `.command.out` — stderr/stdout. + - `.command.log`, `.exitcode` — exit status. + +2. **Classify the error by exit code / message:** + - **137 / OOM-killed** → memory limit. Increase the process `memory` directive + or add a dynamic retry (`memory { 8.GB * task.attempt }`). + - **127 / "command not found"** → tool missing in the container; fix the + component's engine/setup or the image. + - **126 / permission denied** → executable bit / entrypoint issue. + - **File/path errors** → check channel wiring and input staging; confirm the + input file actually exists and matches the expected format + (run `validate_spatial_data`). + - **Config/DSL errors** → confirm DSL2 syntax; OpenProblems pipelines are DSL2. + +3. **Add resilience** where appropriate: `errorStrategy 'retry'`, `maxRetries`, + and dynamic resources by `task.attempt`. Don't paper over a real bug with + retries. + +4. **Reproduce in isolation.** Re-run a single component with `viash run` on the + test data before re-running the whole pipeline. Use `-resume` to avoid + recomputing successful tasks. + +5. **Validate inputs** with `validate_spatial_data` / `analyze_spatial_metadata` + when the failure looks data-shaped (wrong format, missing elements, + raw-vs-normalized mismatch). + +## Output + +Report: the failing process, the root-cause class, the evidence (the log line), +and the specific fix — plus whether it's a data problem, an environment problem, +or a code problem. + +--- + + +# OpenProblems submission + +Goal: a Viash component that conforms to a task's API, builds cleanly, passes the +test profile, and is reproducible — ready for a PR. + +## Checklist + +1. **Repo setup.** Clone the target `task_*` repo and initialize the `common/` + git submodule (`git submodule update --init --recursive`). Read the repo's + `CONTRIBUTING` / `README` for current conventions. + +2. **Conform to the component API.** Your `config.vsh.yaml` must `__merge__` the + correct `comp_.yaml` interface and match its inputs/outputs and + `info`/metadata fields. Run `analyze_workflow_configuration` on the config. + +3. **Data contract.** Inputs/outputs are SpatialData (zarr) / AnnData as the stage + requires. Validate test data with `validate_spatial_data` and confirm the + elements the stage needs are present (`check_spatial_data_compatibility` for + multi-file). State raw-vs-normalized expectations explicitly. + +4. **Reproducibility.** Build on the shared base images + (`openproblems/base_python:1` / `base_r:1`) with `__merge__`-ed setup + partials rather than raw `python:*`/`r-base` images. Pin base-image tags and + package versions — no unpinned `latest`. Provide the standard metadata + (`label`, `summary`, `description`, `links`, `references`/doi) and document + every parameter with a default and biological rationale. + +5. **Build & test locally** (server doesn't run these — use the terminal): + - `viash ns build` + - `viash run config.vsh.yaml -- --input .zarr --output tmp/out.zarr` + - `viash test config.vsh.yaml` — a unit test (`test_resources`) is expected + for every component + - `nextflow run main.nf -profile test,docker` + +6. **Dependency sanity.** Run `analyze_workflow_dependencies` across the workflow + files to catch missing/conflicting containers or libraries. + +7. **PR hygiene.** Include test data + expected output, document parameter + choices, and confirm CI (GitHub Actions) builds and runs the component. + +## Don't + +- Don't claim the server can build/benchmark/validate-submission automatically — + `build_openproblems_method`, `run_openproblems_benchmark`, and + `validate_openproblems_submission` are roadmap. Use the validation/analysis + tools that exist, and run the build/benchmark steps via local CLIs. + +--- + + +# Spatial data validation + +Validate first, reason second. Never assume a file's format or contents from its +extension. + +## Steps + +1. **Detect & validate format.** Call the MCP tool `validate_spatial_data` with + the file path. Choose `validation_level`: + - `basic` — extension/existence only. + - `structure` (default) — format + structural integrity. + - `integrity` — deeper content checks. + - `domain` — spatial-biology-specific expectations. + For several files, use `validate_multiple_spatial_files`. + +2. **Read the metadata.** Call `analyze_spatial_metadata` to extract dimensions, + spatial coordinates, and gene/feature info. Confirm `obsm['spatial']` (AnnData) + or coordinate systems (SpatialData) are present when spatial analysis is + intended. + +3. **Check raw vs. processed.** Integer-valued matrices are likely raw counts; + non-integer/log-scaled values are processed. State which the downstream method + expects and flag a mismatch. + +4. **Check compatibility** when combining files: `check_spatial_data_compatibility` + (coordinate systems + gene overlap). + +## Key facts (see `context/data-formats.md`) + +- A `.zarr` store is SpatialData **only** if it has SpatialData markers or ≥2 of + `images/ labels/ points/ shapes/ tables/`. Otherwise it's a plain zarr array. +- iST datasets can be terabytes. Default to lightweight structural checks; avoid + loading whole objects. The heavy scientific stack (`pip install -e ".[spatial]"`) + is optional — the validators degrade gracefully without it. + +## Don't + +- Don't claim a file is valid SpatialData without inspecting contents. +- Don't call execution tools (e.g. `run_nextflow_workflow`) — they aren't + implemented. Drive local CLIs directly if execution is needed. + +--- + + +# Viash component authoring + +A Viash component = a `config.vsh.yaml` (metadata: arguments, resources, engines) ++ a script (Python/R/Bash). Viash compiles it into a CLI, a Docker image, and a +Nextflow module. + +## Steps + +1. **Identify the stage and its interface.** OpenProblems components conform to a + `comp_*` API merged in via `__merge__: /src/api/comp_.yaml`. Find the + right interface for the pipeline stage you're implementing (see + `context/ist-preprocessing-pipeline.md`) and match its inputs/outputs exactly. + +2. **Write `config.vsh.yaml`.** Use the modern **flat** config (no + `functionality:` wrapper) with `engines:` / `runners:` (not the legacy + `platforms:`). Follow OpenProblems conventions: merge the stage API, build on + the shared base image with a setup partial, include the standard metadata + block, and label the nextflow runner with resource directives. This mirrors a + real `task_ist_preprocessing` component: + + ```yaml + __merge__: /src/api/comp_.yaml + + name: my_method + label: "My Method" + summary: "One-line biological purpose." + description: "Longer description with method context." + links: + documentation: "https://github.com/openproblems-bio/task_ist_preprocessing" + repository: "https://github.com/openproblems-bio/task_ist_preprocessing" + references: + doi: "10.xxxx/xxxxx" # the method's paper + + arguments: + - name: "--some_param" + type: double + default: 1.0 + description: "Biologically meaningful parameter." + # Note: --input/--output are usually inherited from the merged comp_ API. + + resources: + - type: python_script + path: script.py + + engines: + - type: docker + image: openproblems/base_python:1 # shared base, not raw python:* + __merge__: + - /src/base/setup_spatialdata_partial.yaml # extra deps via setup partial + - type: native + + runners: + - type: executable + - type: nextflow + directives: + label: [ midtime, lowcpu, lowmem ] # resource labels + ``` + + Confirm the exact `__merge__` paths (the stage API and the base setup partial) + and the current Viash schema against the live repo before building — keys + evolve between major Viash versions. + +3. **Write the script** with the dev parameter block: + + ```python + import spatialdata as sd + + ## VIASH START + par = {"input": "resources_test/.../dataset.zarr", "output": "output.zarr", "some_param": 1.0} + ## VIASH END + + sdata = sd.read_zarr(par["input"]) + # ... implement; keep coordinate systems consistent ... + result.write(par["output"]) + ``` + + Fail loudly: log the error and `sys.exit(1)` on failure. + +4. **Validate before building.** Run `analyze_workflow_configuration` on the + `config.vsh.yaml` to catch structural/dependency issues. + +5. **Build & test** with the user's local Viash (the server does not run it): + - `viash ns build` + - `viash run config.vsh.yaml -- --input .zarr --output tmp/out.zarr` + - unit test: add a `test_resources` script (e.g. `test.py`) to the config and + run `viash test config.vsh.yaml` — every OpenProblems component ships a test. + - integration: `nextflow run main.nf -profile test,docker` + +## Don't + +- Don't invent `create_spatial_component` / `build_viash_component` tool calls — + they're roadmap, not implemented. Generate files and run `viash` in the terminal. diff --git a/GEMINI.md b/GEMINI.md index 10aac90..3d3b3fa 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -107,9 +107,242 @@ format: YAML frontmatter + markdown). Load the one matching the task: installer; do not hand-edit the generated provider files. -## Skill playbooks (in `skills/`) +# Skill playbooks -- **nextflow-debugging**: Diagnose a failing Nextflow pipeline run in an OpenProblems benchmark. Use when a `nextflow run` fails, a process errors out, or the user shares a .nextflow.log / .command.err and asks why it broke. -- **openproblems-submission**: Prepare a spatial transcriptomics method for contribution to an OpenProblems benchmark (e.g. task_ist_preprocessing). Use when the user wants to submit/contribute a method, open a PR to a task_* repo, or check submission readiness. -- **spatial-data-validation**: Validate and inspect spatial transcriptomics data files (SpatialData/zarr/AnnData) before any analysis. Use when the user points at a spatial data file, reports a loading/format error, or asks whether data is suitable for a method. -- **viash-component-authoring**: Author or modify a Viash component (config.vsh.yaml + script) for an OpenProblems method, especially a task_ist_preprocessing stage. Use when the user wants to add/implement a spatial method, scaffold a component, or fix a config.vsh.yaml. +Load the one matching your task; full text follows. + +--- + + +# Nextflow debugging + +The server does not yet parse logs for you (`analyze_nextflow_log` is roadmap), so +triage the logs directly. Be systematic. + +## Steps + +1. **Find the failing task.** From the run output, note the process name and the + work directory hash (`work/ab/cdef...`). The per-task files there are the + ground truth: + - `.command.sh` — the exact command run. + - `.command.err` / `.command.out` — stderr/stdout. + - `.command.log`, `.exitcode` — exit status. + +2. **Classify the error by exit code / message:** + - **137 / OOM-killed** → memory limit. Increase the process `memory` directive + or add a dynamic retry (`memory { 8.GB * task.attempt }`). + - **127 / "command not found"** → tool missing in the container; fix the + component's engine/setup or the image. + - **126 / permission denied** → executable bit / entrypoint issue. + - **File/path errors** → check channel wiring and input staging; confirm the + input file actually exists and matches the expected format + (run `validate_spatial_data`). + - **Config/DSL errors** → confirm DSL2 syntax; OpenProblems pipelines are DSL2. + +3. **Add resilience** where appropriate: `errorStrategy 'retry'`, `maxRetries`, + and dynamic resources by `task.attempt`. Don't paper over a real bug with + retries. + +4. **Reproduce in isolation.** Re-run a single component with `viash run` on the + test data before re-running the whole pipeline. Use `-resume` to avoid + recomputing successful tasks. + +5. **Validate inputs** with `validate_spatial_data` / `analyze_spatial_metadata` + when the failure looks data-shaped (wrong format, missing elements, + raw-vs-normalized mismatch). + +## Output + +Report: the failing process, the root-cause class, the evidence (the log line), +and the specific fix — plus whether it's a data problem, an environment problem, +or a code problem. + +--- + + +# OpenProblems submission + +Goal: a Viash component that conforms to a task's API, builds cleanly, passes the +test profile, and is reproducible — ready for a PR. + +## Checklist + +1. **Repo setup.** Clone the target `task_*` repo and initialize the `common/` + git submodule (`git submodule update --init --recursive`). Read the repo's + `CONTRIBUTING` / `README` for current conventions. + +2. **Conform to the component API.** Your `config.vsh.yaml` must `__merge__` the + correct `comp_.yaml` interface and match its inputs/outputs and + `info`/metadata fields. Run `analyze_workflow_configuration` on the config. + +3. **Data contract.** Inputs/outputs are SpatialData (zarr) / AnnData as the stage + requires. Validate test data with `validate_spatial_data` and confirm the + elements the stage needs are present (`check_spatial_data_compatibility` for + multi-file). State raw-vs-normalized expectations explicitly. + +4. **Reproducibility.** Build on the shared base images + (`openproblems/base_python:1` / `base_r:1`) with `__merge__`-ed setup + partials rather than raw `python:*`/`r-base` images. Pin base-image tags and + package versions — no unpinned `latest`. Provide the standard metadata + (`label`, `summary`, `description`, `links`, `references`/doi) and document + every parameter with a default and biological rationale. + +5. **Build & test locally** (server doesn't run these — use the terminal): + - `viash ns build` + - `viash run config.vsh.yaml -- --input .zarr --output tmp/out.zarr` + - `viash test config.vsh.yaml` — a unit test (`test_resources`) is expected + for every component + - `nextflow run main.nf -profile test,docker` + +6. **Dependency sanity.** Run `analyze_workflow_dependencies` across the workflow + files to catch missing/conflicting containers or libraries. + +7. **PR hygiene.** Include test data + expected output, document parameter + choices, and confirm CI (GitHub Actions) builds and runs the component. + +## Don't + +- Don't claim the server can build/benchmark/validate-submission automatically — + `build_openproblems_method`, `run_openproblems_benchmark`, and + `validate_openproblems_submission` are roadmap. Use the validation/analysis + tools that exist, and run the build/benchmark steps via local CLIs. + +--- + + +# Spatial data validation + +Validate first, reason second. Never assume a file's format or contents from its +extension. + +## Steps + +1. **Detect & validate format.** Call the MCP tool `validate_spatial_data` with + the file path. Choose `validation_level`: + - `basic` — extension/existence only. + - `structure` (default) — format + structural integrity. + - `integrity` — deeper content checks. + - `domain` — spatial-biology-specific expectations. + For several files, use `validate_multiple_spatial_files`. + +2. **Read the metadata.** Call `analyze_spatial_metadata` to extract dimensions, + spatial coordinates, and gene/feature info. Confirm `obsm['spatial']` (AnnData) + or coordinate systems (SpatialData) are present when spatial analysis is + intended. + +3. **Check raw vs. processed.** Integer-valued matrices are likely raw counts; + non-integer/log-scaled values are processed. State which the downstream method + expects and flag a mismatch. + +4. **Check compatibility** when combining files: `check_spatial_data_compatibility` + (coordinate systems + gene overlap). + +## Key facts (see `context/data-formats.md`) + +- A `.zarr` store is SpatialData **only** if it has SpatialData markers or ≥2 of + `images/ labels/ points/ shapes/ tables/`. Otherwise it's a plain zarr array. +- iST datasets can be terabytes. Default to lightweight structural checks; avoid + loading whole objects. The heavy scientific stack (`pip install -e ".[spatial]"`) + is optional — the validators degrade gracefully without it. + +## Don't + +- Don't claim a file is valid SpatialData without inspecting contents. +- Don't call execution tools (e.g. `run_nextflow_workflow`) — they aren't + implemented. Drive local CLIs directly if execution is needed. + +--- + + +# Viash component authoring + +A Viash component = a `config.vsh.yaml` (metadata: arguments, resources, engines) ++ a script (Python/R/Bash). Viash compiles it into a CLI, a Docker image, and a +Nextflow module. + +## Steps + +1. **Identify the stage and its interface.** OpenProblems components conform to a + `comp_*` API merged in via `__merge__: /src/api/comp_.yaml`. Find the + right interface for the pipeline stage you're implementing (see + `context/ist-preprocessing-pipeline.md`) and match its inputs/outputs exactly. + +2. **Write `config.vsh.yaml`.** Use the modern **flat** config (no + `functionality:` wrapper) with `engines:` / `runners:` (not the legacy + `platforms:`). Follow OpenProblems conventions: merge the stage API, build on + the shared base image with a setup partial, include the standard metadata + block, and label the nextflow runner with resource directives. This mirrors a + real `task_ist_preprocessing` component: + + ```yaml + __merge__: /src/api/comp_.yaml + + name: my_method + label: "My Method" + summary: "One-line biological purpose." + description: "Longer description with method context." + links: + documentation: "https://github.com/openproblems-bio/task_ist_preprocessing" + repository: "https://github.com/openproblems-bio/task_ist_preprocessing" + references: + doi: "10.xxxx/xxxxx" # the method's paper + + arguments: + - name: "--some_param" + type: double + default: 1.0 + description: "Biologically meaningful parameter." + # Note: --input/--output are usually inherited from the merged comp_ API. + + resources: + - type: python_script + path: script.py + + engines: + - type: docker + image: openproblems/base_python:1 # shared base, not raw python:* + __merge__: + - /src/base/setup_spatialdata_partial.yaml # extra deps via setup partial + - type: native + + runners: + - type: executable + - type: nextflow + directives: + label: [ midtime, lowcpu, lowmem ] # resource labels + ``` + + Confirm the exact `__merge__` paths (the stage API and the base setup partial) + and the current Viash schema against the live repo before building — keys + evolve between major Viash versions. + +3. **Write the script** with the dev parameter block: + + ```python + import spatialdata as sd + + ## VIASH START + par = {"input": "resources_test/.../dataset.zarr", "output": "output.zarr", "some_param": 1.0} + ## VIASH END + + sdata = sd.read_zarr(par["input"]) + # ... implement; keep coordinate systems consistent ... + result.write(par["output"]) + ``` + + Fail loudly: log the error and `sys.exit(1)` on failure. + +4. **Validate before building.** Run `analyze_workflow_configuration` on the + `config.vsh.yaml` to catch structural/dependency issues. + +5. **Build & test** with the user's local Viash (the server does not run it): + - `viash ns build` + - `viash run config.vsh.yaml -- --input .zarr --output tmp/out.zarr` + - unit test: add a `test_resources` script (e.g. `test.py`) to the config and + run `viash test config.vsh.yaml` — every OpenProblems component ships a test. + - integration: `nextflow run main.nf -profile test,docker` + +## Don't + +- Don't invent `create_spatial_component` / `build_viash_component` tool calls — + they're roadmap, not implemented. Generate files and run `viash` in the terminal. diff --git a/case-study/runner/README.md b/case-study/runner/README.md index a02bd8e..956b07e 100644 --- a/case-study/runner/README.md +++ b/case-study/runner/README.md @@ -64,17 +64,39 @@ If the configured `task_repo` doesn't exist, mock mode synthesizes a minimal stand-in repo automatically, so the smoke test needs nothing but this repo. Swap `--mock-harness ...` for the real run once it looks right. +## How a "skill arm" gets the skill + +For skill arms the runner does two things: (1) installs the agent-native files +(via the installer `agent_target`) and copies `AGENTS.md` + `skills/` + `context/` +into the workdir, and (2) **injects the skill playbooks into the prompt** +(`inject_skills: true`). The injection matters because agents differ in whether +they auto-load skills — Gemini/Antigravity CLI won't open `SKILL.md` files on +their own. Injecting guarantees the skill *content* reaches the model, so the +experiment measures the value of the content rather than each agent's discovery +mechanism. Set `inject_skill_names` to a subset, or `inject_skills: false` to +test pure auto-load behavior. + +## Repeats (beat single-run noise) + +Set `repeats` in the config or pass `--repeats N` (N≥3 recommended). Each arm runs +N times in isolated `…__rep` workdirs; the table reports the **median**, the +range, and the pass-rate. A single run is an anecdote — a 2-point swing is well +within sampling noise. + ## Harness setup The `command` templates in the config are substituted with `{prompt}` and `{model}`. Defaults provided: -- **Gemini CLI** — `["gemini", "-y", "-p", "{prompt}"]`. Headless via `-p`; `-y` - auto-approves tool calls. Reads `GEMINI.md` + `.gemini/settings.json` (which the - `gemini` installer target writes). Auth via `gemini` login or `GEMINI_API_KEY`. +- **Antigravity CLI** — `["agy", "--yolo", "-p", "{prompt}"]`. Headless via `-p`; + `--yolo` auto-approves tool calls. Reads `AGENTS.md` + `.agents/` (the + `antigravity` installer target writes `.agents/mcp_config.json` + skills). + Note: `agy -p` can emit no stdout when spawned as a subprocess, but it still + writes files — which is what the grader reads, so grading is unaffected. + (Gemini CLI is still available as the legacy `gemini` harness/target.) - **opencode** — `["opencode", "run", "{prompt}", "--model", "{model}"]`. Reads - `AGENTS.md` natively (the skill arm copies it in). Use an OpenRouter model id - like `openrouter/qwen/qwen3-coder`; set your OpenRouter key per opencode's docs. + `AGENTS.md` natively. Use an OpenRouter model id like + `openrouter/qwen/qwen3-coder`; set your OpenRouter key per opencode's docs. Both must be installed and on `PATH` with credentials configured. If a harness binary is missing, the arm is recorded as not-run rather than crashing the batch. @@ -83,15 +105,19 @@ binary is missing, the arm is recorded as not-run rather than crashing the batch | Arm | Harness | Model | Skill | | --- | --- | --- | :---: | -| A | gemini | commercial Gemini | ❌ | -| C | gemini | **same** Gemini | ✅ | +| A | antigravity | commercial Gemini | ❌ | +| C | antigravity | **same** Gemini | ✅ | | B | opencode | OpenRouter OSS | ❌ | | C′ | opencode | **same** OSS | ✅ | The decisive contrast is **same model, skill toggled** (A vs C, B vs C′): it -isolates the skill's effect. Run N≥3 repeats and grade blind. The runner records -the conformance score, build/test (with `--run-viash`), and the agent log per -arm; copy the numbers into `results/RESULTS.md`. +isolates the skill's effect. Run N≥3 repeats and grade blind. Turn on +`run_viash: true` so `viash build`/`viash test` give the real correctness signal +alongside the static rubric. Copy the numbers into `results/RESULTS.md`. + +> **Headroom matters.** If your commercial model already scores near 11/11 +> without the skill (ceiling), the skill can't show a lift — focus the +> comparison on the weaker/OSS model, or choose a less common pipeline stage. ## Notes diff --git a/case-study/runner/arms.example.json b/case-study/runner/arms.example.json index ed5edaa..33540e5 100644 --- a/case-study/runner/arms.example.json +++ b/case-study/runner/arms.example.json @@ -6,29 +6,37 @@ "workdir": "case-study/runs", "prompt_file": "case-study/task/prompt.txt", "timeout_seconds": 1800, + "repeats": 3, + "run_viash": false, + "inject_skills": true, + "_inject_note": "Skill arms get the playbooks injected into the prompt, so the skill CONTENT reaches the model regardless of whether the agent auto-loads skills. Set 'inject_skill_names' to a subset if you want only some.", "harnesses": { - "gemini": { - "command": ["gemini", "-y", "-p", "{prompt}"], - "comment": "Headless Gemini CLI; -y auto-approves tool calls, -p is the prompt." + "antigravity": { + "command": ["agy", "--yolo", "-p", "{prompt}"], + "comment": "Google Antigravity CLI (agy), headless via -p, --yolo auto-approves. Note: agy -p can emit no stdout in a non-TTY subprocess; the agent still writes files, which is what the grader reads." }, "opencode": { "command": ["opencode", "run", "{prompt}", "--model", "{model}"], - "comment": "Non-interactive opencode; --model takes e.g. openrouter/qwen/qwen3-coder." + "comment": "Non-interactive opencode; --model takes e.g. openrouter/qwen/qwen3-coder. Requires opencode configured with an OpenRouter key." + }, + "gemini": { + "command": ["gemini", "-y", "-p", "{prompt}"], + "comment": "Legacy Gemini CLI (replaced by Antigravity CLI). -y auto-approves, -p is the prompt." } }, "arms": [ { - "name": "A_gemini_noskill", - "harness": "gemini", + "name": "A_antigravity_noskill", + "harness": "antigravity", "model": "gemini-2.5-pro", "skill": false }, { - "name": "C_gemini_skill", - "harness": "gemini", + "name": "C_antigravity_skill", + "harness": "antigravity", "model": "gemini-2.5-pro", "skill": true, - "agent_target": "gemini" + "agent_target": "antigravity" }, { "name": "B_opencode_oss_noskill", diff --git a/case-study/runner/run.py b/case-study/runner/run.py index 4a22127..0a0b337 100644 --- a/case-study/runner/run.py +++ b/case-study/runner/run.py @@ -10,13 +10,19 @@ the cleanest automated signal. The "human validations" metric comes from *interactive* runs the operator does by hand (see case-study/README.md). +Skill arms get the project playbooks injected into the prompt (config +``inject_skills``, default true), so the skill *content* reaches the model +regardless of whether the agent auto-loads skills. Use ``repeats`` / ``--repeats`` +(>=3 recommended) to report a median and beat single-run noise. + Examples: python case-study/runner/run.py --config case-study/runner/arms.json - python case-study/runner/run.py --config arms.json --only C_gemini_skill + python case-study/runner/run.py --config arms.json --only C_antigravity_skill + python case-study/runner/run.py --config arms.json --repeats 3 python case-study/runner/run.py --config arms.json --dry-run -Requires: the chosen harness CLI (e.g. `gemini`, `opencode`) on PATH with -credentials configured. Use --dry-run to validate the plan without running them. +Requires: the chosen harness CLI (e.g. `agy` for Antigravity, `opencode`) on PATH +with credentials configured. Use --dry-run to validate the plan without running. """ from __future__ import annotations @@ -24,6 +30,7 @@ import argparse import json import shutil +import statistics import subprocess import sys import time @@ -51,6 +58,33 @@ def _resolve(base: Path, value: str) -> Path: return p if p.is_absolute() else base / p +def _skill_block(copilot_repo: Path, names: list[str] | None) -> str: + """Concatenate skill bodies to inject into a skill-arm prompt. + + Agents differ in whether they auto-load skills (Gemini/Antigravity CLI won't + open SKILL.md files on their own). Injecting the relevant playbooks into the + prompt guarantees the skill *content* reaches the model, so the experiment + measures the value of the content, not each agent's discovery mechanism. + """ + skills_dir = copilot_repo / "skills" + blocks = [] + for skill_md in sorted(skills_dir.glob("*/SKILL.md")): + name = skill_md.parent.name + if names and name not in names: + continue + text = skill_md.read_text(encoding="utf-8", errors="ignore") + if text.startswith("---"): # strip YAML frontmatter + parts = text.split("---", 2) + text = parts[2] if len(parts) == 3 else text + blocks.append(f"\n\n## Reference playbook: {name}\n{text.strip()}") + if not blocks: + return "" + return ( + "\n\n---\nThe following project reference playbooks describe the required " + "conventions. Follow them.\n" + "".join(blocks) + ) + + def _load_config(path: Path) -> dict: cfg = json.loads(path.read_text(encoding="utf-8")) cfg.setdefault("component_name", "log_normalization") @@ -71,9 +105,9 @@ def _ignore_heavy(_dir, names): return {n for n in names if n in {".git", "node_modules", "__pycache__", ".venv"}} -def prepare_workdir(cfg: dict, arm: dict, copilot_repo: Path) -> Path: +def prepare_workdir(cfg: dict, arm: dict, copilot_repo: Path, label: str) -> Path: """Copy the task repo and install/strip the skill for this arm.""" - workdir = Path(cfg["workdir"]).resolve() / arm["name"] + workdir = Path(cfg["workdir"]).resolve() / label if workdir.exists(): shutil.rmtree(workdir) task_repo = Path(cfg["task_repo"]).expanduser().resolve() @@ -196,9 +230,19 @@ def grade_component( def run_arm( - cfg: dict, arm: dict, copilot_repo: Path, dry_run: bool, mock: str | None = None + cfg: dict, + arm: dict, + copilot_repo: Path, + dry_run: bool, + mock: str | None = None, + repeat_idx: int | None = None, ) -> dict: prompt = Path(cfg["prompt_file"]).read_text(encoding="utf-8").strip() + # Skill arms get the playbooks injected into the prompt, so the skill content + # reaches the model regardless of whether the agent auto-loads skills. + if arm.get("skill") and cfg.get("inject_skills", True): + prompt += _skill_block(copilot_repo, cfg.get("inject_skill_names")) + label = arm["name"] if repeat_idx is None else f"{arm['name']}__rep{repeat_idx}" result = { "arm": arm["name"], "harness": arm["harness"], @@ -213,8 +257,9 @@ def run_arm( ) cmd = cfg["harnesses"][arm["harness"]]["command"] result["plan"] = { - "workdir": str(Path(cfg["workdir"]) / arm["name"]), + "workdir": str(Path(cfg["workdir"]) / label), "prep": action, + "inject_skills": bool(arm.get("skill") and cfg.get("inject_skills", True)), "command": ( f"" if mock @@ -228,7 +273,7 @@ def run_arm( } return result - workdir = prepare_workdir(cfg, arm, copilot_repo) + workdir = prepare_workdir(cfg, arm, copilot_repo, label) if mock: run_info = mock_harness(arm, workdir, mock) else: @@ -244,20 +289,56 @@ def run_arm( return result +def run_arm_repeated( + cfg: dict, arm: dict, copilot_repo: Path, mock: str | None, repeats: int +) -> dict: + """Run an arm ``repeats`` times and aggregate (median + range + pass rate).""" + runs = [ + run_arm( + cfg, + arm, + copilot_repo, + dry_run=False, + mock=mock, + repeat_idx=(i if repeats > 1 else None), + ) + for i in range(repeats) + ] + scores = [r["graded"].get("score", 0) for r in runs] + passes = [bool(r["graded"].get("static_pass")) for r in runs] + return { + "arm": arm["name"], + "harness": arm["harness"], + "model": arm.get("model"), + "skill": bool(arm.get("skill")), + "repeats": repeats, + "scores": scores, + "score_median": statistics.median(scores), + "score_min": min(scores), + "score_max": max(scores), + "pass_rate": round(sum(passes) / repeats, 2), + "runs": runs, + } + + def render_table(results: list[dict]) -> str: rows = [ - "| Arm | Harness | Model | Skill | Score /11 | Pass | Component |", - "| --- | --- | --- | :---: | :---: | :---: | --- |", + "| Arm | Harness | Model | Skill | Median /11 | Range | Pass-rate | N |", + "| --- | --- | --- | :---: | :---: | :---: | :---: | :---: |", ] for r in results: - g = r.get("graded", {}) - score = g.get("score", "—") - mx = g.get("max_score", 11) - passed = "✅" if g.get("static_pass") else "❌" - comp = r.get("component", g.get("note", "—")) + median = r.get("score_median", "—") + lo, hi = r.get("score_min"), r.get("score_max") + rng = ( + f"{lo}–{hi}" + if lo is not None and lo != hi + else (str(lo) if lo is not None else "—") + ) + pass_rate = f"{int(round(r['pass_rate'] * 100))}%" if "pass_rate" in r else "—" rows.append( f"| {r['arm']} | {r['harness']} | {r.get('model','')} | " - f"{'✅' if r['skill'] else '❌'} | {score}/{mx} | {passed} | {comp} |" + f"{'✅' if r['skill'] else '❌'} | {median}/11 | {rng} | " + f"{pass_rate} | {r.get('repeats', 1)} |" ) return "\n".join(rows) @@ -288,6 +369,13 @@ def main(argv: list[str] | None = None) -> int: "'skill-aware' produces a good component when skill assets are present, " "else a bad one.", ) + parser.add_argument( + "--repeats", + type=int, + default=None, + help="Runs per arm (overrides config 'repeats'; default 1). Use >=3 to " + "report a median and beat single-run noise.", + ) args = parser.parse_args(argv) cfg = _load_config(args.config) @@ -333,14 +421,19 @@ def main(argv: list[str] | None = None) -> int: print(f"❌ no arms match {args.only}", file=sys.stderr) return 2 - results = [ - run_arm(cfg, arm, copilot_repo, args.dry_run, args.mock_harness) for arm in arms - ] - if args.dry_run: + results = [ + run_arm(cfg, arm, copilot_repo, True, args.mock_harness) for arm in arms + ] print(json.dumps(results, indent=2)) return 0 + repeats = max(1, args.repeats or int(cfg.get("repeats", 1))) + results = [ + run_arm_repeated(cfg, arm, copilot_repo, args.mock_harness, repeats) + for arm in arms + ] + out_dir = Path(cfg["workdir"]).resolve() out_dir.mkdir(parents=True, exist_ok=True) (out_dir / "results.json").write_text( diff --git a/case-study/scripts/strip_skill.sh b/case-study/scripts/strip_skill.sh index d09b5fa..44e87d5 100755 --- a/case-study/scripts/strip_skill.sh +++ b/case-study/scripts/strip_skill.sh @@ -9,7 +9,7 @@ cd "$DEST" rm -rf \ AGENTS.md CLAUDE.md GEMINI.md QUICKSTART.md \ skills/ context/ installer/ \ - .claude/ .codex/ .cursor/ .gemini/ .claude-plugin/ \ + .claude/ .codex/ .cursor/ .gemini/ .agents/ .claude-plugin/ \ .github/copilot-instructions.md \ .mcp.json diff --git a/installer/targets.py b/installer/targets.py index b687105..667efdc 100644 --- a/installer/targets.py +++ b/installer/targets.py @@ -154,35 +154,53 @@ def install_cursor(src: Sources, dest: Path, written: List[Path]) -> None: _write(dest / ".cursor" / "mcp.json", _mcp_json(), written) +def _self_contained_md(src: Sources) -> str: + """AGENTS.md plus the FULL skill bodies, for agents with no skill auto-load. + + Embedding the bodies (not just an index) ensures the model actually has the + playbooks in context — agents like Copilot, Gemini CLI, and Antigravity CLI + won't autonomously open the SKILL.md files otherwise. + """ + parts = [GENERATED_BANNER, src.agents_md, "\n\n# Skill playbooks\n"] + parts.append("\nLoad the one matching your task; full text follows.\n") + for s in src.skills: + parts.append(f"\n---\n\n\n{s.body.strip()}\n") + return "".join(parts) + + def install_copilot(src: Sources, dest: Path, written: List[Path]) -> None: """GitHub Copilot: .github/copilot-instructions.md (self-contained).""" - skills_index = "\n".join(f"- **{s.name}**: {s.description}" for s in src.skills) - content = ( - GENERATED_BANNER - + src.agents_md - + "\n\n## Skill playbooks (in `skills/`)\n\n" - + skills_index - + "\n" + _write( + dest / ".github" / "copilot-instructions.md", + _self_contained_md(src), + written, ) - _write(dest / ".github" / "copilot-instructions.md", content, written) def install_gemini(src: Sources, dest: Path, written: List[Path]) -> None: """Gemini CLI: GEMINI.md context file (self-contained) + .gemini/settings.json.""" - skills_index = "\n".join(f"- **{s.name}**: {s.description}" for s in src.skills) - gemini_md = ( - GENERATED_BANNER - + src.agents_md - + "\n\n## Skill playbooks (in `skills/`)\n\n" - + skills_index - + "\n" - ) - _write(dest / "GEMINI.md", gemini_md, written) + _write(dest / "GEMINI.md", _self_contained_md(src), written) # Gemini CLI reads MCP servers from .gemini/settings.json; the top-level # mcpServers shape matches the standard JSON config we emit elsewhere. _write(dest / ".gemini" / "settings.json", _mcp_json(), written) +def install_antigravity(src: Sources, dest: Path, written: List[Path]) -> None: + """Google Antigravity CLI (agy): AGENTS.md + embedded skills + .agents/ config. + + Antigravity reads ``AGENTS.md`` natively and a ``.agents/`` workspace dir. + We also write a self-contained context file with full skill bodies (the CLI + won't open SKILL.md files on its own) and the MCP config it reads from + ``.agents/mcp_config.json``. + """ + if dest.resolve() != src.repo_root.resolve(): + _write(dest / "AGENTS.md", src.agents_md, written) + for skill in src.skills: + _copy_skill(skill, dest / ".agents" / "skills", written) + _write(dest / ".agents" / "context.md", _self_contained_md(src), written) + _write(dest / ".agents" / "mcp_config.json", _mcp_json(), written) + + @dataclass class Target: key: str @@ -195,5 +213,6 @@ class Target: "codex": Target("codex", "OpenAI Codex", install_codex), "cursor": Target("cursor", "Cursor", install_cursor), "copilot": Target("copilot", "GitHub Copilot", install_copilot), - "gemini": Target("gemini", "Gemini CLI", install_gemini), + "gemini": Target("gemini", "Gemini CLI (legacy)", install_gemini), + "antigravity": Target("antigravity", "Google Antigravity CLI", install_antigravity), } diff --git a/tests/test_case_study_runner.py b/tests/test_case_study_runner.py index b9e21ba..98d0248 100644 --- a/tests/test_case_study_runner.py +++ b/tests/test_case_study_runner.py @@ -20,7 +20,7 @@ def test_dry_run_returns_zero(capsys): rc = run_mod.main(["--config", str(EXAMPLE_CONFIG), "--dry-run"]) assert rc == 0 out = capsys.readouterr().out - assert "A_gemini_noskill" in out + assert "antigravity" in out assert "install skill" in out and "strip skill" in out @@ -52,13 +52,17 @@ def test_render_table_has_rows(): "harness": "gemini", "model": "m", "skill": True, - "graded": {"score": 11, "max_score": 11, "static_pass": True}, - "component": "src/x", + "repeats": 3, + "scores": [10, 11, 11], + "score_median": 11, + "score_min": 10, + "score_max": 11, + "pass_rate": 0.67, }, ] table = run_mod.render_table(results) assert "| Arm |" in table - assert "X" in table and "11/11" in table + assert "X" in table and "11/11" in table and "10–11" in table def test_mock_harness_skill_aware(tmp_path): @@ -104,11 +108,41 @@ def test_mock_end_to_end(tmp_path): assert rc == 0 results = json.loads((tmp_path / "runs" / "results.json").read_text()) - by_arm = {r["arm"]: r["graded"]["score"] for r in results} + by_arm = {r["arm"]: r["score_median"] for r in results} assert by_arm["skill"] == 11 assert by_arm["noskill"] == 0 +def test_repeats_aggregate_with_median(tmp_path): + """--repeats runs each arm N times and reports median/range/pass-rate.""" + config = { + "copilot_repo": str(REPO_ROOT), + "task_repo": str(tmp_path / "missing"), + "workdir": str(tmp_path / "runs"), + "arms": [{"name": "skill", "harness": "g", "skill": True, + "agent_target": "gemini"}], + "harnesses": {"g": {"command": ["g", "-p", "{prompt}"]}}, + } + cfg_path = tmp_path / "arms.json" + cfg_path.write_text(json.dumps(config), encoding="utf-8") + rc = run_mod.main( + ["--config", str(cfg_path), "--mock-harness", "good", "--repeats", "3"] + ) + assert rc == 0 + results = json.loads((tmp_path / "runs" / "results.json").read_text()) + r = results[0] + assert r["repeats"] == 3 + assert r["scores"] == [11, 11, 11] + assert r["score_median"] == 11 + assert r["pass_rate"] == 1.0 + + +def test_skill_block_injects_playbooks(): + block = run_mod._skill_block(REPO_ROOT, None) + assert "Reference playbook: viash-component-authoring" in block + assert "openproblems/base_python" in block # body content, not just a name + + def test_config_paths_are_cwd_independent(tmp_path, monkeypatch): """Paths resolve against the repo root, not the current working directory.""" monkeypatch.chdir(tmp_path) # run from an unrelated directory