Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions .agents/skills/create-issue/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
name: create-issue
description: Create a GitHub issue in this repository from its issue forms (Feature / improvement, Bug report), with checkable "Done when" criteria. Use when the user asks to create, raise, open or file an issue, report a bug, or turn an idea, note, Miro sticky or conversation into a ticket. Not for pull requests or for editing an existing issue.
---

# Create an issue

Create an issue that looks exactly like one filed through the repository's issue forms in the browser. The forms in `.github/ISSUE_TEMPLATE/` are the source of truth: read them every time, never rely on a remembered list of fields.

Run every command from the repository root. You need `gh` (authenticated) and `uv`.

## 1. Read the forms

```bash
uv run .agents/skills/create-issue/scripts/render_issue.py list
```

This prints each template's name, title prefix, labels and fields (label, type, required, description, default value, options).

Pick the template that fits: a **Bug report** for something that isn't working, a **Feature / improvement** for new work. If the request fits neither, or you can't tell, ask the user.

## 2. Search for duplicates

```bash
gh issue list --state all --search "<two or three key words>" --limit 10
```

If a close match exists, show it to the user and ask whether to comment on it instead. Only tick the form's "I have searched the existing issues" box after you have actually searched.

## 3. Draft the answers

Fill each field from what the user said and from the conversation. Follow each field's description from step 1.

- **Title**: short and specific, without the template prefix (the script adds it).
- **Context / bug fields**: the user's facts, not your guesses. Link the source (Miro sticky, decisions doc, meeting notes, failing run) when there is one.
- **Done when**: keep the template's default structure (**Must have** / **Nice to have**). Propose concrete criteria drawn from the conversation, each one checkable by someone else without asking. Never present invented criteria as agreed: the user confirms or edits them in step 4.
- Leave optional fields empty rather than padding them; they render as `_No response_`, as on GitHub.
- Never put credentials, tokens or personal data in an issue.

Write the answers to a temporary file outside the repository, keyed by field label, with checkbox fields as a list of the options to tick:

```json
{
"title": "Short summary",
"Is there an existing issue for this?": ["I have searched the existing issues"],
"Context": "...",
"Done when": "**Must have**\n\n- [ ] ...\n\n**Nice to have**\n\n- [ ] ..."
}
```

Render it:

```bash
uv run .agents/skills/create-issue/scripts/render_issue.py render <template> <answers.json> <tmp-dir>
```

The script checks required fields and unknown labels, writes `body.md`, and prints the final `title`, `labels` and `body_file`. Fix and re-render on any error.

## 4. Confirm with the user

Creating an issue is visible to the whole team. Show the user the final title, labels and the full rendered body, and ask them to confirm. Apply any edits and re-render. Do not create the issue without a clear yes.

## 5. Create it

```bash
gh issue create --title "<title>" --body-file <body_file> --label "<label>" [--label "<label>" ...]
```

Pass each label from the render output with its own `--label`. Report the issue URL to the user.

Then offer, without doing it unasked, to create the linked branch so the work can start (`gh issue develop <number> --checkout`).
161 changes: 161 additions & 0 deletions .agents/skills/create-issue/scripts/render_issue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
# /// script
# requires-python = ">=3.10"
# dependencies = ["pyyaml"]
# ///
"""Render a GitHub issue from the repository's issue forms.

`gh issue create` cannot fill an issue form, so this rebuilds what GitHub produces when a form is
submitted in the browser: the form's title prefix, one `### <label>` section per field, and the
form's labels. Fields are read from `.github/ISSUE_TEMPLATE/` at runtime, so template edits need
no change here.

uv run render_issue.py list
uv run render_issue.py render <template> <answers.json> <out-dir>

`answers.json` maps field labels to values, plus a `title` key:

{"title": "Short summary", "Context": "...", "Done when": "**Must have**\\n- [ ] ..."}

Checkbox fields take a list of the option labels to tick. `render` writes `<out-dir>/body.md` and
prints JSON with `title`, `labels` and `body_file` for `gh issue create`.
"""

import json
import subprocess
import sys
from pathlib import Path

import yaml

NO_RESPONSE = "_No response_"


def template_dir() -> Path:
root = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
capture_output=True,
text=True,
check=True,
).stdout.strip()
return Path(root) / ".github" / "ISSUE_TEMPLATE"


def load_forms() -> dict[str, dict]:
forms = {}
for path in sorted(template_dir().glob("*.y*ml")):
form = yaml.safe_load(path.read_text())
if isinstance(form, dict) and "body" in form:
forms[path.stem] = form
return forms


