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