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

AGENTS.md

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