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

AGENTS.md

796 lines22.1 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)
64​
65## Type Safety
66​
67### Avoid `any` Types
68​
69**❌ Bad:**
70​
71```typescript
72function processData(data: any) {
73 return data.value
75​
76const result: any = someOperation()
77```
78​
79**✅ Good:**
80​
81```typescript
82function processData(data: unknown) {
83 if (isDataObject(data)) {
84 return data.value
85 }
86 throw new Error('Invalid data')
88​
89const result: TQueryData = someOperation()
90```
91​
92**Key Principles:**
93​
94- Use `unknown` instead of `any` when the type is truly unknown
95- Provide proper type annotations for return values
96- Use type guards to narrow `unknown` types safely
97- If you find yourself using `any`, question whether there's a better type
98​
99## Code Organization
100​
101### Extract Common Logic
102​
103**❌ Bad:**
104​
105```typescript
106// Duplicated logic in multiple places
107function processA() {
108 const key = typeof value === 'number' ? `__number__${value}` : String(value)
109 // ...
111​
112function processB() {
113 const key = typeof value === 'number' ? `__number__${value}` : String(value)
114 // ...
116```
117​
118**✅ Good:**
119​
120```typescript
121function serializeKey(value: string | number): string {
122 return typeof value === 'number' ? `__number__${value}` : String(value)
124​
125function processA() {
126 const key = serializeKey(value)
127 // ...
129​
130function processB() {
131 const key = serializeKey(value)
132 // ...
134```
135​
136### Organize Utilities
137​
138**Key Principles:**
139​
140- Extract serialization/deserialization logic into utility files
141- When you see identical or near-identical code blocks, extract to a helper function
142- Prefer small, focused utility functions over large inline implementations
143- Move reusable logic into utility modules (e.g., `utils/`, `helpers/`)
144​
145### Function Size and Complexity
146​
147**❌ Bad:**
148​
149```typescript
150function syncData() {
151 // 200+ lines of logic handling multiple concerns
152 // - snapshot phase
153 // - buffering
154 // - sync state management
155 // - error handling
156 // all inline...
158```
159​
160**✅ Good:**
161​
162```typescript
163function syncData() {
164 handleSnapshotPhase()
165 manageBuffering()
166 updateSyncState()
167 handleErrors()
169​
170function handleSnapshotPhase() {
171 // Focused logic for snapshot phase
173```
174​
175**Key Principle:** If a function is massive, extract logical sections into separate functions. This improves readability and maintainability.
176​
177## Algorithm Efficiency
178​
179### Be Mindful of Time Complexity
180​
181**❌ Bad: O(n²) Queue Processing:**
182​
183```typescript
184// Processes elements in queue, but elements may need multiple passes
185while (queue.length > 0) {
186 const job = queue.shift()
187 if (hasUnmetDependencies(job)) {
188 queue.push(job) // Re-queue, causing O(n²) behavior
189 } else {
190 processJob(job)
191 }
193```
194​
195**✅ Good: Dependency-Aware Processing:**
196​
197```typescript
198// Use a data structure that respects dependencies
199// Process only jobs with no unmet dependencies
200// Consider topological sort for DAG-like structures
201const readyJobs = jobs.filter((job) => !hasUnmetDependencies(job))
202readyJobs.forEach(processJob)
203```
204​
205### Use Appropriate Data Structures
206​
207**❌ Bad:**
208​
209```typescript
210// O(n) lookup for each check
211const items = ['foo', 'bar', 'baz' /* hundreds more */]
212if (items.includes(searchValue)) {
213 // ...
215```
216​
217**✅ Good:**
218​
219```typescript
220// O(1) lookup
221const items = new Set(['foo', 'bar', 'baz' /* hundreds more */])
222if (items.has(searchValue)) {
223 // ...
225```
226​
227**Key Principles:**
228​
229- For membership checks on large collections, use `Set` instead of `Array.includes()`
230- Be aware of nested loops and their complexity implications
231- Consider the worst-case scenario, especially for operations that could process many items
232- Use appropriate data structures (Set for lookups, Map for key-value, etc.)
233​
234## Semantic Correctness
235​
236### Ensure Logic Matches Intent
237​
238**❌ Bad:**
239​
240```typescript
241// Intending to check if subset limit is more restrictive than superset
242function isLimitSubset(
243 subset: number | undefined,
244 superset: number | undefined,
245) {
246 return subset === undefined || superset === undefined || subset <= superset
248​
249// Problem: If subset has no limit but superset does, returns true (incorrect)
250```
251​
252**✅ Good:**
253​
254```typescript
255function isLimitSubset(
256 subset: number | undefined,
257 superset: number | undefined,
258) {
259 // Subset with no limit cannot be a subset of one with a limit
260 return superset === undefined || (subset !== undefined && subset <= superset)
262```
263​
264### Validate Intersections and Unions
265​
266When merging predicates or combining queries, ensure the semantics are correct:
267​
268**Example Problem:**
269​
270```sql
271-- Query 1: WHERE age >= 18 LIMIT 1
272-- Query 2: WHERE age >= 20 LIMIT 3
273-- Naive intersection: WHERE age >= 20 LIMIT 1
274-- Problem: This may not return the actual intersection of results
275```
276​
277**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.
278​
279## Abstraction Design
280​
281### Avoid Leaky Abstractions
282​
283**❌ Bad:**
284​
285```typescript
286class Collection {
287 getViewKey(key: TKey): string {
288 // Caller needs to know internal representation
289 return `${this._state.viewKeyPrefix}${key}`
290 }
292​
293// Usage exposes internals
294const viewKey = collection.getViewKey(key)
295if (viewKey.startsWith(PREFIX)) {
296 /* ... */
298```
299​
300**✅ Good:**
301​
302```typescript
303class Collection {
304 getViewKey(key: TKey): string {
305 // Delegate to state manager, hiding implementation
306 return this._state.getViewKey(key)
307 }
309​
310class CollectionStateManager {
311 getViewKey(key: TKey): string {
312 return `${this.viewKeyPrefix}${key}`
313 }
315```
316​
317**Key Principles:**
318​
319- Encapsulate implementation details within the responsible class
320- Don't expose internal data structures or representations
321- Use delegation to maintain clean boundaries between components
322- Keep internal properties private when possible
323​
324### Proper Encapsulation
325​
326**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.
327​
328## Code Clarity
329​
330### Prefer Positive Predicates
331​
332**❌ Bad:**
333​
334```typescript
335if (!refs.some((ref) => ref.path[0] === outerAlias)) {
336 // treat as safe
338```
339​
340**✅ Good:**
341​
342```typescript
343if (refs.every((ref) => ref.path[0] !== outerAlias)) {
344 // treat as safe
346```
347​
348**Key Principle:** Positive conditions (every, all) are generally easier to understand than negated conditions (not some).
349​
350### Simplify Complex Conditions
351​
352**❌ Bad:**
353​
354```typescript
355const isLoadingNow = this.pendingLoadSubsetPromises.size > 0
356if (isLoadingNow && !isLoadingNow) {
357 // Confusing logic
359```
360​
361**✅ Good:**
362​
363```typescript
364const wasLoading = this.pendingLoadSubsetPromises.size > 0
365this.pendingLoadSubsetPromises.add(promise)
366const isLoadingNow = this.pendingLoadSubsetPromises.size === 1
367​
368if (isLoadingNow) {
369 // Started loading
371```
372​
373### Use Descriptive Names
374​
375**❌ Bad:**
376​
377```typescript
378const viewKeysMap = new Map() // Type in name is redundant
379const dependencyBuilders = [] // Sounds like functions that build
380```
381​
382**✅ Good:**
383​
384```typescript
385const viewKeys = new Map() // Data structure not in name
386const dependentBuilders = [] // Accurately describes dependents
387```
388​
389**Key Principles:**
390​
391- Avoid Hungarian notation (encoding type in variable name)
392- Use names that describe the role or purpose, not the data structure
393- Choose names that make the code read like prose
394- Prefer `dependentBuilders` over `dependencyBuilders` when referring to things that depend on something
395​
396## Testing Requirements
397​
398### Required reading: oracle tests
399​
400Before designing, changing, or reviewing an oracle or generated-history test,
401read [Writing reliable oracle tests](docs/contributing/oracle-tests.md).
402Use the [coverage map](docs/contributing/oracle-coverage.md) to find an existing
403owner and its limits before adding another model. The guide explains testing
404methods; it does not authorize new product behavior or retire existing laws.
405​
406Write every oracle and generated-history test as executable subsystem
407documentation. Follow the guide's section on literate oracle files. Keep the
408contract, model, generated history grammar, production driver, and refinement
409check—including its public observations and checkpoint—visible and close enough
410that a reviewer can compare them directly. A focused regression may remain
411short, but it does not waive this structure for an oracle and cannot replace
412applicable oracle coverage.
413​
414### Always Add Tests for Bugs
415​
416**Key Principle:** Reproduce a bug in a test before fixing it. Prefer extending
417an oracle as described below over adding an isolated unit test. This ensures:
418​
419- The bug is actually fixed
420- The bug doesn't regress in the future
421- The fix is validated
422​
423**Example:**
424​
425```typescript
426// Found a bug with fetchSnapshot resolving after up-to-date message
427// Should add a test:
428test('ignores snapshot that resolves after up-to-date message', async () => {
429 // Reproduce the corner case
430 // Verify it's handled correctly
431})
432```
433​
434### Treat Every Review Bug as a Test Gap
435​
436When a reviewer agent confirms a bug, it must also ask why the existing tests
437did not catch it. The finding should name the missing test law, state
438transition, generator dimension, adapter boundary, or assertion. If a test or
439oracle should already have caught the bug, identify the false-green model,
440classifier, fixture, or assertion that let it pass. Use that analysis to suggest
441the smallest test or oracle improvement that would catch the same class of bug,
442not only the reported example.
443​
444### Keep Oracles Independent
445​
446An oracle is useful only when its expected result comes from a source independent
447of the implementation under test. Do not translate production branches, state
448machines, classifiers, or helper functions into a second implementation and call
449that an oracle. Both copies can encode the same wrong assumption.
450​
451- Derive expected behavior from public contracts, documented prior behavior,
452 mathematical laws, or a separately specified reference model.
453- Keep the reference model structurally different from production. Do not import
454 the production helper or reuse its classifications to compute expected results.
455- Preserve existing contract tests unless a product or design decision explicitly
456 changes the contract. Rewriting a passing expectation to match new production
457 behavior is a design review, not routine test maintenance.
458- When production work suggests an oracle change, compare the old and new
459 semantics with counterexamples before editing the oracle.
460- Use hostile mutants to prove the oracle rejects plausible wrong designs,
461 including the mistake production currently makes. A green oracle without a
462 demonstrated kill is weak evidence.
463- Use process grammar to explore lifecycle paths, and design grammar to challenge
464 the oracle's reference semantics. More generated traces cannot repair a wrong
465 reference model.
466​
467### Prefer Oracle Coverage Over Isolated Regressions
468​
469An oracle that checks general laws across generated states and histories is a
470stronger form of coverage than a unit test for one specific example. Prefer
471extending an existing oracle when it can cover the behavior. Add the missing
472model rule, generator dimension, state transition, or observable assertion;
473adding more pinned examples alone does not generalize the oracle.
474​
475Use a focused regression to isolate and shrink a failure, then keep it as a
476replay example for the broader oracle where possible. Verify that the expanded
477oracle fails without the fix and passes with it. Keep valuable unit tests, but
478do not treat them as a substitute for applicable oracle coverage. If an oracle
479is not practical for the behavior, explain why a focused test is sufficient.
480​
481### Name Tests After Behavior
482​
483Test names should state the behavior they prove. Do not put issue or pull
484request numbers in test names; those references become stale and make the test
485suite harder to read. When an external report contains essential context that
486the test cannot express, link it in a nearby comment instead.
487​
488### Test Corner Cases
489​
490Common corner cases to consider:
491​
492- Empty arrays or sets
493- Single-element collections
494- `undefined` vs `null` values
495- Operations on already-resolved promises
496- Race conditions between async operations
497- Limit/offset edge cases (0, 1, very large numbers)
498- IN predicates with 0 or 1 elements
499​
500## Function Design
501​
502### Prefer Explicit Parameters Over Closures
503​
504**❌ Bad:**
505​
506```typescript
507function outer() {
508 const config = getConfig()
509 const state = getState()
510​
511 const updateFn = () => {
512 // Closes over config and state
513 applyUpdate(config, state)
514 }
515​
516 scheduler.schedule(updateFn)
518```
519​
520**✅ Good:**
521​
522```typescript
523function updateEntry(entry: Entry, config: Config, state: State) {
524 applyUpdate(entry, config, state)
526​
527function outer() {
528 const config = getConfig()
529 const state = getState()
530​
531 scheduler.schedule({
532 config,
533 state,
534 update: updateEntry,
535 })
537```
538​
539**Key Principles:**
540​
541- Functions that take dependencies as arguments are easier to test
542- Explicit parameters make data flow clearer
543- Closures can hide dependencies and make code harder to follow
544- Use closures when they genuinely simplify the code, but be intentional
545​
546### Return Type Precision
547​
548**❌ Bad:**
549​
550```typescript
551function serializeKey(key: string | number): unknown {
552 return String(key)
554```
555​
556**✅ Good:**
557​
558```typescript
559function serializeKey(key: string | number): string {
560 return String(key)
562```
563​
564**Key Principle:** Always provide the most precise return type. Avoid `unknown` or `any` return types unless truly necessary.
565​
566## Modern JavaScript Patterns
567​
568### Use Modern Operators
569​
570**❌ Bad:**
571​
572```typescript
573if (firstError === undefined) {
574 firstError = error
576​
577const value = cached !== null && cached !== undefined ? cached : defaultValue
578​
579if (obj[key] === undefined) {
580 obj[key] = value
582```
583​
584**✅ Good:**
585​
586```typescript
587firstError ??= error
588​
589const value = cached ?? defaultValue
590​
591obj[key] ??= value
592```
593​
594### Use Spread Operator
595​
596**❌ Bad:**
597​
598```typescript
599const combined = []
600for (const item of currentItems) {
601 combined.push(item)
603for (const item of newItems) {
604 combined.push(item)
606```
607​
608**✅ Good:**
609​
610```typescript
611const combined = [...currentItems, ...newItems]
612```
613​
614### Simplify Array Operations
615​
616**❌ Bad:**
617​
618```typescript
619const filtered = []
620for (const item of items) {
621 if (item.value > 0) {
622 filtered.push(item)
623 }
625```
626​
627**✅ Good:**
628​
629```typescript
630const filtered = items.filter((item) => item.value > 0)
631```
632​
633## Edge Cases and Corner Cases
634​
635### Common Patterns to Consider
636​
6371. **Key Encoding**: When converting keys to strings, ensure no collisions
638​
639 ```typescript
640 // ❌ Bad: numeric 1 and string "__number__1" collide
641 const key = typeof val === 'number' ? `__number__${val}` : String(val)
642​
643 // ✅ Good: proper encoding with type prefix
644 const key = `${typeof val}_${String(val)}`
645 ```
646​
6472. **Subset/Superset Logic**: Consider all cases
648​
649 ```typescript
650 // Consider: IN with 0, 1, or many elements
651 // Consider: EQ vs IN predicates
652 // Consider: Range predicates (>=, <=) vs equality
653 ```
654​
6553. **Limit and Offset**: Handle undefined, 0, and edge values
656​
657 ```typescript
658 // What happens when limit is 0?
659 // What happens when offset exceeds data length?
660 // What happens when limit is undefined?
661 ```
662​
6634. **Optional vs Required**: Be explicit about optionality
664​
665 ```typescript
666 // ❌ Why is this optional?
667 interface Config {
668 collection?: Collection
669 }
670​
671 // ✅ Document or make required if always needed
672 interface Config {
673 collection: Collection // Always required for query collections
674 }
675 ```
676​
6775. **Race Conditions**: Async operations may resolve in unexpected order
678 ```typescript
679 // Request snapshot before receiving up-to-date
680 // But snapshot resolves after up-to-date arrives
681 // Should ignore the stale snapshot
682 ```
683​
684## Git and PR Hygiene
685​
686### Never Rewrite Published Branch History
687​
688**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`.
689​
690Once 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.
691​
692**❌ Bad:**
693​
694```bash
695git commit --amend --no-edit
696git push --force-with-lease
697```
698​
699**✅ Good:**
700​
701```bash
702git add <files>
703git commit -m "fix: address CI failure"
704git push
705```
706​
707**Key Principles:**
708​
709- Never force-push unless the user explicitly asks for it in that moment.
710- Do not assume `--force-with-lease` is acceptable; it still rewrites shared history.
711- Prefer small follow-up commits over rewritten history on PR branches.
712- If a clean history is desired, let the human maintainer squash or rebase during merge.
713- If you think history rewriting is necessary, stop and ask for explicit confirmation before running any command.
714​
715## Package Versioning
716​
717### Understand Semantic Versioning
718​
719**Common Mistake:**
720​
721```json
723 "dependencies": {
724 "package": "^0.0.0"
725 }
727```
728​
729**Problem:** `^0.0.0` restricts to exactly `0.0.0`, not "latest 0.0.x" as you might expect.
730​
731From [npm semver docs](https://github.com/npm/node-semver):
732​
733> Caret Ranges allow changes that do not modify the left-most non-zero element. For versions `0.0.X`, this means no updates.
734​
735**Solutions:**
736​
737- Use `*` for any version
738- Use `latest` for the latest version
739- Use a proper range like `^0.1.0` if that's what you mean
740​
741## Documentation and Comments
742​
743### Keep Useful Comments
744​
745**Good Comment:**
746​
747```typescript
748// Returning false signals that callers should schedule another pass
749return allDone
750```
751​
752**Good Comment:**
753​
754```typescript
755// This step is necessary because the query function has captured
756// the old subscription instance in its closure
757```
758​
759### Remove Outdated Comments
760​
761**Key Principle:** When refactoring code, update or remove comments that reference old function names or outdated logic.
762​
763## General Principles
764​
7651. **Question Optionality**: If a property is optional, understand why. Often it should be required.
766​
7672. **Consider Performance**: Before implementing, think about time complexity, especially for operations that might process many items.
768​
7693. **Validate Semantics**: Ensure that your implementation actually does what you think it does. Consider edge cases.
770​
7714. **Avoid Premature Complexity**: Don't add ternaries, special cases, or checks for things that can't happen.
772​
7735. **Test First for Bugs**: Reproduce bugs in tests before fixing them.
774​
7756. **Be Consistent**: Follow naming conventions and patterns used elsewhere in the codebase.
776​
7777. **Simplify**: Modern JavaScript provides many concise operators and methods. Use them.
778​
7798. **Encapsulate**: Hide implementation details. Use delegation and proper abstraction boundaries.
780​
7819. **Type Precisely**: Use the most specific type possible. Avoid `any`.
782​
78310. **Extract When Duplicating**: If you're writing the same logic twice, extract it.
784​
785## When in Doubt
786​
787If you're unsure about an implementation decision:
788​
7891. Look for similar patterns in the existing codebase
7902. Consider the worst-case scenario for performance
7913. Think about edge cases and corner cases
7924. Ask: "Does this abstraction leak implementation details?"
7935. Ask: "Would this be easy to test?"
7946. Ask: "Is this as simple as it could be?"
795​
796Remember: 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.