# Coding Standards

## Purpose

Ensure consistent terminology and naming across code and docs.

## Scope

**In**: Terminology rules for UI, code, docs, and commit messages.
**Out**: Formatting or lint rules (handled by tooling).

## Do

- Use the exact terms below in code, docs, and issues.

## Do Not

- Substitute synonyms for defined terms.

## Terminology

Define project-specific terminology here to ensure consistency across codebase:

| Correct | Avoid |
|---|---|
| [Term 1] | [Synonym 1], [Synonym 2] |
| [Term 2] | [Synonym 1], [Synonym 2] |
| [Term 3] | [Synonym 1], [Synonym 2] |

### Examples of Terminology to Define

- **User Types**: End user, admin, moderator, customer, etc.
- **Core Entities**: Product, order, transaction, item, etc.
- **Actions**: Create, add, register, signup, etc.
- **UI Elements**: Modal, dialog, popup, drawer, etc.
- **Status Values**: Active, enabled, live, published, etc.

## Code Conventions

### Naming Conventions

- **Files**: [Your convention - e.g., kebab-case, camelCase, PascalCase]
- **Functions**: [Your convention - e.g., camelCase, snake_case]
- **Components**: [Your convention - e.g., PascalCase]
- **Constants**: [Your convention - e.g., SCREAMING_SNAKE_CASE]
- **Variables**: [Your convention - e.g., camelCase, snake_case]

### Project-Specific Patterns

Document any project-specific coding patterns here:

#### Example: File Organization

```
src/
  features/
    [feature-name]/
      components/
      hooks/
      utils/
      types.ts
      index.ts
```

#### Example: Import Order

1. External dependencies
2. Internal utilities
3. Components
4. Types
5. Styles

#### Example: Error Handling

```typescript
// Preferred pattern
try {
  // operation
} catch (error) {
  // handle error
}

// Avoid pattern
if (error) {
  // handle error
}
```

## Reference-Aliasing Mutation Patterns

> **SSOT.** This section is the canonical policy for reference-aliasing mutation
> hazards. It is cited as the source of truth by `coder.md`
> (§ Reference-Aliasing Mutation Hazards), `code-reviewer.md` (review checklist),
> and `.claude/skills/new/references/{completeness,codex-gate}.md` (Phase 2.5 step 5c
> deterministic detector + Phase 3.7 gate). When those files cite "§ Reference-Aliasing Mutation
> Patterns", they mean this section.

### The hazard

A call site pairs a helper invocation with in-place mutation of an input
array/object, where the helper *may return the input reference unchanged*
(early-return, fallback, or no-op guard path). When the returned value and the
input are the same reference, an in-place reset of the input also empties the
"result", and the subsequent re-populate pushes nothing:

```ts
const result = filterHelper(input, ...);
input.length = 0;        // ← wipes BOTH input AND result when result === input
input.push(...result);   // ← pushes zero elements (result was just emptied)
```

The TypeScript signature does **not** encode reference identity — a function
typed `(xs: T[]) => T[]` may still return its argument unchanged. Unit tests on
the helper in isolation pass; the defect only manifests end-to-end at the call
site. This is the class of bug that motivated this policy (a filter helper that
returned its input reference on most paths, paired with an unguarded
`length = 0; push(...result)` reset, collapsing a list to empty in production).

### The 3-question detector

Before writing — or while reviewing — any call site that mutates an input array
in place after a helper call, answer:

1. **Does the helper return an array or object?** If yes, continue.
2. **Could the helper return the input reference unchanged** on any path?
   Read every `return` statement in the helper body. If yes, continue.
3. **Does the call site mutate the input in place** via `arr.length = 0`,
   `arr.splice(0)`, `Object.assign(input, result)`, or similar? If yes — and
   (1)+(2) were also yes — you have an alias-mutation hazard.

### Required remediation (apply exactly one)

- **Identity guard** at the call site:
  ```ts
  const result = filterHelper(input, ...);
  if (result !== input) {
    input.length = 0;
    input.push(...result);
  }
  ```
- **Defensive clone** before the call: `filterHelper([...input], ...)` (or
  `input.slice()`).
- **Refactor the helper** to always return a new array on every path
  (preferred when the helper is exported and consumed by 2+ callers). Document
  the immutability contract in the helper's JSDoc, e.g.
  `@returns a NEW array — never the input reference`, so reviewers can trust it
  without re-reading every branch.

### Test contract

When a guard or clone is applied, ALSO write a regression test on the **caller
pattern** — not only on the helper in isolation. The test MUST include:

- An assertion on the post-call state of the input (e.g. its length/contents
  after the helper invocation), and
- A **negative-control case** that documents the failure mode that would recur
  if the guard/clone were removed.

Place caller-pattern reference tests under your project's test root (the same
path the card's `paths.*` test convention uses); cite that reference test from
the helper's JSDoc so future editors find the contract.

### Enforcement layers

- **This section** — full policy + JSDoc contract + remediation menu.
- `coder.md § Reference-Aliasing Mutation Hazards` — pre-implementation check.
- `code-reviewer.md` review checklist — flags un-guarded patterns at review time.
- `.claude/skills/new/references/completeness.md § Phase 2.5 step 5c` — deterministic
  detector that flags un-guarded patterns as `[ALIAS-MUTATION] BLOCKER` in
  `## Issues & Flags`.
- `.claude/skills/new/references/codex-gate.md § Phase 3.7` — a mutation-after-helper
  call invokes a per-card adversarial cross-model review before commit.

## Commit Message Format

- **Format**: `[TYPE-XXX] Brief description` or adapt to your project convention
- **Types**: feat, fix, docs, refactor, test, chore
- **Examples**:
  - `[FEAT-123] Add user authentication`
  - `[FIX-456] Resolve login redirect issue`
  - `[DOCS-789] Update API documentation`

## Documentation Standards

### Code Comments

- Comment **why**, not **what**
- Use JSDoc/docstrings for public APIs
- Avoid obvious comments
- Update comments when code changes

### README Requirements

- Installation instructions
- Configuration steps
- Usage examples
- Contributing guidelines
- License information

## Type Safety (if applicable)

- [Your type safety requirements]
- [Strictness level]
- [Type annotation requirements]
- [Any/unknown usage policy]

## Testing Standards

- [Test coverage requirements]
- [Test naming conventions]
- [Test file organization]
- [Mocking guidelines]

## Accessibility Standards (if applicable)

- [ARIA label requirements]
- [Keyboard navigation requirements]
- [Screen reader compatibility]
- [Color contrast requirements]

## Performance Standards (if applicable)

- [Bundle size limits]
- [Image optimization requirements]
- [Lazy loading guidelines]
- [Caching strategies]

## Security Standards

- [Input validation requirements]
- [Authentication patterns]
- [Data sanitization rules]
- [Secrets management]
