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 [Oracle Testing Rubric](docs/contributing/oracle-rubric.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-rubric.md#orc-003-distinguishable-oracle-responsibilities)
456and the guide's
457[literate-oracle guidance](docs/contributing/oracle-rubric.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, then follow the
479[applicable oracle coverage requirements](#require-applicable-oracle-coverage).
480The evidence must show:
481
482- The bug is actually fixed
483- The bug doesn't regress in the future
484- The fix is validated
485
486**Example:**
487
488```typescript
489// Found a bug with fetchSnapshot resolving after up-to-date message
490// First isolate the failure in a focused regression:
491test('ignores snapshot that resolves after up-to-date message', async () => {
492 // Reproduce the corner case
493 // Verify it's handled correctly
494})
495
496// Then extend the applicable primary oracle so the law is exercised across
497// nearby legal histories.
498```
499
500### Treat Every Review Bug as a Test Gap
501
502When a reviewer agent confirms a bug, it must also ask why the existing tests
503did not catch it. The finding should name the missing test law, state
504transition, generator dimension, adapter boundary, or assertion. If a test or
505oracle should already have caught the bug, identify the false-green model,
506classifier, fixture, or assertion that let it pass. Use that analysis to suggest
507the smallest test or oracle improvement that would catch the same class of bug,
508not only the reported example.
509
510### Close the Declared Bug Class
511
512A passing reproduction fixes one trace; it does not establish that the bug
513class is closed. Before claiming closure, name the violated product law and
514bound the claim by legal histories, production paths, and public observations
515at specific checkpoints.
516
517Extend the primary oracle so it reaches the reported trace and nearby legal
518histories that distinguish the repair from plausible wrong designs. Use a
519separate oracle owner when another boundary needs a different model. Show that
520the check fails on the original implementation or a hostile mutant at the
521intended checkpoint, then passes with the fix.
522
523At closeout, state what the evidence covers. Record remaining in-scope
524histories or paths in the oracle coverage map with an owner and needed witness.
525A reachable in-scope counterexample keeps the class open. Passing random runs
526is not a universal proof. A bug-fix pull request is not ready while a known
527in-scope part of the declared bug class remains open.
528
529Every bug-fix pull request must show how it evaluated and closed the declared
530bug class. State the violated law and its authority. Name the legal histories,
531production paths, and public observation checkpoints that the oracle exercises.
532Include the original or hostile-mutant RED result and the repaired GREEN result.
533State any remaining limits. A passing reproduction for one trace does not
534satisfy this requirement.
535
536### Keep Oracles Independent
537
538An oracle is useful only when its expected result comes from a source independent
539of the implementation under test. Do not translate production branches, state
540machines, classifiers, or helper functions into a second implementation and call
541that an oracle. Both copies can encode the same wrong assumption.
542
543- Derive expected behavior from public contracts, documented prior behavior,
544 mathematical laws, or a separately specified reference model.
545- Keep the reference model structurally different from production. Do not import
546 the production helper or reuse its classifications to compute expected results.
547- Preserve existing contract tests unless a product or design decision explicitly
548 changes the contract. Rewriting a passing expectation to match new production
549 behavior is a design review, not routine test maintenance.
550- When production work suggests an oracle change, compare the old and new
551 semantics with counterexamples before editing the oracle.
552- Use hostile mutants to prove the oracle rejects plausible wrong designs,
553 including the mistake production currently makes. A green oracle without a
554 demonstrated kill is weak evidence.
555- Use process grammar to explore lifecycle paths, and design grammar to challenge
556 the oracle's reference semantics. More generated traces cannot repair a wrong
557 reference model.
558
559### Require Applicable Oracle Coverage
560
561An oracle that checks general laws across generated states and histories is a
562stronger form of coverage than a unit test for one specific example. Every
563production change that adds, removes, or changes observable behavior must
564extend the primary oracle when that oracle can express the governing law. Add
565the missing model rule, generator dimension, state transition, or observable
566assertion; adding more pinned examples alone does not generalize the oracle. Do
567not submit only an isolated unit test for behavior owned by an applicable
568oracle. An internal refactor does not require new oracle coverage when existing
569applicable oracles already exercise the unchanged contract.
570
571Applicability follows the contract ownership recorded in
572`docs/contributing/oracle-coverage.md`, not the limits of the owner's current
573histories, production paths, or observations. A missing history, path, or
574observation is a coverage gap in the primary owner. Add a separate oracle owner
575only when the boundary requires a different independent judgment. Add a
576receiving witness when a claim crosses an adapter, framework, provider, or other
577integration boundary.
578
579For a bug fix, use a focused regression to isolate and shrink the failure, then
580keep it as a replay example for the broader oracle. Verify that the expanded
581oracle fails without the fix and passes with it. Keep valuable unit tests as
582supplemental coverage, but do not treat them as a substitute for applicable
583oracle coverage. If no existing oracle applies, create one when the behavior
584admits a practical independent model. For a change that is not a bug fix, a
585focused test alone is acceptable only when an oracle is not practical for the
586behavior. The pull request must identify the relevant coverage-map entry and
587explain why extending its owner, creating a new independent oracle, or adding a
588receiving witness is not practical. Bug fixes cannot use this focused-test-only
589exception. They must provide evidence that closes the entire declared bug class.
590
591### Name Oracle Files for Discovery
592
593Include `oracle` in filenames that own an independent reference computation,
594state model, differential or metamorphic comparison, or reusable law checker.
595Modules that define the model, checker, or its history grammar also qualify.
596Identify the actual mechanism before renaming a file. A coverage-map entry,
597contract comment, or collection of fixed assertions is not sufficient evidence.
598
599Ordinary example tests, type assertions, fixtures, registration wrappers, and
600runner utilities keep their ordinary names. A module that only drives production
601or records observations is not an oracle definition. Report oracle owners and
602definitions separately from supporting files; a file count is not an oracle count.
603Preserve runner suffixes and update imports, commands, replay selectors, and
604current documentation whenever an oracle file moves.
605
606### Name Tests After Behavior
607
608Test names should state the behavior they prove. Do not put issue or pull
609request numbers in test names; those references become stale and make the test
610suite harder to read. When an external report contains essential context that
611the test cannot express, link it in a nearby comment instead.
612
613### Test Corner Cases
614
615Common corner cases to consider:
616
617- Empty arrays or sets
618- Single-element collections
619- `undefined` vs `null` values
620- Operations on already-resolved promises
621- Race conditions between async operations
622- Limit/offset edge cases (0, 1, very large numbers)
623- IN predicates with 0 or 1 elements
624
625## Function Design
626
627### Prefer Explicit Parameters Over Closures
628
629**❌ Bad:**
630
631```typescript
632function outer() {
633 const config = getConfig()
634 const state = getState()
635
636 const updateFn = () => {
637 // Closes over config and state
638 applyUpdate(config, state)
639 }
640
641 scheduler.schedule(updateFn)
642}
643```
644
645**✅ Good:**
646
647```typescript
648function updateEntry(entry: Entry, config: Config, state: State) {
649 applyUpdate(entry, config, state)
650}
651
652function outer() {
653 const config = getConfig()
654 const state = getState()
655
656 scheduler.schedule({
657 config,
658 state,
659 update: updateEntry,
660 })
661}
662```
663
664**Key Principles:**
665
666- Functions that take dependencies as arguments are easier to test
667- Explicit parameters make data flow clearer
668- Closures can hide dependencies and make code harder to follow
669- Use closures when they genuinely simplify the code, but be intentional
670
671### Return Type Precision
672
673**❌ Bad:**
674
675```typescript
676function serializeKey(key: string | number): unknown {
677 return String(key)
678}
679```
680
681**✅ Good:**
682
683```typescript
684function serializeKey(key: string | number): string {
685 return String(key)
686}
687```
688
689**Key Principle:** Always provide the most precise return type. Avoid `unknown` or `any` return types unless truly necessary.
690
691## Modern JavaScript Patterns
692
693### Use Modern Operators
694
695**❌ Bad:**
696
697```typescript
698if (firstError === undefined) {
699 firstError = error
700}
701
702const value = cached !== null && cached !== undefined ? cached : defaultValue
703
704if (obj[key] === undefined) {
705 obj[key] = value
706}
707```
708
709**✅ Good:**
710
711```typescript
712firstError ??= error
713
714const value = cached ?? defaultValue
715
716obj[key] ??= value
717```
718
719### Use Spread Operator
720
721**❌ Bad:**
722
723```typescript
724const combined = []
725for (const item of currentItems) {
726 combined.push(item)
727}
728for (const item of newItems) {
729 combined.push(item)
730}
731```
732
733**✅ Good:**
734
735```typescript
736const combined = [...currentItems, ...newItems]
737```
738
739### Simplify Array Operations
740
741**❌ Bad:**
742
743```typescript
744const filtered = []
745for (const item of items) {
746 if (item.value > 0) {
747 filtered.push(item)
748 }
749}
750```
751
752**✅ Good:**
753
754```typescript
755const filtered = items.filter((item) => item.value > 0)
756```
757
758## Edge Cases and Corner Cases
759
760### Common Patterns to Consider
761
7621. **Key Encoding**: When converting keys to strings, ensure no collisions
763
764 ```typescript
765 // ❌ Bad: numeric 1 and string "__number__1" collide
766 const key = typeof val === 'number' ? `__number__${val}` : String(val)
767
768 // ✅ Good: proper encoding with type prefix
769 const key = `${typeof val}_${String(val)}`
770 ```
771
7722. **Subset/Superset Logic**: Consider all cases
773
774 ```typescript
775 // Consider: IN with 0, 1, or many elements
776 // Consider: EQ vs IN predicates
777 // Consider: Range predicates (>=, <=) vs equality
778 ```
779
7803. **Limit and Offset**: Handle undefined, 0, and edge values
781
782 ```typescript
783 // What happens when limit is 0?
784 // What happens when offset exceeds data length?
785 // What happens when limit is undefined?
786 ```
787
7884. **Optional vs Required**: Be explicit about optionality
789
790 ```typescript
791 // ❌ Why is this optional?
792 interface Config {
793 collection?: Collection
794 }
795
796 // ✅ Document or make required if always needed
797 interface Config {
798 collection: Collection // Always required for query collections
799 }
800 ```
801
8025. **Race Conditions**: Async operations may resolve in unexpected order
803 ```typescript
804 // Request snapshot before receiving up-to-date
805 // But snapshot resolves after up-to-date arrives
806 // Should ignore the stale snapshot
807 ```
808
809## Git and PR Hygiene
810
811### Never Rewrite Published Branch History
812
813**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`.
814
815Once 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.
816
817**❌ Bad:**
818
819```bash
820git commit --amend --no-edit
821git push --force-with-lease
822```
823
824**✅ Good:**
825
826```bash
827git add <files>
828git commit -m "fix: address CI failure"
829git push
830```
831
832**Key Principles:**
833
834- Never force-push unless the user explicitly asks for it in that moment.
835- Do not assume `--force-with-lease` is acceptable; it still rewrites shared history.
836- Prefer small follow-up commits over rewritten history on PR branches.
837- If a clean history is desired, let the human maintainer squash or rebase during merge.
838- If you think history rewriting is necessary, stop and ask for explicit confirmation before running any command.
839
840## Package Versioning
841
842### Understand Semantic Versioning
843
844**Common Mistake:**
845
846```json
847{
848 "dependencies": {
849 "package": "^0.0.0"
850 }
851}
852```
853
854**Problem:** `^0.0.0` restricts to exactly `0.0.0`, not "latest 0.0.x" as you might expect.
855
856From [npm semver docs](https://github.com/npm/node-semver):
857
858> Caret Ranges allow changes that do not modify the left-most non-zero element. For versions `0.0.X`, this means no updates.
859
860**Solutions:**
861
862- Use `*` for any version
863- Use `latest` for the latest version
864- Use a proper range like `^0.1.0` if that's what you mean
865
866## Documentation and Comments
867
868### Keep Useful Comments
869
870**Good Comment:**
871
872```typescript
873// Returning false signals that callers should schedule another pass
874return allDone
875```
876
877**Good Comment:**
878
879```typescript
880// This step is necessary because the query function has captured
881// the old subscription instance in its closure
882```
883
884### Remove Outdated Comments
885
886**Key Principle:** When refactoring code, update or remove comments that reference old function names or outdated logic.
887
888## Code Weight and Fail-Fast Design
889
890Treat each line of production code as a continuing cost. Bug fixes and
891features should aim for a net-negative production diff. Pay for new behavior by
892refactoring the existing code it touches: merge duplicated logic and parallel
893structures, delete indirection, and remove branches that the change makes
894redundant. Refactoring existing code is the expected way to fix a bug or add a
895feature. Do not graft new code onto a design and leave the old code in place.
896
897When a change still grows production code after that work, state why. Name
898the refactors you tried and the evidence that ruled them out.
899
900Tests and contract documentation can grow to prove the behavior. Report their
901weight separately from production code. Do not compress code or weaken names
902to reduce a line count. Reduce states, branches, helpers, and recovery paths.
903
904Use the test-first and bug-class guidance above to reproduce the failure and
905identify the violated contract. Strengthen or simplify existing control flow
906before adding state or recovery machinery.
907
908### Separate Valid Edge Cases from Contract Contradictions
909
910A rare but valid operation is not an invariant violation. The implementation
911must support it.
912
913An impossible internal state or a contradictory collaborator signal is an
914invariant violation. Throw or reject immediately at the boundary. Check the
915invariant before the code releases established state or publishes success.
916
917Do not convert an invariant violation into false readiness, partial success,
918or a silent fallback. In library code, "crash" means a synchronous throw or a
919rejected promise. It does not require process termination.
920
921### Recovery Must Earn Its Code Weight
922
923Add retries, generations, queues, fallback states, or rollback paths only when
924all these conditions are true:
925
926- The condition can occur during valid operation.
927- The public contract defines recovery behavior.
928- Recovery protects user-visible behavior.
929- A test or oracle proves the recovery law.
930
931If a condition requires a programming error or contract breach, detect it and
932fail loudly. Do not build a second lifecycle to recover from it.
933
934Prefer a small change to the current abstraction over a replacement state
935machine. A new state machine requires an explicit architectural reason and an
936oracle law that the existing design cannot express.
937
938For reviewer-proposed defensive machinery based only on contradictory mocks,
939add an invariant witness that fails before mutation instead.
940
941## General Principles
942
9431. **Question Optionality**: If a property is optional, understand why. Often it should be required.
944
9452. **Consider Performance**: Before implementing, think about time complexity, especially for operations that might process many items.
946
9473. **Validate Semantics**: Ensure that your implementation actually does what you think it does. Consider edge cases.
948
9494. **Avoid Premature Complexity**: Don't add ternaries, special cases, or checks for things that can't happen.
950
9515. **Test First for Bugs**: Reproduce bugs in tests before fixing them.
952
9536. **Be Consistent**: Follow naming conventions and patterns used elsewhere in the codebase.
954
9557. **Simplify**: Modern JavaScript provides many concise operators and methods. Use them.
956
9578. **Encapsulate**: Hide implementation details. Use delegation and proper abstraction boundaries.
958
9599. **Type Precisely**: Use the most specific type possible. Avoid `any`.
960
96110. **Extract When Duplicating**: If you're writing the same logic twice, extract it.
962
963## When in Doubt
964
965If you're unsure about an implementation decision:
966
9671. Look for similar patterns in the existing codebase
9682. Consider the worst-case scenario for performance
9693. Think about edge cases and corner cases
9704. Ask: "Does this abstraction leak implementation details?"
9715. Ask: "Would this be easy to test?"
9726. Ask: "Is this as simple as it could be?"
973
974Remember: 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.