def input_fields(form: dict) -> list[dict]:
"""The fields that appear in the issue body; markdown blocks are display-only."""
return [item for item in form["body"] if item["type"] != "markdown"]


def describe(forms: dict[str, dict]) -> list[dict]:
out = []
for key, form in forms.items():
fields = []
for item in input_fields(form):
attrs = item.get("attributes", {})
field = {
"label": attrs["label"],
"type": item["type"],
"required": item.get("validations", {}).get("required", False),
"description": attrs.get("description", "").strip(),
}
if "value" in attrs:
field["default"] = attrs["value"]
if item["type"] in ("checkboxes", "dropdown"):
field["options"] = [
o["label"] if isinstance(o, dict) else o for o in attrs["options"]
]
if item["type"] == "checkboxes":
field["required"] = any(
isinstance(o, dict) and o.get("required")
for o in attrs["options"]
)
fields.append(field)
out.append(
{
"template": key,
"name": form["name"],
"description": form.get("description", ""),
"title": form.get("title", ""),
"labels": form.get("labels", []),
"fields": fields,
}
)
return out


def render(form: dict, answers: dict) -> tuple[str, str, list[str]]:
title = answers.get("title", "").strip()
if not title:
sys.exit("answers.json needs a non-empty 'title'")
prefix = form.get("title", "")
title = (
prefix.replace("<title>", title) if "<title>" in prefix else f"{prefix}{title}"
)

sections, missing = [], []
for item in input_fields(form):
attrs = item["attributes"]
label = attrs["label"]
value = answers.get(label)
if item["type"] == "checkboxes":
ticked = set(value or [])
options = attrs["options"]
if any(o.get("required") and o["label"] not in ticked for o in options):
missing.append(label)
text = "\n".join(
f"- [{'X' if o['label'] in ticked else ' '}] {o['label']}"
for o in options
)
else:
text = (value or "").strip()
if not text and item.get("validations", {}).get("required"):
missing.append(label)
text = text or NO_RESPONSE
sections.append(f"### {label}\n\n{text}")

unknown = (
set(answers)
- {"title"}
- {i["attributes"]["label"] for i in input_fields(form)}
)
if unknown:
sys.exit(f"unknown fields in answers.json: {sorted(unknown)}")
if missing:
sys.exit(f"required fields missing: {missing}")
return title, "\n\n".join(sections) + "\n", form.get("labels", [])


def main() -> None:
forms = load_forms()
if len(sys.argv) == 2 and sys.argv[1] == "list":
print(json.dumps(describe(forms), indent=2, ensure_ascii=False))
elif len(sys.argv) == 5 and sys.argv[1] == "render":
key, answers_path, out_dir = sys.argv[2:]
if key not in forms:
sys.exit(f"unknown template {key!r}; choose from {sorted(forms)}")
title, body, labels = render(
forms[key], json.loads(Path(answers_path).read_text())
)
body_file = Path(out_dir) / "body.md"
body_file.parent.mkdir(parents=True, exist_ok=True)
body_file.write_text(body)
print(
json.dumps(
{"title": title, "labels": labels, "body_file": str(body_file)},
ensure_ascii=False,
)
)
else:
sys.exit(__doc__)


