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