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.
CR-bash-basics
Section titled “CR-bash-basics”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 pipefailas 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
shellcheckas the stack’s standard linter before every commit; do not suppress its warnings wholesale. - Pitfalls:
- Never parse the output of
lsin a loop — use globbing orfind ... -print0withread -d ''. - Check the result of
cd(cd dir || exit 1); otherwise following commands run in the wrong directory.
- Never parse the output of
CR-bash-script-shape
Section titled “CR-bash-script-shape”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.
CR-c-basics
Section titled “CR-c-basics”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, orCMAKE_C_STANDARD) and use nothing newer:nullptr,constexpr,boolas a keyword andtypeofare C23 only;_Generic,_Static_assertand<threads.h>need C11. Without a configured standard, assume C11. - Never write C++ habits into C: no cast of the
mallocresult, nobool/truewithout<stdbool.h>before C23, and declare parameterless functions asf(void), notf(). - 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-tidyas the usual linter andclang-formatas 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.
CR-c-memory
Section titled “CR-c-memory”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,strcatorsprintfinto a fixed buffer — usesnprintfandmemcpywith an explicit length, and terminate strings yourself where the function does not (strncpy). - Every
malloc/calloc/reallocresult is checked forNULLbefore use.reallocgoes 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 (callocdoes 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
NULLafterwards where it stays in scope, and release on every error path (a singlegoto cleanupexit is the accepted idiom). - Never return or store a pointer to a local (stack) variable.
CR-c-correctness
Section titled “CR-c-correctness”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,snprintftruncation,read/write,pthread_*); an error message names the call, its argument anderrno(strerror). - Signed integer overflow is undefined behavior: validate operands before the arithmetic, not after.
Use
size_tfor sizes and indices, and never compare signed with unsigned without an explicit conversion. Check shift counts, division by zero andINT_MIN / -1. - Do not read an object through a pointer of an incompatible type (strict aliasing) or an uninitialized
variable; use
memcpyfor type punning and initialize at declaration. - Make unused parameters and switch fallthrough explicit (
(void)x;, a comment, or[[fallthrough]]in C23), not silent.
CR-c-tests
Section titled “CR-c-tests”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.
CR-ci-supply-chain
Section titled “CR-ci-supply-chain”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/remoteand CI images to a commit SHA or an image digest, never tomainorlatest. - Set
permissions:at the top of every workflow, tocontents: 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, GitLabid_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/checkoutwithpersist-credentials: falseunless a later step pushes.
CR-ci-injection
Section titled “CR-ci-injection”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 arun:script — the text is substituted before the shell parses it and becomes code. Pass it throughenv: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 insidescript:, neverevalor splice them. pull_request_targetandworkflow_runrun 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 plainpull_requestfor 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, GitLabrules:with$CI_COMMIT_REF_PROTECTED), behind the environment’s required approval.
CR-ci-secrets
Section titled “CR-ci-secrets”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 throughenv:, not as an argument. - Never
echoa secret or a value derived from it, and noset -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.
CR-ci-runtime
Section titled “CR-ci-runtime”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'), GitLabcache:key:files), never on a fixed string; cache downloaded dependencies, not build output of untrusted branches. - Set
concurrency:withcancel-in-progress: truefor pull request checks; never cancel a running deploy or release — give those a group without cancellation. GitLab:interruptible: trueandresource_groupfor deploys. - Set
timeout-minutes:(GitLabtimeout:) 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 tocontinue-on-error(R-code-checks-intact). - GitLab: use
rules:, not the deprecatedonly:/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.
CR-cpp-basics
Section titled “CR-cpp-basics”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_viewand structured bindings are C++17; concepts, ranges,std::spanandstd::formatare C++20 (std::formatalso needs a recent standard library);std::expectedandstd::printare 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-tidyas the usual linter andclang-formatas 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(usenullptr), or raw arrays wherestd::array,std::vectororstd::stringfit.
CR-cpp-ownership
Section titled “CR-cpp-ownership”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: usestd::make_unique(default) orstd::make_shared(only for genuinely shared ownership), containers, orstd::lock_guard/std::scoped_lock. - A raw pointer or reference is non-owning and borrowed; never
deletethrough it and never keep it beyond the owner’s lifetime. Do not return a reference orstd::string_viewto 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.
CR-cpp-correctness
Section titled “CR-cpp-correctness”const, types and undefined behavior
Summary: const by default, explicit constructors, no unchecked casts, container invalidation
constby default for variables, member functions and parameters; pass large read-only arguments byconst&, small ones by value. Mark single-argument constructorsexplicitand overridesoverride.- Use
static_castand friends only where needed; no C-style casts, and neverreinterpret_castor a cast that removesconstwithout 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 classover plainenum.
CR-cpp-tests
Section titled “CR-cpp-tests”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).
csharp
Section titled “csharp”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.
CR-csharp-basics
Section titled “CR-csharp-basics”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
Asyncsuffix and returnTask/Task<T>. - Never use
async voidoutside event handlers — useasync Task, otherwise exceptions are swallowed. - Avoid
.Result/.Wait()on tasks; blocking on a task this way risks a deadlock in synchronous contexts. - Manage every
IDisposableresource exclusively throughusing/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 formatand the analyzer rules (.editorconfigsectiondotnet_diagnostic) as the stack’s standard linting/static analysis; set them up in every project, run what is installed.
CR-csharp-conventions
Section titled “CR-csharp-conventions”var, records, one type per file
Summary: var only for an obvious type, records for value objects, one public type per file
- Use
varonly 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.
CR-csharp-dependency-injection
Section titled “CR-csharp-dependency-injection”Constructor injection
Summary: constructor injection, no service locator
- Inject dependencies through the constructor; no hidden service-locator access.
CR-csharp-library-code
Section titled “CR-csharp-library-code”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.
CR-css-tokens
Section titled “CR-css-tokens”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 usevar(--…)everywhere else; a hex value or13pxrepeated 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.
CR-css-cascade
Section titled “CR-css-cascade”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#idselectors, 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: nonewithout a visible:focus-visiblereplacement.
CR-css-layout
Section titled “CR-css-layout”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,
gapfor spacing between items; no floats or fixed heights that clip text. - Size text and spacing in
rem/em, notpx, so user font settings still work;pxis 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
browserslistor stated targets before using a new feature (container queries,:has(), nesting); do not assume the newest syntax is available.
CR-css-toolchain
Section titled “CR-css-toolchain”Lint and format tooling
Summary: stylelint by default, formatter of the project, SCSS only if the project already uses it
stylelintwith the project’s shared config is the template’s usual choice for linting,prettierfor formatting — either way, run what the project actually has configured (seeR-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.
docker
Section titled “docker”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.
CR-docker-image
Section titled “CR-docker-image”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:...); neverlatestor 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
builderstage; 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 laterrmdoes not shrink an earlier layer. - Prefer
COPYtoADD; use the exec form forCMDandENTRYPOINT(["python", "app.py"]) so signals reach the program; one main process per container.
CR-docker-security
Section titled “CR-docker-security”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 setUSERbeforeCMD; copy files with--chown. Do not run a service as root “to make it work”. - Keep a
.dockerignorenext 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,COPYor aRUNargument: 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.
CR-docker-compose
Section titled “CR-docker-compose”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-levelversion:key. Check the installed version withdocker compose version. - Pin every
image:as above; nolatest. 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
.envfile orsecrets:, never incompose.yaml; commit only an.env.example. Publish only the ports that are needed, bound to127.0.0.1unless the service is meant to be reachable from outside. A host port clashes with the owner’s server — seeR-safe-dev-server. - Make start order real:
depends_onwithcondition: service_healthyand ahealthcheck, not a sleep.
CR-docker-toolchain
Section titled “CR-docker-toolchain”Lint and build checks
Summary: hadolint for Dockerfiles, docker compose config for Compose, or what the project has set up
hadolintis the template’s usual Dockerfile linter; validate Compose files withdocker 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.
CR-go-basics
Section titled “CR-go-basics”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/goimportsbefore 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)) soerrors.Is/errors.Askeep working further up the call chain; never lose or flatten the underlying error. - Run
go vetandstaticcheckin 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.Contextis the first parameter of any function that must propagate cancellation, a deadline, or request-scoped values.- Every goroutine has a visible lifecycle end (
WaitGroupor context cancellation) — a goroutine with no way to stop is a leak. - Synchronize state shared between goroutines through channels or explicit locks, never silently.
CR-go-package-design
Section titled “CR-go-package-design”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/commongrab-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.
CR-java-basics
Section titled “CR-java-basics”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/@NonNullor the alternative the project has fixed on) instead of leaving it implicit. - No raw
Object, no raw types on generics. - No empty
catchblocks and nocatch (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 manualsynchronized/wait/notify. - Log through SLF4J, parametrized (
log.info("user {} failed", id), never string concatenation) — seeR-safe-no-secret-logfor what never goes into a log line at all. - Use
varonly 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/hashCodeonly together; usejava.time, neverDate/Calendar; useBigDecimalfor money, neverfloat/double; stateUTF_8explicitly, 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.
CR-java-modern-idioms
Section titled “CR-java-modern-idioms”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,hashCodeand 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(switchon type) instead ofinstanceofchains — 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.
CR-java-structure
Section titled “CR-java-structure”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.
CR-java-toolchain
Section titled “CR-java-toolchain”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).
CR-java-tests
Section titled “CR-java-tests”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.
javascript
Section titled “javascript”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.
CR-javascript-basics
Section titled “CR-javascript-basics”Modern language defaults
Summary: ESM, const/let, strict equality, async/await, explicit errors
- Use ES modules:
"type": "module"inpackage.json,import/export, thenode:prefix for built-ins (import fs from "node:fs/promises"), and the file extension in relative imports. No new CommonJS (require,module.exports);__dirnamebecomesimport.meta.dirname(Node 20.11+). constby default,letwhere reassigned, nevervar.- Compare with
===/!==;==only for the deliberatex == nullcheck, with a comment. async/awaitover.thenchains.forEachdoes not wait for an async callback — usefor…ofwithawait, orPromise.allovermapwhen the calls are independent.- Throw
Errorobjects (withcausewhen 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.
CR-javascript-promises
Section titled “CR-javascript-promises”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
asyncfunction as an event handler orsetIntervalcallback without its owntry/catch. - No
new Promise(async (resolve) => …); noawaitin a loop where the calls are independent. - ESLint core cannot find floating promises (
@typescript-eslint/no-floating-promisesneeds types), so review for them, and set a top-level handler forunhandledRejectionthat logs and exits non-zero.
CR-javascript-toolchain
Section titled “CR-javascript-toolchain”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.nodeinpackage.jsonplus.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-prettierwhere both run — not a second style guide. - Tests: the built-in
node:testrunner (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-lockfileoryarn install --immutable, never a plain install. With pnpm,pnpm updateandpnpm why <package>replacenpm 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).
kotlin
Section titled “kotlin”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.
CR-kotlin-basics
Section titled “CR-kotlin-basics”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 earlyreturn, orrequireNotNull(x) { "message" }/checkNotNullwhere a missing value is a bug — the message names what was missing.lateinitonly for framework-injected fields. - Prefer
valovervar, 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 catchCancellationExceptionwithout rethrowing it. UseResultor 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.timetypes (notDate/Calendar) on the JVM. - Log through SLF4J or the project’s logging facade with parametrized messages — see
R-safe-no-secret-logfor what never goes into a log line.
CR-kotlin-coroutines
Section titled “CR-kotlin-coroutines”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 ownCoroutineScope) so that failure and cancellation propagate. - Do not call
runBlockingin production code outsidemainand test bridges, and do not block a coroutine thread withThread.sleepor blocking I/O: usedelayandwithContext(Dispatchers.IO). - Inject dispatchers as parameters instead of hard-coding
Dispatchers.IO/Default, so tests can replace them. Exposesuspendfunctions orFlowfrom APIs, notDeferredor callbacks. - Use
kotlinx-coroutines-test(runTest) for coroutine tests; never wait withThread.sleep.
CR-kotlin-data-modeling
Section titled “CR-kotlin-data-modeling”data class, sealed types, value classes
Summary: data class for values, sealed types for closed sets, copy over mutation
- Model plain values as
data classwithvalproperties and change them withcopy(); do not put logic with side effects into adata class. - Model closed sets of cases as
sealed interface/sealed classand match them with an exhaustivewhenwithout anelsebranch, so adding a case breaks the build. - Use
@JvmInline value classfor typed identifiers (ids, units) instead of bareString/Long; useenum classonly for a fixed set without per-case data.
CR-kotlin-toolchain
Section titled “CR-kotlin-toolchain”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 inwhenare 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 (seeR-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.
CR-nuxt-basics
Section titled “CR-nuxt-basics”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/useAsyncDatawhile rendering, use$fetchfor one-off writes and actions. -
Never copy the return value of
useFetch/useAsyncDatainto your ownref— pass the returned object through andawaitit wheredata/status/errorreach 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 lostfunction useThing() {const result = ref()useFetch('/api/thing').then(r => (result.value = r.data.value))return result}// Right — pass the returned object through unchangedasync function useThing() {return await useFetch('/api/thing')}``` -
Path aliases, by installed Nuxt major (
R-code-version). Since Nuxt 4,~points atapp/, so without its own entry~/typesresolves 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 roottsconfig.jsonholds nothing butreferencesto those generated configs and never its ownpaths: withfiles: []plusreferencesapathsthere 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 itspaths, and the framework aliases disappear. - Nuxt 3: declare aliases in
nuxt.config.tsas well; a roottsconfig.jsonthat extends./.nuxt/tsconfig.jsonmay addpathsonly if it repeats every generated entry. Nuxt 3 also writes eachaliasinto the generatedpaths, so thenuxt.config.tsentry alone is enough; the generated.nuxt/tsconfig.jsonshows it.
- Nuxt 4 and later: declare aliases only in
-
Files the generated contexts leave out (unit and e2e tests, test-runner configs) are skipped by
nuxt typecheckwithout a message. Add them through Nuxt’s TypeScript options innuxt.config.ts(typescript.tsConfig.include, or the per-contexttypescript.sharedTsConfig/typescript.nodeTsConfig/typescript.tsConfigobjects on Nuxt 4; the server context vianitro.typescript.tsConfig), then prove each context once: put a deliberate type error in one file of it, seenuxt typecheckfail, 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
runtimeConfigfor configuration values instead of readingprocess.envin components; secrets live in the private part ofruntimeConfig, never underpublic. -
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 withcreateErrorand 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 typecheckneedsvue-tscas 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), plustest(vitest run) andtest: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. UseuseStatefor state that must survive the request. - Forms with
@submit.preventalso needmethod="post"(seeCR-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 onnetstat | findstr LISTENING(the word is localized,ABHÖRENon German Windows). The filter can still list Bound or Closed entries and several or stale PIDs: beforeStop-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 inpowershell -NoProfile -Command "…", or usetaskkill //PID <pid> //F(a single/PIDis rewritten to a path there and ends nothing). Afterwards requesthttp://localhost:<port>/(a server may listen on::1only): it must be refused. Elsewhere uselsof -iTCP:<port> -sTCP:LISTENandkill <pid>. A server on the owner’s port is theirs: ask first. - Security: set
workspaceDirinnuxt.config.tsto 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 (advisoryGHSA-mjrq-cffv-q4qc, Nuxt 3 and 4 through@nuxt/schema3.5.0 up to below 4.6.4, fixed in 4.6.4).
- SSR code must not touch browser globals (
CR-nuxt-root-folders
Section titled “CR-nuxt-root-folders”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/orshared/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 inapp/utils/, code only the server runs inserver/utils/. shared/needs Nuxt 3.14 or later (R-code-version). Nuxt 4 auto-importsshared/utils/in app and server; Nuxt 3 does so only withfuture.compatibilityVersion: 4, otherwise import from#shared/utils/….
CR-nuxt-ssr
Section titled “CR-nuxt-ssr”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: falseor 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 throughuseState, never a module-levelref; 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-elsechain 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/useAsyncDataresult into your ownrefis a common hydration-mismatch cause too — seeCR-nuxt-basicsfor 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>, providernone,clientBundle.scan,fallbackToApi: false; an unknown icon then shows as missing with a console warning.
CR-nuxt-toolchain
Section titled “CR-nuxt-toolchain”Lint and format tooling
Summary: ESLint with @nuxt/eslint plus Prettier, whichever the project has set up
- ESLint with
@nuxt/eslint, configured ineslint.config.mjs, and Prettier for formatting are the template’s usual choice; what the project actually has installed and configured governs (seeR-code-tools).
CR-nuxt-tests
Section titled “CR-nuxt-tests”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 (seeR-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/ui4.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 (ignoresineslint.config,.prettierignore,ignoreinnuxt.config) where they do not skip it already. Each test server gets its ownbuildDir, Nitro output dir and VitecacheDir(absolute: Vite resolves a relative one againstapp/), all three from an environment variable thatnuxt.configreads, plus its own port. Reported for the Nuxt 5 CLI:nuxt devlocks itsbuildDirand refuses a second dev server on it, and on the same port a non-interactivenuxt devends 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 ownbuildDirmay 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.
CR-nuxt5-channel
Section titled “CR-nuxt5-channel”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
nuxtas"npm:nuxt-nightly@5x"— a tag, never a build number. Ifnpm install(pnpm install) writes a fixed version, set it back to@5xby hand and install again (with pnpm that install is itself a Nuxt update, see below); only the lockfile pins the state. Drops oncenuxt/nuxttagsv5.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 fromCR-nuxt5-checks. - Direct dependencies that Nuxt brings along stay on the same major as Nuxt does (e.g.
vue-router5,@unhead/vue3); after every update,npm ls <package>(pnpm why <package>) shows one copy of each. - Node 22.21 or 24.11 at least.
- Install
@nuxt/devtoolsexplicitly as a devDependency; run it only in the dev server and only withNUXT_DEVTOOLS=1, and confirm each browser once with the code from the dev terminal. Never setdevtools.disableAuthorization. - With pnpm and
nuxtas 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 installafter a hand edit,pnpm update <package> --depth Infinityfor a transitive fix; even with Nuxt pinned exactly inpackage.jsonits 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 withpnpm why nuxtthat 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
nuxtinpackage.jsonfor the run to the exact version the lockfile holds, update the package, restorepackage.json, then set the lockfile’s specifier fornuxtback to the channel tag. Afterwardspnpm install --frozen-lockfilemust 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 inCR-nuxt5-checksto the fixed version without moving the nightly. Drops with the pnpm line above. - A nightly can raise its own
vuerange; a projectvueentry 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 viewalike), raise your entry to it, thennpm ls vue/pnpm why vueshows one version. Runnuxt preparetoo: the generated ESLint config can point at the old store path until it runs (postinstallusually does it). - pnpm 11’s
minimumReleaseAgemakespnpm update nuxttake 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
devorbuild, read the diff ofpackage.json: every entry the tooling added on its own is one you can explain.
CR-nuxt5-modules
Section titled “CR-nuxt5-modules”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_B8013switches off a module whosecompatibilityfield does not match, with nothing but a warning: check the field before the update, read the warnings after it.- Pinia 4:
@pinia/nuxt1 or later,@vue/devtools-api^8 as a direct dependency. @nuxtjs/i18n10.6, before it supports Nuxt 5:i18n.experimental.nitroContextDetection: false. Without it a path without locale prefix gets no server redirect (checked with strategyprefixon nightly5.0.0-2611122105); as reported, the default waits for the Nitro hookrender: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: falseis no longer needed from nightly5.0.0-2611031025on; remove it oncebuildand the E2E tests pass without it.- Under Nuxt 5 the
serverprovider of@nuxt/icondoes 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/vue5) (reported, upstream nuxt/icon issue 571). Use the bundled setup fromCR-nuxt-ssrand 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.
CR-nuxt5-server
Section titled “CR-nuxt5-server”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/, importdefineEventHandler,readBody,getQuery,createError… fromnuxt/server, and define plugins withdefinePluginfromnitro;server/utils/stays auto-imported. event.reqis the webRequest(there is noevent.node); read a multipart body withevent.req.formData().readBody<T>()with aninterfaceof 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 });statusTextin ASCII only (e.g.'Unprocessable Entity'), localized text goes intodata. - On the client,
createError({ data })arrives underresponse._data.data; the field errors of a 422 sit under…data.errors(e.g. for Nuxt UI’sUForm.setErrors). useRuntimeConfig()withoutevent.- 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 withMISSING_EXPORTonce a module keeps that file from being tree-shaken (seen withmlly1.8.2,@nuxtjs/i18n10.6.0, nightly5.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
/**innuxt.config: Nitro 3 serves files frompublic/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(useServerHooksfromnuxt/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 asR-safe-dev-serversays) before tests against it count; the owner’s server only after asking. No transitional alias for the old name. Never setNUXT_IGNORE_LOCKorNUXT_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.
CR-nuxt5-app
Section titled “CR-nuxt5-app”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 ofprocess.*(import.meta.client,import.meta.dev…).queryinstead ofparamsin the options of$fetch/useFetch.$fetchis 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$fetchwithas 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: … }">— fornavigateTo,router.push,NuxtLinkand a Nuxt UItoas well; a plain path gets no locale prefix and ends in a 404. For the same reason, builddefinePageMeta({ redirect })relative to the current path. - Unhead 3: no
hid/vmid, deduplicate withkey; a dev hint aboutog:*or the description is a finding, except the known case below. - Unhead 3 reports
og-missing-titleon a page that carries otherog:meta tags (often set app-wide) but noog:title(checked in Unhead 3.4.3, the validate plugin indist/plugins.mjs). On a page that deliberately has noog:title(private page, error page), leave out the otherog:tags there too; where that is not possible, treat the hint as a known false positive and re-check it after each Unhead update. Settingrules: { '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 intoapp.vueanderror.vue, since Nuxt renderserror.vuein place ofapp.vue. A head value that is missing is left out, never passed asundefined—useSeoMeta({ description: undefined })removes the fallback (so theog:titlecase above is solved by leaving tags out, not byundefined). - Pin
workspaceDiras the security line inCR-nuxt-basicssays; it holds for Nuxt 5 as well. - No
compilerOptions.baseUrlintsconfig.json— Nuxt ignores it; aliases go intonuxt.config.tsonly (CR-nuxt-basics).
CR-nuxt5-checks
Section titled “CR-nuxt5-checks”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), andtest:e2e;devand the built server as your own test servers (port asR-safe-dev-serversays), stopped afterwards. - Also between updates, a commit that changes an auto-imported folder (
server/,shared/,app/composables/,app/utils/) ornuxt.configrunsbuildbesides lint, typecheck and tests: they stay green on a broken export scan (CR-nuxt5-server), only the build fails. Build with its ownbuildDirand Nitro output dir asCR-nuxt-testssays, 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, runpython .act/scripts/security_scan.py --deps. - Count copies of a package with
npm ls <package>/pnpm why <package>; folders undernode_modules/.pnpmleft from earlier installs stay until pnpm prunes them (modulesCacheMaxAge) and are not copies. - Under the nightly, common modules still pull
@nuxt/kit4.x and with it an@nuxt/schema4.x: the dependency scan reports theworkspaceDiradvisory (CR-nuxt-basics) on that copy, not on the nightly, so the hit is expected. Lift the copy asCR-nuxt5-channeldescribes for a single package. Drops once the common modules depend on a Nuxt 5 kit. - A
MaxListenersExceededWarningaboutcloselisteners on the server response in the nightly’snuxt devis 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 innuxt devon a current nightly. npm ls --all 2>&1 | grep invalid: fix a stale resolution withnpm update <package>(with pnpm:pnpm why <package>,pnpm update <package>, under the pnpm line ofCR-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 indocs/project/coding_rules.mdand goes to the template throughact-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.
CR-php-basics
Section titled “CR-php-basics”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
mixedonly with a comment justifying it, and mark nullable types (?Type) explicitly instead of falling back to an implicitnull. - Throw exceptions instead of returning
falseor 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_errorsoff 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.
CR-php-conventions
Section titled “CR-php-conventions”Closures over global callbacks
Summary: arrow functions and closures instead of global callback functions
- Use arrow functions/closures instead of global callback functions.
CR-php-toolchain
Section titled “CR-php-toolchain”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).
powershell
Section titled “powershell”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.
CR-powershell-edition
Section titled “CR-powershell-edition”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.PSVersionand the project files before applying anything below (R-code-version); declare it in the script with#Requires -Version 5.1or#Requires -Version 7.0. - The two editions differ in defaults: 5.1 writes UTF-16 LE with
>,>>andOut-File, andSet-Contentuses the ANSI code page; 7 writes UTF-8 without BOM everywhere. Never rely on the default — pass-Encoding utf8(5.1 adds a BOM;utf8NoBOMexists only in 7) to everyOut-File,Set-Content,Add-ContentandExport-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), noexport VAR=...(use$env:VAR = ...), norm -rf(useRemove-Item -Recurseon a path you checked). - Windows pitfalls (the PowerShell items checked in 5.1 and 7.6, the CRLF-shebang failure in bash under WSL):
scis the alias ofSet-Contentin 5.1 (in 7 it resolves to the program); call the service tool assc.exe.Set-Content/Add-Contentend the text with CRLF even if it holds LF. A shell script needs-NoNewlineand LF throughout (or[IO.File]::WriteAllTextwithUTF8Encoding $false); a CRLF shebang fails on Linux with “required file not found” orbad interpreter.- A UTF-8 file without BOM read by 5.1
Get-Contentis taken as the ANSI code page and turns─into─: pass-Encoding UTF8when reading. - CSV for Excel in a decimal-comma locale:
-UseCultureor-Delimiter ';'; 5.1Export-Csvwrites ASCII by default (non-ASCII becomes?),-Encoding UTF8there writes a BOM, which Excel needs; in 7 use-Encoding utf8BOM. - A captured or redirected
pwsh7 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-Pathand$PSScriptRoot, never by concatenating\; quote paths that may contain spaces; use-LiteralPathwhen a name may contain[or].
CR-powershell-strictness
Section titled “CR-powershell-strictness”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 Latestand$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$ErrorActionPreferencedoes not catch it: check$LASTEXITCODEright after the call andthroworexitwith 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 emptycatch {}. Use-ErrorAction SilentlyContinueonly 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 withWrite-Errororthrow, notWrite-Host.
CR-powershell-style
Section titled “CR-powershell-style”Names, parameters, no aliases
Summary: approved verbs, advanced functions, param blocks with types, full cmdlet names, output as objects
- Name functions
Verb-Nounwith an approved verb (Get-Verblists them:Get-,Set-,New-,Remove-,Test-,Invoke-…); a singular noun, noDo-,Run-orCheck-. - Write a function as an advanced function:
[CmdletBinding()], aparam()block with a type on every parameter,[Parameter(Mandatory)]and[ValidateSet()]/[ValidateNotNullOrEmpty()]where they fit. Mark functions that change state withSupportsShouldProcessand honour-WhatIf. - No aliases in a script (
ls,gci,%,?,foreachforForEach-Object,curl,wget) and no positional parameters for anything beyond the first; write the full cmdlet and parameter name.curlandwgetare aliases ofInvoke-WebRequestin 5.1, not the programs. - Return objects, not formatted text: no
Format-TableorWrite-Hostin a function whose output is used further; useWrite-Verbosefor progress andWrite-Outputor an implicit return for the result.
CR-powershell-toolchain
Section titled “CR-powershell-toolchain”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 aPSScriptAnalyzerSettings.psd1in the project and do not exclude rules wholesale.Pesteris the usual test runner; check the installed major version first (Get-Module Pester -ListAvailable) — Pester 5 needsBeforeAllfor setup and discovery-time code differs from run-time code, so Pester 3/4 tests do not run unchanged. Run it withInvoke-Pester -CI.- Either way, run what the project has configured and install nothing unasked (
R-code-tools).
python
Section titled “python”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.
CR-python-basics
Section titled “CR-python-basics”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
withfor anything that must be opened and closed (files, locks, connections). - Never use a mutable default argument (
def f(x: list = [])) — default toNoneand initialize inside the function body. - Catch specific exception types; never a bare
except Exceptionwithout 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 notonly 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.
CR-python-stdlib-first
Section titled “CR-python-stdlib-first”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.
CR-python-data-models
Section titled “CR-python-data-models”Typed data instead of loose dicts
Summary: dataclasses, TypedDict or pydantic for structured data
- Model structured data with
dataclasses,TypedDictorpydantic, not a loosedict.
CR-python-module-structure
Section titled “CR-python-module-structure”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.
CR-python-toolchain
Section titled “CR-python-toolchain”Lint and format tooling
Summary: ruff by default for lint and formatting, or what the project has set up
rufffor both linting and formatting is the template’s usual choice;blackremains a common alternative for formatting in existing projects — either way, run what the project actually has configured (seeR-code-tools).
CR-python-tests
Section titled “CR-python-tests”Unit tests
Summary: pytest by default, or the test runner the project has set up
pytestis 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 (seeR-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.
CR-react-components
Section titled “CR-react-components”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-hooksrules 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. keyis a stable id from the data, never the array index for a list that can reorder, insert or delete, and neverMath.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.
CR-react-effects
Section titled “CR-react-effects”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
useEffectthat only callssetStatefrom other state is a bug in the making: derive the value, or reset by changing the component’skey. - 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 underStrictMode, and the code must survive that. - Use the data-loading approach the project already has (TanStack Query, SWR, framework loaders); no
hand-rolled
fetchin an effect where one exists.
CR-react-19
Section titled “CR-react-19”Changes in React 19 and later
Summary: ref as prop, use, Actions, context provider, removed APIs
- From React 19, a function component takes
refas a normal prop;forwardRefis not needed in new code. On React 18 and earlier,forwardRefstays. use(promise)anduse(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(formerlyuseFormState),useFormStatus(fromreact-dom) anduseOptimisticreplace hand-written pending and error state. - Removed in 19, do not write them:
propTypesanddefaultPropson function components,ReactDOM.renderandhydrate(usecreateRoot/hydrateRoot), string refs, legacy context. useEffectEventexists from React 19.2; before that, keep the latest value in a ref.
CR-react-structure
Section titled “CR-react-structure”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/reactanduser-event: find elements by role, label or text as a user would, not by class name or internals; preferfindBy…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.
CR-rust-basics
Section titled “CR-rust-basics”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, nopanic!for bad arguments — returnResultand let the caller decide.unwrap()/expect()are allowed in tests, in examples, and inmainfor startup failures;expect("...")then names the violated assumption, not the symptom. - Define errors as typed values: an error
enum(withthiserrorif the project has it) in libraries,anyhoworBox<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, orRc/Arcwhere shared ownership is real; clone only when a separate owned value is what is meant. - Take
&str,&[T]and&Pathin parameters instead of&String,&Vec<T>,&PathBuf. - Every
unsafeblock carries a// SAFETY:comment stating the invariant that makes it sound, and encloses as little code as possible; everyunsafe fndocuments its contract under# Safety. Do not reach forunsafeto get around a compile error. - Never ignore a
Resultor#[must_use]value withlet _ =without a stated reason. - Do not suppress warnings wholesale (
#![allow(warnings)]); an#[allow(clippy::...)]names the lint and the reason. - Narrowing or sign-changing
astruncates or wraps silently: useTryFrom/try_into()and handle the error,From/into()to widen;asonly on a proven range, with a comment. The Clippy lint for it (cast_possible_truncation) is inpedantic, so-D warningsmisses it. - Arithmetic on outside values (input, files, network, sizes, offsets) handles overflow:
checked_*with an error, orsaturating_*/wrapping_*by intent; release builds wrap silently unless the profile setsoverflow-checks = true.
CR-rust-async
Section titled “CR-rust-async”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::sleepor long CPU work in anasync 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
featuresare a project decision: read them fromCargo.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’smpsc::channel()) so a slow consumer pushes back; unbounded only where the producer is bounded by construction, with a comment why. - With
rust-version1.75 or newer, writeasync fnin a trait directly instead ofasync_trait, unless the trait is used asdyn Trait; in a public trait (rustc’sasync_fn_in_traitlint warns there) or where callers need aSendfuture, declarefn name(&self) -> impl Future<Output = T> + Send. Keepasync_traitwhere the project needs it fordyn. Below 1.75 this does not apply (R-code-version).
CR-rust-edition-toolchain
Section titled “CR-rust-edition-toolchain”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) fromCargo.tomland write code that compiles under them: the 2024 edition needs Rust 1.85 or newer and changes, among other things,unsaferules forexternblocks and the scope of temporaries; do not use syntax or library items newer thanrust-version(R-code-version). Do not change the edition unasked. - Format with
cargo fmt(rustfmt) and lint withcargo clippy --all-targets -- -D warnings— the template’s usual choice; run whatever the project has configured (seeR-code-tools), and install nothing unasked. - Commit
Cargo.lockfor 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]inCargo.toml,clippy.toml, crate-level#![deny(...)]); never loosen or extend it unasked (R-code-checks-intact). A new dependency comes in a version whose ownrust-versionfits the project’s:resolver = "3"(the default from edition 2024) picks such versions; otherwise check it, and never raise the project’srust-versionto fit one.
CR-rust-tests
Section titled “CR-rust-tests”cargo test
Summary: cargo test by default, unit tests beside the code, integration tests in tests/, doc tests
cargo testis the template’s usual runner; use the one the project has set up (cargo nextest, for example — seeR-code-tools).- Put unit tests in a
#[cfg(test)] mod testsbeside the code, integration tests intests/, 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.
CR-sql-basics
Section titled “CR-sql-basics”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, seeCR-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.
CR-sql-naming
Section titled “CR-sql-naming”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.
CR-sql-migrations
Section titled “CR-sql-migrations”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 EXISTSor 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.
CR-sql-mariadb
Section titled “CR-sql-mariadb”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 rangeUPDATEorDELETEon a table that others insert into takes gap locks and can deadlock with a concurrentINSERT. Read the ids first without a lock, then change byWHERE 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_isolationis on by default): error 1020 (“record has changed since last read”) aborts a locking read and anUPDATE/DELETEof a row changed after the transaction’s snapshot. It also aborts the foreign-key check of anINSERTonce 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 formFOR SHAREis a syntax error there. A query builder’sforShare()(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 UPDATEis the same in both. - MariaDB, system-versioned table: an
ALTER TABLEthat changes its columns is refused by default. Setsystem_versioning_alter_history = KEEPfor the session just around theALTER, on the same connection taken from the pool, and reset it in afinally; a migration run at application start otherwise aborts every start.KEEPleaves the history rows as they are, so a change that contradicts old values still fails (theENUMcase below). - MariaDB, system-versioned table: dropping a value from an
ENUMfails 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 withALTER COLUMN … SET DEFAULT. Test the migration against a database that has such history rows. - MySQL/MariaDB:
CONVERT_TZwith zone names returnsNULLwithout 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.
tailwind
Section titled “tailwind”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.
CR-tailwind-basics
Section titled “CR-tailwind-basics”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-tailwindcssfor 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
@applyonly in exceptions (e.g. base styles of a third-party component), never as the default way to style. - Keep source detection correct — v3: the
contentpaths in the config; v4 and later: automatic, with@sourcefor additions. A wrong or missing source either drops classes that are actually used or leaves unused utility classes in the build.
- Use
typescript
Section titled “typescript”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.
CR-typescript-basics
Section titled “CR-typescript-basics”Strict mode, narrowing, typed errors
Summary: strict, no any, return types, as/!, error handling, lint
- Enable
strict: trueintsconfig.json; loosen it only with a comment explaining why. - Never use
any— type unknown values asunknownand 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
unknownwith a check at the boundary, or a narrowinterfacefor just the fields used, with a comment saying why — the exception serves readability, not convenience, andanystays excluded even here. - Give exported functions an explicit return type instead of relying on inference.
- Use
as Typeonly 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
throwan 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.
CR-typescript-conventions
Section titled “CR-typescript-conventions”interface, type, generics
Summary: interface for shapes, type for unions, no enums, generics from second use
- Use
interfacefor object shapes/contracts,typefor unions, intersections and derived types. - Avoid enums — use
as constobjects or union literal types instead. - Introduce a generic only once a second concrete use exists; a concrete type is fine for the first.
CR-typescript-module-structure
Section titled “CR-typescript-module-structure”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.
CR-typescript-toolchain
Section titled “CR-typescript-toolchain”Lint and format tooling
Summary: ESLint with @typescript-eslint plus Prettier by default, or what the project has set up
- ESLint with
@typescript-eslintand Prettier for formatting are the template’s usual choice; what the project actually has installed and configured governs (seeR-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.
CR-vue-basics
Section titled “CR-vue-basics”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<...>()anddefineEmits<...>()— no loose object props. - Keep no business logic in the
<template>— move computations intocomputedor a method. - Choose
reffor primitive/atomic values,reactiveonly for one connected object state. - Give composables a
useXname 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
onErrorCapturedto 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-ifandv-foron the same element. - Never mutate a prop directly — report a change to the parent through an event.
- Security: a form using
@submit.preventalso needsmethod="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. Withoutmethodthat 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/uibefore 4.8.1).
- Never combine
CR-vue-sfc-order
Section titled “CR-vue-sfc-order”Fixed SFC block order
Summary: template, script setup, style
- Order SFC blocks as
<template>,<script setup>,<style>.
CR-vue-state-store
Section titled “CR-vue-state-store”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.
CR-vue-toolchain
Section titled “CR-vue-toolchain”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-vueand Prettier for formatting are the template’s usual choice; what the project actually has installed and configured governs (seeR-code-tools).