if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions .claude/skills/create-issue
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ __pycache__/
.DS_Store
.vscode/
.idea/
.claude/
.claude/*
!.claude/skills/

# Notebook scratch — version-controlled notebooks live under analyses/ only.
*.ipynb
Expand Down
1 change: 1 addition & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ repos:
- id: mdformat
additional_dependencies:
- mdformat-gfm
- mdformat-frontmatter
entry: mdformat --number --wrap=no
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
Expand Down
89 changes: 89 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# AGENTS.md

Instructions for AI coding agents (Claude Code, Codex, Copilot, …) working in this repository. They apply on top of [CONTRIBUTING.md](CONTRIBUTING.md), which humans follow too; where the two overlap, they say the same thing.

## Who you are working for

You act on behalf of the person who started the session, and you inherit their role:

- **Core developer** (Cornerstone team, write access): you may open a pull request without an issue. Put the context and the **Done when** criteria in the PR description instead.
- **External contributor**: an issue agreed with the core team must exist before you open a pull request. If there is none, stop and draft the issue with the user instead of the PR.

When you don't know which applies, ask.

## Working principles

- **Think first.** State your assumptions. If the request can be read more than one way, surface the readings instead of picking one silently. Push back when a simpler approach exists.
- **Keep it simple.** Write the minimum code that solves the problem: no speculative features, abstractions, or error handling for cases that can't happen.
- **Change only what the task needs.** Match the existing style. Remove only what your own change made unused; flag pre-existing dead code instead of deleting it.
- **Verify.** Turn the task into checkable goals: write the failing test, then make it pass; make sure tests pass before and after a refactor.

## Issues

To create an issue, follow the `create-issue` skill: [.agents/skills/create-issue/SKILL.md](.agents/skills/create-issue/SKILL.md). Read it even if your tool doesn't load skills automatically.

- Create issues through the templates in `.github/ISSUE_TEMPLATE/` (**Feature / improvement** or **Bug report**); blank issues are disabled.
- Search existing issues before creating one.
- **Done when** must contain checkable criteria under **Must have** and, optionally, **Nice to have**. Write each item so a reviewer can verify it without asking.

## Branches and commits

- Never commit or push to `main` directly. Work on a branch: `<issue-number>-<short-slug>` when there is an issue, `<short-slug>` otherwise.
- Commit or push only when the user asks.
- Keep each branch and PR to one issue or one change. Raise unrelated findings as a separate issue or tell the user; don't fold them in.
- Never commit data, model outputs, credentials or `.env`. Data lives under `INGEST_ROOT` / `SCRATCH_ROOT`.
- If you change dependencies in `pyproject.toml`, commit the updated `uv.lock`.

## CI

CI runs the lint, type and test checks on every pull request. Rely on it rather than running them locally:

- After opening or updating a pull request, check the CI result.
- If CI fails, fix the cause and push again. If you can't fix it, say so in the PR.
- Never skip or disable a check, test or type check to make CI pass.

## Pull requests

**Title**: [Conventional Commits](https://www.conventionalcommits.org/), imperative, because it becomes the squash-merge commit on `main`:

```
<type>: <what changes>
```

Types: `feat`, `fix`, `docs`, `refactor`, `test`, `chore`.

**Description**: write it yourself, covering these sections in this order:

1. **Problem**: what the change solves, with `Closes #<issue>` when there is an issue.
2. **Change**: what was done and why this approach.
3. **Done when**: the must-haves (from the issue, or written here when there is none), ticked off only when actually met; nice-to-haves left open or moved to a follow-up issue.
4. **Testing**: tests added or updated, checks run and their outcome, and any pipeline run used to verify (countries / tiles, methodology).
5. **Impact on outputs**: whether emissions factors or other published outputs change, which ones, and by roughly how much; "None" if not.
6. **Dependencies**: other PRs or issues this one depends on; "None" if not.

Also:

- State in the description that the PR was prepared with an AI agent, and which one.
- Open it as a **draft** unless the user asks for a ready-for-review PR.
- Don't merge, approve, or enable auto-merge; a human reviews and merges.
- Update `docs/` when methodology, data sources or behaviour change.

## Code review

Review happens in two stages, tracked with labels:

1. **AI review.** An agent reviews the PR and posts one comment ending in a verdict, then labels it:
- `llm-changes-needed`: problems found; the author or agent iterates, then asks for another AI review.
- `ready-for-human-review`: no blocking problems; a human reviewer takes over.
2. **Human review.** Merging into `main` needs one approving review, every review thread resolved, CI passing, and the branch up to date with `main`.

`needs-rebase` is set and cleared automatically when a PR conflicts with or falls behind `main`; rebase on `main` when you see it.

When reviewing a PR as an agent, swap the labels instead of adding a second one, and never approve: approval is a human's call.

When addressing review comments:

- Address every comment, or reply with the reason you didn't.
- Don't reply "done" on each comment; push the changes and leave one summary comment.
- Check whether the same problem appears elsewhere in the PR.
- If a fix is postponed, open a follow-up issue and link it in the reply.
9 changes: 7 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,14 @@ Also:

## Code review

A PR can merge into `main` once it has one approving review, every review thread is resolved, CI passes, and the branch is up to date with `main`.
Pull requests prepared with AI agents are reviewed in two stages, tracked with labels:

This guide does not cover AI-assisted contributions yet; guidelines for AI coding agents will be agreed separately.
1. **AI review first.** An agent reviews the PR, posts a comment ending in a verdict, and labels it:
- `llm-changes-needed`: problems found; the author iterates, then asks for another AI review.
- `ready-for-human-review`: no blocking problems; a human reviewer takes over.
2. **Human review.** A PR can merge into `main` once it has one approving review, every review thread is resolved, CI passes, and the branch is up to date with `main`.

AI coding agents follow [AGENTS.md](AGENTS.md), which applies the same rules.

`needs-rebase` is set and cleared automatically when a PR conflicts with or falls behind `main`; rebase on `main` when you see it.

Expand Down