Writing Good Software, and AI That Follows Your Rules

Week 9 · Thursday, Nov 19 · Lecture

Dr. Marcela Alfaro Córdoba

Today’s plan

Time What
1:30 Tuesday is code review: what “ready” means
1:35 Recommendations: ten habits of good research code
2:00 AI audit #2: review the example repository
2:25 Using AI with rules: AGENTS.md, STYLE.md, short prompts
2:50 AI ethics discussion
3:00 Before Tuesday

Learning goals: name and apply habits that make code readable, checkable and reproducible; find their violations in code that runs; write an instruction file that sets boundaries for an AI assistant; keep prompts short by putting stable context in files.

No AI in today’s audit or discussion.

Tuesday, Nov 24: peer code review, in class

Important

Tuesday’s lecture is the peer review (5%). You review a classmate’s repository in class, written by you, no AI, submitted before you leave. The assignments are posted on Ed on Monday.

Your repository must be review-ready by Tue 1:30 pm:

Recommendations

Ten habits of good research code

# Habit One-line test
1 One folder, one job. Raw data is read-only Could you delete output/ and get it back?
2 Names say what a thing is Would a stranger know what df2 holds?
3 No magic numbers Does 2007 appear in more than one place?
4 Don’t repeat yourself Did you copy a block a second time?
5 Comments explain why, and stay true Does the comment still match the code?
6 Fail loudly Does a broken assumption stop the render?
7 Missing values are a decision Do you know how many rows each step dropped?
8 Relative paths, fresh session Does it render from a fresh clone?
9 Let tools check style Have you run lintr / styler?
10 Small commits that say what changed Could you find the commit that broke it?

2-3. Names and magic numbers

Before

tmp <- survey |>
  filter(age >= 18)
x <- tmp |>
  filter(visits > 4)
df2 <- x |> count(site)

After

adult_age <- 18
frequent_visits <- 4

adults <- survey |>
  filter(age >= adult_age)
frequent_adults <- adults |>
  filter(visits > frequent_visits)
frequent_by_site <- frequent_adults |>
  count(site)

A number that means something gets a name, once. Change the threshold in one place, and every use changes with it. In a runbook, the name can be a Quarto parameter (params: in the YAML header, params$adult_age in R).

4. Don’t repeat yourself

Before: the same block three times. The third copy already differs (spot it?)

age_by_site     <- survey |> group_by(site) |> summarize(age = round(mean(age), 1))
visits_by_site  <- survey |> group_by(site) |> summarize(visits = round(mean(visits), 1))
commute_by_site <- survey |> group_by(site) |> summarize(commute = round(mean(commute_min), 2))

After: one call, one rule

by_site <- survey |>
  group_by(site) |>
  summarize(across(c(age, visits, commute_min), ~ round(mean(.x, na.rm = TRUE), 1)))

Copies drift. When you fix a bug in one, you forget the others. Two copies: think about it. Three: write a function or use across().

5-7. Comments, failing loudly, missing values

# keep the survey's adult respondents        <- WHAT. And wrong if the threshold changes
# The IRB approval covers adults only (18+)  <- WHY. Stays true

stopifnot(!any(duplicated(sites$site)))      # a duplicated key would duplicate rows in the join
clean <- na.omit(joined)                     # drops a row if ANY column is NA. Which? How many?

clean <- joined |> filter(!is.na(commute_min))           # only the column this step needs
cat("Dropped", nrow(joined) - nrow(clean), "rows with no commute\n")

na.omit() on a whole table is a silent decision about every column, including the ones you never look at.

9. Let tools check style

Language Style guide Check Fix
R tidyverse style guide lintr::lint("R/02-clean.R") styler::style_file("R/02-clean.R")
Python PEP 8 ruff check python/ ruff format python/
  • Write your project’s choices in a short STYLE.md: the guide you follow, plus your own rules (“never na.omit() a whole table”)
  • It’s for your partner, your reviewer, future you… and the AI assistant

lintr would have found na.rm = T (write TRUE: T is a variable anyone can overwrite).

AI audit #2

Your turn: review the example repository

⏱ 20 min

The example repo was drafted with an AI assistant and reviewed by me. It renders without errors. It also breaks several of our ten habits, and its own STYLE.md.

In pairs, no AI:

  1. Read STYLE.md, then R/02-clean.R, R/03-reshape-join.R, R/04-describe.R, python/summarize.py
  2. List every violation: file, line, which habit, and the fix
  3. Find the one that changes the results. Hint: compare the subtitle of the runbook with the sentence under Step 3
  4. Post your list on the Ed thread “AI audit #2”

