Open History to see the last commit
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## Table of Contents
6
71. [Type Safety](#type-safety)
82. [Code Organization](#code-organization)
93. [Algorithm Efficiency](#algorithm-efficiency)
104. [Semantic Correctness](#semantic-correctness)
115. [Abstraction Design](#abstraction-design)
126. [Code Clarity](#code-clarity)
137. [Testing Requirements](#testing-requirements)
148. [Function Design](#function-design)
159. [Modern JavaScript Patterns](#modern-javascript-patterns)
1610. [Edge Cases and Corner Cases](#edge-cases-and-corner-cases)
1711. [Git and PR Hygiene](#git-and-pr-hygiene)
18
19## Type Safety
20
21### Avoid `any` Types
22
23**❌ Bad:**
24
25```typescript
26function processData(data: any) {
27 return data.value
28}
29
30const result: any = someOperation()
31```
32
33**✅ Good:**
34
35```typescript
36function processData(data: unknown) {
37 if (isDataObject(data)) {
38 return data.value
39 }
40 throw new Error('Invalid data')
41}
42
43const result: TQueryData = someOperation()
44```
45
46**Key Principles:**
47
48- Use `unknown` instead of `any` when the type is truly unknown
49- Provide proper type annotations for return values
50- Use type guards to narrow `unknown` types safely
51- If you find yourself using `any`, question whether there's a better type
52
53## Code Organization
54
55### Extract Common Logic
56
57**❌ Bad:**
58
59```typescript
60// Duplicated logic in multiple places
61function processA() {
62 const key = typeof value === 'number' ? `__number__${value}` : String(value)
63 // ...
64}
65
66function processB() {
67 const key = typeof value === 'number' ? `__number__${value}` : String(value)
68 // ...
69}
70```
71
72**✅ Good:**
73
74```typescript
75function serializeKey(value: string | number): string {
76 return typeof value === 'number' ? `__number__${value}` : String(value)
77}
78
79function processA() {
80 const key = serializeKey(value)
81 // ...
82}
83
84function processB() {
85 const key = serializeKey(value)
86 // ...
87}
88```
89
90### Organize Utilities
91
92**Key Principles:**
93
94- Extract serialization/deserialization logic into utility files
95- When you see identical or near-identical code blocks, extract to a helper function
96- Prefer small, focused utility functions over large inline implementations
97- Move reusable logic into utility modules (e.g., `utils/`, `helpers/`)
98
99### Function Size and Complexity
100
101**❌ Bad:**
102
103```typescript
104function syncData() {
105 // 200+ lines of logic handling multiple concerns
106 // - snapshot phase
107 // - buffering
108 // - sync state management
109 // - error handling
110 // all inline...
111}
112```
113
114**✅ Good:**
115
116```typescript
117function syncData() {
118 handleSnapshotPhase()
119 manageBuffering()
120 updateSyncState()
121 handleErrors()
122}
123
124function handleSnapshotPhase() {
125 // Focused logic for snapshot phase
126}
127```
128
129**Key Principle:** If a function is massive, extract logical sections into separate functions. This improves readability and maintainability.
130
131## Algorithm Efficiency
132
133### Be Mindful of Time Complexity
134
135**❌ Bad: O(n²) Queue Processing:**
136
137```typescript
138// Processes elements in queue, but elements may need multiple passes
139while (queue.length > 0) {
140 const job = queue.shift()
141 if (hasUnmetDependencies(job)) {
142 queue.push(job) // Re-queue, causing O(n²) behavior
143 } else {
144 processJob(job)
145 }
146}
147```
148
149**✅ Good: Dependency-Aware Processing:**
150
151```typescript
152// Use a data structure that respects dependencies
153// Process only jobs with no unmet dependencies
154// Consider topological sort for DAG-like structures
155const readyJobs = jobs.filter((job) => !hasUnmetDependencies(job))
156readyJobs.forEach(processJob)
157```
158
159### Use Appropriate Data Structures
160
161**❌ Bad:**
162
163```typescript
164// O(n) lookup for each check
165const items = ['foo', 'bar', 'baz' /* hundreds more */]
166if (items.includes(searchValue)) {
167 // ...
168}
169```
170
171**✅ Good:**
172
173```typescript
174// O(1) lookup
175const items = new Set(['foo', 'bar', 'baz' /* hundreds more */])
176if (items.has(searchValue)) {
177 // ...
178}
179```
180
181**Key Principles:**
182
183- For membership checks on large collections, use `Set` instead of `Array.includes()`
184- Be aware of nested loops and their complexity implications
185- Consider the worst-case scenario, especially for operations that could process many items
186- Use appropriate data structures (Set for lookups, Map for key-value, etc.)
187
188## Semantic Correctness
189
190### Ensure Logic Matches Intent
191
192**❌ Bad:**
193
194```typescript
195// Intending to check if subset limit is more restrictive than superset
196function isLimitSubset(
197 subset: number | undefined,
198 superset: number | undefined,
199) {
200 return subset === undefined || superset === undefined || subset <= superset
201}
202
203// Problem: If subset has no limit but superset does, returns true (incorrect)
204```
205
206**✅ Good:**
207
208```typescript
209function isLimitSubset(
210 subset: number | undefined,
211 superset: number | undefined,
212) {
213 // Subset with no limit cannot be a subset of one with a limit
214 return superset === undefined || (subset !== undefined && subset <= superset)
215}
216```
217
218### Validate Intersections and Unions
219
220When merging predicates or combining queries, ensure the semantics are correct:
221
222**Example Problem:**
223
224```sql
225-- Query 1: WHERE age >= 18 LIMIT 1
226-- Query 2: WHERE age >= 20 LIMIT 3
227-- Naive intersection: WHERE age >= 20 LIMIT 1
228-- Problem: This may not return the actual intersection of results
229```
230
231**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.
232
233## Abstraction Design
234
235### Avoid Leaky Abstractions
236
237**❌ Bad:**
238
239```typescript
240class Collection {
241 getViewKey(key: TKey): string {
242 // Caller needs to know internal representation
243 return `${this._state.viewKeyPrefix}${key}`
244 }
245}
246
247// Usage exposes internals
248const viewKey = collection.getViewKey(key)
249if (viewKey.startsWith(PREFIX)) {
250 /* ... */
251}
252```
253
254**✅ Good:**
255
256```typescript
257class Collection {
258 getViewKey(key: TKey): string {
259 // Delegate to state manager, hiding implementation
260 return this._state.getViewKey(key)
261 }
262}
263
264class CollectionStateManager {
265 getViewKey(key: TKey): string {
266 return `${this.viewKeyPrefix}${key}`
267 }
268}
269```
270
271**Key Principles:**
272
273- Encapsulate implementation details within the responsible class
274- Don't expose internal data structures or representations
275- Use delegation to maintain clean boundaries between components
276- Keep internal properties private when possible
277
278### Proper Encapsulation
279
280**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.
281
282## Code Clarity
283
284### Prefer Positive Predicates
285
286**❌ Bad:**
287
288```typescript
289if (!refs.some((ref) => ref.path[0] === outerAlias)) {
290 // treat as safe
291}
292```
293
294**✅ Good:**
295
296```typescript
297if (refs.every((ref) => ref.path[0] !== outerAlias)) {
298 // treat as safe
299}
300```
301
302**Key Principle:** Positive conditions (every, all) are generally easier to understand than negated conditions (not some).
303
304### Simplify Complex Conditions
305
306**❌ Bad:**
307
308```typescript
309const isLoadingNow = this.pendingLoadSubsetPromises.size > 0
310if (isLoadingNow && !isLoadingNow) {
311 // Confusing logic
312}
313```
314
315**✅ Good:**
316
317```typescript
318const wasLoading = this.pendingLoadSubsetPromises.size > 0
319this.pendingLoadSubsetPromises.add(promise)
320const isLoadingNow = this.pendingLoadSubsetPromises.size === 1
321
322if (isLoadingNow) {
323 // Started loading
324}
325```
326
327### Use Descriptive Names
328
329**❌ Bad:**
330
331```typescript
332const viewKeysMap = new Map() // Type in name is redundant
333const dependencyBuilders = [] // Sounds like functions that build
334```
335
336**✅ Good:**
337
338```typescript
339const viewKeys = new Map() // Data structure not in name
340const dependentBuilders = [] // Accurately describes dependents
341```
342
343**Key Principles:**
344
345- Avoid Hungarian notation (encoding type in variable name)
346- Use names that describe the role or purpose, not the data structure
347- Choose names that make the code read like prose
348- Prefer `dependentBuilders` over `dependencyBuilders` when referring to things that depend on something
349
350## Testing Requirements
351
352### Always Add Tests for Bugs
353
354**Key Principle:** If you're fixing a bug, add a unit test that reproduces the bug before fixing it. This ensures:
355
356- The bug is actually fixed
357- The bug doesn't regress in the future
358- The fix is validated
359
360**Example:**
361
362```typescript
363// Found a bug with fetchSnapshot resolving after up-to-date message
364// Should add a test:
365test('ignores snapshot that resolves after up-to-date message', async () => {
366 // Reproduce the corner case
367 // Verify it's handled correctly
368})
369```
370
371### Test Corner Cases
372
373Common corner cases to consider:
374
375- Empty arrays or sets
376- Single-element collections
377- `undefined` vs `null` values
378- Operations on already-resolved promises
379- Race conditions between async operations
380- Limit/offset edge cases (0, 1, very large numbers)
381- IN predicates with 0 or 1 elements
382
383## Function Design
384
385### Prefer Explicit Parameters Over Closures
386
387**❌ Bad:**
388
389```typescript
390function outer() {
391 const config = getConfig()
392 const state = getState()
393
394 const updateFn = () => {
395 // Closes over config and state
396 applyUpdate(config, state)
397 }
398
399 scheduler.schedule(updateFn)
400}
401```
402
403**✅ Good:**
404
405```typescript
406function updateEntry(entry: Entry, config: Config, state: State) {
407 applyUpdate(entry, config, state)
408}
409
410function outer() {
411 const config = getConfig()
412 const state = getState()
413
414 scheduler.schedule({
415 config,
416 state,
417 update: updateEntry,
418 })
419}
420```
421
422**Key Principles:**
423
424- Functions that take dependencies as arguments are easier to test
425- Explicit parameters make data flow clearer
426- Closures can hide dependencies and make code harder to follow
427- Use closures when they genuinely simplify the code, but be intentional
428
429### Return Type Precision
430
431**❌ Bad:**
432
433```typescript
434function serializeKey(key: string | number): unknown {
435 return String(key)
436}
437```
438
439**✅ Good:**
440
441```typescript
442function serializeKey(key: string | number): string {
443 return String(key)
444}
445```
446
447**Key Principle:** Always provide the most precise return type. Avoid `unknown` or `any` return types unless truly necessary.
448
449## Modern JavaScript Patterns
450
451### Use Modern Operators
452
453**❌ Bad:**
454
455```typescript
456if (firstError === undefined) {
457 firstError = error
458}
459
460const value = cached !== null && cached !== undefined ? cached : defaultValue
461
462if (obj[key] === undefined) {
463 obj[key] = value
464}
465```
466
467**✅ Good:**
468
469```typescript
470firstError ??= error
471
472const value = cached ?? defaultValue
473
474obj[key] ??= value
475```
476
477### Use Spread Operator
478
479**❌ Bad:**
480
481```typescript
482const combined = []
483for (const item of currentItems) {
484 combined.push(item)
485}
486for (const item of newItems) {
487 combined.push(item)
488}
489```
490
491**✅ Good:**
492
493```typescript
494const combined = [...currentItems, ...newItems]
495```
496
497### Simplify Array Operations
498
499**❌ Bad:**
500
501```typescript
502const filtered = []
503for (const item of items) {
504 if (item.value > 0) {
505 filtered.push(item)
506 }
507}
508```
509
510**✅ Good:**
511
512```typescript
513const filtered = items.filter((item) => item.value > 0)
514```
515
516## Edge Cases and Corner Cases
517
518### Common Patterns to Consider
519
5201. **Key Encoding**: When converting keys to strings, ensure no collisions
521
522 ```typescript
523 // ❌ Bad: numeric 1 and string "__number__1" collide
524 const key = typeof val === 'number' ? `__number__${val}` : String(val)
525
526 // ✅ Good: proper encoding with type prefix
527 const key = `${typeof val}_${String(val)}`
528 ```
529
5302. **Subset/Superset Logic**: Consider all cases
531
532 ```typescript
533 // Consider: IN with 0, 1, or many elements
534 // Consider: EQ vs IN predicates
535 // Consider: Range predicates (>=, <=) vs equality
536 ```
537
5383. **Limit and Offset**: Handle undefined, 0, and edge values
539
540 ```typescript
541 // What happens when limit is 0?
542 // What happens when offset exceeds data length?
543 // What happens when limit is undefined?
544 ```
545
5464. **Optional vs Required**: Be explicit about optionality
547
548 ```typescript
549 // ❌ Why is this optional?
550 interface Config {
551 collection?: Collection
552 }
553
554 // ✅ Document or make required if always needed
555 interface Config {
556 collection: Collection // Always required for query collections
557 }
558 ```
559
5605. **Race Conditions**: Async operations may resolve in unexpected order
561 ```typescript
562 // Request snapshot before receiving up-to-date
563 // But snapshot resolves after up-to-date arrives
564 // Should ignore the stale snapshot
565 ```
566
567## Git and PR Hygiene
568
569### Never Rewrite Published Branch History
570
571**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`.
572
573Once 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.
574
575**❌ Bad:**
576
577```bash
578git commit --amend --no-edit
579git push --force-with-lease
580```
581
582**✅ Good:**
583
584```bash
585git add <files>
586git commit -m "fix: address CI failure"
587git push
588```
589
590**Key Principles:**
591
592- Never force-push unless the user explicitly asks for it in that moment.
593- Do not assume `--force-with-lease` is acceptable; it still rewrites shared history.
594- Prefer small follow-up commits over rewritten history on PR branches.
595- If a clean history is desired, let the human maintainer squash or rebase during merge.
596- If you think history rewriting is necessary, stop and ask for explicit confirmation before running any command.
597
598## Package Versioning
599
600### Understand Semantic Versioning
601
602**Common Mistake:**
603
604```json
605{
606 "dependencies": {
607 "package": "^0.0.0"
608 }
609}
610```
611
612**Problem:** `^0.0.0` restricts to exactly `0.0.0`, not "latest 0.0.x" as you might expect.
613
614From [npm semver docs](https://github.com/npm/node-semver):
615
616> Caret Ranges allow changes that do not modify the left-most non-zero element. For versions `0.0.X`, this means no updates.
617
618**Solutions:**
619
620- Use `*` for any version
621- Use `latest` for the latest version
622- Use a proper range like `^0.1.0` if that's what you mean
623
624## Documentation and Comments
625
626### Keep Useful Comments
627
628**Good Comment:**
629
630```typescript
631// Returning false signals that callers should schedule another pass
632return allDone
633```
634
635**Good Comment:**
636
637```typescript
638// This step is necessary because the query function has captured
639// the old subscription instance in its closure
640```
641
642### Remove Outdated Comments
643
644**Key Principle:** When refactoring code, update or remove comments that reference old function names or outdated logic.
645
646## General Principles
647
6481. **Question Optionality**: If a property is optional, understand why. Often it should be required.
649
6502. **Consider Performance**: Before implementing, think about time complexity, especially for operations that might process many items.
651
6523. **Validate Semantics**: Ensure that your implementation actually does what you think it does. Consider edge cases.
653
6544. **Avoid Premature Complexity**: Don't add ternaries, special cases, or checks for things that can't happen.
655
6565. **Test First for Bugs**: Reproduce bugs in tests before fixing them.
657
6586. **Be Consistent**: Follow naming conventions and patterns used elsewhere in the codebase.
659
6607. **Simplify**: Modern JavaScript provides many concise operators and methods. Use them.
661
6628. **Encapsulate**: Hide implementation details. Use delegation and proper abstraction boundaries.
663
6649. **Type Precisely**: Use the most specific type possible. Avoid `any`.
665
66610. **Extract When Duplicating**: If you're writing the same logic twice, extract it.
667
668## When in Doubt
669
670If you're unsure about an implementation decision:
671
6721. Look for similar patterns in the existing codebase
6732. Consider the worst-case scenario for performance
6743. Think about edge cases and corner cases
6754. Ask: "Does this abstraction leak implementation details?"
6765. Ask: "Would this be easy to test?"
6776. Ask: "Is this as simple as it could be?"
678
679Remember: 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.