Conventions
This guide defines coding conventions and patterns for clarity, consistency, and maintainability.
See also: Modern JS & Rust primitives — current-edition language primitives (ES2024–2026 / Rust 2024) to prefer on hot, RT-audio, and interop paths.
TypeScript soundness
- Use real types. Do not escape through
any, unsafe casts, or broad index signatures. - Narrow unknown values at their boundary.
- Do not suppress actual errors with
@ts-ignore,@ts-expect-error, or disabled lint rules. An interface that is a declaration-merging target (module augmentation) may carry a line-scoped disable for the rules that refuse merge targets, with the reason beside it (ADR 0058). An intentional duration measurement or failure-observation path that a quality rule cannot prove may carry a line-scoped disable naming the rule, with a specific reason and a test or other evidence that would expose the failure (lint quality checks). - Fix fixtures and tests to match production contracts. Never weaken the contract to make a check pass.
Prefer explicit control flow
All control flow must be explicit. Use guard clauses for early returns and always use block statements ({...}) for conditionals. Avoid clever shortcuts like short-circuit invocations (&&) or collapsed if statements. This practice improves readability and reduces the chance of logical errors.
- Related Lint Rule:
curly
// ✅ Good: Guard clauses and block conditionals
export const renderTrack = (track: Track): void => {
if (!track) {
throw new Error('Missing track');
}
if (track.isMuted) {
return;
}
if (track.isBypassed) {
return;
}
renderTrackAudio(track.id);
};
// ❌ Bad: Short-circuit invocation and collapsed ifs
export const renderTrack = (track: Track): void => {
if (!track) throw new Error('Missing track');
track && !track.isMuted && !track.isBypassed && renderTrackAudio(track.id);
};
Avoid clever JavaScriptisms
// ❌ Bad: Chained ternaries obscure intent
const roleLabel = !user ? '—' : user.isAdmin ? 'Admin' : user.isEditor ? 'Editor' : 'User';
// ✅ Good: Clear branches with early returns/blocks
let roleLabel = '—';
if (user) {
if (user.isAdmin) {
roleLabel = 'Admin';
} else if (user.isEditor) {
roleLabel = 'Editor';
} else {
roleLabel = 'User';
}
}
Object spread copies a record while adding keys. Call-site rest (fn(...args)) is the other legal spread. Do not clone with { ...x }, do not clone-then-map ([...notes].map), and do not spread a condition (...(enabled && { extra })).
// ✅ Good: update one field on a copy
const next = { ...clip, loop: true };
// ✅ Good: pass through rest arguments
fn(...args);
// ❌ Bad: clone with no added keys
const clone = { ...clip };
// ❌ Bad: conditional empty spread
const props = { ...base, ...(open && { role: 'dialog' }) };
// ❌ Bad: clone then map — `.map` already returns a new array
const transposed = [...notes].map(transpose);
Keep logic framework-agnostic
// ✅ Good: Pure function + thin view wrapper
export const computeStereoPan = ({ panLeft, panRight }: PanAmount): number => {
return Math.max(-1, Math.min(1, panRight - panLeft));
};
export const PanKnob = ({ panLeft, panRight }: PanAmount): ReactElement => {
const value = computeStereoPan({ panLeft, panRight });
return <span>Pan: {value}</span>;
};
// ❌ Bad: Embedding domain logic in the component
export const PanKnob = ({ panLeft, panRight }: PanAmount): ReactElement => {
const value = Math.max(-1, Math.min(1, panRight - panLeft));
return <span>Pan: {value}</span>;
};
React anti-patterns
- No
useEffectfor data fetching: This is a critical pattern. Data fetching must be handled by TanStack Query (wired viasrc/app/queryClient.ts). - No
useEffectfor derived state: Compute derived state directly during rendering. - No manual memoization: The React Compiler handles memoization automatically at build time. Do not use
useMemo,useCallback, orReact.memomanually -- the compiler inserts optimal memoization for you. Existing manual calls are harmless (the compiler skips already-memoized code) but should be removed when touching a file. - No
forwardRef: In React 19,refis a regular prop. Destructure it directly instead of wrapping withforwardRef. - Prefer
use()overuseContext: Theuse()hook replacesuseContextfor reading context. It can be called conditionally and also reads Promises for Suspense-based patterns. - No manual form state: The documented target is a React Hook Form + Zod stack (forms); forms without it use local component state (
useState).
// ❌ Bad: Manual memoization (the React Compiler handles this automatically)
export const Parent = () => {
const onClose = useCallback(() => modal.close(), []);
const config = useMemo(() => ({ theme: 'dark' }), []);
return <Dialog onClose={onClose} config={config} />;
};
// ✅ Good: Write plain code; the compiler memoizes what's needed
export const Parent = () => {
const onClose = () => modal.close();
const config = { theme: 'dark' };
return <Dialog onClose={onClose} config={config} />;
};
// ❌ Bad: useEffect for derived state from props
export const Badge = ({ count }: { count: number }) => {
const [isMany, setIsMany] = useState(false);
useEffect(() => {
setIsMany(count > 99);
}, [count]);
return <span>{isMany ? '99+' : String(count)}</span>;
};
// ✅ Good: derive during render
export const Badge = ({ count }: { count: number }) => {
const label = count > 99 ? '99+' : String(count);
return <span>{label}</span>;
};
// ❌ Bad: useEffect for data fetching
export const ProjectDetails = ({ id }: { id: string }) => {
const [data, setData] = useState<Project | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
let isMounted = true;
setIsLoading(true);
fetch(`/api/projects/${id}`)
.then((r) => r.json())
.then((json: Project) => {
if (isMounted) {
setData(json);
setIsLoading(false);
}
});
return () => {
isMounted = false;
};
}, [id]);
if (isLoading) {
return <Spinner />;
}
return <div>{data?.name}</div>;
};
// ✅ Good: TanStack Query for data fetching (non-suspense)
// Project/presentations/hooks/useProjectDetails.ts
import { useQuery } from '@tanstack/react-query';
export const useProjectDetails = (id: string) => {
const { data: project, isLoading } = useQuery({
queryKey: ['project', id],
queryFn: () => api.projects.getById(id),
});
return { project, isLoading };
};
useProjectDetails.getKey = (id: string) => ['project', id];
export const ProjectDetails = ({ id }: { id: string }) => {
const { project, isLoading } = useProjectDetails(id);
if (isLoading) {
return <Spinner />;
}
return <div>{project?.name}</div>;
};
// ✅ Good: Suspense-enabled TanStack Query
// Project/presentations/hooks/useProjectDetailsSuspense.ts
import { useSuspenseQuery } from '@tanstack/react-query';
export const useProjectDetailsSuspense = (id: string) => {
const { data: project } = useSuspenseQuery({
queryKey: ['project', id],
queryFn: () => api.projects.getById(id),
});
return { project };
};
useProjectDetailsSuspense.getKey = (id: string) => ['project', id];
export const ProjectDetailsSuspense = ({ id }: { id: string }) => {
const { project } = useProjectDetailsSuspense(id);
return <div>{project.name}</div>;
};
// ❌ Bad: Managing forms with custom state
export const EmailForm = () => {
const [email, setEmail] = useState('');
const [error, setError] = useState<string | null>(null);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!/^[^@]+@[^@]+\.[^@]+$/.test(email)) {
setError('Invalid email');
return;
}
submit({ email });
};
return (
<form onSubmit={handleSubmit}>
<input value={email} onChange={(e) => setEmail(e.target.value)} />
{error ? <span>{error}</span> : null}
<button type="submit">Save</button>
</form>
);
};
Naming conventions
File names
✅ Good
components/TrackCard.tsx # PascalCase for components
views/TrackListView.tsx # PascalCase for views
helpers/formatTime.ts # camelCase for utilities
models/Track.ts # PascalCase for models
useCases/addTrack.ts # camelCase for use cases
❌ Bad
components/track-card.tsx # kebab-case
components/trackcard.tsx # lowercase
helpers/format_time.ts # snake_case
Variable and function names
// ✅ Good: Descriptive, verbose names
const currentUserPermissions = getUserPermissions();
const isTrackMuted = track.status === 'muted';
const calculateFadeOutDuration = (baseDuration: number) => baseDuration * 1.2;
// ❌ Bad: Abbreviated, unclear names
const usrPerms = getUserPermissions();
const isMut = track.status === 'muted';
const calcFade = (d: number) => d * 1.2;
Constants
- Name constants in
SCREAMING_SNAKE_CASE, exported or private. When a value encodes a contract or a tuning decision, carry a short doc comment stating the rationale — the reason a bound exists is what stops the next reader from "fixing" it. - Express fixed collections as
as constarrays or frozen objects. Compute a derived constant from the constants it derives from; never restate the arithmetic at a second site. - Keep module-private constants at the top of the owning file. Add a dedicated constants file only when several files of one feature must agree on the values — not for a value one file uses. That dedicated file is a domain-named vocabulary file in the owning layer, never a module-root
constants.ts: domain and wire vocabulary (protocol discriminants, param-id tables, format constants) lives inmodels/, service behaviour inservices/, and view-only values inpresentations/— because workers, engine, and use cases may importmodels/but nothing below them may importpresentations/. - Cross-module constants live in a
src/utilslaw file named for the rule it encodes (for exampleaudioLevelLaw.ts,midiNoteBatchLimits.ts); UI-shared constants live insrc/components; IPC channel names are declared only inelectron/channels.ts. - Worklets stay isolated: a constant a worklet needs is restated in the worklet file with a pointer comment naming the app-side owner, and a parity spec pins the two equal. TS↔Rust wire values have no shared mechanism — each side owns one constant, each carries a lockstep comment cross-referencing the other side, and a parity spec covers the pair where feasible.
- Never re-hardcode a literal an exported constant already owns — import the constant. If two files must agree on a value, they share one constant; a second copy is a defect even while the copies still agree.
Component and class names
- Components and classes must be
PascalCase.
// ✅ Good: PascalCase for components and classes
export const TrackCard = (): ReactElement => {
/* */
};
export class TrackRepository {
/* */
}
export class ProjectNotFoundError extends Error {
/* */
}
// ❌ Bad: camelCase or other patterns
export const trackCard = (): ReactElement => {
/* */
};
export class trackRepository {
/* */
}
React patterns
Component typing
// ✅ Good: Type the return value
import { type ReactElement } from 'react';
export const TrackCard = ({ name, color }: TrackCardProps): ReactElement => {
return <div style={{ backgroundColor: color }}>{name}</div>;
};
// ❌ Bad: Type the component itself
import { type FC } from 'react';
export const TrackCard: FC<TrackCardProps> = ({ name, color }) => {
return <div style={{ backgroundColor: color }}>{name}</div>;
};
Ref handling (React 19)
In React 19, ref is a regular prop. Do not use forwardRef.
// ✅ Good: ref as a regular prop (React 19)
type InputProps = {
label: string;
ref?: React.Ref<HTMLInputElement>;
};
export const Input = ({ label, ref }: InputProps): ReactElement => {
return <input ref={ref} aria-label={label} />;
};
// ❌ Bad: forwardRef wrapper (deprecated in React 19)
export const Input = forwardRef<HTMLInputElement, { label: string }>(({ label }, ref) => {
return <input ref={ref} aria-label={label} />;
});
Import patterns
// ✅ Good: Import specific types / methods
import { type ReactElement, type MouseEvent, useState, use } from 'react';
// ❌ Bad: Import React and use dot notation
import React from 'react';
export const TrackCard = (): React.ReactElement => {
const [volume, setVolume] = React.useState(0);
return <div>{volume}</div>;
};
Type-only imports and import order
- Use type-only imports (
import { type MyType }) for all type imports. This is enforced by the linter.- Related Lint Rule:
@typescript-eslint/consistent-type-imports
- Related Lint Rule:
- Organize imports in the following order, with newlines between groups and alphabetical sorting within groups:
- Built-in (e.g.,
node:fs,node:path, ...) - External (e.g.,
react,@tanstack/react-query) - Internal (
#/modules/...or#/helpers/...) - Parent (
../) - Sibling (
./) - Index
- Object
- Related Lint Rule:
import/order
- Built-in (e.g.,
// ✅ Good — cross-module: target a contract-folder barrel
import { useState, type ReactElement } from 'react';
import { useSuspenseQuery } from '@tanstack/react-query';
import { getTrack } from '#/modules/Arrangement/useCases';
// ✅ Good — same module: direct useCases path is fine
// import { getTrack } from './useCases/getTrack';
// ❌ Bad: Mixed order and missing type-only imports
import { ReactElement } from 'react';
import { getTrack } from '../../../../../modules/Arrangement/useCases/getTrack';
import { useSuspenseQuery } from '@tanstack/react-query';
Export patterns
// ✅ Good: Named exports
export const TrackCard = (): ReactElement => {
/* */
};
export const useTrack = (id: string) => {
/* */
};
export const formatTime = (seconds: number) => {
/* */
};
// ❌ Bad: Default exports
const TrackCard = (): ReactElement => {
/* */
};
export default TrackCard;
// ⚠️ Re-exports: Cross-module imports target a contract-folder barrel
// (useCases/stores/events/presentations/views), not a root `index.ts` — there is none.
// Within the same module, prefer direct (relative) file paths — do not add extra `index.ts` barrels.
Import paths
- Use absolute imports with the
#/alias for cross-module paths. - Cross-module module imports must target a contract barrel only:
#/modules/<M>/useCases|stores|events|presentations/views— never a deep file under that folder, and never a module-root#/modules/<M>. - Prefer
#/utils/...or#/infra/...for shared non-module code (not emptied#/helpers/...unless a real helper lives there).
Control flow patterns
If statements
- Always use block statements (
{...}) for all conditionals, even single-line ones.- Related Lint Rule:
curly
- Related Lint Rule:
// ✅ Good: Block statements always
export const validateTrackSettings = (track: Track): void => {
if (!track.name) {
throw new Error('Track name is required');
}
if (track.volume > 1) {
throw new Error('Track volume cannot exceed 1.0');
}
};
// ❌ Bad: Collapsed if statements
export const validateTrackSettings = (track: Track): void => {
if (!track.name) throw new Error('Track name is required');
if (track.volume > 1) throw new Error('Track volume cannot exceed 1.0');
};
Early returns over complex ternaries
Use a ternary for a choice between values or JSX. Give a branch its own control flow when it assigns or updates a value, or contains three or more call or constructor expressions outside nested function bodies. The quality check detects those shapes on one line as well as across line breaks.
// ✅ Good: Early return pattern
export const TrackCard = ({ track }: TrackCardProps): ReactElement => {
if (!track) {
return <div>Loading...</div>;
}
if (track.isDeleted) {
return <div>Track no longer available</div>;
}
if (!track.isLoaded) {
return <div>Track is not loaded</div>;
}
return (
<div>
<h3>{track.name}</h3>
<p>Volume: {track.volume}</p>
</div>
);
};
// ❌ Bad: Complex nested ternaries
export const TrackCard = ({ track }: TrackCardProps): ReactElement => {
return (
<div>
{!track ? (
<div>Loading...</div>
) : track.isDeleted ? (
<div>Track no longer available</div>
) : !track.isLoaded ? (
<div>Track is not loaded</div>
) : (
<div>
<h3>{track.name}</h3>
<p>Volume: {track.volume}</p>
</div>
)}
</div>
);
};
JSX conditional rendering
- Use early returns, full ternary operators (
condition ? <A /> : <B />), or logical nullish operators for conditional rendering. - Prefer not to use the logical AND operator (
&&) for conditional rendering, as it can lead to unexpected output (like rendering0or an empty string). Leaky non-boolean&&is error lint; boolean&&is allowed, but ternaries are the house style.- Related Lint Rule:
@eslint-react/no-leaked-conditional-rendering
- Related Lint Rule:
// ✅ Good: Early returns and full ternaries
export const TrackActions = ({ track, canEdit }: TrackActionsProps): ReactElement => {
if (!canEdit) {
return <div>View only</div>;
}
return (
<div>
<button>Edit</button>
{track.isMuted ? <button>Unmute</button> : <button>Mute</button>}
{track.hasPlugins ? <span>Has plugins</span> : null}
{track.clips.length > 0 ? <TrackClips clips={track.clips} /> : undefined}
</div>
);
};
// ❌ Bad: Logical AND operators for conditional rendering
export const TrackActions = ({ track, canEdit }: TrackActionsProps): ReactElement => {
return (
<div>
{canEdit && <button>Edit</button>}
{track.hasPlugins && <span>Has plugins</span>}
{track.clips.length > 0 && <TrackClips clips={track.clips} />}
</div>
);
};
// ❌ Bad: Complex inline ternaries
export const TrackActions = ({ track, canEdit }: TrackActionsProps): ReactElement => {
return (
<div>
{canEdit ? (
<div>
<button>Edit</button>
{track.isMuted ? (
<button>Unmute</button>
) : (
<button>Mute</button>
)}
</div>
) : (
<div>View only</div>
)}
</div>
);
};
Event handler patterns
// ✅ Good: Explicit conditional call
export const handleClick = (onClick?: () => void): void => {
if (onClick) {
onClick();
}
};
// ❌ Bad: Short-circuit invocation
export const handleClick = (onClick?: () => void): void => {
onClick && onClick();
};
Performance patterns
The React Compiler handles memoization
The React Compiler (v1.0, stable since October 2025) automatically memoizes components, values, and callbacks at build time. You no longer need to think about useMemo, useCallback, or React.memo -- just write plain code and the compiler optimizes it.
// ✅ Good: Plain code; the compiler memoizes automatically
export const PluginCard = ({ plugin, inputGain }: PluginCardProps): ReactElement => {
const [isExpanded, setIsExpanded] = useState(false);
const effectiveGain = plugin.baseGain * inputGain;
const formattedGain = `${effectiveGain.toFixed(2)} dB`;
const isClipping = effectiveGain > 0;
return (
<div>
<h3>{plugin.name}</h3>
<p>{formattedGain}</p>
{isClipping ? <span>Clipping!</span> : undefined}
<button onClick={() => setIsExpanded(!isExpanded)}>
{isExpanded ? 'Collapse' : 'Expand'}
</button>
</div>
);
};
// ❌ Bad: Manual memoization is unnecessary with the React Compiler
export const PluginCard = ({ plugin, inputGain }: PluginCardProps): ReactElement => {
const [isExpanded, setIsExpanded] = useState(false);
const effectiveGain = useMemo(() =>
plugin.baseGain * inputGain, [plugin.baseGain, inputGain]
);
const toggleExpanded = useCallback(() => {
setIsExpanded(!isExpanded);
}, [isExpanded]);
return (
<div>
<h3>{plugin.name}</h3>
<p>{`${effectiveGain.toFixed(2)} dB`}</p>
<button onClick={toggleExpanded}>
{isExpanded ? 'Collapse' : 'Expand'}
</button>
</div>
);
};
Props identity
With the React Compiler, inline objects and arrays in JSX are automatically memoized when beneficial. Write naturally and let the compiler handle referential stability.
// ✅ Good: The compiler handles identity automatically
<Chart config={{ data, options: { responsive: true } }} />;
// ✅ Also good: Extracting to a variable for readability is fine
const config = { data, options: { responsive: true } };
<Chart config={config} markers={DEFAULT_MARKERS} />;
Language anti-patterns
// ❌ Bad: Truthy hacks and coercions
const name = user.name || 'Anonymous'; // Falls back on empty string
const count = +input; // Implicit number coercion
const enabled = !!maybeTruthy; // Double negation
// ✅ Good: Explicit semantics
const name = user.name ?? 'Anonymous'; // Nullish coalescing
const count = Number(input);
const enabled = Boolean(maybeTruthy);
// ❌ Bad: Defaulting via || in params
function greet(name) {
name = name || 'world';
}
// ✅ Good: Default parameters
function greet(name = 'world') {}
// ❌ Bad: Short-circuit invocation and nested ternaries
onClick && onClick();
const label = a ? (b ? 'x' : c ? 'y' : 'z') : 'w';
// ✅ Good: Block conditionals and early returns
if (onClick) {
onClick();
}
let label = 'w';
if (a) {
label = b ? 'x' : c ? 'y' : 'z';
}
Function patterns
Function declarations
// ✅ Good: Clear, descriptive function names
export const calculateTrackFadeDuration = ({ baseDuration, fadeMultiplier }): number => {
return baseDuration * fadeMultiplier;
};
export const validateTrackCreationInput = (input: CreateTrackInput): void => {
if (!input.name || input.name.length < 3) {
throw new Error('Track name must be at least 3 characters');
}
if (input.volume < 0) {
throw new Error('Track volume cannot be negative');
}
};
// ❌ Bad: Abbreviated, unclear names
export const calcDuration = (d: number, m: number): number => {
return d * m;
};
export const validate = (input: any): void => {
if (!input.n || input.n.length < 3) throw new Error('Name too short');
if (input.v < 0) throw new Error('Bad volume');
};
Conventional programming patterns
- Prefer conventional, framework-agnostic patterns over JavaScriptisms.
- Use explicit blocks over clever one-liners; avoid short-circuit calls and terse conditionals.
- Keep logic in pure functions and use cases; React remains a thin view.
// Strategy pattern (choose implementation at runtime)
type SortStrategy = (tracks: Track[]) => Track[];
const sortByName: SortStrategy = (tracks) => [...tracks].sort((a, b) => a.name.localeCompare(b.name));
const sortByDate: SortStrategy = (tracks) => [...tracks].sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
export const getSortedTracks = (tracks: Track[], strategy: 'name' | 'date'): Track[] => {
if (strategy === 'name') {
return sortByName(tracks);
}
return sortByDate(tracks);
};
// Module store singleton (preferred)
import { createStore } from '#/infra/store/createStore';
export const appStore = createStore<AppState>({ initialData: {/* ... */} });
// Adapter pattern (transformer layer maps DTO → domain)
type ApiUser = { user_id: number; full_name: string };
type User = { id: number; name: string };
export const mapUserFromApiToModel = (api: ApiUser): User => ({ id: api.user_id, name: api.full_name });
// Observer pattern (domain events — string keys, unwrapped payload)
eventBus.on('track.removed', (payload) => {
auditUseCase.recordTrackRemoved(payload);
});
Guidelines:
- Avoid ternaries in complex logic; prefer early returns or helper variables/functions.
- Never use short-circuit invocation
(fn && fn()). - Keep patterns framework-agnostic; React is only for rendering and wiring.
Code craft
The conventions in this file follow one doctrine: write the simplest code that expresses the intent. Clever code is a defect even when it works — if the reader has to decode a construct, rewrite it with the plainer one.
- Functional by default. Pure functions, immutable data, and composition over classes and mutation. Mutable state belongs in stores at the documented boundaries, not scattered across object graphs.
- Semantic decomposition. Small functions, each named for the one thing it does. A block that needs a comment to be understood gets extracted and named instead.
- Happy path top to bottom. Guard clauses and early returns over nesting, as covered under Prefer explicit control flow above.
// ❌ Bad: a comment propping up an anonymous block
export const renderMixdown = async (project: Project): Promise<void> => {
// Render each track, sum the buffers, then write the mixdown file.
const buffers = await Promise.all(project.tracks.map(renderTrack));
await writeMixdownFile(sumBuffers(buffers));
};
// ✅ Good: extracted and named; the code says what the comment said
export const renderMixdown = async (project: Project): Promise<void> => {
const mixdown = await mixProjectTracks(project.tracks);
await writeMixdownFile(mixdown);
};
Comments
A comment explains what the code cannot make self-explanatory: the why, or non-obvious mechanics such as real-time constraints, hardware quirks, or a spec mandate. A comment narrating what simple code does is a smell — rename or extract until it is unnecessary, then delete it. No commented-out code and no changelog comments: git is the history.
Folder-level knowledge
A significant module or large folder carries an AGENTS.md with the critical knowledge a future
agent needs to work there safely. A change that alters what such a file describes updates that
file in the same change.
Lint-aligned conventions
- Equality and basics: Use
===/!==(no loose equality); preferconst; prefer template strings; noeval; nodebugger. - Curly braces: Required for all conditionals and loops. (
curly) - TypeScript: Use
import { type MyType }. Narrow optional values before use. Keep a type parameter when it relates input, output, or other types in the API. Use the underlying constraint orunknownfor a parameter whose type has no relationship to preserve. (consistent-type-imports,no-non-null-assertion,no-unnecessary-type-parameters) - Promises: Always handle promises (
return/catch/await). Avoid floating promises. - React: No class components; no default React import; JSX uses double quotes; no
forwardRef(userefas a prop); no manualuseMemo/useCallback/React.memo(the React Compiler handles memoization). - DOM: Prefer
textContentoverinnerText. (unicorn/prefer-dom-node-text-content) - Imports: Enforce group order and alphabetical sort. (
import/order) - Storage: Do not use
localStoragedirectly; persist viaStorewithLocalStorageStorage. This is enforced by a custom lint rule. (no-restricted-syntax) - File size: A file holds at most 600 non-blank, non-comment lines, so a reviewer can hold the whole file in their head; past that, split it by responsibility. (
max-lines) - Function size: In ordinary product TypeScript under
src/, use at most 80 non-blank, non-comment lines per function, including IIFEs. The historical check elsewhere keeps its ceiling of 100. Decompose longer functions by responsibility, per Semantic decomposition above. (max-lines-per-function) - Nesting depth: Control-flow blocks nest at most 4 deep; deeper nesting buries the happy path and calls for the guard clauses and early returns covered under Prefer explicit control flow. (
max-depth) - Cyclomatic complexity: In ordinary product TypeScript under
src/, keep a function at 12 or below. The historical check elsewhere keeps its ceiling of 20. Split complex branching by responsibility. (complexity) - Burn-down baseline: Files that already exceed one of the four limits above are listed in
eslint.size-baseline.mjs, which holds those files towarninstead oferrorso they keep reporting without failing the build. A file leaves the list only once it complies with all four rules; no file is ever added, andscripts/checkSizeBaselineShrinks.ts(run in CI) refuses any path absent from the merge base's list. - Baseline line ceilings: Because
warnalone would let a baselined file grow without bound, each baselined file may not exceed its recorded line ceiling inscripts/lintSizeCeilings.json, where a file's line count is its number of newline characters. A file over 600 lines is recorded at its line count plus 50, a fixed headroom granted once; a file within 600 lines is recorded at 600, so the ratchet never lets a short file newly exceedmax-lines. A ceiling more than 100 lines above the ceiling the file's current length earns is stale and must be lowered to that value. Ceilings are never raised:scripts/checkSizeBaselineShrinks.tsrefuses any new or raised figure inscripts/lintSizeCeilings.jsonagainst the merge base. An over-ceiling file is fixed by moving code into a new file, which the size rules hold. Generated files named in the exemption list inscripts/lintSizeCeilings.tscarry no ceiling, because their size follows their generator's input.scripts/__tests__/lintSizeBaseline.spec.tsenforces that no file exceeds its ceiling, that no ceiling is stale, that the ceilings file lists each non-exempt baseline path exactly once in sorted order, and that each exemption names an existing generator stated in the exempt file's header. - oxlint burn-down baselines: Some oxlint rules run at
errorwhile files that already violated them at promotion are exempt. Each such rule has one override at the end of.oxlintrc.jsonthat turns itofffor an exact, sorted list of file paths, so every other file, new ones included, is held to the rule. A path leaves once its file complies, and none is ever added;scripts/__tests__/oxlintWarnLevels.spec.tsfails when a listed path is a glob, unsorted, or no longer exists. - Suppressed violations: Every other ESLint rule is configured at
error. Violations that predate a rule's promotion are recorded per file and rule ineslint-suppressions.json, ESLint's native bulk-suppressions file, which the lint gate reads. A file that gains one violation beyond its recorded count fails, as does any violation in a file the record does not name. The record only shrinks: after fixing a suppressed violation, run ESLint on the file with--prune-suppressions(the gate fails until the count matches), and never regenerate it with--suppress-allor--suppress-ruleto admit a new violation. Because two pull requests can each be green alone yet leave a file's recorded figure wrong once both land,pnpm deliverrefuses a pull request whenmainhas, since it branched, touched a file the pull request also touched and any lint ledger (this record, a burn-down baseline, or a size ceiling) names, where touching means editing the file or changing what a ledger records for it; merge currentmaininto the lane and publish so a freshGatemeasures the combination. - Dependency-boundary baselines:
.dependency-cruiser-known-violations.jsonand its-contract-reexports,-worker-spawns,-reachability,-typesand-testssiblings hold rows whosefromnames a file, whichscripts/check-dependency-boundaries.mjscompares exactly. Delivery treats them like the other lint ledgers: it refuses a pull request whenmainand the pull request both changed a file that a row names, or changed that file's rows, since their merge base. - Quality counts:
oxlint-quality-baseline.jsoncounts existing findings by file and rule. A new quality rule may record measured findings from unchanged files tracked at the merge base. After activation, reduce or remove a count when the finding goes away. In modified TypeScript files with a recorded complexity finding, an over-cap named top-level function declaration or directconstfunction binding cannot increase its native Oxlint score when its path, name, and declaration kind match the merge base. The lint guide lists the pilot scope and fix limits.
Review checks
- Compare each edited legacy function already beyond a decision or depth cap with the same function in the merge base. Inspect the source branches and nesting, and record the before-and-after complexity and depth when either exceeded the cap of 12 or 4. Complexity 16 to 17 grows the same function even though the file still has one finding. Depth 5 to 4 removes its depth finding and calls for pruning that count. Keep new functions within both caps.
- Tie each added compatibility path to a supported caller, existing data format, or supported execution environment. Name the saved input or caller and show where normal execution reaches the branch. Exercise that input and the current path. When support ends, remove the branch with its obsolete contract.
- For a mutation that can fail and be retried, identify the commit boundary and what the caller can observe on either side. Verify that a pre-commit failure leaves no visible partial change, or that rollback completes before retry. When a caller can retry after a commit whose result it did not receive, bind the retry to the same operation identity and verify one committed effect and one corresponding receipt or history entry where applicable.
Parameter patterns
Keep product functions to four positional parameters and name multiple boolean flags in an options object. When an external contract requires a flagged signature, give a line-scoped lint reason that names the contract. Verify the caller before changing an existing signature.
// ✅ Good: Descriptive parameter names
export const createMixerNotification = ({ trackName, alertLevel, notificationType }): void => {
// Implementation
};
// ❌ Bad: Single letter or abbreviated parameters
export const createNotif = (t: string, a: string, n: string): void => {
// Implementation
};
// ✅ Good: Single object with descriptive properties
export const updateTrackVisibility = ({ trackId, isVisible, notifyMixer, updateMetrics }): void => {
// Implementation
};
// ❌ Bad: Multiple boolean parameters - unclear what each does
export const updateTrack = (trackId: string, isVisible: boolean, notify: boolean, updateMeta: boolean): void => {
// Implementation
};
// ❌ Bad: Function call is unclear without checking the signature
updateTrack('track-123', true, false, true); // What do these booleans mean?
// ✅ Good: Function call is self-documenting
updateTrackVisibility({
trackId: 'track-123',
isVisible: true,
notifyMixer: false,
updateMetrics: true,
});
Common patterns
// ✅ Good: Following all conventions
import { type ReactElement, useState } from 'react';
type TrackCardProps = {
track: Track;
onTrackSelect: (trackId: string) => void;
};
export const TrackCard = ({ track, onTrackSelect }: TrackCardProps): ReactElement => {
const [isExpanded, setIsExpanded] = useState(false);
if (!track) {
return <div>No track data available</div>;
}
if (track.isDeleted) {
return <div>This track has been removed</div>;
}
const handleTrackClick = () => {
onTrackSelect(track.id);
};
const formattedVolume = `${track.volume.toFixed(2)} dB`;
return (
<div onClick={handleTrackClick}>
<h3>{track.name}</h3>
<p>{formattedVolume}</p>
{isExpanded ? (
<div>{track.kind}</div>
) : undefined}
</div>
);
};