From 9f060db93cb299d1729371b10ec5c8a2cd54ef54 Mon Sep 17 00:00:00 2001 From: lukabor Date: Thu, 28 May 2026 23:37:48 +0200 Subject: [PATCH] add skills: r-style (box/tidyverse/dtplyr) + jj-atomic --- README.md | 4 + skills/engineering/r-style/SKILL.md | 56 ++++++++++++ skills/engineering/r-style/box.md | 90 +++++++++++++++++++ skills/engineering/r-style/dtplyr.md | 94 +++++++++++++++++++ skills/engineering/r-style/tidyverse.md | 105 ++++++++++++++++++++++ skills/productivity/jj-atomic/SKILL.md | 98 ++++++++++++++++++++ skills/productivity/jj-atomic/examples.md | 93 +++++++++++++++++++ 7 files changed, 540 insertions(+) create mode 100644 skills/engineering/r-style/SKILL.md create mode 100644 skills/engineering/r-style/box.md create mode 100644 skills/engineering/r-style/dtplyr.md create mode 100644 skills/engineering/r-style/tidyverse.md create mode 100644 skills/productivity/jj-atomic/SKILL.md create mode 100644 skills/productivity/jj-atomic/examples.md diff --git a/README.md b/README.md index 6508cc8..831a014 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ skill list. - **handoff** — produce a structured handoff doc for a fresh session. - **grill-me** — Socratic loop to remove ambiguity before implementing. - **caveman** — terse-mode: no preamble, no summaries, code + one-line why. +- **jj-atomic** — atomic-commit discipline: `jj diff` → split → semantic + message; docs / docstrings / READMEs ship in the same change. ### engineering - **tdd-bdd** — strict red-green-refactor loop with BDD Given/When/Then @@ -36,6 +38,8 @@ skill list. hypothesise → instrument → fix with regression test → cleanup. - **grill-with-docs** — docs-anchored Socratic interview; updates `CONTEXT.md` inline, offers ADRs only on the three-of-three rule. +- **r-style** — Tidyverse + `box::use` + `dtplyr` standards with + paired good/bad sibling docs (`box.md`, `tidyverse.md`, `dtplyr.md`). ## Adding a skill diff --git a/skills/engineering/r-style/SKILL.md b/skills/engineering/r-style/SKILL.md new file mode 100644 index 0000000..7d66c12 --- /dev/null +++ b/skills/engineering/r-style/SKILL.md @@ -0,0 +1,56 @@ +--- +name: r-style +description: Project R coding standards — Tidyverse style, `box::use` for imports (no `library()` / `source()`), `purrr::chuck`/`pluck` instead of `$`/`[[`, `purrr::map`/`walk` instead of `for`, and `dtplyr` for large data.table work. Use when the user writes or edits R code, asks "is this R idiomatic", "review my R style", "use box", "use dtplyr", or opens an .R / .Rmd file and asks for help. +--- + +# r-style + +## When to use +- Writing or editing R (`.R` / `.Rmd`) in a project that follows the + Tidyverse style guide. +- Reviewing R code for style / idiom. +- User says "use box", "use dtplyr", "make this tidyverse-y", "review my + R style". + +## Top-level rules +1. **Imports go through `box::use`.** No `library()` calls in `.R` or + `.Rmd` files (top-of-Rmd setup chunks included). No `source()`. See + [box.md](box.md). +2. **No `for` loops** where a `purrr` mapping fits. Prefer `map`/`walk`/ + `map_chr`/`map_dfr`/`pmap`. See [tidyverse.md](tidyverse.md#for-loops). +3. **No raw `$` or `[[`** on named lists / S3 objects when the key could + be missing. Use `purrr::chuck()` (strict — errors on miss) or + `purrr::pluck()` (lenient — `NULL` on miss). See + [tidyverse.md](tidyverse.md#extraction). +4. **`dtplyr` for large pipelines.** When chained `dplyr` verbs hit + `data.table`-class objects above ~1 M rows, wrap with + `data.table::lazy_dt(df)` and exit with `as_tibble()`. See + [dtplyr.md](dtplyr.md). + +## Tooling, not enforcement +The skill states the rules; `styler::style_pkg()` and `lintr` enforce them. +Mention these when relevant; never invoke them as part of editing the +file under review. + +## Guardrails +- **Never** add `library()` to fix an import — replace the underlying + call with `pkg::fn()` or add a `box::use` line. +- **Never** introduce a `for` loop "just to keep the diff small". If the + surrounding code is loop-based, flag it and ask before changing scope. +- **Never** silently swap `$` for `chuck`. They have different failure + modes — `chuck` errors loudly, which is the right default but a + behaviour change. Confirm before flipping in legacy code. +- **Never** wrap small frames with `lazy_dt`. The overhead exceeds the + saving. See [dtplyr.md](dtplyr.md#when-not-to-use). + +## See also +- [../tdd-bdd/deep-modules-r.md](../tdd-bdd/deep-modules-r.md) — + `box::export()` is the public-surface control mechanism. +- [../tdd-bdd/interface-design-r.md](../tdd-bdd/interface-design-r.md) — + pure functions + DI compose with these style rules. +- [../diagnose/feedback-loops-r.md](../diagnose/feedback-loops-r.md) — + worked example #1 (in-place mutation) is the canonical `dtplyr` / + `data.table::copy()` failure mode. +- [../../productivity/jj-atomic/SKILL.md](../../productivity/jj-atomic/SKILL.md) + — when a style refactor changes more than one file, it's an atomic + commit of its own. diff --git a/skills/engineering/r-style/box.md b/skills/engineering/r-style/box.md new file mode 100644 index 0000000..e126760 --- /dev/null +++ b/skills/engineering/r-style/box.md @@ -0,0 +1,90 @@ +# Imports with `box::use` + +`box::use` replaces both `library()` and `source()`. It gives function- +level imports (so you see exactly what each file depends on), aliasing, +and module reload semantics — none of which `library` provides. + +## Canonical import block + +The project pattern, from a real cache module: + +```r +box::use( + nanoparquet[read_parquet, write_parquet], + jsonlite[toJSON, fromJSON], + fs[dir_create, dir_exists, file_exists, file_info], + tibble[tibble], + ./log[relocate_log, log_msg, setup_log, ensure_log] +) +``` + +Rules of thumb: +- **One `box::use(...)` block per file**, at the top, no trailing + `library()` calls. +- **Name the imports** (`pkg[fn1, fn2]`). Avoid `pkg[...]` — the wildcard + hides the contract. +- **Relative paths for in-repo modules** (`./log`, `../indication/client`). +- **Sort alphabetically** within the block; in-repo modules last. + +## Aliased imports + +When you'd rather keep the package name visible: + +```r +box::use( + dp = dplyr, + dt = data.table[setDT, setnames], +) + +result <- df |> dp$filter(x > 0) |> dp$summarise(n = dp$n()) +``` + +This is the project's preferred form when calling many functions from one +package — avoids 12 names in the import list and keeps grep-ability. + +## Public surface = `box::export` + +When writing a `box` module: + +```r +# R/indication/client.R +box::export(query_dataset) # only this is callable from outside + +query_dataset <- function(id) { ... } +prepare_request <- function(id) { ... } # internal — invisible to callers +fetch_pages <- function(req) { ... } +``` + +Keep `box::export()` deliberately small — see +[../tdd-bdd/deep-modules-r.md](../tdd-bdd/deep-modules-r.md). Every name +you export is a contract you owe future callers and tests. + +## Anti-patterns + +### `library()` at the top of a file — BAD +```r +# R/base/ntcs.R +library(readr) # leaks into every chapter that sources this +read_csv("...") +``` +**Fix:** +```r +box::use(readr[read_csv]) +read_csv("...") +``` +In a bookdown repo a stray `library()` in an early chapter can change +later chapters silently (e.g. `dplyr` masking `stats::filter`). Always +scoped imports. + +### `source()` — BAD +```r +# R/base/dw_base_data.R +source("R/base/dw_hippie.R", local = TRUE) +``` +**Fix:** +```r +box::use(./dw_hippie[load_hippie]) +load_hippie() +``` +`source` runs the whole file for its side effects; you cannot see what +landed in your namespace, and you cannot test it in isolation. diff --git a/skills/engineering/r-style/dtplyr.md b/skills/engineering/r-style/dtplyr.md new file mode 100644 index 0000000..1267804 --- /dev/null +++ b/skills/engineering/r-style/dtplyr.md @@ -0,0 +1,94 @@ +# `dtplyr` — `data.table` speed, `dplyr` surface + +`dtplyr` lets you keep the `dplyr` verb chain while executing on +`data.table` internals. The right call for large-frame chained +aggregations; the wrong call for small frames and for one-off operations. + +## When to use + +- Frames ≳ 1 M rows that go through several chained `dplyr` verbs. +- A pipeline whose intermediate steps would each materialise a copy in + base `dplyr`; `dtplyr` collapses them into one `data.table` expression. +- The caller wants a `tibble`, not a `data.table`, on the way out. + +## Canonical pattern + +```r +box::use( + dt = data.table[lazy_dt], + dplyr[filter, group_by, summarise, n], + tibble[as_tibble], +) + +agg_expression <- function(df) { + df |> + dt$lazy_dt() |> + filter(expr > 0) |> + group_by(gene_id, tissue) |> + summarise(n_cells = n(), mean_expr = mean(expr), .groups = "drop") |> + as_tibble() +} +``` + +Three rules: +- **Enter with `lazy_dt()`**, **exit with `as_tibble()`** unless the + caller documented a `data.table` contract. Never leak a lazy frame. +- **No `collect()` mid-pipeline.** The point is one fused expression. +- **No `:=` inside the chain.** Reference semantics defeat lazy + evaluation; if you need it, drop out to plain `data.table`. + +## Reference-semantics warning + +`data.table` mutates in place. A function that accepts a `data.table` and +"just does a tweak" may silently change every caller's copy. + +### Bad +```r +# Caller passes a data.table; we silently mutate it. +add_log_expr <- function(dt_in) { + dt_in[, log_expr := log1p(expr)] # mutates the caller's object + dt_in +} +``` +Two calls in a row look idempotent and aren't: +```r +x <- as.data.table(data.frame(expr = c(1, 2, 3))) +add_log_expr(x); add_log_expr(x) # log_expr column now wrong +``` + +### Good — copy at the boundary +```r +add_log_expr <- function(dt_in) { + dt_in <- data.table::copy(dt_in) # defensive copy at the seam + dt_in[, log_expr := log1p(expr)] + dt_in +} +``` +Or, better, stay in the `dtplyr` lane and don't take a `data.table` at +all: +```r +add_log_expr <- function(df) { + df |> dt$lazy_dt() |> mutate(log_expr = log1p(expr)) |> as_tibble() +} +``` +This is exactly the bug class covered in +[../diagnose/feedback-loops-r.md](../diagnose/feedback-loops-r.md) +*"Worked example 1 — in-place mutation, intermittently wrong output"*. +Read that before you reach for `:=`. + +## When NOT to use + +- Frames < ~100 K rows. The `data.table` setup cost dominates; `dplyr` + on a `tibble` is the same speed or faster. +- Single-verb operations (just `filter`, just `mutate`). No fusion to + gain. +- When the caller relies on `data.table` reference semantics in your + return value. `as_tibble()` materialises and copies. +- Inside `targets` pipelines where the target's contract is a `tibble` — + don't surprise downstream targets with a `data.table`. + +## See also +- [box.md](box.md) — preferred way to bring `data.table` / `dtplyr` + names into scope (`dt = data.table[...]`). +- [../tdd-bdd/interface-design-r.md](../tdd-bdd/interface-design-r.md) — + "return, don't mutate" applies even harder to `data.table`. diff --git a/skills/engineering/r-style/tidyverse.md b/skills/engineering/r-style/tidyverse.md new file mode 100644 index 0000000..c0e668e --- /dev/null +++ b/skills/engineering/r-style/tidyverse.md @@ -0,0 +1,105 @@ +# Tidyverse style — paired good/bad + +Follows the [Tidyverse style guide](https://style.tidyverse.org/) where it +matches the project's idiom. Four substitutions matter most. + +## 1. `for` loops → `purrr` mapping + +### Bad — real example, list-column flattening +```r +# R/base/cache.R +for (col in names(df)) { + if (is.list(df[[col]])) { + df[[col]] <- vapply(df[[col]], function(v) { + if (is.null(v) || (length(v) == 1 && is.na(v[[1]]))) NA_character_ + else if (length(v) == 1) as.character(v[[1]]) + else toJSON(v, auto_unbox = TRUE) + }, character(1)) + } +} +``` +The loop mutates `df` by column-name lookup; the intent ("flatten every +list column to a character vector") is buried. + +### Good +```r +flatten_one <- function(v) { + if (is.null(v) || (length(v) == 1 && is.na(v[[1]]))) NA_character_ + else if (length(v) == 1) as.character(v[[1]]) + else jsonlite::toJSON(v, auto_unbox = TRUE) +} + +df <- df |> + dplyr::mutate(dplyr::across( + dplyr::where(is.list), + \(col) purrr::map_chr(col, flatten_one) + )) +``` +Intent visible at the call site; the row-level transform is a pure +function (`flatten_one`) you can test in isolation. + +## 2. `library()` → `pkg::fn()` or `box::use` + +### Bad — real example +```r +# R/base/ntcs.R +library(readr) +read_csv("...") +``` + +### Good +```r +box::use(readr[read_csv]) +read_csv("...") +``` +See [box.md](box.md) for the longer argument. + +## 3. `$` / `[[` → `purrr::chuck` / `pluck` + +### Bad — real example, silent NA on missing key +```r +# R/base/query_ntcs.R +patentNumber = map_chr(patents, ~ paste(.x[["patentNumber"]], collapse = "; ")), +publicationDate = map_chr(patents, ~ paste(.x[["publicationDate"]], collapse = "; ")) +``` +If a patent record is missing `patentNumber`, `.x[["patentNumber"]]` +returns `NULL`, `paste(NULL, collapse = "; ")` returns `""`, and the row +goes out wrong with no warning. + +### Good +```r +patentNumber = purrr::map_chr(patents, \(p) paste(purrr::chuck(p, "patentNumber"), collapse = "; ")), +publicationDate = purrr::map_chr(patents, \(p) paste(purrr::chuck(p, "publicationDate"), collapse = "; ")) +``` +`chuck` errors at the missing key — you find the schema bug in the first +test run instead of seeing empty cells in a rendered report. When a +missing key is genuinely OK, use `purrr::pluck(p, "patentNumber", +.default = NA_character_)` — the *intent* (lenient default) is now in the +code, not in the absence of an error. + +## 4. `source()` → `box::use` + +### Bad — real example +```r +# R/base/dw_base_data.R +source("R/base/dw_hippie.R", local = TRUE) +``` + +### Good +```r +box::use(./dw_hippie[load_hippie]) +load_hippie() +``` +See [box.md](box.md). `source` is invisible imports + arbitrary side +effects; `box::use` is named imports + tested boundaries. + +## Tooling + +- `styler::style_pkg()` — auto-format to Tidyverse rules. +- `lintr` — flag violations in CI; configure with `.lintr` at the repo + root. + +The skill states the rules. The tools enforce them. Don't run tooling +inside the edit you're being asked to review — that conflates style +changes with logic changes (anti-atomic — see +[`../../productivity/jj-atomic/SKILL.md`](../../productivity/jj-atomic/SKILL.md)). diff --git a/skills/productivity/jj-atomic/SKILL.md b/skills/productivity/jj-atomic/SKILL.md new file mode 100644 index 0000000..3234012 --- /dev/null +++ b/skills/productivity/jj-atomic/SKILL.md @@ -0,0 +1,98 @@ +--- +name: jj-atomic +description: Atomic-commit discipline with jujutsu — read every diff line before describing, split mixed changes with `jj split`, write semantic commit messages (`type(scope): imperative phrase completing "this change will…"`), and update docs / docstrings / READMEs in the same change as the code. Use when the user says "commit", "jj describe", "split this change", "atomic commit", "what's the commit message", or is about to seal a working copy that touches more than one logical concern. +--- + +# jj-atomic + +## When to use +- User says "commit", "jj describe", "atomic commit", "split this + change", "what should the commit message be". +- A working copy contains changes that touch more than one concern. +- A public function signature, CLI flag, env var, or config key changed + and the docs haven't. + +## Principles + +### 1. Inspect first +**Never describe from memory. Read the diff.** +- `jj diff` (whole change) or `jj diff ` (one file). +- Read every changed line. Flag debug code, commented-out blocks, + unrelated whitespace, accidental edits. +- If the diff doesn't match what was intended, fix or split before + describing. + +### 2. One concern per change +**Each `jj describe` covers exactly one logical thing.** +- If the diff touches two areas (a bug fix and a refactor; two + unrelated features), **`jj split`** before describing. +- Style refactors are their own change — they shouldn't share a commit + with logic changes (see [`../../engineering/r-style/tidyverse.md`](../../engineering/r-style/tidyverse.md#tooling)). +- Test additions for an existing feature are their own change unless + they accompany a new behaviour landing in the same diff. + +### 3. Semantic format +``` +type(scope): imperative phrase completing "this change will…" +``` +- `type` ∈ `feat`, `fix`, `refactor`, `perf`, `test`, `docs`, `build`, + `chore`, `style`. +- Imperative voice: **"add"**, **"fix"**, **"remove"**, **"update"** — + never "added", "adding", "adds", "now does X". +- Subject ≤ 72 chars. Body bullets ≤ 90 chars. +- Body uses the same `type(scope): imperative` shape per sub-change. + +### 4. Ticket references (optional, project-configurable) +If the project uses a ticket prefix (e.g. `DRAKE-42`, `JIRA-101`, +`CIRI-7`), use these verbs in the body: +- `starts -N` — first commit on a ticket. +- `extends -N` — incremental progress. +- `ends -N` — final commit closing the ticket. + +If the project has no ticket convention, omit. Don't invent a prefix. + +### 5. Docs travel with the code +The same `jj describe` must include any of: +- Updated docstring for a changed public function signature. +- Updated README / CLAUDE.md for a new CLI flag, script, env var, or + command. +- A new doc under `docs/` for any analysis whose result is **not + self-evident from reading the code** (e.g. a derived statistic, a + threshold choice, a non-trivial pipeline output). Describe: how it + was run, inputs, how to read the result, what was concluded. +- One-line docstrings are fine. No docstring is not. + +## Workflow + +``` +jj diff # 1. read every line +# bad? --> fix or: +jj split # 2. one concern per change +jj describe -m '...' # 3. semantic message +jj diff --revision @- # 4. verify the message matches what shipped +``` + +## Anti-patterns +- **`jj describe` before `jj diff`.** You'll commit debug `cat()`s, + stray `browser()` calls, and TODO scratchpads. +- **"Mixed bag" commits.** `refactor + fix + new feature` in one change + is three regressions waiting to happen and an unrevertable mess. +- **Past-tense / declarative messages.** `"added auth"`, `"auth now + works"`. These don't complete "this change will…". +- **No scope.** `feat: add login` is weaker than `feat(auth): add + OAuth2 login flow`. Scope is the smallest area the change touches. +- **Docs in the next commit.** "I'll update the README after." You + won't. Same change or it doesn't ship. + +## Examples +See [examples.md](examples.md) for a real before/after where a +working-copy is split into two atomic commits with proper messages. + +## See also +- [`../../engineering/r-style/SKILL.md`](../../engineering/r-style/SKILL.md) + — style refactors are their own atomic change. +- [`../../engineering/tdd-bdd/SKILL.md`](../../engineering/tdd-bdd/SKILL.md) + — the regression test for a bug fix lands in the *same* atomic change + as the fix. +- [`../../engineering/diagnose/SKILL.md`](../../engineering/diagnose/SKILL.md) + — phase-6 post-mortem commit message names the confirmed hypothesis. diff --git a/skills/productivity/jj-atomic/examples.md b/skills/productivity/jj-atomic/examples.md new file mode 100644 index 0000000..9c52aa4 --- /dev/null +++ b/skills/productivity/jj-atomic/examples.md @@ -0,0 +1,93 @@ +# Worked example — splitting a mixed change + +A real shape: the working copy contains both a style refactor (replacing +`source()` with `box::use`) **and** a bug fix (adding a defensive +`data.table::copy()` at a boundary). They must not share a commit. + +## Before — `jj diff` (mixed) + +``` +M R/base/dw_base_data.R +- source("R/base/dw_hippie.R", local = TRUE) ++ box::use(./dw_hippie[load_hippie]) ++ load_hippie() + +M R/indication/assemble_expr.R ++ dt_in <- data.table::copy(dt_in) + dt_in[, log_expr := log1p(expr)] + dt_in +``` + +Two concerns, one working copy. Splitting before describing. + +## The split + +```bash +jj diff # confirm what's there +jj split R/indication/assemble_expr.R # interactive — keep only the fix +# leaves the box::use change in the new child commit +jj describe -r @- -m "" +jj describe -m "" +``` + +(`jj split ` puts the named paths in the *parent* of the new +commit; the remaining paths stay in `@`. Adjust per `jj` version.) + +## After — two atomic commits + +### Commit A — the bug fix (lands first; ticket starts here) + +``` +fix(indication/assemble_expr): defensive copy of input data.table; starts DRAKE-NN1 + +* fix(indication/assemble_expr): copy() at boundary to stop in-place mutation; extends DRAKE-NN1 +* test(indication/assemble_expr): add idempotence test; extends DRAKE-NN1 +* docs(indication/assemble_expr): note reference-semantics contract; extends DRAKE-NN1 +``` + +Why this works: +- Subject is one concern (the fix) and reads naturally after "this + change will…". +- Body bullets are each one concern, each `type(scope): imperative`. +- The test ships with the fix (see + [`../../engineering/tdd-bdd/SKILL.md`](../../engineering/tdd-bdd/SKILL.md)). +- The docstring update ships with the fix (see + [SKILL.md §5](SKILL.md)). + +### Commit B — the style refactor + +``` +refactor(base): replace source() with box::use for dw_hippie; ends DRAKE-NN2 + +* refactor(base/dw_base_data): swap source() for ./dw_hippie box import; ends DRAKE-NN2 +``` + +Why this works: +- A style refactor is **never** part of a logic change. +- One-bullet body is fine when the subject already says everything. +- Different ticket because it's a different concern. + +## Anti-pattern — what NOT to do + +``` +fix: refactor and fix assemble_expr ← two concerns +* added defensive copy ← past tense +* swapped source() for box::use ← past tense, mixed concern +* updated README ← what changed in it? +``` + +Every line is wrong: +- Subject claims two concerns (`refactor and fix`). +- No scope (`fix:` not `fix(indication/assemble_expr):`). +- Past tense (`added`, `swapped`, `updated`). +- Vague body (`updated README` — for what?). + +## Verifying after describe + +```bash +jj log -r '::@' --no-graph -T 'change_id.shortest() ++ " " ++ description.first_line() ++ "\n"' | head -5 +jj diff -r @- # the bug fix +jj diff # the refactor +``` +Each commit's diff matches its message. If it doesn't, `jj split` again +or `jj describe` with a corrected message.