Skip to content

Coding rules

22 rule sets with 84 groups. A project switches a set on in docs/project/coding_rules.md; group IDs CR-<set>-<name> are stable.

Coding rules — Bash

Source: .act/coding/bash.md

Summary: strict mode, quoting, exit codes, error messages, shellcheck, pitfalls

Rules for Bash scripts. Group IDs (CR-bash-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Strict mode, quoting, error handling, shellcheck

Summary: set -euo pipefail, quoting, deliberate exit codes, errors on stderr, shellcheck, pitfalls

  • Start every script with set -euo pipefail as the first executable line.
  • Quote variables consistently ("$var"), especially paths that may contain spaces.
  • Set exit codes deliberately (exit 0/exit 1/specific codes) instead of letting the last command’s status pass through implicitly.
  • Check arguments and inputs before use (count, whether a path exists); report failures on stderr, and name what failed and with what — not a bare “error”.
  • Run shellcheck as the stack’s standard linter before every commit; do not suppress its warnings wholesale.
  • Pitfalls:
    • Never parse the output of ls in a loop — use globbing or find ... -print0 with read -d ''.
    • Check the result of cd (cd dir || exit 1); otherwise following commands run in the wrong directory.

One script, one purpose

Summary: header comment, functions over duplication, single-purpose scripts

  • Start with a header comment stating purpose, an example call, and the expected output/exit behavior.
  • Use functions for reusable sections instead of copying the same command sequence.
  • One script, one clearly named purpose — no multi-purpose script with mode flags for unrelated tasks.

Coding rules — C

Source: .act/coding/c.md

Summary: language standard, memory ownership and buffers, checked return values, undefined behavior, warnings and sanitizers

Rules for C only; they do not apply to C++, whose idioms differ (RAII, containers, exceptions) and have their own set. Group IDs (CR-c-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Standard, build and warnings

Summary: fixed language standard, strict warnings as errors, clang-tidy, build system as configured

  • Take the C standard from the build configuration (-std=c11, c17, c23, or CMAKE_C_STANDARD) and use nothing newer: nullptr, constexpr, bool as a keyword and typeof are C23 only; _Generic, _Static_assert and <threads.h> need C11. Without a configured standard, assume C11.
  • Never write C++ habits into C: no cast of the malloc result, no bool/true without <stdbool.h> before C23, and declare parameterless functions as f(void), not f().
  • Take warnings seriously (-Wall -Wextra; MSVC /W4): fix one in the code, do not silence it with a cast or a pragma. Suggest -Werror (/WX) once; never set build flags unasked (R-code-tools).
  • Run clang-tidy as the usual linter and clang-format as the usual formatter, or whatever the project has configured (R-code-tools); keep to the build system it already has (CMake, Make, Meson) and install none unasked.

Buffers and ownership

Summary: every buffer carries its size, one owner per allocation, no unbounded string functions

  • Pass a buffer together with its size and check the size before writing; never gets, strcpy, strcat or sprintf into a fixed buffer — use snprintf and memcpy with an explicit length, and terminate strings yourself where the function does not (strncpy).
  • Every malloc/calloc/realloc result is checked for NULL before use. realloc goes into a temporary, so the old pointer is not lost on failure.
  • Compute allocation sizes from the target (malloc(n * sizeof *p)), and check the multiplication for overflow first (calloc does it for you).
  • Each allocation has exactly one owner, named in a comment or the function’s header comment: who frees it, and who may only borrow it. Free once, set the pointer to NULL afterwards where it stays in scope, and release on every error path (a single goto cleanup exit is the accepted idiom).
  • Never return or store a pointer to a local (stack) variable.

Return values and undefined behavior

Summary: no ignored errors, integer overflow, signed/unsigned and strict aliasing

  • Check the return value of every call that can fail (fopen, fread, fwrite, fclose, snprintf truncation, read/write, pthread_*); an error message names the call, its argument and errno (strerror).
  • Signed integer overflow is undefined behavior: validate operands before the arithmetic, not after. Use size_t for sizes and indices, and never compare signed with unsigned without an explicit conversion. Check shift counts, division by zero and INT_MIN / -1.
  • Do not read an object through a pointer of an incompatible type (strict aliasing) or an uninitialized variable; use memcpy for type punning and initialize at declaration.
  • Make unused parameters and switch fallthrough explicit ((void)x;, a comment, or [[fallthrough]] in C23), not silent.

Tests under sanitizers

Summary: tests run with ASan and UBSan, test runner as configured

  • Run the test suite at least once with -fsanitize=address,undefined -fno-omit-frame-pointer (MSVC: /fsanitize=address); a sanitizer report is a failure, never suppressed to get green (R-code-checks-intact).
  • Use the test framework the project has set up (Unity, Check, CMocka, or plain ctest); do not add one unasked. Cover the error path of each allocation or I/O call, not only the happy path.

Coding rules — CI

Source: .act/coding/ci.md

Summary: pinned actions, minimal permissions, injection-safe workflows, secrets, caching and concurrency for GitHub Actions and GitLab CI

Rules for pipeline definitions: GitHub Actions (.github/workflows/*.yml) and GitLab CI (.gitlab-ci.yml). A pipeline runs with the project’s secrets and write access, so these rules extend the safety rules (R-safe-no-secret-log, R-safe-no-secret-cli, R-safe-approval). Group IDs (CR-ci-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Pin what the pipeline runs

Summary: actions and includes pinned to a commit SHA, minimal token permissions, automated updates

  • GitHub: pin every third-party action to the full 40-character commit SHA, with the version as a trailing comment (uses: actions/checkout@<sha> # v4.2.2). A tag or branch can be moved by its owner and runs new code in your pipeline unseen. Check the SHA belongs to the upstream repository.
  • GitLab: pin include: project/remote and CI images to a commit SHA or an image digest, never to main or latest.
  • Set permissions: at the top of every workflow, to contents: read, and widen it per job only where a job needs it (pull-requests: write, id-token: write). Never leave the default token scope to the repository setting.
  • Prefer short-lived OIDC credentials (id-token: write, GitLab id_tokens:) to long-lived cloud keys stored as secrets.
  • Keep pins current with the project’s updater (Dependabot or Renovate) rather than by hand; a pin nobody updates turns into an unpatched dependency.
  • actions/checkout with persist-credentials: false unless a later step pushes.

Untrusted input never reaches a shell or a privileged run

Summary: no event data inline in run:, no pull_request_target with fork code, no secrets for forks

  • Never put ${{ github.event.* }}, github.head_ref, an issue/PR title, body, branch name or commit message directly in a run: script — the text is substituted before the shell parses it and becomes code. Pass it through env: and use "$VAR". GitLab expands variables in the shell at run time, so the danger there is unquoted use: quote "$CI_COMMIT_MESSAGE", "$CI_MERGE_REQUEST_TITLE" and branch names inside script:, never eval or splice them.
  • pull_request_target and workflow_run run in the base repository’s context with secrets and a writable token. Never check out or run the pull request’s head (ref: ${{ github.event.pull_request.head.sha }}) there, and never run its scripts or build step. Use plain pull_request for anything that builds contributed code.
  • Fork pull requests get no secrets: do not design a check that needs one on pull_request; split it into an unprivileged build and a separate, reviewed privileged step.
  • A deploy or release job runs only on protected branches and tags (if: on the ref, GitLab rules: with $CI_COMMIT_REF_PROTECTED), behind the environment’s required approval.

Secrets stay out of logs, arguments and artifacts

Summary: secrets via secret store and environment, masked, never echoed, never in cache or artifacts

  • Take secrets from the platform’s secret store (GitHub secrets/environment secrets, GitLab masked and protected CI/CD variables) and hand them to a step through env:, not as an argument.
  • Never echo a secret or a value derived from it, and no set -x/CI debug trace in a job that has secrets. Mask a computed value with ::add-mask:: before it is printed.
  • No secret in an artifact, cache, build argument (docker build --build-arg) or uploaded report; those outlive the job and are readable by more people than the secret.
  • A secret that leaked into a log is treated as compromised and rotated, not just deleted from the log.

Caching, concurrency, timeouts

Summary: lockfile-keyed caches, concurrency groups, job timeouts, the same checks as local

  • Key a cache on the lockfile hash (hashFiles('**/package-lock.json'), GitLab cache:key:files), never on a fixed string; cache downloaded dependencies, not build output of untrusted branches.
  • Set concurrency: with cancel-in-progress: true for pull request checks; never cancel a running deploy or release — give those a group without cancellation. GitLab: interruptible: true and resource_group for deploys.
  • Set timeout-minutes: (GitLab timeout:) on every job; the platform default is hours.
  • CI runs the same commands the project documents for local use (docs/ai/config.md, R-code-tools) — no check that exists only in the pipeline. A failing check is fixed in the code, not skipped or set to continue-on-error (R-code-checks-intact).
  • GitLab: use rules:, not the deprecated only:/except:.

Coding rules — C++

Source: .act/coding/cpp.md

Summary: language standard, RAII and ownership, const and Rule of Zero, warnings and sanitizers, CMake and tests

Rules for C++ only; they do not apply to C, whose code is written with manual memory management and C idioms and has its own set. Group IDs (CR-cpp-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Standard, build and warnings

Summary: standard from the build, features gated by it, strict warnings, clang-tidy, CMake

  • Take the standard from the build configuration (CMAKE_CXX_STANDARD, -std=c++17, 20, 23) and use nothing newer. Per standard: std::optional, std::variant, std::string_view and structured bindings are C++17; concepts, ranges, std::span and std::format are C++20 (std::format also needs a recent standard library); std::expected and std::print are C++23. Without a configured standard, assume C++17.
  • Take warnings seriously (-Wall -Wextra -Wpedantic; MSVC /W4): fix one in the code, do not silence it with a cast or a pragma. Suggest -Werror (/WX) once; never set build flags unasked (R-code-tools).
  • Run clang-tidy as the usual linter and clang-format as the usual formatter, or whatever the project has configured (R-code-tools). CMake is the usual build system; use the one the project has (Make, Meson, Bazel) and install none unasked.
  • Do not write C into C++: no malloc/free, C-style casts, NULL (use nullptr), or raw arrays where std::array, std::vector or std::string fit.

RAII, no raw new and delete

Summary: resources owned by objects, smart pointers, Rule of Zero

  • Every resource (memory, file, lock, handle) is owned by an object that releases it in its destructor (RAII). No raw new/delete: use std::make_unique (default) or std::make_shared (only for genuinely shared ownership), containers, or std::lock_guard/std::scoped_lock.
  • A raw pointer or reference is non-owning and borrowed; never delete through it and never keep it beyond the owner’s lifetime. Do not return a reference or std::string_view to a local or temporary.
  • Rule of Zero: a class that holds only RAII members declares none of the special member functions. If one of destructor, copy or move must be written, define or delete all five (Rule of Five); mark move operations noexcept.
  • Do not let exceptions cross a C interface or leave a thread unhandled; follow the project’s existing error style (exceptions or std::expected/error codes) instead of mixing both.

const, types and undefined behavior

Summary: const by default, explicit constructors, no unchecked casts, container invalidation

  • const by default for variables, member functions and parameters; pass large read-only arguments by const&, small ones by value. Mark single-argument constructors explicit and overrides override.
  • Use static_cast and friends only where needed; no C-style casts, and never reinterpret_cast or a cast that removes const without a comment saying why it is safe.
  • Signed overflow, out-of-range operator[], use after move and use of an iterator after the container changed are undefined behavior: use .at() or check bounds where input is untrusted, and do not reuse a moved-from object except to assign to it.
  • Initialize with braces or at declaration; prefer enum class over plain enum.

Tests under sanitizers

Summary: GoogleTest or Catch2 via CTest, ASan and UBSan in the test run

  • Use the test framework the project has set up (GoogleTest or Catch2 are the usual choices), run through ctest; do not add one unasked.
  • Run the suite at least once with -fsanitize=address,undefined -fno-omit-frame-pointer; a sanitizer report is a failure, never suppressed to get green (R-code-checks-intact).

Coding rules — C#

Source: .act/coding/csharp.md

Summary: nullable context, async conventions, error handling, analyzers, DI, library code

Rules for C# projects. Group IDs (CR-csharp-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Nullable context, async, error handling, analyzers

Summary: nullable enabled, async suffix, no async void, no blocking on tasks, using, exceptions

  • Keep the nullable context (<Nullable>enable</Nullable>) on project-wide; do not suppress the warnings it produces.
  • Name asynchronous methods with the Async suffix and return Task/Task<T>.
  • Never use async void outside event handlers — use async Task, otherwise exceptions are swallowed.
  • Avoid .Result/.Wait() on tasks; blocking on a task this way risks a deadlock in synchronous contexts.
  • Manage every IDisposable resource exclusively through using/await using.
  • Use exceptions for exceptional cases, not for regular control flow — consider a return type (Result<T>/bool) for expected failure cases; wherever an exception is thrown, its message names what failed and with what.
  • Run dotnet format and the analyzer rules (.editorconfig section dotnet_diagnostic) as the stack’s standard linting/static analysis; set them up in every project, run what is installed.

var, records, one type per file

Summary: var only for an obvious type, records for value objects, one public type per file

  • Use var only when the type is obvious from the right-hand side, an explicit type otherwise.
  • Use records for immutable value objects/DTOs, classes for objects with identity and behavior.
  • One public type per file, with the file name matching the type name.

Constructor injection

Summary: constructor injection, no service locator

  • Inject dependencies through the constructor; no hidden service-locator access.

ConfigureAwait in library code

Summary: ConfigureAwait(false) in code without a UI context

  • Use ConfigureAwait(false) in library code that has no dependency on a UI context.

Coding rules — CSS

Source: .act/coding/css.md

Summary: custom-property tokens, low specificity, no !important, mobile-first, stylelint

Rules for hand-written CSS (and SCSS) in projects that do not use Tailwind. Do not tick this set in a project that ticks tailwind: utility classes and a hand-written cascade pull in opposite directions, and the rules below would contradict the Tailwind ones (@apply, separate CSS files). Group IDs (CR-css-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Design tokens as custom properties

Summary: one place for colors, spacing and type; no repeated literals; dark mode by remapping

  • Define colors, spacing, radii, font sizes and z-index layers once as custom properties on :root (--color-surface, --space-2) and use var(--…) everywhere else; a hex value or 13px repeated in rule bodies is a missing token.
  • Name tokens by role (--color-text-muted), not by value (--grey-600) or place (--header-blue).
  • Dark mode and themes remap the same tokens under a selector or prefers-color-scheme; never a second set of hardcoded colors in parallel rules.
  • Give var() a fallback only where the property can be absent on purpose, not to hide a typo in a name.

Specificity and the cascade

Summary: flat selectors, no !important, no id selectors, layers for ordering, one naming scheme

  • Keep selectors flat: a class, at most one more level (.card__title, .nav a). No #id selectors, no chains of three or more, no element-qualified classes (div.card).
  • No !important. If a rule does not win, lower the specificity of the competing rule or order the sources with @layer (supported in all current browsers since 2022); an exception for a utility that must win is documented at the declaration.
  • Pick one naming scheme (BEM or what the project already uses) and keep it; do not mix schemes in one file.
  • Style by class, never by DOM structure that a markup change would break (div > div:nth-child(3)).
  • Do not set outline: none without a visible :focus-visible replacement.

Layout and responsiveness

Summary: mobile-first min-width queries, flex/grid, relative units, logical properties

  • Write the base rules for the smallest screen and add @media (min-width: …) for larger ones; breakpoints come from tokens or one list, not from numbers invented per component.
  • Use flexbox and grid for layout, gap for spacing between items; no floats or fixed heights that clip text.
  • Size text and spacing in rem/em, not px, so user font settings still work; px is fine for borders and hairlines.
  • Prefer logical properties (margin-inline, padding-block) in new code when the project supports right-to-left text.
  • Check browser-support claims against the project’s browserslist or stated targets before using a new feature (container queries, :has(), nesting); do not assume the newest syntax is available.

Lint and format tooling

Summary: stylelint by default, formatter of the project, SCSS only if the project already uses it

  • stylelint with the project’s shared config is the template’s usual choice for linting, prettier for formatting — either way, run what the project actually has configured (see R-code-tools).
  • Do not introduce SCSS, PostCSS plugins or a CSS-in-JS library into a project that has none; with native nesting and custom properties most of the old reasons are gone.
  • In SCSS, keep nesting to three levels at most and use @use / @forward, not @import, which is deprecated since Dart Sass 1.80.

Coding rules — Docker

Source: .act/coding/docker.md

Summary: pinned base images, non-root and multi-stage builds, build context and secrets, Compose, hadolint

Rules for Dockerfiles and Compose files. Group IDs (CR-docker-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Pinned base image, small and multi-stage

Summary: tag plus digest, no latest, multi-stage build, one process per container, layer order and cleanup

  • Pin the base image by tag and digest (FROM python:3.12-slim@sha256:...); never latest or a bare major-version tag alone. Take the language version from the project files (R-code-version), not from habit, and update the digest on purpose, not by rebuilding.
  • Build in stages: compilers, dev dependencies and caches stay in a builder stage; the last stage copies only the result (COPY --from=builder) into a slim or distroless base.
  • Order layers by how rarely they change: copy the dependency manifest and install first, the source last, so a code change does not reinstall everything. Do the install and its cleanup in one RUN (apt-get update && apt-get install -y --no-install-recommends ... && rm -rf /var/lib/apt/lists/*), since a later rm does not shrink an earlier layer.
  • Prefer COPY to ADD; use the exec form for CMD and ENTRYPOINT (["python", "app.py"]) so signals reach the program; one main process per container.

Non-root user, no secrets in layers

Summary: USER set, .dockerignore, build secrets instead of ARG/ENV, no credentials in the image

  • Run as a non-root user: create it (RUN useradd --system --uid 10001 app) and set USER before CMD; copy files with --chown. Do not run a service as root “to make it work”.
  • Keep a .dockerignore next to the Dockerfile that excludes at least .git, .env*, dependency folders (node_modules, .venv), build output and local data, so none of it reaches the build context or a layer.
  • A secret never goes into ARG, ENV, COPY or a RUN argument: each stays readable in the image history (docker history). Use a BuildKit secret mount (RUN --mount=type=secret,id=name ..., passed with --secret) for build time and the runtime environment or a mounted file for run time (R-safe-no-secret-cli).
  • Do not bake configuration that differs per environment into the image; pass it in at run time.

Compose files

Summary: no version key, pinned images, named volumes, env file out of version control, healthy dependencies

  • Use the Compose Specification (Docker Compose v2, docker compose): leave out the obsolete top-level version: key. Check the installed version with docker compose version.
  • Pin every image: as above; no latest. Name volumes instead of anonymous ones, and do not bind-mount the Docker socket (/var/run/docker.sock) into a container.
  • Keep values and secrets in an .env file or secrets:, never in compose.yaml; commit only an .env.example. Publish only the ports that are needed, bound to 127.0.0.1 unless the service is meant to be reachable from outside. A host port clashes with the owner’s server — see R-safe-dev-server.
  • Make start order real: depends_on with condition: service_healthy and a healthcheck, not a sleep.

Lint and build checks

Summary: hadolint for Dockerfiles, docker compose config for Compose, or what the project has set up

  • hadolint is the template’s usual Dockerfile linter; validate Compose files with docker compose config --quiet. Run what the project has configured and install nothing unasked (R-code-tools).
  • Build with BuildKit (the default in current Docker) and verify the result by running the image once, not only by a green build.

Coding rules — Go

Source: .act/coding/go.md

Summary: strict error checking, static analysis tooling, package design

Rules for Go projects. Group IDs (CR-go-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Error handling, formatting, static analysis

Summary: check and wrap errors, format with gofmt, run vet/staticcheck, avoid panics and leaks

  • Format every file with gofmt/goimports before committing; no hand-tuned deviation from either.
  • Check an error immediately after the call that returned it (if err != nil) instead of collecting errors for later, and never discard a return value with _ when it comes with an unchecked error.
  • Wrap errors with %w (fmt.Errorf("...: %w", err)) so errors.Is/errors.As keep working further up the call chain; never lose or flatten the underlying error.
  • Run go vet and staticcheck in CI as the stack’s standard static analysis — set them up, but run only what is installed; if a tool is missing, say so once and install nothing unasked.
  • No panics in library code for expected failure cases; panic only for genuine programming errors.
  • context.Context is the first parameter of any function that must propagate cancellation, a deadline, or request-scoped values.
  • Every goroutine has a visible lifecycle end (WaitGroup or context cancellation) — a goroutine with no way to stop is a leak.
  • Synchronize state shared between goroutines through channels or explicit locks, never silently.

Small interfaces, no grab-bag packages

Summary: interfaces defined by the consumer, packages named and cut by domain

  • Define interfaces on the consumer side (small, often one or two methods), not upfront by the provider that implements them.
  • Give packages short, meaningful names cut by domain; no util/common grab-bag package without a real subject of its own.

Coding rules — Java

Source: .act/coding/java.md

Summary: nullability, error handling, structure, toolchain, tests

Rules for Java projects. Group IDs (CR-java-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Nullability, error handling, established pitfalls

Summary: explicit nullability, no raw types, correct exception handling, logging and SQL safety

  • Make nullability explicit on fields, parameters and return types (JSpecify @Nullable/@NonNull or the alternative the project has fixed on) instead of leaving it implicit.
  • No raw Object, no raw types on generics.
  • No empty catch blocks and no catch (Exception e) without a concrete reason; use unchecked exceptions for programming errors and checked exceptions for expected, recoverable failures — the message must name what failed and with what.
  • Manage resources exclusively through try-with-resources.
  • Use java.util.concurrent (executors, CompletableFuture, concurrent collections) instead of manual synchronized/wait/notify.
  • Log through SLF4J, parametrized (log.info("user {} failed", id), never string concatenation) — see R-safe-no-secret-log for what never goes into a log line at all.
  • Use var only where the type is obvious from the right-hand side, otherwise spell out the type.
  • Return Optional<T> only as a method’s return type for “possibly no result” — never as a field, a parameter, or inside a collection.
  • Pitfalls: override equals/hashCode only together; use java.time, never Date/Calendar; use BigDecimal for money, never float/double; state UTF_8 explicitly, never rely on the platform default; use only parametrized SQL, never string-concatenated queries; a plain loop may read better than forcing a Stream.
  • Static analysis is the stack’s standard — set it up, but run only what is installed; if a tool is missing, say so once and install nothing unasked.

Records, sealed types, text blocks, virtual threads

Summary: modern language features, requires Java 17 for most, Java 21 for pattern matching for switch and virtual threads

  • Use records for immutable data carriers (DTOs, value objects) instead of a manual class with getters, equals, hashCode and a constructor — requires Java 16 (records; preview in 14 and 15).
  • Use sealed interfaces/classes instead of open hierarchies — requires Java 17; with pattern matching for switch (switch on type) instead of instanceof chains — requires Java 21 (final there; only a preview in 17).
  • Use text blocks for multi-line strings (SQL, JSON templates) instead of concatenation — requires Java 17.
  • Use virtual threads only where the runtime and every library on the path support them — requires Java 21.

Package cut, immutability, constructor injection

Summary: packages by domain, immutability as the default, constructor injection

  • Cut packages by business domain, not by technical layer.
  • Keep visibility as narrow as possible, fields final, no setter without a reason — immutability is the default and the best guard against concurrency bugs.
  • Use constructor injection instead of field injection, even outside a DI container.

Build and static analysis tools

Summary: Maven or Gradle by default; static analysis whichever the project has set up

  • Build with Maven or Gradle — the project decides which.
  • Enforce formatting and static analysis in CI: Spotless or google-java-format for formatting, plus Checkstyle, SpotBugs, Error Prone or PMD — the template’s usual choice; run whatever the project actually has set up (see R-code-tools).

JUnit 5 with AssertJ by default

Summary: JUnit 5/AssertJ by default, behavior-describing names, no unseeded randomness, no Thread.sleep

  • Write tests with JUnit 5 and AssertJ — the template’s usual choice; use the test framework the project actually has set up instead (see R-code-tools).
  • Name tests after the expected behavior, not after the method under test.
  • Never use randomness without a fixed seed.
  • Never wait with Thread.sleep; wait on the actual condition instead.

Coding rules — JavaScript

Source: .act/coding/javascript.md

Summary: ESM, modern syntax, pinned Node version, ESLint flat config, Prettier, built-in or Vitest tests, handled promises

Rules for JavaScript on Node.js in projects without TypeScript; with TypeScript the typescript set applies. Group IDs (CR-javascript-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Modern language defaults

Summary: ESM, const/let, strict equality, async/await, explicit errors

  • Use ES modules: "type": "module" in package.json, import/export, the node: prefix for built-ins (import fs from "node:fs/promises"), and the file extension in relative imports. No new CommonJS (require, module.exports); __dirname becomes import.meta.dirname (Node 20.11+).
  • const by default, let where reassigned, never var.
  • Compare with ===/!==; == only for the deliberate x == null check, with a comment.
  • async/await over .then chains. forEach does not wait for an async callback — use for…of with await, or Promise.all over map when the calls are independent.
  • Throw Error objects (with cause when wrapping), never strings. Every error message states what failed and with what value.
  • Use the standard library and built-ins (fetch, structuredClone, node:test, util.parseArgs) before adding a package.
  • Describe the shape of structured data with a JSDoc @typedef, not as a loose object passed around.

No floating promises

Summary: every promise awaited, returned or caught; unhandled rejections end the process

  • Every promise is awaited, returned, or ends in .catch(...). A call to an async function as a bare statement hides its failure; on Node 15+ an unhandled rejection terminates the process.
  • No async function as an event handler or setInterval callback without its own try/catch.
  • No new Promise(async (resolve) => …); no await in a loop where the calls are independent.
  • ESLint core cannot find floating promises (@typescript-eslint/no-floating-promises needs types), so review for them, and set a top-level handler for unhandledRejection that logs and exits non-zero.

Node version, lint, format, tests

Summary: Node version pinned, ESLint 9+ flat config, Prettier, node:test or Vitest, lockfile

  • Pin the Node.js version: engines.node in package.json plus .nvmrc (or .node-version), and use the same version in CI. Use an active LTS line; check the installed version (R-code-version).
  • ESLint from v9 reads only the flat config eslint.config.js; .eslintrc* is legacy and not used unless the project still runs ESLint 8. Run what the project has configured (R-code-tools).
  • Prettier is the template’s usual formatter; ESLint covers correctness only, with eslint-config-prettier where both run — not a second style guide.
  • Tests: the built-in node:test runner (node --test) or Vitest, whichever the project has set up.
  • Commit the package manager’s lockfile and install in CI from it, frozen: npm ci, pnpm install --frozen-lockfile or yarn install --immutable, never a plain install. With pnpm, pnpm update and pnpm why <package> replace npm update / npm ls; script arguments go without -- (pnpm run test -t name).
  • A failing lint or test is fixed in the code, not silenced with eslint-disable (R-code-checks-intact).

Coding rules — Kotlin

Source: .act/coding/kotlin.md

Summary: null safety, structured concurrency, data modelling, toolchain, tests

Rules for Kotlin projects (JVM, Android or multiplatform). Group IDs (CR-kotlin-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header. A Kotlin project normally does not take the Java set; with mixed sources init ticks both, and where only the odd Java call occurs, the interop rule below suffices.

Null safety, immutability, error handling

Summary: no !!, val over var, specific exceptions, explicit API at boundaries, Java interop

  • Never use !!. Handle nullability with ?., ?:, let, an early return, or requireNotNull(x) { "message" } / checkNotNull where a missing value is a bug — the message names what was missing. lateinit only for framework-injected fields.
  • Prefer val over var, read-only collections (List, Map) over mutable ones in signatures, and expressions (when, if) over mutation.
  • Catch specific exception types; never swallow an exception or catch Throwable. Inside coroutines never catch CancellationException without rethrowing it. Use Result or a sealed type for expected failures instead of exceptions as control flow.
  • Declare the type of public functions and properties explicitly, instead of relying on inference across a module boundary.
  • Platform types from Java (String!) are not trusted: give them a nullable or non-null type at the point of entry, and annotate Kotlin APIs meant for Java callers (@JvmStatic, @JvmOverloads, @Throws) only where the Java side needs them.
  • Use string templates, not concatenation, and java.time types (not Date/Calendar) on the JVM.
  • Log through SLF4J or the project’s logging facade with parametrized messages — see R-safe-no-secret-log for what never goes into a log line.

Structured concurrency

Summary: no GlobalScope, scopes with a lifecycle, injected dispatchers, no runBlocking in production code

  • Never launch work in GlobalScope. Start coroutines in a scope that owns their lifecycle (coroutineScope, supervisorScope, viewModelScope, a service’s own CoroutineScope) so that failure and cancellation propagate.
  • Do not call runBlocking in production code outside main and test bridges, and do not block a coroutine thread with Thread.sleep or blocking I/O: use delay and withContext(Dispatchers.IO).
  • Inject dispatchers as parameters instead of hard-coding Dispatchers.IO/Default, so tests can replace them. Expose suspend functions or Flow from APIs, not Deferred or callbacks.
  • Use kotlinx-coroutines-test (runTest) for coroutine tests; never wait with Thread.sleep.

data class, sealed types, value classes

Summary: data class for values, sealed types for closed sets, copy over mutation

  • Model plain values as data class with val properties and change them with copy(); do not put logic with side effects into a data class.
  • Model closed sets of cases as sealed interface/sealed class and match them with an exhaustive when without an else branch, so adding a case breaks the build.
  • Use @JvmInline value class for typed identifiers (ids, units) instead of bare String/Long; use enum class only for a fixed set without per-case data.

Build, formatting, static analysis, tests

Summary: Gradle Kotlin DSL by default, ktlint and detekt, JUnit 5 or Kotest

  • Read the Kotlin version from the build file or version catalog (libs.versions.toml) and use only language features that version supports (R-code-version): for example context parameters and guard conditions in when are newer than Kotlin 2.0.
  • Build with Gradle and the Kotlin DSL (build.gradle.kts) — the template’s usual choice; keep dependency versions in one place and use the Gradle wrapper the project ships.
  • Format with ktlint (or ktfmt/Spotless) and analyze with detekt — the template’s usual choice; run whatever the project actually has set up (see R-code-tools), and install nothing unasked.
  • Write tests with JUnit 5 — the template’s usual choice — optionally with Kotest assertions or MockK; use the framework the project has set up. Name tests after the expected behavior; never use randomness without a fixed seed.

Coding rules — Nuxt

Source: .act/coding/nuxt.md

Summary: directory conventions, data fetching, runtime config, SSR mode, tooling

requires: vue, typescript

Rules for Nuxt projects. Group IDs (CR-nuxt-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

On Nuxt 5 the set nuxt5 (.act/coding/nuxt5.md) adds to this one. init checks it when package.json names nuxt at major 5. If the set’s line is missing from docs/project/coding_rules.md on a Nuxt 5 project (one set up before the set existed), read .act/coding/nuxt5.md before touching Nuxt code and suggest adding - [x] use: .act/coding/nuxt5.md with its groups; an unchecked line is the owner’s choice.

Established Nuxt defaults

Summary: directory layout, data fetching, typed handlers, runtime config, pitfalls

  • Follow the directory convention (pages/, components/, composables/, server/) instead of inventing a structure; use auto-imports, no manual re-exports for files in those directories.

  • Read data with useFetch/useAsyncData while rendering, use $fetch for one-off writes and actions.

  • Never copy the return value of useFetch/useAsyncData into your own ref — pass the returned object through and await it where data/status/error reach the template. Copying loses awaitability: the call resolves later, the server renders without data, the client fills it in, and the result is a hydration mismatch.

    ```ts
    // Wrong — awaitability is lost
    function useThing() {
    const result = ref()
    useFetch('/api/thing').then(r => (result.value = r.data.value))
    return result
    }
    // Right — pass the returned object through unchanged
    async function useThing() {
    return await useFetch('/api/thing')
    }
    ```
  • Path aliases, by installed Nuxt major (R-code-version). Since Nuxt 4, ~ points at app/, so without its own entry ~/types resolves somewhere other than ~types.

    • Nuxt 4 and later: declare aliases only in nuxt.config.ts (alias); Nuxt copies each into the generated .nuxt/tsconfig*.json. The root tsconfig.json holds nothing but references to those generated configs and never its own paths: with files: [] plus references a paths there replaces nothing, it simply does not reach the referenced projects, so the alias works nowhere. Only a root that extends a generated config replaces the whole generated mapping with its paths, and the framework aliases disappear.
    • Nuxt 3: declare aliases in nuxt.config.ts as well; a root tsconfig.json that extends ./.nuxt/tsconfig.json may add paths only if it repeats every generated entry. Nuxt 3 also writes each alias into the generated paths, so the nuxt.config.ts entry alone is enough; the generated .nuxt/tsconfig.json shows it.
  • Files the generated contexts leave out (unit and e2e tests, test-runner configs) are skipped by nuxt typecheck without a message. Add them through Nuxt’s TypeScript options in nuxt.config.ts (typescript.tsConfig.include, or the per-context typescript.sharedTsConfig / typescript.nodeTsConfig / typescript.tsConfig objects on Nuxt 4; the server context via nitro.typescript.tsConfig), then prove each context once: put a deliberate type error in one file of it, see nuxt typecheck fail, remove it. Check the option names in the docs of the installed Nuxt version before using them.

  • pnpm projects: see the package-manager notes in the JavaScript rules.

  • Use runtimeConfig for configuration values instead of reading process.env in components; secrets live in the private part of runtimeConfig, never under public.

  • Write out types for props, emits, store actions, composables and defineEventHandler, including return types.

  • Name server routes under server/api/ with a verb suffix (login.post.ts, users.get.ts) and return failures with createError and a matching HTTP status — never swallow an error or answer 200.

  • Lint and typecheck are the stack’s standard and belong in the project; nuxt typecheck needs vue-tsc as a dependency, without it there is no typecheck. Run what is installed, install nothing unasked.

  • Keep the npm scripts named the same everywhere: lint (eslint .), typecheck (nuxt typecheck), plus test (vitest run) and test:e2e (playwright test) where tests exist.

  • Pitfalls:

    • SSR code must not touch browser globals (window, document) without a guard.
    • Use <ClientOnly> only where a component genuinely cannot render on the server, not as a default fix.
    • Security: never keep per-request state in a module-level ref/reactive. On the server such a value outlives the request and is shared between users — the next request sees the previous one’s data. Use useState for state that must survive the request.
    • Forms with @submit.prevent also need method="post" (see CR-vue-basics).
    • Export names in auto-imported folders (composables/, utils/, server/utils/, shared/utils/) are unique across all their files. When two files export the same name, one of them wins without an error, only a warning about duplicated imports appears, and lint and typecheck can stay green. Give each area a prefix, and treat that warning in dev, build or typecheck output as a finding.
    • A page component has exactly one root element; an HTML comment counts as one. With more, Nuxt only warns in dev (on the Nuxt 5 nightly: NUXT_E4004) and the page breaks on a client-side route change, while opening it directly and tests of the single page stay green. After adding or rebuilding a page, check the browser console and the dev output for that warning; it is a finding.
    • Windows: an aborted dev server can keep its port bound; the next start moves to the next free port and HMR/WebSocket errors follow. If it is a server the assistant started itself, end exactly that process instead of configuring a custom HMR port. Find the listening PID with (Get-NetTCPConnection -LocalPort <port> | Where-Object RemotePort -eq 0).OwningProcess. Do not rely on -State Listen (on some Windows builds it returns client connections or nothing) nor on netstat | findstr LISTENING (the word is localized, ABHÖREN on German Windows). The filter can still list Bound or Closed entries and several or stale PIDs: before Stop-Process -Id <pid>, check the process’s command line ((Get-CimInstance Win32_Process -Filter "ProcessId=<pid>").CommandLine) is the test server you started (R-safe-dev-server). From Git Bash wrap the commands in powershell -NoProfile -Command "…", or use taskkill //PID <pid> //F (a single /PID is rewritten to a path there and ends nothing). Afterwards request http://localhost:<port>/ (a server may listen on ::1 only): it must be refused. Elsewhere use lsof -iTCP:<port> -sTCP:LISTEN and kill <pid>. A server on the owner’s port is theirs: ask first.
    • Security: set workspaceDir in nuxt.config.ts to the project folder itself and check the resolved value without starting the server, by loading the config. Reason: with the dev server reachable from the network, a stray lock or workspace file in a parent folder can make that parent folder readable through it (advisory GHSA-mjrq-cffv-q4qc, Nuxt 3 and 4 through @nuxt/schema 3.5.0 up to below 4.6.4, fixed in 4.6.4).

Fixed root folders with their own aliases

Summary: /types, /constants, /server and shared/utils/ at the repo root, each the only place of its kind

  • Keep four folders at the repository root, each with its own alias and each the only place of its kind: /types (~types, shared types and interfaces), /constants (~constants, constants, enumerations, fixed keys), /server (~server, the Nitro backend), shared/utils/ (Nuxt’s #shared, code that the app and the server both run, such as formatting, validation or calculations).
  • Import types and constants from there instead of duplicating them in components. A second type folder under app/types/ or shared/types/ is a mistake, not an addition: types stay in /types.
  • Code in shared/ imports no Vue and no Nitro code (Nuxt’s own limit). Code only the app runs stays in app/utils/, code only the server runs in server/utils/.
  • shared/ needs Nuxt 3.14 or later (R-code-version). Nuxt 4 auto-imports shared/utils/ in app and server; Nuxt 3 does so only with future.compatibilityVersion: 4, otherwise import from #shared/utils/….

Choose the SSR mode on purpose

Summary: ask before assuming SSR, know the hydration cost, check for mismatches after SSR work, bundle icons without SSR

  • ssr: false or a plain SPA is often the simpler choice for a purely local UI with no SEO or first-paint requirement (e.g. an admin tool). Ask the user once, when scaffolding or restructuring the app, instead of defaulting to SSR without asking.
  • Know what SSR costs: every page render runs twice, once on the server and once on the client. Anything that only exists in the browser or differs between the two runs — timestamps, random values, window, localStorage, locale or timezone detection — produces a hydration mismatch.
  • After working on a component that renders server-side, check for hydration errors on purpose: load the page in the browser and read the console warning “Hydration … mismatch” — it names the component and the node. Treat that warning as a finding, not a footnote.
  • Known causes and their fix, in short: gate browser-only values behind onMounted/ import.meta.client; share request-scoped state through useState, never a module-level ref; fix invalid HTML nesting (e.g. a block element inside a <p>); reach for <ClientOnly> only as the last resort.
  • An HTML comment between the branches of a v-if / v-else-if / v-else chain breaks hydration in dev, and neither lint nor the type check notices; move the comment in front of the whole chain or into one branch.
  • Copying a useFetch/useAsyncData result into your own ref is a common hydration-mismatch cause too — see CR-nuxt-basics for why and the fix, not repeated here.
  • With ssr: false, @nuxt/icon (also through @nuxt/ui) fetches icons at runtime from the public Iconify API unless they are bundled: install the icon sets as @iconify-json/<set>, provider none, clientBundle.scan, fallbackToApi: false; an unknown icon then shows as missing with a console warning.

Lint and format tooling

Summary: ESLint with @nuxt/eslint plus Prettier, whichever the project has set up

  • ESLint with @nuxt/eslint, configured in eslint.config.mjs, and Prettier for formatting are the template’s usual choice; what the project actually has installed and configured governs (see R-code-tools).

Unit and end-to-end tests

Summary: vitest/Playwright by default, but whichever suite the project runs must pass; anchored locators, isolated parallel test servers

  • vitest (vitest.config.ts) for unit and component tests, @playwright/test (playwright.config.ts) for end-to-end tests — the template’s usual choice; if the project has a different test runner installed and configured (e.g. Selenium, Nightwatch, Cypress), use that one instead (see R-code-tools).
  • Whichever test suites the project actually has exist and run; a change that breaks them is not done.
  • Anchor a role-and-name locator fully: a required field may carry * in its accessible name, so /^Name/ matches several fields and Playwright’s strict mode fails; use /^Name\*?$/.
  • Take a UI library’s built-in labels (pagination, close buttons) from its locale files instead of writing the text into the test: a library may start following the app’s i18n language on update (reported for @nuxt/ui 4.12 with @nuxtjs/i18n).
  • Parallel test builds or test servers run under the throwaway folder (R-work-throwaway); lint, the formatter and file watchers must exclude it as a whole: add .act-local/ to their ignores (ignores in eslint.config, .prettierignore, ignore in nuxt.config) where they do not skip it already. Each test server gets its own buildDir, Nitro output dir and Vite cacheDir (absolute: Vite resolves a relative one against app/), all three from an environment variable that nuxt.config reads, plus its own port. Reported for the Nuxt 5 CLI: nuxt dev locks its buildDir and refuses a second dev server on it, and on the same port a non-interactive nuxt dev ends a non-interactive holder, so a test runner on the owner’s port can stop the owner’s server (R-safe-dev-server). A stale lock file in a test server’s own buildDir may be removed before start only when its process is gone or its PID now belongs to another process, never by its age.

Coding rules — Nuxt 5

Source: .act/coding/nuxt5.md

Summary: nightly channel, modules, Nitro 3/h3 v2, typed routing and $fetch, Unhead 3, checks after every update

requires: nuxt

Rules for projects on Nuxt 5, written against its nightly channel before the stable release. They add to CR-nuxt-* and replace none of it. init checks this set when package.json names nuxt at major 5 (^5.0.0, npm:nuxt-nightly@5x). Group IDs (CR-nuxt5-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Nightly channel and versions

Summary: nuxt-nightly@5x as a tag, the lockfile as the only pin, pnpm re-resolving the tag, the nightly’s vue range, majors in step with Nuxt, DevTools explicit, one package moved without Nuxt

  • Until the stable release, list nuxt as "npm:nuxt-nightly@5x" — a tag, never a build number. If npm install (pnpm install) writes a fixed version, set it back to @5x by hand and install again (with pnpm that install is itself a Nuxt update, see below); only the lockfile pins the state. Drops once nuxt/nuxt tags v5.0.0 (github.com/nuxt/nuxt/releases); then ^5.0.0.
  • Move forward with npm update nuxt (pnpm update nuxt), as a commit of its own, followed by the full check from CR-nuxt5-checks.
  • Direct dependencies that Nuxt brings along stay on the same major as Nuxt does (e.g. vue-router 5, @unhead/vue 3); after every update, npm ls <package> (pnpm why <package>) shows one copy of each.
  • Node 22.21 or 24.11 at least.
  • Install @nuxt/devtools explicitly as a devDependency; run it only in the dev server and only with NUXT_DEVTOOLS=1, and confirm each browser once with the code from the dev terminal. Never set devtools.disableAuthorization.
  • With pnpm and nuxt as an alias on the channel tag, every write of the lockfile can re-resolve the tag and move Nuxt to a newer nightly: pnpm add, pnpm install after a hand edit, pnpm update <package> --depth Infinity for a transitive fix; even with Nuxt pinned exactly in package.json its subtree was re-resolved. So with pnpm, add, remove or update packages only right after a deliberate Nuxt update (own commit, full check chain), then confirm with pnpm why nuxt that the resolved Nuxt is unchanged. Drops once Nuxt 5 ships a stable release and the project leaves the channel tag.
  • To move a single package (a security fix) without moving Nuxt, with pnpm: set nuxt in package.json for the run to the exact version the lockfile holds, update the package, restore package.json, then set the lockfile’s specifier for nuxt back to the channel tag. Afterwards pnpm install --frozen-lockfile must pass and the lockfile diff shows new entries only, none changed or removed; otherwise start over as a deliberate Nuxt update. A nightly CLI that moved along is taken back in the lockfile. The same steps lift the module copies named in CR-nuxt5-checks to the fixed version without moving the nightly. Drops with the pnpm line above.
  • A nightly can raise its own vue range; a project vue entry left on the old minimum keeps a second Vue copy. After every move, read the nightly’s range (npm view <nightly>@<version> dependencies.vue, pnpm view alike), raise your entry to it, then npm ls vue / pnpm why vue shows one version. Run nuxt prepare too: the generated ESLint config can point at the old store path until it runs (postinstall usually does it).
  • pnpm 11’s minimumReleaseAge makes pnpm update nuxt take the newest nightly older than that age: do not work around it; name the version actually installed in the commit and the upgrade log.
  • After dev or build, read the diff of package.json: every entry the tooling added on its own is one you can explain.

Modules under Nuxt 5

Summary: NUXT_B8013 means switched off, Pinia 4 with its peer, the i18n way back, bundled icons, the Nitro v2 bridge only in modules

  • NUXT_B8013 switches off a module whose compatibility field does not match, with nothing but a warning: check the field before the update, read the warnings after it.
  • Pinia 4: @pinia/nuxt 1 or later, @vue/devtools-api ^8 as a direct dependency.
  • @nuxtjs/i18n 10.6, before it supports Nuxt 5: i18n.experimental.nitroContextDetection: false. Without it a path without locale prefix gets no server redirect (checked with strategy prefix on nightly 5.0.0-2611122105); as reported, the default waits for the Nitro hook render:before, which Nitro 3 never calls, and the client redirect ends in a hydration mismatch. Drop it once a release closes nuxt-modules/i18n#4066 (Nuxt 5 and Nitro 3 support). experimental.nitroViteEnvironment: false is no longer needed from nightly 5.0.0-2611031025 on; remove it once build and the E2E tests pass without it.
  • Under Nuxt 5 the server provider of @nuxt/icon does not serve the icons: it answers with an empty body (2.5.1), or the browser asks the public Iconify API directly (2.6.2 with @iconify/vue 5) (reported, upstream nuxt/icon issue 571). Use the bundled setup from CR-nuxt-ssr and an E2E check that icons render and no request goes to the Iconify API; drop when that issue is fixed in a release.
  • Never rebuild the Nitro v2 bridge (NUXT_B9003) in your own code.

Nitro 3 and h3 v2

Summary: explicit imports from nuxt/server, event.req as a web request, typed bodies, status/statusText, no comma in export-line comments, headers and CSP, no file deleted under the owner’s dev server

  • In server/, import defineEventHandler, readBody, getQuery, createError … from nuxt/server, and define plugins with definePlugin from nitro; server/utils/ stays auto-imported.
  • event.req is the web Request (there is no event.node); read a multipart body with event.req.formData().
  • readBody<T>() with an interface of its own, fallback .catch((): Body => ({})). The type is no validation — validate the body as before (e.g. with a schema library).
  • Type a response at the return value (const response: ApiThing = …; return response), the type in /types (CR-nuxt-root-folders).
  • Errors with createError({ status, statusText }); statusText in ASCII only (e.g. 'Unprocessable Entity'), localized text goes into data.
  • On the client, createError({ data }) arrives under response._data.data; the field errors of a 422 sit under …data.errors (e.g. for Nuxt UI’s UForm.setErrors).
  • useRuntimeConfig() without event.
  • In a folder auto-imported into the server (server/utils/, shared/utils/ …) no comma in a line comment after an exported declaration: the export scan (mlly) reads the word after the comma as one more export and writes it into .nuxt/types/server-imports.mjs, and the server build fails with MISSING_EXPORT once a module keeps that file from being tree-shaken (seen with mlly 1.8.2, @nuxtjs/i18n 10.6.0, nightly 5.0.0-2611122105). Put the comment above the line. Drops once the generated file lists only real exports (no upstream report known).
  • Fixed security headers (not the CSP) go into a route rule /** in nuxt.config: Nitro 3 serves files from public/ and /_nuxt/ before the app’s middlewares, so a header a middleware sets never reaches them. Check the headers against the production build.
  • Reported by a project, not reproduced: Nuxt 5 sets no CSP itself and no CSP module supports it yet. Set the CSP header in a server plugin on render:html (useServerHooks from nuxt/server), with hashes for the fixed inline scripts and a nonce per request on the payload script; Nuxt puts a nonce on its own streaming scripts only if a head script already carries one. A CSP an early middleware sets overrides the renderer’s, so set one there only for API routes. Drops once a CSP module (e.g. nuxt-security) declares Nuxt 5 support.
  • After renaming or removing an export in server/utils/, restart your own test server (its port as R-safe-dev-server says) before tests against it count; the owner’s server only after asking. No transitional alias for the old name. Never set NUXT_IGNORE_LOCK or NUXT_LOCK=0.
  • Deleting a file from an auto-imported folder while the owner’s dev server runs makes every page answer 500 until a restart: the running module graph keeps the old import. As the assistant never restarts that server, empty the file and leave it, delete it after the owner’s next restart, or ask first. A test server started fresh per run is not affected.
  • Every runtime dependency goes into package.json, even one that is already there transitively.

Pages, routing, data fetching, head

Summary: import.meta.*, query instead of params, typed $fetch and route targets, Unhead 3 and its og hint, no baseUrl

  • import.meta.* instead of process.* (import.meta.client, import.meta.dev …).
  • query instead of params in the options of $fetch/useFetch.
  • $fetch is typed from the generated server routes: a wrapper that takes free paths gets a narrow signature of its own (type FreeFetch = <R>(request: string, options: FetchOptions) => Promise<R>) and converts $fetch with as unknown as FreeFetch, with a comment saying why.
  • With typed pages and @nuxtjs/i18n, a page target is a route name without the locale suffix: localePath({ name, params, query }) or <NuxtLinkLocale :to="{ name: … }"> — for navigateTo, router.push, NuxtLink and a Nuxt UI to as well; a plain path gets no locale prefix and ends in a 404. For the same reason, build definePageMeta({ redirect }) relative to the current path.
  • Unhead 3: no hid/vmid, deduplicate with key; a dev hint about og:* or the description is a finding, except the known case below.
  • Unhead 3 reports og-missing-title on a page that carries other og: meta tags (often set app-wide) but no og:title (checked in Unhead 3.4.3, the validate plugin in dist/plugins.mjs). On a page that deliberately has no og:title (private page, error page), leave out the other og: tags there too; where that is not possible, treat the hint as a known false positive and re-check it after each Unhead update. Setting rules: { 'og-missing-title': 'off' } on the validate plugin silences it for every page, so it hides real cases.
  • Every page sets its title, a public page its description too; the fallbacks (title template, og:site_name, default description) go into app.vue and error.vue, since Nuxt renders error.vue in place of app.vue. A head value that is missing is left out, never passed as undefined — useSeoMeta({ description: undefined }) removes the fallback (so the og:title case above is solved by leaving tags out, not by undefined).
  • Pin workspaceDir as the security line in CR-nuxt-basics says; it holds for Nuxt 5 as well.
  • No compilerOptions.baseUrl in tsconfig.json — Nuxt ignores it; aliases go into nuxt.config.ts only (CR-nuxt-basics).

Checks after every Nuxt update

Summary: the full check chain, the type error list compared rather than counted, warnings (a known listener warning), copies (how to count, the expected @nuxt/schema hit) and invalid in the tree, workarounds against upstream, a build before commits to auto-imported folders or nuxt.config, a record

  • Save the typecheck output before the update and compare the errors afterwards — the list, not the count.
  • Then npm run lint, typecheck, test, build, dev (main pages answer 200, no hydration warning), the main pages once more against the built server with the browser console read (a module can break there only), and test:e2e; dev and the built server as your own test servers (port as R-safe-dev-server says), stopped afterwards.
  • Also between updates, a commit that changes an auto-imported folder (server/, shared/, app/composables/, app/utils/) or nuxt.config runs build besides lint, typecheck and tests: they stay green on a broken export scan (CR-nuxt5-server), only the build fails. Build with its own buildDir and Nitro output dir as CR-nuxt-tests says, never into the owner’s .nuxt/ while their dev server runs (R-safe-dev-server).
  • Read the warnings (NUXT_B8013, NUXT_B9003, [unhead]), check for duplicate copies, run python .act/scripts/security_scan.py --deps.
  • Count copies of a package with npm ls <package> / pnpm why <package>; folders under node_modules/.pnpm left from earlier installs stay until pnpm prunes them (modulesCacheMaxAge) and are not copies.
  • Under the nightly, common modules still pull @nuxt/kit 4.x and with it an @nuxt/schema 4.x: the dependency scan reports the workspaceDir advisory (CR-nuxt-basics) on that copy, not on the nightly, so the hit is expected. Lift the copy as CR-nuxt5-channel describes for a single package. Drops once the common modules depend on a Nuxt 5 kit.
  • A MaxListenersExceededWarning about close listeners on the server response in the nightly’s nuxt dev is toolchain noise: the listeners come from the CLI, Vite, the server layer and stream helpers (with a TTY also the CLI’s interface), their number depends on the kind of request, not on uptime, and falls back to none once the response closes; application code does not reach the response. Plain CLI output without the interface avoids it. Investigate only if it also shows in the production build or grows with a stream’s lifetime. Drops once the warning no longer appears in nuxt dev on a current nightly.
  • npm ls --all 2>&1 | grep invalid: fix a stale resolution with npm update <package> (with pnpm: pnpm why <package>, pnpm update <package>, under the pnpm line of CR-nuxt5-channel); entries already known stand in the upgrade log, report only new ones.
  • Check every workaround in this set against the upstream issue or release it names; drop the one whose condition is met, and note it in the upgrade log.
  • Record every break in an upgrade log of the project (e.g. docs/project/nuxt-5-upgrade.md): the symptom quoted in short, the cause checked or marked assumption, the fix, the location. A general lesson becomes an own rule in docs/project/coding_rules.md and goes to the template through act-feedback.

Coding rules — PHP

Source: .act/coding/php.md

Summary: strict types, PSR-12/PSR-4, exceptions, prepared statements, toolchain

Rules for PHP projects (8.x and later). Group IDs (CR-php-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Strict types, safe errors, safe queries

Summary: strict_types, PSR-12/PSR-4, typed methods, exceptions, PDO, production errors, static analysis

  • Put declare(strict_types=1); as the first statement in every PHP file.
  • Follow PSR-12 for formatting (4-space indentation) and PSR-4 for namespaces, one namespace per Composer autoload root.
  • Keep one class per file, with the filename matching the class name.
  • Manage dependencies through Composer only; never include a library by hand.
  • Declare parameter and return types on every public method. Use mixed only with a comment justifying it, and mark nullable types (?Type) explicitly instead of falling back to an implicit null.
  • Throw exceptions instead of returning false or an error code. Define one exception class per error domain rather than throwing a blanket \Exception, and let the message name what failed and with what — a database exception names the query or table, a validation exception names the field and the value it rejected.
  • Keep business logic out of templates (Blade, Twig, plain PHP templates); templates render, they don’t decide.
  • Access the database only through PDO with prepared statements; never build SQL by concatenating values into the query string.
  • Use ===/!== wherever type equality is meant, not the loose operators.
  • Turn display_errors off in production; errors go to the log, not into the response.
  • Static analysis is the stack’s standard and belongs in the project. Run what is installed, install nothing unasked.

Closures over global callbacks

Summary: arrow functions and closures instead of global callback functions

  • Use arrow functions/closures instead of global callback functions.

Formatter and static analysis tooling

Summary: PHP-CS-Fixer/PHP_CodeSniffer plus PHPStan/Psalm by default, or what the project has set up

  • PHP-CS-Fixer or PHP_CodeSniffer, configured for PSR-12, and PHPStan or Psalm for static analysis — the template’s usual choice; run whatever the project actually has set up (see R-code-tools).

Coding rules — PowerShell

Source: .act/coding/powershell.md

Summary: pinned PowerShell edition, encoding, strict mode and errors, native exit codes, script style, PSScriptAnalyzer and Pester

Rules for PowerShell scripts and modules. Group IDs (CR-powershell-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Pin the edition, keep encoding explicit

Summary: Windows PowerShell 5.1 versus PowerShell 7, one target per script, explicit encoding, no Bash syntax

  • Name the target in the project: Windows PowerShell 5.1 (powershell.exe) or PowerShell 7+ (pwsh). Check $PSVersionTable.PSVersion and the project files before applying anything below (R-code-version); declare it in the script with #Requires -Version 5.1 or #Requires -Version 7.0.
  • The two editions differ in defaults: 5.1 writes UTF-16 LE with >, >> and Out-File, and Set-Content uses the ANSI code page; 7 writes UTF-8 without BOM everywhere. Never rely on the default — pass -Encoding utf8 (5.1 adds a BOM; utf8NoBOM exists only in 7) to every Out-File, Set-Content, Add-Content and Export-Csv, and keep an existing file’s encoding (R-code-encoding).
  • Do not mix in Bash syntax: no &&/|| between commands (only PowerShell 7 has them), no export VAR=... (use $env:VAR = ...), no rm -rf (use Remove-Item -Recurse on a path you checked).
  • Windows pitfalls (the PowerShell items checked in 5.1 and 7.6, the CRLF-shebang failure in bash under WSL):
    • sc is the alias of Set-Content in 5.1 (in 7 it resolves to the program); call the service tool as sc.exe.
    • Set-Content/Add-Content end the text with CRLF even if it holds LF. A shell script needs -NoNewline and LF throughout (or [IO.File]::WriteAllText with UTF8Encoding $false); a CRLF shebang fails on Linux with “required file not found” or bad interpreter.
    • A UTF-8 file without BOM read by 5.1 Get-Content is taken as the ANSI code page and turns ─ into ─: pass -Encoding UTF8 when reading.
    • CSV for Excel in a decimal-comma locale: -UseCulture or -Delimiter ';'; 5.1 Export-Csv writes ASCII by default (non-ASCII becomes ?), -Encoding UTF8 there writes a BOM, which Excel needs; in 7 use -Encoding utf8BOM.
    • A captured or redirected pwsh 7 error stream carries ANSI escape sequences; set $PSStyle.OutputRendering = 'PlainText' in that process to drop them (5.1 has none).
  • Paths: build them with Join-Path and $PSScriptRoot, never by concatenating \; quote paths that may contain spaces; use -LiteralPath when a name may contain [ or ].

Strict mode and errors that stop

Summary: Set-StrictMode, ErrorActionPreference Stop, native exit codes, try/catch with the failing value

  • Start a script with Set-StrictMode -Version Latest and $ErrorActionPreference = 'Stop'; a non-terminating error otherwise lets the script carry on with bad data.
  • A native program (git, docker, npm) does not raise an error on failure, and $ErrorActionPreference does not catch it: check $LASTEXITCODE right after the call and throw or exit with a message naming the command and the code. PowerShell 7.4+ can do this with $PSNativeCommandUseErrorActionPreference = $true; 5.1 cannot.
  • Catch specific failures in try/catch, and name what failed and with what value ("Cannot read '$Path': $($_.Exception.Message)"); never an empty catch {}. Use -ErrorAction SilentlyContinue only on a single call whose failure is expected and tested afterwards.
  • Set exit codes deliberately (exit 0/exit 1) at the end of a script that CI or another program calls; write errors with Write-Error or throw, not Write-Host.

Names, parameters, no aliases

Summary: approved verbs, advanced functions, param blocks with types, full cmdlet names, output as objects

  • Name functions Verb-Noun with an approved verb (Get-Verb lists them: Get-, Set-, New-, Remove-, Test-, Invoke- …); a singular noun, no Do-, Run- or Check-.
  • Write a function as an advanced function: [CmdletBinding()], a param() block with a type on every parameter, [Parameter(Mandatory)] and [ValidateSet()]/[ValidateNotNullOrEmpty()] where they fit. Mark functions that change state with SupportsShouldProcess and honour -WhatIf.
  • No aliases in a script (ls, gci, %, ?, foreach for ForEach-Object, curl, wget) and no positional parameters for anything beyond the first; write the full cmdlet and parameter name. curl and wget are aliases of Invoke-WebRequest in 5.1, not the programs.
  • Return objects, not formatted text: no Format-Table or Write-Host in a function whose output is used further; use Write-Verbose for progress and Write-Output or an implicit return for the result.

Lint and tests

Summary: PSScriptAnalyzer for lint, Pester 5 for tests, or what the project has set up

  • PSScriptAnalyzer (Invoke-ScriptAnalyzer -Path . -Recurse) is the template’s usual linter; keep its settings in a PSScriptAnalyzerSettings.psd1 in the project and do not exclude rules wholesale.
  • Pester is the usual test runner; check the installed major version first (Get-Module Pester -ListAvailable) — Pester 5 needs BeforeAll for setup and discovery-time code differs from run-time code, so Pester 3/4 tests do not run unchanged. Run it with Invoke-Pester -CI.
  • Either way, run what the project has configured and install nothing unasked (R-code-tools).

Coding rules — Python

Source: .act/coding/python.md

Summary: strict annotations, stdlib-first, data models, module layout, toolchain, tests

Rules for Python 3 with type annotations, a stdlib-first preference and automated linting. Group IDs (CR-python-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Established Python defaults

Summary: annotations, f-strings, context managers, exception handling, venv, lint

  • Annotate every function signature (parameters and return value), including internal/private functions.
  • Use f-strings, not % formatting or .format().
  • Use with for anything that must be opened and closed (files, locks, connections).
  • Never use a mutable default argument (def f(x: list = [])) — default to None and initialize inside the function body.
  • Catch specific exception types; never a bare except Exception without re-raising or logging it. Every raised or logged error states what failed and with what value — a caller or log reader must find the cause without opening the source. Never a credential or personal data as that value: an identifier or masked value instead (R-safe-no-secret-log).
  • Use is/is not only for identity comparisons (None, singletons), never for values.
  • One virtual environment (venv) per project, dependencies pinned in a lockfile (requirements.txt, poetry.lock); never a global install of project dependencies.
  • Lint is the stack’s standard and belongs in the project; run what is installed, install nothing unasked.

Standard library before a new dependency

Summary: reach for the stdlib before adding a package

  • Prefer the standard library over adding an external dependency; add one only where the stdlib genuinely falls short.

Typed data instead of loose dicts

Summary: dataclasses, TypedDict or pydantic for structured data

  • Model structured data with dataclasses, TypedDict or pydantic, not a loose dict.

One module per responsibility

Summary: module boundaries, no circular imports

  • One module per functional responsibility, no catch-all module without a clear boundary.
  • Resolve circular imports by fixing the module boundaries, not by working around them with deferred or local imports.

Lint and format tooling

Summary: ruff by default for lint and formatting, or what the project has set up

  • ruff for both linting and formatting is the template’s usual choice; black remains a common alternative for formatting in existing projects — either way, run what the project actually has configured (see R-code-tools).

Unit tests

Summary: pytest by default, or the test runner the project has set up

  • pytest is the template’s usual choice, with fixtures instead of repeating setup code in every test module; use the test runner the project actually has configured (see R-code-tools).

Coding rules — React

Source: .act/coding/react.md

Summary: rules of hooks, keys, effects for synchronization only, React 19 changes, server components, Testing Library

Rules for React. They apply together with javascript or typescript — tick one of the two as well; the template cannot express “one of both” as a requirement. Version-dependent items name the version they need; check the installed React version first (R-code-version). Group IDs (CR-react-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Components, hooks and keys

Summary: rules of hooks, pure render, stable keys, no state copied from props

  • Call hooks only at the top level of a component or custom hook, never in a condition, loop or nested function; the eslint-plugin-react-hooks rules stay on and are not silenced.
  • Keep render pure: no mutation of props or state, no fetch, timer or Date.now() in the render body.
  • key is a stable id from the data, never the array index for a list that can reorder, insert or delete, and never Math.random().
  • Do not copy a prop into state to “initialize” it; use the prop, or lift the state.
  • Define components at module level, never inside another component: a nested definition remounts its subtree on every render.
  • Memoize (useMemo, useCallback, memo) for a measured problem only; with the React Compiler enabled in the project, leave existing hand-written memoization alone (the compiler’s docs advise this) and add none; remove it only after careful testing.

Effects only to synchronize with the outside

Summary: no derived state in effects, complete dependencies, cleanup, data loading by the project’s choice

  • An effect synchronizes with something outside React (network, subscription, DOM API, timer). Anything computable from props and state is computed during render; an event’s consequence belongs in the handler.
  • A useEffect that only calls setState from other state is a bug in the making: derive the value, or reset by changing the component’s key.
  • Declare every reactive value the effect reads as a dependency; fix a wrong list by restructuring, never by removing the dependency or disabling the lint rule.
  • Return a cleanup for every subscription, timer and request (AbortController); effects run twice on mount in development under StrictMode, and the code must survive that.
  • Use the data-loading approach the project already has (TanStack Query, SWR, framework loaders); no hand-rolled fetch in an effect where one exists.

Changes in React 19 and later

Summary: ref as prop, use, Actions, context provider, removed APIs

  • From React 19, a function component takes ref as a normal prop; forwardRef is not needed in new code. On React 18 and earlier, forwardRef stays.
  • use(promise) and use(context) read a promise or context during render and, unlike other hooks, may be called in a condition. The promise comes from a cache or a parent, not from the same render.
  • Form handling: a function as <form action>, useActionState (formerly useFormState), useFormStatus (from react-dom) and useOptimistic replace hand-written pending and error state.
  • Removed in 19, do not write them: propTypes and defaultProps on function components, ReactDOM.render and hydrate (use createRoot/hydrateRoot), string refs, legacy context.
  • useEffectEvent exists from React 19.2; before that, keep the latest value in a ref.

Server components and testing

Summary: server components only with a supporting framework, “use client” boundary, Testing Library by role

  • Server Components, "use server" and "use client" need a framework or bundler that supports them (Next.js App Router; React Router’s support is still experimental). In a plain Vite single-page app they do not exist; do not add the directives there.
  • With Server Components, a component is a server component by default: no state, effects or browser APIs. Put "use client" on the smallest leaf that needs interactivity; props across the boundary must be serializable.
  • Test with @testing-library/react and user-event: find elements by role, label or text as a user would, not by class name or internals; prefer findBy… over fixed waits.
  • Run tests with the runner the project has set up (Vitest or Jest), and mock the network at its boundary (msw), not the component’s own modules.

Coding rules — Rust

Source: .act/coding/rust.md

Summary: error handling, numbers, ownership and unsafe, async, edition and toolchain, tests

Rules for Rust projects built with Cargo. Group IDs (CR-rust-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Error handling, numbers, ownership, unsafe

Summary: no unwrap/expect in libraries, checked conversions and overflow, no needless clone, SAFETY comments

  • Library code never panics on a recoverable condition: no unwrap()/expect(), no indexing that can go out of bounds on external input, no panic! for bad arguments — return Result and let the caller decide. unwrap()/expect() are allowed in tests, in examples, and in main for startup failures; expect("...") then names the violated assumption, not the symptom.
  • Define errors as typed values: an error enum (with thiserror if the project has it) in libraries, anyhow or Box<dyn Error> only in the binary’s top layer. Every error states what failed and with what value; propagate with ? and add context instead of discarding the cause.
  • Do not add .clone() to silence the borrow checker. First try borrowing (&T, &mut T), a shorter lifetime, restructuring the code, or Rc/Arc where shared ownership is real; clone only when a separate owned value is what is meant.
  • Take &str, &[T] and &Path in parameters instead of &String, &Vec<T>, &PathBuf.
  • Every unsafe block carries a // SAFETY: comment stating the invariant that makes it sound, and encloses as little code as possible; every unsafe fn documents its contract under # Safety. Do not reach for unsafe to get around a compile error.
  • Never ignore a Result or #[must_use] value with let _ = without a stated reason.
  • Do not suppress warnings wholesale (#![allow(warnings)]); an #[allow(clippy::...)] names the lint and the reason.
  • Narrowing or sign-changing as truncates or wraps silently: use TryFrom/try_into() and handle the error, From/into() to widen; as only on a proven range, with a comment. The Clippy lint for it (cast_possible_truncation) is in pedantic, so -D warnings misses it.
  • Arithmetic on outside values (input, files, network, sizes, offsets) handles overflow: checked_* with an error, or saturating_*/wrapping_* by intent; release builds wrap silently unless the profile sets overflow-checks = true.

Async code

Summary: no blocking in tasks, project runtime, cancel-safe select!, bounded channels, async fn in traits

  • In async code, never block a task: no std::fs/std::net, blocking HTTP client, std::thread::sleep or long CPU work in an async fn; use the async variant (tokio::fs, tokio::time::sleep) or the blocking pool (spawn_blocking). No default lint catches this.
  • The runtime and its features are a project decision: read them from Cargo.toml (tokio, async-std, smol …), write for that runtime, add no second one, enable no new feature unasked.
  • select! in a loop drops the futures of the branches that lost, on every turn: use only futures documented as cancel-safe there, or create the future once before the loop, pin it and poll it by &mut; else half-read data is lost.
  • Channels between tasks are bounded (tokio::sync::mpsc::channel(n), not std’s mpsc::channel()) so a slow consumer pushes back; unbounded only where the producer is bounded by construction, with a comment why.
  • With rust-version 1.75 or newer, write async fn in a trait directly instead of async_trait, unless the trait is used as dyn Trait; in a public trait (rustc’s async_fn_in_trait lint warns there) or where callers need a Send future, declare fn name(&self) -> impl Future<Output = T> + Send. Keep async_trait where the project needs it for dyn. Below 1.75 this does not apply (R-code-version).

Edition, formatting, lint

Summary: edition and rust-version from Cargo.toml, project lints, MSRV-fit dependencies, fmt, clippy

  • Read the edition (edition = "2021" or "2024") and the minimum Rust version (rust-version) from Cargo.toml and write code that compiles under them: the 2024 edition needs Rust 1.85 or newer and changes, among other things, unsafe rules for extern blocks and the scope of temporaries; do not use syntax or library items newer than rust-version (R-code-version). Do not change the edition unasked.
  • Format with cargo fmt (rustfmt) and lint with cargo clippy --all-targets -- -D warnings — the template’s usual choice; run whatever the project has configured (see R-code-tools), and install nothing unasked.
  • Commit Cargo.lock for binaries and, per Cargo’s current advice, for libraries too; keep dependencies few and prefer the standard library where it suffices. Enable only the crate features that are used.
  • Follow the project’s lint configuration ([lints]/[workspace.lints] in Cargo.toml, clippy.toml, crate-level #![deny(...)]); never loosen or extend it unasked (R-code-checks-intact). A new dependency comes in a version whose own rust-version fits the project’s: resolver = "3" (the default from edition 2024) picks such versions; otherwise check it, and never raise the project’s rust-version to fit one.

cargo test

Summary: cargo test by default, unit tests beside the code, integration tests in tests/, doc tests

  • cargo test is the template’s usual runner; use the one the project has set up (cargo nextest, for example — see R-code-tools).
  • Put unit tests in a #[cfg(test)] mod tests beside the code, integration tests in tests/, and keep examples in doc comments compiling as doc tests.
  • Name tests after the expected behavior. Never use randomness without a fixed seed, and never wait with thread::sleep; wait on the actual condition instead.

Coding rules — SQL

Source: .act/coding/sql.md

Summary: query safety, transactions, indexing, naming, migrations, MySQL/MariaDB pitfalls

Rules for schema changes and database access from application code. Group IDs (CR-sql-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Query safety and schema discipline

Summary: parametrized queries, transactions without network calls, UTC, indexing, no hidden logic, locking

  • Use parametrized queries only — never build a query by concatenating values into the SQL string, in any language or driver.
  • Never SELECT * in application code; name columns explicitly, so a schema change breaks visibly instead of silently changing what a query returns.
  • Bundle multi-step writes into one transaction; don’t reconcile partial failures by hand afterward.
  • Make no network call inside a transaction that holds row locks: the locks last as long as the slowest remote answer. Resolve external values before the transaction opens (after the permission checks), cap the number of fetches per request and run them in parallel; helpers called inside the transaction get only resolved values. A retried transaction makes it worse, since the callback and every call in it runs again. In review ask: where does the transaction start and end, how many outside calls, how long at most.
  • Store timestamps in UTC; convert to a time zone only in the presentation layer (on MySQL/MariaDB mind CONVERT_TZ, see CR-sql-mariadb).
  • Add an index to every foreign-key column — without one, joins and cascading deletes degrade as the table grows.
  • Keep application logic out of stored procedures and triggers; logic that isn’t visible in the application code isn’t reviewable.
  • Check a column type change on a large table for lock behavior and expected runtime before running it live.

Identifier naming

Summary: snake_case, plural tables, singular columns

  • Name tables and columns in snake_case.
  • Use the plural for table names, the singular for column names.

Migration discipline

Summary: versioned naming, idempotent, reversible, one tool

  • Name migrations with a version (sequence number or timestamp) plus a description; one file per change.
  • Write migrations idempotently (IF NOT EXISTS or an existence check) — running an already-migrated state again must not fail.
  • Ship a down-migration with every migration where the migration tool supports it.
  • Use one migration tool consistently (e.g. Flyway, Prisma Migrate, Alembic); don’t mix.

MySQL and MariaDB (InnoDB) pitfalls

Summary: gap locks on range writes, error 1020 under snapshot isolation, LOCK IN SHARE MODE instead of FOR SHARE, ALTER and ENUM changes on versioned tables, CONVERT_TZ without zone tables

  • InnoDB (default isolation level REPEATABLE READ): a range UPDATE or DELETE on a table that others insert into takes gap locks and can deadlock with a concurrent INSERT. Read the ids first without a lock, then change by WHERE id IN (…). It shows only with many rows and several concurrent writers, so a small test does not catch it.
  • MariaDB 11.6.2 and later (innodb_snapshot_isolation is on by default): error 1020 (“record has changed since last read”) aborts a locking read and an UPDATE/DELETE of a row changed after the transaction’s snapshot. It also aborts the foreign-key check of an INSERT once the transaction has read anything without a lock and another transaction has since changed the parent row, in any column. 1020 rolls back the whole transaction: retry only the whole transaction, with growing, randomised waits, then give up with a clear error; effects outside the database are not rolled back. Locking the parent row (FOR UPDATE) before the first unlocked read avoids the foreign-key case. Safeguard: run every transaction through one retry helper or give it a marker comment stating why it needs none, and let a fast unit test find transactions with neither.
  • MariaDB: a shared read lock is written LOCK IN SHARE MODE; the MySQL 8 form FOR SHARE is a syntax error there. A query builder’s forShare() (Kysely, for one) emits the MySQL form, and the error shows only at run time against a real database: append the lock clause raw at the end of the query instead (Kysely: .modifyEnd(sql`lock in share mode`)); MySQL 8 accepts that form too. FOR UPDATE is the same in both.
  • MariaDB, system-versioned table: an ALTER TABLE that changes its columns is refused by default. Set system_versioning_alter_history = KEEP for the session just around the ALTER, on the same connection taken from the pool, and reset it in a finally; a migration run at application start otherwise aborts every start. KEEP leaves the history rows as they are, so a change that contradicts old values still fails (the ENUM case below).
  • MariaDB, system-versioned table: dropping a value from an ENUM fails on history rows, including rows just replaced. Keep the value in the type, move the current rows, reject the old value in the application, and change the default with ALTER COLUMN … SET DEFAULT. Test the migration against a database that has such history rows.
  • MySQL/MariaDB: CONVERT_TZ with zone names returns NULL without any error when the time-zone tables are not loaded (common on managed or container databases). Hand the offset in as a number, or do the conversion in application code.

Coding rules — Tailwind

Source: .act/coding/tailwind.md

Summary: utility-first styling, design tokens, dark mode, class sorting

Rules for Tailwind CSS, usually applied inside a frontend framework. Group IDs (CR-tailwind-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Established Tailwind defaults

Summary: utilities in markup, tokens, theme, dark mode, extraction, tooling, pitfalls

  • Write utility classes directly in markup; no separate CSS files without a concrete reason.
  • Use design tokens (the spacing, color and radius scale from the config) instead of arbitrary values — p-[13px] only as a documented exception.
  • Keep theme changes (colors, fonts, breakpoints) centralized in the Tailwind config, not scattered across files.
  • Map dark mode through the configured tokens/variants, never parallel hardcoded color values.
  • Extract a repeated class combination into a component/partial; never copy it around as a text snippet.
  • Lint/format tooling is the stack’s standard and belongs in the project: prettier-plugin-tailwindcss for automatic class sorting (layout, box model, typography, color, state), enforced by the formatter instead of sorted by hand. Run what is installed, install nothing unasked.
  • Pitfalls:
    • Use @apply only in exceptions (e.g. base styles of a third-party component), never as the default way to style.
    • Keep source detection correct — v3: the content paths in the config; v4 and later: automatic, with @source for additions. A wrong or missing source either drops classes that are actually used or leaves unused utility classes in the build.

Coding rules — TypeScript

Source: .act/coding/typescript.md

Summary: strict mode, no any, typed errors, module structure, tooling

Rules for TypeScript projects in strict mode. Group IDs (CR-typescript-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Strict mode, narrowing, typed errors

Summary: strict, no any, return types, as/!, error handling, lint

  • Enable strict: true in tsconfig.json; loosen it only with a comment explaining why.
  • Never use any — type unknown values as unknown and narrow them before use.
  • Draw the line where strictness stops helping: a type nested deeper than the code it describes (heavily nested generics, chained conditional types, stretched mapped types) is worse than a simpler one. Fall back to unknown with a check at the boundary, or a narrow interface for just the fields used, with a comment saying why — the exception serves readability, not convenience, and any stays excluded even here.
  • Give exported functions an explicit return type instead of relying on inference.
  • Use as Type only when narrowing cannot do the job, and say why in a comment.
  • Never use the non-null assertion (!) — it suppresses a real nullability check.
  • Raise errors as typed Error objects, never throw an arbitrary value; whatever is thrown, logged or rethrown, its message names what failed and with what — a caller must find the cause without opening the source.
  • Lint and typecheck (tsc --noEmit) are the stack’s standard and belong in the project; run what is installed, install nothing unasked.

interface, type, generics

Summary: interface for shapes, type for unions, no enums, generics from second use

  • Use interface for object shapes/contracts, type for unions, intersections and derived types.
  • Avoid enums — use as const objects or union literal types instead.
  • Introduce a generic only once a second concrete use exists; a concrete type is fine for the first.

Central types, explicit exports

Summary: shared types in one place, public exports through an index

  • Define shared types/schemas in one central place and import them, instead of redeclaring them per module.
  • Expose a module’s public API through an explicit index, not deep import paths into another module.

Lint and format tooling

Summary: ESLint with @typescript-eslint plus Prettier by default, or what the project has set up

  • ESLint with @typescript-eslint and Prettier for formatting are the template’s usual choice; what the project actually has installed and configured governs (see R-code-tools).

Coding rules — Vue

Source: .act/coding/vue.md

Summary: composition API, typed props, SFC order, shared state, tooling

requires: typescript

Rules for Vue 3 components using the Composition API. Group IDs (CR-vue-<name>) are stable and never reassigned; a group whose purpose no longer holds gets a new ID and is listed as retired: in this header.

Composition API, typed props, safe forms

Summary: script setup, typed props/emits, conventions, error handling, pitfalls

  • Use <script setup lang="ts"> in every component; no Options API in new code.
  • Type defineProps<...>() and defineEmits<...>() — no loose object props.
  • Keep no business logic in the <template> — move computations into computed or a method.
  • Choose ref for primitive/atomic values, reactive only for one connected object state.
  • Give composables a useX name and an explicit return type when it is not trivially inferred.
  • Clean up a watcher/effect that binds a resource (timer, listener) once it is no longer needed.
  • Catch errors around calls in components and composables on purpose: surface them where the template can show them, or rethrow — never swallow one silently; the message names what failed and with what. Use onErrorCaptured to handle a child component’s error deliberately, not as a global catch-all.
  • Lint is the stack’s standard and belongs in the project; run what is installed, install nothing unasked.
  • Pitfalls:
    • Never combine v-if and v-for on the same element.
    • Never mutate a prop directly — report a change to the parent through an event.
    • Security: a form using @submit.prevent also needs method="post" on the <form> element. The handler only exists once hydration finishes; a submit before that point (a password manager pressing enter, a slow connection, a blocked JS bundle) triggers the browser’s native submit. Without method that is a GET to the current URL — a form carrying credentials puts the values in the address bar, browser history and server log. Applies to every server-rendered app, not only auth forms (see GHSA-gj2h-2fpw-fhv9, the same bug in @nuxt/ui before 4.8.1).

Fixed SFC block order

Summary: template, script setup, style

  • Order SFC blocks as <template>, <script setup>, <style>.

Store module for shared state

Summary: Pinia store instead of provide/inject

  • Keep state shared across the app in a dedicated store module (Pinia), not in provide/inject.

Lint and format tooling

Summary: ESLint with eslint-plugin-vue plus Prettier by default, or what the project has set up

  • ESLint with eslint-plugin-vue and Prettier for formatting are the template’s usual choice; what the project actually has installed and configured governs (see R-code-tools).