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## Think like a scientist
6
7Treat the code as an implementation of laws about observable behavior. Before
8changing a subsystem, articulate the law, its authority, and the conditions
9under which it applies. Think hard about whether it is the right law and whether
10we fully enforce it. Existing behavior is evidence about the implementation;
11it is not, by itself, authority for the promise.
12
13Use oracles as instruments: a small independent model enacts a law, legal
14histories exercise it, and public observations test production against it.
15Seek cases that distinguish plausible explanations. A mismatch can expose a
16production bug, a wrong model or law, missing information at the production
17boundary, or an unsuitable observation checkpoint. A green oracle can still
18miss a violation when its histories, path, observation checkpoint, or
19comparison are insufficient.
20Correctly implemented behavior can also fail the user's need. Use the
21[repair-location table](docs/contributing/instruments/adversarial-review.md#locate-the-repair)
22after diagnosing which account failed, before changing expectations.
23
24Challenge the laws themselves when the task warrants it: their suitability,
25interactions, and underlying concepts can need revision. Keep proposed design
26changes distinct from defects under the accepted contract. Preserve useful
27implementation freedom and state what the evidence does and does not establish.
28
29Before creating or editing an oracle, load
30[oracle-authoring](.agents/skills/oracle-authoring/SKILL.md). This applies to
31an edit of an oracle or of the production driver, history grammar, or
32comparison that it uses. It also applies when the edit fixes a bug or a review
33finding.
34Before reviewing an oracle, load
35[oracle-review](.agents/skills/oracle-review/SKILL.md). Both use the
36oracle guide below and a small [instrument library](docs/contributing/instruments/index.md)
37that is also available for other design work. Select instruments as needed;
38routine work does not require a full instrument sequence.
39
40## How oracle work is scored
41
42Every behavior change in an area that an oracle owns has two possible paths.
43The maintainer runs hostile auditors on every pull request. The auditors look
44for the shortcuts listed below and report each one. Pick the path with this in
45mind: a shortcut does not finish the task sooner. It moves the work into
46review, where it costs more.
47
48### The oracle-first path
49
501. State the law and its authority.
512. Extend the oracle so that generated histories reach the state where the law
52 matters. Declare that state with
53 [`createOracleReach`](packages/db/tests/oracle-reach.ts), and show that the
54 generated histories reach it.
553. Run the oracle against the unchanged production code. It fails: this is the
56 RED result, and it proves that the oracle sees the defect.
574. Change production. The oracle gives immediate feedback on each attempt,
58 including attempts that break a neighboring law.
595. Show that a hostile mutant, such as the original defect, fails the oracle.
60
61On this path, you know the fix is correct before you push it. Reviewers find
62little that is new, so the total work and token spend stay low. Later agents
63inherit a clean model of the subsystem that they can extend in place.
64
65### The shortcut path
66
67Change production first, then adjust the oracle until it passes: relax a
68comparison, add an exclusion, change a model rule to match the new output, or
69add one pinned example. The tests pass, but nothing shows that the oracle can
70see the defect class. Auditors find the gap. Each finding costs a fix, a new
71witness, and another review round, and the next fix often breaks a
72neighboring law that the oracle still cannot see.
73
74In one recorded case, a production-first rewrite of reload handling needed four
75more review rounds and about ten follow-up commits. Each round found a defect
76in the previous round's fix. A grammar-first pass then found the last defect on
77its first run, and the fix that followed made the rule smaller. The result is
78usually the same code, after much more work, rework, and maintainer
79frustration.
80
81### Extra credit
82
83Work earns extra credit for:
84
85- an oracle improvement that has proof: a declared reach, a RED result on the
86 parent commit, a GREEN result, and a hostile mutant that fails.
87- a model that stays independent of production and short, with each rule tied
88 to its authority.
89- a production change that is clean and light in shipped bytes, especially one
90 that removes states, branches, or recovery paths.
91
92### Penalties
93
94Auditors penalize these shortcuts heavily, and a pull request that contains one
95is not ready:
96
97- **Production first:** a production change in an oracle-owned area without a
98 RED result from the extended oracle on the code before the change.
99- **Model hacking:** a model rule changed to match production output without a
100 stated authority (a contract document and section, or a maintainer
101 decision). Production output is evidence. It is not authority.
102- **Unreachable claims:** a closure claim for a state that generated histories
103 do not reach, or a reach that nobody measured.
104- **Quiet exclusions:** a skipped, narrowed, or relaxed comparison without an
105 entry in the [coverage map](docs/contributing/oracle-coverage.md) that names
106 the owner and the maintainer decision.
107- **Pinned-only coverage:** a named example where the law needs a generator
108 dimension.
109- **Unit tests inside oracles:** ordinary examples or concrete type assertions
110 placed in an oracle file. A fixed regression must replay the shared model,
111 production driver, and comparison without its own expected answer.
112- **"Pre-existing" as a dismissal:** a reachable counterexample that an agent
113 labels as older than the change, but does not fix, record in the coverage
114 map with its trace, or bring to the maintainer for a decision.
115- **No mutant:** a closure claim without a hostile mutant that fails the
116 oracle.
117
118### The evidence block
119
120Every pull request or commit that changes behavior in an oracle-owned area
121includes this block:
122
123- **Law:** the law and its authority.
124- **Reach:** the declared state and how many generated histories reached it.
125- **RED:** the command and the failure on the parent commit.
126- **GREEN:** the command and the result after the change.
127- **Mutant:** the hostile mutant and how the oracle rejected it.
128- **Limits:** the states, paths, and observations that the evidence does not
129 cover.
130
131### Lint feedback while you work
132
133The `oracle/` lint rules in `scripts/eslint-plugin-oracle/` report the
134shortcuts that a syntactic check can see. The repository's agent hooks
135(`.claude/`, `.codex/`, `.gemini/`, and `.github/hooks/`) return the reports
136after each edit and at the end of each turn. A hook sees only the edits that
137the harness's own edit tools make. After an edit through a shell command, or
138in a harness without these hooks, run `pnpm lint:changed` before you finish.
139
140The end-of-turn hook and `pnpm lint:changed` also report every oracle run
141budget that the branch lowered or removed, and CI prints it as a warning. A
142budget is removed when its key is in no oracle file, or in a module that an
143oracle file imports, any more. A lowered or removed budget can be deliberate.
144Restore it, or explain the reason in the pull request.
145
146Fix a report. Do not turn the rule off. The hooks, `pnpm lint:changed`, the
147pre-commit hook, and CI ignore `eslint-disable` comments for these rules. A
148true exception needs a maintainer to change the rule in a reviewed pull
149request.
150
151## Required reading: live-query materialization
152
153Before reading, analyzing, or modifying correlated live-query materialization
154code under `packages/db/src/query/live/`, read
155`packages/db/src/query/live/ARCHITECTURE.md` in full. Read it before changing
156the related includes oracle tests as well.
157
158Treat that document's component boundaries and normative laws as constraints.
159If a change intentionally revises an architectural contract, update the
160architecture document in the same pull request.
161
162## Required reading: executable subsystem models
163
164Read `docs/contributing/glossary.md` before naming or renaming a subsystem
165state, action, boundary, or observation. Production code, executable models,
166tests, and design documents must use the same term for the same concept. A
167model may stay structurally independent, but it must declare any abstraction
168that combines, splits, or does not correspond to production concepts.
169
170Some oracle files are also the shortest documentation for their subsystem.
171Before changing a covered contract or its machinery, use
172`docs/contributing/oracle-coverage.md` to find the primary executable owner and
173read its stated limits. Do not infer authority from a filename alone.
174
175Read these stable entry points before the narrower owner:
176
177- For correlated live-query materialization, read the architecture document
178 required above.
179- For Collection mutation admission, subscription ownership, replay,
180 publication, or disposal, read
181 `packages/db/tests/collection-subscription-lifecycle-grammar-oracle.ts`.
182- For optimistic snapshots and settlement, read
183 `packages/db/tests/optimistic-history-oracle.ts`.
184- For opaque cursor pagination, read
185 `packages/query-db-collection/tests/cursor-pagination/model-oracle.ts`.
186- For TrailBase lifecycle work, read
187 `packages/trailbase-db-collection/tests/ORACLE.md`.
188- For cross-framework behavior, read the shared contract under
189 `packages/db/tests/conformance/` and the receiving framework's driver. One
190 framework's scheduling cut does not prove another's.
191
192The opening prose states the contract. The small model states the expected
193behavior. The production driver and comparison check whether the implementation
194refines the model for the exercised histories and observations. If a change
195revises one of these contracts, update all three in the same pull request. Do not update only the assertions to match new production output.
196
197## Table of Contents
198
1991. [Type Safety](#type-safety)
2002. [Code Organization](#code-organization)
2013. [Algorithm Efficiency](#algorithm-efficiency)
2024. [Semantic Correctness](#semantic-correctness)
2035. [Abstraction Design](#abstraction-design)
2046. [Code Clarity](#code-clarity)
2057. [Testing Requirements](#testing-requirements)
2068. [Function Design](#function-design)
2079. [Modern JavaScript Patterns](#modern-javascript-patterns)
20810. [Edge Cases and Corner Cases](#edge-cases-and-corner-cases)
20911. [Git and PR Hygiene](#git-and-pr-hygiene)
21012. [Code Weight and Fail-Fast Design](#code-weight-and-fail-fast-design)
211
212## Type Safety
213
214### Avoid `any` Types
215
216**❌ Bad:**
217
218```typescript
219function processData(data: any) {
220 return data.value
221}
222
223const result: any = someOperation()
224```
225
226**✅ Good:**
227
228```typescript
229function processData(data: unknown) {
230 if (isDataObject(data)) {
231 return data.value
232 }
233 throw new Error('Invalid data')
234}
235
236const result: TQueryData = someOperation()
237```
238
239**Key Principles:**
240
241- Use `unknown` instead of `any` when the type is truly unknown
242- Provide proper type annotations for return values
243- Use type guards to narrow `unknown` types safely
244- If you find yourself using `any`, question whether there's a better type
245
246## Code Organization
247
248### Extract Common Logic
249
250**❌ Bad:**
251
252```typescript
253// Duplicated logic in multiple places
254function processA() {
255 const key = typeof value === 'number' ? `__number__${value}` : String(value)
256 // ...
257}
258
259function processB() {
260 const key = typeof value === 'number' ? `__number__${value}` : String(value)
261 // ...
262}
263```
264
265**✅ Good:**
266
267```typescript
268function serializeKey(value: string | number): string {
269 return typeof value === 'number' ? `__number__${value}` : String(value)
270}
271
272function processA() {
273 const key = serializeKey(value)
274 // ...
275}
276
277function processB() {
278 const key = serializeKey(value)
279 // ...
280}
281```
282
283### Organize Utilities
284
285**Key Principles:**
286
287- Extract serialization/deserialization logic into utility files
288- When you see identical or near-identical code blocks, extract to a helper function
289- Prefer small, focused utility functions over large inline implementations
290- Move reusable logic into utility modules (e.g., `utils/`, `helpers/`)
291
292### Function Size and Complexity
293
294**❌ Bad:**
295
296```typescript
297function syncData() {
298 // 200+ lines of logic handling multiple concerns
299 // - snapshot phase
300 // - buffering
301 // - sync state management
302 // - error handling
303 // all inline...
304}
305```
306
307**✅ Good:**
308
309```typescript
310function syncData() {
311 handleSnapshotPhase()
312 manageBuffering()
313 updateSyncState()
314 handleErrors()
315}
316
317function handleSnapshotPhase() {
318 // Focused logic for snapshot phase
319}
320```
321
322**Key Principle:** If a function is massive, extract logical sections into separate functions. This improves readability and maintainability.
323
324## Algorithm Efficiency
325
326### Be Mindful of Time Complexity
327
328**❌ Bad: O(n²) Queue Processing:**
329
330```typescript
331// Processes elements in queue, but elements may need multiple passes
332while (queue.length > 0) {
333 const job = queue.shift()
334 if (hasUnmetDependencies(job)) {
335 queue.push(job) // Re-queue, causing O(n²) behavior
336 } else {
337 processJob(job)
338 }
339}
340```
341
342**✅ Good: Dependency-Aware Processing:**
343
344```typescript
345// Use a data structure that respects dependencies
346// Process only jobs with no unmet dependencies
347// Consider topological sort for DAG-like structures
348const readyJobs = jobs.filter((job) => !hasUnmetDependencies(job))
349readyJobs.forEach(processJob)
350```
351
352### Use Appropriate Data Structures
353
354**❌ Bad:**
355
356```typescript
357// O(n) lookup for each check
358const items = ['foo', 'bar', 'baz' /* hundreds more */]
359if (items.includes(searchValue)) {
360 // ...
361}
362```
363
364**✅ Good:**
365
366```typescript
367// O(1) lookup
368const items = new Set(['foo', 'bar', 'baz' /* hundreds more */])
369if (items.has(searchValue)) {
370 // ...
371}
372```
373
374**Key Principles:**
375
376- For membership checks on large collections, use `Set` instead of `Array.includes()`
377- Be aware of nested loops and their complexity implications
378- Consider the worst-case scenario, especially for operations that could process many items
379- Use appropriate data structures (Set for lookups, Map for key-value, etc.)
380
381## Semantic Correctness
382
383### Ensure Logic Matches Intent
384
385**❌ Bad:**
386
387```typescript
388// Intending to check if subset limit is more restrictive than superset
389function isLimitSubset(
390 subset: number | undefined,
391 superset: number | undefined,
392) {
393 return subset === undefined || superset === undefined || subset <= superset
394}
395
396// Problem: If subset has no limit but superset does, returns true (incorrect)
397```
398
399**✅ Good:**
400
401```typescript
402function isLimitSubset(
403 subset: number | undefined,
404 superset: number | undefined,
405) {
406 // Subset with no limit cannot be a subset of one with a limit
407 return superset === undefined || (subset !== undefined && subset <= superset)
408}
409```
410
411### Validate Intersections and Unions
412
413When merging predicates or combining queries, ensure the semantics are correct:
414
415**Example Problem:**
416
417```sql
418-- Query 1: WHERE age >= 18 LIMIT 1
419-- Query 2: WHERE age >= 20 LIMIT 3
420-- Naive intersection: WHERE age >= 20 LIMIT 1
421-- Problem: This may not return the actual intersection of results
422```
423
424**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.
425
426### Reject Multiple Copies of `@tanstack/db`
427
428TanStack DB does not support interoperability between multiple copies of
429`@tanstack/db` in one runtime.
430Each copy has its own transaction stack and IR classes. Do not add cross-copy
431expression support or shape-based fallbacks to make the copies interoperate.
432Keep the existing duplicate-instance check, which throws
433`DuplicateDbInstanceError` for duplicate development browser loads. Do not
434replace its error with a warning. SSR and test runners may evaluate the
435package twice without exchanging values; do not reject those independent
436loads or add per-value tracking solely to detect unsupported cross-copy use.
437
438## Abstraction Design
439
440### Avoid Leaky Abstractions
441
442**❌ Bad:**
443
444```typescript
445class Collection {
446 getViewKey(key: TKey): string {
447 // Caller needs to know internal representation
448 return `${this._state.viewKeyPrefix}${key}`
449 }
450}
451
452// Usage exposes internals
453const viewKey = collection.getViewKey(key)
454if (viewKey.startsWith(PREFIX)) {
455 /* ... */
456}
457```
458
459**✅ Good:**
460
461```typescript
462class Collection {
463 getViewKey(key: TKey): string {
464 // Delegate to state manager, hiding implementation
465 return this._state.getViewKey(key)
466 }
467}
468
469class CollectionStateManager {
470 getViewKey(key: TKey): string {
471 return `${this.viewKeyPrefix}${key}`
472 }
473}
474```
475
476**Key Principles:**
477
478- Encapsulate implementation details within the responsible class
479- Don't expose internal data structures or representations
480- Use delegation to maintain clean boundaries between components
481- Keep internal properties private when possible
482
483### Proper Encapsulation
484
485**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.
486
487## Code Clarity
488
489### Prefer Positive Predicates
490
491**❌ Bad:**
492
493```typescript
494if (!refs.some((ref) => ref.path[0] === outerAlias)) {
495 // treat as safe
496}
497```
498
499**✅ Good:**
500
501```typescript
502if (refs.every((ref) => ref.path[0] !== outerAlias)) {
503 // treat as safe
504}
505```
506
507**Key Principle:** Positive conditions (every, all) are generally easier to understand than negated conditions (not some).
508
509### Simplify Complex Conditions
510
511**❌ Bad:**
512
513```typescript
514const isLoadingNow = this.pendingLoadSubsetPromises.size > 0
515if (isLoadingNow && !isLoadingNow) {
516 // Confusing logic
517}
518```
519
520**✅ Good:**
521
522```typescript
523const wasLoading = this.pendingLoadSubsetPromises.size > 0
524this.pendingLoadSubsetPromises.add(promise)
525const isLoadingNow = this.pendingLoadSubsetPromises.size === 1
526
527if (isLoadingNow) {
528 // Started loading
529}
530```
531
532### Use Descriptive Names
533
534**❌ Bad:**
535
536```typescript
537const viewKeysMap = new Map() // Type in name is redundant
538const dependencyBuilders = [] // Sounds like functions that build
539```
540
541**✅ Good:**
542
543```typescript
544const viewKeys = new Map() // Data structure not in name
545const dependentBuilders = [] // Accurately describes dependents
546```
547
548**Key Principles:**
549
550- Avoid Hungarian notation (encoding type in variable name)
551- Use names that describe the role or purpose, not the data structure
552- Choose names that make the code read like prose
553- Prefer `dependentBuilders` over `dependencyBuilders` when referring to things that depend on something
554
555## Testing Requirements
556
557### Required reading: oracle tests
558
559Before designing, changing, or reviewing an oracle or generated-history test,
560read [Oracle Testing Rubric](docs/contributing/oracle-rubric.md).
561Use the [coverage map](docs/contributing/oracle-coverage.md) to find an existing
562owner and its limits before adding another model. The guide explains testing
563methods; it does not authorize new product behavior or retire existing laws.
564
565### Write Oracle Tests as Literate Programs
566
567Write every oracle and generated-history test as a literate program.
568Combine explanatory prose with executable code so the file teaches the
569subsystem contract. Follow
570[ORC-003](docs/contributing/oracle-rubric.md#orc-003-distinguishable-oracle-responsibilities)
571and the guide's
572[literate-oracle guidance](docs/contributing/oracle-rubric.md#write-the-oracle-as-executable-subsystem-documentation).
573
574Start with the promised law and its limits before introducing test mechanics.
575Explain the central law beside the independent model. Describe the legal
576history grammar, production path, public observations, and comparison checkpoint
577beside the relevant code. Keep the contract, model, history grammar, production
578driver, and refinement check distinguishable. Place their explanations close
579enough for a reviewer to compare them directly.
580
581Use the project glossary's terms and clear, direct prose. Explain why each
582observation follows from the model. Update the prose when the executable law
583changes. Code, headings, or a separate review report alone do not satisfy this
584requirement.
585
586Keep the prose proportional to the law. A compact oracle can use one opening
587comment and short explanations beside its code. A focused regression may remain
588short, but it does not waive this requirement for an oracle or replace
589applicable oracle coverage.
590
591### Always Add Tests for Bugs
592
593**Key Principle:** Reproduce a bug in a test before fixing it, then follow the
594[applicable oracle coverage requirements](#require-applicable-oracle-coverage).
595The evidence must show:
596
597- The bug is actually fixed
598- The bug doesn't regress in the future
599- The fix is validated
600
601**Example:**
602
603```typescript
604// Found a bug with fetchSnapshot resolving after up-to-date message
605// First isolate the failure in a focused regression:
606test('ignores snapshot that resolves after up-to-date message', async () => {
607 // Reproduce the corner case
608 // Verify it's handled correctly
609})
610
611// Then extend the applicable primary oracle so the law is exercised across
612// nearby legal histories.
613```
614
615### Treat Every Review Bug as a Test Gap
616
617When a reviewer agent confirms a bug, it must also ask why the existing tests
618did not catch it. The finding should name the missing test law, state
619transition, generator dimension, adapter boundary, or assertion. If a test or
620oracle should already have caught the bug, identify the false-green model,
621classifier, fixture, or assertion that let it pass. Use that analysis to suggest
622the smallest test or oracle improvement that would catch the same class of bug,
623not only the reported example.
624
625### Close the Declared Bug Class
626
627A passing reproduction fixes one trace; it does not establish that the bug
628class is closed. Before claiming closure, name the violated product law and
629bound the claim by legal histories, production paths, and public observations
630at specific checkpoints.
631
632Extend the primary oracle so it reaches the reported trace and nearby legal
633histories that distinguish the repair from plausible wrong designs. Use a
634separate oracle owner when another boundary needs a different model. Show that
635the check fails on the original implementation or a hostile mutant at the
636intended checkpoint, then passes with the fix.
637
638At closeout, state what the evidence covers. Record remaining in-scope
639histories or paths in the oracle coverage map with an owner and needed witness.
640A reachable in-scope counterexample keeps the class open. Passing random runs
641is not a universal proof. A bug-fix pull request is not ready while a known
642in-scope part of the declared bug class remains open.
643
644Every bug-fix pull request must show how it evaluated and closed the declared
645bug class. State the violated law and its authority. Name the legal histories,
646production paths, and public observation checkpoints that the oracle exercises.
647Include the original or hostile-mutant RED result and the repaired GREEN result.
648State any remaining limits. A passing reproduction for one trace does not
649satisfy this requirement.
650
651### Keep Oracles Independent
652
653An oracle is useful only when its expected result comes from a source independent
654of the implementation under test. Do not translate production branches, state
655machines, classifiers, or helper functions into a second implementation and call
656that an oracle. Both copies can encode the same wrong assumption.
657
658- Derive expected behavior from public contracts, documented prior behavior,
659 mathematical laws, or a separately specified reference model.
660- Keep the reference model structurally different from production. Do not import
661 the production helper or reuse its classifications to compute expected results.
662- Preserve existing contract tests unless a product or design decision explicitly
663 changes the contract. Rewriting a passing expectation to match new production
664 behavior is a design review, not routine test maintenance.
665- When production work suggests an oracle change, compare the old and new
666 semantics with counterexamples before editing the oracle.
667- Use hostile mutants to prove the oracle rejects plausible wrong designs,
668 including the mistake production currently makes. A green oracle without a
669 demonstrated kill is weak evidence.
670- Use process grammar to explore lifecycle paths, and design grammar to challenge
671 the oracle's reference semantics. More generated traces cannot repair a wrong
672 reference model.
673
674### Require Applicable Oracle Coverage
675
676An oracle that checks general laws across generated states and histories is a
677stronger form of coverage than a unit test for one specific example. Every
678production change that adds, removes, or changes observable behavior must
679extend the primary oracle when that oracle can express the governing law. Add
680the missing model rule, generator dimension, state transition, or observable
681assertion; adding more pinned examples alone does not generalize the oracle. Do
682not submit only an isolated unit test for behavior owned by an applicable
683oracle. An internal refactor does not require new oracle coverage when existing
684applicable oracles already exercise the unchanged contract.
685
686Applicability follows the contract ownership recorded in
687`docs/contributing/oracle-coverage.md`, not the limits of the owner's current
688histories, production paths, or observations. A missing history, path, or
689observation is a coverage gap in the primary owner. Add a separate oracle owner
690only when the boundary requires a different independent judgment. Add a
691receiving witness when a claim crosses an adapter, framework, provider, or other
692integration boundary.
693
694For a bug fix, use a focused regression to isolate and shrink the failure, then
695keep it as a replay example for the broader oracle. Verify that the expanded
696oracle fails without the fix and passes with it. Keep valuable unit tests as
697supplemental coverage, but do not treat them as a substitute for applicable
698oracle coverage. If no existing oracle applies, create one when the behavior
699admits a practical independent model. For a change that is not a bug fix, a
700focused test alone is acceptable only when an oracle is not practical for the
701behavior. The pull request must identify the relevant coverage-map entry and
702explain why extending its owner, creating a new independent oracle, or adding a
703receiving witness is not practical. Bug fixes cannot use this focused-test-only
704exception. They must provide evidence that closes the entire declared bug class.
705
706### Keep Unit Tests Out of Oracles
707
708Oracle files contain reusable laws, independent models, input or history
709grammars, shared comparisons, and their execution. Do not put ordinary unit
710tests or concrete type assertions in an oracle file. A filename, coverage-map
711entry, contract comment, or table of fixtures does not turn examples into an
712oracle.
713
714Keep a fixed regression as input to the same model, production driver, and
715comparison that the generated campaign uses. It must not carry a separate
716expected answer or its own assertions. Checker calibration may supply a wrong
717observation to that same comparison. Put supplemental unit tests in ordinary
718test files; they do not discharge an oracle-owned coverage obligation.
719
720For compile-time contracts, generate legal TypeScript inputs and check their
721public types against a reusable independent type law. A list of
722`expectTypeOf` calls or `@ts-expect-error` examples is not an oracle. Negative
723checks derived by the shared law from generated inputs are permitted.
724
725### Name Oracle Files for Discovery
726
727Include `oracle` in filenames that own an independent reference computation,
728state model, differential or metamorphic comparison, or reusable law checker.
729Modules that define the model, checker, or its history grammar also qualify.
730Identify the actual mechanism before renaming a file. A coverage-map entry,
731contract comment, or collection of fixed assertions is not sufficient evidence.
732
733An oracle file holds only oracle tests. It declares its check, model, and history
734grammar with `declareOracle` from `packages/db/tests/oracle-declaration.ts`. A
735type-level oracle names its model types in `typeModel`. Each
736part is optional. Every test in the file must use a declared part, directly
737or through a driver, or run a generated property that states its law inline.
738A test that compares production with a hand-written value is a unit test:
739put it in an ordinary test file. The `oracle/no-unit-test` lint rule reports
740a test that does neither.
741
742Ordinary example tests, type assertions, fixtures, registration wrappers, and
743runner utilities keep their ordinary names. A module that only drives production
744or records observations is not an oracle definition. Report oracle owners and
745definitions separately from supporting files; a file count is not an oracle count.
746Preserve runner suffixes and update imports, commands, replay selectors, and
747current documentation whenever an oracle file moves.
748
749### Name Tests After Behavior
750
751Test names should state the behavior they prove. Do not put issue or pull
752request numbers in test names; those references become stale and make the test
753suite harder to read. When an external report contains essential context that
754the test cannot express, link it in a nearby comment instead.
755
756### Test Corner Cases
757
758Common corner cases to consider:
759
760- Empty arrays or sets
761- Single-element collections
762- `undefined` vs `null` values
763- Operations on already-resolved promises
764- Race conditions between async operations
765- Limit/offset edge cases (0, 1, very large numbers)
766- IN predicates with 0 or 1 elements
767
768## Function Design
769
770### Prefer Explicit Parameters Over Closures
771
772**❌ Bad:**
773
774```typescript
775function outer() {
776 const config = getConfig()
777 const state = getState()
778
779 const updateFn = () => {
780 // Closes over config and state
781 applyUpdate(config, state)
782 }
783
784 scheduler.schedule(updateFn)
785}
786```
787
788**✅ Good:**
789
790```typescript
791function updateEntry(entry: Entry, config: Config, state: State) {
792 applyUpdate(entry, config, state)
793}
794
795function outer() {
796 const config = getConfig()
797 const state = getState()
798
799 scheduler.schedule({
800 config,
801 state,
802 update: updateEntry,
803 })
804}
805```
806
807**Key Principles:**
808
809- Functions that take dependencies as arguments are easier to test
810- Explicit parameters make data flow clearer
811- Closures can hide dependencies and make code harder to follow
812- Use closures when they genuinely simplify the code, but be intentional
813
814### Return Type Precision
815
816**❌ Bad:**
817
818```typescript
819function serializeKey(key: string | number): unknown {
820 return String(key)
821}
822```
823
824**✅ Good:**
825
826```typescript
827function serializeKey(key: string | number): string {
828 return String(key)
829}
830```
831
832**Key Principle:** Always provide the most precise return type. Avoid `unknown` or `any` return types unless truly necessary.
833
834## Modern JavaScript Patterns
835
836### Use Modern Operators
837
838**❌ Bad:**
839
840```typescript
841if (firstError === undefined) {
842 firstError = error
843}
844
845const value = cached !== null && cached !== undefined ? cached : defaultValue
846
847if (obj[key] === undefined) {
848 obj[key] = value
849}
850```
851
852**✅ Good:**
853
854```typescript
855firstError ??= error
856
857const value = cached ?? defaultValue
858
859obj[key] ??= value
860```
861
862### Use Spread Operator
863
864**❌ Bad:**
865
866```typescript
867const combined = []
868for (const item of currentItems) {
869 combined.push(item)
870}
871for (const item of newItems) {
872 combined.push(item)
873}
874```
875
876**✅ Good:**
877
878```typescript
879const combined = [...currentItems, ...newItems]
880```
881
882### Simplify Array Operations
883
884**❌ Bad:**
885
886```typescript
887const filtered = []
888for (const item of items) {
889 if (item.value > 0) {
890 filtered.push(item)
891 }
892}
893```
894
895**✅ Good:**
896
897```typescript
898const filtered = items.filter((item) => item.value > 0)
899```
900
901## Edge Cases and Corner Cases
902
903### Common Patterns to Consider
904
9051. **Key Encoding**: When converting keys to strings, ensure no collisions
906
907 ```typescript
908 // ❌ Bad: numeric 1 and string "__number__1" collide
909 const key = typeof val === 'number' ? `__number__${val}` : String(val)
910
911 // ✅ Good: proper encoding with type prefix
912 const key = `${typeof val}_${String(val)}`
913 ```
914
9152. **Subset/Superset Logic**: Consider all cases
916
917 ```typescript
918 // Consider: IN with 0, 1, or many elements
919 // Consider: EQ vs IN predicates
920 // Consider: Range predicates (>=, <=) vs equality
921 ```
922
9233. **Limit and Offset**: Handle undefined, 0, and edge values
924
925 ```typescript
926 // What happens when limit is 0?
927 // What happens when offset exceeds data length?
928 // What happens when limit is undefined?
929 ```
930
9314. **Optional vs Required**: Be explicit about optionality
932
933 ```typescript
934 // ❌ Why is this optional?
935 interface Config {
936 collection?: Collection
937 }
938
939 // ✅ Document or make required if always needed
940 interface Config {
941 collection: Collection // Always required for query collections
942 }
943 ```
944
9455. **Race Conditions**: Async operations may resolve in unexpected order
946 ```typescript
947 // Request snapshot before receiving up-to-date
948 // But snapshot resolves after up-to-date arrives
949 // Should ignore the stale snapshot
950 ```
951
952## Git and PR Hygiene
953
954### Never Rewrite Published Branch History
955
956**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`.
957
958Once 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.
959
960**❌ Bad:**
961
962```bash
963git commit --amend --no-edit
964git push --force-with-lease
965```
966
967**✅ Good:**
968
969```bash
970git add <files>
971git commit -m "fix: address CI failure"
972git push
973```
974
975**Key Principles:**
976
977- Never force-push unless the user explicitly asks for it in that moment.
978- Do not assume `--force-with-lease` is acceptable; it still rewrites shared history.
979- Prefer small follow-up commits over rewritten history on PR branches.
980- If a clean history is desired, let the human maintainer squash or rebase during merge.
981- If you think history rewriting is necessary, stop and ask for explicit confirmation before running any command.
982
983## Package Versioning
984
985### Understand Semantic Versioning
986
987**Common Mistake:**
988
989```json
990{
991 "dependencies": {
992 "package": "^0.0.0"
993 }
994}
995```
996
997**Problem:** `^0.0.0` restricts to exactly `0.0.0`, not "latest 0.0.x" as you might expect.
998
999From [npm semver docs](https://github.com/npm/node-semver):
1000
1001> Caret Ranges allow changes that do not modify the left-most non-zero element. For versions `0.0.X`, this means no updates.
1002
1003**Solutions:**
1004
1005- Use `*` for any version
1006- Use `latest` for the latest version
1007- Use a proper range like `^0.1.0` if that's what you mean
1008
1009## Documentation and Comments
1010
1011### Keep Useful Comments
1012
1013**Good Comment:**
1014
1015```typescript
1016// Returning false signals that callers should schedule another pass
1017return allDone
1018```
1019
1020**Good Comment:**
1021
1022```typescript
1023// This step is necessary because the query function has captured
1024// the old subscription instance in its closure
1025```
1026
1027### Remove Outdated Comments
1028
1029**Key Principle:** When refactoring code, update or remove comments that reference old function names or outdated logic.
1030
1031## Code Weight and Fail-Fast Design
1032
1033Treat production code as a continuing cost. Bug fixes and features should aim
1034for a net-negative production diff. Pay for new behavior by
1035refactoring the existing code it touches: merge duplicated logic and parallel
1036structures, delete indirection, and remove branches that the change makes
1037redundant. Refactoring existing code is the expected way to fix a bug or add a
1038feature. Do not graft new code onto a design and leave the old code in place.
1039
1040Measure production code weight in shipped bytes, not lines. Run
1041`pnpm size:compare` (add `--files` for a per-file breakdown). It builds the
1042changed packages with the same minified build that the Compressed size CI
1043check uses, bundles each one as an app's production build would, and
1044compares gzip and brotli bytes with the merge-base on `origin/main`.
1045Development-only code, such as full error messages, does not count.
1046A package bundle keeps every export, so `size:compare` also reports
1047scenarios in `scripts/size-scenarios/`, each tree-shaken as an app ships it.
1048`app` is the typical app: a query collection, a filtered live query, and the
1049React adapter. Its weight reaches nearly every user, so weigh it most. Each
1050other scenario adds one feature to `app`, and its feature-cost column shows
1051what that feature adds. Comments, names, and formatting cost nothing in that measure, so
1052keep useful comments and clear names. Never delete a comment, shorten a name,
1053or reformat code to improve a code-weight number. Reduce states, branches,
1054helpers, and recovery paths.
1055
1056When a change still grows production bytes after that work, state why. Name
1057the refactors you tried and the evidence that ruled them out.
1058
1059Tests and contract documentation can grow to prove the behavior. Report their
1060weight separately from production code.
1061
1062Use the test-first and bug-class guidance above to reproduce the failure and
1063identify the violated contract. Strengthen or simplify existing control flow
1064before adding state or recovery machinery.
1065
1066### Separate Valid Edge Cases from Contract Contradictions
1067
1068A rare but valid operation is not an invariant violation. The implementation
1069must support it.
1070
1071An impossible internal state or a contradictory collaborator signal is an
1072invariant violation. Throw or reject immediately at the boundary. Check the
1073invariant before the code releases established state or publishes success.
1074
1075Do not convert an invariant violation into false readiness, partial success,
1076or a silent fallback. In library code, "crash" means a synchronous throw or a
1077rejected promise. It does not require process termination.
1078
1079### Recovery Must Earn Its Code Weight
1080
1081Add retries, generations, queues, fallback states, or rollback paths only when
1082all these conditions are true:
1083
1084- The condition can occur during valid operation.
1085- The public contract defines recovery behavior.
1086- Recovery protects user-visible behavior.
1087- A test or oracle proves the recovery law.
1088
1089If a condition requires a programming error or contract breach, detect it and
1090fail loudly. Do not build a second lifecycle to recover from it.
1091
1092Prefer a small change to the current abstraction over a replacement state
1093machine. A new state machine requires an explicit architectural reason and an
1094oracle law that the existing design cannot express.
1095
1096For reviewer-proposed defensive machinery based only on contradictory mocks,
1097add an invariant witness that fails before mutation instead.
1098
1099## General Principles
1100
11011. **Question Optionality**: If a property is optional, understand why. Often it should be required.
1102
11032. **Consider Performance**: Before implementing, think about time complexity, especially for operations that might process many items.
1104
11053. **Validate Semantics**: Ensure that your implementation actually does what you think it does. Consider edge cases.
1106
11074. **Avoid Premature Complexity**: Don't add ternaries, special cases, or checks for things that can't happen.
1108
11095. **Test First for Bugs**: Reproduce bugs in tests before fixing them.
1110
11116. **Be Consistent**: Follow naming conventions and patterns used elsewhere in the codebase.
1112
11137. **Simplify**: Modern JavaScript provides many concise operators and methods. Use them.
1114
11158. **Encapsulate**: Hide implementation details. Use delegation and proper abstraction boundaries.
1116
11179. **Type Precisely**: Use the most specific type possible. Avoid `any`.
1118
111910. **Extract When Duplicating**: If you're writing the same logic twice, extract it.
1120
1121## When in Doubt
1122
1123If you're unsure about an implementation decision:
1124
11251. Look for similar patterns in the existing codebase
11262. Consider the worst-case scenario for performance
11273. Think about edge cases and corner cases
11284. Ask: "Does this abstraction leak implementation details?"
11295. Ask: "Would this be easy to test?"
11306. Ask: "Is this as simple as it could be?"
1131
1132Remember: 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.