Running lintr::lint() is allowed. It’s a tool, not an AI, and it finds some of them (not the important one).

What we found

Collect the class list on the board. Then:

  • Which violations would lintr or ruff have caught? Which needed a person who knew the data?
  • The na.omit() one: how many rows, years and countries disappeared? Would you have noticed from the figures alone?
  • The AI’s draft ran, looked tidy, and had good comments in most places. Why is this kind of error easy to miss?

Code that runs is not code that is right.

Fixing these is optional practice. Fork the repo and try. You’ll use the same eye on Tuesday.

Using AI with rules

An instruction file

Most AI coding tools read a project file before every task:

Tool Reads
Many tools (Codex, Cursor, Copilot agents, …) AGENTS.md
Claude Code CLAUDE.md (the example’s CLAUDE.md only says @AGENTS.md)
GitHub Copilot .github/copilot-instructions.md

What goes in it, in the example repo’s AGENTS.md:

  1. What this project is, in 3 lines, and the order of the pipeline
  2. Boundaries: what it must never do
  3. How to work: small changes, follow STYLE.md, explain each change
  4. How to check: the render completes, and row counts don’t change unless they should

Boundaries

From the example’s AGENTS.md:

## Boundaries: never do these

- Never modify, rename, or delete anything in `data/raw/`.
- Never add an R or Python package without asking first.
- Never use absolute paths, `setwd()`, or `rm(list = ls())`.
- Never download data or call external services.
- Never edit the "AI use" section of `run-analysis.qmd`; the humans write it.
- Never change results silently: if a change alters a number,
  a row count, or a figure, say so.

Your boundaries should include the course AI policy: it may help you work, it may not do your understanding for you. “Don’t write the interpretation of results” is a fair boundary for this class.

Short prompts

Long and vague

I’m working on an R project for my stats class about library visits. We have survey data in two waves and we joined them with sites, and I use dplyr and ggplot. Please use tidyverse style and don’t use absolute paths. Can you look at my code and make it better and fix any problems? Also make the plots nicer.

Short and specific (the context is already in AGENTS.md + STYLE.md)

In R/04-describe.R, the three summarize() blocks repeat. Replace them with one across(). Show me the diff; don’t change anything else.

Stable context goes in files, written once. Each prompt: one task, one file, the check you want. Ask for a diff, not a rewrite. Read it before you accept it.

Why minimize prompts

  • You stay in charge. One small change at a time is one you can understand and explain on Dec 3
  • Less drift. Long conversations forget early instructions; the file is re-read every time
  • Less waste. Every prompt and every regenerated file costs compute, energy and water, and your time reviewing it
  • Reviewable. A small diff can be reviewed; a rewritten file can’t

Your turn: your project’s AGENTS.md and STYLE.md

⏱ 10 min

  1. Copy AGENTS.md and STYLE.md from the example repo into your project
  2. Rewrite “What this project is” for your pipeline
  3. Add one boundary that is specific to your data (a file that must never change? a variable that must never be imputed?)
  4. Add one style rule your team actually disagrees about, and decide it
  5. Commit both

These files are part of Tuesday’s review. Using AI on your project after today? Note in your “AI use” section that it worked under your AGENTS.md.

AI ethics

Discussion: 15 minutes

⏱ 15 min

Groups of 3-4. Pick one question, then share with the class. There’s no right answer; bring a view and a reason.

  1. Training data. The models that write code learned from public code, much of it written by people who never agreed to that. Does that change how you should use the output?
  2. Bias and fairness. Your AI assistant suggests dropping “outliers” in a survey of a small community. Whose data disappears?
  3. Environmental cost. Is a 30-prompt conversation to fix one plot worth it? When would you rather think for 10 minutes?
  4. Intellectual property. If the AI wrote half of a function, whose code is it? What does your “AI use” section owe the reader?

Ed thread “AI ethics”: one post per group, your question, and the strongest disagreement you had.

Key points

  • Ten habits: one folder one job, clear names, no magic numbers, don’t repeat yourself, comments that explain why, fail loudly, decide on missing values, relative paths and a fresh session, tools for style, small commits
  • Code that runs is not code that is right. AI-drafted code makes this the default problem
  • STYLE.md: your rules, written once, for humans and AI
  • AGENTS.md: what the project is, what the AI must never do, how it should work, how to check
  • Short prompts: one task, one file, the check you want, a diff to read

Before Tuesday

Tuesday, Nov 24 (lecture only, no DS section; DS 9 is on Canvas, due Wed Nov 25): peer code review, in class. Bring your laptop, charged, with your reviewer’s repository cloned if it’s posted early.