Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

AGENTS.md

874 lines25.7 KB

1# Agent Coding Guidelines for TanStack DB
2​
3This guide provides principles and patterns for AI agents contributing to the TanStack DB codebase. These guidelines are derived from PR review patterns and reflect the quality standards expected in this project.
4​
5## Required reading: live-query materialization
6​
7Before reading, analyzing, or modifying correlated live-query materialization
8code under `packages/db/src/query/live/`, read
9`packages/db/src/query/live/ARCHITECTURE.md` in full. Read it before changing
10the related includes oracle tests as well.
11​
12Treat that document's component boundaries and normative laws as constraints.
13If a change intentionally revises an architectural contract, update the
14architecture document in the same pull request.
15​
16## Required reading: executable subsystem models
17​
18Read `docs/contributing/glossary.md` before naming or renaming a subsystem
19state, action, boundary, or observation. Production code, executable models,
20tests, and design documents must use the same term for the same concept. A
21model may stay structurally independent, but it must declare any abstraction
22that combines, splits, or does not correspond to production concepts.
23​
24Some oracle files are also the shortest documentation for their subsystem.
25Before changing a covered contract or its machinery, use
26`docs/contributing/oracle-coverage.md` to find the primary executable owner and
27read its stated limits. Do not infer authority from a filename alone.
28​
29Read these stable entry points before the narrower owner:
30​
31- For correlated live-query materialization, read the architecture document
32 required above.
33- For Collection mutation admission, subscription ownership, replay,
34 publication, or disposal, read
35 `packages/db/tests/collection-subscription-lifecycle-grammar.ts`.
36- For optimistic snapshots and settlement, read
37 `packages/db/tests/optimistic-history-oracle.ts`.
38- For opaque cursor pagination, read
39 `packages/query-db-collection/tests/cursor-pagination/model.ts`.
40- For TrailBase lifecycle work, read
41 `packages/trailbase-db-collection/tests/ORACLE.md`.
42- For cross-framework behavior, read the shared contract under
43 `packages/db/tests/conformance/` and the receiving framework's driver. One
44 framework's scheduling cut does not prove another's.
45​
46The opening prose states the contract. The small model states the expected
47behavior. The production driver proves that the implementation refines the
48model. If a change revises one of these contracts, update all three in the same
49pull request. Do not update only the assertions to match new production output.
50​
51## Table of Contents
52​
531. [Type Safety](#type-safety)
542. [Code Organization](#code-organization)
553. [Algorithm Efficiency](#algorithm-efficiency)
564. [Semantic Correctness](#semantic-correctness)
575. [Abstraction Design](#abstraction-design)
586. [Code Clarity](#code-clarity)
597. [Testing Requirements](#testing-requirements)
608. [Function Design](#function-design)
619. [Modern JavaScript Patterns](#modern-javascript-patterns)
6210. [Edge Cases and Corner Cases](#edge-cases-and-corner-cases)
6311. [Git and PR Hygiene](#git-and-pr-hygiene)
6412. [Code Weight and Fail-Fast Design](#code-weight-and-fail-fast-design)
65​
66## Type Safety
67​
68### Avoid `any` Types
69​
70**❌ Bad:**
71​
72```typescript
73function processData(data: any) {
74 return data.value
76​
77const result: any = someOperation()
78```
79​
80**✅ Good:**
81​
82```typescript
83function processData(data: unknown) {
84 if (isDataObject(data)) {
85 return data.value
86 }
87 throw new Error('Invalid data')
89​
90const result: TQueryData = someOperation()
91```
92​
93**Key Principles:**
94​
95- Use `unknown` instead of `any` when the type is truly unknown
96- Provide proper type annotations for return values
97- Use type guards to narrow `unknown` types safely
98- If you find yourself using `any`, question whether there's a better type
99​
100## Code Organization
101​
102### Extract Common Logic
103​
104**❌ Bad:**
105​
106```typescript
107// Duplicated logic in multiple places
108function processA() {
109 const key = typeof value === 'number' ? `__number__${value}` : String(value)
110 // ...
112​
113function processB() {
114 const key = typeof value === 'number' ? `__number__${value}` : String(value)
115 // ...
117```
118​
119**✅ Good:**
120​
121```typescript
122function serializeKey(value: string | number): string {
123 return typeof value === 'number' ? `__number__${value}` : String(value)
125​
126function processA() {
127 const key = serializeKey(value)
128 // ...
130​
131function processB() {
132 const key = serializeKey(value)
133 // ...
135```
136​
137### Organize Utilities
138​
139**Key Principles:**
140​
141- Extract serialization/deserialization logic into utility files
142- When you see identical or near-identical code blocks, extract to a helper function
143- Prefer small, focused utility functions over large inline implementations
144- Move reusable logic into utility modules (e.g., `utils/`, `helpers/`)
145​
146### Function Size and Complexity
147​
148**❌ Bad:**
149​
150```typescript
151function syncData() {
152 // 200+ lines of logic handling multiple concerns
153 // - snapshot phase
154 // - buffering
155 // - sync state management
156 // - error handling
157 // all inline...
159```
160​
161**✅ Good:**
162​
163```typescript
164function syncData() {
165 handleSnapshotPhase()
166 manageBuffering()
167 updateSyncState()
168 handleErrors()
170​
171function handleSnapshotPhase() {
172 // Focused logic for snapshot phase
174```
175​
176**Key Principle:** If a function is massive, extract logical sections into separate functions. This improves readability and maintainability.
177​
178## Algorithm Efficiency
179​
180### Be Mindful of Time Complexity
181​
182**❌ Bad: O(n²) Queue Processing:**
183​
184```typescript
185// Processes elements in queue, but elements may need multiple passes
186while (queue.length > 0) {
187 const job = queue.shift()
188 if (hasUnmetDependencies(job)) {
189 queue.push(job) // Re-queue, causing O(n²) behavior
190 } else {
191 processJob(job)
192 }
194```
195​
196**✅ Good: Dependency-Aware Processing:**
197​
198```typescript
199// Use a data structure that respects dependencies
200// Process only jobs with no unmet dependencies
201// Consider topological sort for DAG-like structures
202const readyJobs = jobs.filter((job) => !hasUnmetDependencies(job))
203readyJobs.forEach(processJob)
204```
205​
206### Use Appropriate Data Structures
207​
208**❌ Bad:**
209​
210```typescript
211// O(n) lookup for each check
212const items = ['foo', 'bar', 'baz' /* hundreds more */]
213if (items.includes(searchValue)) {
214 // ...
216```
217​
218**✅ Good:**
219​
220```typescript
221// O(1) lookup
222const items = new Set(['foo', 'bar', 'baz' /* hundreds more */])
223if (items.has(searchValue)) {
224 // ...
226```
227​
228**Key Principles:**
229​
230- For membership checks on large collections, use `Set` instead of `Array.includes()`
231- Be aware of nested loops and their complexity implications
232- Consider the worst-case scenario, especially for operations that could process many items
233- Use appropriate data structures (Set for lookups, Map for key-value, etc.)
234​
235## Semantic Correctness
236​
237### Ensure Logic Matches Intent
238​
239**❌ Bad:**
240​
241```typescript
242// Intending to check if subset limit is more restrictive than superset
243function isLimitSubset(
244 subset: number | undefined,
245 superset: number | undefined,
246) {
247 return subset === undefined || superset === undefined || subset <= superset
249​
250// Problem: If subset has no limit but superset does, returns true (incorrect)
251```
252​
253**✅ Good:**
254​
255```typescript
256function isLimitSubset(
257 subset: number | undefined,
258 superset: number | undefined,
259) {
260 // Subset with no limit cannot be a subset of one with a limit
261 return superset === undefined || (subset !== undefined && subset <= superset)
263```
264​
265### Validate Intersections and Unions
266​
267When merging predicates or combining queries, ensure the semantics are correct:
268​
269**Example Problem:**
270​
271```sql
272-- Query 1: WHERE age >= 18 LIMIT 1
273-- Query 2: WHERE age >= 20 LIMIT 3
274-- Naive intersection: WHERE age >= 20 LIMIT 1
275-- Problem: This may not return the actual intersection of results
276```
277​
278**Key Principle:** Think carefully about what operations like intersection, union, and subset mean for your specific use case. Consider edge cases with limits, ordering, and predicates.
279​
280### Reject Multiple Copies of `@tanstack/db`
281​
282TanStack DB does not support interoperability between multiple copies of
283`@tanstack/db` in one runtime.
284Each copy has its own transaction stack and IR classes. Do not add cross-copy
285expression support or shape-based fallbacks to make the copies interoperate.
286Keep the existing duplicate-instance check, which throws
287`DuplicateDbInstanceError` for duplicate development browser loads. Do not
288replace its error with a warning. SSR and test runners may evaluate the
289package twice without exchanging values; do not reject those independent
290loads or add per-value tracking solely to detect unsupported cross-copy use.
291​
292## Abstraction Design
293​
294### Avoid Leaky Abstractions
295​
296**❌ Bad:**
297​
298```typescript
299class Collection {
300 getViewKey(key: TKey): string {
301 // Caller needs to know internal representation
302 return `${this._state.viewKeyPrefix}${key}`
303 }
305​
306// Usage exposes internals
307const viewKey = collection.getViewKey(key)
308if (viewKey.startsWith(PREFIX)) {
309 /* ... */
311```
312​
313**✅ Good:**
314​
315```typescript
316class Collection {
317 getViewKey(key: TKey): string {
318 // Delegate to state manager, hiding implementation
319 return this._state.getViewKey(key)
320 }
322​
323class CollectionStateManager {
324 getViewKey(key: TKey): string {
325 return `${this.viewKeyPrefix}${key}`
326 }
328```
329​
330**Key Principles:**
331​
332- Encapsulate implementation details within the responsible class
333- Don't expose internal data structures or representations
334- Use delegation to maintain clean boundaries between components
335- Keep internal properties private when possible
336​
337### Proper Encapsulation
338​
339**Key Principle:** If you need to access a property or method from outside a class, add a public method that delegates to the internal implementation rather than exposing the internal property directly.
340​
341## Code Clarity
342​
343### Prefer Positive Predicates
344​
345**❌ Bad:**
346​
347```typescript
348if (!refs.some((ref) => ref.path[0] === outerAlias)) {
349 // treat as safe
351```
352​
353**✅ Good:**
354​
355```typescript
356if (refs.every((ref) => ref.path[0] !== outerAlias)) {
357 // treat as safe
359```
360​
361**Key Principle:** Positive conditions (every, all) are generally easier to understand than negated conditions (not some).
362​
363### Simplify Complex Conditions
364​
365**❌ Bad:**
366​
367```typescript
368const isLoadingNow = this.pendingLoadSubsetPromises.size > 0
369if (isLoadingNow && !isLoadingNow) {
370 // Confusing logic
372```
373​
374**✅ Good:**
375​
376```typescript
377const wasLoading = this.pendingLoadSubsetPromises.size > 0
378this.pendingLoadSubsetPromises.add(promise)
379const isLoadingNow = this.pendingLoadSubsetPromises.size === 1
380​
381if (isLoadingNow) {
382 // Started loading
384```
385​
386### Use Descriptive Names
387​
388**❌ Bad:**
389​
390```typescript
391const viewKeysMap = new Map() // Type in name is redundant
392const dependencyBuilders = [] // Sounds like functions that build
393```
394​
395**✅ Good:**
396​
397```typescript
398const viewKeys = new Map() // Data structure not in name
399const dependentBuilders = [] // Accurately describes dependents
400```
401​
402**Key Principles:**
403​
404- Avoid Hungarian notation (encoding type in variable name)
405- Use names that describe the role or purpose, not the data structure
406- Choose names that make the code read like prose
407- Prefer `dependentBuilders` over `dependencyBuilders` when referring to things that depend on something
408​
409## Testing Requirements
410​
411### Required reading: oracle tests
412​
413Before designing, changing, or reviewing an oracle or generated-history test,
414read [Writing reliable oracle tests](docs/contributing/oracle-tests.md).
415Use the [coverage map](docs/contributing/oracle-coverage.md) to find an existing
416owner and its limits before adding another model. The guide explains testing
417methods; it does not authorize new product behavior or retire existing laws.
418​
419Write every oracle and generated-history test as executable subsystem
420documentation. Follow the guide's section on literate oracle files. Keep the
421contract, model, generated history grammar, production driver, and refinement
422check—including its public observations and checkpoint—visible and close enough
423that a reviewer can compare them directly. A focused regression may remain
424short, but it does not waive this structure for an oracle and cannot replace
425applicable oracle coverage.
426​
427### Always Add Tests for Bugs
428​
429**Key Principle:** Reproduce a bug in a test before fixing it. Prefer extending
430an oracle as described below over adding an isolated unit test. This ensures:
431​
432- The bug is actually fixed
433- The bug doesn't regress in the future
434- The fix is validated
435​
436**Example:**
437​
438```typescript
439// Found a bug with fetchSnapshot resolving after up-to-date message
440// Should add a test:
441test('ignores snapshot that resolves after up-to-date message', async () => {
442 // Reproduce the corner case
443 // Verify it's handled correctly
444})
445```
446​
447### Treat Every Review Bug as a Test Gap
448​
449When a reviewer agent confirms a bug, it must also ask why the existing tests
450did not catch it. The finding should name the missing test law, state
451transition, generator dimension, adapter boundary, or assertion. If a test or
452oracle should already have caught the bug, identify the false-green model,
453classifier, fixture, or assertion that let it pass. Use that analysis to suggest
454the smallest test or oracle improvement that would catch the same class of bug,
455not only the reported example.
456​
457### Close the Declared Bug Class
458​
459A passing reproduction fixes one trace; it does not establish that the bug
460class is closed. Before claiming closure, name the violated product law and
461bound the claim by legal histories, production paths, and public observations
462at specific checkpoints.
463​
464Extend the primary oracle so it reaches the reported trace and nearby legal
465histories that distinguish the repair from plausible wrong designs. Use a
466separate oracle owner when another boundary needs a different model. Show that
467the check fails on the original implementation or a hostile mutant at the
468intended checkpoint, then passes with the fix.
469​
470At closeout, state what the evidence covers. Record remaining in-scope
471histories or paths in the oracle coverage map with an owner and needed witness.
472A reachable in-scope counterexample keeps the class open. Passing random runs
473is not a universal proof.
474​
475### Keep Oracles Independent
476​
477An oracle is useful only when its expected result comes from a source independent
478of the implementation under test. Do not translate production branches, state
479machines, classifiers, or helper functions into a second implementation and call
480that an oracle. Both copies can encode the same wrong assumption.
481​
482- Derive expected behavior from public contracts, documented prior behavior,
483 mathematical laws, or a separately specified reference model.
484- Keep the reference model structurally different from production. Do not import
485 the production helper or reuse its classifications to compute expected results.
486- Preserve existing contract tests unless a product or design decision explicitly
487 changes the contract. Rewriting a passing expectation to match new production
488 behavior is a design review, not routine test maintenance.
489- When production work suggests an oracle change, compare the old and new
490 semantics with counterexamples before editing the oracle.
491- Use hostile mutants to prove the oracle rejects plausible wrong designs,
492 including the mistake production currently makes. A green oracle without a
493 demonstrated kill is weak evidence.
494- Use process grammar to explore lifecycle paths, and design grammar to challenge
495 the oracle's reference semantics. More generated traces cannot repair a wrong
496 reference model.
497​
498### Prefer Oracle Coverage Over Isolated Regressions
499​
500An oracle that checks general laws across generated states and histories is a
501stronger form of coverage than a unit test for one specific example. Prefer
502extending an existing oracle when it can cover the behavior. Add the missing
503model rule, generator dimension, state transition, or observable assertion;
504adding more pinned examples alone does not generalize the oracle.
505​
506Use a focused regression to isolate and shrink a failure, then keep it as a
507replay example for the broader oracle where possible. Verify that the expanded
508oracle fails without the fix and passes with it. Keep valuable unit tests, but
509do not treat them as a substitute for applicable oracle coverage. If an oracle
510is not practical for the behavior, explain why a focused test is sufficient.
511​
512### Name Tests After Behavior
513​
514Test names should state the behavior they prove. Do not put issue or pull
515request numbers in test names; those references become stale and make the test
516suite harder to read. When an external report contains essential context that
517the test cannot express, link it in a nearby comment instead.
518​
519### Test Corner Cases
520​
521Common corner cases to consider:
522​
523- Empty arrays or sets
524- Single-element collections
525- `undefined` vs `null` values
526- Operations on already-resolved promises
527- Race conditions between async operations
528- Limit/offset edge cases (0, 1, very large numbers)
529- IN predicates with 0 or 1 elements
530​
531## Function Design
532​
533### Prefer Explicit Parameters Over Closures
534​
535**❌ Bad:**
536​
537```typescript
538function outer() {
539 const config = getConfig()
540 const state = getState()
541​
542 const updateFn = () => {
543 // Closes over config and state
544 applyUpdate(config, state)
545 }
546​
547 scheduler.schedule(updateFn)
549```
550​
551**✅ Good:**
552​
553```typescript
554function updateEntry(entry: Entry, config: Config, state: State) {
555 applyUpdate(entry, config, state)
557​
558function outer() {
559 const config = getConfig()
560 const state = getState()
561​
562 scheduler.schedule({
563 config,
564 state,
565 update: updateEntry,
566 })
568```
569​
570**Key Principles:**
571​
572- Functions that take dependencies as arguments are easier to test
573- Explicit parameters make data flow clearer
574- Closures can hide dependencies and make code harder to follow
575- Use closures when they genuinely simplify the code, but be intentional
576​
577### Return Type Precision
578​
579**❌ Bad:**
580​
581```typescript
582function serializeKey(key: string | number): unknown {
583 return String(key)
585```
586​
587**✅ Good:**
588​
589```typescript
590function serializeKey(key: string | number): string {
591 return String(key)
593```
594​
595**Key Principle:** Always provide the most precise return type. Avoid `unknown` or `any` return types unless truly necessary.
596​
597## Modern JavaScript Patterns
598​
599### Use Modern Operators
600​
601**❌ Bad:**
602​
603```typescript
604if (firstError === undefined) {
605 firstError = error
607​
608const value = cached !== null && cached !== undefined ? cached : defaultValue
609​
610if (obj[key] === undefined) {
611 obj[key] = value
613```
614​
615**✅ Good:**
616​
617```typescript
618firstError ??= error
619​
620const value = cached ?? defaultValue
621​
622obj[key] ??= value
623```
624​
625### Use Spread Operator
626​
627**❌ Bad:**
628​
629```typescript
630const combined = []
631for (const item of currentItems) {
632 combined.push(item)
634for (const item of newItems) {
635 combined.push(item)
637```
638​
639**✅ Good:**
640​
641```typescript
642const combined = [...currentItems, ...newItems]
643```
644​
645### Simplify Array Operations
646​
647**❌ Bad:**
648​
649```typescript
650const filtered = []
651for (const item of items) {
652 if (item.value > 0) {
653 filtered.push(item)
654 }
656```
657​
658**✅ Good:**
659​
660```typescript
661const filtered = items.filter((item) => item.value > 0)
662```
663​
664## Edge Cases and Corner Cases
665​
666### Common Patterns to Consider
667​
6681. **Key Encoding**: When converting keys to strings, ensure no collisions
669​
670 ```typescript
671 // ❌ Bad: numeric 1 and string "__number__1" collide
672 const key = typeof val === 'number' ? `__number__${val}` : String(val)
673​
674 // ✅ Good: proper encoding with type prefix
675 const key = `${typeof val}_${String(val)}`
676 ```
677​
6782. **Subset/Superset Logic**: Consider all cases
679​
680 ```typescript
681 // Consider: IN with 0, 1, or many elements
682 // Consider: EQ vs IN predicates
683 // Consider: Range predicates (>=, <=) vs equality
684 ```
685​
6863. **Limit and Offset**: Handle undefined, 0, and edge values
687​
688 ```typescript
689 // What happens when limit is 0?
690 // What happens when offset exceeds data length?
691 // What happens when limit is undefined?
692 ```
693​
6944. **Optional vs Required**: Be explicit about optionality
695​
696 ```typescript
697 // ❌ Why is this optional?
698 interface Config {
699 collection?: Collection
700 }
701​
702 // ✅ Document or make required if always needed
703 interface Config {
704 collection: Collection // Always required for query collections
705 }
706 ```
707​
7085. **Race Conditions**: Async operations may resolve in unexpected order
709 ```typescript
710 // Request snapshot before receiving up-to-date
711 // But snapshot resolves after up-to-date arrives
712 // Should ignore the stale snapshot
713 ```
714​
715## Git and PR Hygiene
716​
717### Never Rewrite Published Branch History
718​
719**Do not amend, rebase, squash, or force-push a branch after it has been pushed or has an open PR.** This includes `git push --force` and `git push --force-with-lease`.
720​
721Once a branch is visible to others, treat its history as shared. If CI fails or follow-up changes are needed, add a normal follow-up commit and push normally.
722​
723**❌ Bad:**
724​
725```bash
726git commit --amend --no-edit
727git push --force-with-lease
728```
729​
730**✅ Good:**
731​
732```bash
733git add <files>
734git commit -m "fix: address CI failure"
735git push
736```
737​
738**Key Principles:**
739​
740- Never force-push unless the user explicitly asks for it in that moment.
741- Do not assume `--force-with-lease` is acceptable; it still rewrites shared history.
742- Prefer small follow-up commits over rewritten history on PR branches.
743- If a clean history is desired, let the human maintainer squash or rebase during merge.
744- If you think history rewriting is necessary, stop and ask for explicit confirmation before running any command.
745​
746## Package Versioning
747​
748### Understand Semantic Versioning
749​
750**Common Mistake:**
751​
752```json
754 "dependencies": {
755 "package": "^0.0.0"
756 }
758```
759​
760**Problem:** `^0.0.0` restricts to exactly `0.0.0`, not "latest 0.0.x" as you might expect.
761​
762From [npm semver docs](https://github.com/npm/node-semver):
763​
764> Caret Ranges allow changes that do not modify the left-most non-zero element. For versions `0.0.X`, this means no updates.
765​
766**Solutions:**
767​
768- Use `*` for any version
769- Use `latest` for the latest version
770- Use a proper range like `^0.1.0` if that's what you mean
771​
772## Documentation and Comments
773​
774### Keep Useful Comments
775​
776**Good Comment:**
777​
778```typescript
779// Returning false signals that callers should schedule another pass
780return allDone
781```
782​
783**Good Comment:**
784​
785```typescript
786// This step is necessary because the query function has captured
787// the old subscription instance in its closure
788```
789​
790### Remove Outdated Comments
791​
792**Key Principle:** When refactoring code, update or remove comments that reference old function names or outdated logic.
793​
794## Code Weight and Fail-Fast Design
795​
796Treat each line of production code as a continuing cost. Bug fixes should start
797with a net-neutral production-code budget. Prefer a negative production diff
798when the change makes the existing design simpler.
799​
800Tests and contract documentation can grow to prove the behavior. Report their
801weight separately from production code. Do not compress code or weaken names
802to reduce a line count. Reduce states, branches, helpers, and recovery paths.
803​
804Use the test-first and bug-class guidance above to reproduce the failure and
805identify the violated contract. Strengthen or simplify existing control flow
806before adding state or recovery machinery.
807​
808### Separate Valid Edge Cases from Contract Contradictions
809​
810A rare but valid operation is not an invariant violation. The implementation
811must support it.
812​
813An impossible internal state or a contradictory collaborator signal is an
814invariant violation. Throw or reject immediately at the boundary. Check the
815invariant before the code releases established state or publishes success.
816​
817Do not convert an invariant violation into false readiness, partial success,
818or a silent fallback. In library code, "crash" means a synchronous throw or a
819rejected promise. It does not require process termination.
820​
821### Recovery Must Earn Its Code Weight
822​
823Add retries, generations, queues, fallback states, or rollback paths only when
824all these conditions are true:
825​
826- The condition can occur during valid operation.
827- The public contract defines recovery behavior.
828- Recovery protects user-visible behavior.
829- A test or oracle proves the recovery law.
830​
831If a condition requires a programming error or contract breach, detect it and
832fail loudly. Do not build a second lifecycle to recover from it.
833​
834Prefer a small change to the current abstraction over a replacement state
835machine. A new state machine requires an explicit architectural reason and an
836oracle law that the existing design cannot express.
837​
838For reviewer-proposed defensive machinery based only on contradictory mocks,
839add an invariant witness that fails before mutation instead.
840​
841## General Principles
842​
8431. **Question Optionality**: If a property is optional, understand why. Often it should be required.
844​
8452. **Consider Performance**: Before implementing, think about time complexity, especially for operations that might process many items.
846​
8473. **Validate Semantics**: Ensure that your implementation actually does what you think it does. Consider edge cases.
848​
8494. **Avoid Premature Complexity**: Don't add ternaries, special cases, or checks for things that can't happen.
850​
8515. **Test First for Bugs**: Reproduce bugs in tests before fixing them.
852​
8536. **Be Consistent**: Follow naming conventions and patterns used elsewhere in the codebase.
854​
8557. **Simplify**: Modern JavaScript provides many concise operators and methods. Use them.
856​
8578. **Encapsulate**: Hide implementation details. Use delegation and proper abstraction boundaries.
858​
8599. **Type Precisely**: Use the most specific type possible. Avoid `any`.
860​
86110. **Extract When Duplicating**: If you're writing the same logic twice, extract it.
862​
863## When in Doubt
864​
865If you're unsure about an implementation decision:
866​
8671. Look for similar patterns in the existing codebase
8682. Consider the worst-case scenario for performance
8693. Think about edge cases and corner cases
8704. Ask: "Does this abstraction leak implementation details?"
8715. Ask: "Would this be easy to test?"
8726. Ask: "Is this as simple as it could be?"
873​
874Remember: Simple, well-typed, well-tested code with clear abstractions is the goal. We raise the standard of code quality—not through complexity, but through clarity and correctness.