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