Awesome Reviewers
Review and verification techniques for code, one place to browse them. Every reviewer instruction comes from a real review discussion in a production repository.
- Agentic explorationAn agent with read, search and run tools investigates a change: follows a suspicion across files, runs code, and returns findings with evidence.Verification catalog3 sub-techniques
- Alert deduplication and triageGroups related production alerts and errors and ranks them so investigation starts with the most impactful.Verification catalog2 sub-techniques
- API compatibility checkingDiffs a public interface between the base and the change and reports breaking changes: removed endpoints, changed types, narrowed inputs.Verification catalog3 sub-techniques
- Attack surface inventoryLists every entry point and trust boundary: API endpoints, webhooks, queues, schedulers, parsers, CLIs, third-party scripts, model calls.Verification catalog5 sub-techniques
- Change intent extractionStates what the change is meant to do, from title, description, commits and linked ticket, so every later check can ask whether a finding is in scope.Verification catalog2 sub-techniques
- CI failure analysisReads failing CI runs, separates real failures from flaky ones, and maps each to the job, step and change that caused it.Verification catalog2 sub-techniques
- CI workflow lintingChecks CI definitions themselves: syntax, script injection through untrusted inputs, over-broad token permissions, unpinned actions.Verification catalog2 sub-techniques
- Commit and pull request hygieneRules on the change itself rather than the code: commit message format, PR description, size limits, required labels or linked tickets.Verification catalog2 sub-techniques
- Complexity limitsMeasures cyclomatic complexity, function length and nesting and fails when a change pushes a function past a limit.Verification catalog2 sub-techniques
- Concurrency model checkingExplores thread interleavings systematically to find races and orderings that fail only rarely.Verification catalog2 sub-techniques
- Confidence calibrationMaps a reviewer's confidence to the observed rate of accepted findings and sets the posting threshold from that curve.Verification catalog2 sub-techniques
- Convention and guideline reviewChecks a change against the repository's written rules: style guides, AGENTS.md, architecture decisions, naming conventions.Verification catalog3 sub-techniques
- Data and control flow analysisBuilds a code property graph or interprocedural model to answer reachability questions: can this null reach that dereference, which callers reach this function.Verification catalog3 sub-techniques
- Dependency auditMatches dependencies against advisory databases and license policy, and fails on known-vulnerable or disallowed packages.Verification catalog3 sub-techniques
- Dependency risk assessmentJudges a new dependency beyond known CVEs: maintenance, project security practices and signs of a malicious package.Verification catalog2 sub-techniques
- Design conformanceCompares the rendered UI with the design it implements and reports layout, spacing, colour and copy differences.Verification catalog2 sub-techniques
- Developer feedback captureRecords how developers respond to findings (fixed, dismissed, argued) and the sentiment of replies, as the ground truth for every other loop.Verification catalog2 sub-techniques
- Documentation buildBuilds documentation as a check so broken cross-references, links and markup fail like code.Verification catalog3 sub-techniques
- Duplicate code detectionFinds copied blocks so a fix in one copy is not missed in the others, and flags new code that re-implements an existing helper.Verification catalog2 sub-techniques
- Dynamic security testingAttacks a running instance: crawls endpoints and sends payloads to confirm injection, misconfiguration and exposure.Verification catalog2 sub-techniques
- End-to-end browser testsDrives a real browser through user flows to catch breakage across components, routing and the network.Verification catalog2 sub-techniques
- Evidence-backed verificationRe-checks each finding against the code before it is shown: look for counterevidence, require proof, and refute or suppress what does not hold.Verification catalog4 sub-techniques
- Exposure verificationConfirms which weaknesses are reachable from outside: external asset discovery and targeted checks against deployed endpoints.Verification catalog2 sub-techniques
- External contract verificationChecks claims about third-party behaviour (an API can return null, a library throws) against authoritative documentation, and grades how strong that proof is.Verification catalog2 sub-techniques
- File hygieneCheap checks on files as files: valid syntax for config formats, no merge markers, no trailing whitespace, no oversized or binary blobs.Verification catalog3 sub-techniques
- Finding deduplicationMerges findings that describe the same problem from different reviewers, files or runs into one.Verification catalog3 sub-techniques
- FormattingA formatter rewrites code to one layout so diffs show only real changes; in CI it runs in check mode and fails on drift.Verification catalog3 sub-techniques
- Functional spec verificationRuns the application and checks each functional requirement in a browser, returning met, partially met, not met or unverifiable with screenshot evidence.Verification catalog2 sub-techniques
- FuzzingFeeds coverage-guided random input to parsers and decoders to find crashes, panics and hangs.Verification catalog3 sub-techniques
- LintingRule-based detection of bug-prone patterns, unused code and conventions the formatter does not cover.Verification catalog3 sub-techniques
- LLM application security reviewReviews code that calls models for the OWASP Top 10 for LLM applications: prompt injection, output handling, excessive agency, unbounded consumption.Verification catalog3 sub-techniques
- Lockfile consistencyFails when the lockfile no longer matches the manifest, so CI installs exactly what was reviewed.Verification catalog2 sub-techniques
- Logic and correctness reviewReads the change for wrong behaviour: off-by-one, inverted conditions, missed error paths, broken invariants, race conditions.Verification catalog3 sub-techniques
- Merge readinessCombines checks, reviews, open threads and findings into one verdict on whether a change can merge.Verification catalog2 sub-techniques
- Missed bug analysisFor each bug that escaped review, finds which technique should have caught it and why it did not, then clusters the causes.Verification catalog3 sub-techniques
- Mitigation mappingChecks whether each weakness is already mitigated by a control (validation, authorization middleware, rate limits) before reporting it.Verification catalog2 sub-techniques
- Mutation testingChanges the code on purpose and checks that some test fails; surviving mutants show tests that do not constrain behaviour.Verification catalog2 sub-techniques
- Noise budgetA fixed cap on how many findings are posted per change, filled in severity order, so the important ones are read.Verification catalog2 sub-techniques
- Output guardrailsValidates what an automated reviewer or fixer produces before it is posted or committed: schema, policy and safety checks.Verification catalog2 sub-techniques
- Past discussion checkCompares a finding with earlier review discussions: a repeat of something already decided is suppressed, a regression of a fixed issue is raised.Verification catalog2 sub-techniques
- Path reachability checkDecides whether the triggering state can reach the flagged line on this code path, given guards, early returns and types.Verification catalog2 sub-techniques
- Plan and spec traceabilityChecks each requirement in a plan or specification against the implementation: done in this change, done elsewhere, or not started, with gaps graded by severity.Verification catalog2 sub-techniques
- Production error investigationInvestigates production errors from observability data, finds the responsible code and proposes a fix with a regression test.Verification catalog2 sub-techniques
- Proofs and specificationsSpecifies a protocol or algorithm and checks it exhaustively or proves it, catching design bugs before code exists.Verification catalog3 sub-techniques
- Property-based testsGenerates inputs and checks invariants that must hold for all of them, then shrinks failures to a minimal case.Verification catalog3 sub-techniques
- Reflection passA self-critique step where the reviewer re-reads its own findings with fresh context and keeps, revises or withdraws each.Verification catalog2 sub-techniques
- Review comment resolutionChecks whether a new commit actually addresses each open review comment before the thread is resolved.Verification catalog2 sub-techniques
- Review context retrievalCollects what a reviewer needs beyond the diff: callers, definitions, related tests, docs and repository rules.Verification catalog3 sub-techniques
- Review question checklistsA fixed bank of questions a reviewer must answer for a kind of change, ranked so the most relevant ones are asked first.Verification catalog3 sub-techniques
- Reviewer evaluationBenchmarks reviewers on labelled changes: did they find the known bugs, and how many findings were wrong.Verification catalog3 sub-techniques
- Reviewer optimizationTunes reviewer prompts and instructions against the evaluation set instead of by hand.Verification catalog2 sub-techniques
- Reviewer routingChooses which specialist reviewers, human or automated, apply to a change based on its files, topics and history.Verification catalog3 sub-techniques
- Reviewers learned from past reviewsMines a repository's review discussions for recurring feedback and turns each cluster into a reusable review instruction.Verification catalog4 sub-techniques
- Risk prioritizationOrders confirmed weaknesses by exposure, exploit likelihood and impact so fixes start where risk is highest.Verification catalog2 sub-techniques
- Sandboxed executionBuilds and runs the change in an isolated environment to confirm it installs, starts and passes its checks before anyone relies on it.Verification catalog2 sub-techniques
- SBOM and provenanceRecords what went into a build and signs it, so consumers can verify where an artifact came from and what it contains.Verification catalog2 sub-techniques
- Scope and relevance filteringKeeps only findings that belong to this change: on changed lines, within the PR's intent, and fixable without reworking unchanged code.Verification catalog3 sub-techniques
- Secret scanningFinds credentials and tokens in the working tree and in history before they are pushed or published.Verification catalog3 sub-techniques
- Security-focused reviewA reviewer that reads for exploitable behaviour across files: authorization gaps, injection through helpers, unsafe trust between services.Verification catalog3 sub-techniques
- Severity scoringScores a finding from separate evidence axes (impact, persistence, detectability, reachability, scope, certainty) instead of a single guess.Verification catalog5 sub-techniques
- SpellingFinds misspellings in identifiers, comments and documentation, where a typo becomes a public API or a search miss.Verification catalog2 sub-techniques
- Static application security testingFinds injection, unsafe APIs, weak crypto and tainted data reaching a sink without running the code.Verification catalog4 sub-techniques
- Symbolic executionExplores program paths with symbolic inputs and a solver to find inputs that violate an assertion.Verification catalog2 sub-techniques
- Ticket intent alignmentChecks a finding or a change against the linked ticket: behaviour the ticket declares intentional is not a bug, and requirements it lists must be present.Verification catalog2 sub-techniques
- Type checkingProves call sites and data shapes agree across modules: wrong types, unhandled null or None, signatures broken by a change.Verification catalog3 sub-techniques
- Undefined-behaviour detectionExecutes code under an interpreter or instrumentation that detects memory-safety and aliasing violations.Verification catalog2 sub-techniques
- Unit and integration testsExample-based tests that run the code and assert on behaviour, from single functions up to services with real dependencies.Verification catalog4 sub-techniques
- Version and platform matrixRuns the suite across runtime versions, operating systems and feature combinations you do not run locally.Verification catalog3 sub-techniques
- Visual regression testingCompares screenshots of rendered pages or components with approved baselines and reports pixel differences.Verification catalog2 sub-techniques
- Weakness discoveryFor each entry point, searches for the weakness classes that apply to it: injection, broken access control, SSRF, deserialization, path traversal.Verification catalog2 sub-techniques
- Canonical Documentation EntriesWhen adding or updating documentation entries (e.g., course/resource lists), use canonical metadata and URLs so links don’t break, don’t leak tracking, and render correctly.EbookFoundation/free-programming-books47 discussions
- documentation clarity standardsEnsure all React-related documentation, comments, and descriptions maintain high standards of clarity, accuracy, and consistency. This includes using proper grammar, consistent terminology, complete descriptions, and well-structured explanations.remix-run/react-router30 discussions
- Use runServerless utilityAll new tests must be written using the `runServerless` utility instead of legacy testing approaches. This utility provides a more reliable way to test functionality by replicating full command runs, ensuring that cross-dependent machinery works as expected in production.serverless/serverless25 discussions
- Complete locale translationsEnsure that all text strings in locale-specific files are properly translated into their respective languages. Leaving untranslated English text in non-English locale files creates an inconsistent user experience and reduces the effectiveness of localization efforts.RooCodeInc/Roo-Code25 discussions
- Configuration ownership and determinismSummary - Ensure configuration is explicit, owned by the correct component (application vs plugin), and deterministic so behavior is predictable and resumable.p-e-w/heretic25 discussions
- Fail-safe Error HandlingUse fail-safe error handling everywhere in long-running / retrying flows: cleanup must be guaranteed, state/cursors must follow the intended retry semantics, and errors must remain diagnosable.QwenLM/qwen-code24 discussions
- Consistent, descriptive identifiersChoose names that are specific, self-explanatory, and consistent with the rest of the codebase. Before introducing a new option, type, or generic parameter, search for existing analogous APIs and reuse their naming pattern instead of inventing a new one (e.g. use `headerName` because bearer-auth/JWT/JWK middleware already use it, instead of `header` or...HONOJS/HONO22 discussions
- Use environment variablesWhen working with configurations that require sensitive data (credentials, tokens, passwords), always use environment variables instead of hardcoding values directly in configuration files. This prevents sensitive information from being stored in version control systems, state files, or plan outputs.hashicorp/terraform21 discussions
- Redact credentials at export boundariesAny path by which data can leave the trust boundary — tracing/OTLP export, debug logs, error messages, DB persistence, cached results, or API responses — must pass through a shared sanitizer that scrubs credentials before the data is written, logged, or serialized. Treat this as a defense-in-depth problem, not a single regex: credentials appear as headers...promptfoo/promptfoo21 discussions
- Complete cache invalidation keysA cache is only as correct as its invalidation logic, and the recurring failure mode across these reviews is a cache key or dirtiness check that omits some dimension the cached value actually depends on. Examples seen repeatedly: a history-search cache keyed on directory identity but not on rows written by another connection; an embedding cache invalidated...can1357/oh-my-pi21 discussions
- Changelog entry conventionsChangelog entries follow a consistent, repo-wide convention, since many PRs were flagged for violating it: 1. **Placement**: New entries always go under `## [Unreleased]`, under the correct `### Added`/`### Changed`/`### Fixed`/`### Removed` subsection matching the nature of the change. Never add or edit content under an already-released version heading —...can1357/oh-my-pi21 discussions
- reduce complexity for readabilityPrioritize code readability by reducing complexity through better organization and clearer patterns. Use early returns to avoid deep nesting, extract methods to break down large functions, and choose appropriate data structures over generic ones.servo/servo20 discussions
- Trusted Error HandlingUse strict, non-silent error handling and evidence gating across CI scripts and publish steps—especially when untrusted inputs and reruns are involved.QwenLM/qwen-code20 discussions
- Test critical branchesWhen code adds/changes behavior (UI logic, URL rewriting, state-merge rules, keyboard/pointer guards, or error-recovery flows), ensure tests cover (1) the behavior itself (not just indirectly), (2) the negative guard cases that prevent regressions, and (3) the full interaction path users trigger.QwenLM/qwen-code20 discussions
- Secure Boundary EnforcementStandard: at every trust boundary, enforce security invariants in a way that cannot be skipped by flags, parsing edge cases, alternate code paths, or serialization differences.QwenLM/qwen-code20 discussions
- Explicit failure handlingEvery operation that can fail must have its failure path treated as deliberately as its success path. Three recurring gaps keep surfacing in review: 1. **Unhandled rejections/exceptions from "success" callbacks.** A `.then(onSuccess, onError)` only catches a rejection of the original promise, not a throw inside `onSuccess` itself; a bare `.then(fn)` on a...cline/cline20 discussions
- Prevent sensitive data exposureNever log or store sensitive information (passwords, tokens, secrets) in clear text. This common security vulnerability can lead to credential leaks and unauthorized access.bridgecrewio/checkov20 discussions
- Use descriptive namesChoose names that clearly convey purpose and intent rather than generic or ambiguous terms. Names should be specific enough to understand functionality without requiring additional context.strands-agents/sdk-python19 discussions
- Docstring StandardsApply a single documentation rule set across the codebase: - **Module/file docstring:** Each file should have a clear module-level docstring **before any imports**.TheAlgorithms/Python19 discussions
- Race-safe concurrent stateCode that spans multiple await points or acts on shared/long-lived state (sessions, locks, lifecycle refs, worktrees, caches) must never trust a snapshot taken before the suspension point, and must never assume a status flag alone stops concurrent work. Two concrete rules follow from the recurring bugs:can1357/oh-my-pi19 discussions
- API authentication requirementsEnsure all API documentation and code examples include proper authentication headers and clearly explain authentication requirements. As of Langflow v1.5, all API requests require a Langflow API key, even when `AUTO_LOGIN` is enabled. The only exceptions are MCP endpoints (`/v1/mcp`, `/v1/mcp-projects`, `/v2/mcp`) which don't require authentication...langflow-ai/langflow19 discussions
- Preserve API compatibility and semanticsWhen adding or modifying public request/response/app methods, preserve their documented types, return values, and behavior unless the change is explicitly scoped to a major version with a deprecation path. Examples: don't silently change `flatten` to `Array.prototype.flat` (different depth semantics) in a minor release, don't let `cookie.expires` accept a...expressjs/Express19 discussions
- configuration value consistencyEnsure configuration values follow consistent formats, use meaningful defaults, and accurately distinguish between required and optional fields across all documentation.traefik/traefik18 discussions
- Doc accuracy and conformanceRequire every documentation change to pass two gates: (1) strict doc-schema conformance, and (2) factual/behavioral accuracy against the implementation and shipped artifacts.nousresearch/hermes-agent18 discussions
- Use Sphinx cross-reference rolesWhen documentation or NEWS entries mention a Python identifier, RFC, or glossary term, use the matching Sphinx role instead of plain text or double backticks, so the reference becomes a clickable, validated link. Pick the role that matches the actual kind of object: `:mod:` for modules, `:func:` for module-level functions, `:meth:` for methods,...python/cpython18 discussions
- Actionable Error PropagationWhen handling failures, ensure your code (a) raises the right exception to control exit code/automation, (b) doesn’t silently ignore user intent or skip required checks, and (c) produces parameter-aware, actionable messages.Azure/azure-cli18 discussions
- Complete network configurationsNetwork configuration examples and documentation should include all essential networking components such as ports, protocols, timeouts, and security considerations. Incomplete configurations can lead to connection failures, security vulnerabilities, or unexpected behavior.traefik/traefik17 discussions
- Optimize allocation hotspotsIdentify and optimize object allocation in performance-critical paths by applying appropriate allocation strategies based on usage patterns. For frequently accessed objects, consider reusing instances rather than creating new ones. For short-lived objects in hot code paths, evaluate whether the JIT can optimize allocations away or if explicit object...netty/netty17 discussions
- Configuration documentation clarityEnsure configuration documentation clearly distinguishes between deployment contexts and uses consistent terminology throughout. When documenting configuration procedures, explicitly specify the target deployment type (Langflow Desktop vs OSS) and platform (macOS vs Windows) to avoid user confusion.langflow-ai/langflow17 discussions
- no braces short ifsRemove braces around single-statement if blocks to maintain consistent code style and improve readability. This applies to all control flow statements with single statements, including if, else if, and else blocks.hyprwm/Hyprland17 discussions
- Use meaningful namesUse descriptive, self-explanatory names for variables, methods, fields, and types. Avoid single-letter variables, abbreviations, and generic naming that obscures intent.juspay/hyperswitch17 discussions
- Telemetry correctness rulesAdopt a single standard for all observability code: 1) Be policy-compliant and opt-out safe - Prefer typed helper functions for telemetry events (fixed event names and fixed payload shapes).ClInE/cLiNe17 discussions
- optimize database operationsWhen working with database operations, prioritize batching multiple statements and pushing operations down to the database level for optimal performance. Use batch statements instead of executing individual prepared statements, and implement proper compatibility checks before attempting query pushdown optimizations.apache/spark16 discussions
- Use descriptive semantic namesVariable and function names should clearly communicate their purpose, type, and scope without requiring additional context. Avoid confusing naming patterns and follow established conventions to improve code readability and maintainability.serverless/serverless16 discussions
- Validate boundary conditionsEnsure algorithms handle boundary conditions and edge cases correctly by adding explicit validation for all input ranges. Special attention should be paid to index calculations, offset arithmetic, and memory management operations, as these are common sources of subtle bugs that only manifest in edge cases.rust-lang/rust16 discussions
- documentation formatting consistencyEnsure consistent formatting throughout documentation by applying these standards: wrap code terms, variable names, and boolean values in backticks (`data`, `error`, `status`, `true`, `false`), use proper markdown link syntax with leading slashes (`/docs/guide/...` instead of `docs/guide/...`), maintain consistent punctuation and spacing in code examples,...nuxt/nuxt16 discussions
- Comprehensive test coverageEnsure comprehensive test coverage by systematically considering all scenarios, edge cases, and feature combinations when adding or modifying functionality. This includes testing both positive and negative cases, feature gate enabled/disabled states, error conditions, and boundary conditions.kubernetes/kubernetes16 discussions
- Model integration rulesWhen adding or changing model loading, quantization, LoRA/abliteration logic, or merging behavior, follow these explicit rules to ensure correctness, compatibility and reproducibility.p-e-w/heretic16 discussions
- Consistent module organizationKeep code organized by responsibility and centralize reusable logic. Concretely: - Centralize helpers: move shared implementations (plugin loading, dataset parsing, prompt helpers, is_notebook, prompt wrappers, etc.) into a single utils or plugin package and import them from one place. Avoid copy-pasting variations of the same logic across files — this...p-e-w/heretic16 discussions
- Extract for clarityExtract complex or reused logic into focused, well-named methods with single responsibilities. This improves code readability, testability, and maintainability while reducing duplication. When refactoring:elastic/elasticsearch16 discussions
- Telemetry correctness contractMake observability code behave like a correctness-critical contract—not “best effort.” Apply these rules: - **Use typed, policy-compliant helpers** for telemetry event names and payload shapes (never free-form event strings). Keep payloads **stable** and **bounded**; never emit raw prompt/text when counts/sanitized fields suffice.Cline/Cline16 discussions
- Protect sensitive dataNever log, display, or store sensitive information like passwords, tokens, or secrets in clear text. This creates significant security vulnerabilities that could lead to unauthorized access and data breaches.bridgecrewio/checkov16 discussions
- Comprehensive documentation standardsCreate clear, well-structured API documentation following proper formatting, correct references, informative examples, and completeness standards. Documentation should be treated as a first-class feature - it's often the first interaction users have with your API.tokio-rs/axum16 discussions
- Docs Match ImplementationDocs must be verifiable against the actual plugin/runtime behavior: schemas (fields/types/requiredness), defaults, and example outputs. Additionally, follow the repo’s established doc formatting conventions for things like canonical tags and secret-value prefixes.apache/apisix16 discussions
- Use descriptive namesChoose variable, function, and parameter names that clearly communicate their purpose and avoid confusion. Names should be descriptive enough that their intent is obvious without requiring additional context or comments.vlang/v15 discussions
- realistic documentation examplesUse practical, complete examples in documentation rather than oversimplified or contrived ones that cut corners. Documentation examples should reflect real-world usage patterns and include necessary context, edge cases, and limitations.sveltejs/svelte15 discussions
- Race-free cancellation and liveness checksWhen wiring an `AbortSignal` (or any cancellation token) into async work — spawning processes, reading files, racing I/O — eliminate every window where a cancellation could be missed or where stale resource state could be misjudged as live.can1357/oh-my-pi15 discussions
- Assert behavior, not wiringA test must fail when the behavior it claims to cover regresses, and pass only because that behavior holds — not because it restates configuration, echoes a value the test itself just set, or grep's implementation source. Before merging a test, ask "would reverting the fix turn this red?" and "does my fake/stub enforce the same rules as the real...can1357/oh-my-pi15 discussions
- Avoid code duplicationEliminate redundant code by leveraging existing utilities, extracting reusable helper functions, and organizing logic in appropriate modules. Before implementing new functionality, check if similar logic already exists in the codebase that can be reused or extended.BerriAI/litellm15 discussions
- Docstrings With IntentAdopt a single documentation standard: every docstring/comment should (1) explain intent and observable behavior, (2) make responsibility/ownership explicit, (3) be traceable when tied to external or non-obvious defaults, (4) be safe when examples could do harm, and (5) follow established docstring conventions without duplicating type annotations.langchain-ai/langchain15 discussions
- Reduce Duplication For ReadabilityWrite code so intent is immediately obvious: avoid repeated boilerplate, collapse near-identical branches, and centralize shared logic/values. Practical rules:kUbernetes/kUbernetes15 discussions
- Organize code structureMaintain clean and well-organized code structure by following consistent organizational patterns. This improves readability, maintainability, and reduces cognitive load for developers.juspay/hyperswitch15 discussions
- Meaningful, deterministic testsTests should verify real, intended behavior and must fail when that behavior is broken. Before adding a test, confirm it actually exercises the code path and would catch a regression — a test that passes even against the old/incorrect implementation provides no value. Assert on precise, meaningful values (actual header content, response body, instance...honojs/hono15 discussions
- Consistent, unambiguous namingChoose identifier names that are unambiguous, self-explanatory, and consistent with existing conventions already used elsewhere in the codebase or in the relevant external spec/ecosystem. Before introducing a new name, check how similar concepts are named in sibling modules (e.g. other middlewares, adapters, generics) and reuse that convention rather than...honojs/Hono15 discussions
- Boundary Hardening RulesTreat every transition from “untrusted / scoped data” into a sensitive sink (shell execution, subprocess credentials, HTTP fetch, filesystem writes, and API-triggered work) as a security seam. Enforce fail-closed policy at that seam: nousresearch/hermes-agent15 discussions
- Explain non-obvious codeAdd explanatory comments for any code that isn't immediately self-explanatory, including magic numbers, implementation decisions, parameter purposes, and edge cases. This improves code maintainability and helps future developers understand the reasoning behind specific choices.flutter/flutter15 discussions
- Use specific assertion methodsChoose the appropriate assertion method based on the data type being tested. This improves test readability and provides clearer error messages when tests fail.fastify/fastify15 discussions
- Robust async test patternsWrite tests that exercise functionality the same way a real consumer would, and make sure asynchronous tests fail loudly rather than hanging. Prefer wiring behavior through the public API inside a request handler and asserting with supertest's `request(app).get('/').expect(...)`, instead of calling internal methods directly, testing an unrelated helper...Expressjs/Express15 discussions
- Database type consistencyEnsure database-specific types, imports, and serialization are used consistently throughout the codebase. This prevents runtime errors, improves type safety, and maintains proper data handling across different database systems.drizzle-team/drizzle-orm15 discussions
- Telemetry Semantics ContractAll observability/telemetry code must follow a consistent “semantics contract”: events must be emitted exactly once, with correct timing/attribution, and with strict schemas that respect opt-out and sanitization.CLINE/CLINE15 discussions
- Revalidate state after awaitsMany races in this codebase come from code that reads shared mutable state (a session slot, a cached config, an in-flight "current" pointer, a pending promise resolver), then awaits something, and finally acts on a stale assumption that nothing changed in the meantime. Examples: a teardown writing a session's terminal status after a replacement already took...cline/cline15 discussions
- Use descriptive, unambiguous namesChoose names that clearly communicate their purpose and avoid ambiguity or misinterpretation. Names should be self-documenting and consider what developers will wonder about at the call site.bazelbuild/bazel15 discussions
- Simplify complex codeBreak down complex code structures into simpler, more readable forms to improve maintainability and reduce cognitive load. This involves several key practices:bazelbuild/bazel15 discussions
- Consistent terminology propagationWhen changing terminology or naming conventions in a codebase, ensure complete and consistent propagation across all related code artifacts. This includes variable names, method names, parameters, error messages, documentation, comments, and any other references. Inconsistent terminology creates cognitive overhead, leads to bugs, and hampers maintainability.appwrite/appwrite15 discussions
- eliminate unnecessary codeRemove redundant operations, unnecessary code blocks, and verbose constructs to improve code clarity and maintainability. Focus on eliminating dead code, avoiding redundant loops, removing unnecessary conditional checks, and using more concise expressions where appropriate.Unstructured-IO/unstructured14 discussions
- Optimize regex patternsWhen using regular expressions, optimize for both performance and precision to ensure efficient and accurate pattern matching: 1. **Use non-capturing groups** when you don't need to reference the matched content, reducing memory allocations:getsentry/sentry-php14 discussions
- Internationalize all textAll user-facing text must be wrapped with translation functions instead of using hardcoded English strings. This includes regular UI text, accessibility attributes (aria-label, title, alt), and screen reader announcements. Using translation keys creates a consistent, maintainable internationalization system and ensures the application is accessible to users...RooCodeInc/Roo-Code14 discussions
- Security Invariants TestingTreat CI/workflow security like production security code: define explicit invariants, enforce them defensively, and lock them with executable regression tests—especially in workflows that run in privileged contexts (e.g., pull_request_target) or execute untrusted PR code.QwenLM/qwen-code14 discussions
- Consistent naming patternsFollow consistent naming conventions throughout the codebase to improve readability and maintainability: 1. **Client property names should be singular**, not plural:octokit/octokit.net14 discussions
- Consistency And ReadabilityApply a single, repeatable style checklist across all new/modified code: 1) Remove unused/redundant code - Drop unused `#include`s and unused variables.Tencent/ncnn14 discussions
- Guard against nullAlways use optional chaining (`?.`) and nullish coalescing (`??`) operators when accessing potentially undefined or null properties. These patterns prevent TypeErrors when accessing nested properties and provide appropriate defaults only when values are null or undefined.n8n-io/n8n14 discussions
- Avoid silent error maskingEstablish a team-wide error-handling contract: 1) Never swallow exceptions in production paths - Avoid bare `except: pass` / broad exception fallbacks that hide the real failure.awslabs/mcp14 discussions
- Handle async operation errorsAlways wrap asynchronous operations in try-catch-finally blocks to prevent unhandled promise rejections and ensure proper cleanup. When errors occur, provide users with meaningful feedback while preserving application state.elie222/inbox-zero14 discussions
- Nonblocking Concurrency RulesEstablish a single concurrency standard: in async code, never block the event loop; in multi-thread/state-machine code, make ownership and cancellation atomic; and in cleanup/shutdown, use bounded, interrupt-friendly paths.nousresearch/hermes-agent14 discussions
- Keep CI configurations minimalWhen configuring CI workflows, include only the extensions, tools, and settings that are necessary for the specific tests being run. Avoid adding unnecessary PHP extensions (such as `xml` or `xdebug`) to workflow configurations unless they're explicitly required. Similarly, keep coverage disabled (`coverage: none`) in CI pipelines by default to improve...laravel/framework14 discussions
- Accurate, scoped documentationDocumentation—including changelogs, guides, tutorials, and inline examples—should be technically accurate, appropriately scoped, and free of misleading or unsafe guidance. Before writing a doc entry, verify the described behavior against the actual code (e.g., confirm blueprint template-loading order, or describe `sqlite3.Row` precisely as supporting both...pallets/flask14 discussions
- Strict null checksMany reported bugs stemmed from using generic truthy/falsy checks (`!x`, `x || y`, ternaries) when the real intent was to detect "missing" (`null`/`undefined`) values. Falsy-but-valid values such as `''`, `0`, `false`, or `'0'` were incorrectly treated as absent, causing logic errors (e.g. an empty `X-Forwarded-Host` header being overwritten, or a `'0'`...Expressjs/Express14 discussions
- Dependency version rangesWhen editing dependency versions in package.json, follow the team's agreed semver range convention rather than mixing styles ad hoc. Unless there is a specific compatibility reason, prefer caret (`^`) ranges for both dependencies and devDependencies, and update version specifiers in their own dedicated commits/PRs rather than bundling them with unrelated...Expressjs/Express14 discussions
- SQLAlchemy 2.0 patternsMigrate from legacy SQLAlchemy 1.x query patterns to modern 2.0 style for better performance, clarity, and future compatibility. This involves several key transformations:langgenius/dify14 discussions
- Thorough edge-case verificationTests should fully exercise the behavior being verified, not just a single happy-path value that happens to pass even without the fix. Before adding a test, confirm it actually fails on the old code and genuinely covers the scenario it claims to: include boundary values (e.g. buffer-size multiples, signed-integer limits, timestamps around overflow points,...python/cpython14 discussions
- Consistent naming standardsEnsure all user-facing strings follow Home Assistant's naming conventions for consistency and proper internationalization. This includes using sentence-case for translatable strings, proper spelling and capitalization of technical terms, and leveraging common string references where available.home-assistant/core14 discussions
- Configuration validation messagesEnsure configuration validation provides clear, actionable error messages that guide users toward correct configuration. Validation should be comprehensive, checking not only types but also value ranges, logical consistency, and edge cases like undefined vs explicitly set values.cloudflare/workers-sdk13 discussions
- avoid expensive repeated operationsCache results of expensive computations and order operations from cheapest to most expensive to minimize performance overhead. This includes storing function call results in local variables, extracting constants to avoid repeated allocations, using appropriate buffer sizes, and placing fast conditional checks before slower ones.vlang/v13 discussions
- Add comprehensive test coverageWhen adding functionality or fixing bugs, always add new test functions rather than modifying existing ones to preserve test coverage. Ensure comprehensive testing by including edge cases, error conditions, and assertions for all public functions. Use meaningful, non-default values in tests to improve sensitivity to regressions.vlang/v13 discussions
- Enforce scope boundariesWhen implementing hierarchical permission systems with scopes, ensure that permissions granted at a specific scope cannot be used to access resources or escalate privileges outside that scope's boundaries. This prevents lateral movement and privilege escalation attacks.gravitational/teleport13 discussions
- Spring code styleFollow Spring Framework's code style guidelines to ensure consistency across the codebase. Key rules include: 1. **Import statements**: - Use specific imports rather than wildcard importsspring-projects/spring-framework13 discussions
- Use semantically accurate namesVariable, method, and type names should accurately reflect their actual purpose, content, and behavior. Avoid generic or misleading names that don't match the underlying functionality.servo/servo13 discussions
- Consistent descriptive namingEnsure variable, function, and type names are consistent, descriptive, and follow Go naming conventions. Names should clearly convey their purpose and maintain consistency across related components.prometheus/prometheus13 discussions
- Exception Handling PolicyAdopt an exception-handling standard that distinguishes **critical control-flow** from **non-critical side effects**, while enforcing safe, observable exception patterns.the-pr-agent/pr-agent13 discussions
- Evidence-Gated HeuristicsWhen implementing content extraction/layout algorithms, treat “heuristics” as *probabilistic classifiers*: constrain them with invariants, gate them with evidence, and lock behavior with targeted regression tests.firecrawl/pdf-inspector13 discussions
- Code for readabilityPrioritize human readability when writing code. Split complex expressions into steps with meaningful variable names. Extract repeated logic into well-named functions. Avoid magic numbers - derive values from existing structures or use named constants. Simplify control flow by reducing nesting levels and using early returns.opencv/opencv13 discussions
- Feature-gated Configuration ConsistencyWhen adding or changing a feature-gated configuration/behavior, ensure the gate is applied consistently across *all* layers (API defaults/validation, admission checks, and runtime logic), and that turning the gate off preserves the previous/legacy behavior (including how updates treat existing stored fields/status).kUbernetes/kUbernetes13 discussions
- Write focused, deterministic testsKeep the test suite lean and trustworthy by following these rules: 1. **Avoid redundancy.** Before adding a test, check whether the behavior is already covered elsewhere (e.g. in another test file or an existing case). Don't add near-duplicate tests (e.g. many permutations of header-based auth) when one success and one failure case already prove the logic...HONOJS/HONO13 discussions
- Optional value handlingWhen a value can legitimately be `undefined`/`null` at runtime, make sure both the type signature and the code reflect that, and access it safely: - Type values correctly: if a function/property can return `undefined` (e.g. a missing route match, a header lookup, a route param), its type must include `| undefined` (or `| null`) rather than being asserted...honojs/hono13 discussions
- Explicit nullish value handlingWhen dealing with optional, nullable, or possibly-missing values, handle them explicitly and avoid redundant or misleading fallback patterns: - Don't add unnecessary fallbacks when the language already handles the case safely. For example, spreading `undefined` is a no-op, so `{ ...args?.header }` is sufficient; `{ ...(args?.header ?? {}) }` is redundant.HONOJS/HONO13 discussions
- Descriptive consistent namingUse descriptive, consistent naming that follows language and platform conventions. Choose names that clearly communicate purpose and context, and maintain consistency across similar elements.ghostty-org/ghostty13 discussions
- Use descriptive namesNames should clearly describe what they represent or do, rather than how they're implemented or using generic terms. Avoid abbreviations and use full, descriptive words that accurately reflect the purpose and behavior of the code element.flutter/flutter13 discussions
- Propagate and clean up errorsNever swallow an error or silently end a response/stream — forward it to the correct error channel. In middleware/handlers that's `next(err)` so the configured error-handling pipeline (and not the handler itself) decides how to log/report it; for one-off operations with a user-supplied callback (e.g. `fn` in `sendFile`), send the error there instead of into...Expressjs/Express13 discussions
- API parameter consistencyEnsure consistent parameter handling across API methods by using appropriate defaults, proper type conversion, validation with meaningful constants, and cross-platform behavior consistency.electron/electron13 discussions
- Clean up your codeMaintain clean, professional code by removing development artifacts and improving readability: 1. **Remove debug code before committing**: - Delete all debugging print statementsdeeplearning4j/deeplearning4j13 discussions
- Centralized Config StandardsWhen implementing new behavior behind feature flags or configuration (paths, env vars, index dimensions, toggles like text2gql), use centralized, documented config instead of hardcoded values or scattered env access.eosphoros-ai/DB-GPT13 discussions
- Meaningful, Test-Level CorrectnessTests should be aligned with what they claim to validate, and placed at the right layer (unit vs integration). Concretely: - **Don’t rely on system side effects in unit tests.** If the test depends on vmnet/network/kernel/fs behavior, prefer **integration** coverage; unit tests should focus on pure logic.apple/container13 discussions
- Error handling without silenceTreat errors as first-class: don’t blanket-suppress them with `try?`, `try!`, `_ =` result discards, or `2>/dev/null` unless you can prove the failure is expected and harmless. For unexpected failures, either propagate (`throw`) or explicitly log and recover in a deterministic way.apple/container13 discussions
- Fail-Closed Security HandlingApply a single principle across auth, credentials, routing, sandboxing, and logging: **security must default to deny and must never proceed on ambiguous/dismissed outcomes; state and boundaries must be explicit and consistent.**Cline/Cline13 discussions
- Fail-Closed Security BoundariesAdopt a single secure-by-default rule-set: **authentication/authorization gates must fail closed**, **secret-bearing data must never be logged**, and **sandbox/file boundaries must be enforced with real paths and deny escape hatches**.ClInE/cLiNe13 discussions
- Explicit Error HandlingAdopt a standard that prevents misleading state, lost root causes, and unhandled async failures—especially in recovery/timeout paths. Rules: 1) Handle both rejection and exceptions in promise chainsCLINE/CLINE13 discussions
- Use descriptive contextual namesChoose variable, function, and struct names that clearly communicate their purpose and content while considering their surrounding context. Avoid generic names like `x`, `normal`, or `data` that provide no semantic meaning. When naming within a specific scope or module, avoid redundant prefixes that repeat the context.alacritty/alacritty13 discussions
- Design interfaces, not implementationsCreate intuitive API interfaces that abstract away implementation details while providing a consistent experience for consumers. Use appropriate parameter types that express intent and maintain established patterns across your codebase.zed-industries/zed12 discussions
- Use testify assertion librariesReplace manual if-error checks with `testify`'s `assert` and `require` packages to make tests more readable, maintainable, and with better error messages.vitessio/vitess12 discussions
- Use semantically clear namesChoose variable, method, and class names that clearly express their purpose and functionality to avoid confusion and improve code readability. Names should accurately reflect what the code does rather than how it's implemented.Unstructured-IO/unstructured12 discussions
- simplify control flow patternsImprove code readability by simplifying control flow structures and avoiding unnecessary complexity. This involves three key practices: **1. Use early returns instead of nested if/else blocks:**twentyhq/twenty12 discussions
- Simplify complex expressionsBreak down complex code structures into simpler, more readable forms. This includes avoiding deep nesting, extracting complex logic into helper functions, simplifying boolean expressions, and reducing code duplication.tree-sitter/tree-sitter12 discussions
- Configuration validation consistencyEnsure configuration fields use consistent validation patterns, appropriate data types, and proper bounds checking. This includes using correct regex patterns for duration fields, consistent type usage across similar fields, and implementing cross-field validation where relationships exist.traefik/traefik12 discussions
- Use semantic namingNames should clearly communicate their purpose, type, and behavior to improve code maintainability and accessibility. Avoid misleading or ambiguous terminology that can confuse developers or users.microsoft/terminal12 discussions
- Guide structure consistencyDocumentation guides should follow a consistent structure and provide clear, descriptive content to improve user experience and comprehension. **Structure Requirements:**gravitational/teleport12 discussions
- consistent descriptive namingUse meaningful, descriptive names that clearly convey purpose and maintain consistency across similar concepts throughout the codebase. Avoid magic strings, cryptic abbreviations, and inconsistent naming patterns.SigNoz/signoz12 discussions
- eliminate code duplicationActively identify and eliminate code duplication by extracting common patterns into reusable components. When you notice repeated code blocks, similar conditional logic, or duplicate class definitions, consolidate them through extraction techniques.sgl-project/sglang12 discussions
- API consistency patternsEnsure API design follows consistent patterns for naming, typing, and composition to improve developer experience and maintainability. **Key principles:**remix-run/react-router12 discussions
- Branch-Exact Test CoverageMake workflow/test suites “branch-complete and predicate-exact”: every reachable `case` arm and every required gating condition must be exercised and asserted, with environment-correct shims/guards.QwenLM/qwen-code12 discussions
- Deterministic Test AssertionsFor tests, prefer deterministic, intention-revealing assertions and keep runtime tests and type-only tests strictly separated. Apply: 1) Use the right matcher for the claimtanstack/query12 discussions
- Consistent dependency configMaintain configuration consistency and compatibility by using a single, intentional strategy for dependency declarations, peer ranges, and script runtimes.tanstack/query12 discussions
- CI workflow correctnessAll CI workflows must be syntactically valid, reliably triggered, and logically non-redundant. Apply these rules: 1) Every step must be valid: each `- name:` entry must include either `uses:` or `run:` (never both missing).TheAlgorithms/Python12 discussions
- Parameterize similar testsUse `pytest.mark.parametrize` to consolidate similar test cases instead of duplicating test code. This approach improves maintainability, reduces code duplication, and ensures comprehensive test coverage across different scenarios.python-poetry/poetry12 discussions
- Component naming consistencyEnsure component usage in templates matches registered components. Vue components must be referenced in templates by either their kebab-case equivalent or by their exact registered name.n8n-io/n8n12 discussions
- Clean and consistent codeMaintain clean and consistent code by removing unnecessary elements and following standard practices: 1. **Remove commented-out code and unused imports** - Don't leave commented-out code in the codebase. If code is no longer needed, delete it entirely rather than commenting it out. Similarly, remove unused imports to reduce bundle size and avoid linting...n8n-io/n8n12 discussions
- Eliminate redundant constructsRemove unnecessary coding patterns that add complexity without providing value. Focus on clarity and simplicity by: 1. Not using enumerate() when the index is unused:apache/mxnet12 discussions
- Model specification accuracyEnsure AI model configurations accurately reflect official specifications and avoid hardcoded assumptions. Model parameters, token limits, capabilities, and naming should match vendor documentation rather than using generic defaults.lobehub/lobe-chat12 discussions
- prefer OpenAI compatibilityWhen integrating new LLM providers or AI services, prioritize OpenAI-compatible patterns and reuse existing utilities rather than creating separate implementations. This approach reduces code duplication, leverages battle-tested functionality, and maintains consistency across the codebase.BerriAI/litellm12 discussions
- Mock tests in tests/litellmAll new functionality must include mock tests placed in the `tests/litellm/` directory structure. Mock external API calls and dependencies rather than requiring real credentials or external services. This ensures tests can run reliably in CI/CD pipelines and are accessible to all contributors.BerriAI/litellm12 discussions
- Use descriptive namesNames should accurately reflect their actual functionality and behavior. Avoid misleading or vague identifiers that don't match what the code actually does.istio/istio12 discussions
- Canonical Stream NamingWhen editing M3U `#EXTINF` metadata, treat `tvg-id` (and related fields) as a canonical identifier: it must be valid, correctly aligned with the displayed channel name, and consistent across variants.iptv-org/iptv12 discussions
- Design extensible, composable option APIsWhen designing public APIs for middleware, helpers, and client functions, favor extensible, composable configuration over ad-hoc parameters that are hard to grow later:honojs/Hono12 discussions
- consistent highlighting patternsMaintain consistency in syntax highlighting patterns by using appropriate, specific scopes and avoiding overly complex or noisy patterns. Follow Helix-specific conventions rather than generic tree-sitter patterns.helix-editor/helix12 discussions
- Lint-Compliant Markdown LinksWhen adding/updating entries in markdown lists, follow the repository’s lint-safe formatting and platform/link conventions. Checklist: - Escape special markdown characters in titles/labels: use `\|` instead of `|`.EbookFoundation/free-programming-books12 discussions
- Preserve API compatibilityWhen adding or changing public request/response methods, protect existing contracts and behavior instead of introducing silent breaking changes. Concretely:Expressjs/Express12 discussions
- Use extensible parameter objectsWhen designing APIs that may need additional parameters in the future, use objects instead of individual parameters to enable extension without breaking changes. This approach allows new properties to be added while maintaining backward compatibility.electron/electron12 discussions
- Provide contextual explanationsDocumentation should explain not just what APIs and features do, but when, why, and how to use them. Provide sufficient context for developers to understand the purpose, appropriate use cases, and practical implementation details.electron/electron12 discussions
- Use descriptive identifiersChoose names that clearly communicate purpose and reduce cognitive load for future readers. Avoid generic, abbreviated, or ambiguous identifiers in favor of self-documenting ones.discourse/discourse12 discussions
- Robust C API error handlingWhen writing C extension/interpreter code, treat every fallible C API call as a potential failure point and handle it consistently: - **Check return values immediately.** After calling functions like `PyNumber_Subtract`, `PyLong_AsLong`, `PyObject_GetAttrString`, etc., check for failure before using the result. Don't assume a prior check covers a later...python/cpython12 discussions
- Follow existing naming patternsMaintain consistency with established naming conventions throughout the codebase. When adding new flags, functions, or variables, examine existing similar implementations and follow the same patterns for naming, separators, and structure.docker/compose12 discussions
- Precise async error coverageEnsure every async boundary fully captures *both* rejected promises and synchronous exceptions, and only performs recovery/retry when the error classification is precise and safe.Cline/Cline12 discussions
- Fail-Closed Secrets SafetyUse fail-closed security boundaries and secret-safe observability by default. ### 1) Auth/CSRF: never store or act on unverified callbacks - Treat `state` (or equivalent anti-forgery token) as a required verification gate.CLINE/cline12 discussions
- consistent readable patternsMaintain consistent coding patterns and prioritize readability to make code easier to understand and maintain. This includes using consistent approaches for similar operations, avoiding overly complex constructions, and ensuring code follows predictable patterns.snyk/cli12 discussions
- Limit token permissionsAlways specify the minimum required permissions for the GITHUB_TOKEN in GitHub Actions workflows to enhance security. By default, the GITHUB_TOKEN has broad permissions that could potentially be exploited if a workflow is compromised.chef/chef12 discussions
- Readable formatting and idiomsPrioritize readability through consistent formatting and modern, simple idioms. For code style changes, ensure multiline constructs are formatted cleanly, complex conditions are made understandable (via extracted “effective” variables or small helpers), repeated patterns are factored out, and modern Python conventions are used.celery/celery12 discussions
- Maintain consistent styleMaintain consistent style patterns throughout the codebase to improve readability, reduce maintenance overhead, and prevent errors. Key areas to focus on:oven-sh/bun12 discussions
- Follow support tiersConfigure your Homebrew installation according to the defined support tiers to ensure optimal functionality and support. For Tier 1 support (fully supported):Homebrew/brew12 discussions
- Narrow catches, log contextWhen handling errors, avoid two failure modes: (a) false-success/zero-signal outcomes and (b) silent data loss. Apply these rules consistently: 1) Fail loudly when correctness is impossiblebmad-code-org/bmad-method12 discussions
- Null-safe FiltersEnsure queries and ASIM parsers handle nullable/optional fields safely by (1) using type-correct null checks, (2) guarding references to optional/missing columns with `column_ifexists` (and using the same guarded form in both `summarize` and `project`), and (3) gating filters/fields that the source cannot provide so they don’t unintentionally exclude all...Azure/Azure-Sentinel12 discussions
- Avoid Duplication, Extract HelpersKeep code readable and maintainable by (1) extracting complex or phase-specific logic into dedicated helper functions, (2) removing duplicated logic/schema/label definitions in favor of shared helpers or a single source of truth, and (3) following existing project idioms/utilities to stay consistent.apache/apisix12 discussions
- maintain consistent styleEnsure consistent application of coding style conventions throughout the codebase, including naming patterns, type usage, code organization, and formatting standards.angular/angular12 discussions
- Use descriptive namingChoose variable, function, and method names that clearly communicate their purpose and behavior. Avoid ambiguous abbreviations, numbered suffixes, double negatives, and names that don't accurately reflect functionality.volcano-sh/volcano11 discussions
- Optimize algorithmic efficiencyChoose efficient algorithms and data structures to minimize computational overhead and improve code maintainability. Prefer positive logic over elimination methods, reuse existing data structures instead of creating new ones, and extract common algorithmic patterns into shared functions.volcano-sh/volcano11 discussions
- Eliminate code redundancyKeep your codebase maintainable by eliminating both unnecessary and duplicated code: 1. **Remove debugging artifacts**: Delete commented-out code, debug print statements, and unused imports before merging.vllm-project/vllm11 discussions
- PEP 257 docstring complianceAll public modules, classes, methods, and functions must have docstrings that follow PEP 257 formatting standards. This ensures consistent, professional documentation across the codebase.Unstructured-IO/unstructured11 discussions
- explicit None handlingAlways handle potential None values explicitly through defensive programming patterns, proper type annotations, and explicit checks to prevent runtime errors and improve code reliability.Unstructured-IO/unstructured11 discussions
- Minimize allocation hotspotsReduce object creation in performance-critical paths by carefully evaluating allocation patterns. For frequently instantiated objects, consider caching instances or using static helpers, but always validate improvements with proper benchmarks.spring-projects/spring-framework11 discussions
- Improve code organizationPrioritize clean code structure and readability in AI/ML codebases by avoiding inline conditionals, using descriptive expressions, and maintaining proper separation of concerns. This is especially important in machine learning systems where complex logic can quickly become unmaintainable.sgl-project/sglang11 discussions
- optimize algorithmic complexityPrioritize algorithmic efficiency by choosing operations and data structures that minimize computational complexity. Look for opportunities to replace O(n) operations with O(1) alternatives, select appropriate data structures for the use case, and avoid unnecessary algorithmic overhead.servo/servo11 discussions
- comprehensive API documentationAll public items, struct fields, and methods must have comprehensive documentation. When implementing web specifications, include the actual specification text in comments rather than just links, as specifications can change over time.servo/servo11 discussions
- Split for better readabilityBreak long lines and complex structures across multiple lines to improve code readability. Follow these guidelines: 1. Keep line length around 80 characters (soft limit)getsentry/sentry-php11 discussions
- require module documentationAll modules containing functions should have corresponding .mli files with comprehensive documentation. The .mli file must include: 1. **Module purpose**: A clear, high-level description of what the module does and why it existssemgrep/semgrep11 discussions
- Optimize for readabilityWrite code that clearly communicates intent by using appropriate naming and formatting techniques. Improve readability by: 1. Replacing magic numbers and string literals with named constants:dotnet/runtime11 discussions
- Workflow State HygieneCI/CD workflows should enforce *state invariants* across steps, runs, and runners: later steps must only execute when earlier phases truly produced a valid outcome, and all per-run state must be cleaned/flushed and permission-safe—especially on persistent self-hosted runners.QwenLM/qwen-code11 discussions
- Single Source HelpersWhen code review finds duplicated logic or repeated formatting/constants, treat it as a “single source of truth” violation. Factor shared logic into a helper/module and reuse it everywhere; avoid hardcoded literals where an existing helper/constant exists; and keep established idioms consistent.QwenLM/qwen-code11 discussions
- Keep Docs AccurateAdopt a rule that comments/JSDoc/API docs must be both *correct* and *useful at the point of use*—never misleading, stale, or attached to the wrong symbol.QwenLM/qwen-code11 discussions
- Device-agnostic acceleration codeAvoid hardcoding specific device types like 'cuda' in AI code. Instead, use device-agnostic approaches such as device type variables or accelerator detection functions. This ensures code runs efficiently across different hardware accelerators (CUDA, ROCm, XPU, etc.) without modification.pytorch/pytorch11 discussions
- Validate Inputs ExplicitlyEnforce each function’s documented input contract with early, explicit checks; raise specific exceptions with accurate messages (avoid asserts, silent fallbacks/defaults, and misleading error paths after normalization). Keep try/except blocks as narrow as possible—only around the operations that can fail.TheAlgorithms/Python11 discussions
- Verify documentation against behaviorEvery factual claim in documentation—links, API endpoints, default behaviors, required vs. optional settings, supported capabilities, and setup commands—must be verified against the actual running system (built site, source code, or live execution) before publishing, not assumed. Precisely scope statements to the environment or configuration they apply to,...promptfoo/promptfoo11 discussions
- Classify and isolate failuresWhen a response, stream, or batch item can fail independently, explicitly validate it and keep that failure from corrupting unrelated results or silently becoming a "pass." Two rules apply broadly:promptfoo/promptfoo11 discussions
- maintain code consistencyEnsure consistent patterns, formatting, and conventions throughout the codebase. Inconsistencies in code style create confusion, reduce readability, and make maintenance more difficult.emcie-co/parlant11 discussions
- Craft actionable errorsCreate error messages that provide precise context, avoid unnecessary details, and give users clear actions to take. Error messages should include location information when possible, avoid jargon, and maintain a consistent tone without being patronizing.opentofu/opentofu11 discussions
- precise language usageUse precise, natural language in documentation to improve clarity and readability. Focus on accurate word choice, proper grammar, and natural phrasing that flows well for readers.nuxt/nuxt11 discussions
- Idempotent error-safe disposersWhen implementing resource cleanup logic, especially disposers for explicit resource management, always design for resilience during error conditions:nodejs/node11 discussions
- Centralize shared utilitiesWhen code has repeated “plumbing” (string templating/formatting, pagination/envelopes, client setup, session/ctx extraction, embedding serialization, etc.), move it into a shared helper/utility and keep stable imports/constants at module scope. This reduces drift, improves readability, and keeps formatting behavior consistent across tools.awslabs/mcp11 discussions
- Follow modern C++ guidelinesAdhere to the C++ Core Guidelines for improved code quality, readability, and maintainability. Follow these key practices: 1. **Use enum class instead of regular enums** for type safety and scope:maplibre/maplibre-native11 discussions
- consolidate algorithmic patternsAvoid duplicating similar algorithmic logic across multiple functions by consolidating them into generic, templated, or trait-based implementations. This reduces maintenance burden and improves code consistency.ggml-org/llama.cpp11 discussions
- AI model data validationAll AI model configuration parameters must be verified against official provider documentation before merging. This includes token limits, pricing values, provider assignments, model names, and supported features. Incorrect configuration data leads to runtime errors, cost miscalculations, and integration failures.BerriAI/litellm11 discussions
- Organize documentation contentStructure documentation to prevent information overload and improve readability by using appropriate organizational elements and callouts judiciously.langflow-ai/langflow11 discussions
- Use semantically clear namesChoose names that accurately reflect the actual functionality, purpose, or semantic meaning rather than using generic, misleading, or implementation-focused terms. Names should be self-documenting and help readers understand what the code does without needing additional context.kubernetes/kubernetes11 discussions
- Semantics-Aware Test CoverageWhen adding or modifying tests, ensure they (1) cover the minimal correctness set (including edge/error paths), (2) validate key invariants so the test itself can’t silently be wrong, and (3) in E2E, assert the real semantics—not just the final API phase—while keeping timing bounded to avoid flakiness.kUbernetes/kUbernetes11 discussions
- Feature gate field preservationWhen implementing feature-gated fields, always preserve existing field values when the feature gate is disabled, but drop new field values that depend on disabled features. This prevents breaking existing functionality during feature gate transitions or version skew scenarios.kubernetes/kubernetes11 discussions
- Cancellation Aware ConcurrencyWhen adding or modifying concurrent code, treat context/cancellation, goroutine lifecycle, and state ownership as first-class requirements. Practical standards:kUbernetes/kUbernetes11 discussions
- Names express clear intentChoose names that clearly express intent and follow established conventions. Prefer explicit, descriptive names over abbreviations or ambiguous terms. Align with platform-specific naming patterns and maintain consistency with existing codebase conventions.JetBrains/kotlin11 discussions
- Consistent Error PropagationWhen handling failures, choose behavior intentionally: either propagate a real error in a consistent format, or gracefully degrade only for *explicitly non-error* cases (e.g., notifications, permission edge cases). Avoid masking, asserting, or continuing after validation/parsing fails.Kong/kong11 discussions
- Consistent, Actionable LoggingWhen adding/modifying logs, follow these rules: 1) Use the Kong logging API - Prefer `kong.log.<level>` (e.g., `kong.log.err(...)`) over `ngx.log(...)` to keep logging consistent with Kong conventions.Kong/kong11 discussions
- comprehensive test coverageEnsure tests cover not only the happy path but also edge cases, error scenarios, and complete workflows. Many code reviews reveal gaps where only basic functionality is tested while important edge cases, exception handling, and integration scenarios are missing.apache/kafka11 discussions
- consistent command flag designDesign command-line interfaces with consistent flag semantics and leverage framework features for validation. Avoid ambiguous syntax that can be interpreted multiple ways, use explicit conflict declarations instead of manual validation, and ensure flag combinations have clear, predictable behavior.jj-vcs/jj11 discussions
- Sanitize all inputsProperly sanitize or escape all user-provided inputs before using them in sensitive contexts to prevent injection attacks. This applies to multiple contexts:elie222/inbox-zero11 discussions
- explicit error handlingAvoid catch-all patterns and implicit error handling. Handle each error case explicitly, use the ? operator for error propagation instead of explicit returns, and never silently ignore errors.juspay/hyperswitch11 discussions
- Flexible middleware option designWhen designing options and callbacks for middleware/helpers, favor extensible, composable patterns over narrow, single-purpose additions. - Pass the `Context` (or relevant request data) into user-supplied callbacks whenever behavior may depend on the request, so users can implement custom logic without new options (e.g. `onError: (remote, c: Context) =>...honojs/hono11 discussions
- Extensible options designWhen adding configuration to middleware, helpers, or client functions, favor a single extensible options object over growing lists of positional parameters or narrow convenience flags. Concretely:HONOJS/HONO11 discussions
- Collision-Safe Identifier MappingTreat every identifier (tool name, command name, provider slug, theme name, thread key) as a runtime contract: you must generate, transform, and resolve it consistently, and preserve an unambiguous mapping between any emitted/sanitized UI value and the backend identity.nousresearch/hermes-agent11 discussions
- Use clear namesRule: choose concise, semantically accurate, and responsibility-respecting names for identifiers (variables, functions, classes, modules). Motivation: clear names reduce cognitive load, avoid ambiguity, and prevent leaking responsibilities across layers.p-e-w/heretic11 discussions
- Surface errors clearlyRule: Fail fast, validate assumptions, and distinguish user cancellation. Motivation - Hidden or silently handled errors lead to incorrect behavior, confusing UX, and hard-to-debug failures (e.g., silently ignoring invalid saved study settings, treating Ctrl+C as a legitimate choice, or swallowing invalid split specs).p-e-w/heretic11 discussions
- Idiomatic, minimal Python constructsFavor clear, idiomatic Python over verbose, manual, or unpythonic constructs, and avoid introducing unnecessary complexity or unrelated refactors just to satisfy a linter/type-checker. Specifically:pallets/flask11 discussions
- Use descriptive namingChoose names that clearly communicate intent and purpose rather than being generic, abbreviated, or potentially misleading. Names should accurately reflect what the code does, not how it does it.duckdb/duckdb11 discussions
- Use descriptive namesNames should be descriptive and unambiguous, clearly communicating their purpose and intent. Avoid abbreviations and ambiguous terms that could confuse readers about the actual functionality or data being represented.duckdb/duckdb11 discussions
- Use descriptive namesChoose variable, method, class, and parameter names that clearly communicate their purpose and avoid ambiguity. Names should be self-documenting and specific rather than generic or vague.stanfordnlp/dspy11 discussions
- Mock external dependencies onlyWhen writing tests for Home Assistant integrations, mock external library dependencies rather than Home Assistant internals like coordinators, entities, or config entries. Test integration behavior through proper setup and service calls instead of directly manipulating internal objects.home-assistant/core11 discussions
- Optional-Safe Null HandlingAdopt a consistent null/absence policy: 1) Model absence explicitly - If a value may be missing (older on-disk configs, optional server fields, optional UI inputs), represent it with an optional type (e.g., `String?`) and make the corresponding `Codable` field tolerant of omission.apple/container11 discussions
- Fail Safe Error RoutingIn error/timeout/recovery flows, ensure every failure (including exceptions thrown inside callbacks, stream write failures, and detached promises) is routed through the code path that owns reporting/retries/state invariants—never as an unhandled rejection/exception and never as a silent fallback.CLINE/cline11 discussions
- Fail-Closed Auth And LoggingSecurity standard: authentication/authorization and credential-handling code must fail closed and must not leak secrets. 1) Auth callback state/nonce enforcement (fail-closed)cline/CLINE11 discussions
- Use descriptive semantic namesNames should accurately reflect their purpose, behavior, and semantic meaning to avoid confusion and improve code readability. Avoid misleading names that don't match the actual functionality or content.ClickHouse/ClickHouse11 discussions
- Avoid unnecessary allocationsMinimize memory allocations, data copying, and expensive operations by implementing early exits, using move semantics, and choosing appropriate buffer management strategies.ClickHouse/ClickHouse11 discussions
- Cohesive Converters OrganizationKeep Go files cohesive by responsibility, and make branching/conversion logic easy to extend. **1) Put types where they belong** - Move request/response structs (and their `GetExtraParams` helpers) into `types.go`.maximhq/bifrost11 discussions
- Add explanatory commentsAdd explanatory comments and documentation for complex logic, non-obvious code behavior, method parameters, and API functionality to improve code readability and maintainability.bazelbuild/bazel11 discussions
- Use Stable API VersionsWhen defining or calling APIs (including Azure Sentinel/Microsoft Security connector artifacts), always use a stable, supported `apiVersion` and keep it consistent across all related files. Avoid “preview”/older `apiVersion` values unless there is an explicit, documented need.Azure/Azure-Sentinel11 discussions
- Identifier Naming RulesUse a single, deterministic naming scheme for every content identifier, and follow the validator’s allowed formats. Apply these rules: 1) Follow exact format/allowed-value rules for metadata/idsAzure/Azure-Sentinel11 discussions
- Standardize PowerShell NamingApply consistent, semantic naming to generated cmdlets, parameters, and help/docs. - Cmdlet verb semantics: name sync operations with `Invoke-*` rather than `Start-*`/job-style verbs.Azure/azure-powershell11 discussions
- Concurrency-Safe State OwnershipIn code that runs across multiple concurrent requests/workers (OpenResty/Nginx), make state ownership and lifecycle explicit: use one writer/immutable shared snapshots, keep request/per-plugin state per-instance or per-request, and design timer/event flows to avoid race windows.apache/apisix11 discussions
- Actionable logging rulesAdopt consistent logging practices: - **Never allow correctness-affecting failures to be silent**, especially inside OpenResty async callbacks (e.g., `ngx.timer.at`, log phase). Log each error path *inside* the callback.apache/apisix11 discussions
- Standardize platform-agnostic configurationEnsure configuration handling is consistent and platform-agnostic by following these guidelines: 1. Use environment variables with fallbacks: ```rustzed-industries/zed10 discussions
- prioritize code clarityWrite code that prioritizes readability and clarity over minor optimizations or clever shortcuts. When faced with choices between concise but obscure code and more explicit but readable code, choose readability.cloudflare/workerd10 discussions
- Validate nullability with typesAlways handle null and undefined values explicitly through proper type declarations and validation patterns rather than using non-null assertions or unsafe type casts. This ensures type safety and prevents runtime errors.microsoft/vscode10 discussions
- Enforce security invariantsSecurity decisions (sandboxing, allow/deny access, and token attachment) must remain correct across time, async races, and concurrent policy contributions.microsoft/VSCode10 discussions
- Bound Hot-Path WorkWhen code runs on hot UI paths (keystrokes, popup open, navigation) or retains state for long-lived sessions, enforce **bounded work** and **targeted updates**.microsoft/VSCode10 discussions
- Document code thoroughlyAlways include comprehensive documentation for your code through both docstrings and explanatory comments. For classes, functions, and methods, add docstrings that explain:vllm-project/vllm10 discussions
- Improve code clarityWrite code that clearly expresses intent through explicit patterns, simplified logic, and readable structure. Avoid unnecessary complexity that obscures the code's purpose.vlang/v10 discussions
- prioritize code clarityWrite code that prioritizes readability and explicitness over brevity. This includes using explicit type conversions instead of implicit ones, extracting magic values to named constants, creating helper functions for repetitive operations, and organizing code logic clearly.unionlabs/union10 discussions
- Configuration documentation clarityConfiguration documentation should be precise, specific, and include helpful context for users. Avoid vague or ambiguous language that could lead to misunderstanding of how settings behave.astral-sh/ty10 discussions
- Use proper typesMaintain code clarity by using appropriate type declarations and parameter passing conventions: 1. **Prefer explicit types over `auto` when the type is known and simple**:tensorflow/tensorflow10 discussions
- Organize code by functionalityStructure code based on what it does rather than how it's implemented. Group related functionality together, extract reusable components, and place code in appropriate packages or files to improve maintainability and readability.gravitational/teleport10 discussions
- Complete API documentationDocumentation should be complete, accurate, and follow Spring Framework conventions. Ensure your Javadocs include: 1. **Clear and accurate descriptions** that precisely explain behavior and purposespring-projects/spring-framework10 discussions
- Purposeful documentation standardsDocumentation should convey purpose and behavior, not just replicate code structure. Each docblock should explain what a component does and why it exists, rather than merely restating its name or signature.getsentry/sentry-php10 discussions
- Clear Semantic Identifier NamingAdopt naming conventions that are (1) case-consistent by identifier kind and (2) semantically self-documenting (what it represents/includes/excludes, and what the function returns).redis/redis10 discussions
- Thread-safe shared stateEnsure that shared mutable state is properly protected against concurrent access to prevent race conditions and data corruption. When multiple threads can access the same mutable data, use appropriate synchronization mechanisms such as ThreadLocal, locks, or atomic operations.facebook/react-native10 discussions
- Config Documentation ConstraintsWhen adding or updating configuration-related docs (env vars, config files, feature/transport flags, and deployment commands), ensure the guidance is (1) context-correct, (2) compatibility-checked, and (3) explicit about defaults/overrides.infiniflow/ragflow10 discussions
- Bound Hot-Loop WorkDefault to explicit resource budgets and ensure they’re actually enforced. Apply these rules in code review: 1) **Bound inputs and remote pagination**QwenLM/qwen-code10 discussions
- Explicit undefined invariantsWhen handling query/mutation results, treat `undefined` (and `null`) as semantically distinct and enforce that distinction in both runtime checks and TypeScript types.tanstack/query10 discussions
- Contract-Accurate TestingTests should assert the behavior contract precisely, include the missing coverage for changed code, and stay isolated/noisy-control friendly. Key rules:tanstack/query10 discussions
- API typing parityWhen evolving public API/TypeScript types, ensure the **type surface exactly matches runtime behavior and intended layering**, and reuse existing signature/overload patterns.tanstack/query10 discussions
- Standardize configuration pathsFollow consistent patterns for storing and referencing configuration files across projects. Place custom configuration files in standardized locations (e.g., `src/main/docker` for Dockerfiles, `.s2i` for S2I environment files) and use consistent naming conventions. When referencing file paths in configuration properties, use relative paths from the project...quarkusio/quarkus10 discussions
- Automate All Behavior TestsFor every algorithmic change (and every public function/class), require automated tests that lock in both correctness and failure modes. Minimum standard:TheAlgorithms/Python10 discussions
- Next.js directory structureKeep the Next.js `/app` directory strictly for routing purposes as per framework conventions. Non-routing related code like tools, utilities, and services should be moved to appropriate directories such as `/lib/`. This improves code organization, maintainability, and follows Next.js best practices.prowler-cloud/prowler10 discussions
- Propagate cancellation signalsMany concurrency bugs stemmed from abort/cancellation signals not being threaded through every async call, or from async operations that could hang forever once a caller stopped waiting. When writing any multi-step async flow (provider calls, caches, delays, connection setup, streaming reads), treat the `AbortSignal`/cancellation token as a first-class...promptfoo/promptfoo10 discussions
- simplify complex algorithmsWhen implementing algorithms, prioritize simplicity and maintainability over premature optimization. Complex algorithms should be broken down into smaller, reusable components or replaced with simpler approaches when possible.prometheus/prometheus10 discussions
- Null-safe DefaultsWhen handling settings, parsed model outputs, and lookup results, assume values may be missing (None/empty), omitted, or of the wrong type. Prevent NoneType and KeyError crashes by applying a consistent null-safety pattern.the-pr-agent/pr-agent10 discussions
- Safe null handlingAlways implement robust null handling patterns to prevent unexpected behavior and crashes. Consider all edge cases where null values might affect calculations, type conversions, or data operations:pola-rs/polars10 discussions
- Extract duplicated codeIdentify and extract duplicated code into reusable functions or move common fields to parent structures. This makes the codebase more maintainable and reduces the risk of inconsistencies when code needs to be updated.pola-rs/polars10 discussions
- prefer simple readable codeWrite code that prioritizes clarity and simplicity over cleverness. This improves maintainability and reduces cognitive load for other developers. Key practices:python-poetry/poetry10 discussions
- Use descriptive identifier namesChoose specific, descriptive names for variables, methods, types, and other identifiers that clearly communicate their purpose and behavior. Avoid generic names, unnecessary abbreviations, and assumptions about usage context.microsoft/playwright10 discussions
- Consistent descriptive namingUse clear, descriptive names that follow consistent patterns established in the codebase and broader programming standards. This includes: 1. Choose unambiguous function names that clearly communicate purpose and behavior:opencv/opencv10 discussions
- configuration resolution patternsWhen defining configuration schemas, use consistent patterns for safe property access, async resolution, and default value handling. Always use optional chaining with fallback values for nested configuration properties, leverage `$resolve` for complex async configuration logic, and ensure proper backwards compatibility.nuxt/nuxt10 discussions
- type-safe database operationsImplement proper type conversion and validation when working with different database systems to prevent runtime errors and data corruption. This is critical when handling data types that behave differently across database engines.rocicorp/mono10 discussions
- Precise Scenario-Based TestingWhen writing tests, ensure they (1) match the scenario name and input data, (2) exercise behavior through the appropriate layer (prefer public/high-level APIs so defaults/precedence are covered), (3) use the project’s DOM test helpers/fixtures and avoid unnecessary mocks/polyfills, and (4) assert specific outcomes (including exact error messages) rather...mermaid-js/mermaid10 discussions
- Consistent Naming RulesAdopt consistent, explicit identifier naming across diagrams and TypeScript APIs. **Rules** 1) **Diagram ids/syntax keywords** - Use **lower-case** diagram identifiers.mermaid-js/mermaid10 discussions
- Avoid unnecessary autoUse explicit types instead of `auto` unless the type is obvious from the right-hand side of the assignment or impossible to spell. The LLVM coding standards recommend avoiding `auto` in most cases to improve code readability and maintainability.llvm/llvm-project10 discussions
- TypeScript naming standardsFollow consistent naming conventions in TypeScript to improve code clarity, type safety, and developer experience: 1. **Capitalize types and interfaces**: All type and interface names should start with an uppercase letter.langchain-ai/langchainjs10 discussions
- simplify code structurePrioritize code simplification by removing unnecessary complexity, avoiding duplication, and leveraging existing utilities. This improves readability and maintainability while reducing potential bugs.kubernetes/kubernetes10 discussions
- Nil-Safe Input NormalizationWhen handling optional/null values, normalize and guard them at the boundary so downstream code never has to guess. Apply these rules: 1) Keep safe fallbacks for optional config fields (don’t delete “default” logic unless the field is strictly required).Kong/kong10 discussions
- Concurrency primitive semanticsWhen introducing async work, retries, or batching: 1) Use each concurrency primitive for its intended role - Don’t repurpose a queue as a parallel executor. If you need the same per-entry logic from both the queue and direct callers, extract it into a shared function/module and have both paths call it.Kong/kong10 discussions
- Define technical terms clearlyAlways define technical terms and concepts explicitly in documentation rather than assuming reader knowledge. Avoid ambiguous phrasing that could be interpreted multiple ways.jj-vcs/jj10 discussions
- Handle errors with careAlways implement comprehensive error handling for asynchronous operations, external API calls, and database operations. Catch errors at appropriate levels, log them with sufficient context for debugging, and provide meaningful error responses or recovery mechanisms.elie222/inbox-zero10 discussions
- Write effective, deterministic testsEvery test must genuinely validate the behavior it claims to cover, run deterministically, and avoid noise from redundant or stale cases. - **Verify the test actually fails without the fix.** Before adding a regression test, temporarily revert the fix and confirm the test fails. A test that passes on both old and new code gives false confidence (e.g....honojs/Hono10 discussions
- Prefer concise idiomatic syntaxWrite code using the shortest, most idiomatic form that remains clear, and stay consistent with the project's established conventions rather than reverting to verbose patterns. Concretely:HONOJS/HONO10 discussions
- Config source alignmentBehavioral configuration must be documented and wired through the supported config system, with examples matching the actual runtime resolution. Apply these rules:nousresearch/hermes-agent10 discussions
- Minimize allocations and syscallsOptimize performance by minimizing unnecessary memory allocations and system calls. Key practices: 1. Avoid unnecessary String allocations: ```rust // Instead ofhelix-editor/helix10 discussions
- Explicit API ContractsWhen API behavior depends on client/provider capabilities, request-field validity, or protocol ordering, implement it via explicit contracts—not heuristics—and ensure the exposed responses match the runtime’s effective configuration.aaif-goose/goose10 discussions
- Accurate Recovery Error HandlingCoding standard for recovery/error paths: make failure and recovery behavior truthful, gated, and user-consistent. Apply this rule set: 1) Ground messages and state on authoritative runtime outcomes (avoid predicates/flags that can drift from behavior). If the only way to know is to attempt (e.g., reset/clear), attempt and then report based on the result.aaif-goose/goose10 discussions
- AI model integration patternsWhen integrating with AI models and LLMs, structure your code to properly handle model responses, separate concerns between layers, and implement robust failure detection mechanisms.google-gemini/gemini-cli10 discussions
- Validate Block JSONEnsure every `curriculum/structure/blocks/*.json` file matches the CI-validated schema and constraints. - Remove deprecated/unused fields (e.g., `name`)—CI may reject these.freeCodeCamp/freeCodeCamp10 discussions
- Documentation clarity rulesWhen writing technical curriculum/docs, ensure the content is (a) accurate, (b) unambiguous about what learners must do and what the expected output/input is, and (c) consistent in formatting and tone.freeCodeCamp/freeCodeCamp10 discussions
- Optimize for code readabilityPrioritize code readability over clever solutions by: 1. Using early returns to reduce nesting 2. Leveraging modern PHP features when they improve claritylaravel/framework10 discussions
- Explicit nullish checksAvoid relying on loose truthiness (`||`, `!x`) when the goal is to detect "missing" (`null`/`undefined`) values, since this also matches other valid falsy values like `''`, `0`, and `false`, silently discarding legitimate input. Use explicit, strict checks that only target nullish values: `x === undefined`, `x == null` (catches both `null` and `undefined`),...expressjs/Express10 discussions
- optimize algorithmic efficiencyChoose efficient data structures and algorithms to minimize computational overhead and improve performance. This involves selecting appropriate containers based on usage patterns, avoiding unnecessary operations like redundant copies or conversions, and leveraging optimized library functions.electron/electron10 discussions
- Use descriptive namesChoose names that clearly describe the purpose, behavior, or content of variables, methods, and classes. Avoid ambiguous or generic names that require additional context to understand.langgenius/dify10 discussions
- Safe null handlingHandle null and undefined values safely by using appropriate fallback patterns, validating critical parameters early, and avoiding mutable default arguments.langgenius/dify10 discussions
- organize code structureMaintain clean code organization by moving implementation details to appropriate locations, extracting reusable functionality, and keeping related code together. This improves maintainability and prevents bugs from poor encapsulation.denoland/deno10 discussions
- Centralize dependency managementManage dependencies at the top level using `<dependencyManagement>` to ensure version consistency across modules and prevent conflicts. Define version properties in one place and reference them throughout the project:deeplearning4j/deeplearning4j10 discussions
- Lock the right resourceWhen protecting shared mutable state, make sure the synchronization actually covers the memory that other threads can see and mutate, and scope it correctly:python/cpython10 discussions
- Use structured logger consistentlyAdopt a single logging approach across commands and services: - **Never use `print`/direct `FileHandle.standardError.write` in production code** for user-facing or diagnostic messages. Use `Logger`.apple/container10 discussions
- Telemetry event integrityTreat telemetry as data that other code and dashboards depend on, not as scattered debug prints. Register every new event in the central catalog (e.g. `CORE_TELEMETRY_EVENTS`) with a typed `captureX` helper instead of calling `.capture()` with a raw string literal or ad-hoc properties — this keeps names consistent and is enforced by catalog-consistency...cline/cline10 discussions
- Nullability semantics firstTreat null/undefined/omitted values as distinct states and make that distinction explicit in both types and request/transition logic. Apply these rules:Cline/Cline10 discussions
- Async Claims And GenerationsWhen an async flow “resolves” shared state (answers a question, updates UI/model state, applies attach/detach replies, forwards terminal input, writes checkpoint hashes, etc.), treat concurrency as a first-class contract:Cline/Cline10 discussions
- Graceful error handlingImplement robust error handling that provides fallback mechanisms, ensures proper resource cleanup, and delivers user-friendly error messages without exposing internal details.snyk/cli10 discussions
- Restrict public accessCloud resources should be configured to restrict public network access by default to minimize potential attack surfaces. Always explicitly disable public-facing endpoints and network interfaces unless absolutely necessary for the service to function.bridgecrewio/checkov10 discussions
- Extract focused functionsBreak down complex logic into small, well-named functions that each do one thing well. This improves code readability, maintainability, and testability by making the code's intent clearer and reducing cognitive load.bridgecrewio/checkov10 discussions
- Consistent naming conventionsMaintain consistent naming patterns throughout the codebase to improve readability and reduce confusion: 1. **Use descriptive names that reflect purpose**:bridgecrewio/checkov10 discussions
- Document version annotationsWhen a doc section introduces a new configuration option or feature, include accurate version metadata (Celery and, when relevant, the dependency/library version). Missing or incorrect `.. versionadded::` causes confusion about availability.celery/celery10 discussions
- Deterministic exception handlingWhen handling errors, ensure (1) you don’t accidentally change which exception path fires, (2) recovery/cleanup is deterministic, and (3) any wrapping/aggregation preserves context and remains actionable.celery/celery10 discussions
- Avoid Unnecessary WorkPrefer eliminating work that can’t affect observable behavior and prevent resource retention in hot paths. Apply this as a checklist: 1) Guard mode-dependent logic: if the subsystem doesn’t propagate updates (or the surrounding condition is false), skip the computation/action entirely.celery/celery10 discussions
- Prefer explicit nil handlingHandle nil values explicitly and consistently to improve code clarity and type safety. Follow these guidelines: 1. Use early returns for nil validation:Homebrew/brew10 discussions
- Prevent Secret LeakageApply strict trust boundaries to authentication/credential state: - **Reset per-request sensitive fields on reuse** (especially pooled request/contexts). Never let prior request overrides (keys, base URLs, auth headers) bleed into later requests.maximhq/bifrost10 discussions
- Immutable Snapshots And GatesWhen concurrency crosses subsystem boundaries (HTTP handlers, streaming, background workers, plugin hooks), treat shared state as immutable and coordinate lifecycle explicitly.maximhq/bifrost10 discussions
- consistent configuration handlingEnsure configuration options are handled uniformly across all API endpoints and providers. Configuration should have clear precedence rules, support dynamic values where appropriate, and avoid hardcoded fallbacks.better-auth/better-auth10 discussions
- Type-safe flexible APIsDesign APIs that favor both type safety and flexibility. Use strongly typed wrappers instead of primitive types, but accept generic parameters where flexibility is beneficial.tokio-rs/axum10 discussions
- Validate environment variablesAlways validate environment variables before use and implement proper fallback strategies. For required variables, fail fast with clear error messages. For optional variables with empty values, ensure they don't short-circuit fallback chains.appwrite/appwrite10 discussions
- Handle errors gracefully alwaysAlways implement graceful error handling for resource lookups, data parsing, and system operations. Catch specific exceptions, provide clear error messages, and ensure the system can continue operating in a degraded state rather than failing completely.appwrite/appwrite10 discussions
- Enforce API endpoint consistencyWhen implementing or modifying API endpoints, ensure consistency across related routes by checking: 1. Parameter naming matches between route definition and handler:appwrite/appwrite10 discussions
- optimize algorithmic efficiencyEliminate unnecessary operations and choose appropriate data structures to improve algorithmic efficiency. Look for opportunities to remove redundant computations, avoid unnecessary allocations, and leverage built-in methods instead of manual implementations.alacritty/alacritty10 discussions
- Consistent semantic namingUse clear, consistent, and semantic naming patterns across your codebase to improve readability and maintainability: 1. **Start function names with verbs** that describe the action being performed:vercel/ai10 discussions
- Document behavior clearlyFor every snippet/glossary entry, the documentation must make the implementation’s behavior and constraints immediately clear—especially anything that can surprise users.30-seconds/30-seconds-of-code10 discussions
- Stable, Controllable APIWhen changing or adding public API in schema/validation libraries, prioritize a stable, user-controlled surface: - Avoid “deprecated-from-day-1” APIs. If an equivalent non-deprecated API already exists, prefer removing/migrating rather than adding new deprecated entry points.colinhacks/zod9 discussions
- Prefer idiomatic Option handlingWhen handling null values in Rust, use idiomatic Option patterns instead of verbose nested conditionals. This improves code readability, safety, and reduces the chance of runtime errors.zed-industries/zed9 discussions
- Manage bindings and stateEnsure components explicitly initialize reactive state, manage input/keybinding lifecycle, and decide whether children should subscribe to live atoms or use a stable snapshot.wavetermdev/waveterm9 discussions
- Structured, Meaningful TestsTests should follow consistent structure and provide high-signal coverage. Apply these rules: 1) Put tests in dedicated files - Follow the repo convention: place unit tests in separate `*_tests.rs` (or `*_test.rs`) files, not inline `#[cfg(test)] mod tests { ... }` blocks.warpdotdev/warp9 discussions
- Eliminate unnecessary code patternsRemove redundant code patterns that add complexity without value. This includes: 1. Duplicate code blocks - Extract shared logic into reusable functionsmicrosoft/vscode9 discussions
- Extract reusable functionsWhen you identify duplicate code blocks, complex logic that can be simplified, or functionality that doesn't belong in its current location, extract it into well-named, reusable functions. This improves code organization, reduces duplication, and enhances readability.volcano-sh/volcano9 discussions
- Avoid magic numbersReplace hardcoded values and magic numbers in AI model code with named constants or configuration parameters. This improves maintainability, reduces errors, and makes code more adaptable to different model architectures.vllm-project/vllm9 discussions
- Write clear test casesStructure test cases for maximum readability and maintainability by following these principles: 1. Organize each test in three distinct parts separated by blank lines:Unstructured-IO/unstructured9 discussions
- validate configuration defaultsConfiguration parameters should be properly validated with appropriate defaults and clear handling of edge cases. Avoid using arbitrary defaults when values should be explicitly required, and ensure configuration validation distinguishes between None, empty, and zero values.Unstructured-IO/unstructured9 discussions
- Use descriptive specific namesNames should be descriptive and specific enough to clearly communicate their purpose and avoid confusion. This includes using full words instead of abbreviations, being domain-specific when necessary, and ensuring names accurately reflect the function's behavior or data's purpose.twentyhq/twenty9 discussions
- Propagate errors with contextProperly propagate errors to callers with sufficient context rather than handling them prematurely or hiding them. Let the caller decide how to handle errors when they have the appropriate context.vercel/turborepo9 discussions
- Release locks before wakingIn concurrent systems, it's critical to release locks before performing operations that might trigger reentrancy or block the current thread, such as waking waiters. Holding locks while waking tasks can lead to deadlocks if the awakened code attempts to acquire the same lock.tokio-rs/tokio9 discussions
- Use consistent error handlingApply standardized error handling patterns across your codebase for improved reliability and debugging. For new code, use the `absl` error types instead of `tsl::errors` and include descriptive error messages with context.tensorflow/tensorflow9 discussions
- Use descriptive namesChoose names that clearly indicate their purpose and behavior rather than using generic or ambiguous terms. Avoid internal abbreviations in user-facing content, ensure function names accurately reflect what they do, and prefer specific descriptive terms over generic ones.gravitational/teleport9 discussions
- thoughtful configuration designWhen designing configuration schemas and fields, carefully consider their placement, validation, and long-term implications to prevent conflicts, maintain compatibility, and ensure good user experience.gravitational/teleport9 discussions
- use modern null-safe operatorsPrefer modern JavaScript null-safe operators over verbose conditional checks to improve code readability and prevent null-related errors. Use optional chaining (?.) for safe property access, nullish coalescing (??) for default values, and nullish coalescing assignment (??=) for lazy initialization.sveltejs/svelte9 discussions
- prefer simple code patternsChoose straightforward, readable code patterns over complex or clever alternatives. This improves maintainability and reduces cognitive load for other developers.sveltejs/svelte9 discussions
- Configurable model selectionAvoid hard-coding model names and provider-specific configurations throughout the codebase. Instead, implement flexible model selection patterns that support runtime configuration and consistent naming conventions across different AI providers.browserbase/stagehand9 discussions
- Preserve API compatibilityWhen evolving APIs, maintain backward compatibility to avoid breaking client code. Consider these guidelines: 1. **Add overloaded methods instead of modifying signatures**: When adding parameters, create a new method rather than changing an existing one.spring-projects/spring-boot9 discussions
- avoid unwrap and panicReplace `.unwrap()` and `panic!()` calls with proper error handling to prevent crashes and improve robustness. When encountering potential failures, choose one of three approaches:servo/servo9 discussions
- API design patternsDesign APIs with appropriate parameter types, place conversion functions as trait implementations in the correct modules, and reuse existing patterns instead of creating new abstractions.servo/servo9 discussions
- consistent async/await usageWhen refactoring code to use async/await, ensure complete and consistent adoption throughout the function or module. Avoid mixing async/await syntax with .then() chains, as this creates confusing and hard-to-maintain code.serverless/serverless9 discussions
- Descriptive identifier namingChoose meaningful, self-explanatory names for variables, parameters, properties, and methods that clearly convey their purpose. Avoid abbreviations and acronyms unless they're widely understood industry standards.getsentry/sentry-php9 discussions
- Use descriptive namesNames should clearly and accurately describe their purpose, avoiding abbreviations, acronyms, and misleading terms. This applies to variables, functions, types, constructors, and modules.semgrep/semgrep9 discussions
- prefer simple readable codeChoose clarity and simplicity over clever or complex constructs. Avoid unnecessary abstractions, complex function compositions, and "clever" code patterns that sacrifice readability for brevity.semgrep/semgrep9 discussions
- avoid failwith patternsAvoid using `failwith`, `assert false`, and similar blunt error handling mechanisms that can turn recoverable errors into unrecoverable ones. Instead, prefer more robust approaches:semgrep/semgrep9 discussions
- Keep documentation purposefully minimalDocumentation should be concise, focused, and maintainable. Follow these principles: 1. Keep examples short and demonstrate one concept at a time 2. Avoid redundant documentation across related itemsrust-lang/rust9 discussions
- Specific exceptions with contextAlways throw the most specific exception type appropriate for the error condition and include contextual information in the error message. This helps developers quickly identify and fix issues.dotnet/runtime9 discussions
- Optimize memory accessWhen implementing performance-critical algorithms, carefully consider memory access patterns. Document alignment assumptions when using low-level operations like `MemoryMarshal.Cast` or SIMD intrinsics. Prefer reference-based APIs over pinning to avoid GC interference. For bulk operations, use specialized helpers like `LoadUnsafe(ref T source, nuint...dotnet/runtime9 discussions
- Follow naming patternsMaintain consistent naming patterns throughout your code to improve readability and maintainability. Follow these guidelines: 1. Use PascalCase for public methods and membersdotnet/runtime9 discussions
- Protect shared state accessEnsure thread-safe access to shared state by using appropriate synchronization mechanisms and atomic operations. Avoid race conditions by: 1. Using atomic operations or locks when modifying shared stateRooCodeInc/Roo-Code9 discussions
- Thread Ownership DisciplineWhen code can run on both main and IO threads, require an explicit ownership + synchronization rule for every shared piece of state (flags, counters, refcounts, pending lists, and memory frees). Concretely:redis/redis9 discussions
- Nullable Contracts EnforcementAdopt explicit, consistent nullability contracts for pointer/optional-field parameters and honor them at every call site. Practical rules: - **Document/decide whether a parameter may be NULL**. If it can’t, keep the check out; if it can, guard and define behavior.redis/redis9 discussions
- Bounded Prefetch BatchesWhen adding performance optimizations (prefetch/batching/fast paths), make them bounded, gated, and semantics-correct: - **Bound the work**: use fixed small batch sizes (e.g., 16) and stack-backed buffers with a safe default cap; avoid strategies where user-controlled sizes can force huge allocations (e.g., `vecReserve(count)` without a ceiling).redis/redis9 discussions
- prefer Kotlin idiomsUse Kotlin-specific constructs and syntax patterns instead of Java-style code to improve readability and maintainability. This includes leveraging Kotlin's expressive syntax features and standard library functions.facebook/react-native9 discussions
- Self-documenting identifier namesUse clear, self-documenting names for variables, methods, and classes that express intent without exposing unnecessary implementation details. **For methods and variables:**rails/rails9 discussions
- Layer security defensesImplement multiple layers of security throughout your application rather than relying on a single protection mechanism. This defense-in-depth approach significantly improves your application's security posture.rails/rails9 discussions
- Bound Work and QueriesWhen improving performance, make sure code neither (a) fetches too much data, nor (b) does the same expensive work repeatedly, nor (c) runs unbounded workloads.infiniflow/ragflow9 discussions
- Null-Safe ParsingEnforce null/optional safety at every boundary: treat external API data and persisted JSON as untrusted, validate before dereferencing, and ensure normalization/parsing preserves only values that satisfy the declared type contract. Never let invalid optional fields “leak through” via `...raw` spreads or falsy-based numeric checks; degraded modes must remain...QwenLM/qwen-code9 discussions
- Defense-in-depth Security GuardrailsWhen handling security-sensitive interactions (authz/ownership, network callbacks, and untrusted execution), apply defense-in-depth at the boundaries: be precise about guarantees, bind authorization to explicit identities at creation time, validate inbound payloads before side effects, and isolate both execution and filesystem writes.QwenLM/qwen-code9 discussions
- Stable, lifecycle-correct hooksEnsure React hooks and query integrations remain correct across renders, SSR/hydration, and subscriptions. Rules: 1) Keep QueryClient stable in React componentstanstack/query9 discussions
- Semantic naming consistencyUse names that match the value’s real meaning and align with established/public API conventions. Practical rules: - **Name by semantics, not by adjacent intuition**: if “context” is being reinterpreted, rename (and deprecate old names with clear JSDoc) rather than silently changing what the term means.tanstack/query9 discussions
- Maintain Docs IntegrityDocumentation should be kept correct and maintainable like code: ensure pages are registered, links are stable/valid, and shared doc sections follow the adapter conventions.tanstack/query9 discussions
- Verify token security levelWhen refreshing or updating authentication tokens, always verify the new token maintains or exceeds the original token's security level. This applies to WebSocket connections, step-up authentication scenarios, or any case where tokens are refreshed during an active session.quarkusio/quarkus9 discussions
- Self-Documenting Naming RulesUse self-documenting identifiers: variable/function/class names should explain intent without relying on comments, and avoid confusing or ambiguous abbreviations.TheAlgorithms/Python9 discussions
- minimize memory allocationsPrioritize memory allocation minimization through buffer reuse, pre-allocation, and efficient data structures. Allocations are among the worst performance bottlenecks, especially in hot paths and frequently called functions.prometheus/prometheus9 discussions
- refactor complex conditionsBreak down complex inline conditions and nested logic into separate, well-named functions or simpler expressions to improve code readability and maintainability.prettier/prettier9 discussions
- Use descriptive namesChoose names that clearly communicate purpose and accurately represent what they describe. Avoid ambiguous or misleading names that require additional context to understand.PostHog/posthog9 discussions
- Appropriate error handlingDistinguish between implementation errors (invariant violations) and expected failure cases. For implementation errors that should never occur, use `unreachable!()` with explanatory comments rather than generic `panic!()` or `todo!()`. For expected failure modes, return proper error types with informative messages.pola-rs/polars9 discussions
- explicit configuration specificationAlways explicitly specify configuration values rather than relying on defaults or implicit behavior. Poetry requires unambiguous configuration to function correctly, and many issues arise from incomplete or assumed specifications.python-poetry/poetry9 discussions
- Use semantically accurate namesVariable, method, and class names should accurately reflect their actual behavior and purpose. Misleading or vague names create confusion and make code harder to understand and maintain.commaai/openpilot9 discussions
- Prefer explicit readable codeWrite code that prioritizes readability and explicitness over cleverness or brevity. This includes several key practices: **Import Organization**: Follow standard import ordering - stdlib and third-party imports first, then openpilot imports after a blank line:commaai/openpilot9 discussions
- Standardize Typed ErrorsUse consistent, typed exceptions at the point of failure, with structured context, and never rely on unchecked/bypassed paths that convert errors into later crashes.openai/openai-python9 discussions
- Preserve API ContractsWhen transforming data to/from the API, always implement the backend’s explicit contract: ordering invariants, exact serialization, correct parsing by response format/content-type, endpoint-appropriate headers, and backend-specific URL/auth/version rules.openai/openai-python9 discussions
- Code Style, Typing, DRYAdopt a “type-safe, clean, DRY” style for readability and maintainability. - Prefer module-scope imports: don’t re-import a module inside a function if it already exists at file scope.openai/openai-python9 discussions
- Local Clarity StandardsWhen updating code, optimize for local clarity and correctness, not “cleanup” by indirection. Apply these rules: 1) Prefer locality over forced DRY - If a constant/abstraction is used once, keep it local. Don’t add module-scope indirection unless it materially improves maintainability.diegosouzapw/OmniRoute9 discussions
- Fail Safe Error PropagationEstablish an error-handling standard that prevents crashes/hangs, preserves root errors, and makes recovery bounded and verifiable. Guidelines: - Catch safely: prefer `catch (err: unknown)` and narrow before reading fields.diegosouzapw/OmniRoute9 discussions
- Validate and scope configuration changesConfiguration values from settings, CLI flags, YAML, or environment variables are untrusted input and must be validated/normalized at the point of use, not just cast through a schema. Loosely-typed arrays or fields (e.g. a model-id list) can still receive non-string or malformed entries from `config set` or hand-edited YAML; guard every element with a...can1357/oh-my-pi9 discussions
- Never silently swallow errorsEmpty `catch {}` blocks hide real failures and make debugging impossible; several reviews found bugs that existed only because a failure path logged nothing. Treat every catch as a decision point, not a place to discard information:can1357/oh-my-pi9 discussions
- Enforce security checks everywhereSecurity-sensitive logic—credential/secret redaction, data-scope isolation, authorization/allowlist matching, and output sanitization—must be enforced on every code path that can reach the sensitive data or untrusted input, not just the common or first-discovered path. Audit all entry points (alternate parsers, fallback branches, defaults, display paths)...can1357/oh-my-pi9 discussions
- Edge-case-complete path/text algorithmsWhen an algorithm walks a filesystem tree or parses structured text (e.g. resolving `.git` pointer targets, classifying nested repositories, or parsing git-config), base every decision on the actual underlying mechanism rather than a proxy signal, and enumerate the real-world edge cases the mechanism allows before calling the logic complete.can1357/oh-my-pi9 discussions
- Semantic over generic namesChoose specific, descriptive names that clearly convey purpose over generic or abbreviated identifiers. Names should be self-documenting and unambiguous about their role.netty/netty9 discussions
- Document public APIsAll public-facing APIs must be thoroughly documented with clear javadocs. This includes: 1. **Classes and interfaces**: When creating or changing a class/interface to public visibility, add comprehensive documentation explaining its purpose and usage.netty/netty9 discussions
- Explicit default configurationsAlways provide explicit default values for configuration options to improve code readability and maintainability. Use helper methods consistently for default value management, and document defaults clearly.nestjs/nest9 discussions
- Choose meaningful identifier namesNames for variables, methods, and classes should be descriptive, semantically accurate, and consistent with established conventions. Follow these guidelines:nestjs/nest9 discussions
- Deterministic CI RunsEnsure GitHub Actions CI runs are repeatable, targeted, and don’t rely on brittle hacks. 1) Run tests using the environment you just prepared - If you use `uv sync`, run pytest using the created venv/python (or otherwise guarantee `uv run` uses the synced environment without re-installing).karpathy/nanochat9 discussions
- Vue component test requirementEvery Vue component (.vue file) that is created or modified must have at least one corresponding unit test file. The test must import the component, mount it, and include assertions that validate its behavior.n8n-io/n8n9 discussions
- Avoid Duplication MagicWhen updating code, prioritize maintainability and readability by removing duplicated blocks, eliminating magic numbers, and keeping formatting/imports tooling-friendly.mermaid-js/mermaid9 discussions
- Fail-Closed Input SanitizationAll externally supplied values must be validated/escaped for the *exact* security-sensitive context they’re interpolated into, and security checks must be fail-closed (no bypass via fallbacks, parse differences, redirects, caches, or policy typos).awslabs/mcp9 discussions
- Accurate API ContractsFor API/tool-facing code, treat the external API contract as non-negotiable: validate parameter bounds against the upstream model/docs, handle pagination only when the API is actually paginated, and ensure your client/tool surface (operation routing, errors, and side-effect metadata) is explicit and consistent.awslabs/mcp9 discussions
- Use descriptive specific namesChoose descriptive, specific names that clearly communicate intent and behavior rather than generic or ambiguous alternatives. Names should be self-documenting and reduce the need for additional context or comments.mastodon/mastodon9 discussions
- Ensure semantic naming accuracyNames should accurately reflect the actual behavior, purpose, and scope of functions, variables, and classes. Misleading or inaccurate names create confusion and maintenance burden.logseq/logseq9 discussions
- Use descriptive consistent namesChoose names that clearly convey their purpose, role, and meaning while maintaining consistency with established patterns in the codebase. Names should be self-documenting and unambiguous to future maintainers.LMCache/LMCache9 discussions
- Safe access patternsAlways use safe access methods when working with potentially null or undefined values. Use .get() for dictionary access, check array bounds before indexing, and validate existence before operations.BerriAI/litellm9 discussions
- AI provider documentation completenessEnsure comprehensive documentation for AI/ML provider integrations that covers all usage patterns, uses precise terminology, and provides helpful context for developers.BerriAI/litellm9 discussions
- Sync documentation with codeAlways ensure documentation and comments accurately reflect the actual code implementation. When modifying code, update all related documentation to maintain consistency. This applies to:langfuse/langfuse9 discussions
- Consolidate related informationKeep related documentation content together on a single page rather than fragmenting it across multiple pages. When users need to understand a complete concept or workflow, they should be able to find all relevant information in one location without having to navigate between multiple pages.langflow-ai/langflow9 discussions
- API documentation completenessEnsure API documentation provides comprehensive, accurate information including limitations, complete workflow examples, and proper cross-references. API documentation should clearly state what endpoints do, what they don't support, their constraints, and how they fit into larger workflows.langflow-ai/langflow9 discussions
- Prefer Robust Testing AssertionsWhen adding/changing tests, optimize for (1) clear intent, (2) stability against refactors, and (3) determinism. Practical rules: - Assert observable behavior, not intermediate implementation details. If you need to validate a request payload, mock the SDK client and inspect what was actually sent (not private helpers/step-by-step logic).langchain-ai/langchain9 discussions
- Avoid shared mutable stateWhen working with concurrency (threads/async), ensure code is safe under parallel invocations and does not block or re-enter running event loops. Rules:langchain-ai/langchain9 discussions
- Observability Signal QualityWhen changing or adding metrics/traces, make signals stable, accurate, and alert-friendly. **Apply these rules before submitting:** 1) **Preserve metric semantics and document scope**kUbernetes/kUbernetes9 discussions
- Hot-Path Performance RulesDefault to performance-aware coding for hot paths (proxy routing, request parsing, metrics/serialization, and request body handling): - **Avoid unnecessary periodic work**: only schedule timers or run refresh logic when the correctness mode requires it.Kong/kong9 discussions
- Document Split ContractsWhen implementing algorithmic transformations that clients depend on (especially split/partition functions and any logic that rebuilds/serializes structured strings), treat semantics as a stable API: explicitly define and document the contract (edge cases, limits, nil/empty handling, delimiter rules), and guarantee deterministic output by not relying on...Kong/kong9 discussions
- Deterministic isolated testingMake integration/unit tests deterministic, isolated, and robust against async timing and ordering. Checklist - **No ordering dependence:** Each test must be runnable alone; avoid modifying a shared plugin/config mid-suite. For configuration permutations, create separate routes/services (or fully separate instances) per permutation.Kong/kong9 discussions
- Use semantically accurate namesChoose names that accurately reflect the purpose, scope, and semantics of variables, methods, and classes. Names should be self-documenting and eliminate ambiguity about what the code element represents or does.apache/kafka9 discussions
- eliminate redundant codeRemove unnecessary code, operations, and annotations that don't add value. This includes redundant type annotations when types are already constrained, unnecessary conditional checks, redundant operations like path normalization in multiple places, and overly complex patterns that can be simplified.jj-vcs/jj9 discussions
- Simplify code structurePrioritize code simplicity and readability by leveraging standard library functions, improving control flow patterns, and eliminating unnecessary complexity.istio/istio9 discussions
- Add explanatory commentsCode should include explanatory comments that help future maintainers understand complex logic, design decisions, field semantics, and non-obvious implementation details. Comments are especially important for:istio/istio9 discussions
- Use adaptive load-balanced streamsWhen adding/updating HLS stream URLs, pick the network endpoint that is most likely to work reliably: - Prefer adaptive HLS entrypoints (e.g., `master.m3u8`, `playlist.m3u8`, `manifest.m3u8`, `index.m3u8`) instead of redirect chains or single-bitrate links.iptv-org/iptv9 discussions
- Avoid Tokenized Stream URLsDo not include ephemeral authentication parameters (e.g., `session=`, `tkn=`, `hash=`, `sign=`) or other provider-specific auth wrappers in static `.m3u` entries. These links commonly expire (“timebomb”) and/or may be IP-locked, causing playback failures and turning the playlist into a security-sensitive artifact. Also, reject/omit link types your system...iptv-org/iptv9 discussions
- Use transactions for consistencyAlways wrap multiple related database operations in a transaction to ensure data consistency and prevent partial updates. This applies to operations across different tables or when coordinating database updates with external services (e.g., Redis cache).elie222/inbox-zero9 discussions
- Remove commented codeCommented-out code should be removed from the codebase rather than left as comments. Keeping commented code: 1. Clutters the codebase and reduces readabilityelie222/inbox-zero9 discussions
- Benchmark hot-path optimizationsFor code on frequently executed paths (request handling, routing, serialization, middleware), base optimization decisions on actual benchmarks rather than assumptions, and avoid introducing redundant work. Concretely:HONOJS/HONO9 discussions
- Benchmark-driven hot-path optimizationFor code that executes on every request or in other hot paths (router matching, context/response creation, param decoding, JSX stringification, etc.), prioritize measured performance over assumed performance, and avoid redundant work.honojs/Hono9 discussions
- Accurate null/undefined handlingMake nullability explicit in types and handle it precisely instead of papering over it with assumptions. 1. Type signatures must reflect real-world nullability. If a value can be `undefined` or `null` at runtime (e.g. `c.req.param('id')`, a ref's initial value, a route path when no match exists), the type and tests must say so instead of claiming a...honojs/Hono9 discussions
- Use Null-Safe Config ReadsTreat every potentially-null/nullable config subsection and external payload field as untrusted: normalize it before accessing deeper keys or calling methods.nousresearch/hermes-agent9 discussions
- Secure Rendering And FetchAll untrusted inputs must be hardened at their security boundaries: (1) for network calls, validate the destination on every redirect hop (and ideally after DNS resolution), and (2) for any rendered or embedded output, sanitize/encode for the exact output context to prevent XSS and script-breaking.nousresearch/hermes-agent9 discussions
- Bounded Hot-Path WorkIn performance-sensitive hot paths, ensure you (1) don’t repeat expensive work, (2) keep async/event-loop paths non-blocking, (3) bound external operations with finite timeouts, and (4) avoid unnecessary computation/materialization by prefiltering queries and projecting only what’s needed.nousresearch/hermes-agent9 discussions
- Behavioral Regression TestingWhen adding or modifying tests, favor *behavioral contract* coverage over brittle implementation/shape checks. Apply these rules: - **Test the outcome, not the shape**: drive the code through the real wiring/dispatch path and assert the externally observable behavior (e.g., callback fires once after a cap; command output path rewrites; retry-after falls...nousresearch/hermes-agent9 discussions
- plugin contract APIDefine a clear, minimal plugin contract and loader API for all external/ built-in plugins. Motivation: plugins (taggers/scorers) are the public extension points of the system and must declare what data they need, how they initialize, and be loadable from arbitrary modules so users can provide custom implementations without modifying the project.p-e-w/heretic9 discussions
- Memoize derived stateAvoid using `useState` + `useEffect` to compute values that can be derived directly from existing props, state, or query results. Filtering, mapping, formatting, or any other pure transformation of existing data should be wrapped in `useMemo` (with the correct dependency array) rather than recomputed on every render or pushed into local state via an effect.Helicone/helicone9 discussions
- Extract repeated codeIdentify and extract repeated code patterns into well-named functions to improve readability, maintainability, and testability. Look for blocks of code that appear in multiple places or complex operations that can be encapsulated with a descriptive function name.grafana/grafana9 discussions
- eliminate code duplicationActively identify and eliminate code duplication by extracting repeated logic into reusable functions, using loops instead of repetitive code blocks, and consolidating similar implementations. When you find yourself copying and pasting code or writing nearly identical logic multiple times, refactor it into a shared function or use iteration patterns.block/goose9 discussions
- Bound async waitsIn async/concurrent code, always make cancellation/timeout behavior correct, deterministic, and safe against stale work. **Coding standard** 1) **Bound the full operation**: put `tokio::time::timeout` around the *entire* request/handshake/startup sequence that must not hang (including setup/config/mode steps).aaif-goose/goose9 discussions
- Code structure clarityWrite code with clear structural organization that enhances readability and maintainability. Extract duplicated or complex logic into well-named functions, avoid deeply nested conditionals, and use proper type organization.ghostty-org/ghostty9 discussions
- organize code by responsibilityPlace code at the appropriate abstraction level and extract complex logic to dedicated modules. Large files like App.tsx and gemini.tsx should focus on their core responsibilities, with specific functionality moved to specialized components or utility files.google-gemini/gemini-cli9 discussions
- Explicit null handlingUse explicit identity comparisons for null checks and leverage modern PHP null-handling features to create more reliable, readable code. ## Key practices:laravel/framework9 discussions
- Use idiomatic pytest featuresFavor pytest's built-in testing utilities over manual, imperative patterns to keep tests concise, correct, and maintainable. - Exception testing: use `pytest.raises(ExceptionType)` as a context manager instead of manual try/except blocks with `assert False` in the except clause. Code after the line that raises inside the `with` block is unreachable and...pallets/flask9 discussions
- minimize memory allocationsPrioritize reducing memory allocations and choosing efficient data structures to improve performance. Avoid unnecessary string/byte conversions, use maps for O(1) lookups instead of slices, and leverage compiler optimizations where possible.gofiber/fiber9 discussions
- Ensure comprehensive test coverageAll code paths, error conditions, and edge cases must have corresponding unit tests to ensure robust functionality and prevent regressions. This includes testing both success and failure scenarios, boundary conditions, and error handling paths.gofiber/fiber9 discussions
- Documentation translation guidelinesMaintain consistency and accuracy when translating documentation. Ensure technical terms and special formatting elements are handled properly according to project guidelines.fastapi/fastapi9 discussions
- Respect lint and syntax conventionsBefore introducing newer JavaScript syntax (ES6 classes, multiple `const` declarations, spread operators, template literals, etc.), verify it is actually supported by the project's configured linter and target Node/runtime compatibility. Several PRs had to be reverted or reworked because `eslint` rejected classes, template literals, or spread syntax that...Expressjs/Express9 discussions
- Incremental standard-style adoptionThe codebase is migrating toward the `standard` JavaScript style (no semicolons, multiple `const`/`let` declarations instead of comma-chained `var`, unindented chained method calls, space before function parentheses, etc.). Apply this style only to the lines you are already modifying, not as a wholesale reformat of untouched code — unrelated...expressjs/Express9 discussions
- conditional feature initializationOnly initialize configuration-dependent features, systems, or resources when the relevant settings, flags, or conditions are actually present or enabled. This prevents unnecessary resource allocation, avoids unwanted side effects like creating default contexts, and improves performance by deferring expensive operations until they're needed.electron/electron9 discussions
- Name reflects meaningChoose names that clearly communicate the intent, behavior, and semantics of code elements. Names should be accurate, consistent, and follow established patterns:elastic/elasticsearch9 discussions
- Eliminate code duplicationActively identify and eliminate code duplication to improve maintainability and reduce the risk of inconsistent behavior. This includes several strategies:duckdb/duckdb9 discussions
- avoid silent failuresAlways provide clear feedback when operations fail, even when continuing with fallbacks or alternative approaches. Silent failures make debugging extremely difficult and can lead to unexpected behavior in production systems.stanfordnlp/dspy9 discussions
- Use modern null handlingLeverage modern JavaScript operators and patterns for cleaner, more robust null and undefined handling. This improves code readability and reduces boilerplate while maintaining safety.discourse/discourse9 discussions
- minimize memory allocationsIdentify and eliminate unnecessary memory allocations in performance-critical code paths. This includes pre-allocating collections when the size is known, using static strings for common values, and avoiding intermediate data structures.denoland/deno9 discussions
- Remove debugging artifactsProduction code should be free from debugging artifacts that reduce readability and maintainability. Remove all debugging print statements, commented-out code blocks, and other temporary debugging elements before merging code.deeplearning4j/deeplearning4j9 discussions
- Use idiomatic conventionsWrite code that favors existing project idioms and clear control flow over ad hoc constructs, duplicated logic, or unnecessary complexity: - Avoid magic numbers; use the named constants the codebase already defines (e.g. `_Py_MAX_UNICODE` instead of hardcoding `0x10FFFF`), and use project-specific cast macros (e.g. `_PyMemoryView_CAST(v)`) instead of raw...python/cpython9 discussions
- Extract repeated logicWhen you notice code patterns being repeated across functions or methods, extract the common logic into separate, reusable functions. This improves maintainability, reduces bugs, and follows the DRY (Don't Repeat Yourself) principle.comfyanonymous/ComfyUI9 discussions
- Telemetry correctness and timingTelemetry must be (a) policy-compliant, (b) causally correct in time, and (c) semantically accurate in meaning—so monitoring never turns “what happened” into “something close”.cline/CLINE9 discussions
- Spec-Aligned Parsing AlgorithmsWhen implementing parsing/transform/estimation algorithms for structured inputs, prioritize **format-correct tokenization**, **stateful correctness**, and **complexity safety**.ClInE/cLiNe9 discussions
- Robust Async Error InvariantsAdopt a single standard for error handling in async/control-flow code: 1) **Never let setup/teardown exceptions escape their owner** - Ensure errors thrown inside helper callbacks (e.g., stream piping, attach, pipe setup) are caught and routed through the same failure path as rejected promises.cline/CLINE9 discussions
- Dependency-Aware CachingCaching is safe only when you (1) key by the full dependency set, (2) gate reads by a revision/stale check, (3) invalidate only the correct scope, and (4) handle async failures with rollback + bounded retries.ClInE/cLiNe9 discussions
- Cache correctness & retriesAdopt a single standard for all caches (data, discovery, warm-ups, and load-result caches): 1) Key by the real identity (include all dependencies) - Build cache keys from the complete set of inputs that affect the result (e.g., tool name + arguments; account scope + workspace root; plugin path + execution mode + registry status).CLINE/CLINE9 discussions
- Async race ownership rulesWhen multiple async operations can overlap with replacement/teardown (UI unmount, session rebuild, polling vs actions, stop/dispose, in-flight RPCs), require explicit *ownership* and *lifecycle binding*:CLINE/CLINE9 discussions
- Use descriptive namesChoose names that clearly communicate purpose, content, and intent. Avoid generic or ambiguous identifiers that require additional context to understand.snyk/cli9 discussions
- Fail gracefully alwaysEnsure code handles errors robustly by using protective patterns that prevent resource leaks, provide clear diagnostics, and degrade gracefully when possible:chef/chef9 discussions
- Safe dictionary navigationAlways use the `.get()` method with appropriate default values when accessing dictionaries instead of direct key access with brackets. This prevents KeyError exceptions when keys don't exist and provides predictable default values. For nested dictionaries, chain `.get()` calls with empty dictionaries as defaults for intermediate levels.bridgecrewio/checkov9 discussions
- Centralize environment variablesAll environment variables should be defined in a centralized location (`checkov/common/util/env_vars_config.py`) rather than scattered throughout the codebase. This approach enhances maintainability, promotes consistency, and simplifies tracking of configuration settings.bridgecrewio/checkov9 discussions
- Thread-safe lifecycle isolationWhen changing concurrency/background execution, ensure (a) state is isolated per thread/consumer/instance, and (b) shutdown/cleanup and exception signaling are coordinated with explicit synchronization.celery/celery9 discussions
- Authorization hierarchy verificationAlways implement comprehensive authorization checks that verify user permissions at the appropriate hierarchy level (individual → team → organization) before allowing operations. Consider multiple permission levels and provide proper fallbacks when users have different roles across teams or organizations.calcom/cal.com9 discussions
- Contract-First DocumentationAll documentation should behave like an interface: precise contracts, unambiguous rule precedence, and resilient references. Apply this standard by: bmad-code-org/bmad-method9 discussions
- Ensure comprehensive test coverageWhen implementing new functionality or modifying existing code, always add corresponding tests that comprehensively cover the changes. This includes testing the main functionality, edge cases, error conditions, and different execution paths.bazelbuild/bazel9 discussions
- Documentation quality standardsEnsure documentation is specific, complete, and actionable for developers: 1. **Provide meaningful content** - Avoid vague descriptions like "Test changes" in changelogs. Instead, be specific about what was modified or tested:Azure/azure-sdk-for-net9 discussions
- Infer DependenciesWhen modeling Bicep resources, prefer symbolic references and proper parent/child wiring so ARM/Bicep can infer ordering automatically. This improves readability (fewer manual `dependsOn`/hand-built IDs) and reduces dependency bugs.Azure/azure-quickstart-templates9 discussions
- Idempotent RBAC AssignmentsWhen using Bicep to assign Azure RBAC roles, make roleAssignments deterministic and correct by: - Use the target principal’s **principalId** (e.g., managed identity principalId) rather than resourceId, and include it in the roleAssignment name seed.Azure/azure-quickstart-templates9 discussions
- Naming convention alignmentWhen adding/adjusting commands, options, helpers, or telemetry, ensure names are (1) semantically accurate and (2) consistent with existing CLI/module conventions.Azure/azure-cli9 discussions
- Axum Code Review: Interaction PatternsWhen implementing Axum-based applications, it is crucial to ensure that the interaction patterns between components are well-designed and clearly documented. This includes understanding edge cases, limitations, and best practices around state sharing, router nesting, and extractor ordering.tokio-rs/axum9 discussions
- Ensure database transactional integrityWhen performing multiple related database operations, use transactions and proper error handling to maintain data consistency. Without proper safeguards, partial failures can leave your database in an inconsistent state with orphaned or mismatched records.appwrite/appwrite9 discussions
- Security Invariants GuardrailsWhen changing auth/secret/TLS/validation code, treat existing security semantics as invariants: refactors must not weaken them, and config defaults/warnings must be applied after schema normalization.apache/apisix9 discussions
- comprehensive test coverageEnsure test suites provide comprehensive coverage by including edge cases, different input scenarios, and all code paths. Tests should cover not just the happy path, but also boundary conditions, error cases, and various input combinations.angular/angular9 discussions
- Preserve and Map ErrorsStandardize error handling so failures remain diagnosable and user-facing messages are complete. Apply these rules: 1) Preserve diagnostic context when propagating/rethrowingcolinhacks/zod8 discussions
- Hot-Path Performance RulesDefault to the cheapest behavior: gate expensive work behind explicit options or conditions, and keep the parsing “fast path” strictly minimal. Practical rules:colinhacks/zod8 discussions
- Assert meaningful outcomesWhen writing tests, validate the *actual user-visible behavior and structured error data*, not just a substring or a indirectly implied result. Make failures unambiguous (no swallow-pass patterns) and keep tests easy to debug.colinhacks/zod8 discussions
- Use descriptive namesChoose names that clearly describe their purpose, behavior, and data type rather than generic or ambiguous alternatives. Function names should reflect what they actually do, variables should indicate their specific role, and parameter names should convey semantic meaning.cloudflare/workers-sdk8 discussions
- Informative error messagesError messages should provide specific context and actionable guidance to help developers understand and resolve issues effectively. Include relevant identifiers (class names, file paths, method names) and clear recovery instructions when possible.cloudflare/workers-sdk8 discussions
- dependency version constraintsEnsure consistent and appropriate dependency version constraints across all package.json files. Use flexible version ranges for peer dependencies to avoid forcing unnecessary upgrades, maintain minimum supported versions that align with project requirements, and keep template dependencies up-to-date for consistency.cloudflare/workers-sdk8 discussions
- Use appropriate exception typesChoose the correct exception handling mechanism and type based on the error condition's nature and audience. Use JSG_REQUIRE for user-controllable conditions that should result in JavaScript exceptions, and KJ_ASSERT for internal invariants that indicate programming errors. Provide friendly, actionable error messages for user-facing exceptions.cloudflare/workerd8 discussions
- Prioritize descriptive namingChoose clear, self-explanatory names that prioritize readability over brevity. Avoid abbreviations, obscure identifiers, and names that require domain knowledge to understand. Names should be immediately comprehensible to newcomers and future maintainers.cloudflare/workerd8 discussions
- isolate lock safetyAlways ensure proper isolate lock management and thread-safe access patterns when working with JavaScript contexts and cross-thread operations. Accessing JSG objects, IoContext, or V8 handles without holding the isolate lock leads to undefined behavior and crashes.cloudflare/workerd8 discussions
- Protect shared stateEnsure mutable shared data is never exposed or accessed without explicit synchronization. When data crosses goroutine boundaries you must either copy it, provide a concurrency-safe accessor that returns a snapshot, or protect it with proper synchronization (mutexes, atomics, or reference counting). This prevents races when marshaling, iterating, or doing...wavetermdev/waveterm8 discussions
- Favor reusable helpersCentralize repeated UI logic and prefer modern, consistent JS style. When you see duplicated logic, ad-hoc class strings, local copies of global state, or repeated boolean checks, extract them into small, well-named helpers (or model/computed methods) and apply consistent ES/React idioms.wavetermdev/waveterm8 discussions
- Secure Input and Secret HandlingAdopt a consistent rule: anything coming from persistence, other platforms/accounts, terminal escape sequences, or secret-managed inputs must be validated/normalized and handled with collision-safe, non-injectable, non-leaky logic.warpdotdev/warp8 discussions
- Bound Large WorkWhen code performs expensive IO/compute or reacts to frequent events, (1) gate side effects to meaningful state changes, (2) bound or chunk large inputs/outputs before allocation or heavy processing, and (3) cache/share to avoid repeated recomputation and deep clones.warpdotdev/warp8 discussions
- Deterministic Regression TestsWhen fixing or adding behavior, update tests so they deterministically exercise the exact event/guard path and assert observable outcomes—never rely on “happy-path only” coverage.microsoft/VSCode8 discussions
- Cache correctness rulesUse this checklist whenever you add or change caching: 1) Define dependencies: List every input/state that can change the correctness of the cached value (e.g., category+storage, account+marketplace URL, connection metered-state, ignoreCase spelling, DOM state).microsoft/VSCode8 discussions
- Vectorize over Python loopsReplace Python loops and list comprehensions with vectorized operations when processing tensors or performing repeated computations. This optimization reduces interpreter overhead and enables efficient parallel execution on modern hardware.vllm-project/vllm8 discussions
- Catch specific exception typesAvoid using broad exception handlers like `except Exception:` or bare `except:`. Instead, catch specific exception types that you expect and can handle meaningfully. This makes code more maintainable by:vllm-project/vllm8 discussions
- Prevent concurrent access racesWhen sharing data across goroutines, always use proper synchronization mechanisms to prevent race conditions. Race conditions are difficult to debug and can cause intermittent failures that only appear under load.vitessio/vitess8 discussions
- Meaningful consistent namingUse descriptive, semantically clear names that follow consistent patterns throughout the codebase. Names should convey purpose and follow established conventions.vitessio/vitess8 discussions
- Names should be descriptiveUse clear, descriptive names while avoiding redundant qualifiers. Choose full words over abbreviations unless the abbreviated form is widely recognized. When a type or context already implies certain qualities, avoid repeating them in the name.astral-sh/uv8 discussions
- Clear precise documentationDocumentation should use direct, precise language that accurately describes components and their behavior. Maintain consistent grammatical structure throughout related documentation sections for improved readability.astral-sh/uv8 discussions
- Use descriptive semantic namesChoose names that clearly communicate purpose, intent, and functionality rather than generic or abbreviated alternatives. Names should follow Rust conventions (snake_case for variables, functions, modules) and accurately describe what they represent or do.unionlabs/union8 discussions
- Optimize critical loopsWhen implementing algorithms with nested loops or recursive operations, carefully analyze the computational complexity and optimize the critical path. Pay attention to loop ordering, early termination conditions, and unnecessary recomputation.microsoft/typescript8 discussions
- simplify code structureWrite code that is easy to read and understand by avoiding unnecessary complexity in structure and logic. This includes several key practices: **Avoid complex nesting and nested ternaries:**twentyhq/twenty8 discussions
- Validate configurations comprehensivelyWhen implementing configuration systems, ensure comprehensive validation, testing, and documentation. Key requirements: 1. Use an allowlist approach - explicitly categorize and validate ALL configuration fieldsvercel/turborepo8 discussions
- Descriptive, unambiguous identifiersChoose names that clearly express intent and behavior while avoiding ambiguity. Identifiers should communicate their purpose to other developers without requiring them to read implementation details.vercel/turborepo8 discussions
- ensure documentation completenessDocumentation should include all necessary information for users to successfully implement features. This includes providing complete configuration examples in all supported formats, documenting all available options, including prerequisites and setup requirements, and adding proper metadata.traefik/traefik8 discussions
- Write focused single-purpose testsBreak down large test cases into smaller, focused tests that each verify a single feature or behavior. Each test should have a clear purpose that is evident from its name and structure. This improves test maintainability, readability, and makes failures easier to debug.tokio-rs/tokio8 discussions
- Optimize algorithmic complexityAlways consider the time and space complexity implications of your code. Choose data structures and algorithms that minimize computational overhead and memory usage for your specific use cases.tokio-rs/tokio8 discussions
- Return results not panicsLibraries should never panic as this can crash applications using the library. Always return a `Result` type rather than using functions or methods that can panic (`panic!()`, `unwrap()`, `expect()`, `assert!()`) in public APIs and internal logic. This allows consumers of your library to properly handle error conditions.huggingface/tokenizers8 discussions
- Use descriptive identifiersChoose clear, self-documenting names for variables, methods, parameters, and properties that explicitly convey their purpose and context. Avoid ambiguous or generic names that require additional context to understand.microsoft/terminal8 discussions
- optimize algorithmic choicesChoose efficient algorithms and data structures to improve performance and reduce computational overhead. This involves selecting appropriate containers, avoiding unnecessary operations, and leveraging language features for optimization.microsoft/terminal8 discussions
- Cache expensive computationsIdentify and cache the results of expensive operations that are computed repeatedly with the same inputs. This includes function calls, data structure creation, regex compilation, and complex calculations that don't change between invocations.microsoft/terminal8 discussions
- Names reflect precise behaviorChoose names that accurately reflect the behavior and purpose of code elements. Names should be semantically precise and avoid misleading implications. This applies to methods, variables, and configuration parameters.temporalio/temporal8 discussions
- Descriptive specific namesChoose names that are specific, descriptive, and accurately reflect the purpose and domain of variables, methods, classes, and constants. Avoid overly generic terms that could be ambiguous or conflict with future features.spring-projects/spring-framework8 discussions
- Optimize test case designWrite focused, efficient tests that validate core functionality without unnecessary complexity. Key principles: 1. Test one concept per case 2. Use appropriate test scope (unit vs integration)spring-projects/spring-boot8 discussions
- Follow consistent style conventionsSpring Boot projects maintain specific coding style conventions for consistency and readability. When contributing code, adhere to the following style guidelines:spring-projects/spring-boot8 discussions
- Explicit security configurationsWhen configuring security-related features, always use the most specific configurer classes to make security decisions explicit and improve code readability. For example, when disabling CSRF protection in Spring Security, use `CsrfConfigurer::disable` instead of the more generic `AbstractHttpConfigurer::disable`:spring-projects/spring-boot8 discussions
- Eliminate redundant operationsAvoid duplicate function calls, repeated tensor operations, and redundant computations that can significantly impact performance. Implement caching mechanisms for expensive operations and pre-allocate tensors when possible.sgl-project/sglang8 discussions
- avoid unsafe unwrappingReplace `.unwrap()` calls and sentinel values with safe null handling patterns to prevent runtime panics and improve code robustness. **Key Issues:**servo/servo8 discussions
- avoid unnecessary workIdentify and eliminate computational work that serves no purpose, particularly for inactive, hidden, or irrelevant elements. This includes early returns for non-visible components, lazy initialization of expensive resources, and preventing work during inappropriate timing.servo/servo8 discussions
- prefer simple readable patternsChoose simple, readable code patterns over complex alternatives. Avoid unnecessary complexity that doesn't add functional value but makes code harder to understand and maintain.serverless/serverless8 discussions
- maintain backwards compatibilityWhen modifying public APIs, always preserve backwards compatibility to avoid breaking existing consumers. Public methods, even if rarely used directly, must maintain their existing signatures and behavior.strands-agents/sdk-python8 discussions
- Precise type narrowingImplement sound type narrowing algorithms that balance precision with correctness. When narrowing types: 1. For direct assignments, narrow the type to the assigned value's type:astral-sh/ruff8 discussions
- Use descriptive, conflict-free namesChoose descriptive names that clearly convey purpose while avoiding conflicts with existing APIs, built-in functions, or established conventions. Names should follow consistent patterns across the codebase and use appropriate spelling conventions.TanStack/router8 discussions
- Dependency version specificationEnsure proper dependency version specification and compatibility management in package.json files. Use explicit version ranges for peer dependencies to express compatibility constraints, avoid workspace references in examples and published packages, and properly classify dependencies based on usage patterns.TanStack/router8 discussions
- Extract reusable patternsExtract repetitive or complex code into reusable functions, components, or custom hooks. This improves code organization, reduces duplication, and enhances readability.RooCodeInc/Roo-Code8 discussions
- Improve Readability StyleAdopt a “review-first” style for complex C code: keep control flow and conditions small, make side effects explicit, and avoid duplication. Key rules:redis/redis8 discussions
- Fail/Clamp Error ContractsWhen implementing commands with numeric failure modes (overflow, out-of-range, NaN/Inf) or multi-option parsing, define an explicit error contract and enforce it end-to-end:redis/redis8 discussions
- Fail Fast Input ValidationApply a single security rule: validate arity, lengths, ranges, and invariants before using inputs to index arrays, dereference pointers, compute derived pointers, or persist/serialize into security-sensitive targets.redis/redis8 discussions
- Doc Semantics ConsistencyEnsure comments and public-facing documentation precisely match the actual behavior and contract. Apply this standard by checking: - **No doc/behavior drift**: If you add/adjust command options (e.g., STRICT/PERSIST) or state transitions (e.g., TTL handling), update all descriptions (PR text, command docs, inline comments) to reflect the implemented...redis/redis8 discussions
- API Contracts And CompatibilityWhen adding or evolving APIs (commands, module interfaces, persistence callbacks), make the contract explicit and stable: define lifecycle rules, invariants, grammar, and compatibility boundaries, and ensure implementations preserve existing behavior (including error/return types) across encodings and versions.redis/redis8 discussions
- Organize tests for clarityStructure tests to maximize clarity and maintainability by: 1. Placing related tests together in appropriate test files 2. Using built-in assertion helpers instead of raw assertionsrails/rails8 discussions
- Unified Error HandlingAdopt a single error-handling standard across LLM/provider layers: 1) Retry only transient failures (including connection jitter) with bounded, classified backoffinfiniflow/ragflow8 discussions
- Documentation PrecisionAll documentation must accurately reflect product/API behavior, use exact feature names, and be unambiguous about constraints, defaults, and unsupported scenarios. Also ensure Markdown renders cleanly.infiniflow/ragflow8 discussions
- Hot Path EfficiencyDefault to “do the minimum possible work per hot-path update.” Apply these checks: 1) Early-exit before side effects - If a piece of async work is no longer relevant (stale session, unmounted view, toggled-away state), return before starting the network call/timer/observer.QwenLM/qwen-code8 discussions
- Correct Dedup Cache KeysWhen implementing cursor-based dedup/caching for event dispatch, ensure the dedup “key space” matches the real uniqueness of what you’re trying to prevent:QwenLM/qwen-code8 discussions
- Contract-Driven Workflow TestingWorkflow logic changes can silently ship if tests don’t observe the exact contract your users/ops depend on. Adopt this checklist when writing/modifying tests around GitHub Actions scripts/workflows:QwenLM/qwen-code8 discussions
- Consistent Config GatesWhen behavior is driven by config/flags (timeouts, scopes, feature gates, safe-mode), ensure every code path uses the same authoritative inputs and does not silently degrade.QwenLM/qwen-code8 discussions
- Centralize Stale InvalidationWhen implementing or modifying caching/fetch decisions, treat “fresh vs stale” as a single source of truth derived from the query’s invalidation + stale-time logic. Avoid adding ad-hoc fetch conditions at the observer/queryClient level that bypass (or redefine) TTL semantics.tanstack/query8 discussions
- Optimize numerical precisionWhen implementing AI operations that involve matrix multiplication or neural network components, explicitly support modern numerical precision formats (TF32, BFloat16, Float8) across different hardware backends. These precision formats significantly accelerate AI training and inference while maintaining acceptable numerical accuracy.pytorch/pytorch8 discussions
- Pure Functions and Main GuardKeep reusable code clean and production-ready: reusable/algorithmic functions should be side-effect free (no `print()`), and all executable/demo/driver code must be under an `if __name__ == "__main__":` guard. Also keep imports at the top and sorted/PEP8-compliant.TheAlgorithms/Python8 discussions
- Use configurable default valuesMake configuration values flexible and robust by avoiding hardcoded values and providing sensible defaults. This ensures your application works correctly even with incomplete configuration and supports different environments without code changes.prowler-cloud/prowler8 discussions
- Specific exception handlingHandle exceptions with specificity rather than using broad catch-all blocks. Catch specific exception types, provide clear error messages, and respond appropriately based on the error type. This improves error diagnosis and enables targeted recovery strategies.prowler-cloud/prowler8 discussions
- Fail-closed evaluation metricsWhen implementing deterministic grading/scoring logic for model or agent outputs, design each rule to fail-closed on missing, ambiguous, or edge-case data rather than silently awarding a pass. Concretely:promptfoo/promptfoo8 discussions
- Cache key completenessA cache (or in-flight request dedupe) key must encode every parameter that can change the response, and an entry must only be reused when it truly represents the same logical request. Before adding or reusing a key, enumerate all inputs that affect behavior — timeouts/deadlines, credentials or profile identity, session/trace/memory IDs, retrieval filters,...promptfoo/promptfoo8 discussions
- Write meaningful documentationDocumentation comments should be accurate, concise, and add genuine value rather than restating obvious code behavior. Focus on explaining "what" the code does and "why" it exists, not "how" it works step-by-step.prometheus/prometheus8 discussions
- metrics registration lifecycleEnsure proper metrics registration and lifecycle management to maintain observability system stability. Handle metric registration/unregistration correctly during configuration changes and avoid common pitfalls that can cause panics or data loss.prometheus/prometheus8 discussions
- Configuration mutual exclusivity validationEnsure configuration options that are mutually exclusive are properly validated with clear, actionable error messages. When introducing configuration fields that cannot be used together, implement validation logic that checks for conflicts and provides specific guidance to users.prometheus/prometheus8 discussions
- explicit null handlingPrefer explicit null and undefined handling over optional or nullable types. When possible, provide default values or objects instead of making parameters optional. When null/undefined checks are necessary, handle both values explicitly and use descriptive patterns.prisma/prisma8 discussions
- dependency classification standardsEnsure proper classification and versioning of package dependencies in package.json files. Dependencies should be classified based on their usage pattern: use regular `dependencies` for hard requirements that the package cannot function without, and `peerDependencies` for packages that consumers are expected to provide. When specifying version ranges, use...prisma/prisma8 discussions
- Use descriptive variable namesChoose variable and function names that clearly communicate their purpose, type, and context. Avoid abbreviations, overly generic terms, and names that could be confused for different types.prettier/prettier8 discussions
- Documentation example consistencyEnsure all code examples and documentation maintain consistent formatting standards, use descriptive variable names, and apply proper syntax highlighting. This includes using meaningful identifiers instead of cryptic names like `a60`, applying correct language tags for syntax highlighting (e.g., `css` instead of `jsx` for CSS code), and providing clear...prettier/prettier8 discussions
- Use Clear Style HelpersAdopt maintainable, idiomatic Python patterns to improve readability and reduce future change risk. ### 1) Prefer `isinstance()` over `type(...) == ...`the-pr-agent/pr-agent8 discussions
- Trust Boundaries And Safe ParsingTreat any repo-controlled config, external webhook payload, or model-generated text as untrusted. Enforce trust boundaries and use safe parsing/validation to prevent SSRF/exfiltration, arbitrary file writes, and unsafe deserialization.the-pr-agent/pr-agent8 discussions
- Model-Safe Parameter ValidationAdopt a model/provider-aware configuration standard: before sending requests to LLM APIs, validate that every model-specific parameter (reasoning effort, thinking features, temperature constraints, system support) is supported for that exact model/provider, and apply overrides safely without accidentally changing unrelated limits.the-pr-agent/pr-agent8 discussions
- Explicit null handlingUse explicit and clear patterns when handling null/None values to improve code readability and maintainability. Avoid complex conditional expressions, unnecessary type casting, and ambiguous nullable types.python-poetry/poetry8 discussions
- API consistency standardsMaintain consistent patterns across all API endpoints, including naming conventions, response structures, HTTP status codes, and interface design. This ensures a predictable and professional API surface that follows established conventions.emcie-co/parlant8 discussions
- Separate configuration lifecyclesMaintain clear separation between different stages of configuration processing by creating dedicated structures for each phase of the configuration lifecycle. Divide configuration handling into distinct phases:opentofu/opentofu8 discussions
- Log effectively for debuggingAlways include meaningful log messages at appropriate levels to aid in debugging and system monitoring. Follow these guidelines: 1. **Never silently swallow errors** - Even during cleanup operations, log errors that might be helpful for debugging:opentofu/opentofu8 discussions
- Document intent and limitationsClearly document the intended purpose, scope limitations, and design decisions in your code. For all exported types, functions, and variables, provide comprehensive comments explaining their purpose, usage patterns, expected behavior, and any deliberate limitations.opentofu/opentofu8 discussions
- Secure Auth and LoggingSecurity-sensitive code must ensure (1) the correct auth path is used without accidental overrides, (2) sensitive auth material is never leaked in logs, and (3) auth-mode “sentinels” and provider handles can’t be accidentally triggered or misused.openai/openai-python8 discussions
- Harden Client URL FetchesAny client-controlled URL (including OpenAI image_url) must be treated as SSRF-/DoS-/parsing-risk input and validated *at every transition* before connecting.diegosouzapw/OmniRoute8 discussions
- Efficient hot-path disciplineAdopt a performance-safety standard: prevent unbounded state growth in monitoring, and keep critical-path CPU/memory work linear and avoidable. Apply these rules:diegosouzapw/OmniRoute8 discussions
- Follow GoDoc conventionsDocument code following Go's official documentation style guide (https://tip.golang.org/doc/comment). All exported functions, types, interfaces, and struct fields should have descriptive comments. ollama/ollama8 discussions
- Descriptive balanced namingChoose identifier names that clearly communicate their purpose while maintaining an appropriate balance between brevity and clarity. **Guidelines:**ollama/ollama8 discussions
- Use specific assertionsAlways write assertions that verify specific, expected values rather than simple existence or boolean checks. This ensures tests validate exactly what you intend and provides clearer error messages when tests fail.octokit/octokit.net8 discussions
- Document public API elementsEvery public API element (classes, methods, properties, constructors) must have XML documentation comments that clearly describe its purpose and usage. This improves developer experience through IntelliSense and ensures the API is well-documented.octokit/octokit.net8 discussions
- explicit null safetyAlways perform explicit null and undefined checks before processing values, and use the nullish coalescing operator (??) for safe default value assignment. Distinguish between null (explicit no value) and undefined (use default) semantics in your API design.novuhq/novu8 discussions
- Complete OpenAPI annotationsEnsure all API endpoints have complete and accurate OpenAPI annotations to support proper SDK generation and documentation. Use appropriate decorators, include all necessary metadata, and verify that generated SDKs work correctly.novuhq/novu8 discussions
- Informative error messagesError messages should be specific, actionable, and include context that helps developers understand and fix the issue. Use standard error codes that can be tested and suppressed rather than relying only on text messages. Create errors at the point of detection rather than inside callbacks to preserve useful stack traces.nodejs/node8 discussions
- Evolve return valuesWhen extending APIs with new capabilities, carefully consider how changes to return values affect consumers. Avoid creating polymorphic return types based on input options as this reduces predictability and makes it difficult to programmatically detect supported features.nodejs/node8 discussions
- Technical documentation precisionEnsure technical documentation is precise, accurate, and correctly formatted to prevent confusion and improve developer experience.vercel/next.js8 discussions
- Secure Data Handling in Next.js ApplicationsWhen building Next.js applications that handle sensitive data, it's crucial to implement robust security measures to prevent data leakage and injection attacks.vercel/next.js8 discussions
- Effective Cache Management in Next.js ApplicationsWhen implementing caching in Next.js applications, it is crucial to be intentional about the caching behavior for each component and function. Apply caching directives consistently and consider their implications.vercel/next.js8 discussions
- reduce test verbosityWrite concise, efficient tests by eliminating repetitive code and combining related test cases. Avoid verbose patterns that can be simplified with better approaches.neovim/neovim8 discussions
- consistent naming conventionsMaintain consistent naming patterns and terminology across the codebase to reduce cognitive load and improve code clarity. The same concept should always use the same name in different contexts.neovim/neovim8 discussions
- Design domain-specific error typesCreate and use domain-specific error types instead of generic errors or anyhow. This improves error handling clarity and ensures proper error propagation through the codebase.neondatabase/neon8 discussions
- Spec-aligned Algorithm CorrectnessAll algorithm implementations must be spec-aligned for the exact operator variant, tensor shapes/axes, and boundary conditions. Before merging, developers should explicitly verify that special cases and out-of-bound behavior follow the framework/ONNX semantics; avoid “one-size-fits-all” code paths that silently produce wrong results.Tencent/ncnn8 discussions
- Platform-Targeted FlagsWhen enabling/disabling CPU features or platform-specific APIs, derive decisions from the *configured target/platform* (toolchain/CMake target selection) and apply consistent compile-time guards across code and tests. Do not rely on compiler-defined feature macros that may differ between build/test environments.Tencent/ncnn8 discussions
- Consistent Semantic IdentifiersWhen adding/changing code, use names that (1) match existing project conventions, (2) clearly express intent, and (3) avoid reserved/problematic identifier patterns.Tencent/ncnn8 discussions
- Use structured loggingAlways use the project's structured logger instead of direct console methods (`console.log`, `console.error`, etc.). This ensures consistent log formatting, proper level-based filtering, and integration with monitoring systems.n8n-io/n8n8 discussions
- Prevent null reference exceptionsAlways use optional chaining and nullish coalescing operators to prevent runtime errors when accessing properties or methods on potentially undefined objects.n8n-io/n8n8 discussions
- Technical precision mattersWhen documenting AI models, frameworks, and optimization techniques, precision in language is as important as precision in your algorithms. Technical inaccuracies or unclear explanations can lead to implementation errors and confusion.apache/mxnet8 discussions
- Consistent Style And DiffsApply a consistent, tool-friendly coding style to reduce formatting churn and improve readability. **Rules** - **Keep diffs stable:** Don’t apply formatting-only changes to existing tests/cases unless the PR’s purpose is explicitly formatting coverage. Revert incidental alignment/whitespace changes; add new focused cases instead.mermaid-js/mermaid8 discussions
- Consistent Readability RulesCode should be readable and consistent: avoid inline “magic” expressions, prefer named values/helpers, and use uniform style primitives. Apply: - Replace inline calculations with a named variable/helper when the expression is meaningful or potentially repeated:mermaid-js/mermaid8 discussions
- Changeset release hygieneEnsure changeset PRs produce correct and minimal release automation output. Apply these rules before submitting: - **Create changesets only for user/release-relevant changes.** If it’s documentation-only, **do not** add a changeset.mermaid-js/mermaid8 discussions
- Validate noexcept guaranteesOnly mark functions as `noexcept` when you can guarantee they won't throw exceptions under any circumstances. Common pitfalls include: 1. **Hidden allocations**: Operations like vector operations, `std::make_tuple`, or working with collections might allocate memory and throw.maplibre/maplibre-native8 discussions
- Environment variable accessUse direct `process.env` access and standardized configuration management instead of custom environment variable wrappers. Avoid redundant abstraction layers when the framework or libraries already handle environment variable inference automatically.lobehub/lobe-chat8 discussions
- Use descriptive namesChoose names that clearly describe the purpose, behavior, and content of functions, variables, and constants. Names should be self-documenting and unambiguous to other developers.llvm/llvm-project8 discussions
- maintain naming consistencyFollow established naming patterns and conventions consistently throughout the codebase. This includes using consistent formatting (dashes vs underscores), proper capitalization, descriptive parameter names, and uniform data type representations.ggml-org/llama.cpp8 discussions
- Extract repeated codeFollow the DRY (Don't Repeat Yourself) principle by extracting repeated code patterns into helper functions, constants, or shared utilities. Code duplication leads to maintainability issues, inconsistencies, and bugs when one instance is updated but others are overlooked.langfuse/langfuse8 discussions
- Semantic naming for schemasUse names that communicate intent and framework semantics—especially for (a) schemas and (b) callback parameters whose names are used for injection/dispatch.langchain-ai/langchain8 discussions
- Preserve AI Structure InvariantsWhen working with LLM/chat “auxiliary” content (reasoning, tool calls/results, structured content blocks, and usage/metadata), enforce structural invariants so provider/streaming/truncation logic can’t silently corrupt meaning.langchain-ai/langchain8 discussions
- Keep Helpers SmallFavor readability and maintainability by keeping functions/methods short, extracting complex logic into well-named helpers, and avoiding duplicated or closure-based implementations in constructors.langchain-ai/langchain8 discussions
- Boundary API Format EnforcementWhen building provider requests or consuming provider responses, enforce that all intermediate representations match the provider’s expected wire format *at the boundary*—including IDs, message/content blocks, and versioned behavior.langchain-ai/langchain8 discussions
- Semantic Identifier NamingUse names that precisely describe the thing’s real semantics, and ensure the identifier is valid/unique within its naming “domain” (API fields, tests, labels).kUbernetes/kUbernetes8 discussions
- API field documentationAPI fields must be comprehensively documented with clear behavior specifications, format constraints, and interaction details. This includes documenting how fields interact with each other, specifying allowed formats and validation rules, clarifying field semantics and placement decisions, and aligning naming conventions with existing Kubernetes APIs.kubernetes/kubernetes8 discussions
- Effective API samplesCreate clear, comprehensive, and properly structured code samples to document API usage. Follow these principles: 1. **Organize samples properly:** - Place samples after doc blocksJetBrains/kotlin8 discussions
- Conditional configuration managementEnsure configurations are conditional, context-aware, and resilient. Use feature flags to control functionality availability rather than instructing systems to avoid certain features. Implement proper fallbacks for missing configuration values and support backward compatibility when introducing new config formats.kilo-org/kilocode8 discussions
- prefer modern collection APIsUse modern collection creation methods instead of legacy alternatives for improved readability and conciseness. Replace older patterns with their modern equivalents:apache/kafka8 discussions
- Use descriptive namesNames in code should be self-documenting, accurately reflect purpose, and follow consistent conventions. Apply these principles throughout your code: influxdata/influxdb8 discussions
- Promote code clarityWrite code that prioritizes clarity and maintainability over brevity. This involves several key practices: 1. **Extract repeated code blocks into helper functions**influxdata/influxdb8 discussions
- Minimize critical path allocationsAvoid unnecessary memory allocations in performance-critical code paths. These allocations not only consume memory but also trigger expensive CPU operations that can significantly impact system performance.influxdata/influxdb8 discussions
- Lock with defer unlockAlways follow the lock-defer-unlock pattern when protecting shared resources with mutexes. Acquire the lock, immediately use defer to ensure unlock, then perform operations on the protected resource. This prevents deadlocks and ensures locks are released even when functions exit unexpectedly.influxdata/influxdb8 discussions
- Choose appropriate lock primitivesSelect lock types based on access patterns - prefer RWLock over Mutex for read-heavy operations to enable concurrent reads while allowing exclusive write access. Minimize lock scope to essential operations and avoid holding locks across await points in async code.influxdata/influxdb8 discussions
- Maintain clean code structureKeep code well-organized by separating interface from implementation, managing dependencies properly, and following consistent structural patterns. Function bodies should remain in implementation files rather than headers to reduce compilation dependencies and improve maintainability. Organize includes strategically - move them to implementation files when...hyprwm/Hyprland8 discussions
- Protect sensitive dataWrap all sensitive data fields in Secret<> types to prevent accidental exposure through logs, debug output, serialization, or error messages. This includes authentication tokens, API keys, PII data, payment information, and any credentials.juspay/hyperswitch8 discussions
- Validate and protect untrusted inputAny value that is user-controllable or comes from external input (request data, generated class names, file paths, redirect targets, header values, cookie options) must be treated as untrusted before it reaches a security-sensitive sink such as HTML/CSS output, the filesystem, or a security header/attribute.honojs/Hono8 discussions
- HTTP header semanticsWhen implementing networking middleware (proxy, compress, CORS, etc.), handle HTTP headers according to their exact RFC semantics rather than naive string checks, and be deliberate about merge/overwrite order.honojs/Hono8 discussions
- Consistent lint-compliant styleFollow the project's established linting and formatting conventions consistently rather than introducing one-off styles: 1. Always use curly braces for conditionals, even single-line ones, to match the project's `curly: all` rule:honojs/Hono8 discussions
- Manage tensors proactivelyMotivation: Large models and matrix ops can produce big ephemeral tensors, cross-device copies, and temporary allocations that lead to excessive memory use or OOMs. Adopt consistent, device-aware tensor handling, prefer built-in ops, and free large temporaries at clear boundaries.p-e-w/heretic8 discussions
- Config schema conventionsProvide a clear, stable, and discoverable configuration schema. Apply the following rules to all TOML/environment configs: 1) Use self-documenting valuesp-e-w/heretic8 discussions
- Canonical Model CapabilitiesWhen integrating LLM providers/models, derive capability flags and limits from canonical model metadata (catalog) and apply deterministic compatibility rules with explicit fallbacks—avoid brittle name-based heuristics and keep user overrides authoritative.aaif-goose/goose8 discussions
- Documentation clarity and formattingEnsure documentation is clear, precise, and consistently formatted. Key practices include: 1. **Be explicit and unambiguous** - Define terms that might be unclear and provide specific guidance:ghostty-org/ghostty8 discussions
- Prevent concurrent state racesWhen multiple operations can execute concurrently (e.g., multiple keystrokes in the same React event loop, simultaneous async calls), ensure they don't operate on stale state or create race conditions. Use centralized state management patterns like reducers, proper synchronization flags, and avoid direct state manipulation from concurrent contexts.google-gemini/gemini-cli8 discussions
- Consistent Snippet StyleAll code snippets, hints, seed code, and automated checks must follow a single, consistent formatting and style contract—especially around quote usage and basic JS/TS syntax.freeCodeCamp/freeCodeCamp8 discussions
- Consistent Identifier NamingWhen updating curriculum challenges or UI code, ensure all identifiers are spelled, cased, and named consistently across: the prompt, hints, and what tests/DOM queries expect. Also use framework-correct attribute names (e.g., JSX `className`) and semantic, descriptive labels for user-facing accessibility (e.g., informative `alt` text).freeCodeCamp/freeCodeCamp8 discussions
- Use semantic exceptionsChoose exception types that accurately reflect the nature of the error. Use `LogicException` for developer errors like incorrect usage, `InvalidArgumentException` for invalid inputs, `OutOfBoundsException` for range violations, and specialized exceptions for domain-specific errors.laravel/framework8 discussions
- Precise type annotationsAlways use the most specific and accurate type information possible in PHPDoc comments to improve static analysis, IDE autocompletion, and code clarity. Pay special attention to array types using appropriate syntax:laravel/framework8 discussions
- Robust environment config handlingTreat environment-variable driven configuration as untrusted, possibly malformed input, and handle it defensively and consistently. - Normalize and validate values read from the environment before use. Boolean-like flags (e.g. `FLASK_DEBUG`) must be compared case-insensitively and against a documented set of truthy/falsy strings, e.g. `val.lower() not in...pallets/flask8 discussions
- Explicit None checksAlways test for absence of a value with `is None` / `is not None` rather than truthiness or `== None`/`!= None`. Truthy checks silently misclassify valid-but-falsy values (0, "", {}, []) as missing, and `== None` is non-idiomatic and slower due to implicit bool conversion. This is especially important when building fallback chains with `or`, since `a or b`...pallets/flask8 discussions
- Follow naming patternsMaintain consistent naming conventions throughout the codebase by following established patterns and avoiding redundancy. Key principles include: 1. **Error naming**: Use the pattern `Err + [Subject] + [Error Condition]` (e.g., `ErrStorageRetrievalFailed` instead of `ErrNotGetStorage`)gofiber/fiber8 discussions
- Write clear documentationDocumentation should be clear, precise, and self-contained while following established style conventions. When writing technical documentation, use precise language, make documentation self-contained, follow style conventions, and create accessible links.fastify/fastify8 discussions
- Isolate configuration concernsKeep configuration settings separate from application code by using environment variables or dedicated configuration files. This promotes better maintainability, security, and flexibility across different deployment environments.fastapi/fastapi8 discussions
- Document all responsesWhen designing APIs, thoroughly document all possible responses your endpoints can return, not just the "happy path" success cases. Include documentation for:fastapi/fastapi8 discussions
- Single source documentationMaintain documentation with a single source of truth to prevent inconsistencies and reduce maintenance burden. When information exists elsewhere, link to it rather than duplicating content. This applies to code of conduct references, governance documents, and API documentation.expressjs/express8 discussions
- Propagate errors via pipelineNever swallow, locally render, or silently drop an error — always let it flow through the standard error-handling mechanism so it can be centrally logged, customized, and surfaced consistently. Concretely:expressjs/Express8 discussions
- Enforce null safety patternsImplement comprehensive null safety patterns to prevent runtime errors and ensure predictable behavior. Follow these guidelines: 1. Use explicit null/undefined checks instead of loose comparisons:expressjs/express8 discussions
- Avoid hot-path overheadIn performance-sensitive, frequently-executed code paths (per-request handlers, middleware, core request/response methods), minimize unnecessary allocations, indirection, and repeated expensive operations, and justify optimizations with real benchmarks rather than assumptions.expressjs/Express8 discussions
- use optional types safelyWhen functions may not return valid values, use `std::optional` or `absl::optional` instead of raw types that could represent invalid states. Always check the validity of optional values before accessing them to prevent null pointer dereferences and invalid value usage.electron/electron8 discussions
- Optimize before implementingBefore implementing algorithms, evaluate their efficiency implications, especially for operations that may be executed frequently or with large datasets. Consider:elastic/elasticsearch8 discussions
- Handle optional dependencies gracefullyWhen integrating with external AI libraries, models, or services, handle optional dependencies gracefully to avoid affecting users who don't need those features. Use local imports within class constructors or methods rather than module-level imports, and provide clear error messages when dependencies are missing.stanfordnlp/dspy8 discussions
- Version-safe Docs TemplatingEnsure documentation that uses Liquid/templating renders correctly across all supported doc versions and doesn’t break code samples. Apply these rules when authoring or updating docs:github/docs8 discussions
- Pin CI Actions By SHAWhen writing CI/CD workflows (and the documentation snippets that users copy/paste), always: - **Pin every third-party GitHub Action to an immutable commit SHA** (optionally with a comment showing the intended version), instead of using only tags like `@v4`.github/docs8 discussions
- verify authorization explicitlyAlways perform explicit authorization checks rather than assuming existing security controls are sufficient. Security vulnerabilities often arise from bypassed or missing permission verification, especially in edge cases like impersonation windows, controller action bypasses, or privilege escalation scenarios.discourse/discourse8 discussions
- Doc Intro And LinksFor roadmap/technical documentation pages, follow these rules: - **Use correct Markdown structure**: prefer headings (e.g., `## Section`) over HTML line breaks like `<br/>`.kamranahmedse/developer-roadmap8 discussions
- Avoid ambiguous namingChoose names that clearly convey their purpose and avoid ambiguous identifiers that can be misinterpreted. This applies to methods, variables, parameters, and types.denoland/deno8 discussions
- Document API completelyAll public APIs must have comprehensive and clear documentation that helps developers understand functionality without examining implementation details. Follow these guidelines:deeplearning4j/deeplearning4j8 discussions
- Semantic Naming RulesUse names that accurately reflect meaning, scope (internal vs external), and responsibility—and keep them consistent with existing/base APIs. Apply these rules:eosphoros-ai/DB-GPT8 discussions
- Semantic naming patternsNames should clearly communicate purpose, relationships, and domain context. Choose identifiers that reveal intent and accurately describe what they represent:crewaiinc/crewai8 discussions
- Prefer pythonic simplicityUse Python's expressive features to write cleaner, more maintainable code by reducing nesting and improving readability. Follow these practices: 1. **Avoid unnecessary else blocks** after raising exceptions or returns:crewaiinc/crewai8 discussions
- Specific exceptions, preserved chainsWhen catching and converting exceptions, catch the narrowest exception type that applies rather than a broad `Exception` or bare `except:` unless you are immediately re-raising (bare `except:` is acceptable only when the original exception is re-raised unchanged). Overly broad catches hide programming errors and make debugging harder.python/cpython8 discussions
- Clear variable namingUse descriptive, unambiguous variable and function names that clearly convey their purpose and avoid conflicts with Python built-ins or Home Assistant conventions.home-assistant/core8 discussions
- avoid code duplicationCreate reusable components instead of duplicating similar code patterns. When you find yourself writing similar classes, functions, or logic blocks, extract the common functionality into base classes, helper functions, or generic components that can be parameterized.home-assistant/core8 discussions
- Semantic Naming RulesAdopt a “meaning-first” naming standard: identifiers must communicate semantics, representation, and units—so readers can’t guess. Apply: - Match behavior: rename helpers/methods when behavior changes (avoid names like `installDefaultKernel()` if it no longer does “install default”).apple/container8 discussions
- Atomic Concurrency ContractsAll concurrency-sensitive code must follow an “atomic + lifecycle-valid” contract. **Rules** 1. **Make check-then-act atomic.** If you verify a precondition and then mutate shared state (e.g., “volume not in use => delete”), do both while holding the same synchronization boundary (actor/lock). Prefer closure-based helpers that keep the lock for the whole...apple/container8 discussions
- Environment variable validationAlways validate environment variables and provide appropriate fallbacks when using them for configuration. Environment variables should be checked for existence and non-empty values before use, with clear fallback behavior defined.docker/compose8 discussions
- Gated deterministic releasesAll release/publishing workflows must be deterministic, serialized safely, and strictly gated so that user-facing artifacts are published only after the release candidate has passed the final checks.openai/codex-security8 discussions
- Versioned cache validityCache entries must be tied to a *versioned identity* of the data and only served while that identity is still valid; refresh/retry must be deterministic and bounded.Cline/Cline8 discussions
- Verify regression test efficacyA test written for a bug fix is only useful if it actually distinguishes broken behavior from fixed behavior. Before merging, confirm each regression test fails against the pre-fix code and passes against the fix — don't just assert it "should" catch the bug.cline/cline8 discussions
- Unify config resolutionWhen the same setting (a base URL, a git remote, a host name, an API-key check, a bind-fallback flag) is resolved in more than one place, each implementation tends to drift and the app ends up showing or using inconsistent values (e.g. the webview linking to production while the account service actually hit staging, or the manifest showing a different repo...cline/cline8 discussions
- Synchronous Claim and GatingIn async/concurrent code, establish the operation’s ownership and validity *before* the first `await`, and ensure every continuation checks that it is still the active owner. Also make required ordering explicit (chain/await when later logic depends on it) and always clean up resources when you settle.CLINE/cline8 discussions
- Semantic Naming StandardsUse names that encode the *actual meaning* and follow the project’s *identifier contracts/conventions*. - **Avoid vague booleans/flags**: rename to what the value *means*, not what it excludes.Cline/Cline8 discussions
- Robust async error handlingStandard: when adding error recovery, retries, or asynchronous work, preserve invariants by (1) wiring every failure into the owning state machine, (2) keeping retry/timeout attribution explicit and conservative, and (3) ensuring UI/state changes made on error remain repairable.ClInE/cLiNe8 discussions
- Redact secrets in diagnosticsNever let credentials, tokens, or other sensitive values reach logs, error messages, or telemetry, even indirectly. URLs commonly carry secrets in userinfo (`user:pass@host`), query strings (OAuth codes, state, device codes), or even path segments (some MCP servers embed API keys there); when logging a URL, reduce it to `origin` (or `protocol` for...cline/cline8 discussions
- Null Semantics DisciplineEnsure your code treats `null`, `undefined`, “omitted”, and “empty” as distinct meanings—especially across serialization boundaries—and encode those meanings explicitly.cline/CLINE8 discussions
- Correct Keyed CachesCache only when you can prove the cached value still matches the current “identity” of the request/state, and always have a bounded strategy for refresh/retry.cline/CLINE8 discussions
- Cache with RevisionsCache only what you can prove is still valid. **Standards** 1. **Key by semantic inputs, not just “request type”**: include all parameters that affect the result (e.g., pinned read key must include tool + arguments; cache lookup key must include account scope + workspace root + repo+branch).CLINE/cline8 discussions
- break down large filesLarge files with multiple responsibilities should be broken down into focused, single-responsibility modules to improve maintainability and avoid tight coupling. When a file becomes difficult to navigate or contains unrelated functionality, extract logical components into separate files or classes.cline/cline8 discussions
- Async ownership and cleanupWhen async work outlives its creator, late completions/callbacks will corrupt the current state (wrong session, double-send, lost attachments, teardown overwritten). Standardize concurrency ownership and cleanup:ClInE/cLiNe8 discussions
- validate before executing operationsAlways validate inputs and preconditions before executing database operations, and fail explicitly rather than silently ignoring invalid states or configurations. This prevents data corruption, ensures system consistency, and makes debugging easier.ClickHouse/ClickHouse8 discussions
- Use centralized loggersAlways use centrally supplied loggers from the invocation context or configuration instead of creating new logger instances, using log.Default(), or direct output methods like fmt.Println(). This ensures consistent debug configuration, proper log level control, and centralized logging behavior across the entire application.snyk/cli8 discussions
- Extract and organize methodsBreak down large, complex methods into smaller, focused methods with clear names that describe their purpose. This improves code readability, maintainability, and testability.chef/chef8 discussions
- Write pythonic codeEmbrace Python's idiomatic programming style to make your code more readable, concise, and maintainable. Follow these Pythonic patterns: 1. **Use truthiness checks** instead of explicit length comparisons:bridgecrewio/checkov8 discussions
- Safe dictionary accessAlways use safe dictionary access patterns when handling potentially null or missing values. This prevents KeyError and AttributeError exceptions that can crash your application.bridgecrewio/checkov8 discussions
- Restrict public networkAlways configure cloud resources to restrict or disable public network access unless explicitly required for the application's functionality. Public network exposure increases the attack surface and should be minimized.bridgecrewio/checkov8 discussions
- Choose optimal algorithmsAlways select appropriate data structures and algorithms based on their performance characteristics and the specific operations your code needs to perform. This can significantly improve both code readability and execution efficiency.bridgecrewio/checkov8 discussions
- Meaningful Tests For GuardsWhen adding tests for new behavior, deprecations, or environment-dependent code paths, ensure the test actually exercises the intended branch (avoid vacuous passing) and assert the concrete observable effect.celery/celery8 discussions
- Explicit dependency constraintsIn configuration/requirements files, make compatibility explicit: bound versions to prevent silent breakage across Python/platform build environments, and use environment markers for dependencies that differ by Python version, OS, implementation, or wheel availability.celery/celery8 discussions
- Explicit config behaviorEnsure configuration behavior is predictable, validated, and migration-friendly: - Precedence: When combining env vars, settings, and defaults, explicitly define and implement the precedence order (and document/announce any change). Avoid “surprising” priority flips.celery/celery8 discussions
- Document Behavior ChangesUpdate documentation every time code behavior changes or new public APIs are introduced. Apply this checklist: 1) Docstring accuracy: If you change semantics (error handling, return values, shutdown behavior, etc.), update the docstring to match reality.celery/celery8 discussions
- Write self-documenting testsTests should clearly communicate their purpose and expectations without requiring readers to analyze implementation details or scroll through files. Each test should:boto/boto38 discussions
- Deterministic Prompt ContractsWrite AI prompt/workflow steps as deterministic contracts: remove ambiguity, force required lookups, gate behavior by mode, and make unattended/automation outputs schema-correct.bmad-code-org/bmad-method8 discussions
- Streaming error invariantsAdopt a single, consistent error-handling strategy for streaming (and other multi-step flows): define retry semantics, tolerate isolated decode/parse errors, enforce terminal/completion invariants, and preserve the failure context needed by downstream billing/logging.maximhq/bifrost8 discussions
- Preserve Aggregation InvariantsWhen transforming/aggregating streamed or ranged data, explicitly define the invariants your algorithm depends on (index meaning, ownership/copy semantics, boundary semantics, and ordering), then implement collision- and edge-case-safe logic with targeted tests.maximhq/bifrost8 discussions
- Deterministic Test HygieneAdopt a consistent testing standard that prevents flaky behavior, leaked goroutines, and false positives. **1) Always register cleanup for started resources**maximhq/bifrost8 discussions
- Bounded, Targeted PerformanceWhen optimizing performance, avoid whole-object work and unbounded resource growth. Apply these standards: 1) Targeted extraction/rewrites (no full parsing)maximhq/bifrost8 discussions
- Environment-Driven ParametersWhen a template needs configuration that varies by environment/cloud/region or depends on real resource identifiers, do not hardcode endpoints/locations or fabricate subscription/RG paths. Instead:Azure/azure-quickstart-templates8 discussions
- Generated Help ConsistencyWhen changing cmdlet behavior or parameter semantics, treat help/examples as generated artifacts: update the source definitions/config (custom folder, README.md, autorest options/directives, APIspec where applicable) and then regenerate. Avoid hand-editing generated help/stubs, because edits will be overwritten and may desync parameter sets or requiredness.Azure/azure-powershell8 discussions
- Secure Untrusted BoundariesWhen code crosses security boundaries (subprocess/PowerShell execution, network URLs, filesystem writes, or auth/TLS), treat user/environment input as untrusted and enforce safety rules:Azure/azure-cli8 discussions
- Null-safe Data AccessAcross CLI/API payload handling, treat nullable fields and missing keys as first-class: normalize None before iterating/len’ing, use safe access for nested structures, and validate prerequisites early with clear user errors.Azure/azure-cli8 discussions
- Deterministic recorded testingFor scenario/recording tests, keep behavior deterministic between record and replay, and ensure assertions cover defaults, required inputs, and optional fields.Azure/azure-cli8 discussions
- Concise, Correct CLI HelpCLI help (per-flag short summaries, long summaries, and examples) must be readable, consistent, and executable. Apply these rules: - **Keep per-flag short text short:** Use a single, accurate sentence (with the default when appropriate). Do not exceed the short-help “lane” (avoid overflow).Azure/azure-cli8 discussions
- Wrap errors with contextWhen propagating errors up the call stack, always wrap them with contextual information about the failing operation using fmt.Errorf with the %w verb. This practice significantly improves debugging by providing a clear trail of what operations were being performed when the error occurred.argoproj/argo-cd8 discussions
- Comprehensive migration planningWhen changing identifier systems (e.g., from using `getInternalId()` to `getSequence()`), implement comprehensive migration strategies to preserve data integrity and backward compatibility. For each change:appwrite/appwrite8 discussions
- Cache Validity ContractsWhen caching derived state, you must define (and encode) a validity contract: *what exact changes make the cached data incorrect*, and how that change is detected (keying and/or TTL/refresh).apache/apisix8 discussions
- Accurate Semantic NamingUse names that reflect the external meaning and documented behavior—not internal implementation details or misleading assumptions. **Rules** 1. **Match the public/schema concept**: For headers, config flags, schema fields, provider values, and any user-visible identifiers, use names aligned to the schema wording and intent (avoid internal library terms).apache/apisix8 discussions
- consistent null handling patternsUse consistent and meaningful null/undefined handling patterns throughout your code. Prefer positive type guards over negated early returns, maintain consistency between null and undefined return types, and be careful with optional chaining semantics.angular/angular8 discussions
- Explain code intentComments and documentation should explain WHY code exists and what purpose it serves, not just describe what the code does. Focus on the reasoning, motivation, and intent behind implementation decisions.alacritty/alacritty8 discussions
- Use descriptive action namesNames should clearly indicate purpose and behavior using appropriate action verbs and descriptive terms. This applies to functions, methods, variables, and classes. Avoid generic or ambiguous names that don't convey the actual functionality.apache/airflow8 discussions
- Deterministic Boundary ModelingWhen an algorithm’s correctness depends on what “exactly” was bound/parsed/scanned, never rely on lossy representations (timestamps, ambiguous regex slices, quoted/escaped strings, overlapping recursion). Instead:awslabs/aidlc-workflows8 discussions
- Readable ES styleUse a consistent, readable JavaScript style that favors early exits, standard APIs, and lint-safe expressions—without sacrificing clarity. - Prefer guard clauses: if a branch returns, don’t wrap the rest in `else`.30-seconds/30-seconds-of-code8 discussions
- Secure Input Validation RulesWhen validating security-sensitive inputs (IDs, hostnames, tokens, IPs, payment-like numbers), ensure the implementation is strict, resilient, portable, and non-leaky:colinhacks/zod7 discussions
- Guard nullable inputsWhen a value can be `undefined`/`null`, do not assume it exists—guard it before access and keep the type model consistent. **Rules** - Use optional chaining / nullish guards when reading fields from optional params:colinhacks/zod7 discussions
- Centralize Complex RegexWhen adding validation logic that uses complex literals (especially RegExp), keep it consistent and maintainable: - Don’t scatter regex literals inline across files/branches—move them to a shared constant block near other related regexes.colinhacks/zod7 discussions
- Test through public APIsWrite comprehensive tests that validate functionality through public interfaces rather than testing implementation details. Tests should cover diverse scenarios, handle platform-specific cases, and use appropriate assertions.zed-industries/zed7 discussions
- Document compatibility flags comprehensivelyAll compatibility flags must include comprehensive documentation that clearly explains their purpose, behavior, timing, and relationships with other flags. This documentation should follow a consistent format and provide sufficient context for developers to understand the flag's impact.cloudflare/workerd7 discussions
- comprehensive assertion testingEnsure test assertions are thorough and complete by testing both expected behavior and error conditions with specific error types and messages. Tests should cover edge cases, boundary conditions, and all relevant code branches rather than just happy path scenarios.cloudflare/workerd7 discussions
- Extract Shared HelpersWhen review finds repeated or “very similar” logic patterns, don’t leave copy-paste growth—refactor into a shared helper, and follow local file conventions so future edits don’t diverge.warpdotdev/warp7 discussions
- Config Gating And ValidationWhen behavior depends on platform features, build features, feature flags, or user-provided configuration, keep it explicitly scoped and validated. Apply this checklist:warpdotdev/warp7 discussions
- Resilient Efficient CICI/CD workflows should be resilient, deterministic, and efficient: 1) Required checks should be resilient and scope-correct - Use a single “PR gate” (or equivalent) that passes when all relevant test jobs succeeded or were skipped.microsoft/VSCode7 discussions
- Cancellation-Aware AsyncEnsure any async work that mutates shared state or UI is *cancellation- and identity-safe*: after every `await` (especially inside queued/limited execution), re-validate that the operation is still the current one, and pass the cancellation token into the work.microsoft/VSCode7 discussions
- Avoid redundant operationsEliminate duplicate computations, unnecessary API calls, and redundant processing to improve performance and reduce system load. This includes avoiding duplicate function calls, minimizing API server requests, and implementing early returns or caching to prevent redundant work.volcano-sh/volcano7 discussions
- Add explicit nil checksAlways add explicit nil checks before accessing object properties and after type assertions to prevent null pointer exceptions and runtime panics. Even when type assertions succeed, the underlying value can still be nil, requiring additional validation.volcano-sh/volcano7 discussions
- Follow logging best practicesMaintain high-quality logging throughout the codebase by following these best practices: 1. **Use appropriate log levels**: Reserve `debug` for detailed troubleshooting, `info` for general operational information, `warning` for potential issues, and `error`/`critical` for actual problems. Avoid excessive logging at higher levels.vllm-project/vllm7 discussions
- Check before accessAlways verify that objects, attributes, and variables are not None before accessing their properties, calling their methods, or using them in operations. This prevents common runtime errors like TypeError, AttributeError, or UnboundLocalError when working with optional values.vllm-project/vllm7 discussions
- Dynamic configuration needs validationWhen implementing dynamic configuration options, validate that the system actually supports runtime changes for that setting. A configuration should only be marked as dynamic if:vitessio/vitess7 discussions
- Descriptive consistent namingChoose variable, function, and class names that accurately reflect their purpose while maintaining consistency with established patterns in the codebase. When the purpose or content of an entity changes, update its name accordingly. This applies to:vitejs/vite7 discussions
- informative error messagesError messages should be specific, contextual, and include relevant information to aid debugging and user understanding. Avoid generic messages like "invalid syntax" in favor of descriptive explanations that specify what was expected, what was found, and include the problematic data when helpful.vlang/v7 discussions
- function documentation standardsAll public functions and methods must be documented with comments that `v doc` can understand. Documentation should start with the function name and clearly explain the function's behavior and purpose. For static methods, explicitly identify them as such (e.g., "MethodName static method returns..."). vlang/v7 discussions
- Clear technical writingEnsure technical documentation uses clear, grammatically correct language with consistent formatting when explaining naming conventions and code structure. This includes proper capitalization, precise word choice, consistent code formatting with backticks, and clear sentence structure.vlang/v7 discussions
- Choose efficient data structuresSelect data structures and algorithms based on performance characteristics and actual usage patterns rather than convenience or familiarity. Consider memory efficiency, computational complexity, and scaling behavior when making implementation choices.vlang/v7 discussions
- Structure for readabilityOrganize code to maximize readability and maintainability. When code becomes complex, break it down into smaller, more manageable pieces with clear responsibilities:astral-sh/uv7 discussions
- Redact URL credentialsAlways redact sensitive credentials in URLs before logging, displaying in error messages, or serializing to prevent accidental exposure of authentication information. Use dedicated wrapper types like `LogSafeUrl` that automatically handle credential redaction when displaying URLs:astral-sh/uv7 discussions
- Choose efficient data structuresSelect data structures and algorithms that optimize for the specific use case rather than defaulting to generic collections. Consider computational complexity, memory usage, and access patterns when making these choices.unionlabs/union7 discussions
- Organize tailwind classesStructure your Tailwind CSS classes for readability and maintainability. Instead of long chains of conditional classes with `&&` operators, use object syntax with clear naming patterns. This improves code readability and makes maintenance significantly easier.shadcn-ui/ui7 discussions
- Names reveal semantic purposeChoose names that clearly communicate the semantic purpose and behavior of code elements. Variable and function names should precisely reflect their role, return type, and intended usage.microsoft/typescript7 discussions
- Document function behavior completelyFunctions should be documented with comprehensive JSDoc comments that cover: 1. Purpose and behavior description 2. All parameters with their types and constraintsmicrosoft/typescript7 discussions
- prefer compile-time configurationUse compile-time configuration checks with `cfg!` macros instead of runtime environment variable parsing when the configuration decision can be determined at build time. This improves performance by eliminating runtime checks and makes the code's behavior more predictable.tree-sitter/tree-sitter7 discussions
- avoid unnecessary Option operationsWhen working with Option types, prefer efficient and safe access patterns over unnecessary operations. Use `.as_ref().unwrap()` instead of `.clone().unwrap()` to avoid unnecessary cloning when you only need a reference to the contained value. When possible, prefer safe alternatives like `to_string_lossy()` over `unwrap()`, or use early returns with the `?`...tree-sitter/tree-sitter7 discussions
- Use descriptive namesChoose names that clearly express the purpose, behavior, or semantic meaning of variables, functions, and types. Avoid ambiguous or generic names that require additional context to understand their role.traefik/traefik7 discussions
- Graceful, Specific Error HandlingWhen handling failures, prefer predictable, safe behavior over broad or crash-prone exception handling—especially around filesystem, JSON parsing, network calls, and user/CLI boundaries.TauricResearch/TradingAgents7 discussions
- Structure conditional compilationUse organized structural patterns for conditional compilation to improve code maintainability and readability. Avoid applying `#[cfg]` attributes directly to function parameters - instead wrap conditionally available data in structs that can be zero-sized when features are disabled:tokio-rs/tokio7 discussions
- Follow naming conventionsChoose names that follow established API conventions and guidelines to create a consistent, intuitive codebase: 1. For conversions or views: - Use `as_*` for cheap, reference-based conversionstokio-rs/tokio7 discussions
- Meaningful consistent namesChoose names that are both semantically precise and follow consistent conventions. Names should accurately reflect behavior and purpose while adhering to established patterns in the codebase.tensorflow/tensorflow7 discussions
- Measure performance impactBefore making performance-related changes, measure the actual impact with benchmarks and profiling. Many performance assumptions can be misleading without data.sveltejs/svelte7 discussions
- Document structure consistencyMaintain consistent document structure and formatting in documentation to improve readability and user experience. Follow these key principles: 1. **Use sentence case for headings** - Only capitalize the first word and proper nouns:supabase/supabase7 discussions
- Use AssertJ correctlySpring Framework tests must use AssertJ for assertions rather than JUnit's `Assertions`, Spring's `Assert` class, or plain `assert` statements. Follow these AssertJ best practices:spring-projects/spring-framework7 discussions
- Maintain consistent naming patternsFollow established naming patterns and conventions throughout the codebase to ensure consistency and clarity. This includes: 1. Use existing naming patterns for similar concepts:spring-projects/spring-boot7 discussions
- Consistent observability dataWhen implementing observability features, always ensure consistency in your data model, especially with tags and attributes. This helps prevent issues with backends that expect consistent tag sets.spring-projects/spring-boot7 discussions
- Simplify conditional structuresOrganize complex conditional logic using clear, sequential patterns rather than nested structures or multiple early returns. This improves code readability and maintainability by making the flow of logic easier to follow.apache/spark7 discussions
- validate memory boundsAlways validate array and string bounds before accessing memory to prevent out-of-bounds access and potential crashes. When working with strings or arrays, especially those with known length information, check indices against the actual length before dereferencing pointers.bytedance/sonic7 discussions
- Package organization standardsMaintain proper package organization by following established structural patterns and separation of concerns. Code should be organized into appropriate packages based on functionality and responsibility.SigNoz/signoz7 discussions
- Promise error handling patternsWhen handling promise errors, use the second callback parameter of `.then()` instead of `.catch()` when you want to handle only the specific promise rejection and avoid accidentally catching programmer errors from the success handler. Use `.catch()` only when you intend to handle all errors in the promise chain.serverless/serverless7 discussions
- Eliminate redundant operationsIdentify and eliminate repeated expensive operations to improve performance. Look for opportunities to cache results, avoid duplicate computations, and minimize unnecessary work.serverless/serverless7 discussions
- API schema validation accuracyEnsure that JSON schema validation for API configurations precisely matches the actual service requirements and constraints. Schema validation should use correct JSON schema properties and accurately reflect documented API limits.serverless/serverless7 discussions
- Language-agnostic configuration designDesign configuration parameters to be language-agnostic when possible, use established configuration objects, and maintain consistency across language server implementations. Avoid language-specific CLI options or constructor parameters when the functionality could apply broadly.oraios/serena7 discussions
- Use data providers effectivelyOrganize your test suite by using data providers to consolidate similar test cases rather than creating multiple test methods with duplicated logic. This improves maintainability, increases test coverage, and makes adding new test scenarios easier.getsentry/sentry-php7 discussions
- Evolve API safelyWhen modifying existing APIs, implement changes that maintain backward compatibility while enabling new functionality. For public-facing APIs, avoid breaking changes outside of major version bumps.getsentry/sentry-php7 discussions
- Minimize mocks verify behaviorWrite tests that verify actual system behavior rather than implementation details by minimizing mock usage and focusing on real interactions. Excessive mocking can lead to brittle tests that pass even when core functionality is broken.getsentry/sentry7 discussions
- eliminate code duplicationIdentify and consolidate duplicate code patterns by extracting common logic into reusable functions and unifying similar code blocks. This improves maintainability, reduces bugs, and enhances readability.strands-agents/sdk-python7 discussions
- Choose appropriate synchronizationSelect the correct synchronization mechanism based on your execution context and avoid unnecessary synchronization overhead. In async contexts with coroutines, locks are often unnecessary since coroutines run cooperatively in a single thread. Use `asyncio.Lock()` for async contexts and `threading.Lock()` for multi-threaded scenarios. When bridging sync and...strands-agents/sdk-python7 discussions
- Standardize configuration value handlingImplement robust and type-safe configuration handling to avoid fragile hardcoding and improve maintainability. Key guidelines: 1. Use type-safe structures for passing configuration between processes instead of raw stringsrust-lang/rust7 discussions
- Ensure complete test coverageWrite comprehensive tests that cover all relevant cases and variations while maintaining proper organization and structure. Key practices: 1. Place tests in appropriate locations (e.g., core tests in `library/coretests`)rust-lang/rust7 discussions
- Simplify code expressionsStrive for clarity by simplifying code expressions and reducing unnecessary complexity. Complex or verbose expressions decrease readability and increase the chance of errors during maintenance.dotnet/runtime7 discussions
- Choose error strategies deliberatelyMake deliberate choices about error handling strategies based on the context. Decide between early returns with appropriate error reporting, panic mechanisms, or silent failures with diagnostics:astral-sh/ruff7 discussions
- SSR documentation completenessEnsure server-side rendering documentation provides complete implementation details with proper build configurations and explanatory context. SSR setup guides should include comprehensive Vite configurations that clearly separate client and server bundles, detailed explanations of script purposes, and complete file structures.TanStack/router7 discussions
- Validate nullable values explicitlyAlways handle potentially null or undefined values explicitly using type guards, null coalescing operators, and proper fallback values. This ensures type safety and prevents runtime errors from null references.RooCodeInc/Roo-Code7 discussions
- Preserve error context chainWhen catching and re-throwing errors, always preserve the original error context using the `cause` option of the Error constructor. This maintains the complete error chain for debugging and ensures no critical information is lost when translating errors between layers.RooCodeInc/Roo-Code7 discussions
- Maintain consistent terminology patternsEnsure consistent terminology usage across the codebase, especially in localization files and technical documentation. When a term is established (whether in translation or technical context), maintain that same term throughout related files and contexts.RooCodeInc/Roo-Code7 discussions
- Document i18n string usageAll user-facing strings must be documented with translation function usage to ensure proper internationalization support. This includes error messages, notifications, labels, and any text displayed to users.RooCodeInc/Roo-Code7 discussions
- Consistent localization formattingEnsure all localization strings maintain consistent formatting patterns within each locale file. This includes: 1. **Terminal punctuation**: All similar messages should consistently end with appropriate punctuation marks for the locale (periods in English/French, "।" in Hindi, etc.).RooCodeInc/Roo-Code7 discussions
- Configure with careAlways validate configuration values before use, provide sensible defaults, and centralize constants in shared modules. When implementing configuration handling:RooCodeInc/Roo-Code7 discussions
- Correct Fast-Path SemanticsWhen implementing algorithmic optimizations (fast paths, binary search vs linear, prefetch/slot routing, realloc/compaction shortcuts), require *semantic correctness* and *invariant preservation* before performance.redis/redis7 discussions
- CI/CD Workflow GuardrailsWhen building or modifying CI/CD GitHub Actions workflows, structure them as an explicit DAG of artifact-driven jobs and guard execution to prevent fork/irrelevant-context failures.redis/redis7 discussions
- organize related code togetherKeep related functionality grouped together to improve code discoverability and maintainability. This includes placing related functions in the same module, maintaining consistent test file placement, and avoiding unnecessary file fragmentation.remix-run/react-router7 discussions
- simplify redundant logicEliminate redundant conditional logic, extract duplicated code, and choose simpler patterns over complex implementations. This improves code readability and maintainability by reducing cognitive load.facebook/react-native7 discussions
- extract complex logicBreak down complex functions and large files into smaller, focused units with clear responsibilities. Extract complex logic into well-named helper functions, split large files into focused modules, and prefer `const` over `let` for variables that won't be reassigned.facebook/react-native7 discussions
- Configuration validation and defaultsAlways validate configuration structure before accessing properties and provide sensible defaults while preserving explicit user overrides. Configuration code should defensively check for the existence of nested properties and gracefully handle missing or malformed configuration.facebook/react-native7 discussions
- avoid !! operatorAvoid using the not-null assertion operator (`!!`) as it can cause runtime crashes if the assumption about non-nullability is incorrect. Instead, use safer alternatives that provide better error handling and code clarity.facebook/react-native7 discussions
- Database-specific query optimizationLeverage database-specific features to optimize queries and improve performance. Different database engines have unique capabilities that can significantly enhance query efficiency when used appropriately.rails/rails7 discussions
- Configure at proper scopePlace configuration options at their proper scope within the framework hierarchy. Avoid tight coupling between components and ensure user configurations aren't accidentally overridden.rails/rails7 discussions
- Test isolation and tiersWhen adding or changing behavior, require unit tests that are (a) comprehensive for the logic contract, (b) correctly prioritized/selected via pytest markers, and (c) isolated from global state to avoid cross-suite flakiness.infiniflow/ragflow7 discussions
- Scoped API ContractWhen implementing API-facing features, ensure request/response contracts are consistent across all code paths, correctly shaped for the upstream/downstream API, and complete under pagination/time-windowing.QwenLM/qwen-code7 discussions
- Robust error propagationWhen handling failures, ensure you (a) don’t lose the real root cause, (b) never introduce new exceptions while trying to report one, and (c) keep graceful degradation both implemented and tested.QwenLM/qwen-code7 discussions
- Mutation-Effective TestingEnsure your tests are *mutation-effective*: they must fail when the implementation changes in ways that break intended behavior. Avoid vacuous assertions, and don’t confuse “a test exists” with “the test would catch the real bug.”QwenLM/qwen-code7 discussions
- Avoid Drift ConstantsWhen code relies on values or logic that can diverge from the rest of the system (CSS/layout, shared pagination sizes, status-to-UI rules, helper behavior), prefer a single source of truth.QwenLM/qwen-code7 discussions
- Atomic Reservation And RecheckWhen adding concurrency behavior (locks, in-flight guards, timeouts, retries, sampling), ensure three properties: 1) Atomic “check-and-act” before any await (avoid TOCTOU)QwenLM/qwen-code7 discussions
- Atomic Exact-Run CancellationWhen implementing concurrent async workflows with callbacks (Stop/Submit/Cancel, permission settlement, card actions), make the operation safe against stale/foreign/parallel events by using atomic identity validation plus a synchronous “claim” before any awaited side effects.QwenLM/qwen-code7 discussions
- Stable React RenderingWrite React components and tests so they don’t depend on React’s internal render/callback sequencing, and so Suspense boundaries capture the work that actually suspends.tanstack/query7 discussions
- Precise API ContractsWhen designing or documenting API options and callbacks, ensure the contract is exact, unambiguous, and type-safe. - **Specify true behavior and defaults**: If an option affects multiple behaviors, document what it does *exactly* (including defaults). Prefer the control mechanism that precisely matches intent (e.g., stop polling by returning `false` from...tanstack/query7 discussions
- Deterministic CI PracticesWhen touching CI/CD workflows, keep execution deterministic and CI stable: - **Don’t duplicate steps**: if a publish script already runs tests, avoid running `test:ci` again in the workflow.tanstack/query7 discussions
- Meaningful error communicationError handling should be designed to provide clear, actionable information to developers while avoiding redundancy. Follow these practices: 1. **Don't duplicate error reporting** - If you're throwing an exception, don't also log the same error. This creates noise and confusion.quarkusio/quarkus7 discussions
- Document configuration comprehensivelyConfiguration properties should be thoroughly documented with explicit details about constraints, units, default values, and behavior implications. This helps users understand how to use them correctly and troubleshoot issues.quarkusio/quarkus7 discussions
- API evolution strategyDesign APIs with future extensibility in mind by using parameter objects instead of direct method parameters. When an API might need additional parameters in the future, encapsulate them in an interface or class:quarkusio/quarkus7 discussions
- Document code rationaleAdd clear comments that explain the "why" behind non-obvious code decisions, complex logic, or special-case handling. This is especially important when:pydantic/pydantic7 discussions
- Consistent term capitalizationFollow consistent capitalization rules for technical terms, acronyms, and library names throughout your codebase and documentation: 1. **Capitalize standard acronyms**: Use 'URL', 'JSON', 'API', 'HTML', 'CSS', 'Unicode', etc. rather than lowercase versions.pydantic/pydantic7 discussions
- Meaningful consistent namingUse names that clearly describe the purpose and behavior of variables, methods, classes, and files, while maintaining consistency across the codebase. Follow these guidelines:prowler-cloud/prowler7 discussions
- Explicit endpoint contract compositionDefine each endpoint's request/response contract explicitly rather than deriving it by inheriting another endpoint's full schema and subtracting or layering fields on top. Extend-then-omit composition (e.g., building a Responses schema by starting from the entire Chat schema and omitting fourteen fields, or extending a full provider config into a...promptfoo/promptfoo7 discussions
- Configuration precedence rulesWhenever a setting can come from multiple sources (explicit per-call config, provider-level overrides, suite/global env, specific env vars, or built-in defaults), the precedence order must be explicit, documented, and verified end-to-end — never silently dropped or confused with a built-in default.promptfoo/promptfoo7 discussions
- Extract duplicate codeWhen you notice code patterns being repeated across multiple locations, extract them into reusable functions or constants to improve maintainability and follow DRY principles.prisma/prisma7 discussions
- Database provider compatibilityEnsure database code properly handles provider-specific differences and capabilities. Different database providers have varying syntax requirements, feature support, and connection methods that must be accounted for in the implementation.prisma/prisma7 discussions
- consistent error object usageAlways use proper Error objects when throwing exceptions, maintain consistent error handling contracts, and ensure type safety in error scenarios. Avoid throwing primitive strings, mixing throw/return patterns, or unsafe type assertions on error objects.prisma/prisma7 discussions
- Consistent clear namingUse consistent terminology across similar concepts and choose names that clearly indicate their purpose. Avoid overloaded terms that cause confusion in your domain context, and ensure naming conventions align with established patterns.prisma/prisma7 discussions
- Logging consistency and safetyWhen writing/adjusting code, treat logging as part of error handling: - Use the right level: log request- or operation-failure conditions at `error`/`exception` (not `warning`).the-pr-agent/pr-agent7 discussions
- Config Scope And HygieneTreat configuration as a product surface: make it correct, discoverable, and safe. Practical rules: 1) Document scope/precedence explicitly: If an override is ineffective for certain commands due to caching/initialization order, state that clearly and point users to the effective setting (global config or env var).the-pr-agent/pr-agent7 discussions
- Budget-Aware PerformanceWhen code builds prompts, traverses trees, calls external APIs, or processes many items, make performance predictable by enforcing budgets, preventing pathological inputs, and removing redundant work.the-pr-agent/pr-agent7 discussions
- Use descriptive namesVariable, method, and class names should clearly and accurately describe their purpose, content, or behavior. Misleading or vague names create confusion and make code harder to understand and maintain.python-poetry/poetry7 discussions
- optimize algorithmic efficiencyChoose efficient algorithms and data structures to avoid unnecessary computational complexity. Look for opportunities to replace expensive operations with more efficient alternatives, especially when dealing with collections and search operations.python-poetry/poetry7 discussions
- dependency constraint consistencyMaintain consistent formatting and rationale for dependency version constraints in configuration files. Use caret notation (`^1.0.0`) instead of range notation (`>=1,<2`) for cleaner syntax when specifying compatible version ranges. When constraining to specific Python versions, choose between explicit version strings (`"3.7"`) and comparison operators...python-poetry/poetry7 discussions
- validate inputs earlyAlways validate function parameters and configuration options at the beginning of functions, providing specific and actionable error messages that guide users toward correct usage. This prevents downstream errors and improves developer experience.microsoft/playwright7 discussions
- Specify configuration behaviorsWhen implementing configuration features (variables, flags, resources), thoroughly document their behavior in all scenarios, especially edge cases and interactions with dependencies. Configuration options should have well-defined and tested behaviors across all contexts where they might be used.opentofu/opentofu7 discussions
- Optimize code location scopePlace code in the most specific and appropriate location to improve findability and maintainability. Follow these principles: 1. Avoid generic utility modules - place code in specific, relevant modulesopen-telemetry/opentelemetry-python7 discussions
- Future-proof API designDesign APIs that can evolve without breaking existing code. Use keyword-only arguments (with `*,`) for optional parameters to make API extensions safer. This prevents positional argument errors when parameters change and allows for easier parameter reordering, addition, and deprecation.open-telemetry/opentelemetry-python7 discussions
- Use proper assertionsWrite tests with proper assertions to ensure reliability and maintainability. Follow these guidelines: 1. **Check for empty data** before proceeding with tests to prevent invalid test conditions:opencv/opencv7 discussions
- Use optimized functionsWhen implementing algorithms, prefer using OpenCV's built-in optimized functions over writing custom implementations. OpenCV's library functions are typically vectorized, extensively tested, and optimized for performance across different platforms and hardware architectures.opencv/opencv7 discussions
- Intention-Revealing NamingWrite names that clearly communicate meaning, scope/intent, and project terminology—especially on public APIs/CLI and when calling helpers. Apply: - Match canonical terms: use the team/docs/external-provider wording for user-facing strings and public parameters (e.g., `endpoint`).openai/openai-python7 discussions
- Avoid event-loop blockingDo not perform blocking I/O or other long-running synchronous work on asyncio’s event loop (especially in async client construction). Offload to worker threads (e.g., `asyncio.to_thread`) and prefer lazy credential/platform resolution protected by an async lock.openai/openai-python7 discussions
- Idempotent normalization pipelinesWhen code must normalize or classify structured data (messages, request bodies, model/provider selection, metrics), implement it as deterministic, *idempotent*, and *non-mutating* transformations.diegosouzapw/OmniRoute7 discussions
- Cache correctness rulesAdopt a “cache correctness” checklist for all in-memory/DB caches: 1) Explicit bypass must be honored - If the caller passes a disable value (commonly `ttlMs === 0`), bypass both lookup and inflight coalescing. Don’t treat `0` as “use default TTL”.diegosouzapw/OmniRoute7 discussions
- Maintain consistent styleFollow established patterns consistently throughout the codebase to improve readability and maintainability: 1. **Use auto properties with appropriate access modifiers**:octokit/octokit.net7 discussions
- User-centric documentation practicesDocumentation should prioritize user needs and experience over technical convenience. This means using appropriate link types (guides over API docs for user-facing content), organizing content to avoid overwhelming newcomers, providing necessary context, and ensuring links work correctly with tooling.nrwl/nx7 discussions
- Avoid code duplicationBefore implementing new functionality, check if similar utilities or patterns already exist in the codebase. Reuse existing code rather than duplicating logic, and organize shared types and constants in centralized locations to prevent circular dependencies and maintain consistency.nrwl/nx7 discussions
- Use consistent terminologyPrioritize consistent, clear, and beginner-friendly terminology throughout your codebase and documentation. Choose names that are intuitive for users rather than technically precise but confusing. Maintain consistency with established patterns and style guidelines.nuxt/nuxt7 discussions
- Version APIs with careWhen introducing new API features or changes, implement proper versioning to maintain stability and backward compatibility. Key practices: 1. Guard experimental features behind version flagsnodejs/node7 discussions
- Public over internal APIsWhen designing or implementing APIs, always prefer publicly documented APIs over internal ones. Internal APIs may change without notice as they aren't subject to semantic versioning guarantees.nodejs/node7 discussions
- Benchmark before optimizing codePerformance optimizations should be validated through benchmarks before implementation. This helps prevent premature optimization and ensures changes actually improve performance in real-world scenarios.nodejs/node7 discussions
- Simplify control flowStreamline code by simplifying control flow structures to improve readability. Eliminate unnecessary nesting and verbosity by applying these guidelines:netty/netty7 discussions
- Proper asynchronous error handlingEnsure errors in asynchronous operations and event-based systems are handled consistently to prevent unexpected behavior. Always maintain Promise integrity by never resolving and rejecting the same Promise, and use appropriate error event handlers.nestjs/nest7 discussions
- Descriptive identifier namesChoose identifier names (variables, functions, parameters, classes) that clearly describe their purpose, content, or behavior. Replace generic terms like `value`, `data`, or `options` with more specific alternatives that convey meaning.nestjs/nest7 discussions
- Complete function documentationEnsure all functions have comprehensive, accurate documentation including required tags (@param, @return, @since), clear descriptions that match actual behavior, and explanatory comments for complex logic.neovim/neovim7 discussions
- API consistency patternsEnsure similar API functions use consistent parameter patterns, types, and behaviors. When designing new APIs or modifying existing ones, identify related functions and align their interfaces to create predictable, reusable patterns.neovim/neovim7 discussions
- Structure endpoints for RESTOrganize API endpoints hierarchically by resource type and use appropriate HTTP methods based on operation semantics. Group related operations under resource-based paths, use debug prefixes for administrative endpoints, and select HTTP methods that match the operation's behavior:neondatabase/neon7 discussions
- Clear consistent identifier namesChoose clear, consistent, and non-redundant names for identifiers across the codebase. Follow these guidelines: 1. Use specific, descriptive names that clearly indicate purpose:neondatabase/neon7 discussions
- Unrolled SIMD LocalityWhen optimizing hot kernels (SIMD/vectorized paths), remove avoidable overhead and improve locality: 1) Unroll small fixed-size tails (e.g., remainder=4)Tencent/ncnn7 discussions
- Guard and narrow exceptionsWhen an operation can fail in a known way (edge-case inputs, risky math, I/O/parsing, optional capabilities), handle it explicitly: - Add targeted guards before risky computations (e.g., avoid dividing/normalizing by an empty denominator).karpathy/nanochat7 discussions
- Maintain test state isolationEnsure each test runs in isolation by properly managing test state, mocks, and timers. Clean up all test artifacts in beforeEach/afterEach hooks rather than within individual tests to prevent state leakage and test interdependence.n8n-io/n8n7 discussions
- Simplify for readabilityComplex expressions, especially nested ternary operations, reduce code readability and maintainability. Prefer simpler alternatives: 1. Break down nested ternary operations into clear if-else statements:apache/mxnet7 discussions
- Consistent naming patternsMaintain consistent naming conventions throughout the codebase to enhance readability and reduce confusion. This applies to: 1. **Import aliases**: Use standardized aliases for imported libraries. When working with both MXNet's NumPy and the official NumPy, use 'onp' for the official NumPy to clearly distinguish between them:apache/mxnet7 discussions
- remove unnecessary codeEliminate unnecessary code elements that add complexity without providing value. This includes removing redundant function wrappers, unnecessary type annotations, singleton classes that could be simple objects, explicit type conversions where implicit ones suffice, and methods that duplicate existing functionality.rocicorp/mono7 discussions
- prioritize code readabilityWrite code that prioritizes clarity and readability over cleverness or brevity. This includes several key practices: **Extract static functions**: Move functions that don't depend on component state outside the component to reduce complexity and make their static nature clear.rocicorp/mono7 discussions
- Use Contextual SanitizationAny diagram text/config that can originate from users (node labels, tooltips, markdown, theme/style tokens, and link targets) must be treated as untrusted. Apply **context-appropriate** escaping/sanitization and avoid security-by-regex.mermaid-js/mermaid7 discussions
- Prefer Grammar Over RegexUse the language parser/grammar (e.g., Langium/Jison) for diagram syntax instead of hand-rolled regex parsing. Regex is allowed only for small, well-bounded token-level helpers when (a) it precisely matches the intended grammar slice (e.g., remove only *outer* quotes), (b) it doesn’t destructively change user content or semantics, and (c) it preserves...mermaid-js/mermaid7 discussions
- Prefer fast-paths and cachingWhen performance matters, structure code to avoid unnecessary work: (1) keep cheap fast-paths first for short-circuiting, (2) cache expensive global lookups (like config) instead of repeatedly calling them, (3) reuse costly parser/services/stateful objects, (4) lazy-load heavy dependencies only when required, and (5) remove redundant rendering/computation...mermaid-js/mermaid7 discussions
- Doc Examples Must RenderAll documentation examples/configs must be compatible with the docs build/render pipeline and current Mermaid configuration conventions. **Apply this checklist when touching documentation:**mermaid-js/mermaid7 discussions
- Semantic Identifier ConsistencyUse names that (a) match the authoritative contract and (b) truthfully describe what the code does—consistently across upstream, models, and outputs. awslabs/mcp7 discussions
- Safety-First DocumentationAny technical documentation that includes operational steps (especially schema changes, data deletion, bucket/table cleanup, or “fix by deleting”) must be both safe and unambiguous.awslabs/mcp7 discussions
- Safe Async Resource HandlingShared resources (connections, clients, caches) must be concurrency-safe across async tool invocations. **Standard** 1. **Validate before publish**: never put a resource into a shared cache/map until it is known-good. This prevents race windows where other coroutines can use an unvalidated handle.awslabs/mcp7 discussions
- Document Behavior AccuratelyEnsure all agent-facing documentation (tool descriptions, docstrings, help text, and auto-enriched descriptions) is factually aligned with the actual implementation and is structured consistently.awslabs/mcp7 discussions
- centralize configuration managementMigrate configuration from direct environment variable access to Rails' config_for mechanism for better organization, testability, and maintainability. Instead of accessing ENV variables directly throughout the codebase, consolidate them into YAML configuration files loaded at application startup.mastodon/mastodon7 discussions
- Modern C++ style practicesApply modern C++ features and consistent syntax patterns to improve code readability and safety. Follow these guidelines: 1. Use modern C++ features:maplibre/maplibre-native7 discussions
- Simplify code readabilityWrite code that prioritizes clarity and simplicity over cleverness. Use appropriate Clojure idioms to make code more readable and maintainable. Key practices:logseq/logseq7 discussions
- Extract reusable componentsExtract utilities, types, constants, and shared logic into dedicated modules to improve code maintainability and reduce duplication. When you find yourself writing similar code in multiple places, or when you have magic strings/numbers, inline type definitions, or mixed business logic, extract them into appropriate shared locations.lobehub/lobe-chat7 discussions
- Add unit testsAll new functionality must include corresponding unit tests. This is especially critical for utility functions, core logic modules, stream processing, data transformation methods, and complex business logic. Without unit tests, code becomes difficult to understand and maintain over time.lobehub/lobe-chat7 discussions
- Simplify for readabilityImprove code readability by simplifying complex logic, using Pythonic idioms, and removing unnecessary code. Extract helper functions for complex conditions, avoid code duplication, and leverage Python's built-in features for cleaner code.LMCache/LMCache7 discussions
- Ensure operation completion safetyIn concurrent code, ensure that operations complete safely before proceeding to prevent race conditions and data corruption. This applies to several scenarios:LMCache/LMCache7 discussions
- comprehensive test coverageTests should comprehensively cover all relevant scenarios, including return values, edge cases, different compilation modes, and abnormal conditions. This includes:llvm/llvm-project7 discussions
- avoid unnecessary allocationsMinimize performance overhead by avoiding unnecessary memory allocations, expensive data structures, and redundant object creation. Choose appropriate data types and parameter passing methods based on actual requirements rather than convenience.llvm/llvm-project7 discussions
- leverage existing framework functionalityBefore implementing custom solutions in AI model conversion code, thoroughly investigate whether the framework already provides the needed functionality. This applies to inheritance patterns, configuration handling, tensor operations, and mapping conventions.ggml-org/llama.cpp7 discussions
- eliminate code duplicationAvoid duplicating code blocks by extracting common functionality into reusable functions, using templates for type-generic operations, and moving shared utilities to common modules. Code duplication makes maintenance difficult, increases the likelihood of bugs, and violates the DRY (Don't Repeat Yourself) principle.ggml-org/llama.cpp7 discussions
- Follow consistent naming patternsMaintain consistent naming conventions across all aspects of the codebase, including file structures, folder organization, environment variables, and identifiers. This ensures predictability and reduces cognitive load for developers.BerriAI/litellm7 discussions
- Surface errors to usersAlways provide user-visible feedback for errors instead of only logging to the console. This ensures users are aware of failures and can take appropriate action. This is especially important for:langfuse/langfuse7 discussions
- Falsy vs null checksDistinguish between falsy values (0, '', false, null, undefined) and null/undefined values in your code. Use explicit checks for null/undefined when you want to preserve other falsy values.langfuse/langfuse7 discussions
- Cache expensive operationsIdentify and cache results of computationally expensive or repetitive operations instead of recalculating them multiple times. This includes function calls, date object creation, data transformations, and resolved promises.langfuse/langfuse7 discussions
- Use comprehensive JSDocAlways use JSDoc format (`/** */`) instead of regular comments (`//`) for documenting classes, functions, and interfaces. Documentation should be comprehensive, including:langchain-ai/langchainjs7 discussions
- Preserve API backward compatibilityWhen modifying existing APIs, maintain backward compatibility by implementing changes in a non-breaking way. Use method overloading, optional parameters, or deprecation notices rather than direct breaking changes.langchain-ai/langchainjs7 discussions
- Safe caching practicesApply caching only when it is safe, bounded, and correct: 1) Avoid unbounded method memoization - Don’t use `functools.lru_cache/cache` directly on methods whose arguments can grow without a tight bound (risk of memory leaks). If you must cache, use a bounded cache (`maxsize=...`) or a different lifecycle.langchain-ai/langchain7 discussions
- Deterministic Algorithm CorrectnessWhen implementing non-trivial algorithms (graph ordering, batching under constraints, multi-pass transformations), apply four requirements: 1) **Guarantee termination with explicit guards/invariants**langchain-ai/langchain7 discussions
- Consistent None HandlingWhen a value can be missing/null, reflect it in the type system and handle it explicitly at the boundary—never leak `None` into observable outputs (yields, dict keys, metadata, merged content) and don’t “paper over” missing invariants with synthetic placeholders.langchain-ai/langchain7 discussions
- implement proper observabilityEnsure observability mechanisms (events and metrics) are implemented correctly with appropriate types, accurate labeling, and user-focused messaging. Use events for user-visible information that appears in `kubectl describe`, not just internal logging. Choose correct event types (`EventTypeNormal` for waiting states, `EventTypeWarning` for actual failures)...kubernetes/kubernetes7 discussions
- Document Variants DeltasWhen introducing new code-path variants (e.g., “ForResize” vs base algorithms), comments/documentation must clearly explain: 1) **The delta vs the base implementation**: what changes and what stays identical.kUbernetes/kUbernetes7 discussions
- Clear field documentationWrite precise, unambiguous documentation that explains what fields and methods represent rather than implementation details. Avoid recursive definitions, ambiguous terms, and focus on the user-facing behavior and purpose.kubernetes/kubernetes7 discussions
- Avoid unnecessary workOptimize performance by avoiding unnecessary computations, allocations, and operations. Use feature gates, lazy evaluation, and conditional logic to prevent work that won't be used.kubernetes/kubernetes7 discussions
- Simplify code structureStrive to simplify code structure by eliminating unnecessary complexity. This includes: 1. **Move conditions higher in the code** when appropriate to avoid unnecessary operations. Check conditions as early as possible to fail fast or skip work.kubeflow/kubeflow7 discussions
- Precise workflow triggersConfigure CI/CD workflows to trigger precisely based on relevant file path changes. This minimizes unnecessary builds and tests while ensuring all required workflows run when dependencies are modified.kubeflow/kubeflow7 discussions
- Go export naming conventionsIn Go, the first letter of an identifier (function, variable, struct field, etc.) determines its visibility outside the package: 1. **Uppercase first letter**: The identifier is exported and accessible from other packageskubeflow/kubeflow7 discussions
- Use configuration property providersAlways use Gradle's Provider API when accessing project, system, or Gradle properties in your build configuration. This ensures proper handling of configuration cache and allows for dynamic property updates.JetBrains/kotlin7 discussions
- Test edge casesEnsure tests verify both basic functionality and edge cases. Tests that only cover the happy path can miss critical bugs in boundary conditions and special scenarios.JetBrains/kotlin7 discussions
- Minimize unnecessary workOptimize performance by reducing the amount of computation performed, especially on data that won't appear in the final result. Apply these strategies:JetBrains/kotlin7 discussions
- Keep code clearly organizedMaintain code readability and organization by extracting focused, well-named functions and using appropriate scoping. Break down complex logic into smaller, focused functions and utilize extension functions when appropriate to improve code clarity.JetBrains/kotlin7 discussions
- Design extensible stable APIsWhen designing public APIs, prioritize extensibility while maintaining backward compatibility and implementation hiding. This ensures APIs can evolve without breaking existing clients while allowing for future enhancements.JetBrains/kotlin7 discussions
- Semantic Naming RulesAdopt a naming standard where identifiers encode meaning, don’t clash with framework semantics, and don’t obscure behavior. Guidelines: - Avoid reserved/special filenames and namespace collisions. If a module filename has framework semantics (e.g., `api.lua` in plugin contexts), don’t reuse it for unrelated code—rename or place code where it can’t be...Kong/kong7 discussions
- Network semantics consistencyWhen implementing HTTP/TCP/WebSocket/networking logic, treat protocol semantics as “correctness-critical”: don’t rely on accidental behavior, and don’t assume inputs are single-valued.Kong/kong7 discussions
- prioritize documentation clarityWrite documentation that prioritizes user understanding over technical precision. Avoid unclear phrases, overly technical explanations, and unhelpful references. When in doubt, choose clarity over brevity, especially for user-facing documentation that may be someone's first encounter with a feature.jj-vcs/jj7 discussions
- Use testify assertionsAlways use the testify package (require/assert) in tests instead of standard Go testing assertions. The testify library provides more descriptive failure messages that make debugging test failures easier and faster.influxdata/influxdb7 discussions
- Validate environment variables strictlyEnforce strict validation of environment variables using Zod schemas with explicit environment-specific rules. Required configurations should be mandatory in production while allowing flexibility in development/test environments.elie222/inbox-zero7 discussions
- prevent null dereferencesAlways verify pointers are valid before dereferencing to prevent crashes and undefined behavior. This applies to regular pointers, weak pointers, and return values from C functions that may return null.hyprwm/Hyprland7 discussions
- avoid expensive hot pathsIdentify and optimize expensive operations in frequently executed code paths to prevent performance bottlenecks. Hot paths include rendering loops, input event handlers, and frequently called utility functions.hyprwm/Hyprland7 discussions
- API type consistencyUse structured types instead of generic strings in API definitions to improve type safety and clarity. Prefer enums over string literals, specific ID types over generic strings, and maintain consistent data type usage across request/response models.juspay/hyperswitch7 discussions
- Sanitize untrusted inputAny value that comes from the client or another external source (headers, query params, path segments, class names, cookie values, etc.) must be validated, escaped, or restricted to a known-safe set before it is used in a context where it can change the meaning of surrounding code — dynamic `RegExp` construction, HTML/attribute output, or file-system path...HONOJS/HONO7 discussions
- Safe response header mutationWhen writing caching-related middleware (cache, etag, compress), never assume a cloned or cached `Response` has mutable headers. Responses returned directly from `fetch()` or retrieved from the Cache API are immutable in many runtimes (Cloudflare Workers, Deno), so calling `.clone()` and then `headers.set()/delete()` will throw `TypeError: Headers are...honojs/Hono7 discussions
- HTTP header spec complianceWhen reading, writing, or forwarding HTTP headers, follow RFC semantics instead of naive string checks. For multi-value headers (Accept-Encoding, Vary, Connection, Cache-Control, etc.), parse them properly by splitting on commas, trimming whitespace, and handling parameters such as q-values and wildcards rather than relying on `.includes()` or substring...honojs/hono7 discussions
- Consistent exception handlingStandardize how errors are thrown, propagated, and reported across the codebase. 1. Prefer `HTTPException` over manually constructed `Response` objects when signaling an HTTP-level error, so status codes and bodies stay consistent. When a custom body/content-type is needed, build the response via the `Context` (e.g. `c.text(...)`) and pass it through...honojs/hono7 discussions
- Wire Contract EnforcementExternal API boundaries must enforce the *final wire contract*: only supported parameters, only provider-accepted content shapes, and only schema-valid payloads.nousresearch/hermes-agent7 discussions
- Robust error pathsWhen handling errors, ensure you don’t (1) mask the original failure, (2) violate the intended timeout/retry/cleanup boundaries, or (3) make recovery decisions without explicit evidence.nousresearch/hermes-agent7 discussions
- Profile-scoped API routingAll profile-scoped routing must use the mechanism your IPC/bridge/router actually consumes (e.g., an outer request field or a `...profileScoped()` wrapper). Do not attempt to “scope” routing by placing `profile` inside nested request bodies that the backend simply binds/forwards, or by passing `profile` only as a query param unless the bridge explicitly...nousresearch/hermes-agent7 discussions
- Cache Scope and KeysWhen adding or modifying caching/deduplication, ensure the cache identity (routing + key + scope) matches the exact contract where reuse is valid. Key rules:nousresearch/hermes-agent7 discussions
- Handle nullable valuesTreat None/absent values explicitly and guard attribute access. Motivation: user input, storage APIs, optional configuration, and runtime objects can all produce None or lack expected attributes. Implicitly assuming presence leads to data loss (e.g., deleting checkpoints on a cancelled prompt), brittle logic, and runtime errors.p-e-w/heretic7 discussions
- use descriptive namesChoose specific, purpose-revealing names that clearly communicate intent rather than generic, abbreviated, or ambiguous terms. Names should describe what something does or represents, not what it doesn't do.helix-editor/helix7 discussions
- Safe concurrent programmingWhen working with concurrent code, carefully manage shared resources and synchronization to prevent race conditions, deadlocks, and resource leaks: 1. **Protect shared data**: Always synchronize access to data accessed by multiple goroutines using appropriate primitives like mutexes or channels.grafana/grafana7 discussions
- Follow documentation conventionsEnsure documentation adheres to established style guidelines and technical standards: 1. **Use proper terminology and formatting:** - Write "data source" as two words, not "datasource"grafana/grafana7 discussions
- Test behavioral differencesTests should verify that different states, modes, or inputs produce meaningfully different behaviors, not just that code doesn't crash. Focus on testing state transitions, edge cases, and behavioral changes rather than basic existence checks.google-gemini/gemini-cli7 discussions
- reduce nesting complexityPrefer early returns, guard clauses, and helper method extraction to reduce nesting levels and improve code readability. Deep nesting makes code harder to follow and understand.google-gemini/gemini-cli7 discussions
- Express error handlingFor Express apps, standardize error handling as follows: - Define error-handling middleware with the correct signature: `(err, req, res, next)`. - Register it last in the middleware chain (after routes). If you add a 404 handler, place it after routes but before the error handler.freeCodeCamp/freeCodeCamp7 discussions
- Use modern PHPUnit attributesPrefer modern PHPUnit attributes over PHPDoc annotations for improved type safety, IDE support, and code readability in tests. Replace legacy annotation-style test decorators with their attribute counterparts:laravel/framework7 discussions
- Catch specific, meaningful exceptionsWhen handling errors, catch the narrowest exception type that accurately represents the failure, and avoid broad `except:`/`except Exception` blocks that silently swallow errors or hide tracebacks needed for debugging. If a broad catch is truly required (e.g. Python 2 compatibility where exceptions may not derive from `BaseException`), make the intent...pallets/flask7 discussions
- check all error returnsAlways check and handle error returns from function calls, even for operations that seem unlikely to fail. Ignoring errors can lead to silent failures, resource leaks, and unpredictable behavior in production.gofiber/fiber7 discussions
- Technical term consistencyWhen working with multilingual codebases or documentation, maintain consistent naming conventions for technical terms across all languages. Consider the following practices:fastapi/fastapi7 discussions
- Sync versus async testsChoose the appropriate testing approach based on your test requirements. For standard API endpoint testing, use `TestClient` with regular functions. For tests requiring async operations (like database queries), use `AsyncClient` with proper async test configuration.fastapi/fastapi7 discussions
- Standardize dependency version notationWhen specifying dependencies in package.json, follow consistent version notation patterns that align with your project's stability and compatibility requirements:expressjs/express7 discussions
- Pin and automate action dependenciesAll third-party GitHub Actions must be pinned to an immutable commit SHA (with the version as a trailing comment) rather than a mutable tag, since tags can be rewritten and immutable pins are required for supply-chain security (e.g., OSSF Scorecard). Example:expressjs/Express7 discussions
- Hot-path efficiencyCode that runs per-request or in other hot paths must avoid unnecessary overhead. Prefer simple, cheap operations over heavier alternatives when both achieve the same result: use direct string checks instead of regex for trivial cases, use plain `for` loops instead of `Array#forEach`/closures in tight loops, and short-circuit work that isn't needed (e.g....Expressjs/Express7 discussions
- Follow StandardJS when modifyingWhen modifying existing code, update the touched lines to follow StandardJS conventions while preserving the style of untouched code. This ensures gradual, consistent adoption of StandardJS formatting.expressjs/express7 discussions
- Clear intention in namesChoose names that clearly communicate intention and follow established conventions. This applies to variables, functions, methods, and architectural components.expressjs/express7 discussions
- prefer const correctnessAlways mark variables, parameters, and methods as `const` when they don't modify state. This improves code safety, enables compiler optimizations, and makes intent clearer to readers.electron/electron7 discussions
- comprehensive test coverageEnsure thorough test coverage by systematically testing edge cases, boundary conditions, failure scenarios, and different data types. When implementing new functionality, consider all possible input variations, error conditions, and integration points.duckdb/duckdb7 discussions
- avoid repeated expensive operationsIdentify and eliminate repeated expensive computations, especially in loops and frequently executed code paths. This optimization principle focuses on moving invariant calculations outside loops, caching results of expensive operations, and avoiding unnecessary data conversions or memory allocations.duckdb/duckdb7 discussions
- Complete parameter documentationEnsure all public functions and classes have comprehensive docstrings that include parameter descriptions, type hints, return value documentation, and references to related implementations. This significantly improves usability by helping developers understand how to use APIs correctly and find related code.stanfordnlp/dspy7 discussions
- Use descriptive identifier namesChoose clear, descriptive names for variables, functions, and classes that accurately convey their purpose and follow framework conventions. Avoid abbreviations, single-letter names, or generic placeholders that might confuse readers.django/django7 discussions
- Follow established naming conventionsEnsure all identifiers follow the established naming conventions for the codebase and framework being used. This includes using native JavaScript private method syntax with `#` instead of underscore prefixes, following camelCase for JavaScript methods and variables, matching existing naming patterns for consistency, and avoiding deprecated naming...discourse/discourse7 discussions
- Clean typing and DRYAdopt a “type-correct, DRY, and clean” coding style. Rules: 1) Make type hints compile and be precise - If you use `Dict`, `List`, `Union`, etc., import them from `typing` (or use built-in `dict`/`list` where appropriate).eosphoros-ai/DB-GPT7 discussions
- Prefer simple, idiomatic codeFavor the simplest, most idiomatic construct that accomplishes the task, and remove any code that doesn't add value. Concretely: - Use guard clauses to return early instead of nesting the rest of a function inside an `if`, which reduces indentation and improves readability:python/cpython7 discussions
- Clean code formatting rulesMaintain consistent and clean code formatting to improve readability and maintainability. Follow these guidelines: 1. Use correct syntax for utility classes:continuedev/continue7 discussions
- CI script reliability practicesEnsure CI/CD workflows maintain reliability by following these practices: 1. **Use explicit script paths** - Always use explicit paths when invoking scripts (e.g., `./build.ps1` for PowerShell or `./build.sh` for bash) rather than relying on implicit path resolution. This ensures the runner can locate and execute scripts regardless of the current working...continuedev/continue7 discussions
- Deterministic Parsing And MatchingWhen implementing parsing and lookup/diff algorithms on strings/filesystems, guarantee determinism and correctness by (1) normalizing inputs into a canonical form before comparison/keying, (2) explicitly handling ambiguity instead of silently choosing an arbitrary match, and (3) deduping by semantic change keys while keeping a stable order.apple/container7 discussions
- Avoid repeated hot-path workIn performance-sensitive code, avoid doing expensive operations repeatedly inside loops (repeated flattening/sorting, repeated filesystem attribute resolution, repeated regex/compiler/formatter construction, repeated list+search scans). Also ensure your tree/hierarchy logic uses consistent keys for both ordering and relationship detection.apple/container7 discussions
- explicit configuration managementMake all configuration settings explicit and well-documented, avoiding implicit defaults and auto-detection where possible. This includes dependency versions, build flags, environment variables, and tool configurations.docker/compose7 discussions
- Use roles and unionsWhen code has multiple behavioral variants (output format, hook context type, session state), prefer modeling the variation explicitly with types/roles and reusing shared logic—rather than duplicating implementations or threading many conditionals/flags.CLINE/cline7 discussions
- Typed Role-Based AbstractionsWhen behavior varies (output format, hook origin, execution state), avoid scattering conditionals and duplicated helpers/formatters. Instead: - Centralize branching behind a small set of role objects created once (e.g., a RunOutputter factory) so the main flow stays straight-line.CLINE/CLINE7 discussions
- Test boundaries and wiringWhen writing tests, choose the boundary intentionally: validate user-/system-relevant behavior without brittle low-level mocking, and stub only external dependencies.CLINE/cline7 discussions
- Stateful Network DispatchNetwork code should behave deterministically across retries/reconnects by (a) confirming exactly when data is accepted/“dispatched”, (b) preventing duplicate sends, and (c) bounding/aborting all network work.Cline/Cline7 discussions
- Semantic, Consistent NamingUse naming that is semantically precise, consistent with existing conventions, and hard to misuse. **Rules** 1. **Prefer existing vocabulary/types.** If the codebase already has a canonical type or naming scheme, align to it (e.g., client identifiers should use the established `ClientName` concept).CLINE/cline7 discussions
- Guard Async State UpdatesWhen multiple async operations (fetches, timers, clipboard reads, event streams) can overlap, ensure only the newest/authorized result can mutate shared state or UI.CLINE/cline7 discussions
- Guard Against Stale AsyncWhen async operations can overlap (polls, refreshes, reads with caches, sign-out/account switches, clipboard reads, timers), ensure only the latest/valid result can produce side effects.CLINE/CLINE7 discussions
- Explicit Null SemanticsWhen inputs/settings are optional (undefined/nullable) treat null/undefined as part of the product logic: distinguish “absent” from “explicit empty”, prefer explicit reset values, and gate behavior so missing context can’t silently pick the wrong fallback or misclassify errors.ClInE/cLiNe7 discussions
- Consistent Config ResolutionWhen decisions depend on environment/provider/backend/config, resolve them once using shared, centralized helpers, then pass the resolved value downstream. Avoid duplicated “mini re-resolvers” that can drift.Cline/Cline7 discussions
- Concurrency-safe Async FlowsWhen implementing async/concurrent behavior, prevent stale updates, duplicate side-effects, and resource leaks by following these rules: 1) Register wiring once; route through mutable statecline/CLINE7 discussions
- semantic naming accuracyEnsure that method, variable, and class names accurately reflect their actual behavior, purpose, or content. Names should semantically match what they represent to prevent confusion and bugs.ClickHouse/ClickHouse7 discussions
- Explicit error handlingAlways handle error conditions explicitly rather than silently ignoring them or using generic error responses. Use specific error codes that reflect business logic rather than low-level system errors, and throw exceptions for unexpected states instead of using assertions or returning generic failure indicators.ClickHouse/ClickHouse7 discussions
- Document non-obvious codeAdd explanatory comments for any code element that is not self-explanatory, including complex return types, method parameters, classes, and technical concepts that may not be familiar to all developers.ClickHouse/ClickHouse7 discussions
- prevent silent test failuresTests must explicitly fail when expected conditions are not met, rather than silently exiting early or using weak assertions that can hide real issues. Silent test failures create false confidence in test suites and can mask regressions.snyk/cli7 discussions
- Handle all errors explicitlyAlways explicitly handle errors rather than assuming they are handled by dependencies or ignoring them. Every function that returns an error should have that error checked and handled appropriately. Use proper error wrapping with fmt.Errorf and the %w verb to maintain error chains, and ensure resource cleanup with defer statements even when errors occur.snyk/cli7 discussions
- Document intent and reasoningAdd comments that explain the reasoning, intent, or context behind code decisions, especially for non-obvious logic, workarounds, or business requirements. Focus on the "why" rather than just the "what" to help future maintainers understand the decision-making process.snyk/cli7 discussions
- API response consistencyEnsure consistent patterns for API response handling, error management, and type safety across all API interactions. This includes standardizing error response structures based on status codes, properly defining response types to match actual API behavior, and implementing robust error handling with appropriate fallbacks.snyk/cli7 discussions
- Document with examplesAlways include comprehensive documentation with clear examples for properties, methods, and code patterns. Documentation should include: 1. **Property descriptions**: Use the `description:` attribute to explain what each property doeschef/chef7 discussions
- Consistent descriptive naming patternsUse clear, descriptive names that follow consistent patterns across the codebase. For methods and properties: 1. Use intention-revealing names that clearly indicate purposechef/chef7 discussions
- Meaningful identifier namesChoose descriptive and semantic identifiers that clearly convey purpose, role, and behavior. Avoid vague, generic names in favor of specific ones that enhance code readability and self-documentation.bridgecrewio/checkov7 discussions
- Hoist invariant workIn hot paths (functions called repeatedly, e.g. styling/formatting code), avoid recomputing or re-allocating values that don't change between calls. Precompute and cache expensive-to-build objects (like `RegExp` instances) once at module/init time instead of rebuilding them on every invocation, cache frequently accessed built-in methods or mutable...chalk/chalk7 discussions
- Logging Correctness RulesWhen adding or modifying logging: 1) **Match logging intent to behavior (level + visibility)** - If a user-supplied config or runtime option fails and a fallback happens, log at an appropriate user-visible level (often `warning`)—don’t silently continue.celery/celery7 discussions
- Validate nullability explicitlyAlways validate null or undefined values before using them to prevent crashes and undefined behavior. When implementing null-handling code, consider these principles:oven-sh/bun7 discussions
- Assert before castAlways validate values before performing unsafe operations like dynamic casting. When a value could be null, zero, or undefined, store it in an intermediate variable and verify it before proceeding.oven-sh/bun7 discussions
- Standardize API integration patternsEstablish consistent patterns for API integrations by following these guidelines: 1. Document API endpoint usage specifically: - Clearly specify which components use each endpointHomebrew/brew7 discussions
- Optimize collection operationsUse Ruby's built-in collection methods to write more efficient and readable code. This reduces algorithmic complexity and improves performance by leveraging optimized implementations instead of writing manual iterations or chaining multiple operations.Homebrew/brew7 discussions
- Prevent algorithmic pitfallsAvoid common algorithmic errors that lead to incorrect results or inefficient code by following these practices: 1. **Never modify a collection while iterating over it**boto/boto37 discussions
- Follow naming conventionsUse consistent and appropriate naming conventions based on the context in Python code: 1. **Classes**: Use `CamelCase` for class names ```python class ResourceMeta(object):boto/boto37 discussions
- Defensive null value handlingAlways handle potential null/None values defensively by: 1. Using `.get()` for dictionary access instead of direct key access 2. Checking for None/falsy values before accessing their propertiesboto/boto37 discussions
- Stability-First CachingWhen caching affects externally visible payloads (prompts, auth/JWT inputs, token summaries), ensure the *serialized representation used for cache identity is deterministic* and the cache has an *explicit validity boundary*.maximhq/bifrost7 discussions
- Preserve API ContractsMaintain deterministic, provider-compatible API contracts by (1) applying overrides explicitly and attempt-scoped (no hidden side effects), and (2) preserving exact request/response serialization expectations—especially where providers are sensitive to JSON schema structure/order or where passthrough/raw modes must not be rewritten.maximhq/bifrost7 discussions
- Deterministic DB SemanticsMake database changes (queries, migrations, and tests) explicit about shape and semantics: don’t rely on driver defaults, cached plan inference, or “looks right” reads when the DB can mask the truth.maximhq/bifrost7 discussions
- prefer simple readable codeFavor simple, readable implementations over complex or overly abstracted solutions. This includes eliminating code duplication through better function design, simplifying complex expressions, and using standard library functions instead of custom helpers.bazelbuild/bazel7 discussions
- prefer simple API designsDesign APIs with simple, direct interfaces rather than complex parameter passing patterns or unnecessary indirection. Use appropriate parameter types (e.g., `PathFragment` instead of `String`, `ImmutableMap` instead of `BiFunction`) and avoid expanding API surface area when existing patterns can be reused.bazelbuild/bazel7 discussions
- optimize algorithm choicesChoose algorithms and data structures that provide both deterministic behavior and optimal performance characteristics. Prefer ordered collections when iteration order matters, optimize pattern matching to avoid expensive operations, and be mindful of algorithmic complexity.bazelbuild/bazel7 discussions
- Executor service lifecycleProperly manage executor service lifecycle to prevent resource leaks, deadlocks, and orphaned threads that can cause system inconsistencies. Key practices:bazelbuild/bazel7 discussions
- Configuration clarity standardsConfiguration options should be designed with clarity, consistency, and user experience as primary concerns. This includes several key practices: **Clear and specific help text**: Flag descriptions should explicitly explain their purpose and scope to avoid user confusion. For example, instead of generic descriptions, be specific about when and how the flag...bazelbuild/bazel7 discussions
- Stable, Scoped Query OutputsWhen writing KQL for Sentinel (parsers, analytic rules, hunts), make query outputs and intermediate datasets stable and correct: - Prefer **explicit `project`** of the expected/normalized columns (avoid `project-away`) so newly added source columns won’t change the published schema.Azure/Azure-Sentinel7 discussions
- Null Safety PatternsWhen fields or parameters are optional (may be missing, null, or empty-string), code must be defensive so queries/playbooks/parsers don’t fail and so “unknown” stays unknown.Azure/Azure-Sentinel7 discussions
- Early Filter and CacheWhen writing KQL (hunting queries or ASIM parsers), optimize for fewer rows and fewer expensive computations: 1) Prefilter early (before parse/branch work)Azure/Azure-Sentinel7 discussions
- Document Packaging ConventionsWhen updating Sentinel solution documentation artifacts (workbooks metadata, UI definitions, and connector table schemas), treat them as schema- and regeneration-driven. Ensure values match platform conventions and that any generated text will be correct after regeneration.Azure/Azure-Sentinel7 discussions
- Design stable APIsWhen creating or modifying APIs, carefully consider what becomes part of your public API surface to ensure backward compatibility and consistent developer experience.Azure/azure-sdk-for-net7 discussions
- Check before dereferencingAlways verify objects are not null before dereferencing them, particularly when using methods that might return null like FirstOrDefault(), LastOrDefault(), or 'as' casts. Prevent NullReferenceExceptions by adding explicit null checks before accessing members.Azure/azure-sdk-for-net7 discussions
- Semantic And Stable NamingUse names that clearly convey intent, keep them consistent across related resources, and ensure deterministic uniqueness. **1) Make names/intents self-explanatory**Azure/azure-quickstart-templates7 discussions
- Nested Network Resource IDsWhen working with Azure networking in Bicep, avoid “stringly” nested resource references built from `resourceId()` plus `dependsOn`. Instead: 1) **Define subnets idempotently**: create subnets inside the `virtualNetworks` resource via `properties.subnets`.Azure/azure-quickstart-templates7 discussions
- Explicit API ContractsWhen authoring templates or clients that call/describe APIs (Graph, resource providers, etc.), treat the “API contract” as a first-class design artifact:Azure/azure-quickstart-templates7 discussions
- Deterministic Resource NamingUse deterministic, semantically correct identifiers for ARM template parameters and resource names—especially where idempotency and uniqueness are required.Azure/azure-quickstart-templates7 discussions
- Config completeness and environmentUse deployment-time configuration (parameters/derived values) instead of hardcoded or partially-specified settings, and ensure env/config entries required for the selected feature/identity are fully present.Azure/azure-quickstart-templates7 discussions
- Spec fidelity directivesWhen using AutoRest (or similar) to generate PowerShell/SDK surfaces, enforce that the generated cmdlets and types preserve the intended REST API contract—especially around nullability, required parameters, and unintended extra parameter-set variants.Azure/azure-powershell7 discussions
- Follow Generated NamingUse naming-and-identifier rules that match what AutoRest PowerShell generates, and make flag-style parameter typing consistent with the name. Apply these rules when editing custom cmdlets:Azure/azure-powershell7 discussions
- Scoped, Accurate Warning LogsWhen adding warnings/logs, treat them as part of the user experience: only emit warnings when they are actionable, accurate, and non-noisy—especially when runtime feature detection changes behavior.Azure/azure-cli7 discussions
- Readable Lint-Safe CodeWhen changing code, prioritize readable structure that also passes linters with minimal formatting churn: - Keep formatting linter-safe: avoid re-indenting/alignment that triggers flake8 (e.g., E127). Apply the smallest reformat needed to satisfy style rules.Azure/azure-cli7 discussions
- Defensive null checkingAlways perform explicit null/undefined checks before accessing properties or using values that could be null or undefined. Use strict equality checks rather than relying on JavaScript's truthy/falsy evaluation which can lead to subtle bugs.aws/aws-sdk-js7 discussions
- Error precedence and degradationWhen implementing error handling, ensure (1) failures are validated early or handled explicitly, (2) optional steps degrade gracefully, (3) cancellation/abort prevents unnecessary work, and (4) cleanup never masks the true result.coleam00/Archon7 discussions
- Stable dependency version managementAlways use stable, well-defined version constraints in configuration files to ensure reproducible builds and prevent unexpected behavior. Avoid using development branches for production dependencies.appwrite/appwrite7 discussions
- Keep documentation paths currentMaintain accurate and consistent documentation paths, references, and descriptions across the codebase. When terminology or architecture changes, ensure all documentation references are updated to reflect the current state.appwrite/appwrite7 discussions
- Consistent placeholder conventionsEnsure all placeholders in localization files follow consistent naming conventions to prevent runtime errors and text leakage in the UI. This applies to both sprintf-style placeholders (`%s`) and template variables (`{% raw %}{{name}}{% endraw %}`).appwrite/appwrite7 discussions
- Test isolation and determinismTests should be deterministic, isolated, and assert the intended behavior (not just a coincidence or shared prior state). Concretely: - Reset external/shared state for every test (especially Redis, quotas, counters). Do not rely on the order tests run.apache/apisix7 discussions
- Schema-consistent configWhen implementing configuration-driven features, make validation/forwarding/runtime consumption strictly follow the schema and any shared capability wrapper. Avoid plugin-specific special casing for generic capabilities, avoid manual per-branch field copying that can silently drop accepted config, and ensure environment-variable access uses the project’s...apache/apisix7 discussions
- Protocol phase correctnessWhen writing networking plugins/adapters, make behavior consistent with the request/stream lifecycle and the actual protocol/runtime semantics—then lock it with targeted regression tests.apache/apisix7 discussions
- Observability semantic contractEstablish an explicit observability contract in code: tracing spans must be finished centrally with correct semantics; trace context inputs must be validated/formatted to standards; metrics must not mix different meanings across streaming vs non-streaming.apache/apisix7 discussions
- Null Safety ContractsWhen handling optional/nil values, treat nil as a real input only if it’s reachable; otherwise remove dead checks. More importantly, enforce clear contracts for types/shapes so nil never reaches code paths that assume a table/string.apache/apisix7 discussions
- Harden Errors And CleanupTreat any external input (HTTP headers, JSON bodies, provider responses, dynamic config) as untrusted: validate its type/shape before indexing or string operations, and ensure errors don’t turn into uncontrolled 500s or leak state/resources.apache/apisix7 discussions
- Use semantic descriptive namesChoose variable, function, and type names that clearly communicate their purpose, source, and context. Names should be self-documenting and avoid ambiguity or conflicts with existing identifiers.ant-design/ant-design7 discussions
- Prevent component re-mountingMaintain stable component structure to prevent unnecessary re-mounting and unmounting of child components. Conditional rendering that changes component tree structure can cause child components to lose state and trigger mount/unmount cycles, breaking components with mount effects.ant-design/ant-design7 discussions
- API evolution strategyWhen evolving APIs, design for extensibility and provide clear migration paths to maintain backward compatibility while improving developer experience.ant-design/ant-design7 discussions
- Use descriptive namesChoose names that clearly and unambiguously describe their purpose rather than being overly generic or technical. Names should be self-documenting and immediately convey what the entity does or represents.angular/angular7 discussions
- Document configuration specificsWhen documenting configuration options in changelogs, README files, or other user-facing documentation, focus on specific implementation details and user-actionable information rather than vague feature descriptions. Write from the user's perspective, specifying exact configuration keys, values, and behaviors.alacritty/alacritty7 discussions
- Test fidelity and assertionsTests must exercise the real production code path and fail with clear, actionable diagnostics when they break. 1. Never duplicate implementation logic inside a test file "for isolation." If a helper (e.g. `stripReasoningContent`) is only defined and tested as a local copy, the test can pass while the real exported function is broken or never even reached....Decolua/9Router7 discussions
- Prefer Rust structural patternsUse Rust's structural patterns to write more idiomatic and maintainable code. This includes: 1. Use early returns to reduce nesting: ```rust // Instead ofzed-industries/zed6 discussions
- Consider algorithmic complexityWhen implementing algorithms, be mindful of their computational complexity and choose appropriate data structures for operations. 1. **Use specialized collections for their strengths**:zed-industries/zed6 discussions
- prefer higher-level APIsWhen designing APIs, prefer using higher-level abstractions and established patterns over direct low-level handle manipulation. This improves code maintainability, reduces complexity, and ensures consistency across the codebase.cloudflare/workerd6 discussions
- Node.js API compatibilityWhen implementing Node.js-compatible APIs, ensure exact behavioral matching with Node.js, including export structures, method signatures, return types, and property availability. This maintains compatibility with existing Node.js code and meets developer expectations.cloudflare/workerd6 discussions
- minimize memory operationsAvoid unnecessary memory allocations, copies, and inefficient memory usage patterns that can impact performance. This includes several key practices: cloudflare/workerd6 discussions
- maintain consistent patternsEnsure consistent coding patterns and approaches are used throughout the codebase, even when multiple valid alternatives exist. This improves code readability, reduces cognitive load for developers, and makes the codebase easier to maintain.cloudflare/workerd6 discussions
- Use network timeoutsEnsure all network operations are cancellable, timeout-protected, and executed where the resource lives. Motivation - Network calls can hang, run on the wrong machine, or transfer too much data. Apply consistent patterns to avoid resource leaks, unresponsive reads, and incorrect behavior when operating on remote resources.wavetermdev/waveterm6 discussions
- defensive nil handlingAlways validate values and short-circuit on errors; guard uses of possibly nil/empty values while avoiding redundant checks when types guarantee non-nil.wavetermdev/waveterm6 discussions
- Semantic, Contract-Revealing NamesUse naming that matches the code’s actual semantics and data contracts—avoid misleading terms and generic parameter names. Apply these rules: - Behavior-accurate wording: don’t use terms like “unset” when the implementation “restores”/“replaces” a previous value.warpdotdev/warp6 discussions
- Purpose-Driven DocumentationWhen adding or modifying code, ensure comments/doc comments are written to explain meaning and rationale—not just what the code does or where it’s mutated.warpdotdev/warp6 discussions
- Graceful Error SemanticsDefine and implement explicit, user- and operator-facing error semantics for async/protocol code: handle recoverable/expected mismatches without panicking, make failure outcomes observable, and ensure recovery/retry behavior is bounded and well-specified.warpdotdev/warp6 discussions
- Explicit Missing-State HandlingWhen data is optional/unknown, handle it intentionally and explicitly—either skip the feature (return `None`) or fall back to a safe default—never via implicit drop or placeholder sentinel values.warpdotdev/warp6 discussions
- Use specific semantic namesChoose specific, descriptive names for identifiers that accurately reflect their purpose and behavior. Avoid generic terms or ambiguous names that could lead to confusion. Names should be self-documenting and convey precise meaning.microsoft/vscode6 discussions
- Minimize VerbosityWrite UI/style code to be correct without becoming noisy: - **Preserve intentional inline spacing.** If you remove whitespace nodes, ensure the rendered text still has separation via an explicit space or a CSS rule.microsoft/VSCode6 discussions
- Keep APIs simple JavaScript-likeDesign APIs to be simple and idiomatic to JavaScript/TypeScript while maintaining proper encapsulation. Avoid complex type unions, forced undefined parameters, or implementation details leaking through interfaces.microsoft/vscode6 discussions
- Handle errors with specificityAlways handle errors specifically and explicitly, avoiding generic catch blocks that mask or ignore errors. Ensure proper resource cleanup and consistent error propagation. Key practices:microsoft/vscode6 discussions
- Config Compatibility & Env SafetyWhen configuration behavior changes (new keys, renamed/repurposed toggles, UI pickers, feature-gates), ensure user intent is preserved and avoid unsafe process-wide environment side effects.microsoft/VSCode6 discussions
- Algorithm explanation clarityWhen documenting algorithms, provide detailed explanations of the underlying logic with concrete examples and clear process flows. Abstract algorithmic descriptions should be accompanied by specific scenarios that illustrate how the algorithm behaves in practice.volcano-sh/volcano6 discussions
- Use self-documenting namesVariable, function, and parameter names should accurately reflect their purpose, behavior, and content. Choosing descriptive names improves code readability and reduces bugs caused by naming confusion.vllm-project/vllm6 discussions
- Stable documentation linksEnsure all documentation links are stable, consistent, and correctly targeted to improve navigation and long-term maintainability: 1. **Use stable references**: Always link to stable release tags or specific commit hashes rather than volatile branches like `master` or `main`:vllm-project/vllm6 discussions
- Process configurations consistentlyEnsure that configuration data is processed consistently and correctly throughout the codebase. This includes: 1. **Use proper serialization methods** for configuration dictionaries. Prefer `json.dumps()` over `str()` when converting dictionaries to strings:vllm-project/vllm6 discussions
- Optimize data structuresChoose and implement data structures with careful consideration of algorithmic complexity, memory usage, and Go's specific performance characteristics. Pay attention to:vitessio/vitess6 discussions
- Extract shared code patternsIdentify and extract repeated code patterns into reusable functions to improve maintainability and reduce duplication. When similar code appears in multiple places, create a shared helper function that captures the common logic.vitessio/vitess6 discussions
- Ensure documentation accuracyDocumentation must precisely reflect the current codebase implementation. When documenting features, options, or APIs: 1. Validate that all examples match the actual implementation. For instance, if template names or file formats change, update all references in the documentation:vitejs/vite6 discussions
- Make errors user actionableError messages should provide clear, actionable information that helps users understand and resolve the problem. Each error should: 1. Include specific context about what failedastral-sh/uv6 discussions
- Validate production configurationsAlways validate configuration values and ensure production safety by avoiding hardcoded values, implementing proper defaults, and requiring explicit configuration for production-critical settings. Configuration should be validated at runtime to prevent deployment of incorrect values.unionlabs/union6 discussions
- Module resolution hierarchyWhen configuring TypeScript projects, establish a clear understanding of module and type resolution hierarchies, especially when using different package managers like npm or Yarn's Plug'n'Play (PnP).microsoft/typescript6 discussions
- Specify algorithmic scope preciselyWhen documenting changes to algorithms, data structures, or computational approaches, explicitly identify the specific components affected rather than using vague or generic descriptions. This includes naming exact data structure classes, clarifying the scope and limitations of algorithmic improvements, and using precise technical terminology.astral-sh/ty6 discussions
- Use semantically accurate namesNames should clearly and accurately reflect their actual purpose, functionality, and scope. Avoid misleading terminology that doesn't match the component's or variable's true behavior.twentyhq/twenty6 discussions
- Use domain-specific exceptionsCreate custom exception classes for each domain/module instead of throwing generic errors or letting applications crash. Include both technical details for developers and user-friendly messages for end users. Handle exceptions at the appropriate service layer rather than at API boundaries.twentyhq/twenty6 discussions
- simplify API interfacesKeep API interfaces simple and focused by avoiding unnecessary input wrapping, extracting context parameters appropriately, and limiting exposure of internal implementation details.twentyhq/twenty6 discussions
- Know your implicit configurationsWhen working with Turborepo, be aware of implicit configurations and special files that affect behavior even when not explicitly configured. For example, `turbo.json` and `package.json` are always considered inputs when determining if a package has changed, even if you try to explicitly ignore them. Package manager lockfiles are also always parsed and...vercel/turborepo6 discussions
- Eliminate code duplicationAvoid duplicating logic, patterns, or data across the codebase. When similar code appears in multiple places, extract it into reusable functions or methods.vercel/turborepo6 discussions
- Optimize frequent operationsIdentify code paths that execute frequently (loops, hot functions, repeated calls) and optimize them by avoiding redundant computations, expensive operations, and unnecessary allocations.tree-sitter/tree-sitter6 discussions
- Algorithm and data optimizationChoose efficient algorithms and appropriate data structures based on access patterns and computational requirements. Use built-in comparison methods like `cmp()` to avoid redundant checks, select data structures that match usage patterns (HashSet for lookups, Vec for iteration), and ensure algorithmic correctness by handling edge cases properly.tree-sitter/tree-sitter6 discussions
- complete observability router optionsWhen documenting router configuration options for any provider (Docker, Consul Catalog, ECS, KV stores, Nomad, etc.), ensure that all observability-related router options are included and properly documented. This is critical for enabling comprehensive monitoring, tracing, and logging capabilities.traefik/traefik6 discussions
- Use Option methods idiomaticallyWhen dealing with Optional values, prefer Rust's built-in Option methods over manual null checks. This makes code more concise, self-documenting, and less error-prone by leveraging Rust's type system to enforce null safety at compile time.tokio-rs/tokio6 discussions
- Structural configuration approachesWhen working with feature flags and conditional compilation, prefer structural approaches over scattered configuration attributes throughout your code. This creates more maintainable code and reduces the chance of bugs when features are added or removed.tokio-rs/tokio6 discussions
- Prefer explicit over conciseChoose explicit and unambiguous names over concise but unclear ones. When a method, type, or variable has a specific behavior or purpose, the name should clearly communicate that, even if it results in longer names.tokio-rs/tokio6 discussions
- Organize code logicallyGroup related code elements together with a consistent and logical structure. Place stable fields and functionality first, followed by conditional or unstable features.tokio-rs/tokio6 discussions
- Optimize memory allocationBe deliberate about memory allocation patterns to improve performance. Implement these practices: 1. **Pre-allocate collections when the size is known**:tokio-rs/tokio6 discussions
- Network API design consistencyWhen designing networking APIs, maintain consistency with existing interfaces while ensuring proper cross-platform compatibility. Follow these key principles:tokio-rs/tokio6 discussions
- Follow import styleTokio projects follow specific import conventions for consistency and readability. Adhere to these guidelines: 1. Use separate `use` statements for different modulestokio-rs/tokio6 discussions
- Flexible consistent API patternsDesign APIs with flexibility and consistency by leveraging established patterns and avoiding unnecessary constraints. Accept generic type bounds instead of concrete types to provide more flexibility to users and simplify usage.tokio-rs/tokio6 discussions
- Design error handling carefullyWhen implementing error handling, balance between propagation and recovery. Design error types to preserve context while providing users with meaningful ways to handle failure.tokio-rs/tokio6 discussions
- Simplify for readabilityPrioritize code readability by using simpler and more direct expressions. When possible, return values directly instead of using temporary variables and explicit return statements. Break complex logic into intermediate variables with descriptive names. Structure control flow for maximum clarity, preferring Rust idioms like match expressions over nested...huggingface/tokenizers6 discussions
- Descriptive purpose-driven namingChoose identifiers that accurately describe their purpose and behavior, not just their type or how they're used. Names should be specific enough to understand their role without requiring additional context.hashicorp/terraform6 discussions
- Contextual null checksUse type-appropriate null checking strategies based on the context of your data. For primitive values, ensure they exist before accessing properties. For complex nested structures, use more comprehensive checks like `IsWhollyKnown()` instead of simple `IsKnown()` to verify all nested attributes.hashicorp/terraform6 discussions
- Use established configuration patternsWhen adding new configuration options or settings, leverage existing configuration frameworks and patterns rather than implementing custom solutions. This ensures consistency, reduces boilerplate code, and maintains alignment with established practices.microsoft/terminal6 discussions
- manage object lifetimes carefullyEnsure proper object lifetime management in concurrent scenarios to prevent crashes from dangling pointers and premature destruction. Use weak references for event handlers that may outlive their target objects, and capture strong references in async operations to keep objects alive during coroutine execution.microsoft/terminal6 discussions
- Choose efficient data structuresSelect data structures and types that optimize for both memory usage and computational efficiency. Avoid unnecessary copies, use appropriately sized types, and consider the performance characteristics of your choices.microsoft/terminal6 discussions
- Choose efficient implementationsWhen implementing algorithms, prioritize both correctness and performance by selecting appropriate data structures, optimizing memory usage, and leveraging language features.tensorflow/tensorflow6 discussions
- Specific assertion methodsUse the most specific and descriptive assertion methods available in your test framework to improve test readability and failure diagnostics. Prefer methods that clearly state intent and produce helpful error messages.temporalio/temporal6 discussions
- Precompute and cacheAvoid performing expensive operations repeatedly, especially in hot code paths. Identify operations such as parsing, deserialization, or configuration lookups that can be done once and reused.temporalio/temporal6 discussions
- Comprehensive function documentationFunctions, methods, and non-trivial constants should include comprehensive documentation that explains their purpose, behavior, parameters, and relationships to similar functionality. Documentation should be precise about what the code does and when errors may occur, avoiding misleading statements.gravitational/teleport6 discussions
- document configuration hierarchiesWhen documenting configuration options, clearly explain all available configuration levels and their precedence order. Many configuration options can be set globally, per-component, or dynamically, and users need to understand these different approaches.sveltejs/svelte6 discussions
- Document complex APIsRequire comprehensive JSDoc documentation for classes, complex functions, and all exported functions to improve codebase maintainability and developer onboarding. Focus especially on code with broad reach across the codebase or non-obvious functionality.sveltejs/svelte6 discussions
- Choose descriptive namesPrioritize semantic clarity and descriptive naming over brevity or convenience. Avoid esoteric, abbreviated, or ambiguous identifiers that require mental translation to understand their purpose.sveltejs/svelte6 discussions
- Prevent hardcoded secretsNever store sensitive information such as API keys, passwords, tokens, or credentials directly in your source code. These hardcoded secrets are easily exposed through version control systems, code sharing, or security breaches, creating significant security vulnerabilities.supabase/supabase6 discussions
- Use appropriate collectionsChoose the right collection implementation for each algorithmic task to optimize both performance and readability. Use Sets for operations requiring uniqueness, TreeMap for maintaining sorted keys, and leverage built-in collection methods rather than implementing operations manually.spring-projects/spring-framework6 discussions
- Meaningful exception designDesign exceptions to provide clear context, preserve stack traces, and propagate correctly through your system. Key practices include: 1. Choose the most appropriate exception type based on the error condition:spring-projects/spring-boot6 discussions
- Documentation clarity principlesWhen writing technical documentation, adhere to these core principles to ensure clarity and effectiveness: 1. **Use precise technical terminology**: Choose the most accurate terms for technical concepts and be consistent with product names. Remove unnecessary qualifiers when context is clear.spring-projects/spring-boot6 discussions
- Document configuration properties completelyConfiguration properties should be fully documented with clear descriptions, explicit default values, and proper metadata. This helps users understand and configure the application correctly.spring-projects/spring-boot6 discussions
- Concrete bean return typesWhen defining `@Bean` methods in Spring configurations, use concrete return types rather than interfaces while using interface types in `@ConditionalOnMissingBean` annotations. This approach maximizes type information available to the Spring bean factory while maintaining flexibility in bean overriding.spring-projects/spring-boot6 discussions
- Alphabetical ordering requirementAlways maintain alphabetical ordering for lists of elements including dependencies, modules, configuration entries, and other similar collections. This convention improves code organization, makes it easier to locate items, prevents duplications, and ensures consistency across the codebase.spring-projects/spring-boot6 discussions
- optimize data structuresChoose appropriate data structures and algorithms to optimize computational complexity and performance. Consider the specific use case and access patterns when selecting between different approaches.apache/spark6 discussions
- use loose equality checksUse loose equality (`== null`) instead of strict equality (`=== null` or `=== undefined`) when checking for both null and undefined values. In most JavaScript contexts, null and undefined should be treated equivalently, and loose equality provides a more concise and readable way to handle both cases.serverless/serverless6 discussions
- configuration examples accuracyEnsure configuration examples and documentation use current, supported syntax and accurately reflect the actual behavior of the system. Avoid promoting deprecated features, outdated versions, or configuration options that have no effect.serverless/serverless6 discussions
- avoid local importsPlace all import statements at the top of the file as global imports rather than importing modules within functions or methods. Local imports reduce code readability, complicate dependency tracking, and can indicate poor code organization.oraios/serena6 discussions
- Use descriptive identifiersChoose variable, parameter, field, and class names that clearly communicate their purpose and context. Favor specific, self-explanatory identifiers over generic or ambiguous ones, and ensure they follow Python's snake_case convention.getsentry/sentry6 discussions
- Structure logs with contextUse structured logging with appropriate context and log levels to maximize the value of log messages. Include relevant metadata with each log message to facilitate filtering and debugging:getsentry/sentry6 discussions
- Explicit null handlingAlways be explicit and consistent when handling null values to improve code clarity and prevent subtle bugs. This applies to null checks, nullable type declarations, and function parameters.getsentry/sentry-php6 discussions
- Feature flag rolloutsUse feature flags to gate new functionality for controlled rollouts. This allows for quick enabling/disabling without code reverts when issues arise, and supports gradual adoption through percentage-based rollouts.getsentry/sentry6 discussions
- Structure validation algorithmsWhen implementing or modifying parsing and validation algorithms, carefully consider both the correctness and user experience aspects: 1. **Preserve structural ordering** in data structures like ASTs when order impacts semantics. As noted in discussion #1, "In some cases, like in macro scoping, the order is actually important," so field reordering can...rust-lang/rust6 discussions
- Clear helpful error messagesCreate user-friendly error messages that guide developers toward solutions. Error messages should: 1. Include the problematic value in the message 2. Provide clear suggestions for fixing the issuerust-lang/rust6 discussions
- Optimize common pathsDesign algorithms that optimize for the most common execution paths by prioritizing frequent scenarios in conditional logic, data structures, and resource allocation. dotnet/runtime6 discussions
- Model actual hardware costsBase optimization decisions on accurate hardware cost models rather than outdated assumptions. Modern architectures have different performance characteristics for operations than older hardware, especially for SIMD and memory operations.dotnet/runtime6 discussions
- Document configuration intentConfiguration settings should be self-documenting with clear intent. When adding temporary workarounds, conditional flags, or platform-specific settings, include descriptive comments explaining their purpose, limitations, and lifecycle. Use TODO comments with issue references for temporary configurations, and choose clear, descriptive names for all...dotnet/runtime6 discussions
- Handle nulls with OptionUse Rust's Option type and its methods effectively to handle nullable values. This improves code clarity and safety by making null cases explicit and leveraging the type system.astral-sh/ruff6 discussions
- Enhance code clarityEnsure all code examples and documentation are as clear and complete as possible for developers. This includes adding clarifying inline comments to explain non-obvious behavior, including all necessary import statements, and structuring information for maximum readability.TanStack/router6 discussions
- API parameter designDesign API parameters thoughtfully by making them optional when appropriate, avoiding unnecessary required parameters, and maintaining backward compatibility when changing parameter signatures. Consider the actual usage patterns and avoid forcing users to provide parameters that have sensible defaults or aren't always needed.TanStack/router6 discussions
- Maintain consistent naming patternsUse consistent naming patterns throughout the codebase. When adding new identifiers, follow existing patterns in similar contexts. This includes: 1. Consistent prefix/suffix patterns in related identifiersRooCodeInc/Roo-Code6 discussions
- Enforce resource usage limitsImplement explicit resource limits and monitoring to prevent performance degradation and memory issues. This includes: 1. Define maximum sizes for buffers and cachesRooCodeInc/Roo-Code6 discussions
- Enforce API format consistencyMaintain consistent data formats, parameter units, and interface patterns across API implementations. This includes: 1. Consistent type mappings and format handlingRooCodeInc/Roo-Code6 discussions
- Targeted, Non-Bloated TestsWhen adding/modifying tests, ensure they are (a) semantically aligned to the behavior under test, (b) precise enough to prove the intended code path was executed, and (c) not bloated or duplicated.redis/redis6 discussions
- Use descriptive semantic namesChoose variable, function, and type names that clearly communicate their purpose and context. Prioritize readability and semantic meaning over brevity.remix-run/react-router6 discussions
- precise null type checkingUse precise null and undefined type checking that matches the actual usage context. Distinguish between checking if a type contains undefined (`undefined extends T`) versus checking if a type is exactly undefined (`Equal<T, undefined> extends true`). For inferred return types, use the "contains undefined" check since the type may be a union. For direct...remix-run/react-router6 discussions
- Hook dependencies stabilityEnsure hook dependencies are minimal, stable, and follow React's rules to prevent unnecessary re-renders and maintain predictable behavior. This includes:remix-run/react-router6 discussions
- configuration consistency standardsEnsure configuration options, flags, and environment settings are handled consistently across all commands and modules. This includes supporting the same configuration flags across CLI commands, using standardized approaches for environment detection, and implementing clear precedence rules.remix-run/react-router6 discussions
- configuration compatibility validationEnsure that code examples and documentation accurately reflect the constraints and requirements of different rendering modes and configurations. When documenting APIs or providing examples, verify that the suggested approach is compatible with the specific rendering context (SSR, SSG, client-side) and configuration options being used.remix-run/react-router6 discussions
- Prefer simpler expressionsAlways choose the simplest, most readable way to express your code logic. Unnecessary complexity makes code harder to understand and maintain. When writing conditionals, method calls, or data transformations, ask yourself: "Is there a clearer way to express this?"rails/rails6 discussions
- Minimize unnecessary object allocationsAvoid creating unnecessary objects, especially in frequently executed code paths. This includes being mindful of implicit object allocations from common Ruby operations like array methods, string concatenations, and temporary variable creation.rails/rails6 discussions
- Minimize public API surfaceDesign APIs with a minimal public surface area by carefully controlling which methods and properties are exposed. Start with a restricted set of public methods and expand only when there's clear evidence of need. This approach makes APIs easier to maintain and evolve while reducing the risk of breaking changes.rails/rails6 discussions
- Follow documentation conventionsMaintain consistent formatting and style in all documentation to improve readability and professionalism: 1. **Use proper formatting for code elements**:rails/rails6 discussions
- Document APIs clearlyWhen designing and documenting APIs, prioritize clarity and completeness through concrete examples and accurate parameter descriptions. Your documentation should help developers understand both the basic usage and edge cases of your API.rails/rails6 discussions
- Use Shared UI PrimitivesWhen building UI, follow the project’s existing design-system components and tokens instead of creating bespoke patterns. **Standards** 1. **Prefer shared form/UI building blocks**: Use existing components like `RAGFlowFormItem`, `SimilaritySliderFormField`, and `SearchInput` rather than re-implementing the same UI logic/styling.infiniflow/ragflow6 discussions
- Use Clear IdentifiersUse semantically meaningful, convention-compliant names everywhere (parameters, variables, fields, classes, constants), and avoid ad-hoc renaming/mapping that can create ambiguity or incorrect field exposure.infiniflow/ragflow6 discussions
- Null-safe input handlingApply null-safety consistently for request payloads, optional dict keys, and nullable fields. Specifically: - Guard `None` before doing comparisons/logic that assumes a value exists.infiniflow/ragflow6 discussions
- Non-Blocking Async RecoveryConcurrency standard: (1) keep async code non-blocking, (2) don’t change sync/async boundaries unless callers support it, and (3) make recovery/state transitions race-safe.infiniflow/ragflow6 discussions
- Centralized input guardsRequire a shared, spec-aligned “guard” step for any untrusted input used in security-sensitive contexts (SQL construction, dynamic table names, outbound URL fetch). Fail closed (raise a safe exception) before interpolation/requests, and reuse a single utility to avoid security-policy drift.infiniflow/ragflow6 discussions
- Typed API ContractsWhen introducing or changing an API seam (hooks, callback payloads, lifecycle state transitions), require an explicit, end-to-end, type-safe contract that matches implementation and documentation.QwenLM/qwen-code6 discussions
- Sorted Selection SafetyWhen code decides “latest/first/anchor” behavior (events, schedule steps, URL/mention parsing), it must be deterministic by construction: sort inputs by the relevant timestamp/field before using positional selection (e.g., findLast), use dedup keys at the correct granularity to avoid permanent suppression, and make regex/parsers unambiguous with correct...QwenLM/qwen-code6 discussions
- Error semantics invariantsWhen handling failures, treat “what happened” as a precise, testable contract—not an interpretation. Ensure (1) classification predicates are exact and consistent across docs+code, (2) failure causes are not overloaded, (3) cleanup/settlement invariants prevent stranded states, and (4) adapter/step contracts are enforced with safe fallbacks.QwenLM/qwen-code6 discussions
- CI Verification ContractsCI/CD verification steps must produce *truthful, reproducible, human-visible* evidence under hard environment constraints (time, filesystem, available tools, git history). Concretely:QwenLM/qwen-code6 discussions
- Action slot invariantsWhen building React “action slot” containers (inline vs overflow menus, responsive headers, hold/click controls), enforce these invariants: 1) **Preserve host mount semantics**QwenLM/qwen-code6 discussions
- Respect Angular DIWhen integrating with Angular’s DI and reactivity, follow these rules: - **Dependency access:** For hook-like utilities, accept an optional **Injector** (or injector-derived path) so the function can be executed both **inside and outside** the normal injection context. Use Angular’s injection-context/assert-injector helpers to resolve dependencies from the...tanstack/query6 discussions
- Minimize Hot-Path WorkWhen working on performance-sensitive code (query observers, hydration, render-triggering state, hot utilities), ensure you only do the necessary work and no redundant allocations/wrappers, while also preventing leaks.tanstack/query6 discussions
- Explicit StaleTime PolicyFor every query, define a clear staleness/refetch policy—especially for SSR/hydration—rather than relying on defaults or assumptions. **Standards** - **Always choose `staleTime` deliberately** (default is `0`, which means cached data is treated as stale).tanstack/query6 discussions
- Control focus and suspenseWhen implementing React hooks around navigation focus or React Suspense: 1) Treat focus/mount as distinct - If you use `useFocusEffect` to run data refetches, remember the callback also runs on initial mount. Skip the first run when appropriate.tanstack/query6 discussions
- Thread-safe state managementWhen managing state accessed by multiple threads, ensure thread safety through appropriate synchronization mechanisms: 1. **Use thread-safe collections** for multi-threaded access:quarkusio/quarkus6 discussions
- Graceful API evolutionWhen modifying, deprecating, or replacing APIs, ensure a smooth transition experience for developers by following these practices: 1. **Add deprecation warnings** when removing or changing public APIs to alert users:pytorch/pytorch6 discussions
- Performance-Sensitive EfficiencyWhen optimizing, watch for *hidden* inefficiencies: avoid O(n) per-step operations, don’t duplicate expensive work, and don’t eagerly materialize/convert data unless needed.TheAlgorithms/Python6 discussions
- Explicit Optional NullsWhen a value can be absent, represent that absence explicitly and consistently. **Do** - Use `Optional[...]`/`T | None` in type hints for nullable inputs, outputs, and pointers.TheAlgorithms/Python6 discussions
- Algorithm Correctness StandardsWhen implementing algorithms, enforce correctness and reliability by following this checklist: 1) Validate stated preconditions (and document them) - If the algorithm only works for certain input ranges/shapes (e.g., cyclic sort requires values in 1..n with no duplicates), explicitly check those conditions and fail fast with a clear error.TheAlgorithms/Python6 discussions
- Standardize dependency managementMaintain consistent dependency management practices across CI workflows to ensure reliable builds and tests. Use the same tool (e.g., UV, PDM) throughout workflows and specify Python versions explicitly. Avoid redundant dependency specifications when dependencies are already included in other groups.pydantic/pydantic6 discussions
- Maintain code consistencyEnsure code follows consistent patterns throughout the codebase, even when duplicating code is necessary. When similar code patterns appear in multiple places, they should maintain the same structure and approach to improve readability and reduce errors.pydantic/pydantic6 discussions
- Least privilege principleAlways follow the principle of least privilege by granting the minimum permissions necessary for functionality. This applies to various security contexts:prowler-cloud/prowler6 discussions
- Evidence-complete LLM gradingAutomated grading and evaluation logic for LLM outputs (redteam graders, eval scoring, result interchange) must base pass/fail decisions on all available evidence, not on a narrow signal that is convenient to check. Do not shortcut grading on an empty or trivial final response text when other signals (e.g. a trace summary showing an actual tool call, side...promptfoo/promptfoo6 discussions
- improve code readabilityStructure code to maximize readability and reduce cognitive load through proper formatting and control flow patterns. This includes breaking long function signatures across multiple lines, using early returns to reduce nesting levels, and extracting complex boolean expressions into well-named functions.prometheus/prometheus6 discussions
- avoid subjective languageAvoid subjective terms, unexplained jargon, and assumptions about user knowledge in documentation. Replace subjective language like "obvious" with descriptive explanations, define technical terms that may not be familiar to all readers, and break down compact technical descriptions into more accessible language.prometheus/prometheus6 discussions
- Manage output streams carefullyAlways consider the destination and lifecycle of output streams to prevent protocol interference, data loss, and unexpected behavior. Choose stdout for application output and stderr for debugging/logging. Avoid accidentally closing streams and be mindful of output pollution in protocol-sensitive contexts.prisma/prisma6 discussions
- Verify optional chaining necessityAnalyze whether optional chaining (`?.`) is actually needed based on the surrounding context and prior validations. Remove optional chaining when values are already confirmed to be truthy through previous checks, but add it when there's genuine risk of null/undefined access.prettier/prettier6 discussions
- prefer efficient algorithmsChoose more efficient algorithmic approaches by leveraging built-in methods and APIs instead of implementing manual solutions. This includes using iterator methods over manual loops, direct comparisons over complex operations, and existing path traversal APIs over custom implementations.prettier/prettier6 discussions
- Documentation clarity standardsEnsure documentation is clear, precise, and technically accurate to prevent confusion and build errors. This includes proper escaping of special characters, consistent terminology, version-specific accuracy, and unambiguous language.prettier/prettier6 discussions
- consistent spacing patternsMaintain consistent spacing patterns around operators, keywords, and interpolation syntax throughout the codebase. This improves readability and reduces cognitive load when scanning code.prettier/prettier6 discussions
- Cache invalidation consistencyEnsure comprehensive and consistent cache invalidation patterns across all models that affect cached data. Every model that can impact cached content must have proper invalidation signals, and cache keys should be designed to enable targeted busting without affecting unrelated data.PostHog/posthog6 discussions
- Optimize memory allocation patternsMinimize memory allocations and optimize allocation patterns to improve performance. Key practices: 1. Pre-allocate collections with known sizes 2. Avoid unnecessary intermediate allocationspola-rs/polars6 discussions
- Names reveal clear intentChoose names that clearly communicate intent and context, avoiding ambiguity or confusion. Variable and function names should be self-documenting and reflect their domain purpose.pola-rs/polars6 discussions
- Explicit null handlingAlways be explicit and consistent about how null values are handled in operations and documentation. This clarity prevents confusion and ensures predictable behavior across the codebase.pola-rs/polars6 discussions
- Clear actionable error messagesError messages should be user-friendly, readable, and provide actionable guidance for resolution. Avoid exposing technical implementation details like raw dictionaries, regex patterns, or internal data structures to end users. Instead, format errors clearly and include specific steps users can take to resolve the issue.python-poetry/poetry6 discussions
- proxy configuration precedenceEnsure proxy configuration follows proper precedence hierarchy and handles different proxy types correctly. User-specified proxy settings should always take priority over environment variables, similar to how browsers handle proxy configuration.microsoft/playwright6 discussions
- Extract repeated logicWhen you find yourself writing similar code patterns multiple times, extract them into reusable methods, constants, or leverage existing helpers. This improves maintainability and reduces the chance of inconsistencies.microsoft/playwright6 discussions
- comprehensive test coverageEnsure tests are comprehensive and explicit to prevent regressions and gaps in coverage. Tests should cover all scenarios including edge cases, error conditions, and boundary conditions. Avoid vague assertions that could pass even when the implementation is incorrect.emcie-co/parlant6 discussions
- Structure tests thoroughlyCreate well-structured tests with thorough coverage of both expected success and error conditions. Name test cases descriptively to clearly identify their purpose, and separate test logic from test data when using table-driven tests.opentofu/opentofu6 discussions
- Safe lock patternsWhen implementing concurrent operations, ensure locks are acquired and released properly in all execution paths. Always use patterns that guarantee lock release, and document lock acquisition order to prevent deadlocks.opentofu/opentofu6 discussions
- Reduce code nestingMinimize nesting levels and complexity in your code to improve readability and maintainability. Use early returns instead of deeply nested conditions, and restructure switch statements to reduce complexity.opentofu/opentofu6 discussions
- Write purposeful commentsComments should explain "why" and "how" rather than restating what is already obvious from the code. Focus on providing additional context, usage examples, or explanations that would help other developers understand the intent and proper usage of the code.open-telemetry/opentelemetry-python6 discussions
- Sanitize observability data exportsWhen exporting observability data (metrics, traces, logs) to external systems, properly sanitize all data fields to ensure compatibility and consistency. Key requirements:open-telemetry/opentelemetry-python6 discussions
- Use OpenCV error mechanismsAlways use OpenCV's built-in error handling mechanisms instead of C++ exceptions or custom error handling. This ensures consistent error handling across the codebase and proper integration with OpenCV's error handling infrastructure.opencv/opencv6 discussions
- Prevent null vulnerabilitiesUse container classes and smart pointers instead of manual memory allocation to prevent null pointer dereferences and memory leaks. **Instead of raw memory allocation:**opencv/opencv6 discussions
- Cross-platform API design rulesDesign public APIs to work seamlessly across different programming languages and platforms. Follow these key principles: 1. Use platform-agnostic types in public interfaces:opencv/opencv6 discussions
- Clear API contractsDesign APIs with clear contracts that behave exactly as their names and signatures suggest. Functions should do precisely what they claim to do without surprising side effects or hidden behaviors.opencv/opencv6 discussions
- Behavior-First Pytest TestingWrite tests that are pytest-native, high-signal, and behavior-focused. Apply these rules: - Prefer observable behavior over internal plumbing: assert what the client uses during the request lifecycle (e.g., what headers are present when a request is made or when `auth_headers` is accessed), not just that a helper method mutates a field.openai/openai-python6 discussions
- Null-Safe Validation StandardAlways validate `null`/`undefined` (and malformed shapes) before dereferencing, filtering, or merging—treat `null` as an explicit, documented input rather than “missing”.diegosouzapw/OmniRoute6 discussions
- Lifecycle-aligned CancellationWhen handling concurrent async work (streaming, tees, semaphores/limits, watchdogs), ensure cancellation, timeouts, and accounting are tied to the *actual* consumer lifecycle—release/decrement/teardown at the point where the work is truly finished, and don’t block on cancellation promises that can’t resolve until another branch drains.diegosouzapw/OmniRoute6 discussions
- Optimize with standard libraryWhen implementing algorithms, prefer using Go's standard library over custom implementations or external dependencies for common operations. The standard library offers well-tested, efficient implementations for many algorithmic needs.ollama/ollama6 discussions
- Verify schema changes empiricallyTreat every index, upsert, or trigger change as unproven until you show, with evidence, that it does what it's meant to. For a new index, run EXPLAIN QUERY PLAN against the query it's supposed to help and confirm the planner actually picks it — an index SQLite never selects (e.g. a composite like `idx_edges_type_source_target` superseded by a UNIQUE...can1357/oh-my-pi6 discussions
- Cross-process locking disciplineWhen mutating shared on-disk state that other processes or threads may touch concurrently (worktree registrations, refs, config files), always serialize the check-then-act sequence behind an explicit, cross-process lock, and never let cleanup code interfere with another holder's in-progress work.can1357/oh-my-pi6 discussions
- Use nullable for optionalsWhen a property or parameter represents an optional value that might be absent in requests or responses, use nullable types rather than non-nullable types with default values. This clearly distinguishes between "not set" and an explicit value, prevents sending unintended defaults in API requests, and properly handles missing values in API responses.octokit/octokit.net6 discussions
- validate configuration valuesAlways validate configuration values at runtime and provide clear, actionable error messages when invalid combinations are detected. This prevents runtime failures and guides users toward correct configuration.nrwl/nx6 discussions
- Use explicit, consistent namesVariable and parameter names should be explicit about their purpose and consistent with established naming patterns in the codebase. Avoid ambiguous or generic names that could be confusing in context.nrwl/nx6 discussions
- scope CI access tokensConfigure CI pipelines to use appropriately scoped access tokens based on branch protection status. Use read-write tokens only for protected branches (branches that don't allow direct push) and read-only tokens for all other branches and environments.nrwl/nx6 discussions
- Document CI configuration clearlyAlways include file path comments in CI configuration code blocks and use officially recommended setup actions for CI tools. This improves documentation clarity and ensures reliable CI pipeline configuration.nrwl/nx6 discussions
- Use descriptive namesChoose variable, function, and file names that clearly describe their purpose, behavior, and content. Names should be self-documenting and avoid ambiguity about what they represent or do.nuxt/nuxt6 discussions
- explicit API designDesign APIs with explicit parameters, consistent return types, and clear interfaces to improve usability and maintainability. Avoid boolean flags in favor of option objects, ensure consistent return types across all code paths, and use proper TypeScript overloads for type safety.nuxt/nuxt6 discussions
- Configuration method selectionChoose the appropriate configuration method based on when values are needed and whether they can change at runtime. Use `runtimeConfig` for values that need to be set via environment variables after build (especially secrets), `app.config` for public build-time configuration that won't change, and `process.env` only in server contexts when outside the Nuxt...nuxt/nuxt6 discussions
- Use semantic naming patternsEstablish consistent naming conventions that preserve semantic meaning and follow established patterns. Use descriptive names that clearly indicate purpose and type.novuhq/novu6 discussions
- Extract reusable componentsEliminate code duplication by extracting common functionality into shared utilities, constants, and base classes. When you notice repeated code patterns, logic, or constants across multiple files, consolidate them into reusable components.novuhq/novu6 discussions
- Prefer clarity over clevernessWrite code that prioritizes readability and maintainability over cleverness or excessive optimization. Avoid overly clever techniques that might confuse other developers or make the code harder to maintain.nodejs/node6 discussions
- Handling Dynamic Content in Next.js ComponentsWhen implementing Next.js components that rely on dynamic content (e.g. random values, current time), it is crucial to use proper boundary handling to avoid hydration errors and performance issues.vercel/next.js6 discussions
- Provider-specific AI handlingImplement provider-specific logic when integrating different AI services, as each provider has unique requirements for message formatting, API endpoints, validation rules, and optimization strategies.ChatGPTNextWeb/NextChat6 discussions
- Use null validation utilitiesConsistently use utility methods like `ObjectUtil.checkNotNull()` or `Objects.requireNonNull()` to validate that parameters are not null. When assigning parameters to instance variables, combine the null check with the assignment for cleaner, more maintainable code:netty/netty6 discussions
- Memory ordering needs barriersEnsure proper memory ordering in concurrent code by using appropriate memory barriers and atomic operations based on the access pattern. When implementing release-store semantics, place the store fence before the actual store to prevent instruction reordering:netty/netty6 discussions
- Structure behavior-driven tests properlyOrganize tests using behavior-driven development (BDD) patterns to improve clarity and maintainability. Group related tests using descriptive `describe` blocks for methods/scenarios, and write clear test cases that focus on testing behavior rather than implementation details.nestjs/nest6 discussions
- Follow protocol standardsWhen implementing networking features, strictly adhere to protocol specifications and standards to ensure proper interoperability. This applies to HTTP headers, status codes, and protocol-specific connection handling.nestjs/nest6 discussions
- prioritize code readabilityWrite code that prioritizes readability and clarity over brevity. Use proper formatting, clear expressions, and consistent patterns to make code easier to understand and maintain.neovim/neovim6 discussions
- Follow established API patternsAPIs should follow documented conventions and established patterns within the codebase to ensure consistency and predictability. This includes adhering to naming conventions, parameter structures, and interface designs that users already expect.neovim/neovim6 discussions
- Documentation accuracy standardsEnsure all function documentation accurately reflects the actual code behavior and includes complete, properly formatted descriptions of parameters and return values.neovim/neovim6 discussions
- Optimize cargo dependenciesMaintain clean and efficient dependency configurations in Cargo.toml files by following these practices: 1. **Use workspace inheritance** when available for common settings and dependencies:neondatabase/neon6 discussions
- Minimize unnecessary allocationsAvoid allocations and cloning when they don't provide sufficient benefit relative to their performance cost. Balance optimization efforts against code readability, especially in rarely executed paths. Specifically:neondatabase/neon6 discussions
- Log level appropriatelySelect the appropriate log level based on operational significance and ensure messages are clear, accurate, and formatted for human readability: 1. **ERROR**: Use for failures requiring immediate attentionneondatabase/neon6 discussions
- Keep files focused smallMaintain code organization by keeping files focused on a single responsibility and splitting large files into smaller, well-organized modules. This improves code navigation, readability, and maintainability.neondatabase/neon6 discussions
- Header hygiene rulesKeep headers “composition-safe” and minimal. Apply these rules: - **Do not define non-inline function implementations in headers.** Put the implementation in a `.cpp` file to avoid multiple-definition/linker problems.Tencent/ncnn6 discussions
- Graceful Error PropagationWhen writing library code, never hard-terminate or silently ignore failures. Always (1) validate inputs/shape compatibility correctly (including pack/elempack and dynamic dims), (2) signal errors with consistent return codes, and (3) propagate error statuses from lower-level operations to the caller.Tencent/ncnn6 discussions
- Conditional CMake ConfigurationWhen changing build configuration (compiler definitions, link libraries, compile/link flags), ensure it is applied only when the correct *feature option* is enabled and the *selected target/toolchain* actually requires it. Avoid unconditional/global flags that can break other platforms or remove the ability to disable features.Tencent/ncnn6 discussions
- Capability-Guarded ConfigurationWhen code depends on environment/build features (SIMD/FP16 availability, OpenCV versioned APIs, packing layout support, OS/ABI-specific macros), you must (1) gate the code at compile time with the correct macros and (2) reflect the real capability in the backend’s `support_*` flags so the framework won’t select an unsupported execution path.Tencent/ncnn6 discussions
- Standardize LLM interface parametersMaintain consistent parameter names and interface patterns across LLM implementations to improve maintainability and prevent integration issues. This includes:n8n-io/n8n6 discussions
- Sanitize all dynamic contentAlways sanitize dynamic content before rendering to prevent XSS and injection attacks. This includes HTML content, CSS styles, and executable scripts. Use appropriate sanitization methods based on content type:n8n-io/n8n6 discussions
- Never swallow errors silentlyAlways handle errors explicitly and preserve their context. Never silently catch and discard errors as this hides bugs and makes debugging difficult. When re-throwing errors, include the original error as the cause to maintain the stack trace. In UI components, convert errors to user-friendly messages while logging technical details at appropriate levels.n8n-io/n8n6 discussions
- Optimize iteration patternsWhen iterating through collections, choose the most efficient iteration pattern based on what information you actually need. If you only need the elements without using their indices, use direct iteration instead of enumerate:apache/mxnet6 discussions
- Use descriptive namesChoose names that clearly communicate intent and purpose, avoiding vague or misleading terms. Names should be self-documenting and accurately reflect what the variable, function, or type represents.rocicorp/mono6 discussions
- explicit null handlingUse explicit null and undefined checks with assertions to validate assumptions and maintain type safety. Prefer `!= null` for checking both null and undefined, and use assertions to validate non-null expectations rather than relying on implicit checks.rocicorp/mono6 discussions
- Environment variable patternsUse consistent patterns for environment variable handling and configuration validation. Access environment variables directly where they're needed rather than loading them unnecessarily in build configurations. Provide clear fallback mechanisms and fail fast with descriptive error messages when required configuration is missing or invalid.rocicorp/mono6 discussions
- Use supported documentation formatsWhen updating documentation, examples, or config-related code: 1) Follow the source of truth for generated artifacts - **Do** change the upstream schema/config file.mermaid-js/mermaid6 discussions
- Intentional Version PinningWhen managing configuration via `package.json`/`tsconfig.json`, treat version and target specifiers as compatibility controls—not defaults. Choose constraints based on the dependency/toolchain’s real compatibility behavior, and wire compatibility between packages explicitly.mermaid-js/mermaid6 discussions
- Deterministic Testing PracticesIntegration/e2e tests should be deterministic and directly tied to specified behavior. Apply these rules: 1) Avoid time-based waits. Wait for an observable condition (DOM element present, network idle, event emitted, SVG rendered) instead of `cy.wait(500)`.mermaid-js/mermaid6 discussions
- Region configuration consistencyEnsure configuration-dependent behavior (region/profile) is applied consistently from resolution through client creation through every API call. Rules:awslabs/mcp6 discussions
- LLM Interface ContractsWhen exposing APIs/tools to an LLM, treat docstrings, parameter semantics, and output size as an interface contract: make it unambiguous, match callable tool names exactly, structure “what to do” for reliable parsing, and cap context/token growth.awslabs/mcp6 discussions
- Enforce Resource CapsFor MCP/agent tools, aggressively bound both *inputs* and *outputs* and always clean up on timeout/eviction. This prevents runaway memory, long-held locks, LLM context blow-ups, and leaked connections / consumed service concurrency.awslabs/mcp6 discussions
- Credential-Aware CachingWhen caching heavyweight clients or connections, treat authentication identity (tokens/secret_arn/derived ARN) as part of cache correctness—not just cache performance.awslabs/mcp6 discussions
- Use theme utilities consistentlyAlways use theme utilities for consistent styling across the application instead of hard-coded values. Replace direct pixel values with theme functions like `theme.spacing()` for spacing, and access theme variables directly with `theme.vars.*` for theme-aware styling:mui/material-ui6 discussions
- Meaningful and consistent namesUse descriptive, accurate identifiers that follow established conventions and maintain consistency throughout your codebase. Variables, parameters, and properties should clearly indicate their purpose and content.mui/material-ui6 discussions
- Extract complex logicBreak down complex methods into smaller, well-named private methods to improve readability and maintainability. When a method contains multiple responsibilities, nested conditionals, or complex logic blocks, extract these into descriptive private methods.mastodon/mastodon6 discussions
- Handle errors by severityChoose error handling mechanisms based on error severity and recoverability: 1. Use throws for unrecoverable errors that prevent system operation: ```cppmaplibre/maplibre-native6 discussions
- Consistent API practicesMaintain consistency in API design, documentation, and implementation across all supported platforms to improve developer experience and reduce friction.maplibre/maplibre-native6 discussions
- Add explanatory documentationAdd docstrings to functions and comments to explain complex logic, especially when the purpose or reasoning isn't immediately clear from the code itself. This includes documenting function parameters, explaining non-obvious conditions, and clarifying implementation decisions or workarounds.logseq/logseq6 discussions
- consistent naming patternsMaintain consistent naming conventions within related groups of identifiers. When naming related variables, functions, or constants, use the same naming pattern and style to improve code readability and maintainability.lobehub/lobe-chat6 discussions
- Provide contextual code documentationCode should include documentation that explains the purpose, rationale, and context behind implementation decisions, not just what the code does. This helps future maintainers understand the reasoning and makes the codebase more maintainable.llvm/llvm-project6 discussions
- Follow naming conventionsMaintain consistency with established naming patterns and conventions throughout the codebase. This includes matching enum names with their value prefixes, following existing API naming patterns, using consistent variable naming within similar contexts, and applying appropriate prefixes to avoid naming conflicts.ggml-org/llama.cpp6 discussions
- explicit control flow logicUse explicit control flow structures like switch statements instead of complex boolean logic or implicit reasoning when handling algorithmic decisions. This improves code clarity, maintainability, and reduces the likelihood of logical errors in computational paths.ggml-org/llama.cpp6 discussions
- Use proper logging mechanismsAlways use the logging library instead of print statements and maintain consistent logging patterns throughout the codebase. Print statements should be avoided as they bypass proper log level controls, formatting, and routing. Instead, use appropriate logging methods like `verbose_logger.info()`, `verbose_logger.debug()`, or `verbose_logger.warning()`.BerriAI/litellm6 discussions
- Sanitize Untrusted BoundariesTreat every externally sourced value (API results, URLs, cached artifacts, filesystem-derived error strings, CLI/config inputs) as untrusted at the boundary, and apply **context-specific hardening** before it can be rendered, logged, persisted, or used in a subprocess.mvanhorn/last30days-skill6 discussions
- Non-brittle Contract TestsWhen writing tests, assert the real behavioral contract (the thing that could regress), not incidental formatting or brittle implementation details. Practical rules:mvanhorn/last30days-skill6 discussions
- Distinguish Unknown ValuesWhen data fields can be missing, placeholder, or truly empty, never collapse them into the same falsy value. Explicitly represent and branch on “unknown vs empty” (or verified vs unverified), and avoid `if x:` checks that treat `0`/`""`/`None` equivalently.mvanhorn/last30days-skill6 discussions
- Deterministic Failure SemanticsTreat error handling as deterministic control flow: classify outcomes precisely, set gating flags/budgets before the expensive/remote work, and use those classifications to decide whether to fall back/retry.mvanhorn/last30days-skill6 discussions
- Preserve error handling contextAlways preserve error context by using specific error types, safe error handling patterns, and meaningful error messages. This helps with debugging and maintains a clear error handling chain.langfuse/langfuse6 discussions
- Maintain naming consistencyUse consistent and descriptive names for variables, components, and functions throughout the codebase. When the same concept appears in multiple places, use identical naming to prevent confusion and bugs. This includes:langfuse/langfuse6 discussions
- Hook and state correctnessEnsure React hooks and state updates follow best practices to prevent subtle bugs: 1. **Call hooks unconditionally** at the top level of your component or custom hook - never inside conditionals, loops, or nested functions:langfuse/langfuse6 discussions
- Environment variable documentationEnsure comprehensive and accurate documentation of environment variables, including cross-references, auto-detection behavior, and deployment context. When documenting configuration options, always provide links to the environment variables page and specify the exact variable name. Include information about auto-detected variables that Langflow recognizes...langflow-ai/langflow6 discussions
- Prefer nullish coalescingWhen handling null or undefined values, use modern JavaScript patterns to write more robust and maintainable code: 1. Use the nullish coalescing operator (`??`) instead of logical OR (`||`) for defaults:langchain-ai/langchainjs6 discussions
- Streaming network safetyWhen adding or modifying network transports/proxies/stream multiplexing (HTTP RoundTripper, SPDY↔websocket translators, port-forward websockets), treat it as a lifecycle + overload problem:kUbernetes/kUbernetes6 discussions
- Propagate Errors ReliablyWhen implementing error-prone control flow (cleanup helpers, retries/polls, orchestration, allocation paths), do not hide failures. **Coding standard**kUbernetes/kUbernetes6 discussions
- Optimize Hot PathsWhen a change affects a scheduler/kubelet hot path, avoid quadratic or repeated work: do expensive filtering/KeepOnly/sorting only in the specific variant that needs it, and precompute indexes/sorted structures once outside inner loops. If the faster algorithm depends on input sizes, make iteration strategy adaptive to prevent worst-case slowdowns, and...kUbernetes/kUbernetes6 discussions
- Null-safe initialization and validationWhen dealing with optional fields, feature-gated behavior, or value-or-valueFrom unions, nil safety must be structural—not dependent on caller ordering or duplicated guards.kUbernetes/kUbernetes6 discussions
- Design runtime-flexible APIsWhen extending CRI/ABI-style APIs, avoid over-specifying runtime-variant behavior and instead make contracts that are both implementable and unambiguous for clients.kUbernetes/kUbernetes6 discussions
- Prefer descriptive errorsWhen handling errors in your code, always provide detailed context in error messages to aid debugging. Use Kotlin's standard error handling functions instead of directly throwing exceptions or using non-null assertions.JetBrains/kotlin6 discussions
- Consistent Early-Exit StyleWhen updating/adding code, prioritize readability and predictable control-flow: - Use early exits (return/goto/continue) for error/invalid states to avoid deep nesting/extra indentation.Kong/kong6 discussions
- Use descriptive namesChoose names that clearly communicate purpose, type, and intent rather than generic or ambiguous identifiers. Names should be self-documenting and help other developers understand what the code does without additional context.kilo-org/kilocode6 discussions
- extract reusable utilitiesWhen you notice repeated logic or functions that could be shared across multiple files, extract them into dedicated utility files. This improves code organization, reduces duplication, and minimizes merge conflicts.kilo-org/kilocode6 discussions
- Synchronization safety patternsEnsure proper synchronization mechanisms to prevent deadlocks and race conditions in concurrent code. When designing thread-safe components, carefully consider lock ordering, avoid nested synchronization blocks that could cause deadlocks, and make mutable shared state thread-safe.apache/kafka6 discussions
- avoid unnecessary object creationMinimize object allocation in performance-critical code paths by reusing existing objects, caching expensive operations, and choosing efficient alternatives to object creation patterns.apache/kafka6 discussions
- Choose efficient data structuresSelect data structures and algorithms based on their performance characteristics and expected usage patterns. Consider the size of collections, access patterns, and computational complexity when making implementation choices.jj-vcs/jj6 discussions
- Return errors explicitlyFunctions should return errors explicitly to callers rather than terminating the program, hiding errors in boolean returns, or using implicit error handling. This allows higher-level code to make appropriate decisions about error handling, recovery, and program flow.istio/istio6 discussions
- prevent race conditionsAlways protect shared state access and ensure proper synchronization in concurrent operations to prevent race conditions. Key areas to review: 1. **Shared Data Mutation**: Never mutate shared data structures without proper synchronization. If data is accessed by multiple goroutines, use locks or create copies instead of in-place mutations.istio/istio6 discussions
- Feature flag lifecycle managementEstablish clear guidelines for feature flag creation, default values, and removal strategy based on risk assessment and user impact. **When to use feature flags:**istio/istio6 discussions
- Avoid expensive operationsIdentify and eliminate computationally expensive operations in frequently executed code paths. Common expensive operations include repeated computations, unbounded API calls, inefficient string operations, and operations that don't scale with data size.istio/istio6 discussions
- Wrap errors with contextAlways wrap errors with meaningful context using fmt.Errorf and %w verb. Include relevant identifiers (filenames, IDs, paths) in error messages to aid debugging. This helps pinpoint error sources and simplifies troubleshooting.influxdata/influxdb6 discussions
- Follow API conventionsDesign APIs following modern conventions and best practices to improve usability, maintainability, and consistency across your codebase. APIs should prioritize:influxdata/influxdb6 discussions
- Choose optimal data structuresSelect data structures based on specific access patterns and performance requirements. When both fast lookup and predictable iteration order are needed, specialized structures like IndexMap offer benefits over standard HashMap:influxdata/influxdb6 discussions
- Minimize redundant operationsOptimize application performance by preventing unnecessary renders, calculations, and network operations. Implement proper memoization strategies, lift shared operations to parent components, and batch related tasks.elie222/inbox-zero6 discussions
- Handle nulls with typesEnforce type safety by properly handling null and undefined values through TypeScript types and explicit checks. Avoid using non-null assertions (!) or type assertions (as any), and instead:elie222/inbox-zero6 discussions
- Enforce atomic database operationsReplace check-then-act patterns with atomic database operations to prevent race conditions in concurrent environments. Use transactions for multi-step operations and leverage database-level constraints instead of application-level checks.elie222/inbox-zero6 discussions
- Dynamic configuration handlingWhen implementing configuration changes that need to be applied at runtime, follow these practices: 1. **Use reload mechanisms instead of immediate handling**: Don't process configuration changes directly in dispatch functions. Instead, trigger reloads through proper channels.hyprwm/Hyprland6 discussions
- consistent naming conventionsFollow the project's established naming conventions consistently across all code. Use camelCase for variables, functions, and parameters, avoiding Hungarian notation and snake_case. Apply type-specific prefixes: classes should have a 'C' prefix (e.g., `CXCBConnection`), enums should have an 'e' prefix (e.g., `eAutoDirs`), and enum values should be in CAPS...hyprwm/Hyprland6 discussions
- Synchronize environment configurationsWhen making configuration changes, ensure all relevant environment files are updated consistently to prevent environment-specific inconsistencies and deployment issues.juspay/hyperswitch6 discussions
- Avoid hardcoded configuration valuesConfiguration values should not be hardcoded in the source code. Instead, they should be externalized to configuration files, environment variables, or made configurable through application settings. This improves maintainability, allows for environment-specific customization, and prevents deployment issues.juspay/hyperswitch6 discussions
- Precise Matching RulesWhen implementing parsing/classification logic, treat the input grammar as a contract: (1) constrain pattern matches to the intended envelope/boundaries/character sets (avoid prefix/superset regexes and overly broad Unicode ranges), (2) ensure every computed signal/metric is actually used in the final decision, and (3) add targeted regression tests for each...nousresearch/hermes-agent6 discussions
- Generation-guarded async side effectsWhen async work can overlap (navigation changes, optimistic updates, multiple handler invocations, or speech interruption), treat post-`await` mutations as conditional on the original intent. Capture (1) the state/identity you’re operating on and (2) a monotonically increasing generation/token before any `await` or long-running step. Only apply...nousresearch/hermes-agent6 discussions
- Config.yaml First PolicyBehavioral configuration must be owned by `config.yaml` (and documented), while environment variables must be limited to secrets or internal backward-compatibility bridges. Also ensure any filesystem default paths are profile-safe via `get_hermes_home()`.nousresearch/hermes-agent6 discussions
- preserve dtype and shapesWhen writing PyTorch code, preserve tensor dtypes and devices and be explicit about vector/matrix shapes to avoid precision loss, incorrect broadcasting, and unnecessary CPU allocations.p-e-w/heretic6 discussions
- Concurrency bookkeeping and cancelWhen concurrency involves async tasks, cross-thread messaging, or callbacks from other components, prefer *explicit bookkeeping* and *bounded, non-blocking communication* so correctness doesn’t rely on timing.ogulcancelik/herdr6 discussions
- prefer let-else patternsWhen handling Option types that require early returns on None values, prefer the let-else pattern over verbose match statements or if-let constructs. This pattern improves code readability, reduces nesting, and makes the control flow more explicit.helix-editor/helix6 discussions
- Consistent descriptive naming conventionsUse consistent and descriptive naming conventions across the codebase: 1. Use kebab-case for configuration options and snake_case for internal modifiershelix-editor/helix6 discussions
- Explicit error propagationFavor explicit, typed error propagation over implicit or silent failure handling. Concretely: - Use `Result<T, E>` (or similar) return types to surface success/failure instead of throwing just to catch it a few lines later. For example, instead of:Helicone/helicone6 discussions
- Enforce organization-scoped authorizationEvery endpoint, manager method, or database query that reads or mutates tenant data must explicitly verify and scope access to the authenticated user's organization — never rely solely on a client-supplied ID (e.g., a record's `id`) to locate a resource. Add `organization_id`/`organizationId` filters to every SELECT, UPDATE, and DELETE, and pass identifiers...Helicone/helicone6 discussions
- Explicit null validationAlways validate objects for null/nil before accessing their properties, and establish consistent patterns for handling null values throughout the codebase. This prevents nil pointer dereferences and ensures predictable behavior.grafana/grafana6 discussions
- Descriptive semantic namesAlways use descriptive variable, parameter, function, and constant names that clearly convey their purpose and behavior. Avoid single-letter variables or abbreviations except in well-established contexts like loop counters.grafana/grafana6 discussions
- Use descriptive identifiersReplace generic, ambiguous, or magic identifiers with descriptive, specific names that clearly communicate intent and avoid confusion. Key principles:block/goose6 discussions
- Unified configuration semanticsCoding standard: Centralize configuration/credential semantics and never “re-derive” them in multiple places. Read from the real sources (env/config and provider-specific runtime credential caches), preserve provider identity during legacy interop, and let canonical normalizers own final resolution.aaif-goose/goose6 discussions
- Normalize Missing ValuesWhen handling optional/missing inputs, **normalize and guard early** so “missing” can’t accidentally become a real value or clobber existing state. Rules:aaif-goose/goose6 discussions
- Fail Safe Input HandlingWhen processing security-relevant external inputs (URIs/hosts, file paths/content, auth tokens, and tool-call metadata), validate and constrain early, then ensure failure modes are non-recoverable in ways that could cause retries or duplicate effects.aaif-goose/goose6 discussions
- avoid panics and expectsReplace panic-inducing operations like `.expect()` and `.unwrap()` with proper error handling that allows graceful recovery or controlled failure. Panics can crash entire applications and provide poor user experience, especially in server environments where "it will kill goosed and it is all over."block/goose6 discussions
- avoid environment variable proliferationPrefer the consolidated config system over adding new environment variables. Environment variables should only be used for deployment-specific overrides, not as the primary configuration mechanism.block/goose6 discussions
- AI model configuration consistencyMaintain consistent AI model metadata and configuration across all providers to prevent breaking changes and ensure reliable behavior. When adding new models or updating existing ones, always update corresponding token limits, default configurations, and provider mappings simultaneously.block/goose6 discussions
- Use proper network constantsWhen writing network-related code, always use named constants from system packages instead of magic numbers, and ensure complete protocol implementation. This includes using proper constants for network operations (like `windows.IfOperStatusUp` instead of `0x01`), calculating buffer sizes correctly with system functions (like `syscall.CmsgSpace(4)` for file...golang/go6 discussions
- Document code behaviorDocument the "why" and "how" of your code, not just what it does. Add clear comments to explain: 1. Non-obvious behaviors and edge cases 2. Special input handling and transformationsgin-gonic/gin6 discussions
- Robust SSH integrationWhen implementing SSH integration in your application, follow these practices to ensure reliability across different systems: 1. **Preserve user context**: Include user information in SSH target identification, as many operations (like terminfo installation) write to user-specific directories.ghostty-org/ghostty6 discussions
- Document configs comprehensivelyConfiguration options must be documented comprehensively with: 1. Clear, descriptive name using appropriate platform prefixes (e.g., 'gtk-' for GTK-specific options)ghostty-org/ghostty6 discussions
- Use semantic namingChoose names that clearly communicate the purpose, behavior, and intent of variables, methods, classes, and interfaces. Avoid ambiguous or misleading names that require additional context to understand.google-gemini/gemini-cli6 discussions
- Secure input validationAlways validate and sanitize user inputs, especially when constructing commands or file paths. Use established security libraries instead of implementing custom parsing logic, and implement proper validation that prevents attacks while avoiding false positives.google-gemini/gemini-cli6 discussions
- Ensure comprehensive user documentationAll user-facing features, APIs, and tools must have clear, comprehensive documentation that explains their purpose, limitations, and usage. Documentation should use terminology that users can understand, provide helpful guidance for common scenarios, and include warnings about potential issues.google-gemini/gemini-cli6 discussions
- Organize code logicallyMaintain a clean and logical code structure by properly organizing code according to its functionality and purpose: 1. Group related functionality into dedicated packages based on domain logic (e.g., `pkg/ssh` for SSH-related code)fatedier/frp6 discussions
- Prefer clear, semantic codeWrite code that’s easy to read and matches intent (mutability, string composition, UI semantics), and remove obvious clutter. Apply these rules: 1) Avoid reassignable variablesfreeCodeCamp/freeCodeCamp6 discussions
- Name indicates clear purposeNames should clearly indicate their purpose, type, and behavior. This applies to methods, variables, and parameters. Choose names that are self-documenting and unambiguous.laravel/framework6 discussions
- Cache expensive operationsIdentify and cache results of expensive operations that may be called repeatedly during a request lifecycle, especially recursive functions or operations performed in loops. This reduces redundant processing and can significantly improve application performance.laravel/framework6 discussions
- Extract methods for clarityBreak down large methods and extract repeated code patterns into smaller, focused methods or getters to improve readability and maintainability. When you encounter large conditional blocks, complex logic, or repeated patterns, consider extracting them into well-named private methods or getters. This makes the code easier to understand, test, and modify.flutter/flutter6 discussions
- explicit null validationAlways validate null values explicitly rather than using silent fallbacks or implicit handling. When null values are unexpected or could cause issues, use assertions or explicit checks to fail fast and provide clear error messages.flutter/flutter6 discussions
- Algorithm precision handlingChoose algorithms that handle edge cases and mathematical precision correctly to avoid subtle bugs and unexpected behavior. When implementing algorithms, prioritize mathematical soundness and robust edge case handling over apparent simplicity. Use established mathematical formulas and precise operations rather than approximations that may fail in corner...flutter/flutter6 discussions
- PEP8-compliant, semantically accurate namingAll identifiers (functions, variables, parameters, methods) must follow PEP8 casing rules and clearly reflect what they actually represent or do. Specifically:pallets/flask6 discussions
- Backward-compatible API designWhen adding or changing public API surface, favor explicit, well-documented parameters over hidden `**kwargs` popping, and evolve signatures in a way that keeps existing behavior working.pallets/flask6 discussions
- prefer existing APIsWhen adding new functionality, prioritize reusing existing methods and interfaces rather than creating new ones. This maintains API consistency, reduces cognitive load for developers, and prevents unnecessary duplication.gofiber/fiber6 discussions
- Extract duplicate logicWhen code blocks become large or contain repetitive patterns, extract them into separate functions to improve readability and maintainability. This follows Clean Code principles of keeping functions short and focused on single responsibilities.gofiber/fiber6 discussions
- Consistent test code styleMaintain consistent and clear testing patterns by following these guidelines: use strict equality assertions, prefer variable reassignment over block scoping for multiple sequential requests, and maintain consistent formatting to improve code readability and reduce unnecessary indentation.fastify/fastify6 discussions
- Concurrent operations completion managementWhen running concurrent operations in tests, ensure all operations complete before concluding the test. Race conditions occur when your test calls done() or resolves before all async operations finish, leading to flaky tests or missed assertions.fastify/fastify6 discussions
- Semantic, consistent namingChoose names that clearly convey a variable's, function's, or module's purpose, type, and visibility, and keep that meaning consistent everywhere it's used. Follow established architectural naming patterns (e.g., name a use-case class `NotesService` rather than `NotesUseCase` if the codebase follows Controller-Service-Repository conventions). When requiring...Expressjs/Express6 discussions
- RFC-compliant protocol handlingWhen implementing HTTP-related features—header generation/parsing, charset declarations, content negotiation, or IP address comparisons—validate behavior against the governing RFC/IANA specification rather than relying on assumptions or ad-hoc string checks. Common pitfalls include: using an internal encoding alias (e.g. Node's `utf8`) instead of the...expressjs/Express6 discussions
- RFC-compliant HTTP semanticsWhen implementing HTTP-level behavior—headers, charsets, content negotiation—always conform to the governing RFC rather than relying on internal Node.js conventions or convenience logic that silently changes existing semantics.Expressjs/Express6 discussions
- Pin actions to commit SHAAll third-party GitHub Actions referenced in workflows must be pinned to a full commit SHA rather than a mutable tag or branch, since tags can be rewritten and this breaks the immutability/security guarantees required for supply-chain integrity (this is also an OSSF Scorecard requirement). Always include a trailing comment with the human-readable version...Expressjs/Express6 discussions
- Ensure comprehensive test coverageAlways verify that tests cover all relevant scenarios, edge cases, and conditions rather than just the happy path. When reviewing or writing tests, actively look for missing test cases and suggest additional coverage.electron/electron6 discussions
- avoid redundant operationsIdentify and eliminate unnecessary duplicate operations, redundant function calls, and repeated computations that can impact performance. Common patterns include: avoiding redundant parameter retrieval when values are already available, preventing duplicate map lookups by caching results, checking for changes before performing expensive operations, and...electron/electron6 discussions
- Use configuration access methodsWhen accessing configuration settings, always use the appropriate type-safe accessor methods provided by the configuration framework rather than manual string parsing. This improves code readability, maintainability, and reduces potential bugs from string parsing errors.elastic/elasticsearch6 discussions
- Robust test assertionsUse precise, informative assertions in tests to provide clear feedback when tests fail and verify the correct behavior rather than implementation details.elastic/elasticsearch6 discussions
- Prefer callbacks over blockingAlways structure concurrent code to use asynchronous callbacks instead of blocking operations. Blocking calls like CountDownLatch, Thread.join(), or Future.get() can lead to thread starvation, reduced throughput, and complex deadlock scenarios.elastic/elasticsearch6 discussions
- Measure before optimizing performanceBefore implementing performance optimizations, measure and validate the impact through benchmarks. This applies especially to: 1. Changes affecting common operations (string conversions, collections)elastic/elasticsearch6 discussions
- maintain codebase consistencyEnsure new code follows established patterns, conventions, and standards already present in the codebase. This includes adhering to parameter ordering conventions, maintaining existing code patterns, using consistent header formatting, and reusing existing utilities rather than creating duplicates.duckdb/duckdb6 discussions
- explicit null state managementMake null state checks explicit and comprehensive rather than using implicit return values or redundant fields. Use dedicated methods like `ContainsNull()` to clearly indicate null state, avoid duplicate null tracking when child objects already maintain null state, and ensure hierarchical null checks cover all levels (self and children).duckdb/duckdb6 discussions
- Explicit CI configurationsCI/CD workflows should use explicit, named configurations rather than wildcards, globs, or implicit behaviors to improve maintainability and debuggability. This makes it easier for developers to understand failures and reduces silent errors.duckdb/duckdb6 discussions
- Optional configuration parametersMake configuration parameters optional with sensible defaults instead of requiring mandatory values, and only enable optional features when explicitly configured through environment variables or user settings.stanfordnlp/dspy6 discussions
- Null safety patternsImplement proper null safety patterns to prevent runtime errors and unexpected behavior. This includes several key practices: **1. Handle Optional types correctly:** When working with Union types containing None, extract the non-None type before type checking to avoid `issubclass()` errors with type annotations.stanfordnlp/dspy6 discussions
- implement algorithms correctlyEnsure algorithmic implementations use correct patterns, handle edge cases gracefully, and avoid silent failures. This includes using proper mathematical functions, correct object access methods, and robust error handling for each operation.stanfordnlp/dspy6 discussions
- API backward compatibilityMaintain backward compatibility when evolving API interfaces by preserving existing method signatures and parameter patterns. When adding new functionality, prefer extending existing interfaces over breaking changes, and use deprecation warnings for obsolete parameters.stanfordnlp/dspy6 discussions
- AI configuration documentationEnsure AI model configurations and related documentation use precise terminology and provide clear, complete setup instructions without overwhelming users.stanfordnlp/dspy6 discussions
- Untrusted Actions CheckoutTreat `pull_request_target` and `workflow_run` as *privileged* contexts: if you use them, you must assume any incoming PR code or artifacts are untrusted.github/docs6 discussions
- Write focused efficient testsTests should be focused, efficient and meaningful. Follow these guidelines: 1. Avoid testing implementation details or already-tested functionality 2. Use clear, direct assertions that test actual behaviordjango/django6 discussions
- Use connection by aliasWhen working with database operations in Django projects that might use multiple database backends, always access database features and operations through `connections[alias]` instead of the global `connection` object. This ensures your code works correctly regardless of which database backend is being used for a specific operation.django/django6 discussions
- Use appropriate log levelsChoose the correct logging level based on the importance and purpose of the message. Use DEBUG for debugging information that's only useful during development, INFO for general operational information, WARNING for concerning conditions that don't prevent operation, and ERROR for actual errors. Remove meaningless debug prints and consider using conditional...langgenius/dify6 discussions
- Prefer exceptions over silent failuresRaise exceptions instead of returning None, logging warnings, or silently modifying values when encountering error conditions. This makes failures explicit and forces callers to handle error cases properly, improving code reliability and debugging experience.langgenius/dify6 discussions
- Concurrent resource managementWhen implementing concurrent operations, properly manage shared resources to prevent race conditions and ensure system stability. Use database-level locking mechanisms like `SELECT ... FOR UPDATE SKIP LOCKED` to prevent concurrent access to the same data. Configure thread pools with appropriate limits and timeouts to avoid resource exhaustion. Separate...langgenius/dify6 discussions
- Valid Angular ExamplesWhen adding Angular examples (docs, snippets, templates), ensure they are both *syntactically/semantically valid* and shown in the *correct template context*.kamranahmedse/developer-roadmap6 discussions
- Accurate AI ContentWhen writing AI/LLM-related documentation or roadmap material, ensure it (a) states model limitations precisely, (b) stays in the correct scope for the node/context, and (c) explains implementations in terms of the underlying pipeline (prefer pre-trained tools) rather than framework specifics.kamranahmedse/developer-roadmap6 discussions
- organize code properlyMaintain clean code organization by separating concerns into appropriate classes and files. Extract large functions into smaller, focused methods, and avoid creating monolithic patches that become difficult to maintain.zen-browser/desktop6 discussions
- Validate and document nullsAlways handle null values explicitly and consistently throughout your codebase to prevent null pointer exceptions. Follow these guidelines: 1. **Validate nulls early** using Preconditions to provide clear error messages:deeplearning4j/deeplearning4j6 discussions
- Stable Interface ContractsWhen designing or extending APIs, treat existing “core” interface contracts as stable and enforce exact compatibility (method signature + parameter semantics + return shapes) across base classes and all implementations. If you need different inputs/behavior for a subset of modules, add an adapter/compatibility layer in the business layer instead of changing...eosphoros-ai/DB-GPT6 discussions
- Robust LLM IntegrationWhen integrating LLMs/embeddings into production code, treat the model as unreliable: enforce a stable IO contract (especially JSON), validate and safely recover from format mismatches, and route model calls through the project’s unified abstractions with configurable parameters.eosphoros-ai/DB-GPT6 discussions
- Null-Safe Data AccessWrite code so nullable/missing data can’t cause runtime errors. Apply these rules: 1) Declare nullability in types - If a parameter or field defaults to `None`, type it as `Optional[...]`.eosphoros-ai/DB-GPT6 discussions
- Use descriptive namesChoose names that clearly reveal the purpose and behavior of variables, functions, and methods. Names should be self-documenting and follow these patterns:cypress-io/cypress6 discussions
- function decomposition clarityFunctions should be focused, concise, and easy to understand. Break down large functions (>100 lines) into smaller, well-named functions that each handle a single responsibility. Remove unused parameters to reduce cognitive load and prevent confusion. Prefer functional programming patterns like `.some()`, `.map()`, and `.filter()` over imperative loops when...cypress-io/cypress6 discussions
- Consistent formatting preferencesFollow consistent formatting and syntax patterns to improve code readability and maintainability. This includes using compact formatting for test blocks, proper quote usage, positive-first conditionals, and preferred syntax patterns.cypress-io/cypress6 discussions
- Structure errors with intentImplement error handling with clear intent and proper propagation. Follow these principles: 1. Use structured try/catch blocks with specific error typescrewaiinc/crewai6 discussions
- Secure sensitive data handlingWhen implementing security-sensitive features (parsing untrusted cryptographic configs, enforcing TLS role restrictions, or maintaining a distrust/pinning list), apply defense-in-depth rather than relying on incidental implementation details:python/cpython6 discussions
- Write comprehensive test casesTests should thoroughly cover all code paths and edge cases. Each test case should: 1. Test distinct scenarios in separate test cases 2. Cover all logical branches and code pathsvuejs/core6 discussions
- Use shared string keysReplace hardcoded strings in configuration files with shared string key references to maintain consistency and enable centralized management. This practice reduces duplication, ensures uniform messaging across components, and makes updates easier to maintain.home-assistant/core6 discussions
- Use appropriate logging levelsChoose the correct logging level based on the nature and expected frequency of the event being logged. Follow these guidelines: **Use `debug` for application events:** The `info` level is reserved for system-level messages. Use `debug` for application-specific information like successful authentication, data processing steps, or operational status updates.home-assistant/core6 discussions
- Strict props event handlingEnforce strict typing and consistent handling of component props and events to ensure type safety, runtime validation, and maintainable component interfaces. Key guidelines:vuejs/core6 discussions
- Evolve APIs gracefullyWhen modifying or extending APIs, prioritize backward compatibility while providing clear migration paths for future changes. Follow these practices: vuejs/core6 discussions
- ESLint configuration alignmentEnsure your ESLint configuration matches the JavaScript language features used in your codebase to prevent false warnings and maintain consistent code quality checks. When using ES6+ features like `let`, `const`, object shorthand notation, or other modern JavaScript syntax, update your ESLint configuration to recognize these features.adonisjs/core6 discussions
- Choose semantic descriptive namesNames should be clear, descriptive and follow consistent patterns. Choose names that accurately reflect the purpose and behavior of the code element: vuejs/core6 discussions
- Avoid redundant computationsIdentify and eliminate redundant operations that cause performance bottlenecks by caching expensive function results, performing transformations only when necessary, and implementing lazy evaluation patterns.vuejs/core6 discussions
- Semantically consistent namingNames should accurately reflect their purpose and be used consistently throughout the codebase. This applies to props, function names, variables, and UI labels.continuedev/continue6 discussions
- Handle unsafe operations safelyAlways wrap potentially unsafe operations (like JSON parsing, Buffer operations, or API calls) in try-catch blocks with appropriate error handling. Ensure error messages are user-friendly and actionable.continuedev/continue6 discussions
- Extract into helper functionsBreak down complex or deeply nested code into smaller, well-named helper functions to improve readability and maintainability. Extract code into helpers when:continuedev/continue6 discussions
- Validate untrusted inputsTreat CLI args, config, and IPC payloads as untrusted. Enforce semantic invariants at the boundary, then again during decoding/parsing (defense in depth), and add targeted negative tests.apple/container6 discussions
- Stable API ContractsWhen designing or evolving API surfaces (including XPC/wire formats and CLI-to-client contracts), treat the request/response shape as a long-lived contract: keep it semantically high-level, strongly typed, and backward/forward compatible.apple/container6 discussions
- Copy-Paste Safe DocsEnsure documentation command examples and command reference sections are accurate and safe to copy/paste. Apply these rules: - Code fences: use a `bash` (or relevant shell) code fence for blocks that contain only shell commands.apple/container6 discussions
- Add logging without duplicationWhen adding logging functionality to existing code, encapsulate the logging logic within methods or use parameters to avoid code duplication and maintain clean interfaces. Add informational logging (debug/info level) to provide visibility into system operations, especially for default behaviors and skipped actions, but avoid duplicating conditional checks...docker/compose6 discussions
- Prefer built-in methodsWhen a standard language feature already does the job, use it instead of a manual or custom reimplementation — this is clearer, less error-prone, and easier to maintain. Examples observed in review:tj/commander.js6 discussions
- Consistent, backward-compatible APIWhen adding or changing public methods, properties, or events, make sure the new surface area is consistent with existing conventions and does not silently break current behavior.tj/commander.js6 discussions
- Clear, fail-fast error messagesDistinguish between programmer errors and runtime/user-facing behavior changes when deciding how to handle failures, and make error messages easy to localize and act on.tj/commander.js6 discussions
- Accurate, convention-consistent namingNames of methods, functions, and variables must precisely describe what the code actually does, and should follow the established naming conventions already used elsewhere in the codebase.tj/commander.js6 discussions
- Use descriptive namesChoose descriptive, self-documenting names for constants, functions, parameters, and types that clearly communicate their purpose and meaning. Avoid magic numbers, generic strings, and ambiguous identifiers that require additional context to understand.comfyanonymous/ComfyUI6 discussions
- Hardware compatibility patternsImplement proper hardware compatibility patterns when working with different GPU backends and AI frameworks. Many AI applications need to support multiple hardware platforms (NVIDIA CUDA, AMD ROCm, Intel XPU, Moore Threads, DirectML, ZLUDA) which have different capabilities and limitations.comfyanonymous/ComfyUI6 discussions
- Effective Auth PropagationSecurity-sensitive behavior must be correct *in the real execution boundary*: resolve the effective security configuration (including profile overrides) and then propagate/enforce it through packaged subprocesses and trust-boundary validations.openai/codex-security6 discussions
- Visibility-safe React stateWhen building React UIs that can be hidden/shown (startup screens, side panels, modals, drawers, activity shells), design for **correct state + correct side effects** across transitions.ClInE/cLiNe6 discussions
- Testing With RealismWhen adding or updating tests, prefer realistic behavior checks over brittle mocks, keep them deterministic, and assert meaningful invariants. **Guidelines**ClInE/cLiNe6 discussions
- Semantics-First Algorithm RulesWhen implementing non-trivial logic (token estimation, parsing, normalization, cap/policy decisions, diff/tree composition), first write down the exact semantics/invariants the algorithm must satisfy, then implement and test against “tricky shapes” that commonly break those semantics.Cline/Cline6 discussions
- Reliable Network RetriesWhen implementing networked features (hub dispatch, reconnect/reattach, model/catalog fetches, and local-proxy HTTP), ensure retries are safe and bounded:CLINE/cline6 discussions
- Preserve API Contract SemanticsTreat API-like boundaries (HTTP headers, REST/GraphQL payloads, event envelopes, and even cross-layer client calls) as contracts: field *names* and field *meaning* must remain consistent end-to-end, and gating/serialization rules should follow the spec.Cline/Cline6 discussions
- Prefer shared abstractionsBefore adding new logic, check whether the same behavior already exists in core/shared modules. If so, reuse it instead of duplicating (including small helpers).Cline/Cline6 discussions
- Prefer role and unionWhen adding behavior, reduce duplication and conditional sprawl by modeling variants explicitly and centralizing shared logic. **Standards** - **Use roles/interfaces for output/handlers**: Create an outputter once (e.g., `JsonRunOutputter` vs `ConsoleRunOutputter`) and call straight-line lifecycle methods, instead of repeatedly branching `if (outputMode...cline/CLINE6 discussions
- Pragmatic, contract-based testingWhen adding/updating tests, optimize for stable, cross-platform correctness and isolation: - **Assert behavior and contracts, not implementation noise.** Prefer correctness checks already exercised by existing suites over brittle assertions on internal payload shapes (e.g., exact log field structures), unless that structure is the behavior users rely on.CLINE/CLINE6 discussions
- Normalize Null And UndefinedTreat nullability as a semantic distinction, not just a type system detail. Normalize and apply explicit precedence at boundaries, preserve the difference between “omitted” and “present-but-empty”, and make TypeScript reflect runtime normalization.CLINE/CLINE6 discussions
- Model Limits CorrectnessWhen integrating LLM providers, treat model capabilities and token limits as *schema-variant inputs* and enforce conservative, well-tested limit computation.CLINE/cline6 discussions
- Guard stale async stateWhen an async operation can be superseded (new request, sign-out, selection change, hide/show), never let its late response commit state unconditionally. Use a concurrency token (generation/requestId) and validate it right before every state write.cline/CLINE6 discussions
- Guard Async State WritesWhen async work can overlap (awaits, polls, UI hide/show, user changes), never commit results blindly. Instead, make every async side-effect either (a) versioned (generation) or (b) in-flight locked—or remove the stale write path entirely.Cline/Cline6 discussions
- Guard async race conditionsAsync operations whose results feed into shared state (account data, caches, UI lists, polling) can resolve out of order, or after the context that started them is no longer valid (sign-out, switched account/runtime, cache invalidation, a newer request). Guard against this with a generation/version counter rather than relying on cancellation alone:cline/cline6 discussions
- gRPC interface consistencyEnsure gRPC/RPC interfaces follow consistent patterns for return types, error handling, and method design. Avoid creating duplicate RPC methods when existing ones can be reused, use proper gRPC clients instead of direct imports, and maintain type safety with specific parameter types rather than generic objects.cline/cline6 discussions
- Explicit cache invalidationDon't rely on a bare TTL to keep a cache correct, and never treat "the connection/process is still alive" as proof a cached value is still fresh. Whenever the underlying source can change in a way you can detect (an edited setting, an edited pin definition, a new record version from the server), invalidate or re-validate the cache entry immediately on that...cline/cline6 discussions
- Design stable, semantic contract fieldsTreat every field added to a shared interface (SDK types, request/response payloads, hook options, headers) as a long-term API commitment, and design it deliberately:cline/cline6 discussions
- Consistent Configuration ResolutionConfiguration-derived behavior must be resolved in one authoritative phase (startup or request construction) and then passed through without recomputation or semantic mutation. Divergence (different resolution rules for UI vs runtime, per-refresh re-reads, or observer code changing core inputs) causes environment mismatches, wrong URLs/remotes, and...CLINE/CLINE6 discussions
- Config precedence and reuseImplement configuration resolution with deterministic precedence and reuse resolved values instead of re-deriving them in multiple places. **Standards**ClInE/cLiNe6 discussions
- Complexity-Safe CorrectnessWhen implementing algorithmic logic (parsing, path transforms, selection/slicing, or cost/estimate functions), treat correctness and runtime bounds as first-class requirements.CLINE/CLINE6 discussions
- Check before property accessAlways verify that parent objects and properties exist before accessing nested properties or calling methods on them. Use optional chaining (`?.`) only when the parent object might genuinely be null or undefined, not as a blanket safety measure for guaranteed values. When values can be undefined, provide meaningful defaults rather than arbitrary fallbacks.cline/cline6 discussions
- Centralize Variants and LogicWhen code introduces multiple “modes” (output modes, session start vs resume, tool vs run-start context) or repeats non-trivial logic (git checks, shell detection, escaping/formatting), prefer explicit variant modeling and centralized utilities rather than duplicating logic or branching everywhere.ClInE/cLiNe6 discussions
- Behavior-First Test StandardsWhen adding/updating tests, optimize for correctness signals that match real behavior and avoid brittle scaffolding. **Guidelines** 1. **Test the real decision point, not helper internals**: If a UI outcome depends on combined state/conditions/timing, write a test that exercises the full pipeline (e.g., the hook as used) with realistic state and...Cline/Cline6 discussions
- Batch and Cap WorkFor performance-critical code, avoid unbounded or duplicated expensive work. Prefer (1) reuse of already-computed snapshots/results, (2) batching instead of per-item subprocess calls, and (3) strict size/time caps with streaming and early termination.Cline/Cline6 discussions
- Avoid redundant expensive workExpensive work (external process spawning, large downloads, clipboard round-trips, remote session hydration, heavy git queries) must not be duplicated accidentally. Prefer batching/streaming and ensure you fetch/compute once, then reuse the result for telemetry, success/failure, and downstream logic. Also ensure event listeners and background effects don’t...CLINE/CLINE6 discussions
- Async Staleness GuardingWhen async work can overlap (polling, user-triggered refreshes, sign-out, rapid UI interactions, or streaming), treat updates as *stale-capable*: only the latest (or the correct sequence) is allowed to write state/side-effects.ClInE/cLiNe6 discussions
- API Contract PreservationAlways preserve the meaning of public/API-facing inputs and fields across client/server boundaries. Apply this checklist: - Round-trip fields: if a request/event accepts a new field, ensure every projection/conversion path carries it through (avoid “write-only” fields).cline/CLINE6 discussions
- Pin dependency versionsAlways pin dependencies to exact versions in package.json instead of using semantic version ranges (^, ~) to ensure reproducible builds and prevent unintentional version drift during deployments.snyk/cli6 discussions
- Never commit secretsPrivate cryptographic keys, certificates with private keys, and other secrets must never be committed to source code repositories, even in test or spec files. This is a critical security vulnerability that could lead to unauthorized access, impersonation, or system compromise.chef/chef6 discussions
- Memoize expensive operationsCache results of expensive operations, especially shell commands and external queries, to avoid redundant executions. Use Ruby's idiomatic memoization pattern with blocks for clarity and efficiency. Only fetch data when needed, and structure code to optimize for the most common execution paths.chef/chef6 discussions
- Keep actions versions currentAlways use the latest stable versions of GitHub Actions components in CI/CD workflows to avoid deprecated features, security vulnerabilities, and compatibility issues. This includes:chef/chef6 discussions
- Externalize configuration valuesAvoid hardcoding configuration values directly in scripts, especially for values that might change between environments or contain sensitive information. Instead, use environment variables, build parameters, or secrets management systems.chef/chef6 discussions
- Choose semantic algorithmsSelect algorithms and data operations that match the semantic intent of your code rather than using convenient but potentially problematic approaches. For operations like version comparisons, string parsing, and collection filtering, choose specialized methods over generic ones.chef/chef6 discussions
- Document configuration consistentlyEnsure all configuration options are clearly documented and follow consistent naming and syntax conventions. This includes: 1. **Explicitly document prerequisites** - Clearly state all required tools, dependencies, and environment variables needed for configuration. For example, when jq is required for processing:bridgecrewio/checkov6 discussions
- Simplify code pathsFavor simple, idiomatic constructs over verbose or redundant logic. Specifically: - Avoid unnecessary conditional branches or special-casing when the same built-in method can handle all cases uniformly. For example, instead of checking `arguments.length > 1` and manually concatenating with a loop, just convert `arguments` to an array and call `.join(' ')`...chalk/chalk6 discussions
- Semantic Naming MustUse naming conventions that are both tooling-correct and behavior-semantic: - **Tooling-sensitive identifiers:** If a subsystem matches by name (e.g., test discovery), ensure the identifier follows the project’s configured pattern—otherwise tests may be skipped silently.celery/celery6 discussions
- Explicit None SemanticsWhen handling optional/nullable inputs, treat “missing” and “explicitly set to None” as different semantic states. Practical rules: - Provide safe fallbacks at the boundary: if a config/input can be `None`, use a default that keeps the value non-null.celery/celery6 discussions
- Select specific database fieldsAlways explicitly select only the database fields you actually need instead of using broad includes or fetching entire objects. This practice significantly improves query performance, reduces memory usage, and minimizes data exposure.calcom/cal.com6 discussions
- Check exceptions consistentlyAlways check for exceptions immediately after operations that might throw them, especially before using the results in control flow decisions. When accessing properties that might be used in conditionals, retrieve the property first, check for exceptions, and then use the property in the conditional.oven-sh/bun6 discussions
- Minimize unnecessary operationsOptimize performance by eliminating redundant operations and arranging code to avoid unnecessary computations, especially in frequently executed paths. Follow these principles:Homebrew/brew6 discussions
- Follow established naming patternsNames should be descriptive and consistent with existing patterns in the codebase. This applies to methods, variables, and DSL elements: 1. Follow existing naming patterns for similar concepts:Homebrew/brew6 discussions
- Clear error recovery pathsImplement error handling that provides both clear recovery paths for users and graceful degradation for the system. This includes: 1. Clear, actionable error messages that guide users to resolutionHomebrew/brew6 discussions
- Clear code examplesDocumentation should include clear, actionable code examples that users can reliably follow. Avoid using ambiguous placeholders or variables that might be misinterpreted as literal code to copy-paste. When placeholder values must be used in examples, explicitly mark them and provide clear instructions for replacement.Homebrew/brew6 discussions
- Comprehensive API documentationAlways provide comprehensive API documentation that includes accurate examples, complete parameter descriptions, and clarifications about parameter usage. This helps users understand how to properly use your API and reduces support questions.boto/boto36 discussions
- Structural config merge rulesWhen adding or modifying skill/workflow customization, treat configuration resolution as a deterministic contract with (a) exact merge semantics and (b) clear config ownership/lifecycle.bmad-code-org/bmad-method6 discussions
- Strict Input ValidationAlways validate and constrain any user-controlled or data-driven strings (IDs, slugs, CLI flags, manifest/CSV fields) before using them to build paths, filenames, or subprocess commands, and apply defense-in-depth against common classes of attacks.bmad-code-org/bmad-method6 discussions
- Normalize Generated OutputWhen generating files/metadata, make output deterministic and cross-platform by normalizing both *paths* and *text line endings*, and by keeping shared formatting rules/filters centralized.bmad-code-org/bmad-method6 discussions
- Explicit override correctnessWhen handling configuration from CLI/UI (e.g., `--set`, channel flags, migration prompts), treat user-provided values as explicit assertions that must (a) be seeded into the same data pipeline that prompts/templates use, (b) survive any schema-strict filtering only because the user asserted them, and (c) not be overwritten later by default/template/prompt...bmad-code-org/bmad-method6 discussions
- Correct Matching And ParsingWhen writing installers/transformers/validators that search, rewrite, or regenerate files, require *matching/parsing correctness*: only operate on the exact structure you intend, and avoid ambiguous substring/position matches.bmad-code-org/bmad-method6 discussions
- Semantic Naming ConsistencyAdopt naming rules that accurately reflect meaning, routing behavior, and established codebase conventions. Apply these checks when adding/changing code:maximhq/bifrost6 discussions
- Low-noise, instance-safe logsWhen adding or modifying logging, follow these rules: 1) **Attribute logs to the right component/instance** - Avoid process-global logging hooks/state when a per-instance logger exists.maximhq/bifrost6 discussions
- Use consistent error typesAlways use the appropriate error classes and throwing mechanisms for consistent error handling across the codebase. Prefer `BetterAuthError` or `APIError` over generic `Error` classes, use `throw` instead of returning error responses in endpoints, and structure error codes consistently.better-auth/better-auth6 discussions
- Explicit null handlingAlways make null handling explicit through proper annotations, defensive checks, and clear documentation. Use @Nullable annotations for parameters and fields that can be null, add precondition checks with meaningful error messages for required non-null values, and document when and why values may be null.bazelbuild/bazel6 discussions
- Avoid unnecessary computationsBefore performing expensive operations, check if the work is actually needed or if more efficient alternatives exist. This includes validating preconditions, using optimized system calls, and avoiding duplicate method invocations.bazelbuild/bazel6 discussions
- Use Standard Entity IdentifiersWhen creating `entityMappings`, use semantically strong, standard identifier fields as the mapped `columnName`. Avoid “legacy/weak” intermediary names like `AccountCustomEntity` (and avoid unnecessary wrapper columns like `IPCustomEntity`) when a direct standard field already exists.Azure/Azure-Sentinel6 discussions
- Schema-First DCR KQLFor data connector definitions (DCR + KQL transforms), treat the DCR `streamDeclarations.columns` as the schema contract and ensure KQL transforms match that contract:Azure/Azure-Sentinel6 discussions
- Parameterize Config ValuesWhen authoring queries/parsers and deployment templates, ensure all environment- or customer-specific values are configurable via parameters (e.g., `let`, `ParserParams`, CloudFormation `Parameters`), and avoid unsafe sample/environment defaults. Also, if you introduce or rely on a standard configuration flag (e.g., additional-fields “pack”), make sure it’s...Azure/Azure-Sentinel6 discussions
- arm escaping and diff hygieneWhen editing Azure Sentinel solution artifacts (ARM templates + nested CCF connector templates), treat ARM escaping and packaging output as correctness-critical formatting:Azure/Azure-Sentinel6 discussions
- Arm Escape In ConfigsWhen authoring Sentinel solution/connector configuration JSON (especially CCF/CCP connector `*_PollerConfig.json` and embedded/packaged `mainTemplate.json` content templates), treat `[[ ...` as a configuration-time escape—do not “simplify” it.Azure/Azure-Sentinel6 discussions
- Use domain-specific type namesTypes should be named with clear domain context rather than generic terms. Avoid single-word or overly generic names that could be ambiguous or conflict with other types. Instead, prefix type names with their domain or service name to provide clear context and prevent naming collisions.Azure/azure-sdk-for-net6 discussions
- Minimize memory allocationsReduce garbage collection pressure and improve application performance by avoiding unnecessary memory allocations. This significantly impacts overall system responsiveness, especially for high-throughput services.Azure/azure-sdk-for-net6 discussions
- Document code reasoningAdd clear, concise comments that explain the "why" behind complex logic, non-obvious decisions, and implicit behaviors. Focus on documenting: 1. **Algorithmic choices and control flow** - Explain why loops are broken, conditions are checked, or specific approaches are used.Azure/azure-sdk-for-net6 discussions
- Optional Null PatternsWhen a value is optional in Bicep, use **nullable parameter types** and **null-safe property emission** instead of sentinel values (like empty strings) or `json('null')`.Azure/azure-quickstart-templates6 discussions
- Validate Security InputsApply security validation and gating at the boundaries of security-sensitive behavior: - Validate identifiers and API-version-like parameters during cmdlet/argument binding (e.g., GUIDs, strict date patterns) so malformed inputs can’t flow into authorization/resource construction.Azure/azure-powershell6 discussions
- Reliable Integration TestingWrite integration/recorded tests so they are deterministic, efficient in playback, and self-cleaning. Apply these rules: 1) Deterministic errors → unit tests with mocksAzure/azure-powershell6 discussions
- Respect Wire ContractsWhen calling REST endpoints, ensure the client request/response payload exactly matches the endpoint’s wire contract—especially when GET and PUT/PATCH shapes differ (nested ARM-canonical vs flat service payload) or when envelope fields must be consistent.Azure/azure-cli6 discussions
- Prefer simpler code constructsAlways opt for simpler, more idiomatic code constructs over complex or verbose alternatives. This includes using built-in Rust patterns instead of manual implementations, leveraging pattern matching for cleaner control flow, using method chaining when it improves readability, and maintaining consistent formatting.tokio-rs/axum6 discussions
- Semantic naming conventionsUse descriptive, semantic names for all code elements that clearly indicate their purpose and behavior. Follow consistent casing patterns throughout the codebase:aws/aws-sdk-js6 discussions
- Early return after errorsWhen handling errors in asynchronous functions, always return immediately after invoking a callback with an error to prevent subsequent code execution. This avoids the risk of calling callbacks multiple times or continuing execution paths that assume success.aws/aws-sdk-js6 discussions
- Document APIs thoroughlyAll public API elements must be thoroughly documented with JSDoc annotations that clearly explain their purpose, parameters, return values, and default behaviors. Documentation should be precise, matching the actual code behavior rather than making assumptions or using misleading descriptions.aws/aws-sdk-js6 discussions
- Prefer early returnsUse early returns and guard clauses to reduce nesting levels and improve code readability. Instead of deeply nested if-else structures, invert conditions and return early when possible. This pattern makes the main logic flow more apparent and reduces cognitive load.argoproj/argo-cd6 discussions
- Complete configuration examplesConfiguration examples in documentation must be complete and reference authoritative sources to prevent deployment issues and developer confusion. Incomplete configuration lists can lead to runtime errors and failed setups.argoproj/argo-cd6 discussions
- Guard Optional ValuesTreat any value that may be undefined/null (environment globals, optional stream handles, user config fields, optional IDs) as untrusted at the boundary. Use explicit checks/type guards instead of non-null assertions, and either omit invalid fields or return a deterministic safe failure—never let missing data crash module load or runtime.coleam00/Archon6 discussions
- Use language-specific syntaxCode snippets must use the correct language-specific syntax and include all necessary imports to compile properly. When writing examples: 1. Include all required imports for the libraries and data structures usedappwrite/appwrite6 discussions
- Synchronize configuration valuesEnsure all configuration values, particularly version numbers and environment variables, are consistent across related files to prevent subtle bugs and deployment issues. When updating configurations:appwrite/appwrite6 discussions
- Secure authorization skip handlingWhen using authorization bypass mechanisms like `Authorization::skip()`, ensure proper security validation is maintained. Authorization skipping should only be used for internal system operations where the caller already has appropriate permissions, never for user-facing operations that require access control.appwrite/appwrite6 discussions
- Avoid Hot-Path WorkWhen optimizing performance, ensure hot paths do only the minimum required work and never block while holding scarce resources. Apply these rules: - Gate expensive resolution/processing behind cheap checks (e.g., only resolve secrets if references exist; only buffer/scan when blocking is requested).apache/apisix6 discussions
- High-signal Testing PracticesWrite tests that are (a) high-signal and not fragile, and (b) structured with standard pytest mechanisms. Apply: - Use fixtures instead of module/global clients, so each test has clean, controllable dependencies.anthropics/anthropic-sdk-python6 discussions
- Markdown formatting consistencyEnsure consistent markdown formatting in documentation by wrapping all technical terms, API names, property names, and code-related content in backticks. This improves readability and maintains visual consistency across documentation.ant-design/ant-design6 discussions
- JSDoc deprecation formattingEnsure consistent formatting in JSDoc deprecation comments to improve API documentation clarity and developer experience. Use backticks around parameter/property names to distinguish them from regular text, use angle brackets for component names, and include "instead" for replacement suggestions.ant-design/ant-design6 discussions
- Dependency versioning consistencyEstablish and maintain consistent dependency versioning strategies in package.json configuration. Choose between caret (^) and tilde (~) ranges based on stability requirements and update policies. For stable production dependencies, prefer tilde ranges to avoid unexpected breaking changes, while development dependencies can use caret ranges for latest...ant-design/ant-design6 discussions
- Use reactive signal patternsPrefer Angular's reactive signal patterns over manual subscription management and imperative approaches. Use signals directly in templates without calling getters, convert observables to signals with `toSignal()`, and maintain reactive data flow throughout your application.angular/angular6 discussions
- leverage existing Angular patternsBefore implementing new functionality, check if Angular already provides a suitable utility, service, or pattern that can be reused. This promotes consistency across the codebase, reduces duplication, and follows established Angular conventions.angular/angular6 discussions
- Validate user-controlled pathsAlways validate and sanitize user-provided inputs used in file path operations to prevent path traversal attacks. Path traversal vulnerabilities can allow attackers to access unauthorized files outside the intended directory structure.apache/airflow6 discussions
- Standardize API parameter handlingUse consistent parameter handling patterns across API endpoints to ensure maintainability and predictable behavior. Follow these guidelines: 1. Use FastAPI's native parameter handling for lists:apache/airflow6 discussions
- Avoid code duplicationExtract repeated code patterns into reusable functions, variables, or constants to improve maintainability and reduce the risk of inconsistencies. Look for similar code blocks that perform the same operations and consolidate them.apache/airflow6 discussions
- Secure Scope and Input ValidationAll security-relevant authorization/receipt logic must be (1) scope-correct and precondition-correct, and (2) fed only strictly validated/sanitized inputs—especially when values are used to render/parse audit logs, build regexes, or mutate the filesystem.awslabs/aidlc-workflows6 discussions
- Executable Documentation AccuracyAll technical documentation in this repo (stage protocols, stage bodies, templates, plugin authoring docs, READMEs that describe operational steps) must be mechanically consistent with the actual engine/tools/sensors—and must state conditions as explicit, checkable constraints.awslabs/aidlc-workflows6 discussions
- Defensive Observable Error HandlingCoding standard for hook/compose-style tooling: never fail silently; parse defensively; gate writes by installed compatibility; and make transient failures self-healing. Diagnostics must only fail on real faults (e.g., stale markers), not normal in-flight states.awslabs/aidlc-workflows6 discussions
- Verify AI model capabilitiesAlways verify and accurately document AI model capabilities, supported formats, and limitations before implementation. Use consistent terminology (e.g., "multi-modal" instead of "multimodal") and validate model features against official documentation sources. When documenting AI functionalities:vercel/ai6 discussions
- Type-safe null handlingUse TypeScript's type system and modern JavaScript features to prevent null reference errors. **TypeScript type safety:** - Prefer `never` over `undefined` for properties that shouldn't have valuesvercel/ai6 discussions
- Keep tests simpleTests should be straightforward, explicit, and free from complex logic or indirection. Avoid "magic" in tests that makes them harder to understand at a glance. When designing tests:vercel/ai6 discussions
- Test actual functionalityEnsure tests verify real operations and integration scenarios rather than just basic concepts or type definitions. Many test suites contain placeholder tests that only check if functions exist or verify simple type structures, but fail to test the actual behavior and interactions that matter in production.cloudflare/agents6 discussions
- Test real behavior clearlyTests should exercise the actual production code and fail with clear, actionable messages when something breaks. - Import and call the real implementation under test instead of re-declaring a copy of the logic inside the test file. A duplicated helper can silently drift from production code, giving false confidence that the feature is covered when it's...decolua/9router6 discussions
- Enforce trust boundariesTreat every point where data crosses a trust boundary as a security checkpoint, not an afterthought. Concretely: 1. Never leak secrets outward. Any response-shaping helper (e.g. `toProviderConnectionResponse()`) must strip credential fields such as `sessionToken`/`accessKeyId` from create, list, detail, and update responses even though the raw value is...Decolua/9Router6 discussions
- Correct Algorithm ContractsFor algorithm/data-structure snippets, make correctness and the function contract explicit: don’t silently break edge cases, validate required input constraints, and only mutate inputs when the name/description guarantees it. Also prefer native/built-in equivalents when available.30-seconds/30-seconds-of-code6 discussions
- Consistent Null HandlingUse a consistent null/undefined policy and make it explicit in both type checks and call/return behavior. - **Guard before indexing/access:** when inputs may be missing or null, check the right predicate (e.g., `Array.isArray`) and return a consistent “not found” value (commonly `undefined`).30-seconds/30-seconds-of-code6 discussions
- Consistent, clear namingUse naming that is unambiguous, consistent with the codebase, and semantically accurate. Apply: - Avoid shadowing: don’t reuse the same parameter name in a nested scope; either rename or move the nested function out.colinhacks/zod5 discussions
- Use structured model metadataRepresent AI model information using structured data rather than hardcoded enumerations or conditionals. Store capabilities, limitations, and features as structured fields that can be queried at runtime. This approach simplifies adding new models, detecting feature support, and adapting to model updates without requiring extensive code changes.zed-industries/zed5 discussions
- Scope dependencies appropriatelyConfigure dependencies with their minimum necessary scope to maintain clean architecture and improve build times. Key practices: 1. **Test-only dependencies should be dev-dependencies**zed-industries/zed5 discussions
- Document configuration constraints clearlyWhen defining configuration options, always clearly document parameter constraints, valid ranges, and behaviors. For numeric values, explicitly state acceptable ranges and how out-of-range values are handled. Configuration options should have appropriate granularity - avoid simple booleans when more nuanced control is beneficial.zed-industries/zed5 discussions
- Choose domain-specific semantic namesNames should clearly reflect their domain-specific meaning and purpose, avoiding generic or ambiguous terms. This applies to variables, methods, classes, and other identifiers. When naming, consider:zed-industries/zed5 discussions
- Strict null checksUse explicit strict equality checks when testing for null or undefined values. Prefer `x === undefined` over `typeof x === 'undefined'` when the variable is known to exist. When checking for both null and undefined, use `x == null` (loose equality) as it covers both cases, or check each explicitly with `x === null || x === undefined`. Avoid using the `||`...facebook/yoga5 discussions
- Explicit undefined state handlingAlways use explicit, well-defined representations for undefined, uninitialized, or invalid states instead of magic values or allowing undefined behavior to propagate silently. Create named constants or enum values for undefined states, and make conscious decisions about whether to crash, return defaults, or handle undefined values gracefully.facebook/yoga5 discussions
- JSDoc documentation standardsAll public functions and complex code should have proper JSDoc documentation. Functions must include clear descriptions of their purpose, parameters, and return values. Ensure JSDoc comments are accurate, well-formatted, and kept up-to-date with code changes.cloudflare/workers-sdk5 discussions
- Configuration file consistencyEnsure consistent patterns for configuration files, proper exclusion of development artifacts, and clear environment-specific handling across projects.cloudflare/workers-sdk5 discussions
- proper span lifecycle managementEnsure spans are properly created, attached to async operations, and reported at appropriate times to maintain accurate tracing data. Spans that are not properly managed will result in incorrect durations, missing trace data, or unreliable observability metrics.cloudflare/workerd5 discussions
- Network resource state validationAlways validate the state of network resources (sockets, streams, connections) before performing operations to prevent errors, resource leaks, and ensure proper connection reuse.cloudflare/workerd5 discussions
- compatibility flag consistencyEnsure compatibility flags follow consistent naming conventions, use explicit typing, and maintain proper usage patterns throughout the codebase. Compatibility flags should use descriptive, version-specific names that accurately reflect their purpose and lifecycle.cloudflare/workerd5 discussions
- avoid unnecessary allocationsMinimize object creation and memory copying operations to improve performance. Cache and reuse objects when possible, use buffer views instead of copying data, and avoid creating temporary objects that will be immediately discarded.cloudflare/workerd5 discussions
- Specify API contractsState and document explicit, unambiguous contracts for all API endpoints and RPC messages, especially around resource identity, data encoding, and file-operation semantics. Motivation: inconsistent assumptions about where a path comes from, whether payloads are encoded, and what ReadAt/WriteAt should return lead to brittle clients and surprising server...wavetermdev/waveterm5 discussions
- Explicit API shapesRequire API surfaces (payloads, function contracts, and compact descriptor grammars) to be explicit, well-documented, and normalized at the boundary. This reduces client/server surprises, clarifies intent (single vs collection), and ensures deterministic parsing.wavetermdev/waveterm5 discussions
- Centralize constants and structureMotivation Keep code readable, consistent and easy to change by centralizing configuration, constants and mutable state, and by extracting repeated flows into well-scoped helpers or service types.wavetermdev/waveterm5 discussions
- Type-Safe API BoundariesAPIs that cross module boundaries, wire formats, or event streams should be designed so callers can’t accidentally construct invalid requests or rely on unstable semantics.warpdotdev/warp5 discussions
- Serialize async per-keyEnsure async/stateful flows are race-free by avoiding overlapping work for the same logical key and by handling events that arrive before the relevant state is ready.warpdotdev/warp5 discussions
- Robust config handlingTreat configuration as a stable, privacy-safe contract: it must load without breaking the whole file, resolve safely at apply-time, use platform-correct paths, and (for significant changes) be shipped behind feature flags with explicitly defined non-lossy toggle behavior.warpdotdev/warp5 discussions
- Doc exactness standardAdopt a “docs must be executable-accurate” standard: treat technical docs/specs/changelogs as part of the product contract, and ensure they exactly match current behavior, supported formats, and rendering constraints.warpdotdev/warp5 discussions
- Deterministic Matching InvariantsWhen implementing algorithms for pairing/alignment, matching/routing, search, or event fan-out, require a clearly stated invariant and explicit boundary/edge-case behavior, then back it with targeted tests.warpdotdev/warp5 discussions
- Thread explicit nullabilityWhen code needs to decide behavior based on “which kind/shape” of a value it has, avoid inferring that shape from nullable proxy fields (e.g. `handle !== undefined`). Instead, compute the nullability/union-discriminant once at the source (where the real value is in scope) and pass an explicit flag or `kind` through a DTO. Also ensure your TypeScript types...microsoft/VSCode5 discussions
- Service contract clarityPrefer explicit, responsibility-aligned service APIs with well-defined contracts for (a) what callers should expect synchronously/async, (b) how caching vs live validation behaves, and (c) how events supersede in-flight work.microsoft/VSCode5 discussions
- Graceful error handlingWhen handling failures in UI/async flows, design for graceful degradation and predictable recovery: - Treat async outcomes as explicit states (uninitialized/loading/loaded/failed). Never let “empty success” be conflated with “not fetched,” and avoid recursive re-fetch loops.microsoft/VSCode5 discussions
- Use structured loggingAlways use structured logging methods like klog.InfoS and klog.ErrorS instead of unstructured methods like klog.Infoln, klog.Infof, or klog.Errorln. Structured logging improves log parsing, analysis, and monitoring capabilities. Additionally, ensure log messages are clear, descriptive, and provide complete context about actions taken and values being set.volcano-sh/volcano5 discussions
- Use descriptive consistent namingChoose names that are self-explanatory, descriptive, and consistent across the codebase. Avoid abbreviated or informal naming that requires additional explanation. Follow language-specific conventions and include units or data types where appropriate.volcano-sh/volcano5 discussions
- Validate algorithmic operations carefullyMathematical and logical operations require careful validation to ensure correctness. Common issues include: 1. Operator precedence in complex conditionsvllm-project/vllm5 discussions
- Remove unnecessary code elementsKeep code clean and maintainable by removing unnecessary elements that add complexity without value: 1. Remove unused header includes that increase compile timesvllm-project/vllm5 discussions
- Preserve API compatibilityWhen modifying API interfaces, parameters, or argument behavior, ensure backward compatibility is maintained to prevent breaking existing user code. If a parameter needs to be renamed or enhanced, continue supporting the old parameter name alongside the new one.vllm-project/vllm5 discussions
- Optimize memory allocationAlways allocate data structures with appropriate initial capacity and use memory-efficient data types to reduce memory pressure and improve application performance. Pre-allocate containers when the size is known or can be estimated, avoid unnecessary intermediate data structures, and choose compact data representations.vitessio/vitess5 discussions
- Runtime-agnostic API designWhen designing APIs for systems that support multiple JavaScript runtimes, prioritize decoupling server state from user modules. This approach enables code to run consistently across different environments (Node.js, browsers, edge runtimes) without relying on runtime-specific features.vitejs/vite5 discussions
- Propagate errors with contextAlways propagate errors with proper context and recovery strategy. Use try-catch blocks for both synchronous and asynchronous operations, ensure error information is preserved, and provide meaningful error messages.vitejs/vite5 discussions
- Environment variable managementWhen working with environment variables in Vite applications, be explicit about variable loading behavior and precedence. Environment variables from `.env` files are always loaded regardless of mode, with mode-specific files (`.env.[mode]`) taking precedence over generic ones.vitejs/vite5 discussions
- Runtime configurable defaultsPrefer runtime-configurable values over hardcoded constants to allow users to customize behavior without recompilation. Use environment variables with `os.getenv_opt()` for runtime configuration instead of compile-time constants with `$d()`, and consider environment variables instead of complex CLI parsing.vlang/v5 discussions
- Secure configuration defaultsEstablish secure default configurations in project metadata files to prevent accidental publishing and ensure proper version constraints. This is particularly important for private packages and build system configurations.astral-sh/uv5 discussions
- Optimize CI/CD commandsDesign CI/CD workflows to be efficient, consistent, and purposeful across all environments. When writing or modifying pipeline scripts: 1. Batch related operations to minimize redundant commands and improve performanceastral-sh/uv5 discussions
- Environment variable best practicesWhen implementing environment variable configuration: 1. Follow standard environment variable conventions: - Use uppercase with underscores (e.g., `NO_COLOR`, `FORCE_COLOR`)astral-sh/uv5 discussions
- Raise exceptions properlyAlways ensure exceptions are properly raised and propagated rather than being logged and swallowed. Avoid patterns where errors are caught, logged, and then execution continues normally, as this can hide critical failures from calling code.Unstructured-IO/unstructured5 discussions
- extensible parameter designDesign API parameters to support future extension without breaking changes. Use string enums instead of boolean flags when the parameter might need additional values later, implement comprehensive parameter forwarding with **kwargs, and avoid overly specific parameter designs that limit future flexibility.Unstructured-IO/unstructured5 discussions
- Environment variable patternsUse consistent patterns for environment variable handling in shell scripts. Always provide sensible defaults using the `${VAR:-default}` syntax, validate required variables early with clear error messages, and preserve the ability to override configuration values.Unstructured-IO/unstructured5 discussions
- Meaningful consistent identifiersChoose descriptive, semantically accurate names for variables, types, and components that clearly communicate their purpose. Maintain consistency throughout your codebase by:shadcn-ui/ui5 discussions
- Guard against undefinedAlways protect against potential null or undefined values before attempting property access or method calls to prevent runtime errors. This applies especially to array access, method calls like `.some()` or `.length`, and property access on objects that might be null.microsoft/typescript5 discussions
- Extract complex logical expressionsComplex logical expressions should be extracted into well-named variables or functions to improve code readability and maintainability. This applies to:microsoft/typescript5 discussions
- prefer type guardsUse semantic type guards like `isDefined()` instead of basic type checks (`typeof`, simple null checks) or unsafe type assertions (`as!`, `!`). Type guards provide better readability, type safety, and null reference prevention.twentyhq/twenty5 discussions
- Minimize hook re-rendersDesign React hooks to minimize unnecessary re-renders by avoiding common anti-patterns that cause performance issues. **Key principles:** 1. **Avoid umbrella hooks** - Don't create hooks that combine multiple responsibilities, especially mixing read and write operations. Split them into focused, single-purpose hooks.twentyhq/twenty5 discussions
- Add tests for functionalityNew functionality should include corresponding tests to ensure code quality and maintainability. When introducing new methods, utilities, or services, always add appropriate test coverage.twentyhq/twenty5 discussions
- Validate performance impact firstAlways validate performance changes through profiling or benchmarking before implementation, and favor memory-efficient patterns when making optimizations. Key practices:vercel/turborepo5 discussions
- Design ergonomic APIsCreate APIs that are both easy to use correctly and hard to use incorrectly. Focus on: 1. **Use pattern matching for safer error handling** instead of unwrapping values that might be null:vercel/turborepo5 discussions
- Use meaningful identifiersChoose identifiers that accurately represent their purpose, semantics, and relationship to the codebase. Names should be self-documenting and consistent with established patterns in the module or API.tree-sitter/tree-sitter5 discussions
- Use descriptive identifiersChoose identifiers that clearly communicate their purpose, content, or role rather than using generic or abbreviated names. Names should be self-documenting and reduce the need to reference documentation or implementation details to understand what they represent.tree-sitter/tree-sitter5 discussions
- Ensure documentation clarityDocumentation should be clear, accurate, and provide meaningful information to users. Avoid misleading descriptions, template text that doesn't add value, and unclear explanations that leave users confused about functionality.tree-sitter/tree-sitter5 discussions
- consistent formatting preferencesMaintain consistent formatting and use concise, standard syntax throughout the codebase. This includes several specific formatting rules: 1. **Preprocessor directives**: Do not add spaces after the `#` symboltree-sitter/tree-sitter5 discussions
- complete API documentationEnsure all API configuration options are fully documented with accurate default values, required field indicators, and complete parameter tables. Missing configuration options, incorrect defaults, or incomplete documentation tables create confusion and implementation errors for developers.traefik/traefik5 discussions
- Structure feature flags strategicallyDesign feature flags to minimize dependency bloat while maximizing flexibility for users. Each optional dependency should be tied to a specific feature flag, allowing users to enable only the functionality they need.tokio-rs/tokio5 discussions
- Structure API doc blocksEach public API documentation block should follow a consistent structure: 1. Start with a single-line summary that concisely describes the item 2. Add an empty line after the summarytokio-rs/tokio5 discussions
- Socket configuration guidanceWhen implementing networking APIs, always clearly document socket modes, configuration options, and platform-specific behaviors. Be explicit about blocking versus non-blocking mode implications, required flags, and ensure consistent API design across related components.tokio-rs/tokio5 discussions
- Optimize hot pathsIdentify and optimize frequently executed code paths to improve performance. Hot paths have a significant impact on overall application performance. Key strategies include:tokio-rs/tokio5 discussions
- Graceful error handlingPrioritize graceful error handling over panicking by providing fallbacks and propagating rich context. When operations can fail: 1. For non-critical failures, use fallbacks instead of unwrap():tokio-rs/tokio5 discussions
- Fast deterministic testsAvoid using real sleeps or delays in tests as they significantly slow down the test suite and can introduce flakiness. Instead, use simulated time with the `start_paused` parameter for time-dependent tests:tokio-rs/tokio5 discussions
- Design flexible APIsWhen designing APIs, prioritize flexibility, ergonomics, and intuitiveness to create better user experiences. APIs should accept the most general parameter types appropriate for the functionality, handle edge cases gracefully, and provide methods that align with user expectations.tokio-rs/tokio5 discussions
- Minimize memory allocationsAvoid unnecessary memory allocations to improve performance. Each allocation has both CPU and memory overhead that can accumulate significantly, especially in hot code paths.huggingface/tokenizers5 discussions
- Handle nullable types idiomaticallyUse Rust's idiomatic patterns when working with Option and Result types to prevent panics and improve code clarity. **Avoid unwrapping** Prefer pattern matching or propagating errors instead of using `.unwrap()` which can cause runtime panics:huggingface/tokenizers5 discussions
- Use precise semantic namesChoose names that accurately reflect the purpose and semantics of the entity being named. Avoid overloaded or ambiguous terms that could lead to confusion or misinterpretation.hashicorp/terraform5 discussions
- Prefer modern authenticationAlways use modern identity-based authentication methods instead of static credentials when accessing external systems. This reduces security risks associated with credential management, rotation, and potential exposure.hashicorp/terraform5 discussions
- Include descriptive documentationProvide complete, clear descriptions for all configuration elements in documentation. Every output, variable, argument, and configuration option should include descriptive text explaining its purpose, requirements, and usage from the consumer's perspective.hashicorp/terraform5 discussions
- Document function behavior completelyFunction and method documentation should accurately describe behavior, parameters, and any non-obvious aspects of the implementation. Documentation should evolve alongside code changes.hashicorp/terraform5 discussions
- Consolidate related codeOrganize code to keep related functionality together. When functions serve similar purposes or operate on the same data, combine them rather than creating separate implementations. Position validation and condition checks before execution to allow early returns and avoid unnecessary processing. This improves code readability, maintainability, and reduces...hashicorp/terraform5 discussions
- prefer const declarationsUse `const` for variables that are not modified after initialization, and avoid creating unnecessary temporary variables when the value can be computed directly in the declaration.microsoft/terminal5 discussions
- Validate quantization parameters carefullyWhen implementing quantized operations in ML models, thoroughly validate quantization parameters to ensure correctness and prevent subtle numerical errors. Key validation points:tensorflow/tensorflow5 discussions
- Validate before dereferenceAlways check that pointers, optional values, and results of type casts are valid before dereferencing or using them. This prevents null pointer exceptions, undefined behavior, and potential crashes in production.tensorflow/tensorflow5 discussions
- Optimize loop operationsMinimize expensive operations within inner loops to improve performance. Key practices include: 1. Extract loop-invariant calculations outside of loopstensorflow/tensorflow5 discussions
- Informative error messagesError messages should be informative, actionable, and concise to help users quickly understand and fix issues. Follow these guidelines: 1. Include specific details in error messages:tensorflow/tensorflow5 discussions
- Handle dynamic shapesWhen implementing tensor-based algorithms, avoid assumptions about fixed tensor shapes by not relying on direct shape attributes (`.shape`, `.ndim`), which may return `None` in graph mode. Instead, use TensorFlow operations like `tf.shape()` and `tf.rank()` which work in both eager and graph execution modes. For validation, use TensorFlow's conditional...tensorflow/tensorflow5 discussions
- Optimize metrics label cardinalityCarefully manage metric label cardinality to prevent excessive memory usage and maintain system performance. Follow these guidelines: 1. Separate high-cardinality metrics:temporalio/temporal5 discussions
- Domain-specific error boundariesDefine and use domain-specific error types within bounded contexts rather than relying on generic service errors. Each component/package should define its own error types that reflect its domain concepts, avoiding dependencies on external error frameworks.temporalio/temporal5 discussions
- Design stable APIsWhen designing APIs, prioritize long-term stability and compatibility to avoid breaking changes. Use request/response objects pattern for methods that might evolve over time rather than direct parameters:temporalio/temporal5 discussions
- Use appropriate testify assertionsChoose the most specific and appropriate testify assertion methods for your test scenarios to improve test clarity, error reporting, and maintainability.gravitational/teleport5 discussions
- minimize unnecessary allocationsAvoid unnecessary memory allocations in performance-critical code paths, especially in frequently executed functions or loops that process large datasets. Common allocation sources to eliminate include:gravitational/teleport5 discussions
- Configuration requirements clarityConfiguration requirements and dependencies should be made explicit and prominent in documentation, not buried in notes or admonitions. When introducing new configuration options or requirements, ensure they are clearly documented as prerequisites or explicit steps rather than side notes that users might miss.gravitational/teleport5 discussions
- API consistency patternsMaintain consistent API patterns and structures across different resource types and access methods within the same system. When designing new API fields or resources, follow established patterns from existing similar functionality rather than creating divergent approaches.gravitational/teleport5 discussions
- Teach by examplePresent concepts through clear, focused examples that demonstrate features positively rather than through comparisons or criticisms of alternative approaches. Allow readers to discover benefits through well-constructed examples rather than explicit statements about superiority.tensorflow/swift5 discussions
- Explicit configuration validationAvoid using configuration values as implicit feature flags or logic triggers. Instead, validate configuration explicitly and make behavior predictable.SWE-agent/SWE-agent5 discussions
- prefer testing librariesWhen testing components, use established testing libraries like @testing-library/svelte instead of low-level DOM manipulation approaches. Low-level testing with direct mount/unmount and querySelector calls is brittle and requires frequent updates when component structure changes. Testing libraries provide user-focused APIs that are more robust to...sveltejs/svelte5 discussions
- defensive error handlingAdd defensive checks and proper error handling to prevent crashes and handle edge cases gracefully. This includes using try-catch blocks around potentially unsafe operations, adding guard conditions to prevent infinite loops or invalid states, and ensuring the system can recover from unexpected inputs or conditions.sveltejs/svelte5 discussions
- avoid expensive operationsIdentify and eliminate computationally expensive operations through early termination, better data structures, and algorithmic optimizations. Look for opportunities to short-circuit loops, cache results, and choose more efficient algorithms.sveltejs/svelte5 discussions
- Structure components with clarityMaintain clean and logical component organization by following these guidelines: 1. Keep related files together - place test files beside their components rather than in separate folderssupabase/supabase5 discussions
- Clear, descriptive identifiersChoose variable, component, and parameter names that clearly describe their purpose and avoid ambiguity. Names should fully reflect functionality, be properly spelled, and avoid confusion with library terms or similar concepts.supabase/supabase5 discussions
- Use structured logging consistentlyAlways use the established logging framework instead of console.log or ad-hoc logging approaches. This ensures consistent log formatting, proper log levels, and better log management across the application.browserbase/stagehand5 discussions
- Use descriptive namesChoose descriptive, domain-specific names that clearly communicate intent and prevent confusion. Avoid generic names when more specific alternatives exist, especially when working alongside similar types or concepts from external libraries.browserbase/stagehand5 discussions
- Provide contextual error messagesError messages should include specific context about what went wrong and provide actionable guidance for resolution. Avoid generic error messages that leave developers guessing about the root cause or solution.browserbase/stagehand5 discussions
- Leverage TypeScript null safetyUse TypeScript's type system proactively to prevent null and undefined issues at compile time rather than handling them reactively at runtime. This includes using exhaustive pattern matching, explicit type annotations, and avoiding type casting that can hide null safety problems.browserbase/stagehand5 discussions
- Respect annotation processing orderWhen designing Spring components, pay careful attention to the order in which annotations are processed, especially for inheritance scenarios. Spring processes annotations in a specific sequence that can affect bean initialization and override behavior.spring-projects/spring-framework5 discussions
- Design for API extensionWhen designing APIs, prioritize extensibility by providing clear extension points and avoiding direct exposure of implementation details. This allows for future enhancements without breaking compatibility.spring-projects/spring-framework5 discussions
- Cleanup error handlingWhen handling resources that require cleanup (like streams, connections, or transactions), ensure that errors during the cleanup phase don't overshadow or silently replace the original error. This applies to both try-with-resources and traditional try/finally blocks.spring-projects/spring-framework5 discussions
- API boundary null handlingEstablish consistent null handling patterns at API boundaries to prevent null pointer exceptions and improve code clarity: 1. Validate method parameters using explicit null checks:spring-projects/spring-framework5 discussions
- Property description conventionsWhen documenting configuration properties in Spring Boot applications, follow these conventions for clarity and consistency: 1. Avoid starting descriptions with articles like "the" or "a"spring-projects/spring-boot5 discussions
- prefer simple APIsDesign APIs with simplicity in mind by avoiding unnecessary method overloads, reducing configuration options, and preferring single well-designed methods that handle all cases rather than multiple variants.apache/spark5 discussions
- Include contextual informationLog messages should include comprehensive contextual information to support debugging and system monitoring. This includes relevant identifiers, operation details, and state information that help developers understand what happened and why.apache/spark5 discussions
- avoid unnecessary computationsPrevent performance degradation by avoiding unnecessary expensive operations such as premature execution, redundant iterations, and costly data conversions. Use lazy evaluation, short-circuiting, and efficient data handling patterns to optimize execution paths.apache/spark5 discussions
- Use appropriate error typesAlways use semantically correct error types and codes that match the actual failure scenario. This ensures proper error handling by callers and consistent API behavior across the system.SigNoz/signoz5 discussions
- Centralize configuration managementConsolidate configuration parameters into centralized config structures instead of using scattered options structs or hardcoded values. Configuration should be owned and controlled by the appropriate component, with all related settings grouped together in well-organized config files.SigNoz/signoz5 discussions
- Use descriptive namesChoose variable, function, and parameter names that accurately reflect their content, type, and purpose. Avoid misleading names that don't match the actual data or functionality they represent.sgl-project/sglang5 discussions
- conditional CI executionUse appropriate conditional statements in CI workflows to ensure steps execute under the right circumstances and handle different environments gracefully.servo/servo5 discussions
- Structure configs for clarityOrganize configuration objects to maximize clarity and maintainability while ensuring robust validation. Follow these principles: 1. Use single object definitions instead of multiple configurations to enable specific error messagesserverless/serverless5 discussions
- API clarity and consistencyEnsure API configurations, documentation, and terminology are clear, consistent, and properly organized. Group related API properties together logically, use precise terminology that matches the underlying service (e.g., distinguish "HTTP API" from "REST API"), and maintain consistent naming conventions throughout.serverless/serverless5 discussions
- exact assertion testingTests should verify exact expected results rather than generic existence checks. Avoid assertions like `isinstance()`, `len() > 0`, `is not None`, or `any()` that only confirm something exists without validating correctness. Instead, assert for specific expected values, names, and properties.oraios/serena5 discussions
- Secure sensitive dataAlways protect sensitive data through proper encryption, secure cookies, and careful exception handling to prevent information leakage. When handling sensitive data:getsentry/sentry5 discussions
- Remove unnecessary code elementsKeep code clean and maintainable by removing unnecessary elements. This includes: 1. Omit type annotations when TypeScript can infer them: ```typescriptgetsentry/sentry5 discussions
- Prevent N+1 database queriesAvoid N+1 database queries by using appropriate Django ORM features like select_related(), prefetch_related(), and bulk operations. N+1 queries occur when you access related objects in a loop, causing additional database queries for each iteration.getsentry/sentry5 discussions
- Propagate errors with contextAlways propagate errors appropriately by rethrowing caught exceptions and maintaining error context. Catch exceptions only when you can handle them meaningfully, and ensure errors aren't silently swallowed.getsentry/sentry-php5 discussions
- Document API changesWhen documenting API changes, particularly breaking changes, follow these practices to ensure clarity and ease of migration: 1. **Group related changes** for better scannability. When multiple methods or functions change in a similar way, format them as a structured list:getsentry/sentry-php5 discussions
- Defensive null checkingImplement defensive null checking to prevent NoneType errors, KeyError, and IndexError exceptions. When accessing dictionaries, collections, or optional values, verify existence before use.getsentry/sentry5 discussions
- Choose efficient algorithmsWhen implementing algorithms, prioritize computational efficiency by selecting appropriate data structures and avoiding unnecessarily complex approaches. Consider the time complexity of your solution and whether built-in functions or better data structures could improve performance.semgrep/semgrep5 discussions
- Fail fast explicitlyAlways throw exceptions for error conditions rather than silently failing, logging warnings, or attempting fallback behavior that masks underlying problems. When encountering unexpected states, missing required data, or configuration errors, raise descriptive exceptions immediately rather than continuing execution with degraded functionality.strands-agents/sdk-python5 discussions
- explicit null checksUse explicit existence checks rather than value-based null checks, and be intentional about failing fast versus providing defaults for missing data. When checking for optional data, prefer checking for key/attribute existence rather than checking if values are truthy or greater than zero. This prevents subtle bugs where legitimate zero values or empty...strands-agents/sdk-python5 discussions
- comprehensive test assertionsWrite robust test assertions that verify complete objects and behaviors rather than individual properties. Use pytest's built-in features for exception testing and mock verification to make tests more reliable and maintainable.strands-agents/sdk-python5 discussions
- Complete docstring documentationEnsure all classes, methods, and properties have comprehensive docstrings that clearly explain their purpose, behavior, and usage. Docstrings should be preferred over inline comments for method descriptions and should include:strands-agents/sdk-python5 discussions
- AI provider normalizationWhen integrating multiple AI model providers, implement proper abstraction layers to normalize differences in APIs, data formats, and behaviors. Different providers often have inconsistent interfaces that require careful handling to maintain application consistency.strands-agents/sdk-python5 discussions
- Name for semantic meaningChoose names that clearly convey the semantic meaning and purpose of the identifier, rather than using clever or ambiguous names. Names should be explicit and descriptive enough that their purpose is immediately clear to readers.rust-lang/rust5 discussions
- Document lock behaviorWhen implementing or documenting synchronization primitives, always clearly specify how locks behave under exceptional conditions, particularly during thread panics. This information is critical for developers to write robust concurrent code.rust-lang/rust5 discussions
- Benchmark before optimizing codeAlways validate performance optimizations with benchmarks before implementation. Ensure measurements account for: 1. Platform-specific characteristics (32-bit vs 64-bit)rust-lang/rust5 discussions
- Prevent null referencesUse defensive coding practices to prevent null reference exceptions by properly handling potentially null values throughout your code. 1. **Properly initialize objects** instead of using default values when instantiation is needed:dotnet/runtime5 discussions
- Maintainable test structureWrite tests that are maintainable, self-documenting, and that promote good testing practices: 1. **Use proper assertion mechanisms**: Prefer modern assertion patterns over legacy approaches. Use built-in assertion methods that clearly indicate what is being tested.dotnet/runtime5 discussions
- Document code meaningfullyProvide meaningful documentation that enhances code maintainability and understanding. Follow these practices: 1. **Explain the "why"** - Document complex or non-obvious code behavior with comments that explain reasoning, not just functionality:dotnet/runtime5 discussions
- Cache expensive computationsAvoid recomputing expensive operations by caching results when they will be used multiple times. This applies to method calls, property access, and static property lookups. The performance impact of repeated calculations can be significant, especially in hot code paths.dotnet/runtime5 discussions
- Avoid busy waitingWhen implementing concurrent code that waits for conditions to be met, avoid busy-wait loops that continuously consume CPU resources. Busy-waiting wastes processing power, reduces overall system performance, and can increase power consumption.dotnet/runtime5 discussions
- Abstract traversal patternsWhen implementing algorithms that operate on complex data structures (trees, graphs, dominator structures), abstract the traversal mechanism from the operation performed at each node. Use visitor patterns or callbacks to separate concerns, making algorithms more maintainable and reusable.dotnet/runtime5 discussions
- Use descriptive identifiersAvoid abbreviations in variable, parameter, and method names to improve code readability and maintainability. Use descriptive identifiers that clearly indicate the purpose and content of what they represent.astral-sh/ruff5 discussions
- Profile allocations before optimizationBefore implementing data structures or algorithms, analyze allocation patterns and optimize for common cases. Key strategies: 1. Use fixed-size arrays for known small collections:astral-sh/ruff5 discussions
- Document component behavior comprehensivelyDocumentation should clearly explain the purpose, behavior, and relationships between code components using accessible terminology. This helps other developers understand the code without needing to dig into implementations.astral-sh/ruff5 discussions
- Consider algorithmic complexity tradeoffsWhen implementing algorithms or data structures, carefully evaluate the tradeoffs between computational complexity, memory usage, and code maintainability. Consider:astral-sh/ruff5 discussions
- validate configuration schemasAlways validate configuration objects using proper schema validation (like Zod) before type casting or using the configuration values. Avoid unsafe type casting from input types to output types without validation, as this can lead to runtime errors when expected properties are undefined.TanStack/router5 discussions
- validate before accessingAlways validate that values exist and have expected properties before accessing them, especially when removing non-null assertions or performing type casting. Avoid making assumptions about value presence or type safety without explicit checks.TanStack/router5 discussions
- Use parameterized testingWhen testing multiple scenarios with similar logic, use your testing framework's built-in parameterized testing features (`test.each`, `describe.each`, `it.each`) instead of manual `forEach` loops or duplicated test functions. This approach reduces code duplication, improves readability, and makes it easier to add new test cases.TanStack/router5 discussions
- Maintain comprehensive documentationWhen making code changes, ensure all relevant documentation is updated comprehensively across different formats and locations. This includes: 1. **JSDoc comments** for functions, especially internal APIs that need usage contextTanStack/router5 discussions
- explicit error type handlingHandle errors with explicit type checking and intentional decisions rather than generic catch-all approaches. This improves error handling precision and makes error recovery logic clearer.TanStack/router5 discussions
- Configuration option consistencyEnsure configuration options follow consistent naming conventions and are documented accurately. Use "default" prefix for options that can be overridden at more specific levels (e.g., `defaultOutputPath` instead of `outputPath`). Document only public APIs - avoid documenting internal or experimental configuration options that are not yet part of the public...TanStack/router5 discussions
- Write resilient test assertionsWrite test assertions that are resilient to implementation changes by focusing on behavior rather than implementation details. Avoid exact matches when partial or behavioral assertions would suffice.RooCodeInc/Roo-Code5 discussions
- Use structured loggingReplace direct `console.log`, `console.warn`, and `console.error` calls with a centralized logging abstraction. This ensures logs are consistently formatted, properly categorized by severity, and can be filtered or disabled in production environments.RooCodeInc/Roo-Code5 discussions
- Prevent duplicate keysAlways ensure configuration files, especially JSON files, have unique keys. Duplicate keys can cause unpredictable behavior as the last occurrence of a key will overwrite previous values, potentially leading to runtime errors or inconsistent application behavior.RooCodeInc/Roo-Code5 discussions
- Extract shared code patternsIdentify and extract duplicate code patterns into shared utility functions to improve maintainability and reduce redundancy. When similar logic appears in multiple places, create a reusable function in a shared utility file.RooCodeInc/Roo-Code5 discussions
- Performance-first StructureWhen optimizing, treat performance as a design constraint: prevent contention/cache inefficiency, ensure server-side work is bounded per call, and keep tests from becoming slow bottlenecks.redis/redis5 discussions
- Consistent TTL Pre-checkWhen handling TTL/expiration, decide “already expired?” (and validate expiry inputs) before performing DB mutations or expensive work, and then keep DB changes, stats/counters, and keyspace notifications consistent with the real outcome. For conditional variants (NX/XX, ENX/FNX/FXX), short-circuit behavior must match the condition.redis/redis5 discussions
- Consistent Clear NamingUse naming that is (1) safe per language rules, (2) semantically explicit, and (3) consistent with existing symbol families. Practical checklist: - Avoid reserved/unsafe identifier patterns. In C/C++, don’t introduce names starting with `_[A-Z]` (rename instead).redis/redis5 discussions
- Clear API ContractsPublic APIs must make their guarantees and caller responsibilities explicit—especially around encapsulation, lifecycle/ownership, and callback semantics.redis/redis5 discussions
- maintain naming consistencyEnsure consistent naming conventions across the entire codebase, including terminology, file names, directory structures, and API naming. Inconsistent naming creates confusion and poor developer experience.remix-run/react-router5 discussions
- dependency version rangesWhen configuring dependencies in package.json, use version ranges that maintain backwards compatibility and follow semantic versioning principles. For peer dependencies, prefer ranges that support multiple major versions when possible to avoid forcing consumers to upgrade unnecessarily.remix-run/react-router5 discussions
- Configure rendering modes clearlyEnsure clear distinction and proper handling between different rendering modes (SSR, SSG, SPA) with appropriate conditional logic for each mode's specific requirements.remix-run/react-router5 discussions
- API naming consistencyEnsure related APIs use consistent naming patterns, parameter structures, and calling conventions across the codebase. When introducing new APIs alongside existing ones, maintain naming consistency to provide clarity and reduce cognitive load for developers.remix-run/react-router5 discussions
- validate before accessingAlways validate parameters for both null values and correct types before accessing their properties or methods. Provide safe fallback values when validation fails to prevent crashes and undefined behavior.facebook/react-native5 discussions
- Prefer micro-optimizationsApply small performance improvements that accumulate to significant gains. Focus on efficient memory usage, API choices, and avoiding unnecessary operations.facebook/react-native5 discussions
- Early returns prevent wasteAdd early return statements and duplicate checks to avoid unnecessary computations, memory allocations, and API calls. This pattern prevents performance degradation by stopping expensive operations before they begin.facebook/react-native5 discussions
- Document configuration logicAlways add clear, explanatory comments for conditional configuration logic, architectural decisions, and platform-specific handling. Configuration code often involves complex decision trees, temporary solutions during transitions, and platform-specific workarounds that may not be immediately obvious to other developers.facebook/react-native5 discussions
- avoid Hungarian notationDo not use Hungarian notation prefixes (like `m`, `s`) in variable and field names. Use descriptive, semantic names that clearly indicate the variable's purpose without encoding type or scope information in the name.facebook/react-native5 discussions
- Write complete API examplesAlways provide complete, context-rich code examples in API documentation. Examples should show the full usage context and avoid abbreviated or partial code snippets that may confuse developers.rails/rails5 discussions
- Place configurations appropriatelyChoose the right location and scope for your Rails configuration options to improve maintainability and clarity: 1. **Use appropriate namespaces** - For truly global configurations, place them on the module rather than on a specific class:rails/rails5 discussions
- Initialize nil-prone variablesAlways initialize variables that might be nil to appropriate default values to prevent unexpected behavior. For boolean flags, explicitly initialize to false in constructors or initialization methods:rails/rails5 discussions
- Typed API ContractsFor each API endpoint, treat the request as a strict contract: define a dedicated typed request model for the exact payload shape, validate required inputs early, and keep auth/tenant scoping and client URL construction consistent.infiniflow/ragflow5 discussions
- Safe configuration changesWhen updating configuration/env logic, treat it as compatibility-sensitive: preserve existing default behavior and env var formats, avoid enabling config blocks that silently change runtime semantics, and ensure config typing and dependent settings stay consistent.infiniflow/ragflow5 discussions
- Portable Config ManagementWhen changing configuration, treat runtime configuration as the source of truth and avoid embedding/duplicating settings. Apply these rules: 1) Prefer `.env` + `env_file: .env` and avoid duplicating the same variables in multiple places.infiniflow/ragflow5 discussions
- Extract Shared ValidationPrefer small shared helpers for repeated request parsing/validation, and use modern, consistent type annotations to keep code readable and uniform. Apply this when you see the same “get field → type-check → return error” logic duplicated across endpoints or functions.infiniflow/ragflow5 discussions
- Document Stable API ContractsAll API reference docs (and examples) must clearly define the *public* contract vs *temporary/hidden* behavior, and keep endpoint paths/query params and response fields consistent.infiniflow/ragflow5 discussions
- Deterministic Mapping PipelineWhen implementing parsing/storage/retrieval logic (or any pipeline with downstream queries), design the algorithm so that *representations, keys, and batching decisions are stable and consistent*:infiniflow/ragflow5 discussions
- Config Contracts And DefaultsTreat environment variables and configuration flags as a documented contract: the code must (1) read settings from the correct source with safe defaults, (2) make feature-flag behavior explicit (including what becomes a true no-op when disabled), and (3) validate any external runtime dependency that the integration relies on.infiniflow/ragflow5 discussions
- Evidence-grade TestingWhen adding or updating test/verification logic, treat the harness setup as part of the test and ensure the evidence is causally attributable and non-vacuous.QwenLM/qwen-code5 discussions
- Deterministic Set ReconciliationWhen you correlate agent outputs, commit history, or prior workflow state across time, avoid fuzzy matching and “best-effort” heuristics. Instead: 1) Associate via stable identifiers (IDs), not text substrings.QwenLM/qwen-code5 discussions
- Capability-Aware Interface ContractsWhen designing client-facing interfaces (request payloads, component props, or render-slot “host action” APIs), treat optional features and host-provided children as contracts—not assumptions.QwenLM/qwen-code5 discussions
- Use Suspense Only When ReadyIn Next.js SSR/app-router, do not use `useSuspenseQuery` unless your server prefetch + hydration setup guarantees the data is already in the cache such that the component will not suspend.tanstack/query5 discussions
- Use Angular v19+ StrictnessWhen targeting Angular v19+ (or modernizing to it), align your package peer/dependency baselines and update tsconfig to the corresponding strict compiler settings—then apply the same policy across all Angular examples.tanstack/query5 discussions
- Test error propagationWhen changing error handling, add/maintain tests that: - Cover all supported configuration shapes (e.g., `useErrorBoundary: true` and `useErrorBoundary: (err) => boolean`).tanstack/query5 discussions
- Scoped cache reset rulesWhen code triggers cache reset/refetch or relies on cached freshness, make the behavior intentionally scoped and snapshot-correct: - Scope reset-triggered refetches to the intended cache region:tanstack/query5 discussions
- Explicit Undefined DefaultsPrevent `undefined`/`void`/falsy values from becoming accidental runtime states. Apply these rules: 1. **Eliminate transient `undefined`**: If a value can be absent (e.g., localStorage, optional query data), wire an explicit `defaultValue` so hooks/state initialize to a concrete value and consumers never render an “undefined first frame”.tanstack/query5 discussions
- Explicit Error NarrowingWhen using data/mutation libraries, treat error handling as a two-step process: (1) type errors conservatively at the boundary, and (2) implement recovery/UI logic that matches the library’s actual error-state semantics.tanstack/query5 discussions
- Consistent readable patternsApply consistent, type-safe idioms and keep logic/formatting easy to scan. - Prefer the established guard/pattern style: ```ts // preferred if the surrounding code uses boolean guardstanstack/query5 discussions
- Configuration Version IsolationWhen changing package/tooling configuration (peer deps, TS/ESLint parser versions, tsup/esbuild settings, or feature/behavior flags), make version and behavior control explicit and isolated so CI/build/tests don’t break unexpectedly.tanstack/query5 discussions
- Prefer Optional over nullsUse Java's Optional API instead of null checks to improve code readability, safety, and maintainability. When dealing with potentially absent values: quarkusio/quarkus5 discussions
- Optimize algorithmic operationsBefore implementing or modifying algorithms, carefully evaluate data structure properties and operation costs. Always: 1. **Understand data structure guarantees**: Choose structures that provide the necessary ordering and performance characteristics. For instance, when replacing one structure with another, be aware of their different behaviors:quarkusio/quarkus5 discussions
- Name for meaning firstChoose names that prioritize domain meaning and clarity over implementation details. This applies to methods, variables, constants, and configuration properties. Names should be immediately understandable to developers working in the domain, without requiring knowledge of the underlying implementation.quarkusio/quarkus5 discussions
- Document public APIsAll public APIs, interfaces, and methods should include comprehensive JavaDoc that clearly explains their purpose, parameters, return values, and any non-obvious behaviors. This is especially important for:quarkusio/quarkus5 discussions
- Clear database configuration examplesDatabase configuration examples in documentation should be correct, minimal, and include proper context. Provide only essential configuration properties rather than defaults or environment-specific values that would change in production. Use proper syntax and be precise about component interactions.quarkusio/quarkus5 discussions
- Use higher-level iterationsWhen working with multiple sequences that need to be combined, prefer higher-level iteration abstractions over nested loops. This improves code readability, reduces nesting depth, and helps prevent logical errors when managing multiple iterative dimensions.pytorch/pytorch5 discussions
- Prevent null pollutionDesign your code to minimize the unexpected introduction of None values into data structures and APIs. Use immutable parameter types when you don't need to modify the input, and be explicit about nullable types to establish clear contracts.pytorch/pytorch5 discussions
- Handle errors specificallyAlways be explicit and specific when handling errors rather than using catch-all approaches or implicit conventions. This improves code robustness, debuggability, and maintainability.pytorch/pytorch5 discussions
- Robust error messagingCreate clear, specific, and actionable error messages that help users understand and resolve issues, while implementing defensive error handling to maintain system integrity. Follow these principles:pydantic/pydantic5 discussions
- Eliminate redundant computationIdentify and eliminate redundant or duplicate computation paths in your code, especially for expensive operations like schema generation, type resolution, or recursive traversals. This improves performance and reduces resource usage.pydantic/pydantic5 discussions
- Cache expensive computationsImplement strategic caching and memoization for expensive or frequently repeated computations to avoid redundant work. This can significantly improve performance in hot code paths.pydantic/pydantic5 discussions
- Secure authentication flowsImplement authentication flows that protect sensitive information and follow secure credential management practices: 1. **Prevent domain enumeration attacks** by returning consistent responses regardless of whether the input (like domain name) is valid:prowler-cloud/prowler5 discussions
- Safe attribute access patternsImplement consistent patterns for safely accessing potentially null or undefined attributes and dictionary values. This prevents runtime errors and makes code more robust.prowler-cloud/prowler5 discussions
- Prioritize code readabilityWrite code that optimizes for human readability and understanding. Complex expressions, while technically correct, can become difficult to understand and maintain over time.prowler-cloud/prowler5 discussions
- Consistent naming patternsFollow systematic naming conventions for types, interfaces, and functions to enhance code readability and navigability: ### Type/Interface Naming - `*Data`: Full API models with `id`, `type`, `attributes`, `relationships` (e.g., `RoleData`)prowler-cloud/prowler5 discussions
- Null-safe value handlingWhen a value may be null, undefined, or structurally different than expected (e.g. legacy/persisted data, external input, or an intentionally empty override), don't assume its shape or truthiness — check explicitly and fail safe.promptfoo/promptfoo5 discussions
- Isolate test side effectsTests must not leak global or shared state across runs, and must not depend on execution order. Before mutating anything shared with the rest of the process — signal listeners (`SIGTERM`/`SIGINT`/`beforeExit`), module-level caches, environment variables, or mocks — snapshot the prior state in `beforeEach`/setup and restore it in `afterEach`/`finally`, even...promptfoo/promptfoo5 discussions
- Explicit null/type validationWhen consuming loosely-typed or external data (parsed JSON, optional fields, etc.), never rely on Python truthiness to decide whether a value is "present" or "valid" — it conflates `None`/missing with legitimate falsy values (e.g. `0`, `""`, `[]`) and can let malformed data through un-validated. Instead:promptfoo/promptfoo5 discussions
- Ancestor-stack cycle detectionWhen writing recursive algorithms that walk graph-like or tree-like data (deep clone, serialization, search), distinguish "this object is one of the current recursion's ancestors" (a real cycle) from "this object was visited somewhere else in the structure" (a legitimate shared/non-cyclic reference). Using a single global `WeakSet`/`Set` of visited nodes...promptfoo/promptfoo5 discussions
- simplify test structureWrite tests that are direct, focused, and free of unnecessary complexity. Remove redundant test fields, use direct assertions with expected values, and leverage existing fixtures instead of creating temporary content.prometheus/prometheus5 discussions
- explicit test assertionsTests should explicitly assert both positive and negative expectations to make test intentions clear and prevent regressions. Use the `expect` syntax to specify not only what should happen, but also what should NOT happen in your tests.prometheus/prometheus5 discussions
- avoid panics gracefullyNever use panic() for error handling in production code paths, especially in core engine components. Instead, handle errors gracefully by returning appropriate values or ignoring problematic data with optional warnings.prometheus/prometheus5 discussions
- Avoid unnecessary allocationsMinimize memory allocations by avoiding intermediate objects, sharing underlying buffers, and eliminating unnecessary array operations. This is particularly important in hot code paths and when processing large datasets.prisma/prisma5 discussions
- validate configuration valuesAlways validate configuration values and provide clear, actionable error messages when validation fails. Handle invalid values gracefully by either ignoring them or providing sensible defaults, and validate that configuration options are used in the correct context.prettier/prettier5 discussions
- Modern configuration formatsPrefer ES module configuration files with TypeScript annotations over JSON formats for better developer experience and tooling support. Use `.js` or `.mjs` extensions with proper type annotations to enable IDE autocompletion and type safety.prettier/prettier5 discussions
- Add explanatory commentsAdd explanatory comments for complex logic, special cases, or non-obvious code behavior. Comments should explain the "why" behind the code and "what" specific conditions or syntax patterns are being handled.prettier/prettier5 discussions
- Provider-aware API contractsExternal API calls must be routed and shaped using provider/version-aware logic derived from immutable inputs (before any mutation), and idempotency keys must use stable identifiers.the-pr-agent/pr-agent5 discussions
- Isolated, Deterministic TestsTests should be deterministic and non-leaky: any test that depends on (or mutates) global state, environment variables, or import-time configuration must isolate that impact and restore it afterward.the-pr-agent/pr-agent5 discussions
- Config precedence consistencyFor configuration-driven code (especially anything that affects user-facing URLs, published links, secrets, or server startup), centralize resolution and make precedence explicit.the-pr-agent/pr-agent5 discussions
- Maintain naming consistencyEnsure consistent naming conventions, terminology, and identifiers across the entire codebase. Names should be uniform between frontend/backend, across different modules, and within the same domain.PostHog/posthog5 discussions
- eliminate code duplicationActively identify and eliminate code duplication in all its forms to improve maintainability and reduce bugs. This includes removing redundant conditional checks, extracting common functionality into reusable functions, and avoiding component or logic duplication.PostHog/posthog5 discussions
- Cache expensive operationsIdentify and eliminate redundant expensive operations by implementing caching, memoization, or conditional execution. Look for repeated database queries, complex calculations, object creation, or data processing that can be cached or avoided entirely when not needed.PostHog/posthog5 discussions
- break down large functionsLarge functions that handle multiple responsibilities should be decomposed into smaller, focused functions to improve readability, maintainability, and facilitate code reviews.PostHog/posthog5 discussions
- Hide implementation detailsDesign public APIs to hide implementation details and focus on the user's mental model of the system. Avoid exposing internal classes, implementation-specific parameters, or technical approaches that might change in the future.pola-rs/polars5 discussions
- Explicit configuration precedenceImplement a clear configuration resolution chain that follows a consistent precedence pattern: explicit parameters first, then environment variables, then default values. This ensures predictable behavior and proper respect for user-provided settings at different levels.pola-rs/polars5 discussions
- Evaluate algorithmic complexity tradeoffsWhen implementing algorithms, carefully evaluate tradeoffs between performance optimizations and code maintainability. Consider: 1. Early vs Late Optimization:pola-rs/polars5 discussions
- Documentation clarity standardsEnsure documentation is grammatically correct, clearly structured, and uses precise terminology. Avoid verbose or repetitive explanations, and provide specific details that help users understand exactly what will happen.python-poetry/poetry5 discussions
- Configure HTTP requests properlyWhen making HTTP requests, use standard library enums for status codes, set appropriate timeouts, and handle redirects efficiently. Avoid raw status code numbers in favor of HTTPStatus enums for better readability and maintainability. Always configure timeouts to prevent indefinite hanging, preferably making them configurable via environment variables with...python-poetry/poetry5 discussions
- Synchronous event handlersKeep event handlers synchronous to prevent race conditions and timing issues. Async operations within event handlers can cause deadlocks, missed events, and unpredictable behavior.microsoft/playwright5 discussions
- comprehensive test coverageTests should be comprehensive and cover edge cases, complete scenarios, and use specific assertions rather than generic checks. When writing tests, include multiple test cases that validate different states, use precise count assertions instead of simple visibility checks, and ensure all relevant interactions are tested.microsoft/playwright5 discussions
- API parameter clarityDesign API parameters to be self-documenting and minimize cognitive overhead. Avoid boolean parameters in favor of descriptive enums or string literals, leverage type inference where possible, and prefer clean parameter passing over state mutation patterns.microsoft/playwright5 discussions
- Respect config precedenceWhen configuration can vary by user/environment, resolve it deterministically (following documented precedence), keep it configurable instead of hardcoded, and apply it dynamically if it may change at runtime.earendil-works/pi5 discussions
- Prefer cohesive modulesKeep the repository’s module structure and implementations cohesive and non-redundant. Apply these rules: - **Don’t add “single-purpose” files for trivial helpers**: if a function belongs next to its call site (or in an existing utility module), move it there instead of creating a standalone file.earendil-works/pi5 discussions
- preserve exception contextWhen handling exceptions, preserve the original exception context and provide clear, actionable error information. Avoid creating new exceptions that lose important details from the original error, and replace generic error handling (like assertions) with specific, user-friendly messages.emcie-co/parlant5 discussions
- Names reflect exact purposeChoose names that precisely reflect the component's purpose and behavior, avoiding ambiguous terms or shortcuts. Names should be self-documenting and consistent with related components.emcie-co/parlant5 discussions
- LLM provider abstractionWhen integrating with different LLM providers, create proper base class abstractions that filter and validate parameters based on each provider's capabilities. Follow established architectural patterns rather than creating custom configuration approaches.emcie-co/parlant5 discussions
- Document with examplesAlways include clear, contextual examples when documenting APIs, interfaces, or command-line functionality. Examples significantly improve understanding and reduce ambiguity, particularly for new or complex features. Maintain consistent terminology throughout documentation, avoiding unexplained jargon or abbreviations.opentofu/opentofu5 discussions
- Defensive null handlingAlways initialize data structures before use, particularly before accessing them in loops or conditional blocks. Check for null values before accessing their properties, and provide clear, contextual error messages when null values are not allowed.opentofu/opentofu5 discussions
- Clear concise documentationWrite documentation that is direct, consistent, and appropriately detailed. Follow these principles: 1. **Use direct language** - Prefer straightforward assertions over gentle phrasing. Instead of "Please be cautious when..." use "Use caution when..." or simply state facts and instructions directly.opentofu/opentofu5 discussions
- Optimize configuration structureStructure configuration files like tox.ini to maximize maintainability and efficiency. Use factor prefixes (e.g., "test-opentelemetry:", "lint:") to install packages only for specific environments, avoiding unnecessary dependencies. When naming environments, avoid characters that have special meaning in the tool (e.g., use "precommit" instead of...open-telemetry/opentelemetry-python5 discussions
- Handle exceptions appropriatelyWhen implementing error handling logic, be deliberate about which exception types you catch and where you handle them. 1. **Catch `Exception`, not `BaseException`** - Classes that directly inherit from `BaseException` (like `GeneratorExit` or `KeyboardInterrupt`) are not technical errors and should generally propagate:open-telemetry/opentelemetry-python5 discussions
- Follow Python naming conventionsUse consistent Python naming conventions to improve code readability and maintainability: 1. Use snake_case for functions and variables: ```python # Badopen-telemetry/opentelemetry-python5 discussions
- Configuration source precedenceDefine and document a clear precedence order when configurations come from multiple sources (code parameters, environment variables, defaults). Typically, explicit parameters should take precedence over environment variables, which should take precedence over defaults.open-telemetry/opentelemetry-python5 discussions
- Use environment variablesMake configuration values configurable through environment variables with sensible defaults instead of hard-coding them. This improves flexibility and testability while maintaining backward compatibility.commaai/openpilot5 discussions
- use context managers concurrencyWhen working with concurrent operations involving shared resources or processes, use context managers and explicit synchronization to ensure proper cleanup and thread safety. This prevents resource leaks, race conditions, and ensures graceful shutdown even when operations are interrupted.commaai/openpilot5 discussions
- eliminate unnecessary codeRemove redundant code constructs and prefer concise, direct patterns that improve readability and maintainability. This includes eliminating unnecessary widget/layout creation, using ternary operators for simple conditionals, direct initialization patterns, and simplifying complex calculations with named constants.commaai/openpilot5 discussions
- Context-aware algorithm selectionChoose algorithms and data structures based on operational requirements and usage context rather than defaulting to familiar patterns. Consider factors like compilation timing, API constraints, and different execution contexts when making design decisions.opengrep/opengrep5 discussions
- Optimize memory allocation patternsPrefer efficient memory allocation patterns to improve performance. Key practices: 1. Use RAII containers (like Mat) instead of raw pointers to prevent memory leaksopencv/opencv5 discussions
- Optimize container accessChoose efficient container types and optimize access patterns in performance-critical code. Avoid operations that cause hidden allocations and minimize overhead when accessing container elements.opencv/opencv5 discussions
- Maintain code consistencyKeep code clean and consistent with established project conventions. This includes: 1. Follow existing formatting style in files: ```cpp // Follow Allman style if file uses itopencv/opencv5 discussions
- Guard optional dependenciesConfiguration management requires careful handling of optional dependencies in both build scripts and source code. Always guard code that depends on optional modules or libraries with appropriate feature guards, and check for component existence before using them.opencv/opencv5 discussions
- Cache validity and boundsWhen adding caching, ensure **(1) correctness via validity/refresh** and **(2) safety via bounds/staleness resistance**. ### 1) Align cache lifetime with real validityopenai/openai-python5 discussions
- Validate Config InputsAny configuration derived from environment variables or external config must be (1) wired to the correct runtime fields, (2) normalized/validated with safe defaults, and (3) applied with deterministic precedence.diegosouzapw/OmniRoute5 discussions
- Use idiomatic Go flowFollow Go's idiomatic control flow patterns to improve code readability and maintainability. Key practices include: 1. Prefer early returns over else blocksollama/ollama5 discussions
- Use environment variablesUse environment variables instead of hardcoding configuration values such as file paths, port numbers, or system-specific locations. This makes the code more flexible across different platforms, installation methods, and user preferences.ollama/ollama5 discussions
- Guard against nilAlways check for nil values and successful type assertions before accessing or dereferencing objects, especially when working with interfaces, type conversions, or functions that may return nil values.ollama/ollama5 discussions
- Document synchronization intentAlways clearly document the purpose and scope of synchronization primitives (mutexes, read-write locks) by: 1. Placing them directly adjacent to the data they protectollama/ollama5 discussions
- Comprehensive test coverageTest functions should provide comprehensive coverage of both expected and edge cases. Include tests for: 1. **Boundary conditions**: Test zero, minimum, maximum values, and other special cases.ollama/ollama5 discussions
- Clear recoverable error messagesError messages should be clear, actionable, and indicate whether recovery is possible. When designing error handling: 1. Use descriptive messages that explain what went wrong and how to fix itollama/ollama5 discussions
- Abstract model operations cleanlyWhen implementing AI model operations, create clean abstractions through interfaces that separate core mathematical operations from specific implementations. This enables:ollama/ollama5 discussions
- Match nullability to guaranteesNull/undefined checks, optional chaining, and non-null assertions must reflect the actual type contract and runtime invariants — not an assumed one. - Don't add defensive `?.`, `??`, or `!== undefined` checks for values the type system already guarantees are present. If `AssistantMessage.provider` is typed as required, `message.provider !== undefined` is...can1357/oh-my-pi5 discussions
- Match external config semantics exactlyWhen reading, writing, or transferring configuration governed by an external format or tool (e.g. git's config files), replicate that tool's full semantics rather than the common-case behavior, and cover each semantic edge case with a dedicated test. Config-file parsing has subtle rules that are easy to miss on a first pass: repeated keys must resolve using...can1357/oh-my-pi5 discussions
- Iterative, cycle-safe traversalWhen walking graph or tree structures whose depth or shape is attacker/user controlled (JSON-like payloads, recall graphs, nested message content), avoid naive recursive walks and naive cycle checks — both degrade from an engineering bug into an algorithmic complexity bug:can1357/oh-my-pi5 discussions
- Environment-driven config resolutionWhen behavior depends on environment variables or config files (e.g. git's `core.hooksPath`, `GIT_DIR`, `GIT_CONFIG*`), never assume an in-process reimplementation of the resolution rules is complete. Config can be layered and overridden through many sources — env vars, `~`/`%(prefix)%` expansion, system/global/local config, `-c` flags, wrapper scripts —...can1357/oh-my-pi5 discussions
- Discriminate error codes preciselyWhen catching errors from syscalls, spawned processes, or optional APIs, never collapse distinct failure modes into one generic catch. Check the specific error code/condition and handle only the exact case you mean to special-case; let anything else either propagate or be reported with its own precise status, instead of silently mapping it onto an unrelated...can1357/oh-my-pi5 discussions
- Design intuitive API methodsWhen designing API methods, prioritize intuitive usage patterns and backwards compatibility. Follow these guidelines: 1. Order parameters from required to optional, maintaining consistency across overloads:octokit/octokit.net5 discussions
- Verify configuration pathsEnsure configuration property paths are accurate and complete, especially for nested configurations and context-specific placement. Many configuration issues stem from incorrect or incomplete property paths that prevent features from working properly.nrwl/nx5 discussions
- Use nullish coalescing operatorsPrefer modern JavaScript nullish coalescing (`??`) and optional chaining (`?.`) operators over verbose conditional logic for handling null and undefined values. These operators provide cleaner, more readable code while maintaining null safety.nrwl/nx5 discussions
- minimize resource usageOptimize performance by being selective about resource consumption - process only necessary data, avoid redundant operations, and use lightweight alternatives when possible.nrwl/nx5 discussions
- Follow Vue API patternsAlways prefer Vue's native APIs and follow official Vue patterns instead of creating custom implementations. This ensures better compatibility, maintainability, and consistency with the Vue ecosystem.nuxt/nuxt5 discussions
- explicit response typesAlways specify explicit response types when making API calls, especially for prerendered routes or external APIs. In production environments, response headers may not be preserved as expected, leading to incorrect content-type detection that can break applications in unpredictable ways.nuxt/nuxt5 discussions
- Extract repeated patternsExtract repeated code patterns, CSS classes, and constants to improve maintainability and reduce duplication. When the same values, classes, or logic appear multiple times, consolidate them into reusable constants or utilities.novuhq/novu5 discussions
- Environment variable fallbacksAlways implement proper fallback chains for environment variables and handle missing configuration gracefully. When introducing new environment variables, maintain backward compatibility with existing ones, and apply environment-specific behavior conditionally to avoid issues across different deployment contexts.novuhq/novu5 discussions
- contextual API parametersDesign APIs to provide contextual information and adapt behavior based on current usage context. Pass context objects to callbacks, compute derived attributes based on state, and generate appropriate options dynamically.novuhq/novu5 discussions
- Use modern C++ featuresEmbrace modern C++20 features throughout the codebase to improve code readability, maintainability, and performance. Specifically: 1. Use condensed namespace syntax:nodejs/node5 discussions
- Thread-safe resource management patternsEnsure thread-safe access to shared resources while following proper resource management patterns. When implementing concurrent operations: 1. Prefer worker threads over process spawning for parallel tasksnodejs/node5 discussions
- Standardize null pointer checksAlways use standard null-checking patterns like CHECK_NOT_NULL for pointer validation instead of manual null checks. This ensures consistent error handling and improves code readability. For functions that may return null objects, consider using wrapper types like MaybeLocal to properly propagate null states.nodejs/node5 discussions
- Propagate errors with contextAlways propagate errors with their original context instead of swallowing them or throwing new errors that hide the original cause. This helps with debugging and allows proper error handling up the call stack.nodejs/node5 discussions
- Minimize configuration dependenciesKeep configuration dependencies minimal and platform-aware. Avoid including unnecessary configuration files or external tools that can introduce unpredictable behaviors or unrelated settings. For platform-specific code, use conditional compilation to ensure that components are only built and executed in relevant environments.nodejs/node5 discussions
- Follow consistent naming patternsMaintain consistent naming conventions throughout the codebase to improve readability and reduce confusion. Adhere to these guidelines: 1. **Function naming patterns**: Use established prefixes like `create` for factory functions, which accurately conveys their purpose and aligns with existing patterns.nodejs/node5 discussions
- Document with precise accuracyMaintain precise and accurate documentation through both JSDoc annotations and explanatory comments. Ensure all technical documentation matches the actual implementation, avoiding inconsistencies between code and documentation.nodejs/node5 discussions
- Behavior-focused test designTests should focus on verifying behavior rather than implementation details to ensure they remain robust during refactoring. Avoid dependencies on timers or internal code structure that can lead to flaky and brittle tests.nodejs/node5 discussions
- Write robust assertionsWhen writing tests, ensure assertions can handle non-deterministic content while providing clear failure context: use targeted assertions for non-deterministic content, use specialized tools like cheerio for DOM testing, and include contextual information in diagnostic tests.vercel/next.js5 discussions
- Optimize Next.js Resource UtilizationAs a code reviewer, I recommend the following practices to optimize resource utilization when implementing Next.js applications.vercel/next.js5 discussions
- Release resources consistentlyAlways ensure resources are properly released, especially in exception paths. Use try-finally blocks to guarantee cleanup of buffers, streams, and other resources even when errors occur.netty/netty5 discussions
- Use consistent curly bracesAlways use curly braces for conditional statements and loops, even for single-line bodies. This maintains consistency throughout the codebase and improves readability. Avoid inline conditionals.nestjs/nest5 discussions
- Strategic dependency configurationConfigure dependencies in package.json strategically based on how they're used in your project: 1. **Direct dependencies** - Only for packages required for normal operationnestjs/nest5 discussions
- Standardize null safety patternsUse modern JavaScript features and utility functions consistently for null/undefined checks. Prefer optional chaining (?.), nullish coalescing (??), and dedicated utility functions like isNil() over direct null checks or OR (||) operators.nestjs/nest5 discussions
- Preserve public API stabilityWhen modifying or extending public interfaces, ensure changes maintain backward compatibility and follow proper versioning practices. Key guidelines: nestjs/nest5 discussions
- Preserve API interface stabilityWhen modifying or extending public API interfaces, ensure backward compatibility and proper versioning. Follow these guidelines: 1. Make interface additions optional to avoid breaking changes:nestjs/nest5 discussions
- Modern null safety patternsLeverage modern JavaScript features and utility functions for safer null/undefined handling. This reduces code verbosity while improving reliability. nestjs/nest5 discussions
- Avoid testing anti-patternsEnsure your tests actually validate functionality by avoiding common testing anti-patterns: 1. **Don't mock what you're testing** - When testing a method, don't mock its implementation as this tests nothing meaningful:nestjs/nest5 discussions
- validate early, fail fastPerform comprehensive input validation and precondition checks at the beginning of functions, before executing any operations that could have side effects or modify system state. This prevents partial execution, inconsistent states, and resource leaks when validation fails.neovim/neovim5 discussions
- Provide helpful documentation contextDocumentation should include sufficient context, practical examples, and helpful hints to make it truly useful for developers. Avoid assuming users have background knowledge - explain concepts, provide examples, and mention related functionality.neovim/neovim5 discussions
- prefer concise expressionsWrite concise, readable code by choosing the most direct expression for simple operations. Use ternary operators for simple boolean assignments instead of verbose if-else blocks, but avoid unnecessary ternaries when direct boolean assignment works. Return comparison results directly rather than using intermediate variables or verbose conditional blocks.neovim/neovim5 discussions
- Use descriptive identifiersChoose clear, meaningful names for variables, parameters, and constants that convey their purpose without requiring additional documentation or context.neondatabase/neon5 discussions
- Stage configuration changes graduallyWhen introducing configuration changes that affect multiple system components, implement them in stages to ensure smooth transitions and backward compatibility. Follow these steps:neondatabase/neon5 discussions
- Hierarchical semantic namingUse hierarchical prefixes and clear descriptive names to indicate the domain, source, and purpose of code elements. This improves code organization, searchability, and helps maintain consistency across the codebase.neondatabase/neon5 discussions
- Flexible documented configurationsCreate configuration interfaces that are flexible, well-documented, and future-proof. When designing configuration parameters: 1. **Prefer flexible parameterization** - Use functions/interfaces with optional parameters and sensible defaults rather than separate specialized functions for related configuration operations.neondatabase/neon5 discussions
- Document concurrency design decisionsAlways document key concurrency design decisions in code, including: 1. Locking protocols and ordering between multiple locks 2. Assumptions about data access patterns and thread safetyneondatabase/neon5 discussions
- Design metrics for insightsDesign metrics that provide actionable insights while maintaining system efficiency. Follow these key principles: 1. Track success and failure counts instead of just total counts to enable error rate calculationsneondatabase/neon5 discussions
- Comprehensive code documentationProperly document code with clear, accurate, and useful comments using the correct syntax based on context: 1. Use `///` to document items (structs, functions, etc.) that follow the comment:neondatabase/neon5 discussions
- Stable Public API SurfaceWhen modifying or adding exported interfaces in public headers, ensure the external API surface is stable, easy to use across platforms/languages, and does not leak internal implementation details.Tencent/ncnn5 discussions
- Semantic Collision-Safe NamingAll identifiers should be (1) semantically clear, (2) consistent with project naming patterns, and (3) collision-safe. Apply this checklist: - Prefer clear, domain-meaningful names for configuration fields (avoid ambiguous terms like `resize_type` when the concept is “mode/sample_type”).Tencent/ncnn5 discussions
- Platform-correct CI PipelinesEnsure CI/CD workflows build, test, and package artifacts in a way that is correct for each target platform/architecture—without running irrelevant jobs.Tencent/ncnn5 discussions
- Null-safe checksMake null/empty handling explicit and safe—so empty values don’t break logic or even generate invalid syntax, and raw null-pointer checks are replaced with semantic, invariant-based checks.Tencent/ncnn5 discussions
- Inference Compatibility RulesEnsure layer math, parameter semantics, and model conversion/backends remain consistent so inference results don’t silently change. Apply these rules:Tencent/ncnn5 discussions
- Avoid Performance PessimizationWhen optimizing for CPU/GPU speed, don’t accidentally remove fast paths via build/toolchain settings, and don’t add expensive memory-access patterns in the hottest kernels.Tencent/ncnn5 discussions
- Idiomatic Readable FormattingWhen touching code that formats output or builds paths, keep it idiomatic and repo-consistent: - Avoid inline conditionals inside large f-strings; precompute conditional fragments and interpolate them.karpathy/nanochat5 discussions
- Validate API data contractsAlways validate API request and response data using schema validation to ensure type safety and prevent runtime errors. Define explicit schemas (e.g., using Zod or similar) for all API interfaces rather than relying on TypeScript types alone.n8n-io/n8n5 discussions
- Optimize loop operationsAvoid repeated computations and object creation in loops or high-frequency operations. Move invariant calculations outside the loop and reuse objects rather than creating new instances on each iteration. This reduces CPU overhead, memory churn, and improves performance in critical code paths.n8n-io/n8n5 discussions
- Manage database connectionsAlways properly manage database connections to prevent resource leaks and improve application stability. Implement these key practices: 1. Release connections back to the pool after use with a try/finally blockn8n-io/n8n5 discussions
- Use intent-revealing namesChoose names that clearly reveal the purpose, behavior, or type of the code elements they represent. A good name should answer "what" rather than "how" and should be precise enough to avoid ambiguity.apache/mxnet5 discussions
- Hybridization compatible operationsWhen implementing neural network models that will be hybridized for performance optimization, use operations that are compatible with symbolic execution to avoid runtime errors. Hybridization converts imperative code to symbolic for better inference performance, but requires special handling of certain operations.apache/mxnet5 discussions
- Explain optimization mechanismsWhen implementing or documenting performance optimizations, clearly explain the mechanism and expected performance benefit. For memory-bound optimizations, specify exactly how memory operations are reduced:apache/mxnet5 discussions
- Document all parametersAlways provide complete and accurate documentation for all function parameters, especially when adding new ones. Each parameter should have a clear description that explains its purpose, expected values, and behavior.apache/mxnet5 discussions
- preserve error contextWhen propagating errors through promise rejections, catch blocks, or error transformations, always preserve the original error information to maintain debugging context and error traceability.rocicorp/mono5 discussions
- minimize hot path allocationsReduce memory allocations and garbage collection pressure in frequently executed code paths. Object creation through functional methods like `Object.fromEntries()`, `map()`, and repeated `toString()` calls can cause significant performance degradation in hot paths.rocicorp/mono5 discussions
- avoid unnecessary computationsOptimize algorithms by eliminating redundant work and intermediate data structures. Look for opportunities to use lazy evaluation, conditional execution, and more efficient operations.rocicorp/mono5 discussions
- API consistency patternsMaintain consistent patterns across similar APIs to improve developer experience and reduce cognitive overhead. When designing related APIs, use factory patterns for shared contexts, consistent parameter structures, and uniform return types.rocicorp/mono5 discussions
- Add missing test coverageIdentify and address gaps in test coverage by requesting specific tests for untested functionality. When reviewing code changes, look for new features, complex logic, or critical interactions that lack corresponding tests. Focus on testing type inference, component interactions, edge cases, and different code paths.rocicorp/mono5 discussions
- Precise CI WorkflowsCI workflows should be precise, minimal, and predictable: - Trigger only when needed: narrow `on: pull_request.paths` (avoid overly broad selectors like `**/*.js` unless required). If the PR doesn’t touch dependency inputs, the lockfile validation workflow shouldn’t run.mermaid-js/mermaid5 discussions
- Options-Based API DesignWhen designing/typing internal and public APIs, keep signatures tight and future-proof: - Don’t pass parameters you don’t use. If `config` isn’t needed, remove it from the function signature (or make it optional only where truly required).mermaid-js/mermaid5 discussions
- Null-safe Input ContractsWhen handling possibly-null/undefined/empty inputs, be explicit about nullability and keep code aligned with the promised types/semantics. Practical rules:mermaid-js/mermaid5 discussions
- Identifier Naming ConsistencyUse naming that is explicit, consistent, and self-describing. Rules: - Avoid magic strings for statement/type/keyword values: create named constants (and reuse them).mermaid-js/mermaid5 discussions
- Explicit Null HandlingNull/undefined safety should prevent crashes *and* preserve correct semantics. Don’t hide missing required inputs with optional chaining or weak fallbacks.mermaid-js/mermaid5 discussions
- Deterministic Grammar ChangesWhen updating diagram parsers (Jison/Langium/Chevrotain), treat lexer/tokenization precedence as a compatibility contract: ensure changes don’t break existing inputs and that intended tokens are unambiguously chosen.mermaid-js/mermaid5 discussions
- Define Error Recovery PolicyWhen handling failures, classify them as **recoverable** vs **unrecoverable**, then apply a consistent rule: log with enough context, **continue only for recoverable side-effects**, and **fail fast with explicit (prefer custom) errors** for invalid/unknown inputs or internal invariants.mermaid-js/mermaid5 discussions
- Config must be consistentEnsure every rendering/utility path uses the correct configuration *namespace* and that config values are passed explicitly (not implicitly via global getters or captured/stale variables).mermaid-js/mermaid5 discussions
- Config-driven themingWhen rendering/layout is affected by configuration or theming, avoid magic numbers and ad-hoc config handling. Instead: - Use a centralized “effective config” helper for all config-derived decisions, including correct type coercion (e.g., treat `"false"` the same as `false`).mermaid-js/mermaid5 discussions
- Test isolation and assertionsWhen code under test uses shared mutable state (module globals, singletons, tool registrations) or introduces new public behaviors, unit tests must (1) assert meaningful outcomes/calls and (2) isolate themselves by resetting/restoring that shared state.awslabs/mcp5 discussions
- Configure CSS layersWhen integrating Material UI with other styling solutions like Tailwind CSS v4, proper configuration of CSS layers is essential to ensure correct style precedence and override behavior.mui/material-ui5 discussions
- Use semantic namingChoose names that clearly communicate purpose and align with established domain terminology. Prioritize semantic clarity over brevity, and ensure consistency with the codebase's vocabulary.mastodon/mastodon5 discussions
- Use contextually descriptive namesNames should clearly indicate their purpose and context to avoid confusion, especially when similar concepts exist in the same scope. Generic names like "api", "params", or "arg1" create ambiguity and make code harder to understand. Instead, use specific, meaningful identifiers that describe what they represent or do.mastodon/mastodon5 discussions
- Optimize database queriesWrite efficient database queries by leveraging proper indexes, using performance-optimized ActiveRecord methods, and avoiding unnecessary database operations. Key practices include:mastodon/mastodon5 discussions
- early nil validationCheck for nil values early in methods and handle them gracefully before they can cause runtime errors or trigger expensive operations. This prevents NoMethodError exceptions and improves performance by avoiding unnecessary processing.mastodon/mastodon5 discussions
- batch similar operationsWhen performing multiple similar operations (database queries, Redis calls, job enqueues, or data lookups), batch them together or eliminate redundancy to reduce overhead and improve performance.mastodon/mastodon5 discussions
- API parameter designDesign API parameters with clear intent, proper validation, and thoughtful default behaviors. Parameter names should reflect their purpose rather than their source (e.g., `include_original` instead of `client_type == 'editor'`). Always validate parameters through StrongParameters to prevent security issues, and carefully consider the implications of default...mastodon/mastodon5 discussions
- Structure documentation effectivelyDocumentation should prioritize clear organization with a logical flow to help developers find information quickly. Apply these practices: 1. Use descriptive headings and titles that directly communicate content purposemaplibre/maplibre-native5 discussions
- Self-documenting code namingMethod, parameter, and variable names should clearly describe their purpose and behavior, making code self-documenting. Choose names that indicate exactly what the code does and how it behaves with different inputs.maplibre/maplibre-native5 discussions
- Prefer safe null handlingUse explicit, safe practices when dealing with potentially null resources to prevent memory leaks and undefined behavior. Key guidelines: 1. **Use `nullptr` instead of `NULL`** in all C++ code, even when calling C functions:maplibre/maplibre-native5 discussions
- Document public API completelyAll public APIs (files in `include/`) must have comprehensive documentation using either Doxygen-style or triple-slash comments. Documentation should include:maplibre/maplibre-native5 discussions
- optimize algorithm performanceWhen implementing algorithms, prioritize performance optimization through careful algorithm selection, query structure, and evaluation strategy choices. Key considerations include:logseq/logseq5 discussions
- Defer expensive operationsAvoid performing expensive computations until they are actually needed, and eliminate redundant work in hot code paths. This includes delaying database pulls, moving expensive object creation outside functions, and removing unnecessary operations.logseq/logseq5 discussions
- Configuration option lifecycleWhen adding new configuration options, follow a systematic approach to ensure consistency and maintainability across the application. This prevents incomplete implementations that can break existing functionality or create inconsistent user experiences.logseq/logseq5 discussions
- API parameter consolidationWhen designing API functions with multiple parameters, consolidate optional or related parameters into a single options object to improve extensibility and maintainability. This pattern prevents function signatures from becoming unwieldy and allows for easier future parameter additions without breaking changes.lobehub/lobe-chat5 discussions
- Eliminate redundant operationsAvoid unnecessary function calls, I/O operations, and redundant checks that can significantly impact performance. Look for opportunities to consolidate operations, remove duplicate work, and streamline execution paths.LMCache/LMCache5 discussions
- Cache state consistencyEnsure cache operations maintain consistent state and handle shared resources properly throughout the cache lifecycle. This includes proper key type management, safe eviction of shared entries, and accurate state tracking across different operational phases.LMCache/LMCache5 discussions
- AI model architecture flexibilityAvoid hardcoding AI model-specific assumptions and instead design systems to be configurable across different model architectures, data types, and configurations. This ensures your AI systems can adapt to evolving model designs and support multiple model families without requiring code changes.LMCache/LMCache5 discussions
- Use descriptive semantic namesChoose specific, meaningful names that clearly convey purpose and follow established codebase patterns. Avoid generic terms that could apply to many different concepts.llvm/llvm-project5 discussions
- proper error propagationEnsure errors are properly propagated to callers rather than handled locally with exits or fatal errors. Library functions should return error information to allow callers to make appropriate decisions about error handling and recovery.llvm/llvm-project5 discussions
- minimize header dependenciesOrganize code to minimize header dependencies and improve compilation times. Use forward declarations instead of includes when possible, avoid unnecessary dependencies, and follow proper header organization patterns.llvm/llvm-project5 discussions
- Eliminate redundant null checksAvoid unnecessary null checks when the called function already handles null cases, and use references instead of pointers when null values are guaranteed not to occur.llvm/llvm-project5 discussions
- Design thoughtful API interfacesWhen designing APIs, prioritize clarity, appropriate abstraction levels, and user experience. Avoid magic numbers or unclear parameters by using named constants or helper functions. Choose the right balance between generic and specific interfaces - use specific types when the use case is well-defined, but design for genericity when supporting multiple...llvm/llvm-project5 discussions
- cost-based algorithmic decisionsWhen implementing algorithmic transformations and optimizations, use cost analysis and profitability heuristics to guide decision-making rather than applying transformations blindly. This includes choosing appropriate data structures based on access patterns, placing optimizations at the correct architectural level, and validating that algorithmic changes...llvm/llvm-project5 discussions
- use model metadataLeverage model metadata from GGUF format instead of hardcoded configuration values or filename-based logic. Model metadata provides authoritative information about model behavior and should be the primary source for configuration decisions.ggml-org/llama.cpp5 discussions
- optimize memory access patternsEnsure CUDA kernels use optimal memory access patterns to maximize performance. This involves several key practices: 1. **Use `__restrict__` qualifiers** on pointer parameters to inform the compiler that pointers don't alias, enabling better optimizations especially on older GPUs.ggml-org/llama.cpp5 discussions
- measure before optimizingAlways profile and measure performance impact before implementing optimizations, especially micro-optimizations. Many seemingly beneficial optimizations provide no measurable improvement and can hurt code maintainability.ggml-org/llama.cpp5 discussions
- AI parameter organizationEnsure proper organization and placement of AI model parameters, hyperparameters, and configuration options. Avoid parameter duplication by reusing existing values, and place parameters in their logically appropriate structures.ggml-org/llama.cpp5 discussions
- Use configuration helper utilitiesAlways use centralized helper functions for configuration management instead of direct environment variable access or hardcoded values. This ensures consistency, maintainability, and proper error handling across the codebase.BerriAI/litellm5 discussions
- Prefer generic API patternsAvoid creating provider-specific API implementations when generic, reusable solutions exist or can be developed. This principle improves code maintainability, reduces duplication, and ensures consistency across the API surface.BerriAI/litellm5 discussions
- background task coordinationWhen working with background tasks in async applications, ensure proper task lifecycle management and coordination to prevent memory leaks, race conditions, and resource conflicts.BerriAI/litellm5 discussions
- avoid expensive operationsIdentify and optimize resource-intensive operations in frequently executed code paths. This includes avoiding memory-doubling operations like `copy.deepcopy()` on large objects, preventing blocking I/O in async contexts, and eliminating expensive debug logging operations.BerriAI/litellm5 discussions
- API parameter consistencyEnsure consistent parameter naming, format, and usage across all API interfaces, documentation, and code examples. This includes maintaining uniform parameter names between SDK examples and proxy configurations, using correct environment variable names as specified in official documentation, and applying proper naming conventions for model identifiers and...BerriAI/litellm5 discussions
- Explicit API contractsRequire API types and public interfaces to express clear, enforceable contracts: guarantee invariants, normalize variant shapes, and make compatibility choices explicit.likec4/likec45 discussions
- Consistent, Guarded RankingWhen implementing sorting/ranking or token-based relevance in retrieval pipelines, treat the algorithm as a system with strict contracts: 1) Keep ranking features consistent across stagesmvanhorn/last30days-skill5 discussions
- Validate all inputsAll user-controlled inputs must be validated and sanitized before use to prevent injection attacks, unauthorized access, and other security vulnerabilities. This includes query parameters, environment variables, URLs, and database values.langfuse/langfuse5 discussions
- Use structured logging frameworkReplace all console.* calls with an appropriate structured logging framework using proper log levels. This ensures consistent logging patterns, better log management, and appropriate handling of different severity levels.langfuse/langfuse5 discussions
- Memoize computed valuesCache the results of expensive operations and component renders to avoid redundant calculations during re-renders. This improves application performance, especially when working with large datasets or complex transformations.langfuse/langfuse5 discussions
- Ensure deterministic query resultsAlways ensure database queries produce deterministic results by including explicit ORDER BY clauses when using LIMIT operations. This prevents unpredictable result ordering and potential data inconsistencies.langfuse/langfuse5 discussions
- Avoid array mutationsAlways clone arrays before performing operations that would mutate the original array, especially when working with component state or props. Direct mutations can cause subtle bugs and unexpected side effects in React applications.langfuse/langfuse5 discussions
- intentional error handlingMake deliberate, context-appropriate decisions about error handling strategy rather than applying generic patterns. Consider whether each error scenario should fail fast, provide graceful degradation, or offer recovery options based on the specific business impact and user experience requirements.langflow-ai/langflow5 discussions
- Validate untrusted inputAlways validate and sanitize user-provided inputs before using them in sensitive contexts like SQL queries, file paths, or URL requests. This prevents SQL injection, path traversal, SSRF, and similar attacks.langchain-ai/langchainjs5 discussions
- Throw meaningful errorsAlways throw specific, actionable errors instead of returning unexpected values or simply logging issues. Error messages should be clear, concise, and contain the exact reason for failure without redundancy.langchain-ai/langchainjs5 discussions
- Optimize model token usageImplement token-efficient patterns when working with AI models to optimize costs and performance. Key practices include: 1. Batch identical prompts into single API calls where supportedlangchain-ai/langchainjs5 discussions
- Follow documentation standardsEnsure all documentation follows established templates and includes required sections. When referencing components, add links to their documentation pages. Documentation for each component type (like LLMs or vector stores) should follow its specific template format and include standard sections such as "Overview" with links to conceptual guides and...langchain-ai/langchainjs5 discussions
- Scoped configuration defaultsWhen updating `pyproject.toml` (lint/type/dependency config), keep changes minimal and future-safe: enable/disable rules deliberately, scope suppressions to the smallest scope, avoid broad “select everything” patterns that can introduce unintended auto-fixes, remove redundant settings, and bound dependency versions.langchain-ai/langchain5 discussions
- Harden Untrusted InputsWhen code uses externally influenced data (URLs, hostnames, user-provided strings, identifiers) across trust boundaries, treat it as hostile and apply layered defenses:langchain-ai/langchain5 discussions
- Avoid Hidden Performance TrapsDefault rule: in performance-sensitive code, prevent hidden blowups and avoid expensive work being executed repeatedly in hot paths or on import. Apply this checklist:langchain-ai/langchain5 discussions
- Security Field ValidationWhen adding or modifying security-sensitive API fields (including fields written by schedulers/kubelets or reflected in Pod/Container security context), enforce the full security invariant end-to-end:kUbernetes/kUbernetes5 discussions
- Prefer early null returnsUse early return patterns with null checks to reduce nesting and improve code readability. Avoid unnecessary null checks for values that are guaranteed to be non-nil, and prefer length checks over nil checks for slices.kubernetes/kubernetes5 discussions
- Optimize search algorithmsImplement efficient search strategies that minimize computational overhead through proper ordering, early termination, and targeted scope reduction. This involves three key principles:kubernetes/kubernetes5 discussions
- Defaulting and DV RulesWhen evolving an API with new fields, treat defaulting/mirroring and declarative validation as a coupled compatibility problem. 1) Mirror/default fields must preserve client intentkUbernetes/kUbernetes5 discussions
- Algorithm invariants and orderingWhen implementing complex allocation/selection algorithms, require three things in code review: 1) **Explicit accounting invariants (no double-count / no negative “available”):**kUbernetes/kUbernetes5 discussions
- Use modern JavaScript idiomsFavor modern JavaScript syntax and clean code practices to improve readability and maintainability. This includes: 1. **Use template literals** instead of string concatenation for clearer string interpolation:kubeflow/kubeflow5 discussions
- Structured documentation with examplesCreate comprehensive documentation with clear structure and practical examples. Documentation should include: 1. **Standard documentation files** like README.md, CHANGELOG.md, and CONTRIBUTING.md, even if they primarily link to external resources. Search engines index these standard files, improving project discoverability.kubeflow/kubeflow5 discussions
- Standardize makefile patternsMaintain consistent Makefile patterns across all components to improve build reliability and developer experience in CI/CD pipelines. Key practices to follow:kubeflow/kubeflow5 discussions
- Environment variable managementManage environment variables in Docker configurations with appropriate scope, placement, and documentation: 1. **Set environment variables with appropriate scope**:kubeflow/kubeflow5 discussions
- Centralize configuration valuesStore all configuration values in dedicated configuration files rather than hardcoding them throughout the application. This makes the codebase more maintainable and reduces the need for code changes when configurations change.kubeflow/kubeflow5 discussions
- Consider operation time complexityWhen implementing operations that manipulate collections or perform repeated actions, carefully consider the time complexity implications. Avoid operations that could result in unexpected quadratic or worse complexity. Pay special attention to:JetBrains/kotlin5 discussions
- Validate Inputs SecurelyTreat runtime-derived values (env vars, request data, rendered attributes) as untrusted unless they’re validated by the framework’s schema/typedefs or hardened with allowlists.Kong/kong5 discussions
- optimize algorithmic complexityReplace inefficient algorithms with more optimal data structures and approaches to improve computational complexity. Look for opportunities to use appropriate data structures (like priority queues) instead of linear searches, avoid redundant iterations, and choose efficient traversal patterns.apache/kafka5 discussions
- Defensive null validationAlways validate null parameters and dependencies early with proper ordering to prevent NullPointerExceptions and provide clear error messages. Use defensive programming practices including parameter validation, method overloading instead of null parameter handling, and careful ordering of null checks.apache/kafka5 discussions
- API completeness validationEnsure APIs are complete by validating that all necessary cases are handled, all required arguments are properly validated, and response structures are consistent across similar operations.apache/kafka5 discussions
- Use type-specific variable namesUse distinct variable names that reflect their types to avoid confusion and make code intent clearer. Avoid reusing the same variable name for different types within the same scope or related functions.jj-vcs/jj5 discussions
- Consistent naming conventionsMaintain consistent naming and terminology throughout code and documentation. This includes proper capitalization of product names, technical terms, and consistent use of domain-specific vocabulary.jj-vcs/jj5 discussions
- eliminate code redundancyRemove duplicate imports, unused legacy code, and repetitive patterns to maintain clean, organized codebases. Extract commonly used functionality into utilities and avoid code duplication through proper abstractions. Use early returns to reduce nesting and improve readability.menloresearch/jan5 discussions
- network configuration consistencyEnsure network-related configurations remain consistent across different components and avoid unintended overwrites that could break connectivity or security.istio/istio5 discussions
- Conservative networking defaultsWhen configuring networking components, prefer stable and permissive defaults over restrictive or experimental configurations that may not work across all environments. This approach ensures broader compatibility and reduces the risk of breaking existing deployments.istio/istio5 discussions
- API compatibility preservationWhen evolving APIs, prioritize backward compatibility and avoid changing the semantics of existing fields. Instead of overloading existing fields with new meanings, introduce new fields to maintain compatibility with existing usage patterns.istio/istio5 discussions
- Validate tvg-id In DatabaseWhenever you edit an M3U/M3U8 playlist entry with a `#EXTINF` line, ensure the `tvg-id` is consistent with the canonical channel database. If the `tvg-id` you intend to use does not exist in the database, either (a) leave `tvg-id` empty to avoid invalid metadata, or (b) submit/add the missing channel to the database first. Also, don’t assume one feed...iptv-org/iptv5 discussions
- Structured logging best practicesUse structured logging with appropriate field types and context to make logs more useful for troubleshooting. Choose specific field types over generic ones, include relevant metrics, and select appropriate log levels based on information importance.influxdata/influxdb5 discussions
- Stable schema identifiersUse persistent identifiers for schema elements rather than relying on positional information or enumeration, which can break when schema changes occur. Assign unique, immutable IDs to database objects like tables and columns, and ensure these IDs remain stable throughout the object's lifecycle.influxdata/influxdb5 discussions
- Prefer explicit nullabilityAlways make nullable states explicit in your code by leveraging Rust's type system. Use `Option<T>` rather than sentinel values (like empty structs or default values) to represent potentially missing data. When handling options, prefer idiomatic patterns like `.map()` with `.unwrap_or()` for transforming with fallbacks. Consider specialized types like...influxdata/influxdb5 discussions
- Manage complete cache lifecycleImplement comprehensive cache lifecycle management focusing on three key aspects: 1. Idempotent Creation: Make cache creation idempotent by returning success for identical configurations and error only for conflicting ones. This enables reliable automation and prevents redundant cache instances.influxdata/influxdb5 discussions
- Maintain code readabilityEnsure code remains readable and maintainable by following these practices: 1. **Combine case statements with identical outcomes** to reduce duplication. When multiple cases have identical code blocks, group them together:influxdata/influxdb5 discussions
- Handle errors by criticalityChoose error handling strategies based on operation criticality: 1. For critical operations that could corrupt data or state: - Use assertions/panics to fail fastinfluxdata/influxdb5 discussions
- Descriptive semantic namingCreate identifiers that clearly convey meaning through descriptive names and appropriate types. Two key practices improve code readability and prevent errors:influxdata/influxdb5 discussions
- Clear configuration parametersConfiguration parameters should be descriptively named, well documented, and have sensible defaults that are visible to users. This makes your application more user-friendly and reduces confusion.influxdata/influxdb5 discussions
- Transactional verified migrationsEnhance database migration reliability by wrapping changes in transactions with pre-check and post-verification steps. This pattern prevents partial migrations that could leave your database in an inconsistent state.elie222/inbox-zero5 discussions
- Time precision mattersWhen implementing algorithms involving date and time calculations, maintain precise control over time components to avoid subtle bugs: 1. **Reset unwanted time components** - Always explicitly set seconds and milliseconds to zero when you only care about hours and minuteselie222/inbox-zero5 discussions
- Prevent async race conditionsAlways guard against race conditions when working with asynchronous code. Implement these patterns to avoid unpredictable behavior: 1. **Always await async operations**elie222/inbox-zero5 discussions
- Names reflect semantic purposeChoose names that reflect the semantic purpose rather than implementation details or temporal characteristics. Names should be consistent across the codebase and accurately represent their usage.elie222/inbox-zero5 discussions
- optimize computational efficiencyPrioritize algorithmic efficiency and avoid unnecessary computational overhead in performance-critical code paths. Look for opportunities to reduce time complexity and eliminate redundant calculations.hyprwm/Hyprland5 discussions
- Safe, configurable loggingLogging code—whether in middleware or reusable helpers—should be predictable, non-intrusive, and easy to format or disable. 1. Don't hardcode log statements inside library or helper functions that callers can't control. Instead, return a result and let the caller decide what/if to log:honojs/Hono5 discussions
- Propagate and clarify errorsWhen handling exceptions, only catch the specific error types your code is designed to handle, and always rethrow or otherwise propagate unexpected errors instead of swallowing them. Avoid pointless try/catch blocks that just rethrow the same error (`no-useless-catch`); prefer `try { return await promise } finally { ... }` when you only need cleanup logic:HONOJS/HONO5 discussions
- Consistent style conventionsFollow the project's established formatting conventions consistently, and when the linter and formatter disagree, resolve it explicitly rather than leaving noisy diffs or inconsistent code.honojs/hono5 discussions
- Cache header correctnessResponse objects obtained from `fetch` or the Cache API often have immutable headers, so caching middleware must never try to mutate them directly. Always construct a fresh `Response` (copying body/status/headers) before calling `.set()` or `.delete()` on its headers, e.g.:honojs/hono5 discussions
- Explicit Trust and ConsentWhen a security-related skill or script causes any external effect (sending data to third parties, spending funds, changing auth, or modifying security config), the implementation and docs must be explicit about (a) trust boundaries, (b) user-controlled/bounded authorization, and (c) safe, targeted, verifiable changes.nousresearch/hermes-agent5 discussions
- Optimization algorithm compatibilityWhen implementing or changing optimization code (samplers, objectives, and result selection), ensure algorithmic correctness, preserve sampler assumptions, and prefer explicit post-processing over ad‑hoc objective hacks.p-e-w/heretic5 discussions
- Accurate Error PropagationIn error-prone paths, do not “pretend success.” Always make the failure mode explicit to callers, and ensure any returned/serialized status reflects what actually happened.ogulcancelik/herdr5 discussions
- reduce nesting complexityPrefer code structures that minimize nesting levels and improve readability through early returns, pattern matching, and avoiding deeply nested assignments.helix-editor/helix5 discussions
- Follow established conventionsConfiguration settings should align with official language documentation and established community standards rather than arbitrary personal preferences. This applies to indentation styles, formatter configurations, and syntax requirements.helix-editor/helix5 discussions
- Safe, precise queriesWrite queries that are explicit, secure, and correctly typed. Specifically: - Never use `SELECT *`; enumerate the columns you actually need. If you must add a column to an existing query (e.g. `COALESCE(byok_enabled, false)`), take the opportunity to list out all other selected columns explicitly instead of relying on `*`.Helicone/helicone5 discussions
- Deliberate schema constraintsWhen writing migrations, define schemas deliberately and avoid redundant or speculative elements. Specifically: - Don't duplicate mechanisms: if a unique constraint already enforces uniqueness, don't also create a separate unique index for the same columns.Helicone/helicone5 discussions
- Centralize model-specific logicAvoid hardcoding model IDs, provider formats, or model-family checks directly in business logic; this creates duplicated knowledge that drifts out of sync and breaks when new models or providers are added. Prefer a centralized model registry or typed provider enum as the single source of truth for model IDs, response formats, and usage/pricing structures,...Helicone/helicone5 discussions
- Standardize observability semantic conventionsWhen implementing observability features (logs, metrics, traces), use consistent semantic conventions to ensure data can be correlated and analyzed efficiently across the entire system.grafana/grafana5 discussions
- Proper shell quotingAlways use proper quoting in shell scripts (especially GitHub Actions workflows) to prevent word splitting, globbing, and ensure correct variable expansion:grafana/grafana5 discussions
- Function design principlesDesign functions for maximum reusability, clarity, and maintainability. Follow these principles: 1. **Pass complete objects instead of extracted properties**: When a function needs to extract multiple properties from an object, pass the whole object rather than individual properties. This makes the function more composable and easier to reuse in different...grafana/grafana5 discussions
- Close resources with errorsAlways close resources (files, streams, connections) and properly handle their Close() errors. For read operations, Close() errors can be ignored if the primary operation (like JSON parsing) succeeded. For write operations, always check and propagate Close() errors.grafana/grafana5 discussions
- Verify configuration documentationEnsure all configuration documentation accurately reflects actual system behavior, available options, and correct command syntax. Configuration errors in documentation lead to broken user setups and erode trust.block/goose5 discussions
- Readable Maintainable CodeWrite Rust code so its intent is clear at a glance and responsibilities are placed correctly. Apply this checklist: - Remove redundant comments when the code is already self-explanatory.aaif-goose/goose5 discussions
- Migration consistency rulesWhen changing config schemas, treat migrations as part of the API contract: migrations must be safe under partial/legacy states and must not cause read/write skew that overwrites migrated data.aaif-goose/goose5 discussions
- Deterministic normalization predicatesWhen transforming, sorting, deduplicating, or merging structured data, ensure comparisons use domain-correct semantics and identity signals are preserved.aaif-goose/goose5 discussions
- Contract-first API designWhen designing or consuming client/server APIs, keep the contract explicit and prevent duplicate logic/types from drifting. Apply this standard: - **Single source of truth:** If the backend persists/owns a value, the UI should display it directly—avoid re-adding client fallbacks that recreate the same logic.aaif-goose/goose5 discussions
- Canonicalize and Disambiguate IdentifiersEnsure every place that *stores, looks up, validates, or returns* provider/model/function identifiers uses a clear internal naming contract: - **Canonicalize before lookup:** strip known version/date/suffix patterns from externally supplied model ids before querying registries (so variants like `-latest`, `-0709`, or Bedrock `-vN(:M)?` resolve to the same...aaif-goose/goose5 discussions
- Use if-unwrap with optionalsAlways use Zig's if-unwrap pattern (`if (optional) |value| {...}`) when working with optional values instead of forced unwrapping with `.?`. This pattern is safer as it avoids runtime panics, more readable, and aligns with Zig's idioms for null safety.ghostty-org/ghostty5 discussions
- Use specific configuration patternsWhen defining exclusion patterns, file filters, or other configuration rules, use specific, targeted patterns rather than broad glob patterns. Overly broad patterns can lead to unintended exclusions and hard-to-debug issues in the future when legitimate files need to be included.google-gemini/gemini-cli5 discussions
- Never ignore errors silentlyAll errors must be explicitly handled through catching, logging, or user feedback. Silent error suppression makes debugging impossible and creates poor user experiences.google-gemini/gemini-cli5 discussions
- Maintain naming consistencyEnsure consistent naming patterns and approaches across similar functionality in the codebase. This includes using named constants instead of magic strings, aligning input handling patterns with existing code, maintaining consistent identifier formats, and following established conventions from libraries or existing implementations.google-gemini/gemini-cli5 discussions
- implement resource constraintsImplement multiple types of resource constraints with appropriate thresholds to prevent performance degradation and resource exhaustion. This includes rate limiting, memory thresholds, execution time limits, and queue size bounds.google-gemini/gemini-cli5 discussions
- document current functionalityDocumentation should focus exclusively on current, active functionality rather than including historical context, deprecated features, or legacy modes. Remove sections that explain how things "used to work" or provide extensive support for outdated approaches that have minimal user adoption.google-gemini/gemini-cli5 discussions
- classify errors appropriatelyDifferent types of errors require different handling strategies. Classify errors into categories and apply appropriate response patterns: fail fast for user-actionable problems, retry with backoff for transient issues, and graceful degradation for non-critical failures.google-gemini/gemini-cli5 discussions
- Choose efficient data structuresSelect data structures and algorithms that match your performance requirements rather than defaulting to simple but inefficient approaches. Consider the time complexity of operations and use specialized libraries when appropriate.google-gemini/gemini-cli5 discussions
- API consistency patternsMaintain consistent interface patterns across APIs and avoid loose coupling through magic strings or unstable properties. APIs should follow established conventions and provide stable, well-defined contracts.google-gemini/gemini-cli5 discussions
- add tests for changesEvery code change, whether it's a new feature, bug fix, or refactoring, must include corresponding tests. This ensures code quality, prevents regressions, and maintains system reliability.google-gemini/gemini-cli5 discussions
- Handle errors completelyAlways handle errors comprehensively by checking return values, implementing proper error propagation, and ensuring resources are cleaned up. Errors that are ignored or improperly handled can lead to resource leaks, unexpected behavior, or application crashes.fatedier/frp5 discussions
- Connection lifecycle managementImplement comprehensive lifecycle management for network connections. Ensure proper initialization, authentication, monitoring, and termination of connections to maintain system reliability and performance.fatedier/frp5 discussions
- Null-Safe DefaultsWrite code assuming inputs (arrays, objects, DOM nodes) may contain `undefined`, `null`, or “empty slots/holes”, and normalize them early with explicit defaults.freeCodeCamp/freeCodeCamp5 discussions
- Middleware ordering and chainingWhen using Express, treat middleware registration as an HTTP request-processing pipeline: middleware executes in the order you add it, and the chain advances only if your middleware calls `next()`.freeCodeCamp/freeCodeCamp5 discussions
- Middleware and Status SemanticsWhen building API endpoints with Express, make request lifecycle control-flow and response semantics explicit and consistent: - Middleware chaining: only call `next()` when you intend to continue to the next middleware/handler; if you don’t call `next()`, the request-response cycle will stop.freeCodeCamp/freeCodeCamp5 discussions
- Canonical IDs and TitlesAdopt canonical naming rules for both **identifiers (anchors/ids)** and **display names (titles)** to prevent broken links and inconsistent labeling. EbookFoundation/free-programming-books5 discussions
- Manage dependencies wiselyWhen configuring dependencies in composer.json files, follow these guidelines to ensure maintainable and reliable configurations: 1. **Only include direct dependencies**: Add dependencies only when they are directly used by your package. If a dependency is accessed through another package, don't include it directly.laravel/framework5 discussions
- Escape column names properlyAlways use the appropriate wrapping/escaping mechanism when generating SQL to prevent syntax errors and SQL injection vulnerabilities, especially when handling:laravel/framework5 discussions
- Design flexible APIsWhen designing APIs, prioritize flexibility and developer experience by: 1. **Accept broader parameter types** - Use `callable` instead of `Closure` to support various invocation patterns:laravel/framework5 discussions
- Eliminate redundant operationsIdentify and remove unnecessary operations that impact performance, including redundant checks, duplicate calculations, unnecessary allocations, and redundant code paths. This is especially critical in hot paths like widget rebuilds, message handling, and frequently called methods.flutter/flutter5 discussions
- Avoid breaking changesWhen modifying existing APIs, prioritize backward compatibility to prevent breaking changes that would force developers to maintain separate code paths for different SDK versions. Use deprecation with clear migration paths instead of direct breaking changes, make new parameters optional with sensible defaults, and avoid changing existing default values.flutter/flutter5 discussions
- Accurate, consistent documentationDocumentation and comments must be accurate, concise, and follow the project's established conventions so they stay trustworthy and maintainable. - Describe actual behavior precisely. Avoid misleading wording (e.g., don't say "a copy of the session" is used when it's actually the same object reference—say "the current session object is used instead of...pallets/flask5 discussions
- Use structured error loggingAlways use the proper logger instance instead of console methods, and format error logs with structured data objects rather than string concatenation. Console logging methods like `console.error` can lead to log flooding in production and lack proper log level controls. Structured logging with error objects enables better log parsing, monitoring, and...firecrawl/firecrawl5 discussions
- Validate security configurationsAlways verify that security middleware configurations use correct constant values, proper parameter specifications, and follow established security practices. Incorrect configuration values can create vulnerabilities or cause security features to fail silently.gofiber/fiber5 discussions
- Evaluate nil check necessityBefore adding nil checks, evaluate whether they are actually necessary or if they represent false positives from static analysis tools. Consider Go's built-in nil safety patterns and semantics.gofiber/fiber5 discussions
- Type-safe API designsDesign APIs with strong type safety to improve developer experience and catch errors at compile time. Avoid using any types when possible, carefully order generic parameters to support type inference, and ensure return types accurately reflect API behavior.fastify/fastify5 discussions
- Properly Handle Errors in Fastify ApplicationsWhen implementing error handling in Fastify applications, it is important to always throw instances of the Error class rather than primitive values or non-Error objects. This ensures that errors are properly propagated through the Fastify error handling chain.fastify/fastify5 discussions
- Preserve error contextWhen handling errors, always ensure the original error context is preserved and properly surfaced. Error information should never be silently swallowed in try/catch blocks, as this makes debugging extremely difficult and can lead to unexpected system behavior.fastify/fastify5 discussions
- Null safe patternsUse concise null checking patterns to prevent runtime errors and improve code readability when handling potentially undefined values.fastify/fastify5 discussions
- Explicit Configuration Usage in FastifyWhen using the Fastify framework in TypeScript, ensure that all configuration options are explicitly declared and properly documented. This includes clearly defining all required configuration parameters, explicitly specifying any configuration constraints or mutually exclusive options, and providing comprehensive examples.fastify/fastify5 discussions
- Consistent JSDoc standardsDocument all public APIs and significant internal functions with comprehensive JSDoc comments that include accurate descriptions, parameter and return types, and any notable side effects. Follow standard JSDoc format conventions consistently across the codebase.fastify/fastify5 discussions
- Adhere to Fastify Coding ConventionsWhen implementing code that uses the Fastify package in TypeScript, ensure the following conventions are followed: avoid contractions, use Oxford commas, and maintain consistent formatting.fastify/fastify5 discussions
- Protocol-specific error handlingHandle errors and responses appropriately based on the network protocol being used. Different protocols have different mechanisms for error reporting and communication patterns.fastapi/fastapi5 discussions
- Consistent code examplesMaintain consistent formatting and styling in code examples throughout your NestJS application documentation. This ensures developers can quickly understand dependency injection patterns, module structures, and decorator usage.fastapi/fastapi5 discussions
- Semantic and consistent namingChoose identifiers that accurately reflect what they represent and stay consistent with established project or architectural conventions. Avoid names that mislead about scope, purpose, or type.expressjs/Express5 discussions
- Safe async test assertionsWhen asserting inside asynchronous callbacks (HTTP response handlers, `listen` callbacks, stream events, etc.), always guard assertions with `try`/`catch` (or `try`/`finally`) and guarantee that cleanup (`server.close()`) and the `done()` callback are invoked on both the success and failure path. An uncaught assertion thrown inside a callback is only caught...expressjs/Express5 discussions
- REST principles firstWhen designing APIs with Express, prioritize proper REST principles and HTTP semantics over convenience. This ensures your API is predictable, standards-compliant, and maintainable:expressjs/express5 discussions
- Propagate errors properlyAlways forward errors to the framework's error handling pipeline instead of swallowing them or handling them inconsistently. This enables centralized error handling, consistent user experiences, and proper error logging.expressjs/express5 discussions
- Handle streams properlyWhen transferring data over HTTP, properly implement streaming mechanisms to prevent memory exhaustion and potential denial-of-service vulnerabilities. Handle backpressure appropriately to ensure that slow clients cannot overwhelm server resources.expressjs/express5 discussions
- Ensure test completionTests must properly terminate by following appropriate asynchronous patterns. For asynchronous tests, always invoke the `done()` callback after assertions or use returned Promises. For synchronous tests, omit the `done` parameter entirely. Use Mocha's built-in assertion handling rather than manual try-catch blocks.expressjs/express5 discussions
- App settings managementTreat application settings as a well-defined, centrally managed API rather than ad-hoc values scattered through the codebase. - Always read and write settings through the accessor methods (`app.set()` / `app.get()`), never via direct object access like `app.settings.foo`; direct access bypasses validation and has been deprecated since 3.0.expressjs/Express5 discussions
- maintain API compatibilityWhen implementing or extending APIs, preserve compatibility with existing standards and expected behaviors. APIs should maintain the same contracts, interfaces, and behavioral patterns as the systems they emulate or replace.evanw/esbuild5 discussions
- Use descriptive consistent namesChoose names that are both semantically accurate and consistent with established patterns. Names should clearly convey their purpose, data type, and behavior while following existing conventions in the codebase and upstream dependencies.electron/electron5 discussions
- Descriptive error messagesError messages should be descriptive, contextual, and self-identifying to aid debugging and user understanding. Include relevant context like method names, parameter values, or identifiers that help locate the source of the error.electron/electron5 discussions
- Prevent redundant operationsIn distributed database systems, prevent redundant operations that can overload cluster resources. When implementing update operations that might be triggered simultaneously from multiple nodes:elastic/elasticsearch5 discussions
- validate inputs earlyValidate function inputs, preconditions, and assumptions as early as possible in the execution flow, preferably during binding or initialization phases rather than deep within implementation logic. This prevents invalid states from propagating through the system and ensures errors are caught at the appropriate architectural level.duckdb/duckdb5 discussions
- validate inputs comprehensivelyEnsure thorough input validation and comprehensive edge case handling in database operations. This includes checking parameter validity, handling null inputs, testing boundary conditions, and covering all comparison operators or function variants.duckdb/duckdb5 discussions
- Optimize algorithm complexityChoose efficient algorithms and data structures to avoid unnecessary computational complexity. Replace manual loops with optimized library functions, select appropriate containers based on access patterns, and use direct conversion paths when possible.duckdb/duckdb5 discussions
- consistent null validationEnsure null checks and input validation are applied consistently across similar functions and code paths. When one function in an API performs null pointer checks or input validation, all similar functions should follow the same pattern to maintain predictable behavior and prevent runtime errors.duckdb/duckdb5 discussions
- Test structure and clarityOrganize tests for maximum clarity and maintainability by leveraging pytest features and proper test structure. Split complex tests into focused, single-purpose test cases rather than testing multiple scenarios in one function. Use pytest fixtures for setup and cleanup instead of manual resource management, and prefer parameterization for testing multiple...stanfordnlp/dspy5 discussions
- reduce nesting levelsMinimize nested conditional statements and complex control flow by using early returns, guard clauses, and default value patterns. This improves code readability and maintainability by reducing cognitive load.stanfordnlp/dspy5 discussions
- prefer nullish coalescing operatorUse the nullish coalescing operator (`??`) instead of the logical OR operator (`||`) when you specifically want to provide fallback values only for `null` or `undefined`, not for other falsy values.drizzle-team/drizzle-orm5 discussions
- Version annotation in docsAlways include appropriate version annotations when documenting new features or changes in behavior. Use `.. versionadded::` for new features and `.. versionchanged::` for modifications to existing functionality. Place these annotations immediately after the feature's first mention in the documentation.django/django5 discussions
- Use semantic HTML elementsStructure HTML templates using semantically appropriate elements rather than generic containers. Replace non-semantic elements like `<div>` and `<p>` with more meaningful elements such as `<nav>`, `<ol>`, `<ul>`, and include proper accessibility attributes like `aria-labelledby` and `aria-current`.django/django5 discussions
- Structure logs effectivelyWhen implementing logging in your application, structure your log messages and parameters consistently to improve readability, searchability, and integration with monitoring tools. Consider these practices:django/django5 discussions
- Preserve error handling contextWhen handling exceptions, preserve the original error context and provide clear, actionable error messages. This helps with debugging and improves the developer experience. Key practices:django/django5 discussions
- Graceful API evolutionWhen evolving APIs, prioritize backward compatibility and provide clear migration paths. For any significant change: 1. Add explicit deprecation warnings that explain what's changing and how to adapt codedjango/django5 discussions
- Comments versus docstrings usageChoose between comments and docstrings based on the documentation's purpose and scope. Use docstrings for API-level documentation of functions, classes, and methods, writing verbs as commands (e.g., "Return" not "Returns"). Use inline comments sparingly for implementation details that aren't appropriate for the public API documentation.django/django5 discussions
- validate migration data comprehensivelyMigration scripts must thoroughly validate data conditions and handle edge cases to ensure reliable data transformation. Always check for data existence before applying operations, properly handle duplicate records, and avoid migrating calculated or derived fields.discourse/discourse5 discussions
- Use modern syntaxAdopt modern JavaScript and Ember syntax patterns instead of legacy approaches to improve code readability and maintainability. Key modern patterns to use:discourse/discourse5 discussions
- optimize test fixturesUse the `fab!` shorthand syntax for creating test fixtures and reuse fabricated objects across tests to improve performance and maintainability. The `fab!` method creates objects once per test context and reuses them, reducing database overhead compared to creating new objects for each test.discourse/discourse5 discussions
- Improve code readabilityStructure code to match logical flow and extract intermediate variables to improve readability. When dealing with multiple discrete cases, prefer switch statements over if/else chains for better extensibility. Replace magic numbers with named constants for self-documentation.discourse/discourse5 discussions
- Extract duplicate codeWhen you notice repeated code patterns, logic blocks, or similar implementations across methods or classes, extract the common functionality into reusable methods or utilities. This improves maintainability, reduces bugs, and makes the codebase more consistent.discourse/discourse5 discussions
- simplify complex logicImprove code readability by reducing complexity and nesting through early returns, extracting complex logic into dedicated functions, and using clear parameter naming.langgenius/dify5 discussions
- HTTP standards complianceEnsure API endpoints follow HTTP standards for status codes and method selection. Delete operations should return 204 (No Content) without a response body, while update operations should use PUT method instead of GET. This improves API consistency and follows REST conventions.langgenius/dify5 discussions
- Configuration value typesEnsure configuration values use appropriate types, avoid unnecessary Optional annotations, and maintain consistency in data formats and units. Key principles:langgenius/dify5 discussions
- Fail-Fast CI/CD StepsWhen building CI/CD pipelines, keep them scope-focused and deterministic, and add explicit quality gates so failures stop the deployment. Apply: - Put workflows in the conventional location and naming your team standard expects (e.g., `.github/workflows/main.yml`).kamranahmedse/developer-roadmap5 discussions
- Use appropriate synchronization mechanismsSelect and implement synchronization primitives that match your concurrency requirements and avoid unsafe patterns. Consider the number of consumers, thread safety requirements, and proper initialization order.denoland/deno5 discussions
- avoid panics gracefullyReplace panic-prone operations like `unwrap()` and `expect()` with graceful error handling that provides meaningful feedback. When encountering unexpected conditions, prefer logging warnings and falling back to reasonable defaults rather than crashing the application.denoland/deno5 discussions
- avoid implementation detail leakageAPIs should provide clean abstraction boundaries without exposing internal implementation details or creating unwanted dependencies between modules. When designing public interfaces, carefully consider what needs to be exposed versus what can remain internal.denoland/deno5 discussions
- User-friendly documentation examplesDocumentation should guide users toward best practices through clear examples. Begin with positive patterns before covering pitfalls, clarify all function parameters, and recommend appropriate methods for common tasks.deeplearning4j/deeplearning4j5 discussions
- Use logging best practicesAdopt these logging best practices to ensure consistent, efficient, and meaningful logs: 1. **Use Lombok's `@Slf4j` annotation** instead of manually declaring loggers:deeplearning4j/deeplearning4j5 discussions
- Numerical stability practicesWhen implementing machine learning algorithms, ensure numerical correctness and stability by following these practices: 1. Use appropriate default parameters based on research paper recommendations. For example, in AdaBelief, use smaller epsilon values as recommended by the authors:deeplearning4j/deeplearning4j5 discussions
- Descriptive error contextError messages should be specific, descriptive, and include context to help with debugging. Avoid generic messages like "Failed execution" or numeric error codes without explanation.deeplearning4j/deeplearning4j5 discussions
- Performance GuardrailsWhen implementing knowledge-graph storage/search, proactively prevent expensive work and payload bloat by following these rules: 1) Minimize returned payloads (especially vectors)eosphoros-ai/DB-GPT5 discussions
- Catch Expected ExceptionsWhen handling failures, avoid broad try/except that hides root causes. Catch only the exceptions you expect, log a warning (with enough context to debug), and preserve the original error/stack trace. For unsupported/unimplemented functionality or dependency/version mismatches, fail explicitly with clear, actionable error messages.eosphoros-ai/DB-GPT5 discussions
- Thoughtful error handlingImplement error handling that considers recoverability, appropriate logging levels, and prevents redundant operations. Use warnings for recoverable errors during retry attempts, and errors only for final failures. Avoid duplicate error logging when errors are already wrapped or handled elsewhere. Implement guards to prevent redundant error handler setup,...cypress-io/cypress5 discussions
- Simplify complex expressionsBreak down complex conditional logic, nested structures, and verbose syntax into smaller, well-named functions or more concise expressions. This improves code readability and maintainability.cypress-io/cypress5 discussions
- prefer modern composition patternsUse Vue 3 Composition API patterns that provide better performance, type safety, and maintainability. Prefer `computed` over `watch` + reactive assignment when deriving values from other reactive data. Use `defineEmits` instead of `$emit` in templates for type safety. Adopt modern `defineProps<{}>()` syntax over PropType casting for better TypeScript...cypress-io/cypress5 discussions
- Explain non-obvious codeAdd explanatory comments for complex logic, workarounds, and non-obvious code patterns to help future maintainers understand the reasoning behind implementation decisions. Include links to external resources like GitHub issues, documentation, or source materials when relevant.cypress-io/cypress5 discussions
- Environment variable validationAlways validate environment variables with proper type checking, fallback values, and defensive handling to prevent runtime failures and unexpected behavior.cypress-io/cypress5 discussions
- consistent descriptive namingMaintain consistent naming patterns across similar functionality while ensuring names accurately describe their current purpose and scope. When multiple options exist for the same feature, standardize on one clear option to avoid confusion in documentation and usage. Update variable names when their type or purpose changes, and use descriptive names that...cypress-io/cypress5 discussions
- Configuration documentation clarityEnsure configuration documentation, setup instructions, and changelogs use precise, clear language with proper technical terminology. Avoid ambiguous words like "sometimes" or "generally" that create uncertainty. Use correct capitalization for technical terms (e.g., "Node.js" not "Node", "CommonJS/ESM" not "commonjs/ESM"). Remove redundant words and fix...cypress-io/cypress5 discussions
- Model-agnostic AI codeWhen building applications that interact with AI models, avoid hardcoding model-specific behavior and instead design for flexibility across different LLM providers and versions. This approach increases resilience and makes your code more maintainable as the AI ecosystem evolves.crewaiinc/crewai5 discussions
- Verify algorithmic equivalenceWhen replacing an exact check or well-defined numeric algorithm with an optimized, approximated, or restructured version (e.g., a bit-length shortcut instead of a direct comparison, or a rewritten normalization loop), you must prove or thoroughly test that the new logic is mathematically equivalent to the original across all boundary values, not just...python/cpython5 discussions
- Validate recursive algorithms against nestingWhen an algorithm operates on hierarchical or recursive structures (nested scopes, nested comprehensions, tree-like state), verify it with multi-level test cases, not just the flat/single-level case. Bugs repeatedly surfaced only when a second level of nesting was introduced, e.g. a comprehension inside another comprehension inside a class body, or a free...python/cpython5 discussions
- Optimize hot-path codeIn performance-sensitive code (loops, frequently-called functions, parsers, I/O paths), eliminate redundant work and unnecessary indirection, and validate optimizations with measurements rather than assumptions.python/cpython5 discussions
- Deterministic concurrency testsWhen writing tests that try to trigger a race condition or verify thread-safety, do not rely on implicit timing (e.g. just calling `Thread.start()` and hoping the scheduler interleaves correctly, or sprinkling `time.sleep()` calls) to hit the narrow window under test. Such tests are flaky: they may pass hundreds of times and still miss the bug, or...python/cpython5 discussions
- Accurate, synced documentationDocstrings, comments, and reference docs must always reflect the current, actual behavior of the code, and all related documentation locations must be updated together. Concretely:python/cpython5 discussions
- prefer None over placeholdersWhen data is unavailable, unknown, or invalid, return `None` instead of placeholder strings like "Unknown", "Unspecified", or "???". This makes the absence of data explicit and prevents downstream code from treating placeholder values as legitimate data.home-assistant/core5 discussions
- Minimize try block scopeOnly include code that can actually raise exceptions within try blocks. Move variable assignments, logging statements, and other operations that cannot fail outside of the try block to avoid accidentally catching unintended exceptions and to improve code clarity.home-assistant/core5 discussions
- Maintain consistent code styleFollow project-wide code style conventions to ensure consistency and readability. Key practices include: 1. Use consistent spacing and formatting: - Maintain blank lines between test casesvuejs/core5 discussions
- Explicit nullish checksWhen checking for the absence of values, use explicit nullish checks rather than relying on JavaScript's falsy behavior. This prevents issues with valid falsy values like empty strings, zero, or false being treated as non-existent.vuejs/core5 discussions
- Validate before data accessAlways validate data existence and type before accessing properties or methods to prevent runtime errors from null/undefined values. This includes: 1. Array bounds checking before indexingcontinuedev/continue5 discussions
- Standardize AI model interfacesWhen implementing AI model integrations, maintain consistent interfaces and proper type definitions across different providers. This ensures compatibility, prevents runtime errors, and simplifies maintenance.continuedev/continue5 discussions
- Robust comparison algorithmsEnsure your comparison algorithms handle edge cases properly and avoid common pitfalls: 1. **Normalize values before comparison** - When comparing strings, consider if you need to normalize whitespace, case, or other variants:continuedev/continue5 discussions
- Document why not whatDocumentation should explain rationale and be technically precise. Focus on: 1. Including all required parameters with correct names in examples and documentationcontinuedev/continue5 discussions
- Decouple tests from implementationTests tightly coupled to implementation details break easily when the implementation changes, creating maintenance burden and reducing test reliability. Write tests that validate behavior rather than specific implementation details.continuedev/continue5 discussions
- Choose clear semantic namesNames should clearly and accurately convey their purpose, behavior, and content. Follow these guidelines: 1. Use positive boolean flags: ```typescriptcontinuedev/continue5 discussions
- Prefer Readable ConditionalsWhen updating or adding code, keep control flow and non-trivial expressions easy to reason about. Rules of thumb: - Avoid nested ternary operators; use `switch` (or equivalent) for branching decisions.apple/container5 discussions
- Document invariants and changesWhen introducing/altering API fields, parsing rules, or behavior, ensure documentation makes the code’s correctness contract explicit. Apply this standard:apple/container5 discussions
- Config Resolution DisciplineWhen adding/updating configuration handling, resolve configuration once into a single immutable runtime context, and make precedence/fallback behavior explicit.apple/container5 discussions
- Scope concurrency control preciselyApply concurrency control mechanisms with precise scope to prevent both race conditions and unnecessary blocking. Use appropriate synchronization tools (mutex, channels, errgroup) only around critical sections that actually require protection.docker/compose5 discussions
- prefer dynamic configuration sourcesUse runtime-determined configuration sources instead of hardcoded values or static file parsing when more reliable alternatives are available. This improves robustness, cross-platform compatibility, and deployment flexibility.comfyanonymous/ComfyUI5 discussions
- optimize CI resource usageDesign CI/CD workflows to minimize unnecessary resource consumption and provide faster feedback. Avoid triggering builds when changes don't impact the build output, use appropriate event triggers, and implement clean artifact management strategies.comfyanonymous/ComfyUI5 discussions
- Explicit error propagationFunctions should raise exceptions with meaningful messages instead of returning False, None, or silently catching all exceptions. This allows calling code to properly understand what went wrong and take appropriate action.comfyanonymous/ComfyUI5 discussions
- avoid expensive operationsIdentify and eliminate unnecessary expensive operations that can significantly impact performance. Common patterns to watch for include: 1. **Unnecessary deep copying**: Instead of using `deepcopy()` on large objects, build new dictionaries with only the required values. For example, rather than `copy.deepcopy(self.history[key])` and then removing unwanted...comfyanonymous/ComfyUI5 discussions
- API backward compatibilityEnsure API changes maintain backward compatibility to avoid breaking existing clients and workflows. When adding new functionality, use optional parameters with sensible defaults rather than required parameters. When versioning APIs, follow the `/api/v2/resource` pattern and maintain deprecated endpoints during transition periods to allow clients time to...comfyanonymous/ComfyUI5 discussions
- Write comprehensive test assertionsInstead of making multiple small assertions that check individual fields or conditions, write single comprehensive assertions that verify the complete expected state. This approach makes tests more maintainable, provides better documentation of expected behavior, and makes test failures more informative.openai/codex5 discussions
- Structure configurations properlyDefine a clear, hierarchical structure for application configurations with descriptive naming and proper organization. Avoid hardcoded values, use named constants for magic numbers, and ensure configuration is loaded only once at startup and passed through the application rather than loaded at arbitrary points.openai/codex5 discussions
- Error Handling GuardrailsAdopt a small set of guardrails for failures so recovery is predictable, repeatable, and doesn’t deadlock or mask outcomes: 1) Classify errors into “retryable” vs “permanent,” then apply a bounded retry budget.openai/codex-security5 discussions
- Defensive Security ValidationApply defensive validation rules anywhere code derives security decisions from paths, filesystem objects, executables, or integrity metadata. Guidelinesopenai/codex-security5 discussions
- Document non-obvious aspectsDocumentation should explain what isn't obvious from the code itself. Focus on providing context about "why" certain decisions were made rather than restating what the code does.openai/codex5 discussions
- Contextualize, don't swallowAlways propagate errors with appropriate context rather than silently ignoring them. This makes debugging easier and prevents unexpected behavior. **Do**:openai/codex5 discussions
- Centralize configuration managementPrefer centralized configuration objects over environment variables for application settings. Environment variables create inconsistent configuration sources and can lead to maintenance challenges.openai/codex5 discussions
- Verify docs against actual behaviorDocumentation (CLI references, config tables, examples) must accurately reflect the current, real behavior of the system—not assumed, aspirational, or stale behavior. Before merging docs:cline/cline5 discussions
- use semantic namingChoose variable, function, and type names that clearly communicate their purpose and meaning without requiring additional context or comments. Names should be self-documenting and unambiguous to future developers.cline/cline5 discussions
- Trust-boundary Security ControlsTreat “ignore/filter” and heuristics as non-security: they must not be relied on for authorization or access control. Apply explicit, trusted enforcement instead:CLINE/CLINE5 discussions
- Safe LLM retry recoveryWhen adding retry, continuation, or recovery logic around LLM streaming responses (stream errors, max-tokens truncation, degenerate/incomplete output, etc.), never silently discard work that already happened or is still pending delivery. Before issuing a retry: confirm the underlying error is actually marked retryable and back off appropriately rather than...cline/cline5 discussions
- reuse common message typesPrefer reusable message types over single-purpose request/response pairs to reduce API bloat and improve maintainability. Avoid creating dedicated "Response" types when the return value can be a plain, reusable struct. Merge identical request types and leverage common message patterns like StringRequest or EmptyRequest where appropriate.cline/cline5 discussions
- Resolve config onceWhen behavior depends on provider/env configuration (URLs, feature links, capability gating), derive the *effective* configuration once using shared helpers, then pass the resolved values through—don’t recompute them during refresh/account cycles. Also, make configuration precedence explicit and test it (CLI flags vs env vs defaults), especially for...CLINE/cline5 discussions
- Preserve API ContractsEnsure API contracts are explicit, semantically consistent, and forwarded end-to-end across layers. Practical rules: 1) Don’t change semantics without changing the contract: if a request header field’s *meaning* changes, either keep the original meaning or rename the header (or add a new header) so the backend contract remains unambiguous.ClInE/cLiNe5 discussions
- Normalize reasoning tokensWhen integrating LLM providers/adapters, treat reasoning and token budgets as *provider-specific data shapes* and normalize them so downstream systems don’t double-count or receive invalid fields.CLINE/CLINE5 discussions
- Network retry and boundsDefine networking behavior so failures don’t cause duplicate work, hangs, or incorrect routing. Apply these rules: 1) Track dispatch boundaries for retry/resend UXCLINE/CLINE5 discussions
- Network request lifecycleAny code that performs network I/O must define (1) routing correctness (proxy vs loopback/local), and (2) a bounded request lifecycle (AbortSignal/timeout) for *every* path, including fallbacks; and (3) consistent in-flight cancellation/grace semantics on disconnect.cline/CLINE5 discussions
- Model-aware limits and reasoningWhen building AI/gateway/provider request logic, derive token budgets and reasoning payloads from the most accurate, provider-verified model metadata, and make defaulting/clamping semantics explicit.cline/CLINE5 discussions
- Make naming semantics explicitPrefer identifier names that encode the real intent and lifecycle semantics, and keep names consistent across the codebase. Apply these rules: - Align with existing canonical types/names: if there’s a shared naming source (e.g., `ClientName`), reuse it rather than inventing near-duplicates.cline/CLINE5 discussions
- Guard state on failureWhen an action can fail or an environment can change, ensure error handling preserves user state, prevents incorrect side effects, and recovers automatically.cline/CLINE5 discussions
- Guard side effectsIn React, any effect that listens to global/input events or performs one-time navigation/initialization must be explicitly coordinated with UI lifecycle and state ownership.CLINE/CLINE5 discussions
- Guard against concurrent state racesWhen shared state is mutated by multiple threads, background readers/waiters, or async callbacks, treat every check-then-act sequence as a potential race and design for it explicitly:cline/cline5 discussions
- Explicit Null Reset SemanticsNull/undefined handling must preserve intent across API boundaries and persistence layers. Treat `undefined` as “not provided/unchanged/omit”, and treat `null` (or an explicitly reset payload) as “clear/reset this value”. Ensure your type annotations and runtime normalization match what the receiving contract/storage layer expects, and lock the behavior...CLINE/cline5 discussions
- Enforce Trust-Boundary ControlsSecurity-sensitive behavior must be enforced from trusted inputs and with validated permission logic; do not rely on mechanisms that an untrusted repository can change or that are known to be ineffective as access control.ClInE/cLiNe5 discussions
- Don’t Trust Local ControlsTreat any “filter” (e.g., file ignores) as *non-security* unless it is enforced by a trusted, bypass-resistant control point. Apply this standard: - **Never rely on ignore lists as an access boundary.** If a mechanism can be bypassed by explicit reads/commands, document it as *best-effort filtering* only (or remove it).Cline/Cline5 discussions
- Distinguish null, undefined, emptyWhen null, undefined, and "empty" (`[]`, `""`, missing field) can each carry a different meaning, handle each case explicitly instead of collapsing them with `??`, default parameters, or truthy checks. These three states are not interchangeable:cline/cline5 discussions
- Config-driven consistencyWhen code behavior or links depend on environment variables, feature flags, or user preferences, follow these rules: 1) Centralize env-aware URL buildingCLINE/cline5 discussions
- centralize configuration managementConsolidate related configuration settings into dedicated config objects or files rather than scattering hardcoded values throughout the codebase. Separate different types of configuration (API endpoints, timeouts, credentials) into distinct config sections to improve maintainability and avoid coupling.cline/cline5 discussions
- Avoid stale closures in callbacksWhen an effect, timer, or async operation schedules a callback that may run after a gap (an `await`, an interval tick, or a React `<Activity>` hide/show cycle), do not let it act on values captured in its closure at creation time — state may have changed by the time it fires. Read the current value through a ref that is kept up to date on every render/call,...cline/cline5 discussions
- Avoid duplicate logicBefore adding new logic, search the codebase for an existing implementation and reuse or extend it rather than writing a parallel version. This applies to utility functions (e.g. shell/PowerShell detection already in `@cline/shared`'s `getShellKind`), domain logic (e.g. git snapshot/preflight code already in `core/services/cloud-handoff`), and...cline/cline5 discussions
- Add missing error handlingWrap operations that can fail in try/catch blocks to prevent unhandled exceptions from crashing the application or leaving it in an inconsistent state. This is especially important for file operations, API calls, and critical initialization code.cline/cline5 discussions
- Accurate Parsing EstimationWhen implementing algorithmic utilities (parsers, normalizers, token/complexity estimators), specify and enforce invariants, and test the edge cases that break naive implementations.cline/CLINE5 discussions
- optimize algorithmic complexityAlways consider the algorithmic complexity and performance implications of data structure choices, memory allocation patterns, and container operations. This includes pre-allocating containers when sizes are known, choosing appropriate data structures based on usage patterns, and measuring performance impact of changes.ClickHouse/ClickHouse5 discussions
- optimize algorithm selectionChoose algorithms and data structures based on actual performance characteristics rather than defaulting to standard library implementations. Consider lighter-weight alternatives when standard library functions are over-engineered for your use case.ClickHouse/ClickHouse5 discussions
- Extract common patternsIdentify and extract repeated code patterns into reusable functions or methods to improve maintainability and reduce duplication. When you notice similar logic appearing in multiple places, create a common utility function or method that can be shared.ClickHouse/ClickHouse5 discussions
- Database schema consistencyEnsure database operations maintain consistent behavior and ordering, especially in distributed systems. When working with data structures that affect schema representation or query results, prioritize deterministic ordering over performance optimizations to prevent schema mismatches and ensure reliable distributed operations.ClickHouse/ClickHouse5 discussions
- Use optional chainingAlways use optional chaining (`?.`) and null checks when accessing properties or methods on objects that might be null or undefined. This prevents runtime crashes and makes code more robust.snyk/cli5 discussions
- comprehensive test coverageEnsure thorough test coverage by extracting complex logic into small, testable functions and using appropriate testing utilities. When encountering complex code blocks, break them into smaller functions that can be tested in isolation. Use Go's built-in testing utilities like `t.Setenv()` instead of `os.Setenv()` for environment variables, and...snyk/cli5 discussions
- Secure credential managementWhen handling passwords, certificates, or keys in your code, implement secure encryption and storage mechanisms to prevent exposure of sensitive data. chef/chef5 discussions
- Prefer guard clausesUse guard clauses with early returns for null checking instead of wrapping code in conditional blocks. This improves readability by reducing nesting and making the code's "happy path" more evident.chef/chef5 discussions
- Explicit configuration over implicitAlways define explicit configuration defaults rather than relying on implicit behavior or autovivification. Configuration values should: 1. Use explicit nil defaults instead of undefined valueschef/chef5 discussions
- Use appropriate logging levelsSelect the correct logging level based on the importance and visibility requirements of the information. Choose WARNING for issues that should be visible by default and may require attention, INFO for general operational messages, and DEBUG for detailed information needed only during troubleshooting. Additionally, ensure log messages include sufficient...bridgecrewio/checkov5 discussions
- Thorough test assertionsEnsure tests thoroughly validate functionality through comprehensive assertions. When writing tests: 1. Assert all relevant aspects of the expected behavior, not just presence/absence or simple success/failurebridgecrewio/checkov5 discussions
- Strategic exception managementChoose the appropriate error handling strategy based on the context and severity of potential failures. Use exceptions for truly exceptional conditions that represent invalid states or unrecoverable errors, while providing graceful fallbacks for non-critical failures.bridgecrewio/checkov5 discussions
- Strategic error handlingChoose appropriate error handling strategies based on the nature of the error and recovery potential: 1. **Raise exceptions only for truly exceptional conditions**:bridgecrewio/checkov5 discussions
- Document configuration optionsAlways provide comprehensive documentation for all configuration options, including environment variables, feature flags, and version overrides. For each configuration option:bridgecrewio/checkov5 discussions
- Choose optimal data structuresSelect the most appropriate data structure based on the specific operations your algorithm needs to perform. This choice can dramatically impact performance and code clarity:bridgecrewio/checkov5 discussions
- Maintain API Backward CompatibilityWhen changing code that affects a public interface (method signatures, CLI command arguments, plugin discovery, type/subscriptable behavior), treat it as an API contract: keep existing call patterns working, and ensure runtime semantics match the intended contract.celery/celery5 discussions
- Use descriptive identifiersChoose specific, descriptive names for variables, functions, and parameters that clearly communicate their purpose and content. Avoid generic terms that could be ambiguous or misleading.calcom/cal.com5 discussions
- Explicit null checksAlways use explicit null and undefined checks instead of relying solely on optional chaining, especially when you need predictable boolean results or want to prevent null/undefined values from propagating to APIs, URLs, or causing runtime errors.calcom/cal.com5 discussions
- ensure test reliabilityWrite tests that are stable, independent, and non-flaky by following proper isolation and waiting practices. Tests should create their own data, clean up after themselves, and avoid dependencies on other tests or external state.calcom/cal.com5 discussions
- Design contextual API interfacesAPI interfaces should expose only relevant data and functionality based on context, configuration, and user requirements. This principle ensures efficient data transfer, cleaner interfaces, and appropriate user experiences.calcom/cal.com5 discussions
- Use memory poolsReuse memory with buffer pools for temporary allocations instead of creating new buffers each time. This reduces memory allocation overhead and improves performance, especially for operations that frequently need temporary storage.oven-sh/bun5 discussions
- Network API compatibilityWhen implementing networking APIs that mirror Node.js functionality, ensure both behavior and error patterns match Node.js exactly. This is critical for maintaining compatibility with the Node.js ecosystem and ensuring that code works consistently across both environments.oven-sh/bun5 discussions
- Match filenames to contentsFiles should be named to clearly reflect their primary contents: 1. When a file contains a single primary type: - Name the file exactly after the typeoven-sh/bun5 discussions
- Descriptive identifier namesChoose clear, consistent, and accurate identifiers that precisely reflect behavior and follow established patterns. This applies to function names, method names, variable types, and enum values.oven-sh/bun5 discussions
- Clean all error pathsEnsure all error paths properly clean up resources and handle errors appropriately. This includes: 1. Using errdefer for cleanup when allocating resourcesoven-sh/bun5 discussions
- Environment variable configurationPrefer environment variables over hardcoded configuration values to improve flexibility and avoid forcing configuration choices on users. Always provide sensible defaults and implement proper validation.browser-use/browser-use5 discussions
- Simplify complex code blocksBreak down complex code blocks and expressions into simpler, more readable components. Complex boolean logic, nested conditions, and multi-operation lines should be refactored for clarity.Homebrew/brew5 discussions
- Actions workflow best practicesUse GitHub Actions native features and follow best practices to create maintainable, secure, and reliable CI workflows: 1. **Use working-directory instead of manual cd commands**Homebrew/brew5 discussions
- Write clear examplesCreate comprehensive code examples in documentation that demonstrate common operations and use proper formatting. Use double backticks (``) for inline code references in reStructuredText, and wrap code blocks in proper directives:boto/boto35 discussions
- Consistent method interfacesDesign APIs with consistent method interfaces across related resources to improve usability and reduce learning curve. When similar operations are available on different resources, they should follow the same naming conventions, parameter structures, and behavior patterns.boto/boto35 discussions
- Configure proxies with schemesWhen configuring proxies in AWS SDK clients, always include the complete URL scheme in proxy definitions. Match the scheme to the protocol: use 'http://' for HTTP connections and 'https://' for HTTPS connections. Missing or incorrect schemes can lead to connection failures or security issues.boto/boto35 discussions
- Treat Inputs as UntrustedApply a consistent security posture to every workflow/prompt-controlled value and to any derived content that will be rendered or linked: 1) Validate untrusted paths *before* cleanup/normalizationbmad-code-org/bmad-method5 discussions
- Naming contracts enforcementTreat IDs, artifact filenames, and command invocation strings as part of a naming contract: they must be deterministic for dispatch, glob matching, and resume/compatibility.bmad-code-org/bmad-method5 discussions
- Graceful Error RecoveryDesign review/orchestration flows so failures, missing dependencies, and partial automation never corrupt state or silently drop work. Apply these standards:bmad-code-org/bmad-method5 discussions
- Validate security contextDefine and enforce security-context behavior as a clear contract, then implement CI/runtime logic to match it without brittle assumptions. Apply this in two places:maximhq/bifrost5 discussions
- Stable Backward-Compatible MigrationsWhen adding schema/config fields, design migrations to be stable across upgrade/downgrade boundaries: - Handle “unset vs default” explicitly in config-store: store a sentinel/unset value (commonly `0`), ensure getters apply the real default (e.g., 15), and ensure config hashing only incorporates the field when it is explicitly set (non-zero). Add a test...maximhq/bifrost5 discussions
- Null semantics and safetyDefine and enforce null/optional semantics consistently: (1) treat nil/zero/empty/absent as distinct states, (2) clear stale state when nil means “remove”, (3) never rely on plain `interfaceValue != nil` when the underlying value may be a typed-nil pointer, and (4) when using `omitempty`, only set pointer fields when the value is actually present.maximhq/bifrost5 discussions
- Backend Enforcement, UI ValidationTreat the frontend as an *UX layer*, not an authorization or confidentiality enforcement boundary. Any access control (licensing, revoke/re-auth, hidden-content guarantees, RBAC) must be enforced by the backend/data layer; the UI may be redundant or fail-open without granting access. Separately, whenever the UI must render untrusted values into...maximhq/bifrost5 discussions
- Validate before usageAlways explicitly check for null or undefined values before using them in operations. Don't assume values exist - validate their presence and handle missing cases appropriately with early returns, error throwing, or fallback logic.better-auth/better-auth5 discussions
- Prefer simple solutionsChoose existing utilities, simpler patterns, and cleaner implementations over manual or complex approaches. This improves code maintainability and reduces potential bugs.better-auth/better-auth5 discussions
- Use semantically clear namesChoose names that clearly express their purpose and avoid patterns that can lead to confusion or bugs. Names should be self-documenting and unambiguous in their meaning.bazelbuild/bazel5 discussions
- Error-handled API CallsFor every external API/data-store call, enforce a consistent error-handling contract: 1) Validate inputs up front (fail fast for predictable bad requests)Azure/Azure-Sentinel5 discussions
- Deterministic KQL PipelinesTreat each analytics/hunting query as a deterministic algorithm: parse based on the actual encoded input, collapse repeated events by key, and use correct expand/join/re-aggregate patterns so results are complete and non-duplicative.Azure/Azure-Sentinel5 discussions
- Specific exceptions for clarityUse specific exception types with meaningful error messages rather than generic exceptions to improve error handling, debugging, and API usability. This allows callers to distinguish between different error conditions and respond appropriately.Azure/azure-sdk-for-net5 discussions
- Preserve API compatibilityWhen evolving APIs, maintain backward compatibility to prevent breaking changes for existing consumers. Key approaches: 1. **Retain removed members with obsolete attributes**: When removing or replacing public methods, mark the original as obsolete but maintain its functionality.Azure/azure-sdk-for-net5 discussions
- Maintain clean code structureKeep code clean and well-organized by: 1. Removing unnecessary elements: - Delete commented-out code that is no longer needed - Remove unused using directivesAzure/azure-sdk-for-net5 discussions
- Centralize configuration valuesConfiguration values should be defined once and referenced throughout your project to ensure consistency and simplify maintenance. Hardcoded values scattered across multiple files lead to update errors and inconsistent configurations.Azure/azure-sdk-for-net5 discussions
- Source-only Template InputsDefault to a single source-of-truth for infrastructure-as-code and ensure CI/CD owns generated deployment artifacts. This reduces drift and keeps pipeline behavior predictable.Azure/azure-quickstart-templates5 discussions
- Maintainable Documentation StandardsKeep template READMEs technically correct, GitHub-renderable, and maintainable. - Use markdown syntax that GitHub will render (avoid docs.microsoft.com-only constructs like `[!TIP]`; if needed, replace with standard headings/blockquote/correct GitHub-compatible callouts).Azure/azure-quickstart-templates5 discussions
- In-code Documentation ConsistencyEnsure any developer-facing documentation embedded in the codebase (template metadata, links, and sample deployment instructions) is complete, unambiguous, portable, and consistent with the repository layout.Azure/azure-quickstart-templates5 discussions
- Implicit Dependencies OnlyFor CI/CD stability and to avoid Bicep linter/build failures, do not add explicit `dependsOn` entries when Bicep can infer the dependency. **Rule** - **Remove unnecessary `dependsOn`** when the deployment order is already implied by:Azure/azure-quickstart-templates5 discussions
- PowerShell style hygieneAdopt consistent PowerShell coding patterns to improve correctness and readability, and keep project definitions clean. - Boolean parameter syntax: pass boolean parameters using the idiomatic form for the context.Azure/azure-powershell5 discussions
- Null-Safe Inputs And MappingWhen a value is optional (or can differ by feature/region/constructor), never assume it’s present or non-empty. Apply consistent null/empty/whitespace handling, gate context-dependent logic, and validate after any transform (e.g., JSON/model conversion) so missing fields don’t silently change behavior.Azure/azure-powershell5 discussions
- Generated Artifacts in CITreat anything under build/generated locations (including auto-generated test stubs and generated module mirrors) as write-protected CI outputs: update only the custom source files / AutoRest config / build inputs, not the generated artifacts themselves. When CI tests fail due to missing environment (e.g., Azure context/SubscriptionId in playback),...Azure/azure-powershell5 discussions
- Explicit Null Safety ChecksEnsure null-safety is precise: guard against $null *and* empty results *and* blank strings (including blank entries inside arrays/hashtables). Also treat “omitted optional/switch parameters” as meaningful (absence != explicit value), and structure conditions so short-circuiting prevents null dereferences.Azure/azure-powershell5 discussions
- Consistent error handlingApply a single, predictable error-handling strategy across cmdlets and SDK wrappers: - **Make existence semantics consistent**: if a method supports `throwIfNotExists` (or callers rely on it), every related “read/modify” path must honor it the same way (return `null` vs throw), and callers should not silently diverge between Get/With* operations.Azure/azure-powershell5 discussions
- CI/CD Build Artifact RulesTreat autogenerated content as build artifacts owned by CI/CD, and handle breaking changes through the release system (not ad-hoc edits). Do: - Edit the source-of-truth inputs (e.g., custom folder content and autorest README.md/autorest configuration) and place human-authored examples under the dedicated “examples” directory.Azure/azure-powershell5 discussions
- API versioning and client methodsWhen changing API clients, keep API versioning and HTTP operation semantics explicit and isolated. **Do** - **Scope ApiVersion changes** to only the new operation(s). If a shared client is used by many cmdlets, either (a) split the client, (b) wrap the new operation in a dedicated client/operation class, or (c) prove all affected cmdlets are covered.Azure/azure-powershell5 discussions
- Align SDK contract typesWhen updating generated PowerShell/SDK clients (e.g., AutoRest v3 → v4), treat the generated model contract as authoritative: match namespaces/types and ensure request serialization shape matches what the REST service expects.Azure/azure-powershell5 discussions
- Prefer descriptive over briefChoose clear, descriptive names over abbreviated or shortened versions. Names should be self-documenting and follow Rust conventions. While brevity can be tempting, the clarity and maintainability benefits of descriptive names outweigh the extra characters.tokio-rs/axum5 discussions
- Documentation consistency standardsMaintain consistent documentation formatting standards across all project files, especially in changelogs, code examples, and technical documentation. This ensures readability and prevents confusion when documentation is viewed in different contexts.tokio-rs/axum5 discussions
- Consistent axum Usage in TypeScriptWhen implementing TypeScript code that uses the axum package, maintain consistent and idiomatic usage: always use lowercase 'axum', leverage axum's built-in types correctly, follow best practices for state and dependencies, ensure proper error handling, and use routing and middleware features effectively.tokio-rs/axum5 discussions
- Enforce API ContractsWhen designing or extending APIs, ensure the request/response schema and behavior strictly preserve invariants and provider compatibility. Apply these rules:looplj/axonhub5 discussions
- Consistent Authorization and AuthWhen changing or adding security-sensitive functionality, keep authorization semantics stable and use project-wide shared validation/auth plumbing. Apply this standard:looplj/axonhub5 discussions
- Type-safe API interfaces designDesign API interfaces with strong type safety while maintaining excellent developer experience. Prefer explicit types over loose ones to enable better IDE support and catch errors at compile time.axios/axios5 discussions
- Standardize null value checksAlways use consistent patterns and utility functions for handling null and undefined values. This improves code reliability and maintainability while preventing common errors.axios/axios5 discussions
- Specific test assertionsWhen writing tests, explicitly assert specific conditions and expected values rather than relying on general success/failure checks. This prevents tests from silently passing when they should fail and ensures tests verify exactly what they're intended to verify.axios/axios5 discussions
- Proxy protocol handlingWhen implementing HTTP clients with proxy support, ensure the connection to the proxy uses the protocol specified in the proxy configuration (not the request protocol). This is crucial for scenarios like accessing HTTPS resources through an HTTP proxy.axios/axios5 discussions
- Documentation reflects realityAlways ensure documentation accurately represents the actual code behavior and implementation details. Include important contextual information such as platform-specific limitations, explanations for deprecated features with recommended alternatives, precise descriptions of function parameters and behaviors, and concise, merged code examples to demonstrate functionality.axios/axios5 discussions
- Consistent method behaviorsDesign API methods with predictable behavior patterns that follow common conventions. Methods that modify objects directly should not return values unless supporting method chaining. Methods that retrieve or transform data should return new objects without modifying inputs.axios/axios5 discussions
- Complete error handling chainImplement comprehensive error handling throughout the codebase by ensuring all error scenarios are properly caught, typed, and propagated. This includes always including catch blocks for async operations, properly typing and propagating error information, using standardized error codes, and ensuring error callbacks receive and handle error parameters.axios/axios5 discussions
- Structured test resource managementOrganize tests with proper resource lifecycle management to ensure reliability and maintainability. Create test resources once in `before` hooks rather than in individual tests, and clean them up in corresponding `after` hooks. For shared resources, use unique identifiers (e.g., timestamps) to prevent conflicts between test runs.aws/aws-sdk-js5 discussions
- Content integrity verificationWhen handling HTTP responses, especially with streaming data, properly verify content integrity and length to prevent data corruption or unexpected termination. Key considerations:aws/aws-sdk-js5 discussions
- Use descriptive constantsReplace hardcoded strings, numbers, and magic values with well-named constants that clearly describe their purpose and meaning. This improves code readability, maintainability, and reduces the risk of typos when the same values are used in multiple places.argoproj/argo-cd5 discussions
- Use configuration constantsReplace hardcoded values with named constants from common packages or make values configurable through environment variables or flags. This improves maintainability, reduces magic numbers, and enables runtime configuration.argoproj/argo-cd5 discussions
- structured logging practicesUse structured logging with proper context and consolidate related log messages. Instead of multiple separate log statements or string interpolation, use structured fields that are parseable by log tools and provide sufficient context for debugging.argoproj/argo-cd5 discussions
- Provide comprehensive explanationsDocumentation should provide thorough technical explanations that define key concepts, explain behaviors, and include necessary context for users to properly understand and use features. Avoid leaving users to guess what terms mean or how features differ from similar functionality.argoproj/argo-cd5 discussions
- Follow Go naming conventionsAdhere to Go naming conventions and maintain consistency with established codebase terminology. This includes proper capitalization of acronyms (e.g., "OCI" not "Oci"), avoiding underscores in identifiers, following standard library naming patterns, and using consistent terminology throughout the codebase.argoproj/argo-cd5 discussions
- Choose appropriate synchronization primitivesSelect the right synchronization mechanism based on your specific use case to avoid performance regressions and ensure thread safety. Follow these guidelines:argoproj/argo-cd5 discussions
- Check nil before accessAlways verify that pointers and nested struct fields are not nil before accessing their members to prevent runtime panics. This is especially important when dealing with optional configuration fields, middleware components, and API responses where certain fields may not be initialized.argoproj/argo-cd5 discussions
- Safe spawn and permission validationEnforce security for any code that turns user/config inputs into subprocess execution or permission settings. Apply these rules: 1) Spawn safely - Use `spawn(binary, args, ...)` with an args array.coleam00/Archon5 discussions
- Assert response fully alwaysAlways validate all relevant aspects of API responses in tests, including status codes, headers, and body content. Don't partially validate responses or make assumptions about response structure.appwrite/appwrite5 discussions
- Secure examples correctnessWhen implementing or documenting security-related plugins/features, ensure examples are both *secure* and *operationally correct*: avoid leaking sensitive data, match cookie/transport settings, use the correct authentication header formats, and ensure authentication happens before authorization/restriction.apache/apisix5 discussions
- API contract consistencyWhen defining or documenting APIs/plugins, ensure the declared contract matches how the system actually resolves requests and config fields. Validate examples and client expectations against these checks:apache/apisix5 discussions
- Prefer precise typingUse precise types instead of `Any`, and avoid unnecessary `typing.cast` by relying on type-guard utilities and existing type narrowing. In tests, prefer the concrete pytest types/fixtures (e.g., `pytest.MonkeyPatch`) over broad `Any`.anthropics/anthropic-sdk-python5 discussions
- Simplify complex expressionsExtract repeated expressions and complex conditional logic into clear, readable variables to improve code maintainability and reduce cognitive load. **Key practices:**ant-design/ant-design5 discussions
- Semantic naming consistencyChoose semantically clear and consistent names across related elements in your codebase. Names should convey their purpose without requiring additional context or explanation, and related elements should follow consistent naming patterns.ant-design/ant-design5 discussions
- React component API clarityEnsure React component APIs are well-designed with accurate TypeScript interfaces, clear documentation, and intuitive developer experience. This includes: (1) Using precise type definitions that match actual functionality, avoiding misleading exposed props from internal implementations, (2) Providing accurate property descriptions in documentation that...ant-design/ant-design5 discussions
- Extract common patternsWhen you encounter repeated code patterns, conditional logic within loops, or similar implementations across components, extract them into reusable utilities or common styles. This improves maintainability, reduces bundle size, and makes the codebase more consistent.ant-design/ant-design5 discussions
- Consistent null safety patternsMaintain consistent approaches to null and undefined handling throughout the codebase. Use optional chaining (`?.`) for safe property access, but be mindful that it may not always be equivalent to explicit type and null checks. When accessing properties on values that could be objects, always include explicit null checks alongside type checks since `typeof...ant-design/ant-design5 discussions
- Configuration documentation standardsEnsure configuration properties and settings are documented with consistent formatting and precise specifications. Configuration property names should be wrapped in backticks for proper formatting in documentation and changelogs. Version dependencies must specify exact version ranges rather than vague references like "latest version". Documentation should...ant-design/ant-design5 discussions
- avoid redundant operationsIdentify and eliminate redundant computations, function calls, and expensive operations that can be cached, memoized, or combined. This includes avoiding repeated function invocations with the same parameters, caching expensive calculations, and combining multiple operations that access the same data.angular/angular5 discussions
- API consistency patternsEnsure that similar APIs follow consistent patterns and conventions across the codebase. When designing or modifying APIs, maintain the same expressivity, return type patterns, and usage conventions as existing similar APIs.angular/angular5 discussions
- AI documentation clarityEnsure AI-related documentation, comments, and explanations are clear, accurate, and well-structured. This includes fixing spelling errors, using precise terminology, adding necessary context about experimental features, and employing active voice for better readability.angular/angular5 discussions
- Add explanatory commentsCode should include explanatory comments when the purpose, behavior, or context is not immediately clear from reading the code itself. This is especially important for:angular/angular5 discussions
- Write audience-appropriate documentationDocumentation should be written from the perspective of its intended audience, using language and detail levels appropriate for that audience. Focus on what matters most to the reader rather than technical implementation details.alacritty/alacritty5 discussions
- prefer early returnsUse early returns and guard clauses to reduce nesting levels and improve code readability. When you have multiple conditional branches or error conditions, return early from the function rather than creating deeply nested if-else structures.alacritty/alacritty5 discussions
- Configuration validation feedbackAlways validate configuration options and provide clear feedback to users about potential issues. This includes warning about unused configuration keys, preventing redundant options, and ensuring cross-platform compatibility.alacritty/alacritty5 discussions
- Configuration documentation accuracyEnsure configuration documentation is accurate, consistent, and clearly indicates optional versus required values. Use consistent terminology throughout documentation, provide accurate technical details, and make examples actionable for developers.alacritty/alacritty5 discussions
- Avoid unwrap on nullablesNever use `unwrap()` on nullable values that could reasonably be None, as this can cause crashes that are harder for users to work around than bugs. Instead, provide graceful fallbacks or proper error handling.alacritty/alacritty5 discussions
- avoid unnecessary operationsEliminate redundant work by implementing early returns, avoiding unnecessary clones/references, and skipping computations when results won't be used. This fundamental optimization reduces CPU cycles and improves performance across hot code paths.alacritty/alacritty5 discussions
- Validate nulls explicitlyAlways check for null values before using them, and use Python's idiomatic patterns to make these checks concise and readable. This prevents unexpected errors and makes code more maintainable.apache/airflow5 discussions
- Use system configuration defaultsAlways use the configuration system's default values instead of hardcoding defaults in the code. This ensures consistency across the application and makes configuration management more maintainable.apache/airflow5 discussions
- Maintain code consistencyEnsure consistency throughout the codebase by following established patterns for both UI components and code structure. Specifically: 1. Use semantic color names and variables rather than hardcoded values to maintain theme consistency and facilitate future changes:apache/airflow5 discussions
- Internationalize ui textAll user interface text must be internationalized using the appropriate i18n module instead of hardcoded strings. This ensures the application can be properly localized for different languages and regions.apache/airflow5 discussions
- Handle exceptions with specificityUse specific exception types and avoid masking errors through overly broad exception handling or default values. This improves error diagnosis and system reliability.apache/airflow5 discussions
- Documentation best practicesDocumentation should follow established best practices to ensure clarity, consistency, and usefulness: 1. **Use proper link types**: Use relative links for internal resources and absolute HTTP links only for external resources.apache/airflow5 discussions
- Single-Transaction LockingFor any shared mutable system state (receipts/ledgers, stage files + sidecars, and derived artifacts), treat the operation as one transaction: acquire a single shared lock, perform all read/validate/merge/emit/write steps (and any dependent compile/derivation) while holding it, then release.awslabs/aidlc-workflows5 discussions
- Verify properties before loggingWhen logging object properties, always verify that the property names exactly match the actual structure of the object being logged. Incorrect property names (like 'responses' instead of 'response') or non-existent properties will result in undefined values in logs, reducing their usefulness for debugging and troubleshooting.vercel/ai5 discussions
- Maintain API naming consistencyWhen working with AI model interfaces and result objects, ensure consistent property naming across related components. The AI ecosystem involves multiple providers and model types, making naming consistency crucial for maintainable code.vercel/ai5 discussions
- Document API schemasAdd comprehensive JSDoc comments to all API interfaces, types, and schema definitions. This documentation should: 1. Include links to official external documentation when availablevercel/ai5 discussions
- Consistent provider optionsWhen designing APIs that support multiple providers or service integrations, implement consistent patterns for handling provider-specific options. This includes proper validation, separation of request vs. non-request options, and clear type definitions.vercel/ai5 discussions
- Explicit Vercel ConfigurationTreat Vercel deployment as a configuration contract: declare dependency/version/runtime settings explicitly and align your code layout with Vercel’s discovery (or override it explicitly).vercel-labs/agent-skills5 discussions
- Guard trust boundariesTreat every point where data crosses a trust boundary — server to client, client to server, or internal module to external provider — as a security checkpoint, not a pass-through.decolua/9router5 discussions
- Clear, real-implementation test assertionsTests must exercise the actual production code and fail with clear, actionable diagnostics rather than cryptic errors. - Import and test the real implementation instead of duplicating logic inline. A test that reimplements the function under test (e.g., copy-pasting `stripReasoningContent` into the test file) can pass even when the real code is broken;...Decolua/9Router5 discussions
- Document API contractsWhen publishing a function/snippet, explicitly define the API contract: (1) platform/runtime assumptions, (2) input shape and required types, (3) option defaults/behavior, and (4) output/return type consistency. Ensure examples and docs match the contract.30-seconds/30-seconds-of-code5 discussions
- Consistent, Clear IdentifiersUse naming that is consistent with the surrounding code/style, avoids ambiguity, and preserves semantic meaning—both in code and in documentation. Rules:30-seconds/30-seconds-of-code5 discussions
- Documentation Must ExplainEnsure inline docs and comments are accurate, clear, and justified: - **Match implementation defaults:** If JSDoc mentions “default”, it must reflect what the code actually does. If there’s a real default value, document it (e.g., with an `@default` tag).colinhacks/zod4 discussions
- Define Validation ContractsWhen adding/maintaining API validation schemas, make the input contract explicit: specify exactly what input types are accepted, and whether the schema is parsing (strict mapping) or coercing/converting values. Don’t rely on assumptions about built-in JS semantics or on a single runtime’s concrete types.colinhacks/zod4 discussions
- Protect render loop performanceEnsure render loop operations stay within frame time budget (typically 16.67ms for 60fps). Avoid expensive computations, traversals, and I/O operations during frame rendering. Instead, compute and cache results ahead of time or move heavy operations to background tasks.zed-industries/zed4 discussions
- Contextualize don't panicAlways provide meaningful context for errors and avoid code that can panic in production. Use `.context()` or `.with_context()` to add rich error information, making debugging easier. Replace `.unwrap()` and `.expect()` with proper error handling mechanisms like error propagation or logging.zed-industries/zed4 discussions
- Background process blocking operationsAlways move potentially blocking operations to background threads to maintain UI responsiveness. Use appropriate spawning mechanisms based on the operation type:zed-industries/zed4 discussions
- standardize build configurationsEnsure build configurations are consistently propagated through all build steps and output directories follow standardized patterns. This prevents configuration mismatches that can cause deployment issues and makes CI/CD pipelines more reliable.facebook/yoga4 discussions
- optimize memory layoutPrioritize memory-efficient data structures and algorithms by favoring stack allocation over heap allocation, utilizing bit packing for compact storage, and applying proper bit masking for data integrity. When designing iterators or containers, consider whether operations can avoid dynamic allocation - most backtracking scenarios use empty vectors that...facebook/yoga4 discussions
- Improve code readabilityEnhance code clarity and maintainability by applying several readability techniques: extract repeated expressions into well-named variables, simplify complex boolean logic, use proper constant declarations, and remove redundant code that sets default values.facebook/yoga4 discussions
- explicit code declarationsAlways make code declarations explicit and consistent to improve readability and maintainability. This includes specifying all property attributes, using const for immutable parameters, and avoiding misleading naming conventions.facebook/yoga4 discussions
- Evaluate synchronization necessityBefore implementing thread safety mechanisms like atomic operations or mutexes for global variables, critically assess whether perfect synchronization is actually required for program correctness. Consider the performance cost of synchronization against the importance of data accuracy.facebook/yoga4 discussions
- Simplify conditional logicPrefer concise conditional expressions over verbose nested conditions and unnecessary boolean variables. This improves readability and reduces cognitive overhead.cloudflare/workers-sdk4 discussions
- ensure test isolationTests must be isolated and not leak state between runs. This includes properly cleaning up mocks, spies, and any global state modifications to ensure reliable and maintainable test suites.cloudflare/workers-sdk4 discussions
- changeset validation standardsEstablish comprehensive validation for changesets to ensure reliable release automation. Changesets are required for all releasable artifacts, including internal refactors, as they drive the release process. Implement validation to enforce proper changeset format, meaningful descriptions, and correct semantic versioning.cloudflare/workers-sdk4 discussions
- HTTP protocol complianceEnsure HTTP protocol implementations strictly follow RFC standards and handle edge cases correctly. This includes proper header parsing that respects quoted-string constructions, realistic port value assignments, and appropriate status code filtering.cloudflare/workerd4 discussions
- Connection reuse safetyWhen implementing network connection reuse, prioritize safety over performance by enforcing sequential request patterns and clear resource ownership. Connection reuse should be supported to avoid the overhead of creating new connections for each request, but must include proper safeguards to prevent concurrency issues and resource conflicts.cloudflare/workerd4 discussions
- Add explanatory commentsWhen code behavior, limitations, or implementation decisions are not immediately obvious from reading the code itself, add explanatory comments to clarify the reasoning and context. This is especially important for:cloudflare/workerd4 discussions
- Use design tokensCentralize visual styles and prefer theme variables over hardcoded values. Motivation: duplicate hardcoded colors, repeated color classes, inconsistent sizing, and ad-hoc styles reduce maintainability and make global theme changes error-prone. How to apply it:wavetermdev/waveterm4 discussions
- Propagate errors clearlyAlways return and propagate errors; surface them to callers and the UI, and clean up resources on error paths. Motivation - Avoid hiding failures by logging only or encoding errors as special string values. Returning errors lets callers decide how to handle, retry, or present failures. Ensure resources (files, network streams, conex) are closed with defer...wavetermdev/waveterm4 discussions
- platform-specific configCentralize OS-specific configuration and modifier mappings in a dedicated config/adapter module and document global declaration files. Motivation: key modifiers (Cmd/Meta/Alt/Option), global shortcuts, and shared types behave differently across platforms; putting the logic in one place avoids inconsistent handling, duplicate OS checks, and brittle startup...wavetermdev/waveterm4 discussions
- SSE and Sync EligibilityWhen implementing networking/event-streaming and bidirectional sync, make event delivery correctness explicit: who owns the subscription, who owns cursor advancement, and whether an event should be echoed back.warpdotdev/warp4 discussions
- Secret and Inert SafetyWhen handling auth secrets, user directory/path-based configuration, or shell-generated code, treat any value that could reveal identity/organization or execute code as *sensitive* and *untrusted by default*.warpdotdev/warp4 discussions
- Invariant Diff MatchingWhen implementing matching/diff logic (especially for code/entities), define and test the algorithmic invariants you rely on, and avoid fragile heuristics.warpdotdev/warp4 discussions
- Cache Key ConsistencyWhen you cache UI/model state, make the cache key and lifecycle unambiguous: - **Key boundary:** Perform the cache lookup using the exact key form the cache was populated with. Apply normalization/transformation *after* the lookup (only when constructing the output key/label), unless you also normalize consistently when inserting.warpdotdev/warp4 discussions
- Validate before expensive operationsPerform lightweight validation checks before executing expensive operations to avoid unnecessary resource consumption. This is especially important in hot paths or frequently called functions.microsoft/vscode4 discussions
- Stable Keys and OrderingWhen code derives behavior (actions, dedupes, counts, ordering) from collections, make the algorithm deterministic by using stable identifiers and centralized predicate/key logic—never by relying on mutable positional indexes or ad-hoc normalization scattered across call sites.microsoft/VSCode4 discussions
- Optimize algorithmic complexity firstWhen implementing algorithms, prioritize reducing computational complexity before adding special cases or optimizing for specific scenarios. Key practices:microsoft/vscode4 discussions
- Handle configuration value changesConfiguration values should be properly initialized and stay updated throughout their lifecycle. Follow these guidelines: 1. Initialize configuration values immediately upon service creation, not just in change handlers:microsoft/vscode4 discussions
- Cargo config in CIWhen adjusting Cargo behavior for CI (especially network-related settings), apply configuration via Cargo’s CLI using `--config key=value` flags and keep it consistent across all Cargo subcommands (build, test, clippy).microsoft/VSCode4 discussions
- Comprehensive test structureTests should focus on comprehensive coverage of main logic flows rather than trivial functions, use established testing patterns like TestCommonStruct for end-to-end validation, and maintain proper table-driven test formatting for readability and maintainability.volcano-sh/volcano4 discussions
- Always check errorsAlways check and handle errors returned from function calls, especially API operations, before proceeding with subsequent logic. Unchecked errors can lead to inconsistent state, data corruption, or unexpected behavior.volcano-sh/volcano4 discussions
- Document AI model capabilitiesProvide clear, comprehensive documentation for AI model capabilities, especially for multimodal features and deployment scenarios. Include: 1. Explicit documentation of supported input types and formatsvllm-project/vllm4 discussions
- Use parameterized queriesAlways use parameterized queries with bind variables instead of string concatenation or formatting when constructing SQL statements. This prevents SQL injection attacks and improves query performance through better statement caching.vitessio/vitess4 discussions
- Standardize error wrapping patternsUse consistent error wrapping patterns to preserve error context and ensure proper error code propagation. Always: 1. Use vterrors.New/Errorf when creating new errors to include error codesvitessio/vitess4 discussions
- Metric design best practicesDesign metrics to be reliable and maintainable by following these key principles: 1. Initialize metrics with zero values to ensure consistent existence:vitessio/vitess4 discussions
- Log levels and clarityChoose appropriate log levels and write clear, meaningful log messages that provide necessary context without creating noise. Follow these guidelines:vitessio/vitess4 discussions
- Explicit nil handlingAlways handle nil values explicitly in your code to improve clarity and prevent subtle bugs. When a function needs to deal with potentially nil values:vitessio/vitess4 discussions
- Environment-portable configuration managementEnsure all configurations are environment-portable and follow current best practices for the target platforms. This includes: 1. Using environment variables instead of hardcoded paths or user-specific valuesvitessio/vitess4 discussions
- Use optional patternsChoose the most appropriate pattern for handling potentially undefined or null values. When designing types, prefer optional properties (`?:`) over nullable types (`| null`) when a value is conceptually "not yet computed" rather than explicitly null.vitejs/vite4 discussions
- Optimize glob operationsWhen using glob patterns for file system operations, ensure optimal performance and consistent behavior by configuring glob libraries appropriately and handling paths efficiently:vitejs/vite4 discussions
- Minimize memory allocationsChoose methods and patterns that reduce unnecessary memory allocations and object creation to improve performance. When working with buffers, prefer direct methods like `Buffer.byteLength()` over approaches that create intermediate objects:vitejs/vite4 discussions
- Manage configuration inheritance carefullyWhen designing configuration systems, establish clear default values and inheritance patterns. Follow these principles: 1. Set explicit defaults that can be overridden by frameworks and usersvitejs/vite4 discussions
- Leverage native toolingPrioritize native or Rust-based implementations of build tools over their JavaScript counterparts to significantly improve performance in both development and build phases. Tools like Rolldown (replacing Rollup and esbuild) can reduce build times and provide a more consistent experience between development and production environments.vitejs/vite4 discussions
- Evolve APIs with compatibilityWhen evolving APIs, maintain backwards compatibility while introducing new features by following a staged deprecation approach: 1. Introduce new APIs alongside existing ones without deprecation warningsvitejs/vite4 discussions
- Document code purposefullyHigh-quality code documentation improves maintainability and helps other developers understand your intentions. Follow these practices: 1. **Use appropriate JSDoc annotations** to indicate API visibility and status:vitejs/vite4 discussions
- Clean configuration organizationOrganize configuration settings logically and avoid redundancy in project configuration files. Group related options into appropriate sections, eliminate duplicated settings (especially those already provided by extended configurations), and document non-obvious choices with explanatory comments.vitejs/vite4 discussions
- Break down complex functionsImprove code readability and maintainability by decomposing large, complex functions into smaller, focused ones. When a function handles multiple responsibilities or becomes difficult to understand at a glance, extract logical parts into well-named helper functions.vitejs/vite4 discussions
- explicit null checksAlways verify that pointers and function return values are not null before dereferencing or using them. This prevents crashes and undefined behavior, especially when working with C functions or manual memory management.vlang/v4 discussions
- Document algorithm behaviorWhen implementing or documenting algorithms, clearly specify their behavior, expected outputs, and usage patterns. This includes documenting mathematical operation semantics, output characteristics, and providing complete examples that demonstrate the algorithm's behavior.vlang/v4 discussions
- Configure socket blocking behaviorAlways explicitly configure socket blocking behavior when creating TCP connections, and provide compile-time flags for backwards compatibility when changing default behaviors.vlang/v4 discussions
- Use direct documentation styleWrite documentation using direct, clear language that addresses the reader directly. Follow these style guidelines: 1. Use direct address instead of referring to "users" - write "You can configure..." rather than "Users can configure..."astral-sh/uv4 discussions
- Respect connectivity stateApplications should gracefully handle different network connectivity states and provide appropriate feedback to users. Follow these guidelines: 1. **Check connectivity state before network operations** - Always verify if the application is in offline mode before attempting network requestsastral-sh/uv4 discussions
- Consistent authentication patternsDesign API authentication mechanisms with consistent patterns, clear documentation, and helpful error messages. When implementing authentication: 1. **Document authentication requirements explicitly**:astral-sh/uv4 discussions
- Balance test performance considerationsWhen writing tests, consider both thoroughness and execution time. For operations with significant overhead (like Python installations, downloads, or filesystem operations), it's acceptable to consolidate multiple assertions into a single test.astral-sh/uv4 discussions
- optimize algorithmic complexityWhen implementing algorithms, prioritize performance by avoiding unnecessary computations and choosing efficient approaches. Consider algorithmic complexity early in design and look for opportunities to eliminate redundant operations or expensive calculations when simpler alternatives exist.Unstructured-IO/unstructured4 discussions
- Document configuration reasoningAlways document the reasoning behind configuration decisions, especially for temporary settings like dependency pins, parameter choices, and version constraints. Include explanations of why the configuration was needed, what problem it solves, and when it might be safe to remove or update.Unstructured-IO/unstructured4 discussions
- Database schema complianceEnsure database integrations use correct field names, data types, and schema conventions specific to each database system. Different databases have special field naming requirements and data type expectations that must be respected to avoid runtime errors and ensure proper functionality.Unstructured-IO/unstructured4 discussions
- workspace dependency consistencyAll internal project dependencies should use workspace configuration instead of direct path or git references to ensure consistent versioning and build behavior across the monorepo. Maintain the standard `{ workspace = true }` syntax format and avoid redundant configuration options when using workspace dependencies.unionlabs/union4 discussions
- Validate before type conversionsAlways validate input constraints and use safe conversion methods before performing type conversions that could fail or produce undefined behavior. Avoid arbitrary casting with `as` operators, especially when the source value range may not fit the target type.unionlabs/union4 discussions
- Use structured logging fieldsPrefer structured logging fields over string formatting in tracing logs to improve searchability, parsing, and consistency. Use field syntax like `field = %value` or `%field` instead of embedding values directly in log messages. Keep log messages single-line, lowercase, and include relevant context as separate fields.unionlabs/union4 discussions
- Effect-based API clientsUse Effect-based HTTP clients with specific error types instead of throwing generic exceptions or relying on third-party HTTP libraries like axios. API functions should return Effects with proper error types rather than throwing errors, enabling better error handling and composability.unionlabs/union4 discussions
- Configuration file completenessEnsure all configuration files contain required fields, maintain proper structure, and follow consistent formatting standards. Configuration files should be complete with all mandatory nodes present, properly sorted for consistency, and preserve critical values that shouldn't be auto-updated.unionlabs/union4 discussions
- API interface designDesign APIs with clean abstractions, logical data organization, and proper layer separation. Structure interfaces to group related data hierarchically and provide convenient helper functions instead of requiring manual object construction.unionlabs/union4 discussions
- React rendering safeguardsThis standard ensures your React components render correctly and efficiently, preventing common pitfalls that cause errors or performance issues. ### Proper key usageshadcn-ui/ui4 discussions
- Provide actionable errorsError messages should not only identify problems but also guide developers toward solutions. Include specific steps, alternatives, or configuration changes that can resolve the issue.microsoft/typescript4 discussions
- Preserve API compatibility firstWhen modifying existing APIs, maintain backwards compatibility by adding new overloads rather than directly changing existing signatures. Mark old signatures as deprecated when introducing new patterns, but keep them functional until a major version change.microsoft/typescript4 discussions
- Consistent type algorithmsImplement consistent algorithms for type compatibility and comparison across different data structures. When developing type checking logic, ensure similar operations (like assignment compatibility, intersection, or mapping) behave predictably regardless of the underlying type structure.microsoft/typescript4 discussions
- Cache expensive computed valuesCache frequently accessed or computed values to avoid redundant calculations and property lookups. This applies to: 1. Loop invariant values 2. Expensive computationsmicrosoft/typescript4 discussions
- API documentation clarityEnsure API documentation, including changelogs and feature descriptions, prioritizes user understanding over implementation details. Write descriptions that explain what users can expect from the API behavior rather than how it's technically implemented. Avoid redundant information when context is already established (e.g., don't repeat "language server...astral-sh/ty4 discussions
- Validate configuration consistencyEnsure configuration values have consistent defaults across all systems and validate configuration structures using shared schemas. When introducing new configuration options, establish system-detected defaults that work intelligently based on browser or environment context, similar to existing patterns for date/time formats and timezone detection.twentyhq/twenty4 discussions
- Avoid expensive repeated operationsIdentify and eliminate expensive operations that are performed repeatedly, such as object creation in loops, redundant computations, or duplicate filtering operations. Cache expensive objects like RegExp instances, i18n instances, or computed results to improve performance and prevent memory leaks.twentyhq/twenty4 discussions
- Keep build tooling updatedMaintain up-to-date build and CI/CD tooling to leverage the latest features, performance improvements, and security patches. Regularly check for updates to build orchestration tools like Turborepo and use provided codemods for seamless upgrades. When configuring build pipelines, optimize task dependencies by using topological approaches (like Turborepo's...vercel/turborepo4 discussions
- Define API boundariesClearly specify what constitutes your public API contract to manage versioning expectations and documentation requirements. Distinguish between structured outputs intended for programmatic consumption versus human-readable outputs that may change without being considered breaking changes.vercel/turborepo4 discussions
- Configuration precision mattersEnsure configuration files are precise and stable to prevent unexpected build failures and runtime issues. This includes: 1. **Use correct syntax in configuration files**vercel/turborepo4 discussions
- Choose logging levels wiselySelect appropriate logging levels based on the frequency and importance of the logged operation. Use `trace` for high-frequency operations (e.g., operations executed once per package or file) to prevent log noise at lower verbosity levels, and reserve `debug` for less frequent, more significant events or aggregated information.vercel/turborepo4 discussions
- Boundary case handlingAlways handle boundary conditions explicitly in algorithms to prevent unexpected behavior. When implementing algorithms that involve iteration, traversal, or boundary checks, consider different approaches based on the specific requirements:vercel/turborepo4 discussions
- validate algorithm boundariesAlways validate boundary conditions and termination criteria in algorithms to prevent infinite loops, out-of-bounds access, and incorrect behavior. This includes checking loop bounds against variable type limits, validating range parameters, and ensuring proper termination conditions.tree-sitter/tree-sitter4 discussions
- Use meaningful prefixed namesNames should be semantically meaningful and properly prefixed to prevent namespace conflicts. In C, enum variants and global identifiers are added to the top-level namespace, so prefix them with their type name even if repetitive. Choose names that reflect domain concepts and purpose rather than technical implementation details. Prioritize clarity over...tree-sitter/tree-sitter4 discussions
- Simplify conditional logicImprove code readability by simplifying complex conditional expressions and control flow structures. Factor out repeated boolean expressions from nested conditions, use early returns instead of result variables when possible, and consolidate related conditional blocks.tree-sitter/tree-sitter4 discussions
- Respect environment overridesBuild systems and configuration scripts must respect standard environment variables and provide proper override mechanisms. This ensures flexibility for users with different build environments, cross-compilation needs, and custom toolchain requirements.tree-sitter/tree-sitter4 discussions
- Provide clear error contextAlways provide meaningful, specific error messages that help users understand what went wrong and why. Use descriptive language that indicates what was expected versus what was encountered. Leverage error context tools like `with_context()` to add relevant information about the operation that failed, and use debug formatting for error display to show...tree-sitter/tree-sitter4 discussions
- parameter type clarityDesign API parameters using specific, intention-revealing types rather than generic or ambiguous ones. This improves code readability, prevents misuse, and makes the API's behavior self-documenting.tree-sitter/tree-sitter4 discussions
- Optimize CI workflow syntaxWrite cleaner and more maintainable CI/CD workflows by following established syntax patterns and best practices. Use GitHub Actions' built-in features like `working-directory` instead of manual directory changes, employ proper shell quoting and efficient commands, and prefer single-line commands when appropriate.tree-sitter/tree-sitter4 discussions
- Conditional compilation guardsAlways use appropriate preprocessor directives to guard platform-specific, version-dependent, or feature-specific code. Ensure that conditional compilation checks accurately reflect the actual availability of features and APIs, not just version numbers or single configuration flags.tree-sitter/tree-sitter4 discussions
- validate input sanitizationAlways maintain input sanitization and validation mechanisms to prevent security vulnerabilities. Disabling built-in security features like path sanitization can expose applications to path traversal attacks and routing manipulation.traefik/traefik4 discussions
- Network information extractionWhen extracting network information from connections (such as remote addresses, proxy IPs, or forwarded headers), implement robust extraction methods that don't depend on specific connection wrapper ordering or implementation details. Use iterative unwrapping patterns and ensure all relevant network information is properly preserved and forwarded.traefik/traefik4 discussions
- API interface simplificationDesign APIs with clean, minimal interfaces that encapsulate internal logic and avoid exposing unnecessary complexity to consumers. Prefer methods that internally handle implementation details over exposing flags or parameters that clients must manage.traefik/traefik4 discussions
- Secure unsafe codeWhen working with unsafe code, follow these practices to minimize security vulnerabilities: 1. **Minimize scope**: Limit unsafe blocks to only the operations that require them.tokio-rs/tokio4 discussions
- Optimize algorithmic efficiencyPay careful attention to operations inside loops and recursive functions to avoid unexpected algorithmic complexity. Be particularly vigilant about: 1. **Hidden O(n²) operations**: Avoid operations that iterate over entire collections inside loops, as they can degrade performance significantly.tokio-rs/tokio4 discussions
- Memory ordering needs justificationWhen using atomic operations, explicitly justify the choice of memory ordering. Each use of a memory ordering should be documented with a clear explanation of why that specific ordering is sufficient and safe.tokio-rs/tokio4 discussions
- Granular feature flagsFeature flags should be designed with granularity to ensure dependencies are only required when absolutely necessary. When adding functionality that requires additional dependencies, create separate features rather than adding those dependencies to existing features.tokio-rs/tokio4 discussions
- Document null safety assumptionsWhen writing code that handles potentially null, undefined, or uninitialized values, always document safety assumptions with clear comments. This is especially important for unsafe blocks that manipulate raw pointers, uninitialized memory, or perform type conversions.tokio-rs/tokio4 discussions
- Code block formatting standardsWhen documenting code examples and shell commands in project documentation, follow these formatting standards to ensure consistency and clarity: 1. **Use appropriate language specifiers**:tokio-rs/tokio4 discussions
- Prefer explicit API designWhen designing APIs, favor simple and explicit interfaces over flexible but complex ones. This reduces cognitive load, improves compile-time checking, and makes the code more maintainable.huggingface/tokenizers4 discussions
- Choose semantically clear identifiersSelect parameter and method names that accurately describe their purpose and behavior, avoiding ambiguous terms that can lead to confusion. Consider these guidelines:huggingface/tokenizers4 discussions
- Choose optimal data structuresSelect data structures based on their algorithmic complexity and usage patterns. Consider the tradeoffs between different structures (e.g., Vec vs HashMap) and their impact on performance. Key considerations:huggingface/tokenizers4 discussions
- Resource cleanup on errorsAlways ensure proper resource cleanup in error paths to prevent leaks. Use defer functions with explicit error checking for closing operations, and log any close errors that occur during cleanup.hashicorp/terraform4 discussions
- Guard shared stateConsistently protect shared state with appropriate synchronization mechanisms and ensure proper cleanup to prevent race conditions and deadlocks in concurrent environments.hashicorp/terraform4 discussions
- Explicit protocol interfacesDesign protocol interfaces with explicit behavior definitions rather than relying on implicit conventions. Clearly specify the purpose and expected handling of each field, especially when adding new parameters or response structures.hashicorp/terraform4 discussions
- Ensure test isolationTests should be completely isolated from each other and clean up after themselves to prevent interference. 1. **Use testing utilities properly**: Leverage the standard library's testing helpers correctly.hashicorp/terraform4 discussions
- Consistent documentation formattingMaintain consistent style in documentation files to improve readability and professionalism. Specifically: 1. **Command references**: Use a consistent format when referring to CLI commands. Prefer either:hashicorp/terraform4 discussions
- Configuration override precedenceWhen designing systems with configurations that can be specified at multiple levels (global vs local, environment vs file, default vs override), establish and document a clear precedence model. Always prioritize more specific configurations over general ones.hashicorp/terraform4 discussions
- Clarify test documentationEnsure all testing-related documentation is clear, accurate, and user-focused. Use precise terminology when describing test components, fully explain configuration attributes with their effects, and provide complete examples that demonstrate proper usage.hashicorp/terraform4 discussions
- Choose appropriate API typesSelect the simplest data types that satisfy requirements when designing API signatures. Avoid using complex types (like cty.Value) when simpler types (like string, int, bool) would suffice. This improves API usability, reduces complexity, and simplifies client implementations while maintaining consistent patterns across the API.hashicorp/terraform4 discussions
- Validate before configuration generationAlways validate system capabilities and existing configuration state before generating new configuration entries or profiles. This prevents unnecessary configuration generation, improves startup performance, and avoids presenting unusable options to users.microsoft/terminal4 discussions
- Safe optional handlingAlways use safe patterns when working with optional, nullable, or potentially empty types. Avoid direct comparisons with optional values and ensure proper initialization of nullable members.microsoft/terminal4 discussions
- Safe null handling patternsAlways use consistent and safe patterns when dealing with potentially null or undefined values. This includes using safe casting methods, explicit null checks, proper initialization, and immutable variables after validation.microsoft/terminal4 discussions
- Reuse defined resources consistentlyAlways reuse existing defined constants, resources, and reusable components instead of duplicating values or creating redundant implementations. This improves maintainability, ensures consistency across the codebase, and reduces the risk of introducing inconsistencies when values need to be updated.microsoft/terminal4 discussions
- Minimize reference counting overheadAvoid unnecessary reference counting operations that can impact performance, especially in frequently called code paths. Use move semantics, appropriate pointer types, and efficient parameter passing to reduce AddRef/Release churn.microsoft/terminal4 discussions
- Implement defensive validationAlways validate inputs, check boundaries, and avoid relying on undocumented API behavior or assumptions about how functions handle edge cases. When dealing with potentially null or invalid data, implement explicit checks rather than assuming the API will behave consistently across all scenarios.microsoft/terminal4 discussions
- API parameter explicitnessAlways use correct and explicit parameters when calling APIs, rather than relying on defaults or passing incorrect values. This includes passing appropriate objects to API methods, specifying all required parameters explicitly, and using correct operation patterns.microsoft/terminal4 discussions
- Tensor-aware control flowWhen working with TensorFlow tensors, avoid using Python comparison operators (`<`, `>=`, `==`) or conditional checks that expect Boolean scalars. Python operators evaluate eagerly and won't work correctly with tensors that represent deferred computations.tensorflow/tensorflow4 discussions
- Complete docstring structureFunction documentation should follow a consistent structure that includes all necessary components to be complete and usable. Each docstring should: 1. Start with a one-line summary that concisely describes the function's purposetensorflow/tensorflow4 discussions
- Centralize configuration settingsPlace configuration settings in centralized, appropriate locations rather than duplicating them across multiple files. This improves maintainability by ensuring changes only need to be made in one place.tensorflow/tensorflow4 discussions
- Trust GetX accessorsWhen working with protocol buffer messages or similar objects that provide GetX() accessor methods, avoid redundant nil checks before calling these methods. GetX() methods are designed to handle nil receivers safely, allowing for cleaner and more concise code.temporalio/temporal4 discussions
- Safe lock usage patternsFollow these critical patterns when using locks to prevent deadlocks, resource leaks, and performance issues: 1. Use consistent lock naming: ```go // Prefertemporalio/temporal4 discussions
- Ensure deterministic executionWhen working with Temporal workflows, maintaining deterministic behavior is critical for reliable replay and execution across distributed systems. Key practices:temporalio/temporal4 discussions
- Dynamic config usage principlesUse dynamic configuration selectively and effectively by following these principles: 1. Only use dynamic config for values that need runtime modification:temporalio/temporal4 discussions
- Consistent naming patternsMaintain consistent naming patterns across related components and services. When implementing equivalent functionality in different services, use identical field/method names. When naming related fields that form logical groupings, either:temporalio/temporal4 discussions
- Synchronization primitive selectionChoose appropriate synchronization primitives and ensure proper protection of shared state to avoid race conditions and deadlocks. Prefer regular mutexes over RWMutex unless read-heavy workloads justify the complexity, as RWMutex can be a performance trap. When accessing shared state, ensure the entire read-modify-write operation is atomic by keeping it...gravitational/teleport4 discussions
- prefer simpler patternsChoose simpler, more readable code patterns over complex alternatives to improve maintainability and reduce cognitive load. This includes avoiding unnecessary complexity in variable assignment, function parameters, and styling approaches.gravitational/teleport4 discussions
- Optimize computational complexityAlways analyze the computational complexity of algorithms and choose efficient implementations to avoid performance bottlenecks and security vulnerabilities. Pay special attention to avoiding O(N²) algorithms that can create DoS risks, eliminate unnecessary computational overhead, and select appropriate data structures.gravitational/teleport4 discussions
- Authenticated health checksWhen implementing health checks for external services, verify the complete communication stack rather than just basic connectivity. Health checks should validate that your service can successfully authenticate and perform actual operations, not merely establish network connections.gravitational/teleport4 discussions
- Add contextual loggingAdd informative log messages with sufficient context to help operators diagnose issues, understand system state, and trace complex operations. Include relevant error details, system configuration status, and operational flow information.gravitational/teleport4 discussions
- Mathematical precision mattersWhen implementing mathematical algorithms, ensure precise terminology and correct implementation of mathematical concepts. This is especially important for complex domains like differentiation, optimization, or numerical methods.tensorflow/swift4 discussions
- Document environment variablesWhen using configurable components, clearly document all relevant environment variables and their effects. Include examples showing how to set variables for common use cases, and specify any platform-specific differences. For environment variables that affect runtime behavior, clearly document when they need to be set and any order dependencies.tensorflow/swift4 discussions
- state boundary managementEnsure proper state management when passing reactive values across component and function boundaries. State reactivity can be lost when values are read at the point of return rather than through getters, setters, or object properties.sveltejs/svelte4 discussions
- Simplify and deduplicate codeWrite concise, non-redundant code by eliminating unnecessary duplication and using simpler syntax where possible. This improves readability and maintainability.sveltejs/svelte4 discussions
- Documentation clarity standardsEnsure technical documentation clearly distinguishes between similar but different concepts, uses precise language, and provides unambiguous explanations. When documenting Vue features, explicitly label and differentiate between reactive and non-reactive data, different directive behaviors, and component patterns.sveltejs/svelte4 discussions
- Complete code examplesEnsure all code examples are complete, functional, and accurately demonstrate the intended concepts. Code examples should include all necessary imports, variable declarations, and interactive elements to be self-contained and runnable.sveltejs/svelte4 discussions
- API flexibility balanceWhen designing APIs, carefully balance simplicity for common use cases with flexibility for advanced scenarios. Consider whether to expose simple interfaces (strings, direct exports) that make typical usage ergonomic, or more flexible interfaces (objects, options parameters) that enable customization.sveltejs/svelte4 discussions
- Use Robust Error ContractsHandle errors in a predictable, maintainable way by (1) ensuring all failure-path variables are defined, (2) handling exceptions at one layer (no redundant try/catch), (3) validating external data at boundaries with Zod, and (4) using stable structured error fields instead of brittle string message matching.supermemoryai/supermemory4 discussions
- Prefer React PatternsWrite React components so state and events are handled using standard React patterns (hooks/state setters correctly, pending/loading comes from React/Form hooks, and key events don’t accidentally trigger default browser behavior). Also, pick the right navigation strategy when component-scoped data must be reset.supermemoryai/supermemory4 discussions
- Secure authentication flowsDesign APIs with secure authentication flows by following proper error handling and documentation practices. Avoid non-null assertions in authorization code, properly document URL format requirements, and provide clear configuration steps for auth providers.supabase/supabase4 discussions
- Protect sensitive API keysNever expose keys with elevated privileges (such as `service_role` or secret keys) in client-side code. These keys can bypass Row Level Security (RLS) and provide unrestricted access to your data. supabase/supabase4 discussions
- Pin dependency versionsAlways specify exact versions for dependencies in your configuration files and import statements to ensure consistent behavior across different environments. Unpinned dependencies can lead to unexpected breaking changes when packages are automatically updated to newer versions.supabase/supabase4 discussions
- Maintain network controlsCreate maintainable and clearly documented network access controls. Instead of hardcoding network restrictions, use dedicated tables that can be updated without code changes. Always document networking concepts with plain language explanations for developers unfamiliar with networking terminology.supabase/supabase4 discussions
- Maintain code consistencyEnsure consistent code organization, naming conventions, and structure throughout the codebase: 1. Use identical parameter names for similar components (e.g., `queryGroup="language"` instead of custom names)supabase/supabase4 discussions
- Handle external operations safelyAlways implement explicit error handling for external operations such as network requests, database queries, and API calls. When errors occur, either:supabase/supabase4 discussions
- Follow hooks rulesAdhere strictly to React hooks rules and best practices to ensure your components behave correctly and predictably. Common issues include: 1. **Manage dependencies properly**: Always include all dependencies in useEffect/useCallback dependency arrays or use useLatest() for values you intentionally exclude to prevent stale data issues.supabase/supabase4 discussions
- Document intent clearlyAdd clear documentation that explains not just what code does, but why certain approaches were chosen. This applies to: 1. **Complex code sections**: Add explanatory comments to complex logic, particularly SQL queriessupabase/supabase4 discussions
- organize code properlyMaintain clear code organization by placing code in appropriate files, directories, and modules. Respect module boundaries and create logical directory structures that reflect the code's purpose and domain.browserbase/stagehand4 discussions
- API parameter designDesign API methods with structured object parameters instead of ordered parameters or loose typing. Use proper TypeScript types rather than `any`, and consider parameter patterns that enhance safety and flexibility.browserbase/stagehand4 discussions
- Use environment-independent defaultsWhen designing configuration options, avoid relying on environment-specific defaults such as system character encodings, file paths, or platform-specific features. Instead, specify explicit defaults that work consistently across all supported environments. This prevents subtle bugs that manifest only in specific environments.spring-projects/spring-framework4 discussions
- Spring annotation best practicesWhen working with Spring annotations, follow these guidelines to avoid common issues: 1. **Use interface types for dependency injection**: When autowiring dependencies, declare fields using the interface type rather than the implementation class. This ensures proper behavior with proxies and AOP.spring-projects/spring-framework4 discussions
- Minimize lock contentionWhen implementing thread-safe code, minimize the scope and duration of locks to reduce contention and improve performance. Keep critical sections small, avoid redundant operations under locks, and consider whether pessimistic locking is appropriate for your use case.spring-projects/spring-framework4 discussions
- Consistent style conventionsApply consistent formatting and organization conventions throughout the codebase to enhance readability and maintainability: 1. Follow the project's `.editorconfig` settings for indentation style (tabs vs spaces) and other formatting rules.spring-projects/spring-framework4 discussions
- Explicit security documentationAlways provide explicit and accurate documentation for security-related configurations, including: 1. Use proper configuration property syntax with validation where possible (e.g., `configprop:spring.security.oauth2.resourceserver.jwt.audiences[]`)spring-projects/spring-boot4 discussions
- Session-specific configuration accessAlways access configuration through the appropriate session context rather than using global configuration access. This ensures that session-specific settings are respected and maintains consistency across different execution contexts.apache/spark4 discussions
- self-documenting code practicesWrite code that explains itself through clear structure and meaningful names, while adding targeted comments only where necessary for future maintainability. Extract complex logic into well-named functions with comprehensive documentation, but avoid redundant comments that duplicate what the code already expresses clearly.apache/spark4 discussions
- Resource cleanup responsibilityEnsure proper resource management by clearly defining cleanup responsibilities and implementing robust cleanup patterns. Resources should be closed by their creator, and cleanup must occur even when exceptions happen during resource creation or usage.apache/spark4 discussions
- Externalize configuration valuesAvoid hardcoding configuration values directly in code. Instead, make them externally configurable through appropriate mechanisms based on their usage patterns. Use environment variables for values that may need to change between deployments or runs, move configuration setup to appropriate lifecycle methods (like setupClass), and choose the right location...apache/spark4 discussions
- avoid null in ScalaAvoid using null values in Scala code and prefer Option types for representing optional values. Null usage can lead to NullPointerException at runtime and makes code less safe and predictable.apache/spark4 discussions
- Use existing API utilitiesAlways leverage existing utility hooks, constants, and navigation methods instead of implementing manual solutions. This ensures consistency across the codebase, improves testability, and reduces maintenance overhead.SigNoz/signoz4 discussions
- REST API conventionsFollow standard REST API conventions for HTTP methods, status codes, endpoint structure, and response completeness. Use appropriate access controls and implement proper pagination patterns.SigNoz/signoz4 discussions
- ensure migration idempotencyDatabase migrations must be designed to run safely multiple times without causing errors or data corruption. This involves using structured migration APIs instead of raw SQL, implementing proper checks for existing state, and avoiding unnecessary complexity that could lead to failures.SigNoz/signoz4 discussions
- Avoid inline stylesMove all inline styles to dedicated CSS/SCSS files to improve maintainability, consistency, and separation of concerns. Inline styles make components harder to maintain, reduce reusability, and violate the principle of separating presentation from logic.SigNoz/signoz4 discussions
- Modern React MountingWhen building React components that wrap external resources (e.g., WebGL/canvas), follow these rules: - Forward refs for React 18+ compatibility: use `forwardRef` rather than custom ref plumbing.paper-design/shaders4 discussions
- Verify algorithmic correctnessEnsure algorithmic implementations are correct before applying optimizations or complex conditional logic. This is especially critical for performance optimizations, computational complexity considerations, and batch processing logic where errors can have cascading effects.sgl-project/sglang4 discussions
- Use Optional types safelyAlways use proper nullable type annotations and safe access patterns to prevent runtime errors from null/undefined values. Use `Optional[Type]` or `Union[None, Type]` for nullable parameters, employ safe dictionary access with `.get()`, and handle None values explicitly in operations.sgl-project/sglang4 discussions
- Prevent race conditionsEnsure atomic operations and proper synchronization when multiple threads or processes access shared state. Race conditions occur when the timing of operations affects correctness, leading to data corruption, memory leaks, or inconsistent behavior.sgl-project/sglang4 discussions
- Optimize cache performancePrioritize cache performance by leveraging proven optimization techniques and avoiding performance anti-patterns. Use standard caching decorators like @lru_cache for functions that benefit from memoization, implement zero-copy operations when moving data between cache layers, and avoid unnecessary operations that degrade performance.sgl-project/sglang4 discussions
- standardize log output methodsUse `process.stdout.write` instead of `console.log` for controlled logging output to avoid linter issues and ensure consistent behavior. When using `process.stdout.write`, manually add newlines since they are not automatically appended like with `console.log`. Maintain consistent log message formatting with proper prefixes and structured layout.serverless/serverless4 discussions
- Use semantically meaningful namesChoose names that clearly convey purpose and intent rather than generic or ambiguous terms. Prefer specific, descriptive terminology that makes code self-documenting and reduces cognitive load for readers.oraios/serena4 discussions
- Use proper logging practicesAlways use logging instead of print statements, and choose appropriate log levels to avoid log spam. Print statements can contaminate the stdio buffer and break system functionality, especially in server environments.oraios/serena4 discussions
- explicit None handlingWhen operations cannot complete successfully or return meaningful results, explicitly return None rather than raising exceptions or using placeholder values. Document when None is expected and ensure consistent None handling throughout the codebase.oraios/serena4 discussions
- Exception chaining practicesAlways use exception chaining with `raise ... from e` when re-raising or wrapping exceptions to preserve the original error context and stack trace. This maintains debugging information and follows Python best practices for error propagation.oraios/serena4 discussions
- Ensure complete documentation qualityDocumentation should be comprehensive, clear, and provide all necessary context for understanding and using the code effectively. This includes several key aspects:oraios/serena4 discussions
- Thread management best practicesWhen working with threads or thread pools in concurrent code, follow these practices to improve reliability and debuggability: 1. **Always name your threads and thread pools** using the `thread_name_prefix` parameter. This makes debugging and monitoring much easier when issues arise.getsentry/sentry4 discussions
- Raise contextual error typesAlways raise specific, contextual exception types instead of generic exceptions. Include relevant error details that help identify the root cause and potential solutions. This improves error tracking, debugging, and system reliability.getsentry/sentry4 discussions
- Precise dependency versioningWhen specifying dependency version constraints in configuration files, be deliberate about minimum versions based on required features and compatibility requirements. Use the lowest compatible version constraint to maximize project compatibility, but ensure specific feature requirements are met.getsentry/sentry-php4 discussions
- Include practical examplesEnhance technical documentation with clear, practical code examples that demonstrate usage. This applies to: 1. Changelog entries for new features 2. API documentationgetsentry/sentry-php4 discussions
- Flexible configuration formatsSupport multiple configuration formats where appropriate (string, callable, object) to accommodate different frameworks and usage patterns. This improves developer experience across different ecosystems (like Laravel, Symfony) while maintaining type safety through proper validation.getsentry/sentry-php4 discussions
- Balance CI test coverageConfigure CI workflows to optimize both comprehensive testing and resource usage. For resource-intensive tests that may cause issues (like OOM errors with code coverage), split test suites and run coverage selectively:getsentry/sentry-php4 discussions
- Optimize React hook patternsDesign React hooks with performance and maintainability in mind by following these key principles: 1. Minimize useEffect usage - Update values directly when possible instead of using effects. Effects should only be used for true side effects, not for derived state updates.getsentry/sentry4 discussions
- Explicit optional type declarationsAlways explicitly declare optional types in interfaces and function parameters rather than relying on runtime checks or using `any`. This improves type safety, makes null/undefined handling requirements clear, and prevents runtime errors.getsentry/sentry4 discussions
- validate environment variable usageAlways validate environment variables with proper fallback logic and avoid unnecessary usage in tests or when defaults suffice. Check for truthiness rather than explicit None comparisons to handle empty strings, and ensure configuration values match their declared types and intended usage.semgrep/semgrep4 discussions
- Use appropriate log levelsChoose log levels based on the intended audience to prevent user-visible noise. Most logging should use `Logs.debug` rather than `Logs.info` or `Logs.err`, since info-level and above messages are visible to end users with `--verbose` or by default.semgrep/semgrep4 discussions
- Simplify complex logicBreak down complex code structures into simpler, more readable forms. Long indented blocks, verbose conditionals, and repetitive patterns should be simplified to improve code clarity and maintainability.semgrep/semgrep4 discussions
- Document configuration choicesAdd explanatory comments for non-obvious configuration settings, especially when they deviate from defaults or serve specific purposes. Configuration choices that aren't immediately clear should include comments explaining their rationale, impact, or relationship to other settings.semgrep/semgrep4 discussions
- Document code purposeEnsure that code elements have clear documentation explaining their purpose, behavior, and context. This includes function parameters (especially non-obvious ones), complex business logic, and magic values or constants.semgrep/semgrep4 discussions
- Design consistent tracing interfacesWhen implementing observability features like tracing, prioritize consistent and extensible API design. Use structured annotations that can accommodate future configuration options rather than simple flags. Place tracing instrumentation directly on the functions being measured rather than creating wrapper functions. Follow established naming conventions...semgrep/semgrep4 discussions
- CI workflow optimizationOptimize CI/CD workflows by prioritizing reliability over convenience and leveraging built-in platform features. When workflows generate files or have complex dependencies, use brute-force approaches like `make clean; make` to ensure reproducible builds, even if it seems inefficient. Simplify workflow steps by using native GitHub Actions features instead of...semgrep/semgrep4 discussions
- Benchmark performance assumptionsAlways validate performance concerns with actual measurements before making optimization decisions. Avoid making assumptions about what is "too slow" without benchmarking evidence.semgrep/semgrep4 discussions
- Add CI safety checksImplement defensive checks and error handling in CI/CD workflows to prevent failures and ensure robust operations. This includes validating preconditions, checking for edge cases, and using appropriate tools that preserve important information.semgrep/semgrep4 discussions
- Ensure deterministic resume behaviorWhen implementing persistence and resume functionality in durable execution systems, ensure that state is persisted at consistent event boundaries and that resume logic handles all execution states explicitly to maintain deterministic behavior.strands-agents/sdk-python4 discussions
- Extract complex logic helpersComplex or duplicated logic should be extracted into well-named helper functions to improve code readability and maintainability. This applies to: 1. Large blocks of code in functions that handle a specific subtaskrust-lang/rust4 discussions
- Contextual error messagesError messages should provide specific context about the error and guide users toward solutions. When reporting syntax errors like mismatched delimiters, include both the location of the error and references to related code elements to help users quickly identify the problem.rust-lang/rust4 discussions
- Structure configuration optionsDesign and document configuration options (feature flags, environment variables, conditional compilation) to be clear, consistent, and maintainable. Group related configurations together and avoid unnecessary splits or redundancies. Document the purpose and behavior of each option, including valid values and interaction effects.dotnet/runtime4 discussions
- Maintain consistent formattingEnsure consistent formatting and organization throughout the codebase to improve readability and maintainability. This includes: 1. **Consistent spacing and alignment**dotnet/runtime4 discussions
- Decompose complex algorithmsWhen implementing algorithms, break down complex methods that handle multiple concerns into smaller, more focused methods. This improves maintainability, makes edge cases easier to handle, and allows for more flexible reuse of algorithm components.dotnet/runtime4 discussions
- Choose appropriate error mechanismsUse the right error handling mechanism for each scenario: exceptions for recoverable situations, assertions only for true programming bugs, and consistent error codes for API boundaries. Don't assert unreachable for scenarios that could legitimately occur, such as in this example:dotnet/runtime4 discussions
- Support configuration extension patternsWhen designing configuration systems, provide both replacement and extension options for list-based settings to give users flexibility in how they modify default configurations.astral-sh/ruff4 discussions
- Maintain focused module structureKeep modules focused and well-organized by grouping related functionality together and splitting large files into logical submodules. Each file should have a clear, single responsibility. When a file grows too large or handles multiple concerns, consider breaking it into smaller, more focused modules.astral-sh/ruff4 discussions
- Leverage existing API utilitiesWhen implementing or consuming APIs, always prefer using existing utility methods and abstractions over manual implementations. This reduces code duplication, improves consistency, and helps avoid subtle bugs in conversion logic or interface handling.astral-sh/ruff4 discussions
- test real user interactionsWrite tests that simulate actual user behavior and verify real rendering outcomes rather than testing implementation details or internal state. Use `data-testid` attributes with `getByTestId` instead of `getByRole` for better maintainability, as it allows changing text and HTML structure without breaking tests. Focus on testing what users actually see and...TanStack/router4 discussions
- Maintain backward compatibilityWhen evolving APIs, always maintain backward compatibility to avoid breaking existing user code. Support both old and new syntax during transition periods, and use deprecation warnings to guide users toward new patterns.TanStack/router4 discussions
- Ensure documentation clarityDocumentation should be clear, accurate, and consistently structured to provide maximum value to developers. Avoid overly broad or inaccurate statements that may mislead users, and prefer explanatory content over warnings when possible.TanStack/router4 discussions
- API backward compatibilityWhen updating existing APIs, maintain backward compatibility by deprecating old options rather than introducing breaking changes. Add new properties while keeping old ones functional, marking them as deprecated to guide migration without forcing immediate updates.TanStack/router4 discussions
- Robust error handlingImplement comprehensive error handling to prevent crashes and aid debugging. This includes: 1. **Use try/catch blocks for risky operations** - Especially when parsing JSON or using browser APIs that might throw exceptions:RooCodeInc/Roo-Code4 discussions
- Prevent unnecessary processingOptimize React component performance by minimizing unnecessary operations that can slow down your application: 1. **Memoize stable components** to prevent unnecessary re-renders when parent components update:RooCodeInc/Roo-Code4 discussions
- Optimize React componentsApply these React optimization techniques to improve component performance and maintainability: 1. **Use stable, unique keys for list items** - Avoid using array indices as keys when rendering lists that can change. Instead, use unique identifiers from your data.RooCodeInc/Roo-Code4 discussions
- Optimize algorithm implementationsWhen implementing algorithms, ensure they are both efficient and correct across all input cases. Key considerations: 1. **Pattern matching edge cases**: Ensure regex patterns handle all edge cases, including matches at the beginning of strings. For example, replace `/[^\\]`[^`\n]+`/` with `/(?:^|[^\\])`[^`\n]+`/` to catch backticks at string start.RooCodeInc/Roo-Code4 discussions
- Names reflect semantic purposeIdentifiers (variables, properties, keys, IDs) should accurately reflect their semantic purpose and context. Names should be chosen to clearly communicate the meaning and role of the element within its specific context, not just its technical type or generic purpose.RooCodeInc/Roo-Code4 discussions
- Consistent output path specificationConfiguration files defining operations that generate data outputs must always include a `<save_to>` element specifying the output location. Follow established patterns for similar operations, typically using predictable paths like `.roo/temp/pr-[PR_NUMBER]/[operation]-output.{json|diff}`. This ensures operation outputs are consistently stored and easily...RooCodeInc/Roo-Code4 discussions
- Configuration consistency checkEnsure that configuration files and settings are consistent with their intended functionality and maintain portability across different environments. RooCodeInc/Roo-Code4 discussions
- Conditional debug loggingRemove or conditionally disable console.log and console.debug statements before committing code to production. These debugging statements create noise in browser consoles, may expose sensitive information, and can impact runtime performance.RooCodeInc/Roo-Code4 discussions
- model-appropriate configurationEnsure AI models use configuration settings that match their specific architecture and requirements. Different model families (e.g., BigCode vs LLaMA) require different tokenizer configurations, memory management settings, and parameter mappings. Avoid using generic or copy-pasted configurations across different model types.smallcloudai/refact4 discussions
- Required API PartitioningWhen designing cluster APIs/specs, explicitly partition endpoints into categories by *actor* and *compatibility obligation*, and document which categories alternative implementations must implement.redis/redis4 discussions
- Header Organization And CommentsKeep header edits readable and durable: 1) Don’t write brittle comments - Avoid referencing exact line numbers or file offsets (they drift and become misleading). Prefer describing the behavior/why, not where it currently is.redis/redis4 discussions
- Deterministic Control-Plane ProtocolsWhen multiple agents participate in cluster control-plane updates (e.g., TD, FC, nodes), treat the protocol as an algorithm and make its conflict-resolution and time/progression semantics explicit in the spec/code review contract.redis/redis4 discussions
- Atomic Contracts EnforcementDefine and enforce atomicity as an explicit contract: if correctness depends on thread/writer invariants, encode it in the API name/docs and validate it at usage sites; if a value can be concurrently updated, read/write it exclusively via atomic operations (no non-atomic peeking into parts of an atomic container).redis/redis4 discussions
- Simplify configuration setupAvoid redundant configuration parameters and prefer automated solutions over manual maintenance. Remove configuration options that duplicate library defaults, replace manual dependency lists with programmatic detection, and eliminate unused configuration logic when usage patterns change.remix-run/react-router4 discussions
- Provide explicit error handlingCreate custom, descriptive errors instead of allowing external dependencies or systems to fail with generic messages. Use consistent error handling utilities throughout the codebase rather than implementing ad-hoc error responses.remix-run/react-router4 discussions
- prefer built-in React typesFavor React's built-in types over custom interfaces when possible, and consolidate to standard library types for better maintainability and type safety. Use `PropsWithChildren` instead of creating custom component prop interfaces, leverage generics for type flexibility, and migrate away from deprecated types in favor of type-safe alternatives.remix-run/react-router4 discussions
- API backward compatibilityWhen evolving APIs, maintain backward compatibility by preserving existing public interfaces while adding new functionality through internal implementations or optional parameters. Avoid breaking changes that remove functionality without providing migration paths.remix-run/react-router4 discussions
- Optimize hot pathsIn performance-critical code paths that execute frequently, optimize to reduce unnecessary operations that can impact runtime performance.facebook/react4 discussions
- proper synchronization practicesEnsure thread safety by using appropriate synchronization mechanisms and understanding thread context. When working with shared mutable state, protect critical sections with proper synchronization to prevent race conditions and concurrent modifications. Choose the right synchronization approach for your use case - prefer language-provided utilities over...facebook/react-native4 discussions
- preserve component patternsWhen refactoring React components, maintain essential component patterns including type annotations, ref forwarding capabilities, and thoughtful component composition. Avoid losing important functionality during simplification.facebook/react-native4 discussions
- organize tests clearlyStructure tests with clear organization, focused scope, and minimal duplication to improve maintainability and debugging. Each test should have a single, well-defined purpose that correlates directly to its name. Group related tests using describe blocks and extract common setup code to reduce duplication.facebook/react-native4 discussions
- optimize algorithmic efficiencyWhen implementing algorithms, especially in performance-critical paths like scroll handlers or layout methods, prioritize computational efficiency and avoid expensive operations. Consider algorithmic complexity and choose more efficient approaches when dealing with large datasets or frequently called methods.facebook/react-native4 discussions
- minimize public API surfaceCarefully evaluate whether functionality needs to be exposed as public API. Keep implementations private when they're only used internally, and avoid creating public APIs that increase maintenance burden without clear benefit.facebook/react-native4 discussions
- Eliminate unnecessary computationsIdentify and remove redundant operations, unnecessary copies, and repeated computations that add algorithmic overhead without providing value. This includes avoiding redundant hash operations, using const references instead of copies, implementing memoization for expensive lookups, and making conscious space-time tradeoffs.facebook/react-native4 discussions
- descriptive specific namingUse descriptive and specific names that clearly communicate purpose and context. Method names should indicate their platform target when applicable, test names should describe the expected behavior, and function names should follow consistent conventions.facebook/react-native4 discussions
- dependency management strategyWhen configuring dependencies in package.json, follow these strategic principles to ensure stable and maintainable package management: **Peer Dependencies**: Use peer dependencies judiciously to enable proper package hoisting while avoiding forced installations for all consumers. As noted: "We still need it here for it to be hoisted correctly. But we can...facebook/react-native4 discussions
- Avoid synchronous main dispatchAvoid using `RCTUnsafeExecuteOnMainQueueSync` and similar synchronous main queue dispatch methods as they can cause deadlocks, especially in initialization code, dispatch_once blocks, or when called from background threads that may already hold main queue dependencies.facebook/react-native4 discussions
- Balance constraints with flexibilityWhen designing APIs, carefully evaluate constraints imposed on consumers. Each limitation should serve a clear purpose; otherwise, favor flexibility. Instead of rigid enforcement, consider more adaptable interfaces with documentation about recommended usage patterns.facebook/react4 discussions
- Understand query method behaviorWhen working with database queries in Active Record, it's essential to understand the precise behavior of query methods to avoid unexpected results and performance issues.rails/rails4 discussions
- Optimize cache headersUse appropriate HTTP cache headers based on content mutability. For immutable assets (like digest-stamped files), apply aggressive caching with far-future expiry and the immutable flag. For mutable files, use short cache times to balance between preventing thundering herds and allowing timely updates.rails/rails4 discussions
- Human-readable configuration valuesWhen writing configuration files, prioritize human readability and maintainability by using descriptive expressions instead of magic numbers or cryptic values. This makes code more understandable and easier to maintain.rails/rails4 discussions
- Efficient data processingWhen implementing algorithms that process large data streams or collections, use a chunking approach rather than processing the entire input at once. This improves memory efficiency and prevents out-of-memory errors for large inputs.rails/rails4 discussions
- Contextual error messagesError messages should provide sufficient context to understand and debug the problem efficiently. Include both the expected and actual values in error messages, along with specific information about what failed. This makes troubleshooting much more straightforward and reduces debugging time.rails/rails4 discussions
- Content security policy configurationImplement Content Security Policy (CSP) configurations appropriately for your application's context. Use report-only mode during implementation to avoid breaking functionality while testing policies.rails/rails4 discussions
- UseEffect Dependency CorrectnessSide effects must be written with the correct React lifecycle mental model: `useEffect` runs after render/commit, not at the place the code is written. Always include a dependency array and make the effect’s inputs explicit so state resets (e.g., initializing defaults when a dialog opens) happen at the right time and without stale reads.infiniflow/ragflow4 discussions
- Token and Prompt FidelityWhen implementing LLM/AI APIs (including streaming), treat three things as contract-critical: (1) compute token usage with a real tokenizer, (2) ensure the intended system/user context is actually passed through every planning/tool stage, and (3) emit only the events your client expects.infiniflow/ragflow4 discussions
- Strict External API ValidationWhen integrating with external AI/HTTP APIs, treat both transport errors and payload validity as first-class failures. Validate inputs, verify provider/HTTP status, and enforce response invariants—never silently accept partial or malformed data.infiniflow/ragflow4 discussions
- HTTP Timeout StrategyStandardize how you apply timeouts for outbound HTTP requests. - If the shared `http.Client` already sets `Timeout`, do **not** also wrap each request with `context.WithTimeout` (it’s redundant and can make behavior harder to reason about).infiniflow/ragflow4 discussions
- Publish-safe dependency rangesWhen CI/CD builds and release automation publish or test packages from a monorepo, inter-workspace dependency specs and lockfile contents must stay publish-safe and CI-consistent.QwenLM/qwen-code4 discussions
- Guard Async ReentryAny UI/logic that performs async work must be resilient to rapid user actions and intermediate async states: prevent re-entry, ensure callbacks use the latest intended state, and avoid losing results/errors when components unmount.QwenLM/qwen-code4 discussions
- Fail-Closed Security HygieneSecurity gates and cleanup must be *fail-closed* and *boundary-proven*. Apply these rules when implementing/adjusting secure workflows: 1) **Authorization must not degrade**QwenLM/qwen-code4 discussions
- Explicit null fallbacksWhen handling `null`/`undefined`, be explicit about intent: - **Choose the correct fallback source**: if a variable is `undefined`, ensure `??` falls back to the intended “truth” (not a stale previous value). QwenLM/qwen-code4 discussions
- Enforce Policy ParityWhen changing CI routing/guardrails (workflows, CODEOWNERS, rulesets), ensure the *policy intent* is still enforced in the same way. **Standard** 1) **Never replace enforced approvals with “request reviewers”**: reviewer requests do not block merges. If your repo relies on `require_code_owner_review: true`, keep CODEOWNERS entries (or explicitly update the...QwenLM/qwen-code4 discussions
- Documentation consistencyDocumentation and doc-driven instructions must stay truthful and self-consistent with the underlying code and the document’s structure. **Apply this checklist when writing or editing docs/specs/templates:**QwenLM/qwen-code4 discussions
- Configuration drift preventionPrevent inconsistencies between configuration sources of truth (build config, extension manifests, and package metadata) that cause IDE/runtime surprises.QwenLM/qwen-code4 discussions
- Concurrency synchronization rulesDesign GitHub Actions concurrency so overlapping runs can’t corrupt multi-step outcomes. Rules: 1) Don’t assume `concurrency` is a durable multi-stage queue. If stage A and stage B must be serialized as one logical transaction, either:QwenLM/qwen-code4 discussions
- API Call CorrectnessWhen automating GitHub (or similar) APIs from CI/workflows, treat API access like production client code: make it correct, complete, and safely reconcilable.QwenLM/qwen-code4 discussions
- Type-safe option consistencyTyped “options” objects (e.g. `queryOptions`, `infiniteQueryOptions`, `mutationOptions`) should round-trip cleanly across *all* API entrypoints that accept them (hooks, suspense/non-suspense hooks, and `QueryClient` methods).tanstack/query4 discussions
- Prefer inferred, clear asyncWhen writing code and tests, optimize for clarity and idiomatic TypeScript: 1) Prefer `async/await` when the async function includes a side effect. ```tstanstack/query4 discussions
- Prefer explicit RTL assertionsIn React Testing Library tests, keep assertions outside components, and rely on proper global teardown. - Teardown/cleanup: Since RTL v9, `cleanup()` is automatic when RTL is configured normally. Only call `cleanup()` manually if your test setup does not provide an `afterEach`.tanstack/query4 discussions
- Persist Only Settled QueriesWhen using async/concurrent flows (streaming, dehydration/rehydration, optimistic updates), ensure you never persist “in-flight” async state and you always return promises from async callbacks.tanstack/query4 discussions
- Deterministic Error PropagationWhen handling async work, cancellation, retries, or hydration/prefetch, ensure errors are propagated consistently and control flow can’t leave callers stuck.tanstack/query4 discussions
- Deterministic Concurrent StateWhen code runs with concurrent rendering and async workflows, ensure any async/derived value that can affect what gets rendered (or how consumers behave) is deterministic per concurrent “world”, and make promise behavior explicit.tanstack/query4 discussions
- Avoid subscription race windowsWhen code derives state from an external cache/store (or wraps promises), treat subscription setup and promise resolution as concurrent events. Ensure your implementation is race-safe and doesn’t use stale inputs.tanstack/query4 discussions
- Active Cache & Config SafetyWhen implementing caching layers/providers and cache-driven handlers: - **Assume multiple cache instances may exist.** Avoid single “default cache” globals for runtime behaviors (e.g., focus handlers). Track **all active caches** and update/notify each.tanstack/query4 discussions
- Validate database connections explicitlyAlways implement explicit database connection validation strategies to ensure robust application behavior during startup and runtime. This includes: 1. Configure validation queries with appropriate timeouts:quarkusio/quarkus4 discussions
- Secure authentication defaultsConfigure authentication mechanisms with secure default settings to prevent security vulnerabilities. When implementing WebAuthn or similar authentication protocols:quarkusio/quarkus4 discussions
- Documentation style consistencyMaintain consistent documentation style to improve readability and user experience: 1. **Use precise terminology**: When referencing features or components, use their full and correct names.quarkusio/quarkus4 discussions
- Avoid wildcard importsWildcard (star) imports like `import java.util.*;` are prohibited in the codebase as they reduce code readability and can cause naming conflicts. Always import specific classes individually.quarkusio/quarkus4 discussions
- Avoid unnecessary allocationsMinimize object creation and memory allocations, especially in frequently called methods and hot code paths, to reduce garbage collection pressure and improve performance.quarkusio/quarkus4 discussions
- Automate style enforcementImplement automated code style enforcement using complementary tools rather than relying on manual reviews. Configure multiple tools to work together, as each has unique strengths and blind spots.quarkusio/quarkus4 discussions
- Optimize memory usageLimit memory consumption in performance-critical paths by conditionally creating large data structures or deferring allocation until needed. Large tracking structures, debug information, and memory-intensive operations should be guarded by configuration flags to prevent them from impacting performance in production environments.pytorch/pytorch4 discussions
- Normalize configuration parametersAlways normalize configuration inputs (especially environment variables) by removing whitespace and applying consistent case transformation before processing them. This prevents unexpected behaviors caused by insignificant variations in input format.pytorch/pytorch4 discussions
- Eliminate redundant operationsAvoid unnecessary operations that can impact performance. This includes: 1. Redundant data transformations: - Load data directly from sources instead of creating temporary copiespytorch/pytorch4 discussions
- Design for compatibilityWhen evolving APIs, prioritize backward compatibility to minimize disruption for existing users. Add new functionality using default arguments rather than creating overloaded methods that could cause ABI compatibility issues. For example:pytorch/pytorch4 discussions
- Choose appropriate exceptionsSelect the proper exception type based on the error scenario to provide clearer error handling and better debugging experience: 1. Use ValueError (TORCH_CHECK_VALUE) when input parameters have invalid valuespytorch/pytorch4 discussions
- Validate Security InputsSecurity-sensitive code should *fail fast* with explicit validation of inputs and security parameters. That means: (1) validate structure/format (e.g., exact length, allowed characters), (2) validate ranges per component (e.g., IPv4 octets must be 0–255), (3) validate logical invariants the algorithm assumes (e.g., arrival time ≤ deadline), and (4) in...TheAlgorithms/Python4 discussions
- Write targeted, specific testsTests should validate specific, well-defined behaviors with clear assertions that directly relate to what's being tested. Avoid writing overly general or unfocused tests that try to cover too much at once, as these are often harder to maintain and debug when they fail.pydantic/pydantic4 discussions
- Simple defaults, flexible overridesDesign APIs with intuitive defaults for common use cases while providing specialized options for edge cases. This approach makes your API approachable for most users while maintaining flexibility for advanced scenarios.pydantic/pydantic4 discussions
- Semantic over syntacticChoose names that clearly communicate the purpose and behavior of your code elements, focusing on semantic meaning rather than just syntax. Names should instantly convey what something is or does without requiring readers to investigate implementation details.pydantic/pydantic4 discussions
- Safe attribute access patternAlways use safe attribute access patterns to handle potentially null or undefined attributes. Instead of direct attribute access that might raise AttributeError, use `getattr()` with a default value. This pattern prevents null reference errors and makes code more robust.pydantic/pydantic4 discussions
- Document configuration relationshipsWhen designing configuration options that interact with each other, clearly document these relationships and consider implementing safeguards against invalid combinations. This is especially important for boolean flags controlling related behaviors.pydantic/pydantic4 discussions
- Consistent configuration patternsWhen working with configurations in Pydantic models, maintain consistency by using `ConfigDict()` instead of plain dictionaries for better type checking support and IDE assistance. This provides explicit typing and makes your configuration intentions clearer.pydantic/pydantic4 discussions
- Balance documentation thoroughnessDocumentation should balance completeness with avoiding redundancy. When documenting complex features: 1. Centralize detailed explanations in a single locationpydantic/pydantic4 discussions
- Service layer abstractionSeparate business logic and external service interactions from API views by using dedicated service layers. This improves testability, maintainability, and enforces separation of concerns in your API design. prowler-cloud/prowler4 discussions
- Parameterize security commandsWhen writing security-related CLI commands or remediation steps, always use standardized parameter placeholders (e.g., `<REGION>`, `<RESOURCE_NAME>`) instead of hardcoded values. This practice ensures commands are adaptable across different environments, prevents implementation errors, and makes security remediation steps more reliable. Properly...prowler-cloud/prowler4 discussions
- Memory usage optimizationOptimize memory usage in high-performance applications by implementing explicit memory management techniques. This includes: 1. **Configure cache limits** to prevent excessive memory consumption:prowler-cloud/prowler4 discussions
- Maintain component consistencyUse a consistent approach when working with components to improve code maintainability and ensure visual coherence throughout the application: 1. **Reuse existing components** rather than creating new ones for similar functionality.prowler-cloud/prowler4 discussions
- Ensure migration compatibilityWhen modifying database schemas through migrations, ensure compatibility with existing data. For new required fields, use `null=True` or provide appropriate default values to prevent failures on existing records. Always keep migration files synchronized with model changes, and test migrations against a representative dataset before deploying to production.prowler-cloud/prowler4 discussions
- Document configuration variablesAlways provide complete documentation for configuration variables, including their exact format, purpose, and behavior. For environment variables and connection strings, specify the full expected format with examples and explain why specific formats are required.prowler-cloud/prowler4 discussions
- Document authentication requirementsWhen creating or modifying APIs, always provide comprehensive documentation for authentication methods and prerequisites. For each authentication approach:prowler-cloud/prowler4 discussions
- Quote templated config valuesWhen Helm chart values (or other YAML-driven config) are interpolated into templates as string fields—such as `ingressClassName`, `storageClassName`, or similar identifiers—always wrap them in explicit quotes in the template. YAML parsers coerce unquoted bare words that look numeric (e.g. a class named `123`) into numbers, which breaks the manifest at apply...promptfoo/promptfoo4 discussions
- special value handlingAlgorithms must explicitly define and consistently handle special values like NaN, infinity, and edge cases across all mathematical operations. Special values can significantly impact computational results and should not be treated as afterthoughts.prometheus/prometheus4 discussions
- prevent concurrent data racesAlways analyze shared data access patterns to prevent race conditions in concurrent code. Use appropriate synchronization mechanisms based on access patterns and data ownership.prometheus/prometheus4 discussions
- maintain API consistencyWhen designing or modifying APIs, ensure they follow established patterns and conventions within the codebase rather than introducing inconsistent approaches. This includes maintaining symmetrical interfaces, preserving backward compatibility when possible, and using consistent parameter types across similar functions.prometheus/prometheus4 discussions
- ensure mathematical correctnessWhen implementing or testing algorithms, ensure mathematical relationships and constraints are maintained throughout the computation. Test data should have plausible values that reflect real-world mathematical relationships, and algorithmic edge cases should be carefully handled to prevent mathematical inconsistencies.prometheus/prometheus4 discussions
- Configure dependency management comprehensivelyWhen configuring dependency management tools like Renovate, ensure comprehensive setup that includes modern syntax, strategic dependency grouping, and controlled update policies. Use current configuration formats (e.g., cron syntax instead of deprecated natural language), implement proper dependency grouping strategies, and configure update separation for...prometheus/prometheus4 discussions
- Complete observability documentationEnsure documentation for observability systems provides comprehensive information including all required permissions, complete configuration options, and clear warnings about operational impacts. Monitoring and metrics systems often have significant performance and security implications that users must understand to operate them safely.prometheus/prometheus4 discussions
- Check nil at usagePerform null and validity checks at the point where values are actually used, rather than defensively initializing or checking everywhere. This approach reduces unnecessary overhead while ensuring safety where it matters most.prometheus/prometheus4 discussions
- proper async error testingWhen testing for expected errors in async code, use Jest's built-in async error testing patterns instead of try-catch blocks with expectations inside catch handlers. Expectations in catch blocks can be silently skipped if the code stops failing, leading to false positives.prisma/prisma4 discussions
- Ensure concurrent resource cleanupAlways ensure proper cleanup of concurrent resources like semaphores, transactions, and async operations, even when exceptions occur. Use finally blocks to guarantee resource release and Promise.allSettled instead of Promise.all when handling multiple concurrent operations that might fail.prisma/prisma4 discussions
- validate configuration changesConfiguration files require careful validation to ensure they work as intended and don't introduce unintended side effects. This includes verifying ignore patterns don't create parent-child conflicts, understanding rule severity implications, and confirming dependency changes are expected.prettier/prettier4 discussions
- Measure performance impactsAlways benchmark and measure actual performance impacts before making optimization decisions, rather than relying on assumptions. Performance characteristics can vary significantly across different runtimes, data sizes, and usage patterns.prettier/prettier4 discussions
- maintain API backward compatibilityWhen evolving public APIs, prioritize backward compatibility and avoid breaking changes to existing interfaces. Support both legacy and new syntax when standards evolve, and clearly document any deprecations.prettier/prettier4 discussions
- Cache correctness validationEnsure caching implementations store the correct data and use appropriate strategies for the context. Cache should store the final processed output, not intermediate or input data, and should include strategy options for different security/performance requirements.prettier/prettier4 discussions
- API documentation clarityEnsure API documentation provides clear, accurate, and comprehensive information for developers. This includes precise function signatures, detailed parameter descriptions, correct terminology, and helpful external references.prettier/prettier4 discussions
- Deterministic Safe ClippingWhen collecting, deduplicating, and truncating algorithm outputs (e.g., “top N” items, merged references, ranked suggestions), enforce determinism and configuration-consistent clipping.the-pr-agent/pr-agent4 discussions
- Bound LLM BudgetsWhen configuring generative AI for code-review workflows, keep prompts and model behaviors tightly bounded to control latency/cost while preserving quality.the-pr-agent/pr-agent4 discussions
- Split complex migrations incrementallyBreak complex schema changes into multiple, sequential migrations to ensure deployment safety and proper data handling. Each migration should represent a single, atomic change that can succeed or fail independently.PostHog/posthog4 discussions
- RESTful endpoint organizationAPI endpoints should be properly organized around resources and follow RESTful principles. Avoid placing aggregation or utility endpoints in viewsets where they don't belong conceptually.PostHog/posthog4 discussions
- optimize ORM queriesOptimize Django ORM queries to prevent performance issues and unnecessary database load. Avoid N+1 query problems by using appropriate prefetch_related() and select_related() calls. Remove unnecessary select_related() when you're only filtering by foreign key IDs and not accessing the related object. Choose the correct database routing (read vs write...PostHog/posthog4 discussions
- Configuration constants managementExtract configuration values into well-named constants instead of using magic numbers or inline values. Use consistent naming patterns across environments and organize configuration values in a maintainable way.PostHog/posthog4 discussions
- Check existence before operationsAlways verify that keys, IDs, indices, or other required values exist before performing operations that depend on them. This prevents runtime errors and unexpected behavior from null references or missing data.PostHog/posthog4 discussions
- Capture broad exceptionsWhen using broad exception handlers like `except Exception:`, always capture and log the exception to avoid silent failures that are difficult to debug in production. Broad exception handling without proper error capture masks underlying issues and makes troubleshooting nearly impossible.PostHog/posthog4 discussions
- API response standardizationEnsure API responses follow established patterns and use proper typing. Always use standardized response types like `PaginatedResponse` for paginated endpoints, avoid hardcoded union types for dynamic values that should be strings, and return fresh data from API responses rather than stale local data.PostHog/posthog4 discussions
- AI context efficiencyWhen providing context to LLMs, choose the most efficient method based on the nature and size of the context data. For bounded, static context (like feature flag mappings or configuration options), inject the information directly into the system prompt rather than using tool calls. This approach is faster, more cost-effective, and reduces complexity.PostHog/posthog4 discussions
- Prevent deadlock conditionsCarefully manage resource acquisition and release to prevent deadlocks in concurrent code. Deadlocks typically occur when multiple threads hold resources while waiting for resources held by each other. To avoid deadlocks:pola-rs/polars4 discussions
- Prevent cryptic errorsAlways implement proper validation and type checking to prevent cryptic error messages. When errors do occur, provide clear, actionable guidance for resolution.pola-rs/polars4 discussions
- Organize tests efficientlyWrite maintainable, well-structured tests that are easy to understand and extend. Tests should remain simple and focused on their specific validation purpose.pola-rs/polars4 discussions
- Optimize data transformationsWhen implementing data processing operations, avoid unnecessary data transformations, copies, and conversions that can impact query performance. Consider these practices:pola-rs/polars4 discussions
- Design for operation flexibilityWhen implementing algorithms that operate on data structures (particularly arrays, lists, or collections), design them to handle both constant and expression-based inputs efficiently. Consider the constraints each imposes on the algorithm:pola-rs/polars4 discussions
- Defer expensive operationsAvoid triggering expensive computations prematurely in your code. Operations like `collect()`, intensive IO operations, or algorithms with quadratic complexity should be deferred until absolutely necessary to prevent wasted computational resources.pola-rs/polars4 discussions
- Choose appropriate abstractionsWhen designing APIs, select data types and patterns that match how they will be consumed while facilitating long-term maintainability: 1. Use data types that naturally fit the intended usage pattern. For cloud paths, prefer `String`/`Box<str>` over `OsStr` when APIs you interact with expect string types:pola-rs/polars4 discussions
- Use appropriate logging levelsUse debug-level logging for technical details and error information that aids developer troubleshooting, while keeping user-facing messages clean and informative. Avoid exposing verbose technical details directly to users, but ensure they are available for debugging.python-poetry/poetry4 discussions
- Document configuration clearlyConfiguration files, hooks, and settings should include clear, accurate descriptions that explain their purpose and behavior. Descriptions should match the actual functionality and help developers understand what the configuration does and why it exists.python-poetry/poetry4 discussions
- Complete config setting integrationWhen adding new configuration settings, ensure they are properly integrated across all required system components. Configuration settings must be registered in multiple locations to function correctly and be discoverable by users.python-poetry/poetry4 discussions
- Cache expensive computationsIdentify expensive operations that may be called multiple times and implement appropriate caching mechanisms to avoid redundant computation. Use `@cached_property` for class properties that involve expensive calculations, store expensive method calls in local variables when used repeatedly in loops, and consider memoization for frequently accessed data that...python-poetry/poetry4 discussions
- API backwards compatibilityWhen evolving public APIs, prioritize backwards compatibility through proper deprecation strategies and careful interface design. Avoid breaking changes by using overloads, deprecation warnings, and gradual migration paths.python-poetry/poetry4 discussions
- validate algorithmic edge casesAlgorithms must be thoroughly tested at boundary conditions and edge cases to prevent subtle bugs. Pay special attention to off-by-1 errors in mathematical calculations, empty collections, and boundary values that might cause unexpected behavior.microsoft/playwright4 discussions
- testing best practicesChoose testing methods, configurations, and approaches that prioritize user experience and reliability over theoretical completeness. Consider the practical needs of your development team and testing environment when making decisions.microsoft/playwright4 discussions
- Prioritize documentation clarityDocumentation should prioritize clarity and actionable guidance over comprehensive coverage. Organize content logically by placing the most relevant information first, provide clear recommendations on preferred approaches, and avoid unnecessary complexity or redundant details that don't add value.microsoft/playwright4 discussions
- explicit undefined checksAlways use explicit checks for undefined values and return appropriate nullable types instead of relying on implicit conversions or unsafe type assertions. Use modern JavaScript equality checks and proper TypeScript utility types for null safety.microsoft/playwright4 discussions
- Avoid redundant operationsIdentify and eliminate duplicate computations, unnecessary object creation, and redundant function calls to improve performance. This is especially critical in memory-sensitive areas and frequently executed code paths.microsoft/playwright4 discussions
- Spec-Driven ParsingFor any code that parses/normalizes strings or aggregates structured events, require deterministic, complete, and bounded logic: - **Complete inputs:** When computing stats/metrics, include every event type that can contribute (including newly added variants like tool/compaction usage, memory, etc.).earendil-works/pi4 discussions
- Explicit, Extensible APIsWhen designing/adjusting API surfaces, ensure (1) consumers can clearly understand what they’re setting and what defaults apply, (2) implementation-only details don’t leak into public types, and (3) variant-specific behavior is routed through dedicated abstractions/resolvers rather than embedded special-cases.earendil-works/pi4 discussions
- Simplify algorithmic implementationsFavor clear, simple algorithmic implementations over complex custom logic. When faced with algorithmic choices, prefer built-in functions, direct approaches, and well-structured decomposition into stages.emcie-co/parlant4 discussions
- Safe null access patternsAlways use safe access patterns to prevent runtime errors when dealing with potentially null or undefined values. Instead of direct access that can raise KeyError or IndexError, use defensive programming techniques.emcie-co/parlant4 discussions
- safe environment variable accessAlways use `os.environ.get()` with appropriate defaults instead of direct dictionary access to prevent KeyError exceptions when environment variables are not set. Additionally, extract configuration constants and magic numbers to named module-level variables for better maintainability and consistency.emcie-co/parlant4 discussions
- Proper span lifecycleAlways ensure trace spans are properly closed in all code execution paths to prevent trace leaks that can distort observability data. This is particularly critical when creating spans within loops, conditional blocks, or functions with multiple exit points.opentofu/opentofu4 discussions
- Prevent backing array surprisesWhen modifying slices in Go, be aware that appending to a slice with available capacity will modify the backing array, potentially affecting other slices that share the same backing storage. This can lead to subtle bugs where one operation unexpectedly affects seemingly unrelated variables.opentofu/opentofu4 discussions
- Minimize API surfaceDesign APIs with minimal exposed surface by encapsulating implementation details within packages. When designing APIs, expose only what's necessary for consumers while keeping internal details hidden.opentofu/opentofu4 discussions
- Write reliable test casesCreate deterministic and reliable test cases by following these guidelines: 1. Use hardcoded values instead of random data to ensure reproducibility:open-telemetry/opentelemetry-python4 discussions
- Return collections not NoneReturn empty collections (lists, dicts, sets) instead of None when representing empty states. This reduces null checking boilerplate, prevents null reference errors, and makes code more predictable. When a function returns a collection type, an empty collection communicates "no items" more clearly than None and allows direct operations without defensive...open-telemetry/opentelemetry-python4 discussions
- Prevent recursive logging callsAvoid implementing logging calls that could trigger recursive logging patterns, which can lead to infinite loops and program crashes. This is particularly important in logging handlers, exporters, and instrumentation code.open-telemetry/opentelemetry-python4 discussions
- Precise configuration specificationsEnsure configuration files use tool-specific syntax and conventions while leveraging appropriate defaults. Be intentional about version constraints and conditionals in dependency specifications.open-telemetry/opentelemetry-python4 discussions
- Place attributes correctlyWhen implementing observability with OpenTelemetry, place attributes at the appropriate level in the telemetry hierarchy to ensure effective data collection and analysis:open-telemetry/opentelemetry-python4 discussions
- Pin dependency versionsAlways use exact version pinning (==) for dependencies in requirements files rather than version ranges. This ensures build reproducibility and prevents unexpected behavior when dependencies release new versions.open-telemetry/opentelemetry-python4 discussions
- Choose data structures wiselySelect data structures based on your specific access patterns and performance requirements. Using the right data structure can simplify your code and improve performance significantly.open-telemetry/opentelemetry-python4 discussions
- Use descriptive namesChoose names that clearly communicate purpose and meaning rather than using abbreviations or unclear terms. Names should be self-documenting and make the code's intent obvious without requiring additional context.commaai/openpilot4 discussions
- Tool-specific configuration compatibilityWhen working with configuration files that support multiple tools or package managers, ensure that configuration syntax and constraints accommodate all supported tools while maintaining functionality across the ecosystem.commaai/openpilot4 discussions
- Prefer asynchronous operationsUse asynchronous patterns to prevent blocking operations from degrading system performance, especially in UI contexts and real-time systems. Prefer higher-level async abstractions like std::future over manual thread management when possible, as they provide automatic thread management, better exception handling, and simpler code maintenance.commaai/openpilot4 discussions
- optimize data structure selectionChoose data structures and algorithms based on their computational complexity and access patterns rather than convenience. Consider performance implications when selecting between alternatives.commaai/openpilot4 discussions
- Initialize and validate valuesAlways initialize variables with sensible default values and validate inputs to prevent null reference errors and undefined behavior. This includes three key practices:commaai/openpilot4 discussions
- Be specific with exceptionsAvoid catching broad exception types like `Exception` and instead catch specific exceptions that you expect and can handle appropriately. When errors occur, they should be explicit rather than failing silently, and should include proper logging or re-raising when necessary.commaai/openpilot4 discussions
- prefer built-in error utilitiesUse existing error handling utilities and appropriate error mechanisms instead of implementing manual error handling logic. This reduces code complexity, improves maintainability, and leverages well-tested library functions.opengrep/opengrep4 discussions
- Optimize for common casesWhen implementing algorithms, create specialized versions for common cases to improve performance, while maintaining a generic version for completeness. For functions that process data with different channel counts, implement separate optimized code paths for 1-channel and 3-channel data, which represent the majority of image processing workloads.opencv/opencv4 discussions
- Framework synchronization practicesWhen implementing concurrent code, always use the framework's provided synchronization primitives rather than direct language features. This ensures compatibility across all build configurations and platforms:opencv/opencv4 discussions
- Document properly with referencesAlways separate code from documentation and use proper referencing techniques. Documentation should be in markdown files when extensive, while code should be in files that are regularly checked for compilation. opencv/opencv4 discussions
- Preserve Null SemanticsWhen inputs or response fields are optional/nullable, preserve their semantics explicitly and avoid unsafe coercion or indexing. Apply these rules: 1) Don’t coerce `None` with `bool(...)` when `None` has distinct meaning. If you mean “unset,” omit the field/parameter rather than converting it.openai/openai-python4 discussions
- Config resolution consistencyWhen adding or extending client/provider integrations, enforce a single, predictable configuration-resolution contract: - **Args → env fallbacks:** For each required setting (e.g., `api_version`, `region`), accept an explicit argument, otherwise fall back to the corresponding environment variable(s). Only raise a clear error when *neither* is provided.openai/openai-python4 discussions
- Config-Accurate Dependency ManagementWhen updating project configuration (e.g., `pyproject.toml`), ensure dependency declarations match how packages are actually used: align `requires-python` with dependency-supported Python versions, keep dev-only tooling in `dev-dependencies`, and use `extras` for optional features instead of adding new required runtime deps. Also, set minimum versions based...openai/openai-python4 discussions
- Real Regression TestsWhen you fix behavior (especially edge/boundary cases), add regression tests that are: - **Reachable** (not unexported/inaccessible without refactors that make them testable).diegosouzapw/OmniRoute4 discussions
- Contract-First API ValidationTreat every API endpoint as a contract: - Validate all request inputs (query params, body fields) with shared schemas (e.g., Zod) instead of manual parsing.diegosouzapw/OmniRoute4 discussions
- Reuse buffers strategicallyFor frequently called methods or hot code paths, reuse allocations instead of creating new buffers on each call. This significantly reduces GC pressure and improves performance in memory-intensive operations.ollama/ollama4 discussions
- Platform-aware configuration documentationAlways document platform-specific configuration differences and requirements thoroughly. When writing documentation or implementing configuration-related code, explicitly address variations across different operating systems and environments.ollama/ollama4 discussions
- Loose API couplingMaintain a clear separation between API definitions and their implementations by avoiding direct passing of API structures to implementation layers. Extract only the necessary values from API structures when passing data downstream.ollama/ollama4 discussions
- Safe rollback orderingWhen a function performs a multi-step mutation of shared, possibly concurrently-accessed state (e.g., registering or rolling back a worktree on disk), handle failures so the system is never left in an ambiguous or unsafe state, and never mistake "error" for "expected absence."can1357/oh-my-pi4 discussions
- Bound unbounded external outputWhen capturing or buffering output from external or long-running processes (child processes, hooks, wrappers, probes) whose output size is not controlled by your code, never let memory or disk usage grow unbounded. Enforce a fixed cap and keep only the relevant tail (or head) of the data, applying the most efficient mechanism available on each platform...can1357/oh-my-pi4 discussions
- Use async/await patternWhen designing or documenting API clients, always use the async/await pattern rather than blocking calls. Replace code that uses `.GetAwaiter().GetResult()` with proper async/await syntax to prevent potential deadlocks and improve application responsiveness.octokit/octokit.net4 discussions
- Catch specific exceptionsAlways catch specific exception types rather than using general catch blocks. This improves error handling precision, enables targeted recovery strategies, and maintains consistency across your codebase.octokit/octokit.net4 discussions
- robust algorithm implementationImplement algorithms that handle edge cases and avoid brittle assumptions about input data or structure formats. Instead of relying on simple string manipulation or assuming data structure behavior, use comprehensive approaches that account for various scenarios.nrwl/nx4 discussions
- Ensure configuration consistencyConfiguration files should maintain consistency in patterns, use correct paths and values, and follow established conventions across the codebase. This includes proper output paths, consistent dependency versioning patterns, and appropriate dependency categorization.nrwl/nx4 discussions
- Documentation metadata consistencyEnsure documentation uses consistent structural elements and proper metadata to optimize user experience and content discoverability. Use platform-native components (like `aside` instead of `callout` for Astro docs), include appropriate sidebar labels, and leverage weight/filter properties to control search result prominence.nrwl/nx4 discussions
- Configuration documentation clarityConfiguration changes and examples should be documented with clear formatting, proper context, and helpful references to aid developer understanding. nrwl/nx4 discussions
- Vue context boundariesEnsure Vue composables, reactive state, and side effects are properly scoped within Vue's execution context to prevent SSR failures, memory leaks, and shared state across requests.nuxt/nuxt4 discussions
- Strategic component loadingChoose component loading strategies based on when interactivity is actually needed, not just code splitting. Lazy prefixed components only control chunk size but still load eagerly with the page's scripts. Use delayed hydration for components that don't need immediate interactivity, avoiding unnecessary JavaScript execution during initial page load. Be...nuxt/nuxt4 discussions
- optimize array operationsPre-allocate arrays when the final size is known and consolidate multiple iterations into single loops to reduce memory allocations and improve performance.nuxt/nuxt4 discussions
- Handle async cancellation properlyWhen implementing async operations with cancellation support, ensure that cancelled operations do not continue to update application state and that all cleanup logic is properly consolidated. This prevents race conditions where cancelled requests might still modify data after cancellation.nuxt/nuxt4 discussions
- Cache lifecycle managementImplement comprehensive cache lifecycle management that includes proper key management, invalidation strategies, and cleanup mechanisms. Cache implementations should handle the full lifecycle from creation to cleanup to prevent memory leaks, stale data, and unbounded growth.nuxt/nuxt4 discussions
- Optimize collection operationsWhen processing collections of data, choose efficient algorithms and data structures that minimize computational complexity. Use appropriate array methods (filter, find, map, reduce) and consider batching operations when possible.novuhq/novu4 discussions
- Environment-aware feature gatingAlways check environment variables, deployment modes, subscription tiers, and feature flags before enabling functionality or changing application behavior. Combine multiple configuration checks when necessary to ensure features are only available in appropriate contexts.novuhq/novu4 discussions
- Limit environment variable scopeWhen working with environment variables for configuration: 1. **Reuse existing environment variables** rather than creating new ones. Leverage established variables like `NODE_TEST_CONTEXT` where possible to avoid fragmentation.nodejs/node4 discussions
- Format docs for readabilityDocumentation should follow consistent formatting and structural patterns to maximize readability and maintainability. Key guidelines: 1. Keep line lengths to 80 characters maximumnodejs/node4 discussions
- Follow naming conventionsMaintain consistent naming conventions across the codebase: - Use PascalCase for class methods (e.g., `All()`, `Get()`, `Run()` instead of `all()`, `get()`, `run()`)nodejs/node4 discussions
- Document non-intuitive codeAdd clear comments to explain complex logic, function differences, and non-obvious implementation details. This is especially important for: - Similar functions with subtle differencesnodejs/node4 discussions
- Descriptive function namesFunction and method names should precisely describe their purpose and behavior. Choose names that explicitly communicate what the function does, including any special conditions or behaviors.nodejs/node4 discussions
- Await all promisesAlways explicitly await all asynchronous operations, especially in cleanup code paths and resource management. Failing to properly await promises can lead to race conditions, resource leaks, and unpredictable behavior in concurrent environments.nodejs/node4 discussions
- Verify documentation referencesWhen writing or updating documentation, ensure all code examples, installation commands, and project references accurately reflect the current codebase.vercel/next.js4 discussions
- Proper Use of Suspense in Next.js ComponentsWhen building Next.js applications that leverage server-side rendering (SSR) or Partial Prerendering (PPR), it is essential to wrap components that access dynamic or non-deterministic values in Suspense boundaries with appropriate fallbacks.vercel/next.js4 discussions
- Proper Error Handling in Next.js API RoutesThis review focuses on ensuring proper error handling in Next.js API routes. Key principles include validating incoming request data, using consistent error response structures, and sanitizing error messages.vercel/next.js4 discussions
- Maintain Consistent Naming Conventions in Next.js CodeAs a code reviewer for Next.js projects, ensure that all code artifacts, including component names, file names, and configuration keys, adhere to consistent naming conventions.vercel/next.js4 discussions
- Dynamic API behavior detectionAPIs should determine behavior based on runtime request characteristics rather than static configuration flags. This enables multiple API providers and models to coexist and ensures proper handling of provider-specific requirements.ChatGPTNextWeb/NextChat4 discussions
- Protect network buffer lifecycleWhen handling network buffers in protocol implementations, ensure proper lifecycle management to prevent memory leaks and data corruption. Key practices:netty/netty4 discussions
- Preserve backward compatibilityWhen evolving APIs in minor versions, always maintain backward compatibility to avoid breaking client code. Follow these principles: 1. **Don't add abstract methods** to existing interfaces or abstract classes. Instead, provide default implementations:netty/netty4 discussions
- Optimize search operationsEnhance search algorithm performance by prioritizing common cases, using appropriate data structures, and avoiding unnecessary operations. When implementing binary search:netty/netty4 discussions
- Configurable over hardcodedMake configuration parameters configurable rather than hardcoding values, especially for limits, sizes, and thresholds. Provide reasonable defaults but allow users to override through:netty/netty4 discussions
- Use consistent control structuresAlways use curly braces for control structures (if, for, while, etc.), even for single-line statements. This improves code readability and maintainability by making the code structure explicit and consistent.nestjs/nest4 discussions
- Structure exception handling patternsImplement consistent exception handling using framework-provided mechanisms rather than ad-hoc try-catch blocks or manual error propagation. Use appropriate exception classes and interceptors to handle errors at the right architectural level.nestjs/nest4 discussions
- Standardize logger configuration patternsMaintain consistent logger configuration and usage patterns across the application while leveraging built-in customization options. This promotes maintainable logging practices and ensures uniform log output.nestjs/nest4 discussions
- Prevent async race conditionsDesign async operations to prevent race conditions, memory leaks, and ensure proper resource cleanup. Key principles: 1. Avoid mutating shared state in async operationsnestjs/nest4 discussions
- Pin dependency versionsExplicitly pin or constrain dependency versions in CI/CD configurations instead of using `latest` tags. This prevents unexpected build failures when new incompatible versions are released. Consider using parameterized versions to centralize version management while maintaining stability.nestjs/nest4 discussions
- Package dependency configurationConfigure dependencies appropriately in package.json based on usage patterns and requirements. This improves package maintainability, flexibility, and reduces unnecessary dependencies.nestjs/nest4 discussions
- HTTP header managementWhen working with HTTP responses, follow these principles for proper header management: 1. **Only set default headers when undefined, not when falsy:**nestjs/nest4 discussions
- Document configuration behaviorsAlways document configuration options thoroughly, especially for module and service settings. For each configuration property: 1. Provide clear descriptions of what the option doesnestjs/nest4 discussions
- Configurable log formattingDesign logging systems with customizable formatting and output options. Separate formatting logic into protected methods that can be overridden by derived logger implementations.nestjs/nest4 discussions
- Benchmark before optimizingWhen making performance-critical decisions, always validate your approach with benchmarks using realistic data sizes and use cases rather than relying on theoretical assumptions.nestjs/nest4 discussions
- Use descriptive namesAvoid ambiguous or vague identifiers in favor of specific, self-documenting names that clearly convey purpose and context. Names should be immediately understandable without requiring additional context or documentation. Generic terms like "float" should be replaced with specific terms like "floatwin" or "win_float" to eliminate ambiguity. Function names...neovim/neovim4 discussions
- Semantic naming over implementationChoose names that reflect the semantic purpose and meaning rather than implementation details or internal mechanisms. Names should communicate what something does or represents from the user's perspective, not how it works internally.neovim/neovim4 discussions
- Initialize before dereferencingAlways ensure buffers, containers, and data structures are properly initialized before passing them to functions that will dereference them. This prevents null pointer dereferences and undefined behavior.neovim/neovim4 discussions
- consolidate network APIsWhen implementing network functionality, consolidate around standardized APIs like `vim.net.request()` instead of maintaining custom download functions or direct curl calls. Implement comprehensive testing for network operations using integration test guards to prevent failures in environments without network access.neovim/neovim4 discussions
- Configuration variable organizationUse structured naming patterns and avoid polluting the global namespace when managing configuration variables. Prefer storing configuration state on relevant objects rather than creating numerous top-level global variables.neovim/neovim4 discussions
- Conditional expensive operationsOnly execute expensive operations when they are actually necessary. Avoid paying performance costs for functionality that may not be used or when conditions don't require the expensive computation.neovim/neovim4 discussions
- avoid unnecessary configurationAvoid creating special-purpose configuration options when simpler alternatives exist. Don't force users to call setup functions or provide explicit configuration for basic functionality to work.neovim/neovim4 discussions
- avoid error maskingDon't use mechanisms that suppress or hide errors unless absolutely necessary for the application flow. Error masking makes debugging difficult and can hide important issues from users and developers.neovim/neovim4 discussions
- Scope JWT authentication tokensAlways include tenant, timeline, and endpoint identifiers in JWT tokens used for service authentication. This ensures proper isolation between tenants and prevents unauthorized access across endpoints or timelines, even within the same tenant hierarchy. neondatabase/neon4 discussions
- Proper Option type usageUse Option<T> only for truly optional values that can meaningfully be None. Avoid using Option when a value is always required or when defaulting to empty/invalid values.neondatabase/neon4 discussions
- Proactive cache warmingImplement proactive cache warming strategies to minimize performance degradation after system restarts or during cold starts. Rather than waiting for normal workload patterns to gradually populate caches, actively prefetch and load likely-needed data into memory ahead of time.neondatabase/neon4 discussions
- Pin GitHub action versionsAlways pin GitHub Actions to specific commit hashes instead of using major/minor version tags (like @v4). This ensures reproducible builds and prevents supply chain attacks through compromised action versions.neondatabase/neon4 discussions
- Ensure algorithm robustnessWhen implementing algorithms, ensure they handle all edge cases correctly and robustly. Code should gracefully manage exceptional conditions rather than producing incorrect results or panicking.neondatabase/neon4 discussions
- Connection pooling with pipeliningImplement connection pooling with request pipelining for network services to optimize resource usage and improve throughput. Pool should manage three resource levels:neondatabase/neon4 discussions
- Reliable Technical DocumentationWhen updating technical docs, ensure they are reliable in both what they claim and how developers can apply them: - Keep headings/sections aligned with the exact runtime/build parameters shown in outputs (e.g., if the benchmark runs with gpu_device=0, reflect “GPU0” in the subsection title).Tencent/ncnn4 discussions
- Intentional Test CoverageAll unit tests should be (1) intentionally designed for coverage, (2) non-redundant, and (3) maintainable. Apply these rules: 1) Enforce correctness with invariantsTencent/ncnn4 discussions
- Backwards-Compatible API EvolutionWhen evolving or integrating client-facing interfaces (CLI/API) and platform-dependent APIs, preserve compatibility across existing clients and across SDK/platform versions.Tencent/ncnn4 discussions
- PyTorch Compatibility GuardsAdopt explicit compatibility guards in PyTorch code to prevent silent numeric issues and runtime failures across devices, PyTorch versions, and compilation modes.karpathy/nanochat4 discussions
- Keep config minimalAvoid “config monsters” by limiting new runtime knobs and centralizing stable defaults. Only add CLI/config parameters when they materially change behavior across experiments; otherwise, bake them into the existing config (or the run script) and reuse current config locations rather than introducing new config modules for a few constants. For...karpathy/nanochat4 discussions
- Justify dependency and build pinsAny config change that affects build/runtime behavior (dependency version pins, feature flags, build backend settings, tool/target sources like GPU wheels) must include a concrete compatibility rationale and align with the build tooling or runtime environment.karpathy/nanochat4 discussions
- Secure credential data handlingAlways protect sensitive credential data through proper encryption, secure storage, and careful handling in code. Key requirements: 1. Never store credentials in plaintext within source coden8n-io/n8n4 discussions
- Maintain semantic naming consistencyNames should be semantically meaningful and consistent across related concepts in the codebase. This applies to variables, functions, components, and types. When naming:n8n-io/n8n4 discussions
- Explicit environment configuration handlingEnvironment and configuration values should be explicit, visible, and environment-aware. Avoid hardcoded production values, hidden configuration properties, and complex environment variable logic. Instead:n8n-io/n8n4 discussions
- Descriptive parameter namesUse specific, descriptive parameter names for API resources rather than generic identifiers. Parameter names should clearly indicate the resource type they refer to by using namespaced identifiers (e.g., `userId` instead of `id`). This improves API readability, reduces ambiguity in code, and prevents confusion when multiple resource types are used in the...n8n-io/n8n4 discussions
- Consistent naming patternsMaintain consistent naming conventions throughout the codebase to improve readability and maintainability. This applies to translation keys, command names, variables, and terminology.n8n-io/n8n4 discussions
- Consistent identifier namingFollow consistent naming conventions for all identifiers to improve code quality, accessibility, and test reliability. Ensure correct spelling and adhere to established project patterns.n8n-io/n8n4 discussions
- Configuration consistency managementWhen modifying configuration files, ensure all references to the changed values are updated consistently across the entire project. Configuration changes rarely exist in isolation - they often have ripple effects throughout the codebase.n8n-io/n8n4 discussions
- Actions configuration best practicesWhen working with GitHub Actions workflows, follow these configuration best practices: 1. **Boolean inputs comparison**: GitHub Actions boolean inputs are actually strings. Always use string comparison with quotes:n8n-io/n8n4 discussions
- Graph traversal optimizationWhen working with graph structures, avoid performing redundant depth-first search (DFS) traversals as each traversal incurs an O(V+E) complexity cost. Instead, consider:apache/mxnet4 discussions
- Explicit null checksAlways use explicit null checks (`value is None` or `value is not None`) rather than implicit truthiness evaluations when testing for null/None values. Implicit boolean checks can invoke `__bool__` methods leading to unexpected behavior.apache/mxnet4 discussions
- Comprehensive API documentationEnsure all API elements are thoroughly documented following a consistent format. This includes: 1. **All function parameters** must have descriptive documentation that explains their purpose, expected values, and default behaviors.apache/mxnet4 discussions
- Avoid redundant calculationsEliminate redundant calculations by identifying and caching frequently used values to improve performance. Consider these optimization patterns: 1. Cache function results when used multiple times:apache/mxnet4 discussions
- WebSocket lifecycle managementEnsure proper WebSocket connection lifecycle management by using `once()` instead of `on()` for cleanup operations and separating initialization from construction to avoid race conditions.rocicorp/mono4 discussions
- verify authorization before operationsAlways verify that users have proper authorization to access and modify resources before performing any data operations. This prevents privilege escalation attacks and unauthorized data access.rocicorp/mono4 discussions
- dependency management practicesEnsure comprehensive dependency management in package.json files by following these practices: 1. **Evaluate necessity**: Before adding dependencies, check if native Node.js APIs provide the functionality. For example, use `fs.mkdtemp(path.join(os.tmpdir(), 'prefix'))` instead of adding a temporary file library.rocicorp/mono4 discussions
- YAML-first config schemaWhen adding or changing configurable behavior, define it in the correct config scope and expose it via YAML/frontmatter—don’t introduce new diagram-specific syntax/directives, and don’t place diagram-only options in global config.mermaid-js/mermaid4 discussions
- Invariant-Preserving Graph AlgorithmsWhen a graph/geometry algorithm is used recursively (or downstream computations depend on its shape/metrics), don’t patch symptoms. Preserve invariants end-to-end:mermaid-js/mermaid4 discussions
- Secure Auth and SecretsApply these rules whenever implementing auth, tokens, or security-modes: 1) Never leak tokens/secrets - Don’t print full-privilege tokens to stdout, shell history, CI logs, or transcripts.awslabs/mcp4 discussions
- Null-Safe Input NormalizationAlways treat nullable/optional fields and parsed payloads as untrusted at boundaries: normalize `None`/missing values to the expected type before iterating/indexing, validate the parsed shape immediately (fail fast with a clear error), and explicitly handle sentinel/unknown states instead of “silently succeeding” with wrong assumptions.awslabs/mcp4 discussions
- Correct Pagination OrderingEnsure algorithmic results (ordering, counts, and pagination) remain correct after filtering/slicing and that sorting/dedup logic is both efficient and deterministic.awslabs/mcp4 discussions
- Write user-centric documentation guidesDocumentation should be written with the user's perspective in mind, using clear, action-oriented language and intuitive organization. Follow these principles:mui/material-ui4 discussions
- Use slots for compositionWhen designing React component APIs, implement the slots pattern using `slots` and `slotProps` props instead of specialized prop names. This approach provides a consistent, flexible, and maintainable way to customize component parts while preserving their functionality.mui/material-ui4 discussions
- Test behavior not implementationFocus tests on user behavior and outcomes rather than implementation details. Structure tests to simulate real user interactions and verify expected results. This creates more robust tests that remain valid even when implementation changes.mui/material-ui4 discussions
- Strict mode-proof hooksEnsure your React components work correctly in both development (Strict Mode) and production environments by writing hooks that handle React's intentional double-rendering behavior. When using side effects in initializers, guard them with refs to prevent duplicate executions:mui/material-ui4 discussions
- Standardize code formatting patternsMaintain consistent code formatting patterns across the codebase to improve readability and maintainability. This includes: 1. Use consistent spacing and indentationmui/material-ui4 discussions
- Standardize build configurationsWhen configuring module builds, maintain consistent and explicit configuration for different module formats (CJS, ESM, modern) to ensure compatibility across environments. Package exports should be clearly defined with appropriate conditions for each module system.mui/material-ui4 discussions
- Semantic descriptive namingChoose names that clearly communicate purpose, behavior, and semantics of code elements. Names should be self-explanatory and convey their intended functionality without requiring additional context.mui/material-ui4 discussions
- Explicit configuration specificationsWhen writing configuration files, be explicit and precise about dependencies and versions rather than using broad patterns or tags. For dependency declarations:mui/material-ui4 discussions
- Event-triggered network requestsWhen implementing user interactions that trigger network requests, use precise event handling techniques to ensure reliable network operations. Specifically, check event properties like `event.button` (which button was pressed) rather than `event.buttons` (which buttons are currently pressed) to correctly handle user intent.mui/material-ui4 discussions
- Document compatibility boundariesClearly communicate your API's compatibility guarantees and limitations. When designing APIs, explicitly indicate what usage patterns are supported vs. which are experimental or might change. For functions that have multiple calling patterns, document which are stable and which might be deprecated:mui/material-ui4 discussions
- Distinguish Next.js routersAlways provide separate implementation instructions for Next.js App Router (13+) and Pages Router. These routing systems have different file structures, initialization requirements, and component placement:mui/material-ui4 discussions
- Avoid render cycle allocationsCreating new objects, arrays, or functions inside a component's render cycle causes unnecessary allocations on every render, which can degrade performance, especially in frequently-rendered components.mui/material-ui4 discussions
- Use accessible terminologyChoose clear, understandable names and terminology that are appropriate for your intended audience, avoiding technical jargon or obscure references that may not be widely understood. This is especially important for user-facing strings, error messages, and interface labels.mastodon/mastodon4 discussions
- prefer early returnsUse early returns and guard clauses to reduce nested conditionals and improve code readability. This pattern makes the main logic flow clearer by handling edge cases upfront and avoiding deeply nested if-else structures.mastodon/mastodon4 discussions
- optimize test organizationOrganize tests to minimize factory creation, reduce duplication, and improve performance by chaining assertions and extracting common values. **Key practices:**mastodon/mastodon4 discussions
- migration data dependenciesEnsure that migrations properly handle data dependencies and sequencing to prevent deployment failures. When migrations depend on specific records existing (like default roles or seed data), create those records within the migration itself rather than relying on seeds or post-deployment processes.mastodon/mastodon4 discussions
- Hook responsibility separationKeep hooks and components focused on single, well-defined responsibilities to maintain clean architecture and avoid mixing concerns. When designing hooks, ensure they have a clear, singular purpose. Avoid combining unrelated functionality like DOM manipulation with event handling, or complex business logic with simple state management. If a hook or...mastodon/mastodon4 discussions
- explicit API parametersMake API parameters explicit and named rather than hiding them in **kwargs. This improves clarity, enables better validation, and provides clearer interfaces for callers.microsoft/markitdown4 discussions
- Use proper loggingAlways use the project's standard logging system (mbgl::Log) with appropriate log levels instead of ad-hoc solutions like std::cout, printf, or custom logging macros. This ensures consistent log formatting, proper filtering, and integration with test frameworks.maplibre/maplibre-native4 discussions
- Structured coroutine managementAlways bind coroutine scopes to appropriate lifecycles and follow consistent patterns for asynchronous operations. Prefer suspending functions over class-based approaches when possible, and ensure proper job cancellation to prevent memory leaks.maplibre/maplibre-native4 discussions
- Preallocate collection capacityWhen the final size of a collection is known before adding elements, use `reserve()` to preallocate memory capacity. This optimization eliminates multiple reallocations and copy operations during insertions, improving both performance and memory usage patterns. This is particularly beneficial in performance-critical code paths where collections are...maplibre/maplibre-native4 discussions
- Extract workflow scriptsMove complex scripts out of workflow YAML files into separate, dedicated script files in your repository. This practice significantly improves workflow maintainability, enables local testing of CI logic, and makes code reviews more effective.maplibre/maplibre-native4 discussions
- Enforce clear data ownershipAlways establish and maintain clear ownership semantics in concurrent code to prevent data races. This includes: 1. Use RAII patterns for resource management (especially locks)maplibre/maplibre-native4 discussions
- Document platform requirementsWhen setting or changing minimum platform version requirements, always document the specific technical reasons for these decisions. Include: 1. Features or APIs that necessitate the change (e.g., std::filesystem requiring macOS 10.15+)maplibre/maplibre-native4 discussions
- Descriptive named constantsReplace magic numbers and unclear variables with descriptive named constants using appropriate naming conventions. This improves code readability, maintainability, and prevents errors.maplibre/maplibre-native4 discussions
- Configure platform-specific buildsEnsure build and distribution configurations are properly documented and optimized for each target platform. For cross-platform projects, explicitly document which configuration flags are needed for different build scenarios and package manager integrations.maplibre/maplibre-native4 discussions
- Separate user system dataSeparate user-facing data from system/implementation data using proper namespacing and schema design to prevent data pollution and improve user experience.logseq/logseq4 discussions
- Fail fast explicitlyWhen critical components or operations fail, throw explicit errors rather than silently continuing or returning nil. Silent failures can mislead users into thinking operations succeeded when they didn't, potentially causing data loss or inconsistent application state.logseq/logseq4 discussions
- Use reactive hooksAlways use React's reactive hook patterns instead of imperative state access or manual effect management. This ensures proper component re-rendering, better performance, and cleaner code architecture.lobehub/lobe-chat4 discussions
- Use idempotent migrationsAlways use defensive programming patterns in migration scripts to ensure they can be executed multiple times without errors. This prevents failures during re-execution scenarios and makes migrations more robust.lobehub/lobe-chat4 discussions
- Provider-based interface designWhen designing interfaces that handle multiple providers or services, organize the API structure around provider-specific logic rather than mixing different provider handling in generic components. Use provider-based props structures and create dedicated components or methods for each provider type.lobehub/lobe-chat4 discussions
- Explicit environment declarationsAlways explicitly declare environment variables in configuration files, even when they have default values. Use consistent naming conventions with appropriate prefixes for related variables, and clearly document when each variable is required versus optional.lobehub/lobe-chat4 discussions
- CSS utility usageUse CSS utility functions and avoid complex inline calculations for better maintainability and readability. Prefer `cx()` from useStyles for combining CSS classes instead of template literals, and use `css` from antd-style for simple styles without design tokens.lobehub/lobe-chat4 discussions
- Maintain comprehensive error handlingAlways preserve and implement thorough error handling that includes proper resource cleanup, meaningful logging, and appropriate return values. Don't remove existing error handling during code refactoring or simplification.LMCache/LMCache4 discussions
- Configuration validation standardsEnsure configuration parameters follow consistent validation, naming, and default value standards to improve code safety and clarity. **Key Requirements:**LMCache/LMCache4 discussions
- optimize computational complexityWhen implementing algorithms, be mindful of computational complexity and optimize for efficiency by avoiding expensive operations and reusing existing computations where possible.llvm/llvm-project4 discussions
- Configuration completeness validationEnsure configuration options are complete and properly validated before use. When implementing configuration parsing or option handling, verify that all expected cases are covered and add appropriate validation checks for user inputs.llvm/llvm-project4 discussions
- validate bounds before accessAlways validate array indices, buffer sizes, and container bounds before accessing elements to prevent out-of-bounds errors and undefined behavior. This includes checking that indices are within valid ranges and that containers have sufficient size before element access.ggml-org/llama.cpp4 discussions
- prioritize compile-time optimizationsIn performance-critical code, favor compile-time optimizations over runtime flexibility to enable better compiler optimizations and reduce execution overhead. This principle applies to several key areas:ggml-org/llama.cpp4 discussions
- maintain code consistencyAlways follow the existing code style patterns and conventions found in the surrounding codebase rather than introducing new formatting approaches. This includes matching brace placement, function organization, and parameter formatting styles.ggml-org/llama.cpp4 discussions
- API minimalism principleKeep APIs minimal by avoiding redundant interfaces and preferring simple solutions over complex ones. When adding functionality, first consider extending existing functions rather than creating new ones, especially when there's only a single use case. Remove unnecessary options and flags to maintain interface simplicity.ggml-org/llama.cpp4 discussions
- Safe operations with fallbacksImplement defensive programming by wrapping potentially failing operations in safe methods that provide fallback behavior. Critical operations should never cause the main functionality to fail due to secondary concerns like formatting, logging, or auxiliary processing.BerriAI/litellm4 discussions
- Prefer utility reuseWhen changing or adding code prefer existing helpers, language-idiomatic constructs, and small well-maintained libraries to keep code DRY, readable, and consistent.likec4/likec44 discussions
- Prevent flaky test timingReplace non-deterministic timing patterns with reliable alternatives to prevent flaky tests. This includes: 1. Use element-based waits instead of fixed timeouts:langfuse/langfuse4 discussions
- Pin dependency versionsAlways pin external dependencies to specific versions in CI/CD workflows to ensure build reproducibility, stability, and security. This applies to: 1. GitHub Actions (use tagged versions instead of branch names or commit SHAs)langfuse/langfuse4 discussions
- Explicit null value checksUse explicit null/undefined checks instead of truthy/falsy checks when handling potentially null or undefined values. Relying on truthy/falsy checks can lead to bugs when dealing with valid falsy values like 0 or empty strings.langfuse/langfuse4 discussions
- Configuration value consistencyMaintain consistency in configuration values across the application by following these practices: 1. **Use properly formatted template strings for configuration keys**langfuse/langfuse4 discussions
- Prevent code injection vulnerabilitiesWhen evaluating user-provided code or handling dynamic content, implement strict security measures to prevent malicious code execution and unauthorized access. This includes whitelisting allowed modules/imports, validating input integrity, and properly handling sensitive data.langflow-ai/langflow4 discussions
- Database configuration clarityWhen documenting database configuration or setup procedures, provide specific, actionable instructions with clear verification steps. Always specify which database backend is being used and include concrete examples for verification.langflow-ai/langflow4 discussions
- Avoid hardcoded configuration valuesReplace hardcoded configuration values with configurable parameters to improve flexibility and maintainability. Hardcoded timeouts, domain strings, validation constraints, and operational parameters should be exposed as advanced inputs, environment variables, or settings.langflow-ai/langflow4 discussions
- AI response variabilityWhen documenting AI model interactions, account for the non-deterministic nature of AI responses and avoid assumptions about specific outputs. AI models can produce different responses to identical inputs, and model behavior changes over time through updates and improvements.langflow-ai/langflow4 discussions
- AI model chunk sizingWhen configuring text processing components that work with AI embedding models, proactively consider tokenization limits and chunk size constraints. Many embedding models have practical token limits that are lower than their theoretical maximums, and text splitting components may not enforce exact chunk sizes.langflow-ai/langflow4 discussions
- Use database-native typesAlways leverage database-native data types and appropriate schema design to maximize performance and query capabilities. This includes: 1. Use database-specific type bindings when available instead of generic formats:langchain-ai/langchainjs4 discussions
- Eliminate redundant codeSimplify code by eliminating redundancy and unnecessary complexity. This improves readability, reduces potential bugs, and makes the codebase easier to maintain.langchain-ai/langchainjs4 discussions
- Dependency classification standardsProperly classify dependencies in package.json according to their usage pattern and project guidelines. This ensures correct build behavior, optimizes package size, and prevents dependency conflicts.langchain-ai/langchainjs4 discussions
- Comprehensive AI documentationWhen documenting AI integrations, provide comprehensive examples that showcase all common initialization and usage patterns. Documentation should include:langchain-ai/langchainjs4 discussions
- Avoid hardcoded configurationsAlways parameterize values that might vary across different environments or users instead of hardcoding them in your code. This applies to API endpoints, regions, dimensions, credentials, and other configuration values.langchain-ai/langchainjs4 discussions
- Prevent uv OverwritesWhen CI workflows mix multiple uv steps (e.g., install built wheels, then run tests/lint), make dependency installation *deterministic* and prevent later steps from overwriting earlier artifact installs.langchain-ai/langchain4 discussions
- Wrap errors meaningfullyAlways wrap errors with meaningful context that explains what operation failed and why. Use proper error wrapping with `fmt.Errorf("operation failed: %w", err)` to preserve the original error chain while adding context. Include explanatory comments for complex error handling logic to clarify the intended behavior and recovery strategy.kubernetes/kubernetes4 discussions
- Prevent information disclosureAvoid exposing sensitive information through error messages, logs, configuration, or other output channels that might be accessible to unauthorized parties such as cluster administrators or operators.kubernetes/kubernetes4 discussions
- Feature gate configuration managementEnsure feature gates are properly managed across all configuration files and contexts. Feature-specific permissions, settings, and resources should be conditionally included based on appropriate feature gate guards rather than being present in default configurations. Avoid manually adding feature gates to configuration files when they are automatically...kubernetes/kubernetes4 discussions
- Standardize network toolsWhen performing network operations in build scripts or containers, prefer `curl` over `wget` for HTTP requests to standardize dependencies and improve portability. Use the specific flags `-fsSL` for silent operation with proper error handling, and explicitly specify output destinations.kubeflow/kubeflow4 discussions
- Prioritize readability over brevityWhen writing code, favor readability and maintainability over clever or compact solutions. Break down complex logic into smaller, well-named functions with clear purposes rather than embedding all logic in a single function. kubeflow/kubeflow4 discussions
- Pin version dependenciesExplicitly pin version dependencies in configuration files to ensure reproducible builds and prevent breaking changes. When dealing with external tools, scripts, or APIs, always specify exact versions or commit hashes rather than using "latest" or master branches.kubeflow/kubeflow4 discussions
- Load configurations efficientlyWhen designing components that require configuration, follow these practices to enhance performance, maintainability, and usability: 1. **Load configuration once at startup** rather than repeatedly during reconciliation loops:kubeflow/kubeflow4 discussions
- Follow API conventionsWhen designing APIs, adhere to established API conventions, particularly Kubernetes API conventions when working within the Kubernetes ecosystem. This improves API clarity, maintainability, and future compatibility.kubeflow/kubeflow4 discussions
- Externalize configuration parametersCreate configurations that can be easily managed outside your application code. Design configuration parameters to be externalized through appropriate mechanisms like environment variables, config files, or Kubernetes custom resources (CRs). This improves manageability, enables GitOps workflows, and supports different deployment environments.kubeflow/kubeflow4 discussions
- Document code thoroughlyAlways include appropriate documentation in your code to improve readability, maintainability, and usability: 1. **Document all public APIs** with Go doc comments:kubeflow/kubeflow4 discussions
- Contextualize and classify errorsAlways provide meaningful context when handling errors, and classify them appropriately based on their source. This improves debugging, helps users understand issues, and creates a consistent approach to error handling across the codebase.kubeflow/kubeflow4 discussions
- Centralize configuration constantsStore configuration constants, defaults, and environment variable mappings in dedicated configuration files rather than duplicating them across the codebase. This provides a single source of truth, improves maintainability, and reduces errors from inconsistent values.kubeflow/kubeflow4 discussions
- Use defensive null checksWhen working with properties or methods that could potentially be null, use Kotlin's null safety features defensively even if you believe the value should never be null. This prevents runtime exceptions when assumptions change or when interacting with Java/third-party code.JetBrains/kotlin4 discussions
- Cache Consistency RulesWhen implementing caching, make coherence and invalidation explicit and configuration-driven: - If a setting promises immediate consistency (e.g., “strict”), do not perform lazy reloads; rely on the update pipeline to keep cached data correct.Kong/kong4 discussions
- API surface compatibilityTreat any change to a public interface (PDK function signatures, plugin config/schema fields, or other externally-consumed API contracts) as a compatibility commitment.Kong/kong4 discussions
- minimize merge conflictsWhen working with upstream codebases, prioritize coding approaches that minimize merge conflicts while maintaining functionality. Keep dependency arrays in consistent order with upstream code, use CSS classes for conditional styling instead of conditional rendering to create smaller diffs, and isolate custom components in separate directories. For example,...kilo-org/kilocode4 discussions
- validate configuration dependenciesValidate configuration dependencies and constraints at initialization time rather than allowing invalid combinations to cause runtime failures. When configurations have interdependencies, implement validation logic that checks these relationships early and provides clear error messages.apache/kafka4 discussions
- optimize data structuresWhen working with data structures and collections, optimize for performance and correctness by using modern APIs, proper sizing, result filtering, and lazy initialization. Use `List.of()` and `Map.of()` instead of legacy `Collections.singletonList()` and `Collections.singletonMap()` for better readability and performance. Size collections appropriately -...apache/kafka4 discussions
- Optimize collection conversionsWhen converting between Java and Scala collections or performing set operations, choose methods that minimize temporary collection creation to improve performance and reduce memory overhead.apache/kafka4 discussions
- Improve code readabilityWrite code that prioritizes readability through clear string formatting, descriptive method calls, and well-organized structure. Use string interpolation instead of concatenation for better readability, choose descriptive assertion methods that provide meaningful error messages, avoid code duplication by leveraging method overloading, and extract complex...apache/kafka4 discussions
- Ensure complete JavaDoc coverageAll public classes, methods, and parameters must have comprehensive JavaDoc documentation. This includes: 1. **Class-level JavaDoc**: Every public class and interface requires JavaDoc explaining its purpose and usageapache/kafka4 discussions
- catch specific exceptionsAvoid catching overly broad exception types like `Throwable` or `Exception` when you can be more specific about the expected failure modes. Catching `Throwable` is particularly dangerous as it captures JVM-level errors like `OutOfMemoryError` that should typically cause the application to exit.apache/kafka4 discussions
- preserve error contextWhen handling errors, preserve the original error context and avoid exposing internal representations to users. Use `IoResultExt::context()` to attach meaningful path information to I/O errors, and maintain error source chains using `.with_source()` or similar mechanisms.jj-vcs/jj4 discussions
- Minimize API scopeWhen designing APIs, prioritize simplicity and focused scope over feature completeness. Before adding new API methods or expanding existing ones, evaluate whether the functionality can be achieved with existing interfaces. APIs that spread across multiple modules or introduce complex signatures often indicate scope creep that should be avoided.jj-vcs/jj4 discussions
- Use configuration constantsAlways use named constants, enums, or well-defined configuration objects instead of magic strings, numbers, or inline literals for configuration values. This improves maintainability, reduces typos, enables better IDE support, and makes configuration changes easier to track.menloresearch/jan4 discussions
- model description accuracyEnsure AI model descriptions are specific, capability-focused, and avoid marketing language or temporal references like "latest". Descriptions should clearly communicate what the model excels at and its intended use cases to help users make informed selection decisions.menloresearch/jan4 discussions
- Implement graceful error fallbacksAlways implement fallback mechanisms when primary operations can fail, especially for critical operations like resource cleanup, async operations, and user-facing functionality. When the primary approach fails, provide a secondary method to handle the situation gracefully rather than letting errors propagate unchecked.menloresearch/jan4 discussions
- Document AI infrastructure requirementsWhen documenting AI applications that run local models or perform inference, always provide comprehensive infrastructure requirements including hardware specifications, platform-specific drivers, and setup instructions. This ensures users can successfully run AI models without encountering compatibility issues.menloresearch/jan4 discussions
- Cross-platform configuration simplificationWhen writing configuration files and scripts, prioritize cross-platform compatibility while keeping configurations simple and maintainable. Use platform-aware tools like `run-script-os` for npm scripts that need platform-specific behavior, but prefer built-in solutions and global defaults over complex custom configurations.menloresearch/jan4 discussions
- AI model configuration completenessEnsure all necessary AI model parameters are properly configured and passed through the system. AI models require comprehensive configuration including hardware settings (CPU/GPU allocation, thread counts), model-specific parameters (context length, n_gpu_layers), and proper path resolution. Missing configuration can lead to runtime failures, suboptimal...menloresearch/jan4 discussions
- AI accuracy documentationEnsure accurate representation of AI model capabilities, proper attribution, and honest claims about functionality. When documenting AI systems, focus on the underlying model capabilities rather than just pipeline descriptions, provide clear explanations of model variants (distilled vs full models), attribute models to their actual creators, and avoid...menloresearch/jan4 discussions
- telemetry consistency standardsEnsure telemetry attribute population logic is consistent across all components and follows established standards. When implementing telemetry features like resource attributes, baggage headers, or tracing configurations, use the same business logic and attribute naming conventions throughout the codebase.istio/istio4 discussions
- Document observability rationaleWhen introducing, modifying, or removing observability features (tracing, metrics, monitoring configurations), always include clear documentation explaining the rationale, use cases, and migration guidance. Users need to understand why they would want to use a feature and how it solves their specific problems.istio/istio4 discussions
- API version compatibility firstWhen selecting API versions, prioritize compatibility over using the latest available version. Choose older, stable API versions when they provide the same schema but broader compatibility across Kubernetes versions. This approach minimizes breaking changes for users and reduces deployment friction.istio/istio4 discussions
- M3U metadata and linksWhen editing M3U playlist configuration, treat each `#EXTINF` block as configuration data that must be (1) internally consistent, (2) externally valid, and (3) quality/behavior-preserving.iptv-org/iptv4 discussions
- prefer idiomatic patternsChoose language-native methods and control structures that make code more readable and maintainable. Use built-in functions instead of manual implementations, select appropriate control flow structures, and write explicit code that clearly communicates intent.vadimdemedes/ink4 discussions
- Package.json configuration standardsEnsure package.json follows modern standards and maintains consistency across configuration fields. Use structured exports instead of simple main field, align dependency versions with engine requirements, prefer configuration properties over CLI flags, and avoid accidental version locking.vadimdemedes/ink4 discussions
- avoid `any` type usageReplace `any` type annotations with more specific types to improve type safety and null handling. The `any` type disables TypeScript's type checking, including null safety checks, making code prone to runtime errors.vadimdemedes/ink4 discussions
- Use structured logging fieldsAlways use structured logging with descriptive field names rather than string interpolation. Include relevant context variables such as identifiers, durations, and parameters to make logs more useful for debugging and monitoring. This practice makes logs more searchable, filterable, and easier to analyze.influxdata/influxdb4 discussions
- Prevent nil dereferencesAlways verify that pointers, slices, or arrays are non-nil and have sufficient elements before attempting to access their members. Use appropriate checks in the correct order to prevent runtime panics.influxdata/influxdb4 discussions
- Prefer configurable valuesAlways use configurable values instead of hardcoded defaults when available. This ensures that user preferences are respected throughout the application lifecycle and prevents unexpected behavior.influxdata/influxdb4 discussions
- Performance-conscious metrics implementationImplement metrics collection that is both comprehensive and minimally impactful on system performance. Design your metrics system to avoid creating bottlenecks in critical paths.influxdata/influxdb4 discussions
- Include explanatory examplesAlways enhance documentation with concrete, illustrative examples that demonstrate expected inputs, formats, or outputs. Examples significantly improve comprehension and reduce ambiguity, especially for complex parameters, commands, or return values.influxdata/influxdb4 discussions
- Avoid unnecessary workWhen optimizing performance-critical code paths, eliminate redundant operations and unnecessary processing: 1. **Exit loops early** when a decision has been made and no further iterations are needed:influxdata/influxdb4 discussions
- Avoid flaky test patternsWrite reliable tests by avoiding common patterns that can lead to flaky behavior. Specifically: 1. Avoid arbitrary timeouts and sleeps in tests. Instead, use proper test infrastructure or wait for specific conditions.influxdata/influxdb4 discussions
- Test all code pathsWrite comprehensive tests that cover all code paths including edge cases, error conditions, and different parameter combinations. Each test file should include:elie222/inbox-zero4 discussions
- Prevent workflow recursionControl GitHub Actions workflow execution to avoid infinite loops and unnecessary builds. Implement these practices: 1. **Add `paths-ignore` filters** for generated files that might trigger the workflow again:elie222/inbox-zero4 discussions
- Normalize API responsesDesign APIs to return consistent response structures across different data sources or providers. Normalize responses at the API layer rather than handling provider-specific format differences in client components. This approach:elie222/inbox-zero4 discussions
- Handle AI operation failuresAlways implement proper error handling for AI service operations. AI services can fail due to rate limiting, network issues, or service outages. Wrap AI service calls in try-catch blocks to gracefully handle potential failures, log relevant error information, and provide appropriate fallbacks.elie222/inbox-zero4 discussions
- Ensure API contract integrityMaintain strict consistency between API implementation and contract by ensuring: 1. Request/response schemas match exactly between client and server 2. All required parameters are validated and documentedelie222/inbox-zero4 discussions
- Define schema relations correctlyWhen designing database schemas, ensure relations and constraints are explicitly and correctly defined: 1. Every model must have a properly defined primary key:elie222/inbox-zero4 discussions
- Complete hook dependency arraysEnsure all hooks (useEffect, useCallback, useMemo) explicitly list every dependency used within their callback functions. Missing dependencies can lead to stale closures, unexpected behaviors, and hard-to-debug issues.elie222/inbox-zero4 discussions
- Cache invariant computationsAvoid repeatedly computing values that don't change frequently. For data structures, maps, or validation schemas used in hot paths, initialize them once at module scope rather than recreating them on every function call.elie222/inbox-zero4 discussions
- Semantic variable namingVariable names should clearly convey their purpose, type, and units to improve code readability and prevent errors. Follow these naming conventions: **Unit specification**: Include units in variable names when dealing with measurements or time values. Use suffixes like `Us` for microseconds, `Ms` for milliseconds, etc.hyprwm/Hyprland4 discussions
- prefer std::error_code parametersWhen using std::filesystem operations, prefer passing std::error_code parameters instead of relying on try-catch blocks for error handling. This approach provides better performance and more explicit error checking.hyprwm/Hyprland4 discussions
- prefer managed pointersRaw pointers are banned in new code unless absolutely necessary. Instead, use managed pointer types to prevent null pointer dereferences, dangling pointers, and memory safety issues.hyprwm/Hyprland4 discussions
- Precise documentation languageDocumentation language should be precise, unambiguous, and clearly scoped to prevent misinterpretation while maintaining readability. Avoid open-ended terms that could be misunderstood or exploited, and use established terminology when dealing with legal, technical, or domain-specific concepts.hyprwm/Hyprland4 discussions
- Precise configuration patternsUse precise file patterns and correct installation paths in CMake configuration to avoid unintended inclusions and ensure proper system integration. Overly broad patterns can consume unrelated files from subprojects, while incorrect paths can break package discovery.hyprwm/Hyprland4 discussions
- use Option combinatorsLeverage Rust's Option API methods like `map`, `and_then`, `is_some()`, and `filter` instead of manual pattern matching or nested conditional statements when working with optional values. This approach reduces code complexity, improves readability, and prevents common null-handling errors.juspay/hyperswitch4 discussions
- Database schema consistencyEnsure database schema definitions are consistent with ORM annotations and include proper constraints for data integrity and security. This includes matching primary key definitions between migrations and ORM models, making foreign key relationships mandatory where appropriate, and requiring tenant identifiers in queries to prevent cross-tenant data access.juspay/hyperswitch4 discussions
- Choose optimal algorithmsWhen implementing functionality, carefully evaluate and select the most efficient algorithmic approaches for data processing, pattern matching, and operations. Consider computational complexity and performance implications of different approaches.juspay/hyperswitch4 discussions
- Simplify CI workflow structureDesign CI/CD workflows to be simple, DRY, and correctly ordered. Specifically: 1. Avoid duplicating the same sequence of steps across multiple jobs; extract shared logic into a composite action (or reusable workflow) so changes only need to be made in one place.honojs/hono4 discussions
- Safe, readable loggingWhen adding or modifying log output, keep messages concise, human-readable, and resistant to abuse: 1. Format values for readability instead of raw numbers/bytes. For example, colorize HTTP status codes only when color output is enabled, and render sizes in human units (e.g. `746b`, `1.9kb`) rather than raw byte counts:honojs/hono4 discussions
- Cache header handlingWhen caching middleware reads, mutates, or compares HTTP headers (Cache-Control, ETag, expiration timestamps, etc.), account for header immutability and case-insensitivity.HONOJS/HONO4 discussions
- Success Contract Error HandlingDefine a single “success contract” for each step: only report ok/success if the operation is actually accepted; for optional steps, convert failures into a structured soft-skip (but still record a diagnostic reason).nousresearch/hermes-agent4 discussions
- Config contract consistencyApply a “configuration as a contract” standard: when behavior depends on environment/profile/feature flags (remote vs local, active management profile, accessibility mode, client/server timing), wire that configuration into *all* relevant code paths and keep its semantics consistent across layers.nousresearch/hermes-agent4 discussions
- Standardize build configuration patternsExplicitly define and standardize build configuration patterns across the project to ensure consistent behavior and optimal performance. Use explicit build type declarations and separate configurations for development and release builds.helix-editor/helix4 discussions
- hide implementation detailsWhen designing APIs, avoid exposing internal structures, implementation details, or platform-specific concepts to external consumers. Instead, create clean, stable interfaces that focus on what users need to accomplish rather than how the system works internally.helix-editor/helix4 discussions
- consistent naming conventionsMaintain consistent naming patterns throughout your codebase, following established conventions and ensuring uniformity within the same context. This includes using correct syntax for configuration values, matching case conventions for related identifiers, organizing entries systematically (like alphabetically), and choosing descriptive names that clearly...helix-editor/helix4 discussions
- avoid quadratic complexityWhen working with data structures, especially ropes and collections, avoid algorithms that result in quadratic time complexity when linear alternatives exist. Common patterns to watch for include repeated indexing operations and nested loops over related data sets.helix-editor/helix4 discussions
- avoid panics gracefullyReplace panics, expects, and unwraps with graceful error handling that provides user feedback and allows the system to continue operating. Instead of crashing the application, log errors appropriately and return early or set status messages for the user.helix-editor/helix4 discussions
- avoid hardcoded configuration valuesAvoid hardcoding configuration values that affect user experience or behavior. Instead, make these values configurable with sensible defaults. This is especially important for timing values, thresholds, and user-facing constants that different users may want to customize.helix-editor/helix4 discussions
- Prefer functional styleFavor functional, immutable patterns over imperative mutation and control flow. Avoid pushing into arrays or mutating variables in loops; use `map`, `filter`, `reduce`, `some`, and `every` instead, keeping variables `const` wherever possible. Similarly, avoid multi-branch `switch` statements scattered inline—TypeScript's switch lacks the safety of pattern...Helicone/helicone4 discussions
- Explicit, intentional null fallbacksWhen a value may be null or undefined, don't silently coalesce it to a generic default without considering the semantic consequences. A careless `?? 0` or `?? "default"` can mask real errors (e.g., returning 0 for a queue size that failed to load, hiding an alert that should stay active) or produce incorrect behavior (e.g., treating a missing...Helicone/helicone4 discussions
- Safe property access patternsUse appropriate null/undefined handling techniques based on the context to prevent runtime errors. Be mindful of the distinction between `null` and `undefined` in TypeScript, as they behave differently and affect type safety.grafana/grafana4 discussions
- Prefer null-safe accessAlways use null-safe access patterns when dealing with potentially undefined values to prevent runtime errors and improve code robustness. This includes:grafana/grafana4 discussions
- Optimize performance patternsChoose efficient implementation patterns that improve performance. Apply these optimizations throughout your code: 1. **Avoid redundant operations**: Store results of expensive lookups rather than repeating them.grafana/grafana4 discussions
- Name for purpose firstChoose names that lead with their primary purpose or category, followed by specific details. This makes code more discoverable and self-documenting by grouping related items and clearly conveying intent.grafana/grafana4 discussions
- Minimize database joinsPrefer direct filtering or specialized service methods over complex JOIN operations, especially when maintaining or refactoring database access patterns. JOINs across multiple tables can impact performance and make code more difficult to maintain, particularly during architectural migrations.grafana/grafana4 discussions
- Maintain configuration documentation accuracyAlways ensure configuration documentation accurately reflects the current system capabilities, limitations, and feature availability status. When documenting configuration options:grafana/grafana4 discussions
- Judicious configuration managementCarefully manage configuration options, including feature flags, to balance flexibility with maintainability: 1. **Use feature flags strategically:**grafana/grafana4 discussions
- Fail-safe security defaultsAlways implement security features with fail-safe defaults that deny access or disable insecure functionality unless explicitly configured. When security-sensitive features must be available in development environments, add explicit environment checks to prevent their use in production.grafana/grafana4 discussions
- Consistent semantic namingUse consistent, specific, and semantically appropriate naming conventions throughout the codebase. When creating new identifiers: 1. Check for existing patterns for similar concepts (e.g., use 'ascending/descending' for sort options to match existing UI components)grafana/grafana4 discussions
- Consistent API versioning approachAdopt and document a consistent approach to API versioning across your services. The chosen format should be clearly communicated, whether using the simple form (e.g., `"apiVersion": "v0alpha1"`) or the fully qualified form (e.g., `"apiVersion": "prometheus.datasource.grafana.app/v0alpha1"`).grafana/grafana4 discussions
- Component architecture principlesExtract logic that doesn't render JSX into custom hooks instead of components. Components that don't return markup create unnecessary abstraction layers and can lead to harder-to-follow data flows.grafana/grafana4 discussions
- User-focused documentation structureDocumentation should prioritize user needs and problems over technical implementation details. Start with the "why" - what problem does this solve and when would users need it? Provide clear use cases and benefits before diving into technical specifics.block/goose4 discussions
- Optimize memory and algorithmsFocus on efficient memory usage and algorithm selection while preserving functionality. Apply these optimization techniques: **Memory optimization:**block/goose4 discussions
- Null-safe early GuardsAlways handle nullable/optional state explicitly before executing logic that can mutate state, clear user input, or drop data. Use early returns or dedicated “disabled” props driven by well-defined nullable/flag conditions, and preserve intentional empty values instead of treating all falsy/empty inputs as “missing.”aaif-goose/goose4 discussions
- Handle errors intentionallyAvoid generic catch-all error handling that masks important failures. Instead, be selective about which errors to handle locally versus letting them bubble up to higher-level handlers. When you do handle errors locally, implement safe defaults and use robust parsing methods.block/goose4 discussions
- Graceful Error RecoveryWhen handling failures in async, remote, or multi-step flows, make the system degrade safely and keep UI/state consistent with what the server actually persisted.aaif-goose/goose4 discussions
- Explicit Null SemanticsWhen handling optional/nullable values in TypeScript/React, make “unset/default” distinct from “legitimate empty/zero” and avoid truthiness-based guards.aaif-goose/goose4 discussions
- consolidate API parametersPrefer consolidating common configuration and parameters in API constructors or base methods rather than requiring multiple method calls, complex parameter passing, or external configuration loading. This reduces API surface area and makes interfaces easier to use for consumers.block/goose4 discussions
- avoid concurrency anti-patternsAvoid common concurrency anti-patterns that lead to race conditions, deadlocks, and unreliable behavior. Use structured approaches instead of ad-hoc solutions.block/goose4 discussions
- AI terminology consistencyMaintain consistent terminology when describing AI systems, capabilities, and workflows throughout documentation and content. This includes using standardized terms for AI entities (consistently choosing between "AI", "assistant", "model", or "agent"), technical processes, and capability descriptions.block/goose4 discussions
- Descriptive idiomatic identifiersUse descriptive names for variables, types, and interfaces that follow Go language idioms. Avoid single-letter variables or cryptic abbreviations that reduce code readability.gin-gonic/gin4 discussions
- Consistent error patternsImplement consistent error handling patterns throughout your codebase to improve readability and maintainability. **Key guidelines:** 1. Use named error variables instead of inline error creationgin-gonic/gin4 discussions
- Structure user documentationWhen documenting complex features or configuration options, structure your documentation with these four key elements: 1. **Concise summary**: Begin with a brief, terse explanation of what the feature doesghostty-org/ghostty4 discussions
- Semantic name clarityNames should clearly and accurately reflect the purpose of variables, methods, and other identifiers. Follow these principles: 1. Use descriptive, specific names that convey exact purposeghostty-org/ghostty4 discussions
- Prevent unnecessary memory operationsAvoid redundant memory allocations and copies when simpler alternatives exist. This includes: 1. Use in-place comparison functions instead of allocating for string operationsghostty-org/ghostty4 discussions
- Optimize comparison patterns efficientlyChoose efficient comparison patterns and algorithms based on the data type and use case. Key guidelines: 1. For string pattern matching, prefer glob patterns over regex for simple cases:ghostty-org/ghostty4 discussions
- In-tree build configurationsKeep all build configuration files (Snapcraft, Flatpak manifests, etc.) in the repository alongside your code to ensure they are tested, versioned, and maintained together with the application. This approach facilitates CI testing, allows for regression detection, and ensures consistency across distribution methods.ghostty-org/ghostty4 discussions
- Documentation lookup rulesWhen writing or updating API skill docs, treat documentation as an operational dependency: prefer the most up-to-date source, keep docs self-contained, and make examples unambiguous.google-gemini/gemini-skills4 discussions
- prefer settings over environmentPrefer settings.json over environment variables and CLI flags for user configuration options. Environment variables should be reserved for system-level configuration or cases where the setting must be available before settings.json is loaded. CLI flags should be used for options that users frequently change between invocations.google-gemini/gemini-cli4 discussions
- Centralize proxy configurationAvoid duplicate proxy configuration across your application by establishing a single point of proxy setup and leveraging built-in proxy support where available. Multiple proxy configurations can lead to conflicts, inconsistent behavior, and maintenance overhead.google-gemini/gemini-cli4 discussions
- Centralize configuration managementPrefer centralized configuration files (settings.json, settings.ts) over environment variables for application settings, especially when organizational control is needed. Avoid hardcoded assumptions about user environments and ensure configuration is loaded at appropriate initialization points.google-gemini/gemini-cli4 discussions
- Validate with sensible defaultsImplement a comprehensive configuration validation strategy that combines centralized validation functions with appropriate default values and user-friendly messaging. Instead of failing with errors on non-critical configuration issues, provide warnings and continue with sensible defaults.fatedier/frp4 discussions
- Follow Go naming conventionsAdhere to Go's standard naming conventions for identifiers: 1. **Control visibility with capitalization**: - Use uppercase first letter for exported (public) identifiersfatedier/frp4 discussions
- Deterministic Array Algorithm ContractsFor algorithm-heavy code that transforms arrays (multi-step pipelines, scheduling, deduping, cyclic traversal), require clear, testable function contracts and deterministic behavior:freeCodeCamp/freeCodeCamp4 discussions
- Optimize migration codeWhen writing database migration code, prioritize clarity and efficiency to ensure migrations are reliable and maintainable across environments. Apply these practices:laravel/framework4 discussions
- Optimize loop operationsWhen writing loops, optimize for both readability and performance by following these key principles: 1. **Exit early** when a decision can be made: ```phplaravel/framework4 discussions
- Disable coverage in workflowsKeep code coverage tools disabled in CI/CD workflows unless they're specifically needed for generating coverage reports. Enabling coverage tools like xdebug in GitHub Actions can significantly slow down pipeline execution without providing value when reports aren't being collected or analyzed.laravel/framework4 discussions
- Descriptive configuration keysConfiguration keys should clearly indicate their value type, units, or expected format to prevent misunderstandings and errors. Include unit information directly in key names when appropriate and ensure documentation accurately reflects the default values and behavior.laravel/framework4 discussions
- Test observable behaviorFocus on testing what users see and experience rather than internal implementation details. Tests should verify the actual behavior that matters to users, not how the code achieves that behavior internally.flutter/flutter4 discussions
- Make errors explicitAlways make error conditions explicit and visible rather than hiding them through silent failures, default return values, or unchecked operations. This includes validating results before use, using assertions for invalid states, and logging unexpected conditions.flutter/flutter4 discussions
- Future-proof configuration defaultsWhen designing configuration options, avoid hardcoded values and ensure defaults can be changed in future versions without breaking existing code. Make boolean flags negatable so users can opt out when defaults change, avoid ambiguous null vs empty configuration states, and provide clear migration paths for deprecated options.flutter/flutter4 discussions
- Sanitize untrusted client inputTreat all client-supplied data—HTTP headers (e.g. `Host`), query/path parameters, form data—as untrusted, and enforce strict validation or escaping before using it in security-sensitive contexts such as generating URLs or rendering HTML. Mitigations must be mandatory, correctly scoped, and precisely described rather than presented as optional suggestions.pallets/flask4 discussions
- Safe async-to-sync bridgingWhen code must run async coroutines from a synchronous context (or vice versa), be deliberate about correctness, extensibility, and dependency handling:pallets/flask4 discussions
- Document environment config scopeWhen documenting or introducing configuration mechanisms (env files, env vars, build/tox flags, config options), be explicit about what each mechanism is for, where it applies, and what is safe to commit to version control. Specifically:pallets/flask4 discussions
- Validate configuration defaultsConfiguration structs should validate input values and provide sensible defaults that work well in production environments. Always check for invalid values (like negative timeouts), provide reasonable defaults for production use cases, and handle edge cases where users might set unexpected values.gofiber/fiber4 discussions
- Use context for configurationWhen accessing application state or configuration within request handlers, always use the context method `c.App().State()` instead of direct app instance references. This pattern ensures proper context isolation, supports dependency injection, and works correctly in multi-file applications where the app instance may not be directly accessible.gofiber/fiber4 discussions
- Include practical examplesDocumentation should include practical, working examples that demonstrate real-world usage scenarios. When introducing new features, methods, or concepts, provide concrete code examples that show users how to apply them in practice. This is especially important when mentioning functionality multiple times without demonstration, or when documenting complex...gofiber/fiber4 discussions
- Document mutex usageAlways document mutex fields and their purpose, ensure proper locking/unlocking patterns, and avoid redundant locks when underlying structures are already thread-safe. When using mutexes, clearly indicate what data they protect and why the synchronization is necessary.gofiber/fiber4 discussions
- Proper Handling of Promises in Fastify ImplementationsWhen implementing Fastify applications in TypeScript, it is important to follow consistent patterns for handling promises and respecting the framework's specific constraints. Avoid mixing async/await with callback styles, especially when registering routes, plugins, or parsers.fastify/fastify4 discussions
- Content negotiation designWhen building APIs, implement proper content negotiation to handle various media types in both requests and responses. This ensures your API can work with different client requirements and maintain compatibility with diverse ecosystems.fastify/fastify4 discussions
- Consistent descriptive namingUse precise, consistent, and descriptive naming conventions throughout your code to enhance readability and maintainability. This includes using past participle forms for variables storing processed data, choosing function names that clearly describe their purpose, using consistent naming patterns for related parameters, and naming properties to clearly indicate their relationships.fastify/fastify4 discussions
- Benchmark before choosing methodsAlways benchmark different implementation approaches for performance-critical operations before selecting a method. Different approaches (like array operations, string parsing, or data iteration) can have significant performance implications that may not be intuitive.fastify/fastify4 discussions
- Use pytest fixtures effectivelyTests should use pytest fixtures to improve organization, promote test isolation, and avoid code duplication. Fixtures provide a clean way to set up test dependencies, manage test state, and create reusable test components.fastapi/fastapi4 discussions
- Use early returnsDecrease indentation levels in your code by using early returns for edge cases and guard conditions. This approach improves readability by reducing nesting and making the code flow more linear.fastapi/fastapi4 discussions
- Respect async execution orderWhen working with asynchronous code, always be mindful of the execution order of operations, particularly with regards to yielded dependencies, middleware, and background tasks. This affects resource management, error handling, and overall application flow.fastapi/fastapi4 discussions
- Proper HTTP status codesWhen implementing authentication and authorization systems, use semantically correct HTTP status codes to accurately convey the nature of security-related failures. This improves API security by providing accurate information to clients without exposing unnecessary details.fastapi/fastapi4 discussions
- Verify markdown renders correctlyWhen writing or editing markdown documentation (README, History, CONTRIBUTING, guides), verify that links, anchors, and references will actually resolve and render as intended on GitHub rather than assuming raw text works. Specifically: (1) GitHub does not auto-link bare commit hashes or issue/PR numbers, so wrap them in explicit markdown links, e.g. ``...expressjs/Express4 discussions
- Validate untrusted input strictlyTreat any value that originates from user input, HTTP headers, or caller-supplied options as untrusted, and validate it with explicit, narrow rules rather than loose type checks. Prefer allow-lists or numeric ranges over single-type checks (e.g. reject any statusCode outside 100-999 instead of only checking `typeof === 'bigint'`), and only trust headers...Expressjs/Express4 discussions
- Optimize hot pathsWhen writing code that will be executed frequently (hot paths), prioritize performance optimizations that reduce overhead. This includes: 1. **Move expensive operations out of frequently executed blocks**: Place resource-intensive operations like `require()` calls at module initialization rather than in request handlers or response methods.expressjs/express4 discussions
- Optimize dependency automationConfigure automated dependency update tools (like Dependabot) to balance security needs against developer cognitive load. Set monthly intervals instead of weekly to reduce PR noise, limit the number of concurrent PRs, and consider excluding major version updates that could cause compatibility issues.expressjs/express4 discussions
- Access settings properlyAlways use the provided settings accessor methods (`app.get()`, `app.set()`, `app.enabled()`, `app.disabled()`) to access application configuration instead of directly accessing the settings object. Direct access to the settings object was deprecated and may lead to inconsistent behavior or errors.expressjs/express4 discussions
- Algorithm selection correctnessChoose algorithms that correctly match the problem requirements and understand their computational properties and side effects. Avoid using overly general solutions (like regex) when simpler, more precise algorithms exist.evanw/esbuild4 discussions
- mark experimental configuration featuresAlways mark experimental and deprecated configuration options with appropriate stability indicators in documentation. Use `_Experimental_` for features under active development and `_Deprecated_` for features being phased out. This helps developers make informed decisions about which configuration options are safe for production use.electron/electron4 discussions
- Ensure async error cleanupAlways ensure cleanup code executes and avoid creating dangling promises in error handling scenarios. Use try-catch-finally patterns for guaranteed cleanup, and avoid making error handlers async unless you properly handle promise rejections.electron/electron4 discussions
- consistent nullable returnsEstablish consistent patterns for nullable return values in APIs and document them clearly. Use `null` consistently for "not found" or "unavailable" cases rather than mixing `null`, `undefined`, and `false`. Always document when and why nullable values are returned, explaining the specific conditions that lead to these values.electron/electron4 discussions
- Avoid exposing sensitive APIsDo not enable configurations that expose Node.js or Electron APIs to untrusted web content in renderer processes. This includes avoiding `nodeIntegration: true` for remote content and not directly exposing IPC APIs in preload scripts.electron/electron4 discussions
- Parallel branch traceabilityWhen implementing algorithms with parallel processing branches, ensure proper traceability and data consistency across all branches to facilitate result analysis and debugging:elastic/elasticsearch4 discussions
- Exceptions for critical errorsUse exceptions rather than assertions for handling critical error conditions that need to be caught in production. Assertions should only be used for development-time invariant checking that should never occur in production code.elastic/elasticsearch4 discussions
- Defensive null handlingAlways handle null references and values defensively to prevent NullPointerExceptions and unexpected behavior. Follow these practices: 1. **Check nulls before dereferencing**: Always verify a reference is not null before accessing its methods or properties:elastic/elasticsearch4 discussions
- Configure type serializationWhen working with databases that exchange data with other systems, ensure proper serialization and deserialization of data types like UUIDs, dates, or complex objects. System-specific representation differences can lead to data corruption, query failures, or incorrect results.elastic/elasticsearch4 discussions
- Clarity over uncertaintyTechnical documentation should use precise language that clearly differentiates between product behavior and user configuration options. Frame explanations from the user's perspective, emphasizing capabilities rather than limitations.elastic/elasticsearch4 discussions
- Protect shared stateAlways protect shared mutable state with appropriate synchronization mechanisms to prevent race conditions and data corruption in multi-threaded environments. Use `std::call_once` for thread-safe initialization, mutexes for protecting shared resources, and carefully consider whether state belongs in global vs local thread contexts.duckdb/duckdb4 discussions
- preserve serialization compatibilityWhen making changes to serialized data structures, always preserve backward and forward compatibility to prevent breaking existing databases and migration paths. This applies to enums, serialized plans, function serialization, and version handling.duckdb/duckdb4 discussions
- prefer settings over pragmasWhen implementing configuration options, prefer database settings over pragma functions to maintain consistency and better user experience. Settings provide a unified interface that's easier to discover, document, and manage compared to scattered pragma functions.duckdb/duckdb4 discussions
- optimize hot path performanceAvoid expensive operations in frequently executed code paths by implementing performance optimizations such as lookup tables, result caching, conditional initialization, and object reuse.duckdb/duckdb4 discussions
- maintain API backward compatibilityWhen evolving APIs, prioritize backward compatibility by creating new methods or overloads rather than modifying existing function signatures. This prevents breaking changes for existing users and extensions.duckdb/duckdb4 discussions
- Constructor configuration injectionPrefer injecting configuration objects through constructors rather than passing them as ad-hoc parameters or using global instances. This approach improves extensibility, reduces error-prone context passing, and enables per-instance customization.duckdb/duckdb4 discussions
- comprehensive database testingDatabase tests should execute actual queries and verify results comprehensively, not just check query plans or use hash comparisons. Always include edge cases, test data scenarios with both expected and unexpected data, and verify storage correctness through restart/reload cycles.duckdb/duckdb4 discussions
- Use standardized logging patternAlways use the standardized logging pattern with module-level loggers instead of print statements or direct logging calls. This ensures consistent logging behavior, proper log level control, and better debugging capabilities across the codebase.stanfordnlp/dspy4 discussions
- Optional dependency managementAvoid including optional or provider-specific dependencies in the main dependency list. Dependencies should only be required if they are essential for core functionality that all users need.stanfordnlp/dspy4 discussions
- Configuration context consistencyEnsure configuration names, values, and settings accurately reflect their intended context and usage. Configuration mismatches can lead to runtime errors, incorrect behavior, and maintenance issues.drizzle-team/drizzle-orm4 discussions
- Use Correct NamingUse naming conventions that clearly distinguish placeholders from required identifiers, follow platform identifier constraints, and keep variable scope/semantics correct.github/docs4 discussions
- Prevent N+1 queriesThe N+1 query problem is one of the most common performance bottlenecks in Django applications. This occurs when you retrieve a list of objects and then access related objects for each one individually, causing an additional database query for each parent object.django/django4 discussions
- Optimize computational complexityIdentify and reduce computational complexity in your code by minimizing redundant operations and simplifying algorithms. Focus especially on code that processes large datasets or is called frequently.django/django4 discussions
- Measure before optimizingAlways measure performance impact before implementing optimizations and focus on changes with meaningful benefits. Python's performance characteristics can be unintuitive - optimizations that seem beneficial might have minimal impact, while simple changes can yield significant improvements.django/django4 discussions
- Defend against nullsAlways use defensive programming techniques when handling potentially null or empty values to avoid runtime errors. Consider these practices: 1. Use specialized methods when checking for default values or null states rather than direct comparisons:django/django4 discussions
- Use dynamic configuration accessAlways access configuration values through proper service APIs rather than hardcoding them or using unreliable access patterns. This ensures configuration remains maintainable and behaves consistently across different contexts.discourse/discourse4 discussions
- Safe setting modificationsWhen modifying site settings during operations like imports, jobs, or plugin initialization, implement proper safeguards to prevent unintended permanent changes. Consider the impact on existing sites and provide mechanisms for restoration or warnings.discourse/discourse4 discussions
- Include contextual log informationLog messages should include sufficient context to make them useful for debugging, monitoring, and audit trails. Include relevant entity IDs, operation details, and descriptive information that helps identify what was happening when the log entry was created.discourse/discourse4 discussions
- Consistent null safety patternsApply null safety operators consistently throughout your code to prevent runtime errors and improve readability. Use the nullish coalescing operator (??) for default values, optional chaining (?.) for safe property access, and simplify null checks when semantically equivalent.discourse/discourse4 discussions
- Avoid N+1 queriesPrevent N+1 query performance issues by batching database operations instead of making individual queries within loops. This is critical for application performance as each individual query adds significant overhead.discourse/discourse4 discussions
- API parameter handlingEnsure consistent and safe handling of parameters and data across API endpoints. This includes using proper serialization methods, consistent parameter passing approaches, and context-aware processing when the same input may have different meanings.discourse/discourse4 discussions
- API parameter clarityDesign API parameters with clear naming, structured formats, and intuitive interfaces that are easy for clients to use and maintain. Avoid complex string parsing, ambiguous parameter names, or structures that require clients to perform additional processing.discourse/discourse4 discussions
- Validate access controlsAlways implement comprehensive validation for access control mechanisms to prevent unauthorized access and privilege escalation. This includes validating user permissions, enforcing tenant isolation, and preventing bypass through direct API calls.langgenius/dify4 discussions
- Name by semantic purposeChoose names that reflect the semantic purpose and meaning rather than implementation details or arbitrary values. Use enum constants instead of string literals, select precise identifiers that clearly convey intent, and name functions/variables based on their actual purpose.langgenius/dify4 discussions
- Use Approved NamingUse precise, guideline-approved naming for identifiers (tags), technical terminology, and headings—so names are unambiguous, consistent, and match the actual meaning.kamranahmedse/developer-roadmap4 discussions
- Treat Untrusted Data SafelySecurity rule: Treat anything from the client (sessions, form fields, query params, template-bound values) as untrusted at runtime. Enforce safety on the server and use framework safe defaults for output encoding/sanitization. Only use “bypass”/escape hatches when you can prove the value’s origin and safety, and document that proof.kamranahmedse/developer-roadmap4 discussions
- Validate operation permissionsEnsure appropriate permission checks are implemented before performing security-sensitive operations that access files, networks, or system resources. Different operation types require different permission validations, and the timing of these checks matters for security.denoland/deno4 discussions
- Use appropriate error typesFunctions should use specific, appropriate error handling mechanisms rather than generic or brittle approaches. This includes returning proper error codes when operations fail, using specific error types instead of generic `notImplemented` errors, and avoiding fragile error detection methods like string matching.denoland/deno4 discussions
- prefer safe optional returnsWhen designing APIs and handling potentially missing or unavailable values, prefer returning optional types (Option<T>, Result<T, E>) over operations that can panic or fail unsafely. This promotes defensive programming and null safety.denoland/deno4 discussions
- explicit dependency configurationEnsure dependency configurations are explicit and predictable to avoid confusion and unexpected build behavior. Avoid package aliases that obscure the actual dependency being used, prefer published versions over git dependencies for stability, and be explicit about features that control critical behaviors like linking.denoland/deno4 discussions
- defensive null handlingUse defensive programming patterns to prevent null-related issues before they occur. This includes creating safe object copies to prevent mutations, using explicit null/undefined checks, and initializing objects safely.denoland/deno4 discussions
- Use modern API methodsWhen implementing algorithms with numerical libraries like ND4J, always prefer the most direct and type-safe API methods over older patterns. This improves code clarity, prevents subtle bugs, and often leads to better performance.deeplearning4j/deeplearning4j4 discussions
- Minimize object allocationsAvoid creating unnecessary temporary objects or arrays which can impact performance through increased garbage collection and memory pressure. Apply these techniques to optimize memory usage:deeplearning4j/deeplearning4j4 discussions
- Keep configurations currentEnsure all configuration elements (dependencies, build settings, preprocessor flags) are up-to-date, documented, and consistent with project standards. This practice prevents issues arising from outdated references and improves maintainability for team members.deeplearning4j/deeplearning4j4 discussions
- Fail fast clearlyDetect and report errors as early as possible with detailed context to prevent silent failures and aid debugging. Validate inputs, states, and implementation completeness with appropriate exceptions that include relevant information.deeplearning4j/deeplearning4j4 discussions
- Document AI APIs completelyWhen developing AI libraries and tools, provide comprehensive and accurate API documentation that helps users navigate complex functionality. Documentation should:deeplearning4j/deeplearning4j4 discussions
- Cross-platform algorithm optimizationWhen implementing algorithms that need to execute efficiently across different platforms, consider both compile-time and runtime optimizations: 1. For template-heavy code, use explicit instantiations to improve compilation speed and avoid compiler limitations on specific platforms:deeplearning4j/deeplearning4j4 discussions
- Configurable resource locationsAlways make file paths, temporary directories, and resource locations configurable with reasonable defaults instead of hard-coding them. Users may have specific environment requirements such as using SSDs instead of system drives or working with constrained environments like Spring Boot.deeplearning4j/deeplearning4j4 discussions
- Compare floating-point safelyWhen implementing numerical algorithms, never compare floating-point values directly for equality due to precision errors. Instead: 1. Use an epsilon threshold for comparisons:deeplearning4j/deeplearning4j4 discussions
- Use Adapter UpsertWhen writing to a database/graph store, make the storage adapter the source of truth for schema details and persist data idempotently. Apply these rules:eosphoros-ai/DB-GPT4 discussions
- Use precise networking terminologyWhen writing error messages or documentation related to network requests and cross-origin policies, use precise terminology that accurately describes the scope of the issue. Prefer "URL" over "domain" when the problem could involve any URL component (protocol, port, path, etc.), not just the domain name. Use proper technical terms like "origin" when...cypress-io/cypress4 discussions
- prefer existence over truthinessUse explicit existence checks instead of truthiness checks when dealing with object properties, null/undefined values, or when falsy values are valid data.cypress-io/cypress4 discussions
- meaningful test assertionsWrite tests that verify specific behavior and outcomes rather than relying on weak assertions like snapshots or generic checks. Tests should validate the actual functionality being tested, not just capture output or run without proper verification.cypress-io/cypress4 discussions
- GraphQL mutation designDesign GraphQL mutations to return meaningful objects rather than simple booleans, and use simple ID parameters instead of complex nested objects. This follows GraphQL best practices and enables proper client-side cache management.cypress-io/cypress4 discussions
- Environment variable handlingEnvironment variables should be properly validated, parsed, and documented with clear override mechanisms. Always validate that environment variable names are non-empty strings before processing. When parsing environment variable values, trim whitespace and remove surrounding quotes to handle cross-platform differences, especially on Windows where quotes...cypress-io/cypress4 discussions
- Choose appropriate log levelsSelect log levels based on the intended audience and actionability of the message. Use `debug` for internal development information that helps with troubleshooting, `warn` or `error` for user-actionable issues, and avoid logging messages that add noise without providing value to the user.cypress-io/cypress4 discussions
- Default None not emptyAlways use `None` as the default value for optional parameters and class attributes instead of empty collections (`[]`, `{}`, `""`) or other mutable defaults. This prevents sharing mutable state between instances and makes null checks more explicit.crewaiinc/crewai4 discussions
- Validate and safely clear nullable pointersIn C extension code, every pointer that can legitimately be NULL (e.g., the result of PyObject_GetAttr, PyNumber_Add, or other APIs that may fail) must be checked for NULL immediately before it is dereferenced or passed to another API call. Do not assume an "unlikely to fail" call always succeeds—an unchecked NULL result can lead to a null dereference or...python/cpython4 discussions
- Preserve protocol semanticsNetwork/HTTP code must strictly respect protocol contracts and avoid silent behavioral changes. When parsing values governed by an RFC grammar (e.g. Content-Length or chunk-size), validate against that grammar before handing them to a more permissive parser like `int()`, so unintended inputs (signs, underscores, `0x` prefixes, etc.) aren't accepted as...python/cpython4 discussions
- C API design and compatibilityWhen adding or extending a public C API (including the limited/stable ABI), design signatures and semantics to match established conventions used elsewhere in the ecosystem, and keep documentation perfectly in sync with the actual implementation (e.g., don't document a `size` parameter that doesn't exist yet in the function signature). For functions that...python/cpython4 discussions
- Benchmark hot-path regressionsWhen adding bookkeeping for correctness or edge cases (deduplication, debug stats, extra tracking structures), make sure the common/fast path doesn't pay for work it doesn't need. Defer allocations, extra passes, or per-call checks until they're actually required, and fall back to a cheap path when the condition that triggers the extra cost is absent or...python/cpython4 discussions
- Pause tracking during side-effectsWhen executing side-effects in reactive systems (like event handlers, cleanup functions, or async operations), always pause reactivity tracking to prevent unintended dependencies from being captured. This prevents infinite loops, race conditions, and unexpected behavior that can occur when reactive state is accessed during side-effects.vuejs/core4 discussions
- Optimize common search pathsImplement dedicated fast paths for common search patterns while maintaining a complete fallback path for edge cases. This optimization pattern significantly improves performance for frequent operations while ensuring correctness for all scenarios.vuejs/core4 discussions
- log complete error objectsAlways log complete error objects rather than just error messages to preserve stack traces, error codes, and debugging context. Use the application's logger instead of hardcoded console statements in modules.adonisjs/core4 discussions
- Guarantee cleanup executionWhen implementing features that require cleanup or state restoration, always use try-finally blocks to ensure cleanup code executes even when errors occur. This pattern prevents resources from being leaked, components from becoming stuck in intermediate states, and operations from remaining incomplete after exceptions.vuejs/core4 discussions
- Consistent documentation languageMaintain consistency in wording, formatting, and specificity across all documentation strings to improve readability and translation quality. Key practices:home-assistant/core4 discussions
- Batch operations efficientlyCollect and execute similar operations together rather than performing them individually to reduce overhead and improve performance. This applies to entity creation, API calls, and state updates.home-assistant/core4 discussions
- API documentation consistencyEnsure all API-related descriptions, field names, and documentation accurately reflect the terminology and specifications used by external service providers. Descriptions should be consistent between code comments, user-facing strings, and external documentation.home-assistant/core4 discussions
- Working configuration examplesConfiguration examples should be complete, accurate, and ready to use without modification. This applies to both code snippets and configuration file examples.continuedev/continue4 discussions
- Safe property accessAlways use proper null safety patterns when accessing properties that might be null or undefined. This prevents runtime errors and improves code robustness.continuedev/continue4 discussions
- Prevent broken interactionsEnsure UI elements' visual state (e.g., disabled, active) always matches their actual behavior. When an element appears disabled, completely prevent the associated actions by:continuedev/continue4 discussions
- Prevent async deadlocksAvoid circular dependencies in asynchronous code paths that can lead to deadlocks or indefinite blocking. When using async/await, ensure that promise chains have clear resolution paths and aren't dependent on their own completion. Be particularly careful with initialization patterns and refresh mechanisms.continuedev/continue4 discussions
- Maintain API compatibilityWhen modifying existing APIs, ensure backward compatibility to prevent runtime failures and minimize migration effort for consumers. Breaking changes in function signatures, return types, or parameter requirements can cause cascading issues throughout a codebase.continuedev/continue4 discussions
- DNS and Timeout RulesWhen implementing networking features (DNS, proxies, RPC/XPC), make behavior consistent with the correct layer and avoid imposing policy that breaks end-to-end semantics.apple/container4 discussions
- Write deterministic test assertionsTests should be deterministic and explicit in their assertions to ensure reliability and maintainability. Follow these guidelines: 1. Use explicit assertions instead of ambiguous string matchingdocker/compose4 discussions
- Wrap and check errorsAlways wrap errors with meaningful context and use typed error checking instead of string matching. This helps with error tracing and maintains consistent error handling patterns.docker/compose4 discussions
- Use standard API fieldsWhen designing APIs or interfaces, prioritize using existing standard fields and patterns from established APIs rather than creating custom implementations. This ensures consistency across tools and reduces cognitive load for users.docker/compose4 discussions
- Use API options patternDesign API methods using options objects instead of multiple parameters. This pattern provides better extensibility, version compatibility, and maintains consistent interfaces across the codebase.docker/compose4 discussions
- Prevent unintended CI behaviorsEnsure CI/CD pipelines maintain predictable and reliable behavior by avoiding changes that introduce unexpected side effects or alter default behaviors. This includes preventing automatic actions like image pushing when not explicitly requested, using consistent tooling approaches across similar operations, and properly handling unreliable components.docker/compose4 discussions
- Prevent sensitive data exposureImplement comprehensive checks to prevent accidental exposure of sensitive data through multiple vectors in configuration files and deployment artifacts. This includes validating environment variables, file permissions, bind mounts, and individual configuration files before publishing or deployment.docker/compose4 discussions
- Keep code structure flatMaintain code readability by minimizing nesting depth and using appropriate control structures. Prefer flat code organization over deeply nested conditions. When dealing with multiple conditions:docker/compose4 discussions
- consistent formatting choicesMaintain consistent formatting and style choices throughout your codebase to improve readability and maintainability. This includes consistent variable syntax, proper quoting practices, and organized list formatting.docker/compose4 discussions
- Configuration documentation clarityEnsure configuration documentation clearly and accurately describes environment variables, command-line flags, and their relationships. Pay special attention to precedence rules, equivalent options, and proper grammar when explaining configuration behavior.docker/compose4 discussions
- Strict null/undefined checksUse explicit, strict equality (`===`/`!==`) when checking for `null` or `undefined` instead of loose equality (`!=`/`==`) or `typeof` comparisons, which can mask bugs or be unnecessarily verbose. Be especially careful with `typeof value === 'object'` checks: since `typeof null === 'object'`, always add an explicit `value !== null` guard before accessing...tj/commander.js4 discussions
- use logging over printReplace all `print()` statements with appropriate logging calls using Python's built-in logging module. This applies to debug output, informational messages, and error reporting. Print statements should be reserved only for direct user interaction or when logging infrastructure is not available.comfyanonymous/ComfyUI4 discussions
- optimize computational efficiencyImplement memoization and guard clauses to eliminate redundant computations and improve algorithmic performance. Many algorithms can be significantly optimized by caching intermediate results and avoiding unnecessary work.comfyanonymous/ComfyUI4 discussions
- explicit null handling strategiesFunctions and APIs should employ explicit strategies for handling null/None values rather than leaving null handling ambiguous. Choose one of two approaches:comfyanonymous/ComfyUI4 discussions
- Document complex codeAdd explanatory comments or docstrings for complex, specialized, or non-obvious code that may not be immediately clear to other developers. This includes magic constants, platform-specific operations, advanced APIs, and implementation decisions with specific reasoning.comfyanonymous/ComfyUI4 discussions
- Semantic naming patternsUse names that clearly convey purpose and maintain consistency across related components. Avoid generic identifiers (like `dir`) in favor of descriptive ones (like `codex_home`), and ensure placeholder names in string templates are self-explanatory (prefer `SUMMARY_TEXT` over `{}`). For related functions or elements, establish consistent naming patterns...openai/codex4 discussions
- Fail-Closed Release SecurityAny security-sensitive release/publish workflow must be deterministic, run only on trusted code, validate against authoritative data, and fail closed.openai/codex-security4 discussions
- Prefer specific identifiersAlways use specific, descriptive names for identifiers rather than generic terms. Names should clearly indicate their purpose and context, making code more readable and self-documenting. This applies to variables, parameters, types, and files.openai/codex4 discussions
- Organize code top downStructure code files with a clear top-down organization, placing primary functions and important declarations at the top, followed by helper functions and implementation details below. This improves code readability and maintainability by establishing a clear hierarchy.openai/codex4 discussions
- Minimize blocking operationsWhen writing concurrent code, minimize blocking operations to maintain responsiveness and prevent performance bottlenecks. This applies especially to async contexts and lock usage.openai/codex4 discussions
- Leverage style toolsMaintain consistent code style by using and respecting the project's established formatting tools and patterns. Run linters and formatters (`pnpm run format`, `pnpm run lint`) before committing code. Organize logical expressions for clarity and consistency, and prefer language constructs that work well with static analysis tools.openai/codex4 discussions
- Avoid hard-coded configurationMake scripts and applications flexible by avoiding hard-coded configuration values. Instead, allow users to provide configuration through command-line flags, environment variables, or configuration files. When updating scripts to use configurable parameters:openai/codex4 discussions
- Truthful, Platform DocsKeep technical documentation strictly aligned with what the product/CLI actually does, and ensure examples work for the reader’s platform. Apply: - If a documented option/flag “has no effect,” do not keep it as “accepted but ignored.” Either (a) fix the product so it works, or (b) delete the documentation line/row until it works.CLINE/cline4 discussions
- Trusted Enforcement OverreachTreat hooks/allowlists as *defense-in-depth*, not a primary security boundary. Enforce security decisions in a trusted, immutable context, validate inputs strictly, and never depend on code coming from an untrusted repository.CLINE/cline4 discussions
- Strategic telemetry implementationImplement telemetry collection strategically to ensure system reliability and meaningful data capture. Place telemetry calls where relevant context is available, use non-blocking patterns for time-sensitive operations, and avoid unnecessary abstraction.cline/cline4 discussions
- State-Preserving React UIWhen UI depends on async readiness/reconnects, design components so state is preserved across transitions while still preventing focus/pointer-event traps and avoiding unintended re-initialization.Cline/Cline4 discussions
- State Invariants for EventsWhen behavior depends on indirect event signals (timing, scroll events, key events, async streaming), implement it as an explicit state machine with clear invariants—and always separate *what caused the change* from *the side effect you observe*.cline/CLINE4 discussions
- Stable Mount VisibilityWhen an app is gated by async readiness (hub connected/ready, auth, data bootstrap), prefer keeping the main app mounted and switching visibility to preserve user state—BUT gate side-effects so hide/show doesn’t re-run one-time initialization. Also, when failure occurs, replace (don’t cover) the app UI if any mounted dialogs/popovers could keep focus traps...cline/CLINE4 discussions
- Safe object lookupsWhen you build “string key → meaning” maps from paths, extensions, plugin data, or other user-influenced strings, never rely on inherited object members. Use own-property checks (e.g., `Object.hasOwn`) and ensure the same normalization is applied wherever the key is produced and later consumed. For security-related toggles, the UI text must precisely...Cline/Cline4 discussions
- Revert optimistic state safelyWhen an async operation can fail after the UI has already applied an optimistic update, always attach a rejection handler and reconcile the UI back to the authoritative source of truth rather than letting the error propagate unhandled or leaving the UI in an inconsistent state. Reverting to a value captured before the call can be wrong if a second operation...cline/cline4 discussions
- Resilient error-state handlingWhen an interaction or startup path can fail (or an expected event never arrives), make error handling deterministic and user-safe: clean up reliably, reuse the same validation+error messaging, recover on the right signal, and replace (not just cover) UI that could trap focus.Cline/Cline4 discussions
- Recovery-Safe UI StateWhen an async dependency (cloud restore, sidecar/Hub transport, source-control action) can fail or be retried, design UI and side effects so the app remains in a safe, recoverable state:CLINE/cline4 discussions
- Proxy And Timeout DisciplineWhen you customize networking (HTTP agents, proxy dispatchers, sandboxes, or long-running requests), follow these rules: 1) Preserve loopback/direct routing semanticsClInE/cLiNe4 discussions
- Normalize Model TokensWhen integrating LLM providers, treat model limit metadata and token/usage accounting as *schema-variant inputs* that must be normalized into a single internal representation:ClInE/cLiNe4 discussions
- Guard Async Cache WritesWhen caching async data, ensure late/out-of-order responses can’t overwrite newer state. **Do this** - **Use per-key sequencing**: attach a monotonically increasing “generation” (or token) to each cache key when you start a read; bump/invalidate the generation whenever you drop that key’s cache (refresh, close tab, edit). When a response arrives, apply it...CLINE/cline4 discussions
- Graceful Failure RecoveryWhen handling async actions, transport startup, or event-driven UI, treat failures and edge-case delivery as first-class: recover explicitly, preserve user input on failure, and always clean up global/UI state.ClInE/cLiNe4 discussions
- Explicit API ContractsWhen designing or evolving API surfaces (function interfaces, host/tool lists, REST/WebSocket payloads, and request headers), make the contract unambiguous and single-sourced.CLINE/CLINE4 discussions
- Env-Aware Configuration RulesWhen an implementation depends on environment-specific configuration (e.g., app base URL) or capability flags, apply configuration consistently and gate user actions with real state.Cline/Cline4 discussions
- Env-aware actions and linksFor configuration-dependent behavior (feature flags, environment base URLs, self-hosted/proxy setups), ensure UI availability and navigation are determined consistently from config/state *before* the user triggers the action, and that environment-specific URLs are generated via a single, centralized mechanism.cline/CLINE4 discussions
- Complexity-Aware Estimation ParsingWhen implementing “estimation” or “parsing/transform” logic, design for both correctness and worst-case performance: (1) don’t let the algorithm scale with irrelevant large payload sizes when the true cost depends on a different factor, and (2) avoid pathological worst-case parsing constructs (notably regexes that can backtrack badly). Enforce these with...CLINE/cline4 discussions
- Centralize environment configEnvironment-dependent configuration (base URLs, feature endpoints, privacy/dashboard links, etc.) must be resolved from a single authoritative source and reused everywhere, instead of being hardcoded or re-derived in multiple places. cline/cline4 discussions
- Centralize env linksWhen behavior depends on environment/config (feature availability, app base URLs, privacy/account links), ensure it’s derived in one place and applied consistently.CLINE/CLINE4 discussions
- Best-effort cap and reuseWhen code performs expensive IO (git/network/subprocess/clipboard capture), it must (1) avoid redundant work, (2) avoid over-scoped enumeration before it’s necessary, and (3) degrade gracefully when caps are hit.CLINE/cline4 discussions
- Avoid generic suffixesAvoid using generic suffixes like "Response", "Result", or "Request" in type names, especially for non-request types. Instead, use semantic names that describe the actual data structure and can be reused throughout the codebase.cline/cline4 discussions
- Avoid Expensive DuplicatesWhen adding telemetry, previews, or fallback paths, ensure you don’t (a) repeat expensive work, (b) fetch/scan unbounded amounts of data, or (c) hard-fail when size/time limits are exceeded.ClInE/cLiNe4 discussions
- Avoid costly redundant workIn performance-sensitive code paths, ensure you (1) don’t duplicate expensive async computations, (2) don’t do high-fanout git/network work before it’s necessary, and (3) when you must cap time/buffer/size, return partial results instead of failing or dropping all work.cline/CLINE4 discussions
- API contract consistencyWhen designing or evolving API surfaces (HTTP headers, RPC calls, and event envelopes), treat them as *round-trip contracts*: don’t silently change the meaning of identifiers/fields, and don’t let newly introduced fields disappear across layers.CLINE/cline4 discussions
- Setting declaration practicesAlways declare settings before using them and optimize access patterns for performance. Settings must be properly declared in the appropriate scope before being referenced in code. When accessing settings multiple times, cache the value in a local variable to avoid repeated lookups. For configuration parsing, avoid modifying AST nodes directly and use local...ClickHouse/ClickHouse4 discussions
- Documentation precision standardsEnsure API documentation uses precise type specifications, proper formatting, and clear language to improve developer understanding and usability. Key requirements:ClickHouse/ClickHouse4 discussions
- Write actionable documentationDocumentation should be written in active voice with concrete examples and clear context. Avoid passive constructions and vague references that leave readers guessing about implementation details or expectations.snyk/cli4 discussions
- Use centralized configuration accessAlways access configuration values through the configuration object rather than direct helper functions or environment variables. This ensures consistent behavior across the application and provides proper abstraction from the underlying value sources.snyk/cli4 discussions
- Optimize variable declarationsDeclare variables close to their usage point and choose appropriate types to improve code readability and reduce cognitive load. Avoid declaring variables at the top of functions when they're only used once later in the code. Remove unused variables and imports to keep the codebase clean.snyk/cli4 discussions
- debug logging reliabilityEnsure debug logging behaves correctly by only activating when debug flags are explicitly enabled, while providing comprehensive coverage of all relevant cases when active. Debug logs should not cause application failures and should be printed for all error conditions, not just specific subsets.snyk/cli4 discussions
- avoid hardcoded configuration valuesReplace hardcoded URLs, ports, file paths, and environment-specific strings with configurable parameters. Hardcoded values make code difficult to test, deploy across different environments, and maintain over time.snyk/cli4 discussions
- Use strict test doublesAlways use strict test doubles (instance_double, class_double) instead of basic doubles or OpenStruct in tests. Strict doubles provide compile-time checks that prevent tests from passing when the mocked interface changes, improving test maintainability and catching integration issues early.chef/chef4 discussions
- Standardize installation directory pathsMaintain consistent and separate installation paths for different build types to prevent conflicts and improve system organization. Use `/hab` directory for Habitat builds and `/opt/chef` for Omnibus installations.chef/chef4 discussions
- Secure network operationsWhen performing network operations, prioritize security and configurability to ensure robustness across different environments. This includes: 1. **Use explicit command patterns**: When executing shell commands that involve network operations, avoid string interpolation and use argument arrays instead to prevent command injection vulnerabilities.chef/chef4 discussions
- Document configuration decisionsAdd clear comments explaining the rationale behind configuration decisions, especially for workarounds, compatibility fixes, or environment-specific settings. This helps future maintainers understand why certain configurations exist and prevents accidental removal of necessary settings during refactoring.chef/chef4 discussions
- Document configuration completelyAlways provide complete documentation for configuration options, including defaults, override methods, and security implications. When documenting configuration:chef/chef4 discussions
- Use pytest best practicesAdopt modern pytest features to create maintainable, isolated, and comprehensive tests. This includes: 1. **Prefer pytest over unittest** for new test development to leverage pytest's rich feature set and simpler syntax.bridgecrewio/checkov4 discussions
- Preserve API compatibilityWhen modifying existing APIs, function signatures, or return structures, always maintain backward compatibility to prevent breaking dependent code. This applies to both internal interfaces between components and external API integrations.bridgecrewio/checkov4 discussions
- Precise configuration validationEnsure configuration validation logic accurately reflects security intentions and best practices. When writing validation checks: 1. Use precise operators that directly verify the intended state:bridgecrewio/checkov4 discussions
- Validate boundaries and nestingWhen writing parsing, looping, or stateful algorithms, explicitly verify behavior at boundary conditions and across the full valid input range rather than relying on a few manual test cases. For spec-driven logic (e.g. regex matching unicode escapes), check against the actual specification limits (such as max code point 0x10FFFF, or 6-digit brace syntax)...chalk/chalk4 discussions
- TypeScript declaration conventionsWhen writing or updating `.d.ts` files, follow idiomatic TypeScript conventions to keep type declarations concise and consistent: - Avoid duplicating type definitions or their documentation. If a type already exists (locally or in an external package), re-export it instead of redefining it.chalk/chalk4 discussions
- Type definitions mirror runtimePublic type definitions (TypeScript, JSDoc, etc.) must precisely reflect the actual runtime contract of the API — no more permissive, no more restrictive, and no exposing capabilities that don't actually exist.chalk/chalk4 discussions
- Cover edge cases thoroughlyWhen writing or reviewing tests for new behavior, don't stop at the happy path—actively think about edge cases, variations, and subtle state-sharing bugs that a naive fix could miss. Specifically: test both default/shared instances and custom instances (e.g. both `chalk` and `new chalk.Instance(...)`); add explicit tests for escaping/special-character...chalk/chalk4 discussions
- Test Canvas Edge CasesWhen changing Celery task dispatch semantics (especially Canvas: chains/groups/chords, unroll/freeze, and composed workflows), add regression tests that:celery/celery4 discussions
- Stable CI Workflow PolicyWhen modifying CI workflows, keep pipelines deterministic, resource-efficient, and transparent: - **Gate expensive jobs:** Run integration (and other heavyweight suites) only after unit tests succeed to save resources. Use job dependencies (e.g., `needs: unit-tests`).celery/celery4 discussions
- Semantic ordering guardsWhen code depends on ordering/selection (scheduling, routing, matching), implement it using *semantic* state and *explicit* guard windows—avoid brittle string checks and avoid guards that assume “typical” transition times.celery/celery4 discussions
- Cache Only After InputsWhen adding or using caching (e.g., @cached_property, sys.modules-dependent behavior, or internal resolution caches), ensure the cached value depends only on inputs that are already stable.celery/celery4 discussions
- Accurate, Auto ConfigUser-facing configuration should be correct, self-contained, and hard to misuse. Apply these rules: 1) **Document the exact scope of each setting/env var**: the description must match the code paths that actually enforce the behavior (what calls it affects, and what it does *not* affect).celery/celery4 discussions
- Provide error feedbackAlways provide clear user feedback when errors occur or operations fail, rather than allowing silent failures or showing disabled UI without explanation. This includes detecting existing error states, preventing validation errors through input sanitization, and displaying appropriate messages for failed operations.calcom/cal.com4 discussions
- Prefer early returnsUse early returns and guard clauses instead of nested if-else statements to improve code readability and reduce complexity. Apply the fail-fast principle by handling edge cases and invalid conditions first, then proceeding with the main logic.calcom/cal.com4 discussions
- optimize iteration patternsMinimize computational complexity by optimizing iteration patterns and data processing flows. Apply early filtering when possible, but preserve data integrity when order or indexing matters.calcom/cal.com4 discussions
- Configuration access patternsEnsure configuration data is accessed through proper service layers with dependency injection rather than direct database calls in presentation components. Configuration settings should be retrieved via dedicated repository classes or service methods, not through direct Prisma interactions in getServerSideProps or component logic.calcom/cal.com4 discussions
- Avoid redundant operationsIdentify and eliminate duplicate or inefficient operations that waste computational resources. Common patterns to watch for include: 1. **Duplicate function calls**: Multiple calls to expensive operations like database queries or API endpoints within the same request flowcalcom/cal.com4 discussions
- Avoid generic namingChoose specific, descriptive names over generic ones for all identifiers including variables, functions, components, and test IDs. Generic names lack context and can cause confusion as the codebase grows. Names should clearly communicate their purpose and scope.calcom/cal.com4 discussions
- Use consistent test patternsStandardize testing by leveraging established patterns and helper functions throughout your test suite. Extract repetitive test setup into lifecycle hooks like `beforeEach` or shared fixtures. Use existing test helpers rather than duplicating logic, and organize tests logically by functionality.oven-sh/bun4 discussions
- Consistent descriptive identifiersUse camelCase for all variables, parameters, methods, and functions in JavaScript/TypeScript code to maintain consistency with language conventions. Choose names that accurately describe the purpose and behavior of identifiers, and avoid naming collisions between different scopes.oven-sh/bun4 discussions
- Clear accurate documentationDocumentation should be both technically accurate and contextually helpful for developers. Comments and JSDoc entries must correctly describe the behavior, purpose, and relationships of code elements.oven-sh/bun4 discussions
- Always await promisesConsistently use the `await` keyword when working with Promise-returning functions to ensure proper execution flow and prevent race conditions. Missing awaits can lead to unexpected behavior where code continues execution without waiting for asynchronous operations to complete.oven-sh/bun4 discussions
- validate LLM reliabilityAlways validate LLM capabilities before deployment and implement robust handling for unreliable responses. LLMs can vary significantly in capability and may return empty, invalid, or hallucinated responses that can break your application.browser-use/browser-use4 discussions
- Simplify complex implementationsReplace verbose, complex code structures with simpler, more readable alternatives. Prefer existing methods over inline complex logic, use built-in functions instead of manual implementations, and leverage modern Python features for cleaner code.browser-use/browser-use4 discussions
- optimize CI performanceStructure CI workflows to minimize execution time and resource usage through strategic job organization, caching, and elimination of redundant operations.browser-use/browser-use4 discussions
- avoid external test dependenciesTests should not rely on external URLs, live websites, or internet connectivity to ensure reliability, consistency, and faster execution. External dependencies can cause tests to fail due to network issues, website changes, or unavailability, making CI/CD pipelines unstable.browser-use/browser-use4 discussions
- Structured environment configurationUse structured environment variable handling with explicit validation instead of directly accessing ENV hash. Implement proper parsing for boolean values, default values, and type conversion. Consider making paths user-specific when creating temporary configurations.Homebrew/brew4 discussions
- Correct GitHub Actions annotationsWhen using GitHub Actions workflow commands for annotations, always include double colons in the syntax (::command::). Proper formatting ensures warnings and errors are correctly displayed in the GitHub Actions UI and processed by workflow runners.Homebrew/brew4 discussions
- Avoid variable name abbreviationsUse complete, descriptive variable names instead of abbreviations to enhance code readability and maintainability. Short abbreviations like `dir`, `repo`, and single-letter variables often obscure the purpose of the variable and make code harder to understand for new contributors.Homebrew/brew4 discussions
- Structure for readabilityPrioritize code readability by structuring code in a way that makes it easy to understand at a glance. This includes: 1. Break complex conditions into clearer if-else blocks for better comprehension:boto/boto34 discussions
- Isolate concurrent resourcesCreate separate instances of non-thread-safe resources for each thread or process in concurrent applications rather than sharing a single instance. Many objects that maintain state or shared metadata (like sessions, connections, or context-dependent resources) are not thread-safe and can cause race conditions or unpredictable behavior when accessed...boto/boto34 discussions
- Consistent region configurationAlways maintain consistency in region configurations throughout your application. Instead of hardcoding endpoints, use proper region configuration which allows for better maintainability and fewer errors. When working with region-dependent services like S3, ensure your client configuration region matches the service requirements.boto/boto34 discussions
- Defensive Null HandlingWhen values are optional (undefined/null), external data can be malformed, or runtime internals may not exist, code should *guard first* and choose safe, backward-compatible defaults instead of relying on truthiness.bmad-code-org/bmad-method4 discussions
- Containment and Install PolicyFor security-sensitive filesystem and dependency-install flows, treat any path/ref derived from CLI input or manifests as untrusted: (1) parse/validate it, and (2) strictly contain it to the intended root before any filesystem mutation (copy/swap/delete). Also, keep security posture consistent across equivalent install mechanisms.bmad-code-org/bmad-method4 discussions
- Behavior-Focused Test HygieneWrite tests that are (1) behavior-focused rather than implementation-coupled, and (2) use safe, consistently cleaned fixtures. Do - Assert externally observable outcomes/invariants, not “incidental” implementation details. If changing internals wouldn’t break the contract, don’t make the test fail on that internal change.bmad-code-org/bmad-method4 discussions
- Secure configs across environmentsWhen making security-related changes, ensure the configuration is (1) least-privilege/scoped, (2) actually enforced by the platform, and (3) consistent across code/docs.maximhq/bifrost4 discussions
- Secret-Aware Schema ContractsWhen updating configuration schemas (and related env/test fixtures), treat the schema as a contract with runtime unmarshalling and deployment timing. maximhq/bifrost4 discussions
- Null and Omission SafetyWhen a config field is optional/nullable (or has multiple shapes), never rely on “default” or presence quirks. Make absence vs presence explicit, align schema rules with runtime parsing/normalization, and validate the structural inputs that runtime can actually interpret.maximhq/bifrost4 discussions
- Expose essential configurationsCarefully evaluate which configuration options should be exposed to users versus kept internal. Not all configuration parameters need to be user-controllable - expose only those that provide meaningful customization while keeping implementation details private.better-auth/better-auth4 discussions
- derive from session contextAlways derive sensitive identifiers and permissions from the authenticated session context rather than accepting them as user input. This prevents privilege escalation attacks where users could manipulate request parameters to access unauthorized resources or perform actions on behalf of other users.better-auth/better-auth4 discussions
- validate feature configurationsAlways validate that required features are enabled before using feature-dependent functionality. Feature flags should be the primary condition for enabling code paths, not the presence of related data or parameters.bazelbuild/bazel4 discussions
- preserve exception causesWhen catching an exception and re-throwing a different exception type, always preserve the original exception as the cause. This maintains the full stack trace and context, making debugging significantly easier.bazelbuild/bazel4 discussions
- Ensure documentation completenessAll code elements should have sufficient documentation to understand their purpose, usage, and context. This includes adding explanatory comments for non-obvious constants, documenting private functions for maintainability, ensuring grammatical accuracy in all documentation, and providing necessary context such as prerequisites or limitations.bazelbuild/bazel4 discussions
- build action separationKeep build actions focused on their core responsibility and move complex logic to appropriate abstraction layers like builders or configuration components. Build actions should contain minimal action-specific branching and avoid tight coupling to implementation details.bazelbuild/bazel4 discussions
- Solution package versioningWhen releasing Sentinel solutions, treat version fields (e.g., `_solutionVersion`) and packaging outputs as contracts with CI/CD validators and external certification/release systems.Azure/Azure-Sentinel4 discussions
- Cross-service Permission HardeningWhen granting permissions across AWS services (S3→SQS, EventBridge→Lambda, etc.), use the correct permission model and apply least-privilege constraints to prevent confused-deputy and silent authorization failures.Azure/Azure-Sentinel4 discussions
- Backcompatible Migration ContractWhen making schema/connector changes that can affect existing customer deployments (e.g., new CCF/CL tables, changed table generation behavior), you must preserve backward compatibility as an explicit migration contract: (1) keep stable customer-facing identifiers, (2) provide a compatibility access layer for both old and new schemas, and (3) validate the...Azure/Azure-Sentinel4 discussions
- Write deterministic testsTests should be deterministic, reliable, and isolated from external dependencies to ensure consistent results across environments. To achieve this: 1. **Avoid direct network calls** that can introduce flakiness and slow down tests. Instead:Azure/azure-sdk-for-net4 discussions
- User-friendly configuration valuesPrefer intuitive, user-friendly values for configuration options over technical "magic strings" or codes that require special knowledge. This applies to both environment variables and programmatic configuration options.Azure/azure-sdk-for-net4 discussions
- Standardize environment variablesEnsure environment variable names are consistently spelled, properly referenced, and follow established naming conventions across test files. Replace hardcoded values with environment variables for credentials, endpoints, and other configurable test parameters. Always provide meaningful defaults when environment variables aren't available to ensure tests...Azure/azure-sdk-for-net4 discussions
- Externalize configuration valuesStore configuration values (URLs, demands, pool names) in centralized variables rather than hardcoding them inline. This improves maintainability, ensures consistency across the codebase, and simplifies future updates. When possible, group related configurations in dedicated template files or variable groups.Azure/azure-sdk-for-net4 discussions
- Validated API parametersTreat template parameters and embedded ARM calls as a client-facing API contract. Validate inputs and constrain the “request schema” so invalid values can’t be sent, and keep compatibility/UX aligned with how the template is consumed.Azure/azure-quickstart-templates4 discussions
- Single Source Network DefinitionsWhen authoring ARM/Bicep templates, model networking topology as a single source of truth and avoid redundant resources/dependencies. Apply these rules:Azure/azure-quickstart-templates4 discussions
- Consistent ARM Json FormattingFor ARM templates, enforce deterministic JSON formatting and standardized property ordering to keep diffs small and templates readable. **Rules** 1. **Keep property order consistent**: follow the Azure “sort order of properties” guidance (move keys to the expected order).Azure/azure-quickstart-templates4 discussions
- Avoid empty placeholdersWhen a parameter/property is optional in an ARM template, don’t represent “missing” with empty objects or empty strings—these can be treated as real values and fail validation or downstream logic.Azure/azure-quickstart-templates4 discussions
- Normalize Before CompareWhen implementing validation, duplicate detection, or search over structured inputs, first canonicalize (normalize) the representations and make comparisons match the domain semantics (case-insensitive, order-insensitive, whitespace-tolerant, etc.). Never compare raw strings/fields directly when the same meaning can be represented in multiple equivalent...Azure/azure-cli4 discussions
- Configuration Contract EnforcementWhen behavior depends on configuration (files/flags/subscriptions), do three things: (1) derive values from the active runtime context (including any overrides), (2) gate feature behavior on validated completeness of required config inputs, and (3) eliminate hidden defaults/implicit selections.Azure/azure-cli4 discussions
- Cap retries, cache callsFor performance-critical code paths, prevent wasted work and unbounded waits: (1) fetch/cache expensive data once (e.g., registry lookups/credentials, repeated GETs) and pass it into helpers; (2) bound polling/retry time with explicit per-attempt and total worst-case limits; (3) add timeouts for slow infrastructure operations.Azure/azure-cli4 discussions
- Use Option combinatorsInstead of verbose conditional logic, prefer Rust's Option combinators like map, and_then, and filter for handling potentially null values. This creates more concise, readable code that expresses intent clearly and reduces the chance of null-related bugs.tokio-rs/axum4 discussions
- Structure errors for safetyCreate specific error types with appropriate status codes while ensuring sensitive details are logged but not exposed to clients. Follow guidelines for defining specific error types, implementing proper status codes, logging detailed errors internally, and returning sanitized error messages to clients.tokio-rs/axum4 discussions
- Minimize memory allocation overheadOptimize performance by minimizing unnecessary memory allocations and using allocation-efficient APIs. Key practices include using static data when possible instead of dynamic allocations, leveraging specialized types and methods that minimize copies, and considering allocation patterns in data transformations.tokio-rs/axum4 discussions
- Lock carefully in asyncWhen using locks in async code, follow critical guidelines to avoid deadlocks. Never hold std::sync::Mutex locks across .await points as this can cause deadlocks even in single-threaded runtimes. Use tokio::sync::Mutex when the lock needs to be held across await points.tokio-rs/axum4 discussions
- Handle protocol headers properlyWhen implementing network services, especially proxies and protocol handlers, proper HTTP header management is critical for correct functionality, compatibility, and diagnostics.tokio-rs/axum4 discussions
- Nil-safe assignmentWhen fields/items are optional, treat `nil`/empty as a first-class state: guard against nil dereferences, sanitize outputs, and never overwrite meaningful non-nil data with `nil`.looplj/axonhub4 discussions
- Validate security-critical inputsAlways validate and sanitize user-supplied inputs before using them in security-sensitive operations. This helps prevent multiple types of vulnerabilities including Server-Side Request Forgery (SSRF), prototype pollution, and command injection.axios/axios4 discussions
- Robust Axios Usage in TypeScriptThis review focuses on ensuring robust and type-safe usage of the Axios library in TypeScript codebases. Key recommendations include leveraging Axios' built-in type-checking utilities, properly handling Content-Type headers when sending data, and standardizing serialization patterns for complex data types.axios/axios4 discussions
- Proper Error Handling in Axios TypeScript CodeAs a code reviewer, it is important to ensure that Axios-based TypeScript code properly handles and propagates errors. Key recommendations include using console.error() instead of console.log() when logging errors, preserving the full error object rather than just the error message, and following established Axios error handling patterns.axios/axios4 discussions
- Extract for better readabilityComplex expressions and repeated code should be extracted into well-named variables to improve readability and maintainability. This applies to repeated string/value combinations, complex conditional logic, array transformations, and URL or path constructions.axios/axios4 discussions
- Maintain consistent formattingEnhance code readability and maintainability by applying consistent formatting practices throughout your codebase: 1. Properly indent continuation lines (lines that are part of the same statement as the preceding line)aws/aws-sdk-js4 discussions
- Validate untrusted inputsAlways validate and sanitize user-provided inputs to prevent injection attacks, particularly path traversal vulnerabilities. User inputs should be treated as untrusted and validated against expected patterns before use in file operations, URL construction, or system commands.argoproj/argo-cd4 discussions
- Simplify code readabilityPrioritize code readability by using clearer control structures, extracting complex expressions into descriptive variables, and choosing simpler syntax when available. This improves maintainability and makes code easier to understand for other developers.argoproj/argo-cd4 discussions
- optimize algorithmic complexityAlways consider computational complexity and performance when implementing algorithms. Look for opportunities to optimize through early exits, efficient comparison strategies, and avoiding nested loops that create O(N*M) complexity.argoproj/argo-cd4 discussions
- explicit security controlsSecurity configurations should use explicit controls and secure defaults rather than implicit permissions or hardcoded credentials. This principle helps prevent accidental privilege escalation and credential exposure.argoproj/argo-cd4 discussions
- document network requirementsWhen documenting network-dependent features, explicitly specify all network configuration requirements including protocol support, certificate handling, and infrastructure setup. Users often encounter connectivity issues due to undocumented network prerequisites.argoproj/argo-cd4 discussions
- design extensible APIsWhen designing APIs, prioritize extensibility and backwards compatibility over convenience. Avoid modifying existing response types or interfaces in ways that could break existing clients. Instead, create new dedicated types, methods, or optional parameters.argoproj/argo-cd4 discussions
- Ensure proper async contextAlways wrap asynchronous operations (await, suspend functions, try-await) in the appropriate language-specific async context. Top-level await is generally not supported and will cause runtime errors.appwrite/appwrite4 discussions
- Cypress test isolationEnsure end-to-end tests are properly isolated and follow best practices for reliability. Tests should avoid side effects that can impact other tests and eliminate practices that cause flaky results.appwrite/appwrite4 discussions
- Wire-Format Contract TestsWhen implementing or modifying any API-facing behavior (endpoint URL construction, request/response mappings, routing encodings, capability expansion), treat the final wire format as the contract. Prevent silent mismatches by combining schema validation, explicit documentation of any byte-exact normalization rules, and end-to-end tests that assert the exact...apache/apisix4 discussions
- Semantics-Correct AlgorithmsWhen implementing or choosing an algorithm (scoring, aggregation, throttling, parsing), ensure it matches the domain semantics and behaves predictably under edge cases.apache/apisix4 discussions
- Config Contract AccuracyEnsure configuration documentation and validation rules match the real runtime contract: types/structures, default values, actual scope, and when validation happens.apache/apisix4 discussions
- Deterministic API ContractsWhen designing API client/runner behavior, ensure the contract is explicit, state-driven, and aligned with what the server actually supports. Apply these rules:anthropics/anthropic-sdk-python4 discussions
- Async Concurrency PracticesWhen working in async-capable code, ensure correctness and concurrency safety: 1) Keep async code truly async (no accidental sync calls) - If a branch is meant for async transformation, it must call/await async functions (e.g., use `await _async_transform_recursive(...)`, not the synchronous equivalent).anthropics/anthropic-sdk-python4 discussions
- Use semantic namingChoose semantic, non-redundant names that clearly express intent and context. Remove unnecessary prefixes when the context is already clear, use semantic design tokens instead of hardcoded values, and prefer precise type definitions over generic ones.ant-design/ant-design4 discussions
- Update deprecated demo APIsDocumentation, demos, and example code should always use current, non-deprecated APIs instead of showing deprecation warnings. When APIs are deprecated, update all demo code and examples to use the recommended replacement APIs immediately.ant-design/ant-design4 discussions
- Test organization standardsWrite tests that are well-organized, maintainable, and reflect real usage patterns. Test names should describe behavior and requirements rather than implementation details. Group related tests under appropriate describe blocks and avoid redundant test cases.ant-design/ant-design4 discussions
- Handle optional values safelyAlways provide safe defaults or fallbacks when working with optional or potentially undefined values. Avoid using non-null assertion operators (`!`) on optional parameters, and ensure proper handling in type checking and value merging scenarios.ant-design/ant-design4 discussions
- Deprecated API documentationWhen documenting deprecated APIs, follow consistent practices to provide clear guidance to developers while maintaining usability. Use strikethrough formatting (~~propertyName~~) to visually indicate deprecation without completely removing the documentation. Always include replacement guidance using phrases like "请使用 `xxx` 替换" or "Please use `xxx` instead"...ant-design/ant-design4 discussions
- Use specific descriptive namesChoose specific, meaningful names that clearly communicate purpose rather than generic or ambiguous alternatives. This applies to classes, methods, variables, and examples in documentation.angular/angular4 discussions
- Guard nullable value accessAlways use appropriate guards or type checks before accessing potentially null or undefined values. Prefer type-safe guard methods that provide both runtime protection and TypeScript type narrowing over manual null checks.angular/angular4 discussions
- Configuration opt-in safetyWhen introducing new configuration options or making changes that could be disruptive, make them opt-in by default rather than enabled automatically. This prevents breaking existing functionality and gives users control over when to adopt new behaviors.angular/angular4 discussions
- Choose appropriate presentation formatsSelect the most effective format for presenting different types of information in documentation. Use tables for structured data with multiple attributes, step-by-step explanations for processes, and clear section organization to avoid duplication or confusion.angular/angular4 discussions
- Choose appropriate algorithmsSelect algorithms and data structures that match the problem domain and access patterns rather than using convenient but suboptimal approaches. For complex parsing tasks, use proper AST-based parsing instead of regex. Design data structures that align with how data will be accessed and modified.angular/angular4 discussions
- Avoid reactive over-engineeringChoose the simplest React primitive that meets your requirements rather than reaching for complex reactive patterns. Avoid useEffect when useState, useMemo, or useCallback would suffice. If you find yourself using useEffect to copy data from one state to another state, it's a sign you should restructure your component's state management.angular/angular4 discussions
- async resource cleanupAlways ensure proper cleanup of asynchronous resources (subscriptions, timeouts, event listeners) to prevent memory leaks and race conditions. Use Angular's DestroyRef or similar lifecycle management patterns instead of manual cleanup.angular/angular4 discussions
- Platform-specific API documentationThe provided discussions focus on terminal emulator documentation and configuration issues, but do not contain any content related to networking (network protocols, HTTP requests, TCP/IP, DNS, websockets, data transfer, network security, or connection management). alacritty/alacritty4 discussions
- consistent error handlingMaintain uniform error handling patterns throughout the codebase. Avoid mixing different error handling approaches like panics, process::exit(), and proper Result returns within the same application flow.alacritty/alacritty4 discussions
- Safe constraint modification sequenceWhen modifying constraints in database migrations, follow a safe sequence of operations to prevent integrity errors: 1. For adding not-nullable constraints to existing tables:apache/airflow4 discussions
- Parameterize similar testsWrite parameterized tests instead of using for loops or duplicating test code for similar test cases. Using pytest's `@pytest.mark.parametrize` decorator improves test maintainability, provides clearer failure messages, and makes the test structure more readable.apache/airflow4 discussions
- Optimize collection processing patternsUse Python's built-in efficient collection processing methods instead of manual implementations. This reduces code complexity and improves performance by leveraging optimized implementations.apache/airflow4 discussions
- Leverage backend API capabilitiesWhen consuming APIs in frontend applications, utilize the backend capabilities rather than reimplementing equivalent functionality in the frontend. This reduces code complexity, improves performance, and maintains a clean separation of concerns.apache/airflow4 discussions
- Explicit version constraintsAlways specify explicit version constraints for dependencies in configuration files (like pyproject.toml), particularly when dealing with Python version compatibility. Use conditional dependencies based on Python versions to handle compatibility issues, and include explanatory comments when adding constraints.apache/airflow4 discussions
- Explicit over implicit configurationAlways prefer explicit configuration parameters over inferring behavior from indirect sources like image tags, naming conventions, or environment factors. When behavior needs to vary based on environment or version, introduce dedicated configuration parameters that users can explicitly set rather than relying on potentially unreliable metadata.apache/airflow4 discussions
- Ensure deterministic queriesBuild SQLAlchemy queries that are both efficient and deterministic to prevent unpredictable results and improve performance. When writing database queries:apache/airflow4 discussions
- Document public API boundariesClearly define and document the boundaries between public and internal APIs to guide developers on proper interface usage. Use dedicated namespaces (like the 'sdk' namespace) to distinguish public interfaces from internal implementations. Ensure all public interfaces have comprehensive documentation that accurately reflects behavior, with consistent...apache/airflow4 discussions
- Context-rich log messagesEnsure log messages provide clear context about what happened, potential consequences, and actionable information for debugging. Choose appropriate log levels based on severity, and include exception details when catching errors.apache/airflow4 discussions
- Consistent technical term translationWhen localizing an application, maintain consistent conventions for technical terms while respecting language-specific rules: 1. For acronyms, follow the target language's capitalization conventions:apache/airflow4 discussions
- Component reuse firstAlways prioritize reusing existing components before creating new ones. This practice improves codebase consistency, reduces maintenance burden, and prevents duplication. When implementing new UI elements:apache/airflow4 discussions
- Handle errors gracefullyAlways implement appropriate error handling to prevent crashes while providing clear feedback to users. Consider these principles: 1. **Decide on error propagation strategy**: Determine whether errors should be handled locally or propagated to a higher-level handler based on severity and recoverability.Aider-AI/aider4 discussions
- Externalize configuration valuesAlways externalize configuration values rather than hardcoding them directly in the code. This improves maintainability, enables easier configuration changes, and ensures consistency across the codebase.Aider-AI/aider4 discussions
- Place configurations appropriatelyConfiguration options should be organized based on their nature and scope of use. Place model-specific configurations in constructor parameters or config objects rather than in general settings objects that might be shared across models. Additionally, standardized settings should be consistent across providers and not duplicated in provider-specific options.vercel/ai4 discussions
- Explicit code organization patternsMaintain clear and explicit code organization patterns by following these guidelines: 1. Use explicit property visibility in classes: - Prefer public properties over getters/setters when no additional logic is neededvercel/ai4 discussions
- Use Canonical API ContractsWhen integrating with platform services (SDKs or cloud APIs), treat the SDK/API surface as the source of truth: prefer built-in batch and “create-or-get” methods, consolidate overlapping client interfaces, and use structured configuration objects rather than ad-hoc parsing.awslabs/agentcore-samples4 discussions
- Region Configuration StandardDo not hard-code AWS region (or other environment-specific settings) inside scripts or service logic. Instead, make region resolution consistent, configurable, and source-of-truth driven.awslabs/agentcore-samples4 discussions
- Redact Secrets in LogsWhen adding logging/debug output for authentication/authorization, apply two rules: 1) Auth configuration metadata is OK - Safe to print non-sensitive authorization configuration (e.g., allowed OAuth flows, explicit auth flows, client name) since it does not expose credentials.awslabs/agentcore-samples4 discussions
- Dependency Version PolicyIn configuration files like `requirements.txt`, define a consistent versioning policy: - Prefer **minimum version constraints** (`>=`) for most libraries to guarantee required behavior without freezing to a single patch/release.awslabs/agentcore-samples4 discussions
- Config source alignmentWhen using configuration via `.env`/config files, make the notebook’s behavior match what the docs and environment files claim—and ensure fresh environments can run the notebook reliably.awslabs/agentcore-samples4 discussions
- Prefer Imports, Not GlobalsWhen wiring state/functions, avoid implicit access through `window.*`/`globalThis`. Use explicit ES module imports so code is deterministic and loads correctly, and keep code in the module/plugin that owns it.agent0ai/agent-zero4 discussions
- Namespace plugin APIsWhen exposing data to the client, treat shared/global values and plugin routes as explicit API surface: 1) Don’t publish global client/window state by sprinkling ad-hoc dictionaries into multiple unrelated API handlers. Instead, use one centralized mechanism:agent0ai/agent-zero4 discussions
- Centralize shared fieldsWhen multiple modules need the same state/config/schema (e.g., context variables like timezone, or prompt search paths), do not replicate those fields or the logic that derives them in several places. Instead, funnel access through a single abstraction and reuse shared utilities.agent0ai/agent-zero4 discussions
- Handle async failures explicitlyWhen composing state from multiple async calls (parallel fetches, follow-up probes, or secondary enrichment requests), always check the response status explicitly rather than assuming success. A failure in a secondary or optional call must never silently corrupt or override state already established by a more authoritative call — e.g. an `installed` flag...Decolua/9Router4 discussions
- Explicit API routing and translationWhen building adapters that route requests or translate payloads between different provider/API formats (e.g. OpenAI, Claude, Responses), favor narrow, explicit declarations over broad defaults or regex-based fallbacks. A rule meant to fix one observed model/endpoint mismatch should match only that case, not a wide pattern (e.g. a version range) that could...decolua/9router4 discussions
- Reduce runtime overheadWhen optimizing performance, remove repeated work in hot paths: avoid per-call overhead, extra passes over the same data, and unnecessary allocations; validate choices with benchmarks.30-seconds/30-seconds-of-code4 discussions
- Prefer behavior-true namesUse naming that clearly communicates the real behavior/intent of the API and avoids misleading abbreviations or borrowed terms whose common meaning differs.colinhacks/zod3 discussions
- Precise Validation DocumentationWhen documenting inputs/validators, explicitly state (a) the units/meaning of any parameters (e.g., file size units), (b) what is truly validated (syntactic/format via regex vs semantic correctness), and (c) timezone/offset semantics using unambiguous wording (avoid phrasing that suggests an offset is “missing” when “Z” explicitly means zero offset). This...colinhacks/zod3 discussions
- Explicit null handlingTreat `null`/`undefined` and “absence vs presence” as first-class concerns. - **TypeScript:** Keep null safety effective by ensuring `strictNullChecks` is enabled and not overridden by extended configs (explicitly set it to `true` if needed).colinhacks/zod3 discussions
- Define Equality SemanticsEnsure algorithmic helpers that use data structures (e.g., deep equality, key intersections) have an explicit correctness contract and are implemented with runtime-compatible structures.colinhacks/zod3 discussions
- Self-explanatory identifier namesChoose identifier names that clearly convey their purpose without requiring users to understand implementation details. If reviewers struggle to understand what a name means, it likely needs improvement.zed-industries/zed3 discussions
- Respect language-specific conventionsAlways adhere to the established formatting and syntax conventions of each programming language while maintaining consistency across related language configurations. This includes:zed-industries/zed3 discussions
- Maintain style consistencyEnsure consistent styling is maintained across related elements in the codebase. This applies to: 1. **Visual assets**: Icons and images should match the established dimensions and styling of existing assets.zed-industries/zed3 discussions
- Maintain consistent namingEnsure naming follows consistent patterns throughout the codebase in both style and structure: 1. Use agreed-upon case style for identifiers (e.g., snake_case for functions):zed-industries/zed3 discussions
- Hierarchical configuration organizationOrganize configuration settings hierarchically by grouping related settings under meaningful namespaces rather than creating numerous top-level settings. This improves maintainability, discoverability, and reduces configuration sprawl as your application grows.zed-industries/zed3 discussions
- Optimize build configurationsWhen configuring CMake builds, carefully select compiler and linker flags that optimize for performance while maintaining cross-platform compatibility. Performance-oriented flags can significantly impact runtime speed, binary size, and resource utilization, but must be applied conditionally based on the target platform and compiler.facebook/yoga3 discussions
- Measure optimization trade-offsAlways measure and document the impact of performance optimizations before implementing them. When making optimization decisions, quantify the benefits (size reduction, speed improvement) against the costs (build time, code complexity, maintainability).facebook/yoga3 discussions
- Document complex logicAdd clear explanatory comments to complex calculations, platform-specific behavior, or non-obvious code sections. Use NOTE comments to explain the reasoning behind tricky implementations, especially when dealing with framework-specific quirks or mathematical calculations.facebook/yoga3 discussions
- Design familiar APIsDesign APIs that align with platform conventions and user expectations rather than creating novel patterns. APIs should feel natural to developers already familiar with the target platform's idioms and established libraries.facebook/yoga3 discussions
- consistent formatting choicesMaintain consistent formatting and structural choices throughout the codebase to improve readability and maintainability. This includes always using braces for control structures (even single-line statements), choosing appropriate control flow constructs for clarity, and organizing code to prevent execution order issues.facebook/yoga3 discussions
- Analyze performance trade-offsBefore implementing convenience features or making architectural decisions, carefully evaluate their performance implications and hidden costs. Consider factors like method call overhead, automatic behavior frequency, and resource utilization patterns.facebook/yoga3 discussions
- Algorithm specification complianceWhen implementing layout algorithms, ensure strict adherence to web standards and specifications, particularly regarding control flow and edge case handling. Complex algorithms like baseline calculation require precise implementation of specification details to avoid subtle bugs.facebook/yoga3 discussions
- Add safety checksAlways add appropriate safety checks before operations that could result in undefined behavior, null references, or memory issues. This includes using weak references to prevent retain cycles, verifying exact object types before type-specific operations, and adding conditional checks before calling methods that may return undefined values.facebook/yoga3 discussions
- Remove unnecessary configurationsConfiguration files should only include options that are supported in production and work out of the box. Remove configuration fields that are unsupported in production environments, comment out configurations that require external provisioning, and maintain consistency across templates by removing redundant or debugging-specific settings.cloudflare/workers-sdk3 discussions
- HTTP response constructionUse appropriate HTTP response construction methods and status codes for API endpoints. Prefer `Response.json()` over manual JSON stringification, return appropriate status codes (like 404 for unmatched routes), and avoid unnecessary response complexity when simple status codes suffice.cloudflare/workers-sdk3 discussions
- eliminate redundant null checksRemove unnecessary null/undefined checks when you already have sufficient validation in place, and use proper type guards instead of type assertions for better null safety.cloudflare/workers-sdk3 discussions
- Wrap throwing operationsAlways wrap potentially throwing operations in try/catch blocks to prevent unhandled exceptions from crashing the application or causing unexpected behavior. This includes property access on unknown objects, API calls, and resource initialization.cloudflare/workerd3 discussions
- Use KJ_UNWRAP_OR patternWhen handling potentially null values from functions like `tryParse()` or `tryCast()`, avoid the pattern of checking for null/none and then immediately using `KJ_ASSERT_NONNULL` or `JSG_REQUIRE_NONNULL`. This creates redundant checks that make code harder to read and understand.cloudflare/workerd3 discussions
- Simplify async patternsUse modern promise utilities and clean async patterns instead of manual promise construction. Prefer Promise.withResolvers() over manual promise creation with resolve/reject callbacks, and chain promises directly rather than wrapping them in unnecessary async functions.cloudflare/workerd3 discussions
- prefer nullish coalescing operatorsUse nullish coalescing operators (`??`) and logical OR with safe defaults (`|| {}`) to handle null and undefined values more safely and concisely. This prevents runtime errors when accessing properties on potentially null/undefined objects and provides cleaner, more readable code.cloudflare/workerd3 discussions
- document security-sensitive featuresWhen introducing compatibility flags, feature toggles, or APIs that have security implications, use self-documenting names that explicitly warn about risks and provide comprehensive documentation explaining the security concerns.cloudflare/workerd3 discussions
- defer async callbacksAlways ensure callbacks and event emissions are executed asynchronously to maintain proper timing and Node.js compatibility. Even when operations appear to complete synchronously, callbacks should be deferred using `queueMicrotask()` or `process.nextTick()` to match expected async behavior.cloudflare/workerd3 discussions
- Clear descriptive namingChoose names that clearly communicate intent without requiring mental gymnastics to understand. Avoid double negatives in variable names, maintain consistent naming patterns across the codebase, and ensure names accurately describe their purpose and context.cloudflare/workerd3 discussions
- Choose efficient algorithmsWhen implementing algorithms, prioritize efficiency in both time and space complexity. Consider these specific optimizations: 1. **Use bitwise operations** for mathematical computations when appropriate. For random number generation in ranges, bitwise operations can be more efficient than arithmetic expressions:cloudflare/workerd3 discussions
- Centralize error handlingConsolidate error handling logic into central, unavoidable locations rather than scattering it across multiple functions or requiring manual setup. This prevents cases where error handling can be bypassed or forgotten.cloudflare/workerd3 discussions
- Synchronize resource claimsWhen asynchronous operations cross process or component boundaries (backend <> frontend, websocket events, UI lifecycle), design explicit synchronization instead of relying on ad-hoc timing. Apply these rules:wavetermdev/waveterm3 discussions
- Prefer streaming operationsMotivation: avoid large, unnecessary memory allocations and excessive decoding or retention of full data sets. For parsing, logs, or history, operate on raw bytes or streams and read only the portion you need. For long-lived state, avoid keeping full large objects in memory—cap, page, or store lightweight references.wavetermdev/waveterm3 discussions
- Explicit, organized codeWrite code that is explicit, predictable, and organized to improve readability and avoid subtle bugs. What to do: - Make control flow explicit. In switch statements and other control structures always use break/return/continue as appropriate. If fallthrough is intentional, annotate it with a clear comment or a lint directive (e.g. // fallthrough). Example...wavetermdev/waveterm3 discussions
- Config accuracy and safetyConfirm that configuration artifacts (docs, config files, and ignore lists) match actual runtime behavior and preserve developer workflows. Why: Incorrect docs or overly broad ignore rules cause confusion and break common development scenarios (hot UI changes, devcontainer editor settings, in-container git commits).wavetermdev/waveterm3 discussions
- Explicit Partial-Success SemanticsWhen an API operation can be “partially successful” (or yields an empty but non-error outcome), encode that distinction explicitly in the response/protocol so callers can take correct next actions.warpdotdev/warp3 discussions
- Explicit build configurationBuild-time behavior that depends on versions, paths, or external metadata should be configured explicitly and reproducibly—never implicitly via network calls or brittle patching.warpdotdev/warp3 discussions
- Deterministic CI GatesAll CI/CD automation should be deterministic, machine-independent, and enforced via failing gates—never relying on “latest tag,” unstated baselines, or author-local tooling.warpdotdev/warp3 discussions
- Cache invalidation rulesAny cached value must have an explicit, testable “when does it become stale?” policy, plus a fallback path when updates may be missed. Apply this as a checklist:warpdotdev/warp3 discussions
- Bounded Recovery With TimeoutsImplement failure handling so recovery is (1) bounded, (2) never hangs indefinitely, and (3) has explicit validation + deterministic fallback. Apply this when adding retries, polling for readiness, or supporting boundary-specific execution paths:warpdotdev/warp3 discussions
- Parallelize independent operationsWhen writing concurrent code, always execute independent operations in parallel rather than sequentially to improve performance and responsiveness. Using parallel execution patterns can significantly reduce waiting time for I/O-bound operations.microsoft/vscode3 discussions
- Global option placementWhen an interface defines an option/parameter as *global* (i.e., it applies across subcommands or endpoints), pass it using the interface’s established parsing contract—even if it appears after a subcommand. Do not reorder flags “by intuition” if the interface specifies global semantics; instead, align with the documented/implemented behavior and then lock...microsoft/VSCode3 discussions
- Deterministic CI Cache KeysUse deterministic, content-derived cache keys and ensure every producer/consumer of that cache computes the key *identically*. Apply these rules when adding or modifying CI caching (especially GitHub Actions):microsoft/VSCode3 discussions
- Comprehensive JSDoc with examplesWrite thorough JSDoc comments for interfaces, functions, and methods that clearly explain their purpose and behavior. Include: 1. A main description explaining the component's purposemicrosoft/vscode3 discussions
- Avoid CSS !importantUsing `!important` in CSS declarations should be avoided as it makes styles difficult to override and maintain. Instead, use more specific selectors to achieve the desired styling hierarchy. This improves code maintainability and follows CSS best practices.microsoft/vscode3 discussions
- Standardize configuration formatsEnsure all plugin configurations follow a consistent, structured format across the codebase to improve maintainability and user experience. Different plugins and features should not use ad-hoc configuration styles that make the system fragmented and difficult to understand.volcano-sh/volcano3 discussions
- Secure configuration practicesImplement secure configuration practices to protect sensitive data and prevent security vulnerabilities. This includes three key areas: 1. **Credential Protection**: Never store or transmit passwords and sensitive credentials in plain text. Use encryption tools, secure credential management systems, or environment variables with proper access controls.volcano-sh/volcano3 discussions
- Justify default enablementWhen adding new configuration options, carefully consider whether features should be enabled by default. Require explicit justification for default enablement, weighing functionality benefits against compatibility risks and user impact.volcano-sh/volcano3 discussions
- Extract configuration constantsAvoid hardcoded values and magic numbers in configuration-related code by extracting them as named constants. This improves code maintainability, readability, and makes configuration values easier to modify.volcano-sh/volcano3 discussions
- Document technical details clearlyEnsure all technical documentation provides clear explanations and follows proper formatting conventions. Technical parameters, configuration options, and complex concepts should include explanatory comments or descriptions to make them accessible to users and maintainers.volcano-sh/volcano3 discussions
- Secure before deploymentRemove or secure development-specific code before deploying to production environments. Development artifacts like debug print statements, weak validation methods, and development endpoints can introduce significant security vulnerabilities.vllm-project/vllm3 discussions
- Protect shared stateWhen mutable state (like dictionaries, lists, or counters) is accessed from multiple threads or concurrent tasks, use appropriate synchronization mechanisms to prevent race conditions. Unprotected access to shared state can lead to data corruption, inconsistent behavior, and hard-to-debug issues.vllm-project/vllm3 discussions
- Structured configuration managementAvoid using global configuration singletons that rely on string-based lookups, as they lead to brittle code that's hard to maintain. Instead, implement a structured approach where configuration values are explicitly declared with their types, sources (flags, environment variables, config files), and default values. This improves compile-time safety,...vitessio/vitess3 discussions
- Robust network handlingAlways implement proper network timeout handling and address formatting to ensure robust connectivity across different network conditions and IP protocols.vitessio/vitess3 discussions
- Secure workflow permissionsDefine explicit and minimal permissions in GitHub Actions workflows to ensure proper operation while maintaining security. Workflows should only have permissions necessary for their intended tasks, and permission checks should occur early in the workflow to prevent unnecessary actions.vitejs/vite3 discussions
- Restrict server accessAlways configure server security settings with explicit allowed lists rather than permissive values. Using `true` for settings like `server.allowedHosts` or `server.cors` creates serious security vulnerabilities by allowing any website to access your development server through DNS rebinding attacks, potentially exposing source code and sensitive content.vitejs/vite3 discussions
- comprehensive validated examplesDocumentation examples should be self-sufficient, comprehensive, and use proper syntax tags to enable automated validation. Examples must include all necessary context and demonstrate multiple related features rather than isolated snippets. Use `v` syntax tags instead of generic ones like `codeblock` to ensure examples are validated by `v check-md` during...vlang/v3 discussions
- Avoid breaking API changesWhen modifying existing public APIs, always maintain backward compatibility to avoid breaking existing users. Breaking changes include altering function signatures, removing public functions, or changing function visibility from public to private.vlang/v3 discussions
- Short-circuit evaluation strategiesWhen implementing search or traversal algorithms, use short-circuit evaluation strategically to avoid unnecessary computation while ensuring correctness. Short-circuiting is beneficial when the first match is sufficient, but can lead to incorrect results when complete information is needed.astral-sh/uv3 discussions
- Optimize cache sharing strategiesSelect the appropriate cache sharing approach based on your execution environment to maximize performance and efficiency. When working with containerized applications:astral-sh/uv3 discussions
- Follow established naming conventionsAdhere to established naming conventions for files, variables, functions, and configuration options to maintain consistency and clarity throughout the codebase and documentation.astral-sh/uv3 discussions
- Enforce strong optional typesUse strong typing and early validation to handle optional values and prevent null-related issues. Prefer enums and specific types over strings when dealing with optional data, and validate optional values as early as possible in the data flow.astral-sh/uv3 discussions
- Declarative constraints over runtimeDesign APIs that enforce constraints through type systems and declarative mechanisms rather than runtime checks. This makes invalid states unrepresentable by design and improves both API usability and reliability.astral-sh/uv3 discussions
- prefer efficient operationsChoose efficient operations and algorithms over expensive alternatives, particularly when processing data or performing file operations. Avoid operations that create unnecessary intermediate objects or make repeated system calls when vectorized or batch operations are available.Unstructured-IO/unstructured3 discussions
- API examples completenessEnsure all API code examples include all required parameters with correct placeholder values. Incomplete examples lead to user confusion and implementation errors when developers copy-paste documentation snippets.Unstructured-IO/unstructured3 discussions
- use meaningful error typesReplace generic exceptions with context-specific error types that provide meaningful information about what went wrong. When wrapping errors from external libraries, always use the correct error types from those libraries and extract error details to preserve debugging information.unionlabs/union3 discussions
- use Effect Option consistentlyReplace null, undefined, and error throwing with Effect's Option type for handling potentially missing values. This provides better type safety, composability, and prevents null reference errors.unionlabs/union3 discussions
- Use configuration service injectionReplace mutable singletons and getter functions with dependency injection services for configuration-dependent components. This approach eliminates race conditions, provides proper initialization guarantees, and enables environment-specific configuration management.unionlabs/union3 discussions
- SQL query best practicesAlways include ORDER BY clauses in paginated queries to ensure consistent results across multiple requests. Without explicit ordering, databases may return results in different orders each time, making pagination unreliable and potentially causing data to be skipped or duplicated.unionlabs/union3 discussions
- Reuse existing API utilitiesBefore implementing custom API utilities, serializers, or type identification methods, check if equivalent functionality already exists in the codebase or standard libraries. This prevents code duplication, ensures consistency across the API surface, and leverages well-tested implementations.unionlabs/union3 discussions
- organize code for readabilityStructure code to maximize readability and maintainability through clear organization patterns. Use top-level control flow structures (like switch/match statements) to make logic paths obvious and easy to follow. Extract reusable functionality into separate modules or helper libraries to promote code reuse and reduce duplication. Isolate different concerns...unionlabs/union3 discussions
- Maintain naming consistencyEnsure consistent terminology and naming conventions across the entire codebase. Use the same identifier names for the same concepts throughout all modules, files, and APIs. Avoid defining the same logical entity with different names in different places.unionlabs/union3 discussions
- Choose appropriate async primitivesSelect async/concurrency primitives based on your specific usage patterns and requirements rather than defaulting to generic solutions. Different async contexts benefit from different tools:unionlabs/union3 discussions
- avoid hardcoded configurationAvoid hardcoding configuration values directly in code. Instead, make parameters configurable through CLI arguments, config files, environment variables, or runtime queries, while providing sensible defaults.unionlabs/union3 discussions
- avoid error display duplicationWhen using thiserror for error handling, avoid displaying source errors in both the error message and the source attribute, as this creates duplicated error messages when printing the full error trace.unionlabs/union3 discussions
- Prevent object recreationsAvoid creating new objects and functions repeatedly during renders to reduce memory pressure and improve performance. Implement these practices: 1. **Move static data outside components:**shadcn-ui/ui3 discussions
- Leverage framework defaultsAvoid redundant or unnecessary configuration by understanding and utilizing default behaviors provided by frameworks and tools. Remove explicit configuration when the underlying framework already handles it automatically, which reduces maintenance overhead and prevents configuration drift.shadcn-ui/ui3 discussions
- Complete optional chainingWhen using optional chaining (`?.`), ensure that **all subsequent operations** in the chain are also protected from null/undefined values. A common mistake is only protecting the initial object access while leaving subsequent method calls or property accesses vulnerable.shadcn-ui/ui3 discussions
- Complete configuration pathsAlways verify that configuration files include all necessary file paths and extensions, particularly for framework-specific settings. Common issues include missing file extensions for TypeScript files, incorrect directory paths, and configurations that don't account for framework-specific directory structures.shadcn-ui/ui3 discussions
- Preserve naming consistencyMaintain consistent naming patterns and casing across all related code entities to ensure clarity and prevent errors. This includes: 1. Use consistent casing for technical identifiers across all occurrences (in code, documentation, and translations)microsoft/typescript3 discussions
- Eliminate unnecessary constructsRemove redundant or unnecessary code constructs to improve readability and maintainability. This includes avoiding empty blocks, blocks containing only empty statements, and unnecessary variable declarations that don't enhance code clarity.microsoft/typescript3 discussions
- Structure documentation logicallyOrganize documentation sections and content to match user mental models and workflows, not internal technical implementation details. Use descriptive, specific section names instead of generic ones like "Other changes" or overly technical terms. Present information in the order users will encounter or need it, prioritizing common use cases before advanced...astral-sh/ty3 discussions
- Ensure CI dependency reliabilityCI workflows should use the most current versions of dependencies and ensure all required tools are available. Avoid testing against potentially stale submodules or bundled dependencies by checking out the target repository directly. Use self-installing tools and hooks that handle their own installation to prevent failures due to missing dependencies.astral-sh/ty3 discussions
- Use proper PostgreSQL typesLeverage PostgreSQL's native data types and features instead of generic alternatives to improve performance, type safety, and query capabilities. Use JSONB for structured data instead of storing raw text, implement PostgreSQL enums for constrained values rather than varchar columns, and establish proper foreign key relationships with meaningful column names.twentyhq/twenty3 discussions
- Use proper null utilitiesUse dedicated null checking utilities like `isDefined` or `isUndefinedOrNull` instead of generic type coercion functions like `Boolean()`. Prefer `undefined` over empty strings or `null` as default values to maintain type safety and prevent runtime errors.twentyhq/twenty3 discussions
- Security-critical code reviewChanges to security-sensitive areas like authentication, input validation, and business logic require extra scrutiny and thorough review. These modifications can introduce vulnerabilities if not properly validated.twentyhq/twenty3 discussions
- Choose appropriate concurrency patternsSelect concurrency mechanisms that align with your system architecture and established codebase patterns. Avoid using database transactions and pessimistic locking when working with connection pooling, as they can cause unintended side effects where one connection commits on behalf of another. Instead, follow existing patterns in the codebase for handling...twentyhq/twenty3 discussions
- Avoid repeated expensive operationsReplace repeated expensive operations like `find()`, `filter()`, or `sort()` with pre-computed maps or cached results to improve performance. When the same lookup or computation is performed multiple times, create a map or dictionary for O(1) access instead of O(n) searches.twentyhq/twenty3 discussions
- Validate configuration structuresEnsure configuration files and schemas adhere to their expected structure, location, and uniqueness constraints. When supporting multiple configuration file formats (e.g., both .json and .jsonc extensions), implement validation to prevent conflicting configurations:vercel/turborepo3 discussions
- Use functional null handlingLeverage Rust's functional operators for handling nullable and optional values. Instead of using unwrap() or explicit if-statements, prefer combinators like ok(), and_then(), map_or_else() and the ? operator with Option types. This leads to more concise, readable, and null-safe code:vercel/turborepo3 discussions
- Use affected modeOptimize CI pipelines by running tasks only on packages affected by code changes. Use the `--affected` flag in Turborepo commands to automatically filter tasks to packages with changes, significantly reducing CI execution time in large monorepos.vercel/turborepo3 discussions
- Standardize package manager commandsEnsure all package manager commands in documentation and CI/CD scripts follow the correct syntax for the specific package manager being used, especially in monorepo environments. Package manager flags should be positioned correctly according to each tool's specifications to prevent pipeline failures.vercel/turborepo3 discussions
- Semantic naming conventionsUse names that clearly convey the purpose and content of variables, parameters, and properties. When working with objects, always access specific properties rather than using the object directly in string operations to prevent "[object Object]" outputs. Include proper type declarations for parameters that describe their structure.vercel/turborepo3 discussions
- Minimize lock durationWhen using locks in asynchronous code, minimize the scope and duration for which locks are held, especially across `.await` points. Holding locks during asynchronous operations can block progress in other tasks and lead to decreased concurrency or even deadlocks.vercel/turborepo3 discussions
- Document configuration alternativesWhen documenting commands or tools that can be executed in different ways based on configuration settings (like global vs. local installation), always explicitly describe all alternatives with clear, consistent labeling. Include examples for each configuration option to ensure users can follow instructions regardless of their environment setup.vercel/turborepo3 discussions
- Document cache strategiesAlways provide clear documentation and implementation for caching strategies, including key generation, invalidation policies, and default behaviors. When implementing caching:vercel/turborepo3 discussions
- Write explicit concrete testsTests should be written explicitly with concrete examples and clear assertions rather than being generated programmatically or hidden in utility code. This improves test readability, maintainability, and debugging capabilities.tree-sitter/tree-sitter3 discussions
- optimize parser development strategyWhen developing parsers or grammars, apply strategic optimization by prioritizing commonly used language features and choosing appropriate conflict resolution algorithms based on performance trade-offs.tree-sitter/tree-sitter3 discussions
- optimize dependency configurationsWhen configuring dependencies in package manifests, prioritize efficiency and maintainability by avoiding redundant dependencies, using flexible versioning, and explicitly managing features. Before adding new dependencies, check if existing ones already provide the required functionality. Use version ranges (like "^1.0") instead of exact pins to allow...tree-sitter/tree-sitter3 discussions
- API pattern consistencyWhen designing new API functions, maintain consistent patterns across the codebase and avoid creating precedents that lead to function proliferation or inconsistent interfaces. Consider how the design will scale to similar use cases and whether it aligns with existing API conventions.tree-sitter/tree-sitter3 discussions
- Remove unused code elementsEliminate unnecessary code elements including unused parameters, struct tags, methods, and dead code to improve code cleanliness and maintainability. Unused code creates confusion for maintainers and adds unnecessary complexity to the codebase.traefik/traefik3 discussions
- descriptive contextual loggingLog messages should be descriptive, contextual, and provide actionable information. Include relevant context such as service names, configuration details, or affected components. When logging errors or warnings, explain what happened, why it matters, and what action is being taken or should be taken.traefik/traefik3 discussions
- Tool Loop Output ContractWhen implementing tool-using LLM agent nodes (e.g., LangGraph/LangChain multi-agent flows), standardize a “tool loop → finalize only when tools are done” contract.TauricResearch/TradingAgents3 discussions
- SDK-aware API clientsWhen building or calling API client code, follow the SDK’s actual request/response types and conventions instead of assuming REST/dict semantics. Apply these rules:TauricResearch/TradingAgents3 discussions
- Regression Tests With ParametrizationWhen changing business logic that affects output shape/order or resolution rules, add regression tests that assert observable outcomes for edge cases, and keep the suite maintainable by parameterizing repeated mock/assert patterns.TauricResearch/TradingAgents3 discussions
- Null and Empty HandlingApply a consistent null/empty handling pattern for configuration and user-provided values: - Treat “present but empty” inputs (e.g., env vars set to `""`) as invalid rather than silently falling back. Prefer behavior that surfaces a clear configuration error.TauricResearch/TradingAgents3 discussions
- Configuration Source of TruthMaintain configuration in a single, consistent way across the codebase: - **Use explicit defaults + safe fallbacks:** If function parameters accept `None`, resolve them via config defaults (and document why). Prefer provider-specific keys so changing one provider doesn’t silently alter another.TauricResearch/TradingAgents3 discussions
- Actionable Troubleshooting DocsTechnical documentation—especially troubleshooting guides—must let contributors go from symptom to reproducible diagnosis with minimal guesswork. Apply these rules:TauricResearch/TradingAgents3 discussions
- Optimize job structureStructure CI jobs for clarity, parallelism, and efficiency. Each job should have a single, well-defined purpose to prevent confusion about which tools and versions are being used.tokio-rs/tokio3 discussions
- Optimize CI job structureStructure your CI workflows to maximize performance and clarity. Each job should have a single, clear responsibility with these guidelines: 1. **One toolchain per job**: Keep jobs focused with a single Rust toolchain version per job. Multiple toolchains in one job create confusion about which version is being used for each command.tokio-rs/tokio3 discussions
- Minimize unsafe codeWhen writing code that requires unsafe operations, follow these critical security practices: 1. Minimize the scope of unsafe blocks to only the specific operations that require themtokio-rs/tokio3 discussions
- Clear command documentationWhen documenting shell commands in technical documentation, use the `shell` language identifier instead of `bash` as commands are typically relevant to any shell. Separate commands and their output into different code blocks to make it clearer what users should actually input. This improves readability and prevents users from accidentally copying output...tokio-rs/tokio3 discussions
- Thread-safe resource sharingWhen sharing mutable data between threads, use the `Arc<RwLock<T>>` pattern to ensure thread safety. `Arc` provides thread-safe reference counting for sharing ownership across thread boundaries, while `RwLock` enables controlled mutation of the shared data.huggingface/tokenizers3 discussions
- Pythonic API designDesign APIs that follow Python language conventions and idioms rather than blindly mirroring the underlying implementation language. Consider what would feel most natural to Python developers in terms of parameter ordering, default values, and call patterns.huggingface/tokenizers3 discussions
- Purpose-indicating descriptive namesChoose names for variables, methods, parameters, and fixtures that clearly communicate their purpose, content, and behavior. Names should be self-documenting and consider future code evolution.huggingface/tokenizers3 discussions
- Optimize workflow triggersConfigure CI workflows with targeted triggers and path filters to balance thoroughness with efficiency. Run critical build jobs on every commit for affected components, while avoiding unnecessary builds when changes don't impact certain components.huggingface/tokenizers3 discussions
- Modular model componentsDesign machine learning model code with clear component boundaries and proper separation of concerns. Each component (tokenizer, normalizer, model, etc.) should have a single responsibility with appropriate visibility modifiers.huggingface/tokenizers3 discussions
- Manage version constraintsWhen configuring dependency version constraints in project files, follow these principles: 1. Be explicit about version ranges to balance flexibility with stability:huggingface/tokenizers3 discussions
- Technical precision mattersWhen documenting algorithms, data structures, and computational processes, use precise and objective language rather than subjective assessments. Replace phrases like "better approach" with specific technical comparisons that highlight concrete differences, such as:hashicorp/terraform3 discussions
- Document implementation rationaleAdd comments that explain the reasoning behind non-obvious code decisions, technical constraints, or complex logic, while avoiding over-documentation of self-evident functionality. Focus on the "why" rather than the "what" - document implementation choices that future developers (including yourself) might need to rediscover.microsoft/terminal3 discussions
- Clear accurate error messagesError messages should be clear, accurate, and contextually appropriate to help users understand what went wrong and how to fix it. Use complete, descriptive terms instead of abbreviations or technical jargon that may confuse users. Ensure error messages accurately reflect the actual capabilities and constraints of the system rather than copying generic...microsoft/terminal3 discussions
- Validate tensor inputs safelyWhen handling tensor inputs that may contain invalid values, use transformational approaches rather than conditional checks. Conditional checks like `if value < 0:` may work with scalar values but fail with tensor objects during graph execution.tensorflow/tensorflow3 discussions
- Separate test dataLarge test data should be separated from test logic to improve readability and maintainability. Move test data into separate files or define as constants at the top of test files. This makes the test bodies clearer and easier to understand.tensorflow/tensorflow3 discussions
- Use dedicated configuration filesAlways use dedicated configuration files for specific configuration needs rather than modifying core build or system files. This practice improves maintainability, traceability, and scope control.temporalio/temporal3 discussions
- Structured contextual loggingAlways use structured logging with appropriate tags instead of string concatenation or formatting. Include relevant contextual information that would help in troubleshooting, such as namespace, operation ID, or workflow ID.temporalio/temporal3 discussions
- Operation order affects correctnessWhen implementing algorithms that involve multiple operations (like iteration, validation, and execution), the order of operations can critically affect correctness. Always validate operation ordering to ensure no unintended side effects or lost data.temporalio/temporal3 discussions
- Minimize code nesting depthReduce cognitive load and improve code readability by minimizing nested code blocks. Prefer early returns and flattened logic over deeply nested conditions. This makes the code easier to read, understand, and maintain.temporalio/temporal3 discussions
- Context-aware network callsAlways propagate context through network calls to ensure proper cancellation, timeout handling, and tracing. For HTTP requests, use `http.NewRequestWithContext()` instead of `http.Post()` or `http.Get()`. For gRPC, ensure context is passed and enriched with necessary metadata.temporalio/temporal3 discussions
- Use structured API parametersWhen designing APIs with multiple related parameters, especially optional ones like filters, sorting, and pagination options, bundle them into structured types rather than using long parameter lists. This prevents parameter confusion, reduces the likelihood of argument order mistakes, and makes APIs more extensible without breaking changes.gravitational/teleport3 discussions
- Use semantically clear namesChoose names that clearly convey their purpose, scope, and meaning to reduce ambiguity and improve code maintainability. Avoid generic or potentially confusing terms when more specific alternatives exist.gravitational/teleport3 discussions
- Use descriptive semantic namesChoose descriptive, semantic names that clearly convey purpose and meaning rather than generic or ambiguous identifiers. Avoid generic method names like `apply` or `handle` that don't indicate their specific function. When existing semantic references are available (such as theme palette names), prefer them over hardcoded values. Add clarifying comments...gravitational/teleport3 discussions
- Provide contextual error messagesError messages should be specific, contextual, and use appropriate error creation functions to help users understand what went wrong and how to fix it.gravitational/teleport3 discussions
- Plan encryption key recoveryAlways implement recovery mechanisms and plan for key rotation when designing encryption systems. Encryption key failures, compromises, or rotation issues can lead to permanent data loss or service disruption.gravitational/teleport3 discussions
- Follow platform naming standardsAdhere to established naming conventions specific to each platform, framework, or technology being used. Different platforms have different naming requirements and best practices that should be followed to ensure compatibility, avoid linter warnings, and maintain consistency with ecosystem expectations.gravitational/teleport3 discussions
- Avoid overly broad permissionsUse specific, scoped permissions instead of wildcards to prevent unintended access to sensitive resources. Wildcard permissions can grant access to critical applications beyond the intended scope, creating security vulnerabilities.gravitational/teleport3 discussions
- API parameter encapsulationWhen designing API methods that accept multiple related parameters (especially filters, search criteria, or configuration options), encapsulate them in dedicated message types rather than adding individual fields directly to the request message. This pattern improves future extensibility by allowing new parameters to be added without breaking existing...gravitational/teleport3 discussions
- Training-aware ML APIsDesign machine learning APIs with explicit parameters for distinguishing between training and inference phases rather than relying on global state or implicit context. This pattern enables concurrent training and testing, improves model reusability, and prevents subtle bugs in distributed training scenarios.tensorflow/swift3 discussions
- Swift idiomatic namingFollow Swift's naming conventions to write more readable, maintainable code. The Swift language emphasizes clarity and expressiveness in naming: 1. **Avoid `get` prefixes** in function and method names. In Swift, properties and zero-argument methods serve this purpose without the prefix.tensorflow/swift3 discussions
- Provide comprehensive examplesAPI documentation should include complete examples that demonstrate all key usage patterns. When documenting related functions (like differentiation APIs), provide examples for each variant to show their relationships and differences. Include examples that showcase both basic usage and advanced patterns.tensorflow/swift3 discussions
- Generic algorithm designWhen implementing generic algorithms in Swift, follow these best practices to improve code clarity and performance: 1. Place type constraints directly on associated types rather than at the protocol level:tensorflow/swift3 discussions
- Format for readabilityCode should be formatted to optimize readability. Apply these key practices: 1. **Maintain reasonable line length** (typically 100 columns) by breaking long lines of code. For function declarations with multiple parameters or long statements, wrap them across lines with proper indentation:tensorflow/swift3 discussions
- Follow Swift naming conventionsEnsure code follows established Swift naming conventions and remains consistent with domain terminology: 1. Use standard Swift parameter labels (e.g., use `named:` instead of `called:`):tensorflow/swift3 discussions
- Document API stabilityWhen working with AI frameworks and machine learning libraries, clearly document the stability state of APIs being used. For experimental or evolving features:tensorflow/swift3 discussions
- API version managementWhen integrating with external APIs, explicitly handle version differences and use parameterized configurations instead of hardcoded values. Different API versions often require different request methods, endpoints, or parameters, so version-specific logic should be clearly defined to prevent incorrect API calls.SWE-agent/SWE-agent3 discussions
- preserve user input focusWhen implementing reactive state updates that affect input elements, always check if the user is currently interacting with the element before applying the update. This prevents jarring user experiences where typing gets interrupted by state changes.sveltejs/svelte3 discussions
- Multi-indicator configuration detectionWhen detecting configuration states, use multiple indicators rather than relying on a single source of truth, especially when dealing with ambiguous or transitional states. Provide clear documentation explaining the detection logic and reasoning behind each check.sveltejs/svelte3 discussions
- Descriptive migration commentsWhen adding migration task comments, always include specific details about why manual intervention is required rather than using generic instructions. This helps developers understand the underlying issue and implement the correct fix more efficiently.sveltejs/svelte3 discussions
- async cleanup safetyEnsure async operations include proper safety checks to prevent race conditions, memory leaks, and inconsistent state. This includes equality checks before updates, destruction status verification, and proper cleanup mechanisms.sveltejs/svelte3 discussions
- analyze transitive dependenciesWhen implementing dependency analysis algorithms, ensure comprehensive tracking of both direct and transitive dependencies to avoid missing critical relationships. Many bugs arise from incomplete dependency graphs that fail to account for indirect connections.sveltejs/svelte3 discussions
- Prefer typed themed stylesAdopt maintainable UI code style rules: 1) Avoid explicit `any` / lint ignores—use real types - Don’t rely on `any` and don’t silence type linting unless you provide a typed alternative.supermemoryai/supermemory3 discussions
- Use parameter-based pathsWhen designing API routes and interfaces, always use parameter-based path syntax instead of hardcoded literals. This approach provides better flexibility, improved type safety, and allows for more reusable code. Additionally, always validate parameters before using them in routes or API calls to prevent undefined reference errors.supabase/supabase3 discussions
- Use configuration over hardcodingAlways use configuration constants instead of hardcoding values directly in the code. This improves maintainability and reduces errors when values need to change across different environments or contexts.supabase/supabase3 discussions
- Prevent re-render triggersAvoid creating new object/array references in component render functions and carefully manage state updates to prevent unnecessary re-renders. This improves performance by reducing computational overhead and DOM manipulations.supabase/supabase3 discussions
- Explicit role security managementAlways be explicit about role privileges when configuring database security. Remember that both `authenticated` and `anon` roles typically have default privileges that need to be explicitly revoked. Use SQL migrations rather than GUI tools to manage role permissions for better version control and reproducibility.supabase/supabase3 discussions
- Explicit null handlingUse explicit patterns when dealing with potentially null or undefined values to prevent runtime errors and improve code clarity: 1. **Mark optional properties with the `?` operator** in TypeScript interfaces when values might be undefined:supabase/supabase3 discussions
- Database entity configurationConfigure database entities with appropriate defaults and clear type distinctions. For triggers, prefer AFTER/ROW over BEFORE/STATEMENT as defaults for most use cases. When working with database views, clearly distinguish between regular views and materialized views in your code. When counting database resources like replicas, ensure accurate counting by...supabase/supabase3 discussions
- Centralize configuration valuesExtract and centralize configuration values instead of duplicating or hardcoding them throughout the codebase. This improves maintainability by ensuring changes only need to be made in one place and enforces consistency across the application.supabase/supabase3 discussions
- Abstract user-facing errorsError messages displayed to end users should abstract away implementation details while providing actionable information. Avoid exposing internal system components (like "containerd", "K8S") or raw error messages that might confuse users or reveal security-sensitive information. Instead, map technical errors to user-friendly messages that explain what...supabase/supabase3 discussions
- prefer lazy computationAvoid precomputing expensive operations when they may not be needed, especially for large datasets. Instead, compute values on-demand when they are actually required. This prevents unnecessary work and improves performance for scenarios where only a subset of computed values will be used.browserbase/stagehand3 discussions
- Configure workflow triggersEnsure GitHub Actions workflows are triggered appropriately by configuring branch patterns and path filters to balance CI efficiency with comprehensive coverage. Workflows should run on all relevant branches (not just main) while using path filters to avoid unnecessary executions.browserbase/stagehand3 discussions
- abstract environment variablesAvoid directly referencing environment variables throughout your codebase. Instead, abstract them into named constants with sensible defaults at module boundaries. This improves readability, makes configuration explicit, and prevents scattered environment variable access.browserbase/stagehand3 discussions
- Standardize configuration formatsUse consistent, explicit, and well-documented formats in all configuration files to improve readability and prevent misunderstandings. When defining configuration values:spring-projects/spring-framework3 discussions
- Package null-safety annotationsAll package-info.java files must include both @NonNullApi and @NonNullFields annotations to establish null-safety at the package level. These annotations must each be on a single line for proper detection by static analysis tools. This practice makes null-handling behavior explicit, reduces NullPointerExceptions, and enforces consistent null-safety...spring-projects/spring-framework3 discussions
- Optimize CI environment configurationWhen configuring CI environments, carefully evaluate whether default dependency versions are sufficient for your project needs before adding custom installation steps. Default configurations (like Travis CI's JDK version) often provide adequate support while maintaining optimal build times. Only include additional installation commands when specific project...spring-projects/spring-framework3 discussions
- Leverage Kotlin null-safetyUtilize Kotlin's null-safety features effectively to create cleaner, more robust code: 1. For class properties that will be initialized before use, prefer `lateinit var` over nullable types with `?`:spring-projects/spring-framework3 discussions
- Database-agnostic SQL syntaxWrite SQL statements that conform to standard SQL rather than relying on vendor-specific dialects to ensure portability across different database systems.spring-projects/spring-framework3 discussions
- Clone network headers carefullyWhen working with HTTP or WebSocket headers in networking code, be cautious about header manipulation, cloning, and lifecycle management. Native headers in server implementations are often pooled and may be recycled after initial processing.spring-projects/spring-framework3 discussions
- Validate nulls properlyAlways use appropriate null validation mechanisms to prevent NullPointerExceptions and ensure code robustness. For string parameters: - Use `Assert.hasText(profile, "Profile must have text")` instead of `Assert.notNull()` when you need to validate both null and empty stringsspring-projects/spring-boot3 discussions
- Reference existing configurationsWhen setting up configuration files, reference existing configuration sources rather than duplicating values or logic. This creates a single source of truth, reduces maintenance overhead, and prevents inconsistencies between different environments.spring-projects/spring-boot3 discussions
- Verify CI build consistencyEnsure CI pipelines thoroughly verify build outputs and maintain consistency across different build tools and configurations. This prevents broken builds from reaching contributors and ensures reliable deployment artifacts.apache/spark3 discussions
- use modern Java syntaxPrefer modern Java language features and constructs to write more concise, readable code. Since Apache Spark 4.0.0, the project recommends using contemporary Java syntax where applicable.apache/spark3 discussions
- Use descriptive namesChoose names that clearly convey purpose and context rather than generic or vague terms. Names should be self-documenting and provide sufficient information for developers to understand their role without additional investigation.apache/spark3 discussions
- Proper synchronization patternsWhen implementing synchronization mechanisms, avoid common anti-patterns that can lead to performance issues or incorrect behavior. Use proper condition variables with timeouts instead of indefinite or busy waiting, and ensure condition checks occur after wait operations.apache/spark3 discussions
- parameterize configuration valuesReplace hardcoded configuration values with parameterized variables in build files and configuration management. This enables flexible environment-specific settings and improves maintainability.apache/spark3 discussions
- minimize public API surfaceOnly expose APIs that are truly necessary for external consumers and avoid creating public interfaces that may become maintenance burdens. Before adding public builders, helper utilities, or exposing internal types, critically evaluate whether they provide genuine value to API users.apache/spark3 discussions
- context-independent schema designDatabase schema elements (views, constraints, tables) should be designed to be context-independent and self-contained. This means all identifiers should be fully qualified, and only information supported by the SQL parser should be included in DDL representations.apache/spark3 discussions
- comprehensive test coverageEnsure test suites provide comprehensive coverage by including edge cases, boundary conditions, and input variations while verifying that tests actually validate the intended functionality. Tests should cover different input formats (case sensitivity, precision levels), boundary values (empty inputs, maximum/minimum values), and error conditions. Remove...apache/spark3 discussions
- Use semantic namingChoose names that clearly communicate the purpose, meaning, and scope of variables, functions, constants, and files. Names should be self-documenting and immediately convey their role to other developers.bytedance/sonic3 discussions
- optimize algorithms by characteristicsWhen implementing algorithms, make optimization decisions based on the specific characteristics of your data types and usage patterns rather than using generic approaches. Consider factors like type semantics, memory layout, and processing requirements to choose the most appropriate algorithmic strategy.bytedance/sonic3 discussions
- Consistent semantic namingMaintain consistent naming conventions throughout the codebase and use semantically clear identifiers that clearly indicate their purpose and behavior. All functions, variables, and other identifiers should follow the same naming style (preferably snake_case for C code) and have descriptive names that make their functionality obvious.bytedance/sonic3 discussions
- use design tokensReplace hardcoded color values, spacing, and other design-related constants with design tokens or CSS custom properties. This promotes consistency across the application, makes theme changes easier to implement, and reduces code duplication.SigNoz/signoz3 discussions
- Use descriptive contextual namesChoose variable, method, and property names that clearly communicate their purpose and context to avoid confusion and misinterpretation. Names should be self-explanatory and specific enough that their meaning is unambiguous within their usage context.SigNoz/signoz3 discussions
- Use database transactionsAlways use database transactions when performing operations that require atomicity or could create race conditions. This includes scenarios where you check for existence before creating/updating records, or when multiple related database operations must succeed or fail together.SigNoz/signoz3 discussions
- standardize authentication context extractionAlways use the standardized `authtypes.ClaimsFromContext` method for extracting authentication claims from request context, and handle errors properly. This ensures consistent authentication handling across the codebase and prevents potential security vulnerabilities from incorrect claim extraction.SigNoz/signoz3 discussions
- measure before optimizingAlways measure performance impact before making optimization decisions or skipping potential optimizations due to complexity assumptions. Performance characteristics can be counterintuitive, and assumptions about complexity vs. performance trade-offs should be validated with actual benchmarks.SigNoz/signoz3 discussions
- API payload completenessEnsure all required fields are included in API payloads and handle special field cases properly to prevent runtime errors and data inconsistencies. Missing fields in API transformations can cause bugs and unexpected behavior. Always validate that essential fields like `aggregations`, `filter`, and `having` are properly passed through data transformations....SigNoz/signoz3 discussions
- Avoid redundant expensive workFor performance-sensitive React code, prevent unnecessary recomputation and avoid “clever” micro-optimizations that add complexity without measurable benefit.paper-design/shaders3 discussions
- optimize tensor operationsWhen working with PyTorch tensors, prioritize operations that avoid unnecessary memory allocations and copies to improve performance. Choose tensor operations carefully based on whether data will be immediately overwritten or needs preservation.sgl-project/sglang3 discussions
- Explicit API parametersAPI functions should use explicit parameters rather than passing large opaque objects. When a function needs specific data from a complex object, extract and pass only the required fields as individual parameters. This makes the function's dependencies clear, improves testability, and reduces coupling.sgl-project/sglang3 discussions
- Environment variable best practicesAvoid reading environment variables directly in performance-critical code paths, especially during model forward passes or hot loops. Instead, read and cache environment variables during initialization or use dedicated helper functions for consistent handling.sgl-project/sglang3 discussions
- Document AI limitationsWhen implementing AI model support or hardware backends, clearly document known limitations, compatibility constraints, and version requirements to prevent integration issues and set proper expectations.sgl-project/sglang3 discussions
- Handle unsafe code properlyMethods that access raw memory buffers, perform pointer operations, or interact with foreign function interfaces must be explicitly marked as `unsafe` to prevent memory safety vulnerabilities. Conversely, remove unnecessary `unsafe` blocks when calling safe functions to maintain code clarity and prevent masking actual unsafe operations.servo/servo3 discussions
- avoid borrow hazardsPrevent borrow conflicts by collecting or cloning data before operations that may trigger garbage collection, call into JavaScript, or create additional borrows. This is especially critical when holding mutable borrows (`borrow_mut()`) that could conflict with operations that need to access the same data.servo/servo3 discussions
- Provide contextual explanationsDocumentation should explain the reasoning, context, and practical implications behind code examples, not just show syntax or commands. Include explanations of why developers would use specific approaches, how different options work together, and what to expect from running commands.serverless/serverless3 discussions
- Simple explicit interfacesDesign API interfaces to be simple and explicit rather than hiding complexity behind elaborate fallbacks or conditional logic. When core functionality is unavailable, fail explicitly with clear error messages instead of implementing complex workarounds. Push complexity and decision-making to the caller rather than embedding it within the API implementation.oraios/serena3 discussions
- Write comprehensive assertionsWhen writing tests, ensure your assertions thoroughly verify all relevant aspects of the functionality being tested. Go beyond the basic "happy path" checks and include assertions that verify:getsentry/sentry3 discussions
- Structured metric namingCreate metrics with descriptive, unique names that are distinguishable when viewed in monitoring tools. Avoid generic prefixes that make groups of related metrics indistinguishable from each other. Include specific actions or states in the metric name to clearly identify what's being measured.getsentry/sentry3 discussions
- Simplify feature flag logicWhen working with feature flags and configuration conditions, keep your logic clean and up-to-date: 1. **Simplify conditionals when flag states change**: When a feature flag becomes permanently enabled or disabled, update and simplify all conditionals that reference it.getsentry/sentry3 discussions
- Prefer bulk operationsWhen implementing functionality that processes multiple items, always consider the performance implications of individual versus batch processing. Avoid fetching or processing items one-by-one in loops, as this can lead to significant performance degradation, especially at scale. Instead:getsentry/sentry3 discussions
- Minimize file memory footprintWhen handling files in your application, minimize memory usage to optimize performance. Follow these guidelines: 1. **Avoid multiple reads**: Read file content only once and reuse it throughout your code. Each read operation loads the entire file into memory.getsentry/sentry-php3 discussions
- Memoize expensive computations effectivelyPrevent unnecessary recalculations and rerenders by properly memoizing expensive computations and derived values in React components. Pay special attention to dependency arrays and ensure they only include stable references.getsentry/sentry3 discussions
- Consistent URL designDesign API endpoints with consistent, unambiguous URL patterns to improve usability and maintainability. Follow these principles: 1. **Use descriptive parameter names** that clearly indicate their purposegetsentry/sentry3 discussions
- Clear consistent naming patternsUse clear, consistent naming patterns for variables and event handlers. Avoid abbreviations unless they are widely understood standards. For event handlers, follow the pattern 'on' + 'action' + 'object'.getsentry/sentry3 discussions
- Centralize AI codeMove AI-specific functionality (especially prompts) to dedicated services rather than scattering them throughout the codebase. This improves maintainability and follows team conventions.getsentry/sentry3 discussions
- API parameter design flexibilityDesign API parameters to be extensible and future-proof by using object arguments and explicit type definitions instead of boolean flags or simplistic checks. This approach makes APIs more maintainable and easier to evolve over time.getsentry/sentry3 discussions
- Algorithm structure optimizationOptimize algorithm structure by separating concerns and using appropriate data structures and language features. When implementing algorithms: 1. **Separate search from processing** to improve readability and maintainability. When you need to find and process an item, first locate the item, then apply operations to it rather than mixing these steps.getsentry/sentry3 discussions
- Use typed interfacesPrefer typed interfaces over dictionary access to enable static type checking and prevent null reference errors. When accessing data structures, use typed objects with defined fields rather than dictionary key access, as this allows mypy to detect typos and missing fields at compile time.semgrep/semgrep3 discussions
- Use descriptive variable namesChoose variable and parameter names that clearly communicate their purpose and avoid misleading or cryptic naming. Names should be self-documenting and reduce cognitive load for other developers.semgrep/semgrep3 discussions
- Ensure comprehensive test coverageTests should validate all expected behaviors, variants, and edge cases rather than covering only the happy path. When implementing tests, ensure you include scenarios for all relevant configurations, types, or levels that your code supports.semgrep/semgrep3 discussions
- Document configuration troubleshootingConfiguration files and scripts should include comprehensive documentation that helps developers understand their purpose, scope, and how to troubleshoot common issues. This includes adding comments that explain what the configuration does, what errors might occur, and specific steps to resolve them.semgrep/semgrep3 discussions
- Defensive optional handlingAlways handle optional and nullable values defensively by checking for null/empty states before use and handling multiple optional values independently. Use explicit null coalescing patterns to provide safe defaults, and avoid nesting optional value logic when they should be processed independently.semgrep/semgrep3 discussions
- Defensive authorization checksAlways implement explicit authentication and authorization checks before granting access to premium features or sensitive operations, even when other conditions might imply proper authorization. Use defensive programming to prevent accidental privilege escalation.semgrep/semgrep3 discussions
- Conservative security assumptionsWhen implementing security measures, always err on the side of caution by making conservative assumptions about potential risks. This principle applies across multiple security contexts:semgrep/semgrep3 discussions
- Add comprehensive test coverageEnsure all code changes include appropriate unit tests and address any identified testing gaps immediately. When reviewing code, verify that: 1. **New functionality has corresponding tests**: Every new feature or significant code change should include unit tests that exercise the new behavior.semgrep/semgrep3 discussions
- Configuration default handlingUse clean, simple patterns when accessing configuration values with defaults. Avoid redundant fallback operations and overly complex boolean conversions that reduce code readability.strands-agents/sdk-python3 discussions
- Prevent TOCTOU vulnerabilitiesTime-of-Check-to-Time-of-Use (TOCTOU) race conditions occur when a program checks a condition and then uses the result of that check, but the condition might have changed between the check and use. This pattern creates security vulnerabilities, particularly in file system operations, but can affect any multi-step operation where state might change.rust-lang/rust3 discussions
- Default over unsafe initializationPrefer using safe initialization methods like `Default::default()` over unsafe alternatives like `MaybeUninit::uninit()` or null values when initializing variables. This reduces the risk of undefined behavior and eliminates unnecessary unsafe blocks.rust-lang/rust3 discussions
- Validate before accessAlways validate parameters and initialize variables before access to prevent null dereference and undefined behavior. When handling arrays or pointers, require and validate length parameters. For conditionally initialized variables, ensure all code paths explicitly set values.dotnet/runtime3 discussions
- Preserve pointer authenticationWhen implementing Pointer Authentication (PAC) for security, maintain signed pointers throughout their entire lifecycle to prevent potential security vulnerabilities. Avoid unnecessarily stripping PAC signatures from pointers that will be stored and later reused. This preserves the security guarantees that PAC is designed to provide.dotnet/runtime3 discussions
- Platform-agnostic network APIsWhen implementing networking functionality, ensure code uses platform-agnostic APIs and appropriate abstraction layers to handle differences between Windows, Unix, and macOS systems. Similar to how string operations require platform-specific handling (as seen in discussion 1 where `strchr` was replaced with `app_candidate.find(DIR_SEPARATOR)`), networking...dotnet/runtime3 discussions
- Parameterize configuration valuesExtract hard-coded configuration values into variables, parameters, or templates to improve reusability and simplify maintenance. When the same value is used in multiple places or might need to change in the future, define it once and reference it throughout your configuration files.dotnet/runtime3 discussions
- Optimize build dependency chainsWhen configuring build and test processes in CI/CD pipelines, ensure proper dependency chains with clear inputs and outputs to avoid unnecessary execution steps and cross-platform failures. Use techniques like:dotnet/runtime3 discussions
- Memory ordering mattersWhen working with shared data in multithreaded environments, memory ordering is critical to prevent race conditions and ensure thread safety: 1. **Avoid transient incorrect states** - Don't write an incorrect value before replacing it with the correct one, as other threads may see the intermediate state:dotnet/runtime3 discussions
- Choose descriptive namesNames should clearly convey purpose and meaning. Parameter, variable, and method names should be self-explanatory and accurately reflect their behavior and intent. Rename elements when their original name no longer captures their purpose or could lead to confusion.dotnet/runtime3 discussions
- Verify union attribute accessWhen working with union types in Python, always verify that all components of the union have the attributes you're trying to access or modify. Failure to do so can lead to runtime errors when the code attempts to access undefined attributes.astral-sh/ruff3 discussions
- Structure documentation effectivelyDocumentation should follow a consistent structure where explanations precede code examples, preferably ending with a colon to introduce the code. When documenting special cases or complex behaviors, include links to relevant external specifications or standards. Consolidate similar documentation to avoid duplication across files.astral-sh/ruff3 discussions
- Ensure algorithmic determinismWhen implementing algorithms for code analysis, type checking, or pattern matching, ensure they produce consistent and deterministic results for the same inputs. Edge cases should be explicitly handled rather than making assumptions.astral-sh/ruff3 discussions
- Assert exact expectationsAlways assert exact expected values in tests rather than using loose assertions. When testing the presence of elements or count of items, use equality assertions (`assert_eq!`) instead of non-empty checks (`assert!(!items.is_empty())`) or inequality assertions (`assert!(items.len() >= 2)`).astral-sh/ruff3 discussions
- Use descriptive scoped namesPrefer descriptive, scoped names over generic or vague identifiers for types, functions, and properties. Names should clearly communicate their purpose and context within the codebase.TanStack/router3 discussions
- React hook dependenciesCarefully manage dependencies in React hooks to avoid stale closures and ensure correct behavior. When using useCallback, useMemo, or useEffect, include all reactive values that the hook depends on in the dependency array, even if it affects stability.TanStack/router3 discussions
- Environment file managementEnsure proper handling of environment files by following these practices: (1) Add actual environment files (`.env`, `.env.local`, etc.) to `.gitignore` to prevent sensitive data from being committed, (2) Include example environment files (`.env.example`) in version control to help other developers understand required configuration, and (3) Add clear...TanStack/router3 discussions
- Environment-aware configuration managementEnsure configuration management accounts for different environments and maintains backward compatibility during migrations. This includes using safe access patterns for global objects, versioning configuration keys, and preserving environment-specific behavior.TanStack/router3 discussions
- environment-aware API usageAlways detect the runtime environment before using environment-specific APIs or utilities. This is crucial for networking applications that may run in browsers, Node.js servers, or cross-platform contexts.TanStack/router3 discussions
- Choose efficient algorithmsPrefer built-in methods and appropriate data structures over manual implementations to improve both performance and code readability. Consider the computational complexity and trade-offs of different approaches.TanStack/router3 discussions
- avoid unnecessary complexityRemove code complexity that doesn't provide clear value, particularly in type definitions, configuration options, and formatting constraints. This includes eliminating redundant type omissions, using descriptive names for configuration options, and avoiding formatting rules that conflict with user preferences.TanStack/router3 discussions
- algorithm implementation trade-offsWhen implementing algorithms, carefully evaluate trade-offs between built-in methods, custom implementations, and different algorithmic approaches. Consider factors like browser compatibility, performance characteristics, maintainability, and edge case handling.TanStack/router3 discussions
- Validate model capabilities firstAlways validate AI model capabilities and configurations before attempting to use them. This includes checking: 1. Feature support (e.g., images, embeddings)RooCodeInc/Roo-Code3 discussions
- Use nullish coalescingWhen providing default values for numeric properties, use the nullish coalescing operator (??) instead of logical OR (||). This ensures that valid zero values are preserved rather than being replaced with defaults. Using || will treat 0 as a falsy value and replace it with the default, which is often unintended behavior for numeric settings.RooCodeInc/Roo-Code3 discussions
- Use cryptographic randomnessAlways use cryptographically secure random number generation for security-sensitive operations such as generating session IDs, authentication tokens, or unique identifiers. Standard random number generators like `Math.random()` are designed for statistical randomness, not security, making them vulnerable to prediction and exploitation by attackers.RooCodeInc/Roo-Code3 discussions
- Sanitize untrusted contentAlways sanitize user-generated or externally sourced content before rendering it to prevent Cross-Site Scripting (XSS) vulnerabilities. Never use `dangerouslySetInnerHTML` with unsanitized content.RooCodeInc/Roo-Code3 discussions
- Prevent timeout race conditionsWhen working with timeouts and asynchronous operations that affect shared state, clear timeouts at the beginning of event handlers or user interactions to prevent race conditions. This defensive approach ensures that competing operations (like auto-approval timers and manual user actions) don't conflict.RooCodeInc/Roo-Code3 discussions
- Centralize configuration constantsAlways centralize configuration constants in a shared location and import them rather than duplicating values across the codebase. This prevents drift between frontend and backend configurations, reduces errors from manual updates, and makes configuration changes easier to manage.RooCodeInc/Roo-Code3 discussions
- validate null undefined valuesAlways perform explicit null and undefined checks before accessing object properties or using values in operations. Filter out undefined values from arrays and collections to prevent runtime errors and unexpected behavior.smallcloudai/refact3 discussions
- Version Compatibility FirstWhen changing serialized/wire formats (RDB/DUMP/RESTORE or module metadata), treat it as a data migration: define compatibility behavior and make encoding placement deterministic.redis/redis3 discussions
- Null-safe Free WrappersWhen a free/cleanup API may receive NULL (or an invalid handle), don’t rely on ad-hoc checks at call sites. Instead, define a NULL-safe wrapper/helper that:redis/redis3 discussions
- Maintain algorithmic invariantsWhen implementing algorithms that depend on “current state” (client context, cached slot/client, etc.) or on custom data structures (stack/heap modes), make the invariant explicit and ensure all computations are derived from the specific operand/object being processed—not from incidental outer execution context.redis/redis3 discussions
- Define Non-Ack BehaviorFor any control-plane action that depends on acknowledgement (epochs/status updates, joins/removes, metadata propagation), the codebase must explicitly define end-to-end error handling: timeout, retry/escalation, cascade effects, and the operator override path.redis/redis3 discussions
- Control-plane connectivity rulesDefine a single, deterministic networking contract between data-plane nodes and the control plane (TD/FC), and make it resilient to CP reachability and multi-FC state consistency.redis/redis3 discussions
- Verify performance empiricallyAlways validate performance optimizations through measurement rather than assumptions. Run multiple iterations of performance tests to ensure statistical significance and reduce noise in your metrics.facebook/react3 discussions
- Use appropriate testing methodsWhen writing tests, use the appropriate testing utilities and ensure proper test isolation. For testing warning behaviors, use assertConsoleErrorDev instead of environment flags. For testing sequential actions, use logging utilities with corresponding assertions. Always clean up after tests that use mocks.facebook/react3 discussions
- Separate conditional pathsWhen working with concurrent operations, separate conditional logic from potentially expensive or suspenseful execution paths. This improves performance, prevents race conditions, and makes concurrent code more predictable and maintainable.facebook/react3 discussions
- use modern JavaScript patternsAdopt modern JavaScript syntax and patterns to improve code quality and maintainability. This includes using current language features over deprecated alternatives, proper variable declarations, and modern conditional operators.remix-run/react-router3 discussions
- TypeScript configuration setupEnsure proper TypeScript configuration for generated types and development workflow. This includes setting up gitignore patterns, configuring tsconfig.json for type generation, and integrating typegen into build scripts.remix-run/react-router3 discussions
- prefer explicit readable constructsChoose explicit and semantic code constructs that enhance readability over more concise but less clear alternatives. This improves code maintainability and reduces cognitive load for developers.remix-run/react-router3 discussions
- HTTP protocol complianceEnsure code adheres to HTTP protocol standards and handles different protocol versions correctly. This includes respecting protocol limitations, using appropriate status codes, and implementing proper fallbacks.remix-run/react-router3 discussions
- graceful error handlingImplement error handling that gracefully degrades when operations fail, uses consistent reporting patterns, and considers security implications. Always wrap potentially failing operations in try-catch blocks, provide meaningful fallback behavior, and follow established error reporting conventions.remix-run/react-router3 discussions
- Extract test helpersCreate reusable helper functions for common test setup patterns to reduce duplication and improve maintainability. When you find yourself repeating the same mock objects, test data structures, or setup code across multiple tests, extract them into shared utilities.remix-run/react-router3 discussions
- documentation linking standardsEnsure proper linking and cross-referencing in documentation to improve navigation and discoverability. Use correct JSDoc syntax for type references and consistently link to related concepts where they are mentioned.remix-run/react-router3 discussions
- documentation generation compatibilityWhen making code changes, ensure compatibility with documentation generation tools like JSDoc and TypeDoc. This includes: (1) Exporting types that should appear in generated documentation, (2) Avoiding duplicate exports across modules that can confuse documentation parsers, and (3) Formatting code examples appropriately for documentation rendering.remix-run/react-router3 discussions
- Document configuration rationaleWhen adding or modifying configuration files, always include clear comments or documentation explaining the reasoning behind non-obvious choices, especially when suppressing warnings, excluding files, or making decisions that deviate from defaults.remix-run/react-router3 discussions
- Cancel aborted async operationsWhen working with async operations that can be aborted (like HTTP requests), ensure proper cancellation of related promises and deferred operations to prevent memory leaks and unnecessary work. This applies to both operations created after abortion has occurred and those created before abortion.remix-run/react-router3 discussions
- avoid redundant computationsIdentify and eliminate repeated expensive operations to improve performance. Cache computationally expensive objects like regex patterns, API results, or complex calculations outside of loops and repeated execution contexts. Implement early exit conditions when possible to avoid unnecessary processing.remix-run/react-router3 discussions
- Optimize React Component DependenciesWhen implementing React components, ensure that dependencies between component state, props, and side effects are accurately tracked to prevent missed updates and unnecessary re-renders.facebook/react3 discussions
- validate before operationsAlways explicitly check for null, undefined, or missing properties/methods before performing operations that could fail. JavaScript's loose typing and the fact that `typeof null === 'object'` can lead to runtime errors if values aren't validated first.facebook/react-native3 discussions
- Simplify parsing algorithmsWhen implementing parsing or processing algorithms, prioritize simplification and reusability over complex custom solutions. Convert complex conditional logic into simpler, well-defined data structures and reusable functions. Use established, proven algorithms from reliable sources rather than deriving custom implementations.facebook/react-native3 discussions
- Prevent regression crashesWhen implementing error handling or bug fixes, avoid introducing new crash conditions that would break previously working code. Focus on defensive programming that handles edge cases without creating new failure points.facebook/react-native3 discussions
- Meaningful documentation practicesDocumentation should enhance code understanding rather than duplicate information already present in the code. Avoid redundant type annotations in JSDoc when type systems like Flow are already used. Instead, focus on explaining intent, complex logic, and providing context that aids debugging and maintenance.facebook/react-native3 discussions
- leverage framework cache mechanismsWhen implementing caching functionality, prefer using framework-provided cache mechanisms over manual cache management. Frameworks typically offer optimized cache handling that includes automatic error propagation, efficient multi-level cache checking, and built-in performance optimizations that are difficult to replicate manually.facebook/react-native3 discussions
- Follow platform naming conventionsAdhere to the established naming conventions and namespacing practices of your target platform. This includes following language-specific patterns for method names, avoiding namespace pollution in headers, and properly namespacing exported functions.facebook/react-native3 discussions
- Feature flag isolationFeature flags should be properly isolated and scoped to avoid mixing configuration concerns with core interfaces. When implementing feature flags, ensure they only affect behavior when explicitly enabled and don't leak into unrelated system components.facebook/react-native3 discussions
- ensure exception safetyAlways ensure proper exception safety by placing cleanup code in @finally blocks, using stack-allocated exceptions, and implementing comprehensive exception handling for different types. Resource cleanup must occur even when exceptions are thrown to prevent memory leaks.facebook/react-native3 discussions
- consistent null checkingEnsure null checks follow consistent patterns and proper ordering for better readability and safety. Always place the variable being checked on the left side of null comparisons, use defensive programming with hasKey() checks before accessing map values, and maintain null-safe fallbacks when appropriate.facebook/react-native3 discussions
- catch specific exceptionsAlways catch specific exception types rather than generic `Exception` to avoid masking unexpected errors and ensure intentional error handling. This practice helps distinguish between expected failure scenarios that should be handled gracefully and unexpected errors that indicate bugs.facebook/react-native3 discussions
- avoid unnecessary conversionsChoose direct, efficient methods over approaches that require additional parsing, conversion, or processing steps. This reduces computational overhead and improves performance by eliminating intermediate operations.facebook/react-native3 discussions
- Avoid expensive allocationsMinimize object creation and expensive operations in performance-critical code paths, particularly in frequently called methods like onDraw, layout operations, and UI updates.facebook/react-native3 discussions
- Match errors to contextChoose error handling mechanisms based on the error's severity and context. For critical issues that should prevent further execution, throw explicit exceptions. For non-critical issues, use logging with sufficient detail to aid debugging without interrupting execution.facebook/react3 discussions
- Complete hook dependenciesAlways specify complete dependency arrays in React hooks to prevent bugs from stale closures and avoid unnecessary rerenders. When using hooks like useEffect, useMemo, or useCallback, include all values from the component scope that are referenced inside the hook's callback function.facebook/react3 discussions
- Check property existence firstAlways verify that an object and its properties exist before accessing them to prevent 'cannot read property of undefined/null' errors. This is especially important when dealing with objects that might come from different build environments or third-party libraries.facebook/react3 discussions
- Wrap threaded code properlyWhen working with threads in Rails applications, always wrap application code with `Rails.application.executor.wrap` to ensure thread safety and proper state management. Code running outside these wrappers can cause race conditions, memory leaks, and inconsistent application state.rails/rails3 discussions
- Semantic HTML usageUse HTML elements according to their semantic purpose to ensure proper accessibility and code organization. Choose elements based on their intended role, not just how they appear visually:rails/rails3 discussions
- Environment-specific logger configurationConfigure loggers in environment-specific files rather than in application.rb or initializers. Different environments (development, test, production) typically require different logging levels and configurations, and Rails is designed to support this pattern.rails/rails3 discussions
- Document performance implicationsClearly document the performance implications of features and configurations to help users make informed decisions. Avoid overstating or understating performance impacts. Instead, provide specific context about when certain features might impact performance and in what environments they are appropriate.rails/rails3 discussions
- Consistent terminology usageAlways use consistent terminology for the same concept throughout your codebase, documentation, and user interfaces. When multiple terms could describe the same thing, choose one definitive term and use it consistently everywhere.rails/rails3 discussions
- Transactional delete and upsertFor database writes that can partially succeed (multi-step deletes/updates, bulk upserts with conflict handling), enforce invariants with **atomic transactions**, **explicit outcome validation**, and **engine-specific SQL encapsulation**.infiniflow/ragflow3 discussions
- Agent Prompt ContractsWhen building LLM Agents, treat the system prompt + framework prompt blocks as a contract with the agent’s inputs and tool/sub-agent configuration. Apply these rules:infiniflow/ragflow3 discussions
- Verify AI library compatibilityWhen specifying AI/ML library dependencies, ensure version compatibility between related packages and verify that prebuilt binaries are available for the target environment. Many AI libraries like auto_gptq, autoawq, and flash_attn are compiled against specific versions of PyTorch and CUDA, and version mismatches can force compilation from source or cause...QwenLM/Qwen33 discussions
- Configuration parameter documentationEnsure all configuration parameters have explicit default values and are thoroughly documented. When using argparse with `action='store_true'`, always pair it with `default=False`. Document parameter purposes, valid values, and default behaviors in README files. For dependency management, separate conflicting requirements into different files to avoid...QwenLM/Qwen33 discussions
- Warn on silent failuresIn automation scripts/workflows, never fail or skip important work silently. If a condition decides to omit a capability/flag, or if a command fails with diagnostics discarded or a sentinel fallback is used, emit an explicit warning (or notice) that includes the relevant inputs and captured error output.QwenLM/qwen-code3 discussions
- Single Source ConfigEnsure workflow configuration (env vars, inputs, config lists) has a single authoritative definition and a clearly documented consumer. Apply this when editing GitHub Actions/workflow configs or config-driven automation:QwenLM/qwen-code3 discussions
- Normalize selection keysWhen selecting a “preferred” item (via `find`, `filter`, pagination anchors, etc.) or deciding based on a computed threshold, ensure two things: 1) **Compare like with like:** normalize/parse inputs so the keys you compare are in the same canonical form.QwenLM/qwen-code3 discussions
- Minimize expensive API callsWhen your code depends on GitHub (or other remote) APIs, pagination and per-item mutations are often the dominant performance cost. Structure workflows/scripts to avoid redundant full scans and to prevent N+1 API patterns unless the workload is provably small.QwenLM/qwen-code3 discussions
- Type-Safe, Scripted TestsEnsure your testing approach covers both runtime behavior and public API types, and that the test scripts you expose are correct, documented, and preserve any packaging-specific smoke checks.tanstack/query3 discussions
- Standardize monorepo lintingUse shared root configuration for formatting and apply consistent ESLint rule severities across the monorepo, allowing only narrowly scoped exceptions.tanstack/query3 discussions
- Short-Circuit for PerformanceIn performance-sensitive code paths, minimize unnecessary work by ordering conditions to short-circuit early, and avoid redundant async wrappers. **Apply these rules:**tanstack/query3 discussions
- Semantic naming clarityWhen introducing names for APIs/docs and for contribution metadata, ensure the naming is semantic and cannot be mistaken for a requirement that isn’t real.tanstack/query3 discussions
- Propagate and Test ErrorsHandle errors at the right boundary, keep failure state consistent, and ensure tests validate the real semantics. Apply these rules: 1) Don’t swallow errors inside reusable helpers.tanstack/query3 discussions
- Deterministic CI GatesEnsure CI/CD is deterministic and comprehensive: pin versions when dependencies/tooling have drifted, make the same checks run on PRs as on main, and test against the full supported toolchain/version range.tanstack/query3 discussions
- Consistent Unique Package NamesUse stable naming conventions that match repo/tooling expectations and avoid identifier collisions. **Rules** 1. **Keep script names consistent across packages**: if CI/tooling expects specific npm/pnpm script keys, use the same keys in every package (don’t rename per-package).tanstack/query3 discussions
- Configurable tooling rulesSpecialized tooling (lint rules, dev-only packages, docs navigation) must be explicitly enabled and driven by configuration so it won’t misfire in the wrong project context.tanstack/query3 discussions
- Reuse test patternsMinimize duplication and improve test maintainability by reusing existing test patterns and leveraging parameterization. When testing similar functionality across modules or with varying inputs, prefer adapting existing test cases and using parameterized tests over creating entirely new test files.quarkusio/quarkus3 discussions
- Document deployment strategy constraintsAlways document and enforce appropriate deployment strategies for different application types in your CI/CD pipeline configuration. Different deployment strategies have specific constraints that must be considered for successful application delivery.quarkusio/quarkus3 discussions
- Document dependency versionsWhen managing dependency versions in configuration files, provide clear documentation to help maintainers understand version choices and relationships. Include links to repositories where versions can be verified, keep related versions aligned when appropriate, and add explanatory comments for version-related decisions.quarkusio/quarkus3 discussions
- Descriptive consistent namingUse clear, descriptive names instead of cryptic abbreviations, and follow consistent naming patterns across your codebase. This practice enhances readability and maintainability.quarkusio/quarkus3 discussions
- Avoid request-path blockingMinimize blocking operations in request-handling paths to ensure responsive application performance. Implement caching and asynchronous processing for expensive operations to reduce latency and improve throughput.quarkusio/quarkus3 discussions
- Thread context managementAlways explicitly set required thread context and state rather than assuming inheritance from parent threads or other concurrent processes. In multithreaded and distributed environments, assumptions about shared state can lead to subtle bugs, race conditions, and incorrect behavior.pytorch/pytorch3 discussions
- Structure for readabilityStructure code to maximize readability by reducing unnecessary complexity. Use early returns to minimize nesting levels, move invariant conditions outside of loops, and replace magic numbers with named constants.pytorch/pytorch3 discussions
- Reusable workflow designDesign CI/CD workflows with reusability and clear naming conventions from the start. Use meaningful prefixes that reflect the conceptual purpose (like "trunk" for trunk-based development), and consider future extraction into standalone, parameterized actions when similar functionality might be needed across repositories.pytorch/pytorch3 discussions
- Reduce code duplicationEliminate repeated code patterns by using appropriate abstraction techniques. This improves readability, reduces maintenance burden, and minimizes the risk of inconsistencies when changes are needed.pytorch/pytorch3 discussions
- Purpose-revealing identifier namesChoose identifier names that clearly reveal their purpose and behavior. Names should be specific, descriptive, and self-explanatory: - **Function names** should include verbs that indicate the action being performed or a question being answered (e.g., use `is_consistent()` rather than `consistency()`)pytorch/pytorch3 discussions
- Prefer HINTS in CMakeWhen configuring library searches in CMake, use `HINTS` instead of `PATHS` when you want to prioritize specific locations before falling back to system defaults. `HINTS` are searched before default paths, while `PATHS` are searched after default paths. This ensures that user-specified or environment-provided paths are checked first, making dependency...pytorch/pytorch3 discussions
- Parameterize similar test casesInstead of duplicating test code or using nested loops, use test parameterization to handle multiple test cases efficiently. This improves maintainability, ensures complete coverage, and makes test failures more traceable.pytorch/pytorch3 discussions
- Modular configuration designConfiguration systems should be designed with modularity and clarity in mind. When creating configuration classes or mechanisms: 1. **Separate generic from specific configurations**: Organize configuration options by their scope and applicability. Use class hierarchies or namespaces to isolate domain-specific settings from generic ones.pytorch/pytorch3 discussions
- Document configuration decisionsAlways document configuration decisions in package metadata files like `pyproject.toml` with clear comments, especially when: 1. Using deprecated formats due to technical constraintspytorch/pytorch3 discussions
- Consistent code organizationFollow consistent code organization patterns: 1. Place static definitions in .cpp files rather than headers to prevent duplicate definitions when included in multiple compilation units:pytorch/pytorch3 discussions
- Check CUDA availability firstAlways verify CUDA availability before performing CUDA-specific operations to prevent runtime errors when code runs on systems without CUDA support. When working with device-specific code:pytorch/pytorch3 discussions
- Structured configuration managementConfiguration files should follow official standards, have up-to-date tool settings, and appropriate dependency constraints. This ensures consistent behavior across environments and compatibility with the project's requirements.pydantic/pydantic3 discussions
- Preserve language conventionsWhen designing APIs that bridge between programming languages and external data formats (like JSON, XML, etc.), maintain language-specific naming conventions in your code while using aliases to accommodate external data formats. For Python APIs:pydantic/pydantic3 discussions
- Explicit over implicitAlways prefer explicit configuration settings over relying on implicit defaults or environmental behaviors in CI workflows and build configurations. This is particularly important for:pydantic/pydantic3 discussions
- Documentation formatting standardsMaintain consistent documentation formatting to ensure proper rendering and readability. Follow these key practices: 1. **Consistent code output display**: Standardize how objects are printed in examples. Either use `print(<inst>)` or `print(repr(<inst>))` consistently throughout the documentation.pydantic/pydantic3 discussions
- Categorize error typesDistinguish between different categories of errors and handle each appropriately. Specifically: 1. **Validation errors** occur during normal operation when input data doesn't match expectations. These should be caught and handled gracefully.pydantic/pydantic3 discussions
- Use configuration placeholdersAvoid hardcoding specific values like regions, timeframes, or identifiers in configuration commands, examples, or settings. Instead, use descriptive placeholders that clearly indicate the type of value required. This practice:prowler-cloud/prowler3 discussions
- Tenant-aware query optimizationAlways include tenant_id filters in database queries for multi-tenant systems to maintain data isolation and improve query performance. In ORM queries, explicitly filter by tenant_id even when using Row Level Security (RLS) as a defense-in-depth measure and to help the query optimizer.prowler-cloud/prowler3 discussions
- Pin GitHub Actions dependenciesAlways pin GitHub Actions to specific commit SHAs rather than using major version references to prevent supply chain attacks and ensure workflow stability. This practice ensures your CI/CD pipelines remain consistent and secure even if the referenced action is updated or compromised.prowler-cloud/prowler3 discussions
- Parameterize similar testsWrite maintainable tests by using pytest parametrization for similar test cases instead of duplicating test logic. This makes tests easier to read, maintain, and extend when requirements change.prowler-cloud/prowler3 discussions
- Document dependency versioningUse consistent patterns for specifying dependency versions in configuration files and document reasoning behind version constraints. Guidelines: 1. Use exact versions (`==`) for stability-critical dependenciesprowler-cloud/prowler3 discussions
- Guard privileged CI operationsWorkflows that hold secrets/tokens or that create, publish, or delete resources (registry tags, releases, packages) must never let untrusted or attacker-influenceable input decide when they run privileged or destructive steps. Concretely: (1) do not trigger token-bearing or mutating jobs on `pull_request`, since PR code/metadata is contributor-controlled —...promptfoo/promptfoo3 discussions
- AI eval config correctnessWhen writing eval/test configurations for AI models and agents, make sure each run is properly isolated and uses accurate, model-specific parameters so results stay reproducible and uncontaminated:promptfoo/promptfoo3 discussions
- document test tool optionsWhen documenting test tools, migration utilities, or testing frameworks, provide comprehensive explanations of different modes or options available, including their trade-offs and appropriate use cases. This helps developers make informed decisions about which approach best fits their testing needs.prometheus/prometheus3 discussions
- Configuration design clarityDesign configuration options to be unambiguous and self-documenting. Avoid reusing the same configuration field for different data types, as this creates confusion and maintenance burden. Instead, use explicit indicators or separate fields to handle different scenarios. Make mutual exclusivity and constraints between configuration options explicit in both...prometheus/prometheus3 discussions
- maintain clean CI configurationKeep CI/CD configuration files clean and self-documenting by removing outdated comments, using descriptive parameter names, and avoiding redundant specifications. Remove TODO comments that no longer reflect the current state of the codebase, choose parameter names that clearly indicate their scope and purpose, and rely on existing configuration files (like...prisma/prisma3 discussions
- Document configuration decisionsAdd explanatory comments to configuration files that clarify the reasoning behind non-obvious choices, feature exclusions, conditional logic, and environment-specific settings. This helps future maintainers understand why certain configurations exist and prevents accidental modifications.prisma/prisma3 discussions
- Centralize configuration logicAvoid scattering configuration defaults, validation, and loading logic across multiple functions. Instead, centralize these concerns in dedicated configuration modules or at the entry points of your application.prisma/prisma3 discussions
- avoid quadratic complexityWhen processing collections, be mindful of time complexity and avoid accidentally creating O(N²) algorithms, especially when simpler O(N) alternatives exist.prisma/prisma3 discussions
- API abstraction levelsFunctions and utilities should operate at appropriate abstraction levels without being aware of higher-level concepts or implementation details. This prevents tight coupling and improves reusability and testability.prisma/prisma3 discussions
- Organize tests properlyTests should be well-structured with clear separation of concerns, proper grouping, and appropriate cleanup mechanisms. Separate different types of tests (performance vs functional), use descriptive test blocks, and ensure proper isolation to prevent side effects between tests.prettier/prettier3 discussions
- Environment-specific error handlingSeparate development-time assertions from production error handling based on the runtime environment. Development assertions should be used to catch programming errors and validate internal assumptions during development, while production code should focus on graceful error handling with meaningful user-facing messages.prettier/prettier3 discussions
- Ensure semantic naming accuracyNames should accurately reflect the actual behavior, constraints, and purpose of the code element they represent. Misleading names create confusion and make code harder to understand and maintain.prettier/prettier3 discussions
- Validate inputs recursivelyAlways implement recursive validation and sanitization for user inputs, especially when dealing with encoded content or external data sources. Single-pass validation can be bypassed through multiple encoding layers or nested attacks.PostHog/posthog3 discussions
- Test complex logic thoroughlyWhen implementing complex business logic, state management, or algorithms with multiple edge cases, ensure comprehensive test coverage. Complex logic is prone to bugs and difficult to reason about during code review, making tests essential for maintainability and correctness.PostHog/posthog3 discussions
- optimize data loadingReview data loading operations to ensure they are properly scoped, filtered, and batched to prevent performance issues. Large datasets should be handled with appropriate pagination, filtering by relevant criteria (like date ranges), and avoiding operations that could load excessive amounts of data into memory.PostHog/posthog3 discussions
- Add explanatory tooltipsWhen UI elements have unclear functionality or purpose, add tooltips to provide immediate context and explanation. This is especially important for icons, checkboxes, and interactive elements where the behavior or consequences aren't immediately obvious to users.PostHog/posthog3 discussions
- Feature flag compatibilityDesign code to work correctly with any combination of feature flags. When implementing conditional compilation with feature flags: 1. Use conditional imports for dependencies that are only needed when certain features are enabled:pola-rs/polars3 discussions
- Favor clarity over brevityAlways prioritize code readability and maintainability over concise but cryptic implementations. Extract repeated logic into well-named helper functions, use keyword-only arguments for clearer APIs, and structure complex string operations for better readability.pola-rs/polars3 discussions
- Database API abstractionWhen designing database interaction layers, carefully consider when to create wrapper methods versus allowing direct use of underlying libraries. Add abstraction only when it provides significant value through error handling, feature consolidation, or version compatibility management.pola-rs/polars3 discussions
- Create demonstrative examplesInclude clear, concise examples in documentation that effectively demonstrate functionality. Follow these principles for better documentation examples:pola-rs/polars3 discussions
- Consistent naming standardsMaintain consistent and standardized naming throughout the codebase: 1. **Use snake_case for multi-word identifiers**: Separate words in variable names, function names, and parameters with underscores.pola-rs/polars3 discussions
- CI workflow configuration bestConfigure GitHub Actions workflows to maximize reliability and maintainability. Follow these key practices: 1. **Always test with latest patches**: Use `check-latest: true` when setting up language environments to ensure you're testing with the most recent patch versions rather than potentially outdated cached versions.pola-rs/polars3 discussions
- Pin configuration versionsAlways pin specific versions for base images, dependencies, and environment configurations to ensure reproducible builds and prevent unexpected failures from upstream changes.python-poetry/poetry3 discussions
- manage testing dependenciesEnsure testing dependencies are properly organized, avoid redundancy, and proactively manage unmaintained packages. Place testing-specific dependencies in the correct dependency groups (e.g., `group.test.dependencies` rather than `group.dev.dependencies`). Before adding new testing libraries, verify that existing dependencies don't already provide the same...python-poetry/poetry3 discussions
- maintain security constraintsAlways preserve existing security constraints and validation mechanisms rather than weakening them for convenience or functionality. When modifying authentication, validation, or security-related code, ensure that the changes maintain or strengthen the security posture.python-poetry/poetry3 discussions
- avoid redundant tool configurationWhen configuring code style tools, avoid enabling rules or settings that duplicate functionality already provided by other tools in your toolchain. This reduces configuration complexity, prevents conflicting rules, and improves maintainability.python-poetry/poetry3 discussions
- Use modern null-safe operatorsPrefer optional chaining (`?.`) and nullish coalescing (`??`) operators over verbose null checks and ternary expressions. These modern JavaScript operators provide cleaner, more readable code while preventing runtime errors from null or undefined values.microsoft/playwright3 discussions
- prefer CSS over JavaScriptUse CSS solutions instead of JavaScript state management for simple styling and interactions. This approach improves maintainability, reduces complexity, and follows web standards best practices.microsoft/playwright3 discussions
- optimize React rerendersEnsure React components avoid unnecessary rerenders by maintaining object identity in dependencies and eliminating unused state variables. When objects are recreated on every render, they cause effects and child components to re-execute unnecessarily, leading to performance issues.microsoft/playwright3 discussions
- Environment variable validationEnvironment variables should be properly validated, parsed, and have sensible fallback values. Always validate boolean environment variables using explicit string comparisons rather than truthy checks, provide clear default values, and implement proper error handling for malformed values.microsoft/playwright3 discussions
- consistent spacing gridUse consistent spacing values that follow a standardized grid system, typically multiples of 4px or 8px, rather than arbitrary values. This ensures visual consistency across the UI and makes the design system more maintainable.microsoft/playwright3 discussions
- Null-safe value handlingMake null/undefined (and “invalid/unknown”) states explicit and prevent them from flowing into non-null/non-optional operations. Apply these rules: 1) Enforce compiler null safety: enable `strictNullChecks` so the typechecker blocks `x?.foo()`/`x.foo()` on `string | null`-like values.earendil-works/pi3 discussions
- Harden auth and outputSecurity-sensitive data and sinks must be hardened before use. Concretely: 1) Auth/token validity guarantees - When returning or printing OAuth/bearer tokens, ensure the token is proactively refreshed if it’s close to expiring.earendil-works/pi3 discussions
- Explicit failure state machineWhen code has multi-step lifecycle operations (spawn/register/sync/stop) or user/config-driven behavior, make failures explicit and recoverable: model the lifecycle with a small state machine, track which resources were acquired so teardown can always run safely in reverse, and degrade gracefully with validated fallbacks and user-visible diagnostics. Also...earendil-works/pi3 discussions
- Align AI interfacesWhen coding against LLM providers, treat model capabilities and prompt/tool formats as *spec-driven interfaces*: match upstream expectations exactly, and avoid ad-hoc mappings or manual edits that can drift.earendil-works/pi3 discussions
- Use semantic namingChoose names that clearly communicate the purpose, behavior, or domain concept rather than generic or abbreviated terms. Names should be self-documenting and reflect what the entity actually does or represents.emcie-co/parlant3 discussions
- Optimize CI/CD workflowsConfigure CI/CD workflows to maximize efficiency and improve developer experience. Consider these key optimization practices: 1. **Schedule automated jobs strategically**: Use offset minutes in cron schedules to avoid GitHub Actions high load times.opentofu/opentofu3 discussions
- Names preserve cognitive contextChoose variable, function, and type names that preserve cognitive context by clearly indicating their purpose and relationship to surrounding code. Names should help readers understand the code's intent without having to deeply analyze implementation details.opentofu/opentofu3 discussions
- Explicit versus dynamic configurationsPrefer explicit hardcoded configurations over dynamic ones when the configuration changes infrequently and control is important. While dynamic configurations (like API-driven or external service-based solutions) require less maintenance, explicit configurations provide better control and predictability.opentofu/opentofu3 discussions
- Document reference standardsMaintain consistent and accurate reference practices throughout project documentation to enhance usability and maintainability. This includes: 1. **Verify link accuracy**: Ensure all document cross-references point to the correct filenames and paths. Double-check file extensions and names before submitting changes.opentofu/opentofu3 discussions
- Structured changelog documentationMaintain consistent and informative changelog documentation by following these practices: 1. Structure changelogs with an "Unreleased" section at the top where all pending changes are documented before releaseopen-telemetry/opentelemetry-python3 discussions
- Maintain consistent namingEnsure naming conventions are consistent across your codebase and related repositories. When naming commands, functions, variables, or attributes: 1. Check existing conventions in the current and related codebasesopen-telemetry/opentelemetry-python3 discussions
- Explicit CI configurationsAlways use explicit, specific configurations in CI/CD pipelines to prevent ambiguity and conflicts. This includes: 1. **Clear environment naming** - Use specific environment names to avoid test execution conflicts between components. For example, prefer `py3{8,9,10,11,12}-test-opentelemetry-proto-protobuf5` over more ambiguous patterns like...open-telemetry/opentelemetry-python3 discussions
- Test independence designTests should be designed to be independent and avoid coupling to implementation details. Use public interfaces rather than accessing internal state, prefer mocked or fake data over external dependencies, and keep tests general rather than tightly coupled to specific implementations.commaai/openpilot3 discussions
- Standardize configuration approachesWhen documenting or implementing configuration procedures, prioritize standard, unified approaches over custom or platform-specific solutions. This applies to setup scripts, environment activation, and configuration management.commaai/openpilot3 discussions
- Pin dependency versionsAlways pin specific versions of dependencies, tools, and commits in configuration files to ensure consistent behavior across environments and deployments. When pinning versions, include comments explaining the reasoning behind the specific version choice.commaai/openpilot3 discussions
- Configuration defaults consistencyEnsure configuration parameters have appropriate default values, consistent naming conventions, and centralized default management. When adding new configuration keys, consider security implications for defaults (e.g., audio recording should default to off), maintain consistent naming patterns with existing keys, and centralize default values in the...commaai/openpilot3 discussions
- Benchmark performance changesAlways include performance benchmarks when making changes that could impact execution speed, CPU usage, or resource consumption. This prevents performance regressions and validates optimization claims.commaai/openpilot3 discussions
- Use specific descriptive namesChoose names that clearly indicate the specific purpose, scope, or domain of functions, variables, and types rather than using generic terms. Generic names like `is_start`, `is_middle`, `enable_ignore` can be ambiguous and require readers to examine implementation details to understand their meaning.opengrep/opengrep3 discussions
- contextual failure handlingImplement intelligent failure handling that makes contextual decisions about retry, cleanup, and error propagation based on the type and likelihood of recovery from specific failures.opengrep/opengrep3 discussions
- centralize configuration managementConfiguration values should be defined in a single location and passed through proper data structures rather than duplicated across modules or stored in global state. This prevents inconsistencies, reduces error-prone code duplication, and improves maintainability.opengrep/opengrep3 discussions
- Validate tensor dimensionsWhen implementing AI model inference code, always validate tensor dimensions and shapes before manipulating them. Neural network outputs often have complex multi-dimensional structures that require careful handling. Adding explicit dimension checks prevents subtle runtime errors, improves code robustness, and makes debugging easier.opencv/opencv3 discussions
- Meaningful semantic namingChoose names that clearly communicate purpose and follow consistent patterns across the codebase: 1. Use generic function names when the functionality is reusable, with parameters for specific values:opencv/opencv3 discussions
- Feature flag conventionEstablish a consistent pattern for feature flags and dependency management in configuration files: 1. Use `WITH_*` or `OPENCV_ENABLE_*` variables to represent user intentions (features to enable if available)opencv/opencv3 discussions
- Cleanup before errorsAlways ensure all resources are properly released before raising errors to prevent resource leaks. This practice is essential for maintaining system stability and avoiding memory leaks in both normal and error conditions.opencv/opencv3 discussions
- Use descriptive specific namesChoose names that clearly communicate purpose and scope rather than generic or overly broad terms. Names should be specific enough to accommodate future variants and descriptive enough to indicate their function without requiring additional context.sst/opencode3 discussions
- reuse existing codeBefore implementing new functionality, check if similar utilities or patterns already exist in the codebase. Consolidate duplicate logic and leverage existing libraries to maintain consistency and reduce maintenance overhead.sst/opencode3 discussions
- Ensure naming consistencyMaintain consistent naming for the same entities across different contexts including code, documentation, APIs, and external systems. When names must differ between contexts, implement fallback mechanisms to handle variations gracefully.sst/opencode3 discussions
- avoid hardcoded configuration valuesConfiguration values such as URLs, endpoints, timeouts, and environment-specific settings should never be hardcoded in source code. Instead, they should be read from configuration files, environment variables, or other configurable sources to ensure flexibility across different environments and deployments.sst/opencode3 discussions
- Robust aiohttp NetworkingWhen implementing HTTP/multipart requests and streaming (SSE/chunked) parsing with aiohttp, follow these rules: - Prefer aiohttp’s built-in primitives for multipart bodies (e.g., MultipartWriter) instead of manually encoding file payloads or copying brittle logic from other clients.openai/openai-python3 discussions
- Regex Guardrails for FiltersWhen implementing CLI output filters (regex/pattern matchers), make the match logic algorithmically safe: add explicit bypass guards for structured/machine-readable output and use precise patterns for command variants, then lock behavior with include/exclude regression tests.diegosouzapw/OmniRoute3 discussions
- Network payload safetyWhen implementing HTTP/SSE adapters or transforming network responses/streams, enforce three rules: (1) preserve required response headers/trace metadata while normalizing body-related headers, (2) respect protocol framing so streamed events can’t merge, and (3) prevent hanging outbound calls with timeouts.diegosouzapw/OmniRoute3 discussions
- Fail-Closed Security InvariantsDefault to secure behavior when you can’t verify. If a security-relevant check (e.g., whether encrypted credentials exist) or its dependencies (e.g., DB access) fails, treat the state as unsafe and stop or require explicit recovery—never assume “nothing to decrypt.” Also, preserve cross-component encryption/decryption invariants (prefix/salt/format) so that...diegosouzapw/OmniRoute3 discussions
- Database-safe atomic updatesWhen writing/reading sensitive or destructive data, make the database do the work safely and atomically: - Prefer SQL-side filtering to avoid broad in-memory fetch/processing (e.g., add `authType` filtering in the query rather than filtering afterward).diegosouzapw/OmniRoute3 discussions
- Use portable path configurationsBuild and configuration scripts should use portable path handling techniques to ensure they work correctly across different environments and installations. ollama/ollama3 discussions
- Optimize AI implementation patternsWhen implementing AI systems, prioritize established patterns and optimizations rather than creating new implementations for existing problems. This applies to all aspects of AI development:ollama/ollama3 discussions
- Complete null checksAlways perform thorough null checks before dereferencing pointers, and ensure all operations on potentially null objects are contained within the null check block. This prevents null pointer dereferences and undefined behavior.ollama/ollama3 discussions
- AI memory managementDocument and implement proper memory management strategies for AI model inference to prevent out-of-memory errors and optimize performance. When developing AI applications or documentation:ollama/ollama3 discussions
- Enforce provider API limitsWhen mapping internal config or settings onto a third-party provider's wire format, validate against that provider's actual documented constraints instead of forwarding values unbounded or assuming a capability only applies when it is explicitly advertised. Silently passing through an over-limit value (too many array entries, a too-long identifier, an...can1357/oh-my-pi3 discussions
- Assert exercised code pathWhen a test's behavior depends on an environment-specific or conditional code path (e.g., a feature that may silently fall back to an alternate implementation), guard the environment check separately from the assertion that the intended path actually ran. Never let a test pass simply because the conditional guard was false or because the fallback occurred —...can1357/oh-my-pi3 discussions
- Abstract configuration accessUse abstraction layers to access configuration settings rather than accessing environment variables, feature flags, or other configuration sources directly. This improves maintainability by centralizing configuration logic, enabling validation, and simplifying testing.octokit/octokit.net3 discussions
- Use proper synchronization primitivesWhen implementing concurrent operations, always use appropriate synchronization mechanisms and ensure all asynchronous code paths complete properly. This includes specifying explicit timing parameters, using efficient blocking primitives, and guaranteeing promise resolution in all execution branches.nrwl/nx3 discussions
- Security terminology consistencyEnsure consistent formatting and precise terminology when documenting security-related concepts, access controls, and system boundaries. Inconsistent or imprecise language in security documentation can lead to misunderstandings about permissions, access patterns, and security mechanisms.nrwl/nx3 discussions
- Follow established naming patternsEnsure all identifiers, file references, and generated names follow established conventions and patterns rather than using arbitrary or hardcoded values. This includes using correct file extensions in imports, following consistent naming patterns for generated targets, and using template variables instead of hardcoded names in templates.nrwl/nx3 discussions
- Cache expensive calculationsAvoid recalculating expensive operations in frequently called methods by caching results and only recalculating when necessary. This is especially important in rendering loops, event handlers, and other high-frequency code paths where the same computation may be performed repeatedly with the same inputs.nrwl/nx3 discussions
- avoid redundant CI operationsCI/CD processes should eliminate unnecessary repetition and redundant operations across projects and builds. This includes avoiding repeated warning messages, preferring template-based configurations over runtime string replacements, and ensuring operations are performed once at the appropriate level rather than repeatedly for each project.nrwl/nx3 discussions
- prefer != null comparisonsWhen checking for null or undefined values, prefer the concise `!= null` comparison over explicit checks or array-based methods. This pattern effectively handles both null and undefined while preserving other falsy values like `false`, `0`, or empty strings.nuxt/nuxt3 discussions
- Check SSR contextAlways verify execution context (server vs client) before running client-specific operations in SSR applications. Many hydration errors and unexpected behaviors stem from client-only code executing during server-side rendering.nuxt/nuxt3 discussions
- Build documentation clarityEnsure build and deployment documentation clearly explains processes, outputs, and environment options to prevent CI/CD pipeline issues. Documentation should comprehensively cover build context separation, deployment targets, and generated artifacts.nuxt/nuxt3 discussions
- Benchmark algorithmic optimizationsAlways validate performance improvements with benchmarks rather than assuming algorithmic optimizations provide benefits. Many seemingly faster approaches may not deliver measurable gains or may even perform worse in practice.nuxt/nuxt3 discussions
- Provide specific error contextError messages should be specific and contextual rather than generic, helping users understand exactly what went wrong and where. When handling errors, provide detailed information about the cause and set errors on the specific fields or components that triggered them.novuhq/novu3 discussions
- Optimize database queriesStructure database queries and schemas for optimal performance by avoiding nullable fields when possible, organizing query conditions efficiently, and using targeted indexes.novuhq/novu3 discussions
- consistent naming patternsEstablish and maintain consistent naming conventions across similar components and contexts. Inconsistent naming patterns make code harder to understand, discover, and maintain.novuhq/novu3 discussions
- Use modern nullish operatorsWhen dealing with potentially null or undefined values, use optional chaining (`?.`) and nullish coalescing (`??`) operators instead of verbose conditionals. These operators make code more readable, concise, and prevent null reference errors.nodejs/node3 discussions
- Use appropriate metric typesWhen instrumenting applications with metrics, choose the correct metric type based on what you're measuring to ensure accurate and useful observability data:nodejs/node3 discussions
- Reuse computed values efficientlyMove variable declarations and computations outside of loops when their values don't change between iterations. This reduces memory allocations and avoids redundant computations, improving performance.nodejs/node3 discussions
- Resource-aware programming patternsWhen optimizing application performance, be mindful of system resource constraints and use appropriate patterns to handle different scenarios efficiently:nodejs/node3 discussions
- Export environment variables onceWhen writing shell scripts, set and export all environment variables at the top of the script rather than modifying them repeatedly throughout the script. This improves readability, maintainability, and prevents inconsistent environments between commands.nodejs/node3 discussions
- Write concise idiomatic codeFavor concise and idiomatic expressions in your Rust code to improve readability and maintainability.vercel/next.js3 discussions
- Verify workflow configuration integrityCarefully review GitHub Actions workflow configurations to prevent subtle errors that can cause CI/CD pipeline failures or unexpected behavior.vercel/next.js3 discussions
- Prefer Existence Checks in Next.js ComponentsWhen working with props, state, or other values in Next.js components that may be null, undefined, or contain error states, use existence checks rather than direct property access or value comparisons.vercel/next.js3 discussions
- Optimize data structure selectionChoose data structures that match your specific access patterns and performance requirements. The right data structure can significantly improve performance without requiring algorithm changes.vercel/next.js3 discussions
- Consistent variable style patternsMaintain consistent patterns for variable declarations and naming conventions: use const by default for variable declarations, use clear complete words in variable names instead of abbreviations, and for truthiness checks prefer simple boolean conditions unless explicit null/undefined checks are required.vercel/next.js3 discussions
- Use semantically accurate namesVariable, method, and type names should precisely reflect their actual content, purpose, or scope. Names that misrepresent what they contain or do create confusion and make code harder to understand and maintain.ChatGPTNextWeb/NextChat3 discussions
- Simplify conditional logicBreak down complex conditional expressions and control flow into simpler, more readable forms. Use early returns and guard clauses to reduce nesting and avoid unnecessary computations. Avoid chaining multiple conditions with || or && operators when the logic can be made clearer through restructuring.ChatGPTNextWeb/NextChat3 discussions
- Measure performance concernsBefore assuming performance issues exist, measure actual execution time and resource usage. When performance problems are confirmed, eliminate unnecessary operations like redundant initializations, blocking operations, or wasteful resource usage.ChatGPTNextWeb/NextChat3 discussions
- Prevent test resource leaksAlways ensure proper cleanup of resources in tests to prevent memory leaks. When using EmbeddedChannel, call readOutbound() to process all expected buffers and finish() at the end of your test to verify no resources remain and release any remaining buffers. This is particularly important for tests involving data buffers, channels, and I/O operations.netty/netty3 discussions
- Consistent dependency declarationsEnsure dependency declarations in build configuration files use concrete values rather than variables that may not resolve properly at build time. Maintain consistency between related configuration files (like BOM and aggregator POMs) to prevent build failures.netty/netty3 discussions
- Use topological sortingWhen managing dependencies between modules or components, implement a topological sorting algorithm to ensure correct initialization order. This prevents cascading errors and ensures that dependencies are properly initialized before they're used.nestjs/nest3 discussions
- Use factory providersPrefer `useFactory` over `useValue` for better performance in NestJS dependency injection, especially for large objects or complex configurations. Using `useValue` with large objects can significantly slow down application bootstrapping due to expensive module serialization.nestjs/nest3 discussions
- Prevent race conditionsWhen handling concurrent operations in asynchronous environments, avoid mutating shared state that could lead to race conditions. Instead, create operation-specific state or use immutable patterns to ensure each request path has isolated context.nestjs/nest3 discussions
- Parameterize version requirementsAlways parameterize tool and runtime versions in CI/CD configurations rather than hardcoding them. This makes your pipelines more maintainable when dependencies need updates and provides a single source of truth for version requirements.nestjs/nest3 discussions
- Optimize critical path iterationsUse appropriate iteration techniques in performance-critical code paths to minimize overhead and maximize execution speed: 1. **Use raw for loops with early termination** instead of array methods like `map` and `filter` for maximum performance:nestjs/nest3 discussions
- Graph-based dependency managementWhen managing module dependencies in a system, treat the dependencies as a directed graph and apply appropriate graph algorithms to ensure proper initialization order and prevent errors.nestjs/nest3 discussions
- reuse concurrency infrastructureAvoid implementing custom concurrency patterns when existing infrastructure is available. Before creating new debouncing, async/await, or parallel execution code, check if suitable implementations already exist in the codebase.neovim/neovim3 discussions
- prevent autocommand reentrancyGuard against reentrancy issues when operations may trigger autocommands or async events that could invalidate state or cause recursive execution. Check for existing execution context before proceeding and validate that pointers/state remain valid after operations that may trigger autocommands.neovim/neovim3 discussions
- Optimize algorithmic complexityActively identify and eliminate unnecessary computational overhead in algorithms, particularly focusing on nested loops and inefficient data operations that can significantly impact performance.neovim/neovim3 discussions
- Documentation formatting standardsEnsure documentation follows consistent formatting standards to improve readability and maintainability. This includes proper indentation of code blocks for syntax highlighting, clear separation of examples with individual explanatory comments, and concise organization of related information.neovim/neovim3 discussions
- consistent algorithm interfacesWhen designing interfaces for filtering, traversal, or search algorithms, research existing codebase patterns to maintain consistency in terminology and boolean logic. Before introducing new parameter names like "skip", "filter", "match", or "predicate", analyze which terms are already established in similar contexts.neovim/neovim3 discussions
- Secure authentication handlingAlways implement proper authentication checks and protect sensitive credentials throughout your codebase. This includes: 1. **Validate all authentication inputs properly** to prevent panics and security vulnerabilities:neondatabase/neon3 discussions
- Precise algorithm terminologyWhen implementing and documenting algorithms, use precise terminology and be explicit about metrics, operations, and data structures to avoid ambiguity and ensure correctness.neondatabase/neon3 discussions
- Performance test pragmatismWhen designing performance tests, focus on efficiency and meaningful insights rather than exhaustive combinations. Consider these principles: 1. **Limit parameter combinations** to avoid excessive test duration. For example, instead of:neondatabase/neon3 discussions
- Optimize data structuresWhen implementing algorithms, prioritize data structure choices that minimize resource usage while maintaining functionality. Consider if a simpler approach with counters, efficient state tracking, or built-in functions can replace complex custom implementations.neondatabase/neon3 discussions
- Handle all error pathsEnsure comprehensive error handling throughout the codebase by implementing proper error handling blocks, defensive validation, and thorough resource cleanup. neondatabase/neon3 discussions
- Guard against race conditionsWhen working with concurrent operations, always implement proper guards to prevent race conditions between processes. This includes: 1. Adding explicit checks before operations that might be affected by concurrent processes:neondatabase/neon3 discussions
- Extract and reuseCreate focused utility functions for repeated or complex operations instead of duplicating logic across the codebase. When implementing functionality, first check if similar code already exists that can be reused.neondatabase/neon3 discussions
- Environment-specific config defaultsDefine appropriate configuration defaults for different environments (development, testing, production) using dedicated configuration classes with sensible defaults. When test environments require different configurations than production, explicitly create separate config structures rather than hardcoding values throughout tests.neondatabase/neon3 discussions
- Document API specs completelyWhen designing and implementing APIs, always provide comprehensive specifications that clearly document all endpoints, methods, parameters, and expected responses. This should include:neondatabase/neon3 discussions
- Database before memoryWhen working with database systems that also maintain in-memory state, always update the persistent database state before updating the in-memory representation. This ensures that if a crash occurs between operations, the system can correctly rebuild its state from the database without inconsistencies or "time traveling" issues.neondatabase/neon3 discussions
- Configuration context alignmentChoose the appropriate configuration context based on how changes will be handled by the system. When defining custom configuration variables: 1. Use `PGC_POSTMASTER` for options that require a server restart or cannot be changed while the server is runningneondatabase/neon3 discussions
- Configurable cache parametersCache configurations should be runtime-configurable rather than hardcoded, with support for dynamic resizing when configuration changes. This practice improves adaptability to varying workloads and environments without requiring service restarts.neondatabase/neon3 discussions
- Cache performance preservationWhen implementing database failover or restart mechanisms, ensure performance consistency by preserving and prewarming caches. Database performance can significantly degrade after restarts due to cold caches (buffer pools, file system cache, query plan cache), especially for large workloads. neondatabase/neon3 discussions
- Avoid flaky testsTests should be designed to be deterministic and reliable to prevent wasted developer time and false confidence. Two common causes of flakiness to avoid:neondatabase/neon3 discussions
- Adaptive cache expiration strategyDesign cache expiration policies that align with actual workload patterns rather than arbitrary timeframes. For systems with varying access patterns (e.g., daily vs. monthly workloads), implement configurable TTL settings to prevent premature cache invalidation.neondatabase/neon3 discussions
- Optional Null Safety ChecksWhen code depends on possibly-missing inputs/outputs or optional attributes, do not index or read them unconditionally. Add explicit guards for presence and fall back to a safe default/overload.Tencent/ncnn3 discussions
- Eliminate Shared Mutable StateEnsure concurrent execution is race-free by (a) not storing per-inference mutable state in shared layer objects, (b) keeping OpenMP loop temporaries thread-local, and (c) using the correct synchronization primitive for the target platform.Tencent/ncnn3 discussions
- Canonical Naming and TyposUse canonical, consistently formatted identifiers across code and build files, and verify every variable/option name is spelled exactly as the build system expects.Tencent/ncnn3 discussions
- Append Only CompatibilityWhen a generated API surface (e.g., an enum/type-id) is derived from the order of a registration list, treat that order as part of the public/binary API. Never reorder, insert in the middle, or remove/disable entries in that list—add new items only by appending at the end.Tencent/ncnn3 discussions
- Safe configuration defaultsWhen writing run/config scripts, prefer *local, opt-in* environment changes and *guarded* defaults. **Rules** 1. **Don’t mutate persistent user config** (e.g., appending to `~/.bashrc`/`~/.profile`). If you need PATH changes, set them for the current process only (e.g., `export PATH=...` inside the script).karpathy/nanochat3 discussions
- Deterministic selection parsingWhen implementing algorithmic “pick/keep/max” logic, make the selected set deterministic and the ordering explicit—then compute sort/max keys using robust parsing.karpathy/nanochat3 discussions
- Determinism and compatibilityWhen working on LLM inference/engines, ensure (1) determinism tests actually test the intended invariants, (2) optional GPU-accelerated kernels are only loaded when the hardware supports them (with a safe fallback), and (3) KV-cache shape assumptions are documented accurately.karpathy/nanochat3 discussions
- Capability-Aware Fast PathsWhen optimizing for speed, make the fast path both *correct for the actual hardware* and *lightweight in implementation*. 1) Keep kernel support documentation accurate and capability-awarekarpathy/nanochat3 discussions
- Prevent element double-countingWhen working with graph structures, collections, or relationship mappings, ensure each element is processed exactly once to maintain algorithmic integrity. Implement proper tracking mechanisms to prevent duplicate counting or processing of elements, especially in scenarios involving:n8n-io/n8n3 discussions
- Pin actions securelyAlways pin GitHub Actions to specific commit hashes rather than version tags to prevent supply chain attacks and ensure build reproducibility. This practice ensures that your workflow remains stable and secure even if the action's version tag is compromised or modified.n8n-io/n8n3 discussions
- Never commit credentialsCredentials, passwords, API tokens, and database connection strings must never be committed to version control in any form, even in configuration files or Kubernetes manifests. This practice exposes sensitive information to anyone with repository access and creates security vulnerabilities.n8n-io/n8n3 discussions
- Complete error handling cycleImplement comprehensive error handling that covers prevention, recovery, and diagnosis: 1. **Prevent errors** through thorough validation before enabling actionsn8n-io/n8n3 discussions
- Use explicit optional typesWhen dealing with values that may be absent or null, always use explicit optional type wrappers instead of implicit null checks or nullable types without clear type constraints. This makes the code's intent clearer, prevents null reference errors, and improves type safety.apache/mxnet3 discussions
- Documentation clarity and formattingWhen writing documentation (README files, tutorials, API docs), ensure clarity and proper formatting: 1. **Define technical terms and concepts** - Don't assume readers are familiar with specialized terminology. Include brief explanations and relevant links for reference.apache/mxnet3 discussions
- Document environment variablesAll environment variables must be documented in the central env_var.md file with clear descriptions of their purpose, acceptable values, and effects. Use consistent naming patterns that reflect the subsystem they configure (e.g., MXNET_CUDNN_*, MXNET_MKLDNN_*) and avoid introducing new variables when existing ones can serve the same purpose.apache/mxnet3 discussions
- Document API completelyAlways provide comprehensive API documentation that clearly specifies: 1. **Parameter types** - Document all acceptable parameter types, not just specific implementations. When a parameter accepts any object that satisfies certain behavior (like iterables), explicitly state this rather than referencing a specific class.apache/mxnet3 discussions
- Consistent logging formatUse consistent string formatting in logging statements throughout the codebase. Prefer `%` style placeholders over f-strings or `.format()` in logging calls as this is more efficient when logs are filtered by level (placeholders are only evaluated if the log is actually emitted).apache/mxnet3 discussions
- Centralize synchronization logicWhen implementing concurrent operations, especially in heterogeneous computing environments (CPU/GPU), centralize synchronization management in dedicated components rather than using flags scattered throughout the codebase. This approach improves maintainability, reduces the potential for race conditions, and makes concurrency behavior more predictable.apache/mxnet3 discussions
- Centralize configuration parametersAvoid hardcoded paths and duplicated configuration values throughout the code. Instead: 1. Use dedicated configuration files for settings that appear in multiple placesapache/mxnet3 discussions
- Optimize React performance patternsPrioritize React performance by avoiding expensive operations and using proper React patterns. Key practices include: 1. **Avoid unnecessary exception throwing**: Exception dispatch is a slow operation in React 18. Instead of throwing promises directly, create helper functions to minimize performance impact:rocicorp/mono3 discussions
- enforce database constraints properlyDatabase schemas should use appropriate constraints to enforce business rules and prevent data inconsistencies. When designing tables, identify potential duplicate data scenarios and implement unique constraints to prevent them. Consider consolidating related tables when a single table with proper constraints can achieve the same goal more efficiently.rocicorp/mono3 discussions
- Versioned API Change ContractsWhen changing a user-facing interface (API/config/grammar or externally consumed resources), treat it as a versioned contract: 1) Classify change severity and reflect it in release artifactsmermaid-js/mermaid3 discussions
- Short-circuit and cacheOptimize performance-sensitive code by eliminating unnecessary work: - **Short-circuit expensive calls:** order conditions so cheap checks run first and prevent calling costly functions.mermaid-js/mermaid3 discussions
- Declarative Vue Component DataIn Vue SFCs, keep templates declarative and driven by explicit data. **Rules** 1. **Put static/config data in `<script setup>`**: define typed constants/arrays in the script rather than building or embedding data via template expressions.mermaid-js/mermaid3 discussions
- Consistent Identifier NamingUse consistent, standards-aligned naming for identifiers, especially for user-facing text/URLs and registry keys. - ID casing: Use `ID` (not `Id`) when it’s normal prose/descriptions; only use `Id` if an external API/storage contract explicitly requires it.mermaid-js/mermaid3 discussions
- Consistent Docs FormattingFor documentation, apply strict formatting rules to both code samples and embedded assets: - Use the correct fenced-code language for rendered examples: fence Mermaid diagram samples with `mermaid-example` and keep indentation consistent.mermaid-js/mermaid3 discussions
- Config schema defaultsWhen updating configuration schemas, ensure each config option is fully specified and not redundantly redefined. Apply these rules: 1) **Always set `type` and `default` for new properties** so downstream consumers get predictable behavior and the schema remains type-correct.mermaid-js/mermaid3 discussions
- CI/CD release hygieneFor any PR that affects the build/release pipeline (scripts, manifests like package.json, or release tooling), require: 1) Pipeline must be green before requesting/continuing reviewmermaid-js/mermaid3 discussions
- Data model guardrailsDefault schemas should be designed for (a) correct capacity/performance assumptions and (b) efficient, queryable storage. 1) Use correct cardinality math for sizingawslabs/mcp3 discussions
- Accurate Config GuidanceWhen documenting configuration (env vars, parameters, tuning knobs, maintenance windows), ensure the guidance is actionable and operationally accurate—not just descriptive. In particular:awslabs/mcp3 discussions
- Use design system tokensAlways use design system tokens (theme values, breakpoints, spacing units) instead of hard-coded values. This ensures consistency across the codebase and makes maintenance easier when design changes are needed.mui/material-ui3 discussions
- Maintain configuration accuracyRegularly audit configuration files to remove unused entries and ensure all configurations accurately reflect the project's requirements and intended functionality. When modifying configuration files, carefully consider the purpose of each entry and verify that changes align with the desired behavior.mui/material-ui3 discussions
- Explicit configuration resolutionAlways use explicit path resolution and document ordering requirements in configuration files to prevent environment-dependent issues. This makes configurations more reliable and self-documenting.mui/material-ui3 discussions
- Effect hook best practicesWhen using React effect hooks, follow these practices to ensure predictable behavior and prevent memory leaks: 1. **Use stable dependency arrays**: Create a reusable constant for empty dependency arrays rather than creating a new array on each render.mui/material-ui3 discussions
- Document implementation decisionsAdd explanatory comments for non-obvious implementation details, especially when maintaining backward compatibility or implementing complex logic that isn't immediately clear without context. This helps other developers understand the reasoning behind design decisions and implementation choices.mui/material-ui3 discussions
- Defensively handle nullablesWhen working with values that could be null or undefined, implement defensive coding patterns to prevent runtime errors. This practice is essential for robust React applications.mui/material-ui3 discussions
- Consistent component API patternsDesign component APIs with consistent patterns that promote extensibility and clear usage. Prefer generic prop structures like `slotProps` over specific props (such as `InputProps`, `InputLabelProps`) for better maintainability and consistency across components.mui/material-ui3 discussions
- Use safe type guardsWhen implementing type guards for nullable or unknown types, use the `in` operator and property existence checks instead of type casting. This approach provides better null safety by verifying that properties exist before accessing them, preventing runtime errors from null or undefined values.mastodon/mastodon3 discussions
- optimize network configurationsOptimize network configurations by eliminating redundancy, using modern compression standards, and properly configuring load balancing. This includes setting sensible defaults to avoid duplicative parameters, leveraging efficient compression algorithms like zstd alongside gzip for better data transfer, and implementing proper load balancing with health...mastodon/mastodon3 discussions
- optimize collection iterationsAvoid multiple passes through the same data structure when a single iteration can accomplish the same work. This reduces computational complexity and improves performance, especially for large datasets.mastodon/mastodon3 discussions
- Network resource limitsImplement protective limits for network operations to prevent resource exhaustion and denial-of-service attacks. Network operations should have bounded resource consumption to avoid overwhelming servers or clients.mastodon/mastodon3 discussions
- leverage existing configuration sourcesWhen implementing configuration logic, prefer using built-in configuration mechanisms and existing framework parameters over creating custom configuration options. This reduces complexity, improves maintainability, and follows established patterns.mastodon/mastodon3 discussions
- Extract view complexityKeep views clean and readable by extracting complex logic to appropriate locations. Move database queries with complex conditions to model scopes, extract reusable form fields to partials, and move complex conditional logic to helper methods.mastodon/mastodon3 discussions
- Complete translatable sentencesUse complete sentences in translatable strings rather than breaking them into fragments, even if this results in some repetition. Sentence fragments make translation difficult or impossible for languages with different grammatical structures, and they provide insufficient context for translators.mastodon/mastodon3 discussions
- Choose appropriate exception typesSelect exception types that match method contracts and avoid surprising behavior. Methods with names like `find_or_initialize_by_*` should not raise validation errors since the standard Rails method doesn't perform validation. Use `save` instead of `save!` when you want to handle validation errors gracefully rather than raising exceptions. Prefer standard...mastodon/mastodon3 discussions
- meaningful exception handlingException handling should provide meaningful feedback and use appropriate exception types rather than failing silently or relying on fragile string-based checks. Avoid catching exceptions without proper logging, user feedback, or recovery mechanisms. Use built-in Python exceptions when available instead of creating custom ones unnecessarily.microsoft/markitdown3 discussions
- Improve documentation discoverabilityEnsure that important information about code purpose, behavior, and context is easily discoverable through proper documentation placement and completeness. Add comprehensive docstrings to modules, classes, and functions that explain their purpose and usage. Place critical implementation details in docstrings rather than inline comments to improve...microsoft/markitdown3 discussions
- Improve code modularityOrganize code into well-structured, reusable components by extracting specific functionality into separate functions, using flexible parameter patterns, and consolidating duplicate logic. This improves readability, maintainability, and extensibility.microsoft/markitdown3 discussions
- Documentation language precisionEnsure documentation uses precise, accurate language that clearly describes functionality and highlights important behaviors users need to understand. Avoid vague or misleading terms that could confuse users about what the code actually does.microsoft/markitdown3 discussions
- Template instantiation trade-offsWhen designing algorithms that accept callbacks or function parameters, consider the trade-off between template functions and `std::function`: 1. **Templates generate code** - Each unique lambda passed to a template function creates a new instance of that entire function body, which can significantly increase binary size for large functions.maplibre/maplibre-native3 discussions
- Reserve container capacity earlyWhen using containers like `unordered_map`, `unordered_set`, or vectors in performance-critical code, always pre-allocate space by calling `reserve()` before adding elements. This prevents expensive rehashing or reallocation operations during insertion, which can cause significant performance degradation, especially in rendering loops or frequently called...maplibre/maplibre-native3 discussions
- Prefer values over pointersWhen designing classes and interfaces, prefer passing lightweight objects by value rather than using raw pointers or converting smart pointers to raw pointers using `.get()`. This eliminates the risk of null dereferences and dangling pointer issues.maplibre/maplibre-native3 discussions
- Group related propertiesDesign APIs by organizing related properties into purpose-specific structures rather than flat parameter lists. This improves clarity about which properties apply in different contexts, enhances API documentation, and makes interfaces more maintainable as they evolve.maplibre/maplibre-native3 discussions
- Externalize configuration valuesUse environment variables and external configuration mechanisms instead of hard-coding values in build scripts. This makes your build system more flexible, maintainable, and adaptable to different environments.maplibre/maplibre-native3 discussions
- Externalize config valuesReplace hardcoded "magic numbers" and environment-specific logic with externally configurable values. Use preprocessor definitions, build flags, or configuration constants to make your code adaptable to different environments and requirements.maplibre/maplibre-native3 discussions
- DRY class hierarchiesFollow the Don't Repeat Yourself (DRY) principle when designing class hierarchies. Extract common functionality into base classes and avoid duplicating state or methods in subclasses. When extending a class, delegate to parent implementations rather than redefining functionality.maplibre/maplibre-native3 discussions
- Design evolution-ready APIsDesign APIs that are both explicit in their usage and provide clear evolution paths. When designing APIs: 1. Prefer structured objects with named fields over primitive collections or multiple parameters to improve clarity and self-documentationmaplibre/maplibre-native3 discussions
- Cross-platform CI validationAlways verify that code changes work across all CI platforms before submitting. When addressing a CI issue for one platform, ensure your fix doesn't break other environments. Common cross-platform CI issues include:maplibre/maplibre-native3 discussions
- Tailwind configuration patternsFollow Tailwind CSS's recommended configuration patterns to ensure proper functionality and JIT mode compatibility. Use the `theme.extend` object for custom values like font sizes, implement plugin functions for advanced customizations like CSS variable exposure, and explicitly safelist dynamic classes when regex patterns are incompatible with JIT mode.logseq/logseq3 discussions
- Multi-arity backward compatibilityWhen extending existing API functions with new parameters, use multi-arity function definitions to maintain backward compatibility. This allows existing code to continue working unchanged while providing enhanced functionality through additional arities.logseq/logseq3 discussions
- Maintain documentation consistencyWhen modifying documentation structure or content, ensure all cross-references remain valid and avoid creating inconsistencies between related documents. Before renaming files or restructuring documentation, search for and update all internal links that reference the changed content. When platform-specific documentation exists alongside general guides,...logseq/logseq3 discussions
- Filter nil values defensivelyProactively filter out nil values from collections and validate non-empty states before processing to prevent runtime errors. This defensive approach prevents common issues like "Cannot read properties of null" errors and ensures robust data handling.logseq/logseq3 discussions
- Classify configuration properties appropriatelyEnsure configuration properties and settings are properly categorized based on their intended use, visibility, and user interaction requirements. Built-in system properties should be classified as hidden, editable, or user-visible depending on whether end users should interact with them directly.logseq/logseq3 discussions
- API input validationWhen working with APIs, always validate inputs beyond basic format checking to ensure semantic correctness and handle edge cases properly. Simple constructor calls or basic format validation may accept invalid or unexpected inputs that could cause issues downstream.logseq/logseq3 discussions
- Simplify error flowsAvoid complex, multi-layered error handling that obscures error origins and makes debugging difficult. Each error should be handled at the most appropriate level without unnecessary re-parsing or nested try-catch blocks.lobehub/lobe-chat3 discussions
- Protect sensitive dataAlways identify and properly protect sensitive data fields in your code. Sensitive information includes IP addresses, API keys, authentication tokens, personal identification data, and high-privilege credentials. lobehub/lobe-chat3 discussions
- Optimize store selectorsWrite store selectors with proper patterns to prevent unnecessary component re-renders. Use inline selector functions that extract only the needed data, and provide custom equality comparisons for complex data types like arrays and objects.lobehub/lobe-chat3 discussions
- Optimize database column typesChoose appropriate data types for database columns to improve storage efficiency and performance. Use auto-incrementing identity columns for primary keys when there are no specific semantic requirements, and select column types with proper constraints based on expected data characteristics.lobehub/lobe-chat3 discussions
- Dependency version managementUse semantic versioning ranges for dependencies instead of "latest" or overly broad ranges. Avoid "latest" as it can cause caching issues during updates. Maintain minimum required version semantics to ensure compatibility - if your code requires features from version 4.4, specify "^4.4" rather than "^4" to prevent runtime errors when using tools like pnpm...lobehub/lobe-chat3 discussions
- Consider SSR impactWhen using Next.js dynamic imports, carefully evaluate whether to disable server-side rendering (SSR) based on the component's purpose and impact on user experience.lobehub/lobe-chat3 discussions
- Configuration merging precedenceWhen merging configuration objects, always preserve existing values and follow clear precedence rules to avoid unintentionally overriding settings. Use spread operators carefully and ensure the merge logic is implemented at the appropriate layer (preferably in action/store layer rather than component level).lobehub/lobe-chat3 discussions
- Configuration file consistencyEnsure configuration values are consistent and properly coordinated across all related files (docker-compose, .env files, initialization scripts, workflows, etc.). Verify that port mappings, environment variables, and tokens don't conflict between files, and provide fallback configurations for critical settings.lobehub/lobe-chat3 discussions
- optimize CI/CD pipelinesCI/CD pipelines should be optimized for both performance and maintainability through strategic caching, script consolidation, and compilation optimization. This involves three key practices:LMCache/LMCache3 discussions
- Ensure metadata consistencyAlways persist metadata alongside data and implement proper checking mechanisms to prevent duplicates and ensure consistency in distributed storage scenarios. When writing data to storage backends, metadata should be written atomically with the data itself. Additionally, implement separate checking logic for existence vs. active operations to prevent race...LMCache/LMCache3 discussions
- Choose efficient data structuresSelect appropriate built-in data structures and algorithmic patterns that eliminate manual checks and reduce code complexity. This improves both performance and maintainability by leveraging Python's optimized implementations.LMCache/LMCache3 discussions
- Target-aware configuration handlingWhen implementing features that depend on specific compilation targets or modes, design configuration mechanisms that gracefully handle target availability differences. Provide clear detection methods for feature availability on the current target, and ensure attributes and builtins work consistently across different compilation contexts.llvm/llvm-project3 discussions
- minimize test complexityTests should be minimal and focused on the specific functionality being verified. Remove unnecessary passes, tools, or operations that aren't directly related to what's being tested to reduce noise and improve clarity.llvm/llvm-project3 discussions
- validate configuration options explicitlyWhen handling configuration options or tool types, use explicit conditional statements with proper error handling for unknown values instead of implicit fallbacks or else clauses. This prevents silent failures and makes it clear which configurations are supported.ggml-org/llama.cpp3 discussions
- systematic test coverageWhen writing tests that need to cover multiple scenarios (different data types, backend capabilities, etc.), structure them systematically rather than duplicating code or hardcoding conditional logic.ggml-org/llama.cpp3 discussions
- optimize algorithmic complexityWhen implementing or refactoring algorithms, prioritize efficient data structures and computational approaches over simpler but slower alternatives. This is especially critical in performance-sensitive code where operations may be called frequently.ggml-org/llama.cpp3 discussions
- measure algorithm performance impactChoose algorithms based on measurable performance benefits rather than theoretical complexity advantages. Start with simpler implementations and only adopt complex algorithms when they demonstrate clear performance improvements over basic approaches.ggml-org/llama.cpp3 discussions
- Maintain consistent naming patternsFollow established naming conventions in the codebase and align with original source patterns while using modern, non-deprecated alternatives. Avoid creating confusing duplication in naming structures.ggml-org/llama.cpp3 discussions
- Choose appropriate error mechanismUse GGML_ASSERT for early validation and programming errors that indicate misconfigurations, but implement graceful error handling with logging for runtime conditions where fallback options exist. Assertions should catch problems early in development, while runtime errors should provide informative feedback and allow system recovery when possible.ggml-org/llama.cpp3 discussions
- AI documentation precisionEnsure documentation for AI/ML tools and libraries is precise, complete, and properly formatted. This includes being specific about tool references, providing complete command-line option formats, and using proper markdown formatting.ggml-org/llama.cpp3 discussions
- Standardize environment versionsEnsure consistent versions of languages, tools, and dependencies across all CI/CD environments (GitHub Actions, CircleCI, local development, etc.). Inconsistent versions between environments make it difficult to reproduce issues and debug failures, as seen when using "Python 3.12 in GitHub & 3.9 elsewhere - makes it hard to figure out how to fix the broken...BerriAI/litellm3 discussions
- Prefer lightweight observability integrationsObservability integrations should minimize external dependencies and avoid patching LiteLLM's core functions. Instead of requiring users to install additional SDKs, prefer lightweight approaches using custom loggers with direct HTTP calls (like httpx) or implement CustomBatchLogger interfaces. Avoid monkey-patching completion functions as this can cause...BerriAI/litellm3 discussions
- minimize core dependenciesKeep core dependencies minimal in configuration files like pyproject.toml. Non-essential packages should be added as optional dependencies or placed in extras sections rather than as required core dependencies. This prevents package bloat and allows users to install only what they need.BerriAI/litellm3 discussions
- Ensure database consistencyMaintain data consistency by using appropriate database operations and ensuring transactional integrity when updating related fields. Choose the right ORM methods (upsert vs create) to handle potential duplicates, and ensure that updates to related fields across multiple tables happen atomically to prevent data drift.BerriAI/litellm3 discussions
- normalize config sourcesEnsure all runtime and project configuration is explicit, type-safe, and machine-independent. Motivation - Implicit or ad-hoc config (raw process.env usage, feature flags only in local env, or file:///absolute asset paths) causes type errors, unresolved imports, and “works on my machine” failures in CI and collaborators’ environments.likec4/likec43 discussions
- Behavioral CI workflow testsCI/CD workflow and release-automation checks must be deterministic and behavior-based. - Never “soft-skip” critical validations due to missing dev tooling; declare the needed test dependency (e.g., YAML parser) so the check always runs in CI.mvanhorn/last30days-skill3 discussions
- Validate environment variables strictlyImplement comprehensive validation for environment variables using a schema validation library (e.g., Zod). Include proper typing, conditional validation rules, and sensible defaults. This ensures configuration errors are caught early and prevents runtime issues.langfuse/langfuse3 discussions
- Standardize configuration valuesAlways standardize configuration values to ensure consistency, reproducibility, and maintainability: 1. **Pin specific versions** instead of using floating tags for dependencies to ensure consistent behavior across environments.langfuse/langfuse3 discussions
- Semantically correct statusUse HTTP status codes that accurately reflect the outcome of API operations. This improves API clarity and allows client applications to handle responses more intelligently.langfuse/langfuse3 discussions
- Secure external linksAlways add `rel="noopener noreferrer"` to external links that use `target="_blank"` to prevent tabnabbing attacks. This security attribute prevents malicious websites from gaining access to your window object through the opener property, which could be exploited for phishing attacks or other security breaches.langfuse/langfuse3 discussions
- Ensure algorithmic precisionWhen implementing algorithms, ensure they perform exactly the operations needed without introducing unintended side effects or limitations. Verify all calculations produce correct results and avoid assumptions that restrict applicability.langfuse/langfuse3 discussions
- Document data constraintsExplicitly document all input and output constraints directly in API definitions. For inputs, specify validation rules such as length limits, character restrictions, and value ranges. For outputs, detail the exact format of returned data structures, including array ordering, boundary conditions (inclusive/exclusive), and semantic meanings of values. This...langfuse/langfuse3 discussions
- Database migration best practicesWhen implementing database schema changes, follow these migration best practices to maintain data integrity and ensure backward compatibility: 1. **Create separate migration files** for new schema changes rather than modifying existing migrations. This ensures users who already ran previous migrations will get new fields added correctly.langfuse/langfuse3 discussions
- Consistent database namingMaintain consistent naming patterns across all database objects. Ensure that: 1. Related object names are aligned (e.g., indexes should reference their table names)langfuse/langfuse3 discussions
- Secure credential managementEnsure sensitive data like API keys, passwords, and encryption keys are stored securely and never exposed in code, configuration files, or documentation. This prevents credential leakage and unauthorized access to external services and systems.langflow-ai/langflow3 discussions
- observability documentation structureUse proper heading hierarchy instead of bold text formatting when documenting observability features like monitoring, failure points, and telemetry. This improves navigation, readability, and maintains consistent documentation structure across observability-related content.langflow-ai/langflow3 discussions
- Handle null values safelyWhen handling potentially null or undefined values, implement explicit null checks and provide safe default values rather than allowing null values to propagate through the system. This prevents null reference errors and ensures predictable behavior.langflow-ai/langflow3 discussions
- eliminate code duplicationIdentify and eliminate duplicated code by extracting shared functionality to appropriate locations. When multiple components or code sections perform identical operations, consolidate the logic into a single, reusable location such as a parent component, utility function, or shared module.langflow-ai/langflow3 discussions
- Document security implications clearlyWhen documenting features that involve sensitive data, authentication, or privileged operations, explicitly state the security implications and use appropriate warning levels to ensure users understand potential risks.langflow-ai/langflow3 discussions
- Document connection parameters clearlyWhen documenting network connections (SSH, HTTP, database, etc.), provide clear explanations of all connection parameters, their security implications, and their relationships. Don't just list placeholders - explain what each parameter represents and why it's needed.langflow-ai/langflow3 discussions
- Consistent formatting standardsMaintain consistent formatting and syntax across all documentation and code examples to improve readability and functionality. Follow established style guides and ensure uniformity in presentation.langflow-ai/langflow3 discussions
- API endpoint documentationEnsure API documentation includes all required networking components and uses proper syntax for shell commands. API examples must include authentication headers, use correct variable expansion syntax, and clearly state network configuration assumptions.langflow-ai/langflow3 discussions
- Documentation completeness checkEnsure all documentation is complete, well-formatted, and maximally useful for developers. This includes: 1. **Use proper markdown syntax** for headings, lists, code blocks, and other formatting elements to ensure documents render correctly.langchain-ai/langchainjs3 discussions
- Constructor over setterPrefer passing configuration through constructor parameters rather than setting properties after instantiation. This makes APIs more predictable, enables immutability, and clearly communicates required dependencies at creation time. Additionally, use consistent method naming conventions like `.invoke()` for primary API methods.langchain-ai/langchainjs3 discussions
- Consistent naming conventionsMaintain consistent and explicit naming conventions across your codebase that reflect: 1. **Component dependencies**: Class/function names should explicitly indicate their external dependencies and integrations to improve clarity and avoid confusion.langchain-ai/langchainjs3 discussions
- Consistent AI namingUse specific and consistent naming conventions when referencing AI services, models, and their parameters throughout your codebase. Always include the full provider name (e.g., "AzureOpenAI" instead of just "Azure") to clearly distinguish between different AI services and avoid ambiguity.langchain-ai/langchainjs3 discussions
- Chunked data processingWhen processing large arrays or data structures, implement chunked processing to avoid stack size limitations and optimize performance. Break operations into manageable chunks rather than processing everything at once.langchain-ai/langchainjs3 discussions
- AI dependency managementWhen integrating AI models and language processing libraries, follow these dependency management best practices: 1. Use specific model integration packages instead of general-purpose AI SDKs. For example:langchain-ai/langchainjs3 discussions
- Maintainable documentation hygieneDocumentation should be kept authoritative and maintainable: use stable links, avoid recommending deprecated APIs, and remove misleading/ineffective documentation details.langchain-ai/langchain3 discussions
- Fail Fast Dependency ErrorsWhen resolving dependencies or other derived configuration, never “log-and-continue” into an inconsistent internal state. Apply this standard: 1. **Validate at the source (fail fast):** validate `depends_on` (types/contents) in `AgentMiddleware.__init__()` so errors point to the middleware that provided bad input.langchain-ai/langchain3 discussions
- Explicit CI Environment ConfigMake CI and build configuration deterministic by explicitly selecting tool versions and target environments, and by ensuring monorepo config paths match what downstream generators expect.langchain-ai/langchain3 discussions
- Use table-driven testsIn Go, prefer table-driven tests over multiple separate test functions. Table tests allow for concise testing of multiple scenarios, improve code readability, and make it easier to add new test cases.kubeflow/kubeflow3 discussions
- Use snake_case in PythonFollow Python's PEP 8 naming convention by using snake_case for variables, functions, and methods rather than camelCase or other styles. This enhances readability and maintains consistency across the codebase.kubeflow/kubeflow3 discussions
- Use appropriate log levelsAlways match logging levels to the message's purpose and severity. Use log.Info for general information, log.Warn for warnings, and log.Error for error conditions. Avoid using fmt.Println for logging as it bypasses the logging framework's level-based filtering capabilities.kubeflow/kubeflow3 discussions
- Structured OWNERS filesOWNERS files must follow project documentation standards to properly reflect component ownership and maintainership. When creating or updating these files:kubeflow/kubeflow3 discussions
- Standardize build configurationsAll components should use consistent build configurations and patterns in their CI/CD setup. This includes standardizing Makefile variables, build commands, and docker build processes across repositories. Inconsistent build configurations make CI/CD pipelines difficult to maintain and can lead to confusion during development.kubeflow/kubeflow3 discussions
- Specific network access documentationWhen documenting network access methods or service connections, always provide specific commands with explicit ports and namespaces rather than general approaches. Include clear examples of how to connect to each required service and explain the underlying proxying mechanisms.kubeflow/kubeflow3 discussions
- Normalize URL pathsWhen handling URLs in web applications, consistently normalize path formats to prevent routing and service communication issues. This is especially important when working with services like Istio that expect specific URL formats (e.g., trailing slashes).kubeflow/kubeflow3 discussions
- Mark UI text i18nAll user-facing text in HTML templates should be marked for internationalization using the i18n directive. This includes labels, placeholders, error messages, and any other text displayed to users. Using the i18n directive ensures the text can be properly extracted for translation and maintains consistent internationalization throughout the application.kubeflow/kubeflow3 discussions
- Manage configuration changesCarefully manage configuration file changes to ensure consistency and minimize unintended impacts across your project. When modifying configuration files:kubeflow/kubeflow3 discussions
- Environment-aware configuration designDesign configurations that work consistently across different environments without requiring environment-specific modifications. Configurations should be parameterized and adaptable to various deployment contexts (development, production, air-gapped environments).kubeflow/kubeflow3 discussions
- Document with precisionWrite informative, consistent, and precise code comments throughout your codebase. When documenting code: 1. **Be specific with references** - When referencing external repositories or sources, link to specific versions and files, not just directories. Use precise language to describe the relationship between your code and external sources.kubeflow/kubeflow3 discussions
- Check before useAlways validate that objects, maps, and other reference types are non-nil before attempting to use them. Use early nil checks with clear returns to improve code readability and prevent null pointer exceptions.kubeflow/kubeflow3 discussions
- Standardize build configurationsMaintain consistent and standardized build configurations across the project to improve maintainability and reduce errors: 1. **Centralize dependency management** - Use shared dependency declarations rather than hardcoding versions in individual module build files. This ensures consistency across the project and makes version updates simpler.JetBrains/kotlin3 discussions
- Pin and Inline CIHarden CI/CD workflows by (1) pinning external actions/tool versions, (2) minimizing opaque third-party action wrappers when the underlying steps are small and deterministic, and (3) scoping dependency installation to the right workflow (local dev vs CI).Kong/kong3 discussions
- Isolate config stateConfigurable behavior must be isolated per plugin/consumer instance, and derived/internal values must not be injected into the schema-defined `conf` object. This prevents cross-request/config leakage and keeps schema validation predictable—especially during deprecations.Kong/kong3 discussions
- Handle AI provider specificsDifferent AI providers and models have unique requirements for input processing, output filtering, and API parameters that must be implemented correctly. When working with AI APIs, research and implement provider-specific handling rather than assuming uniform behavior across all providers.kilo-org/kilocode3 discussions
- API header managementEstablish consistent patterns for handling headers in API clients to avoid duplication and ensure predictable behavior. When designing API client interfaces, clearly define header precedence rules and avoid setting headers in multiple locations unless absolutely necessary.kilo-org/kilocode3 discussions
- validate network stateAlways validate network connectivity and cluster state before attempting network operations. Check for leader availability, partition existence, and proper metadata state to avoid unnecessary network calls and provide better error handling.apache/kafka3 discussions
- Validate configurations earlyPerform comprehensive configuration validation as early as possible in the execution flow, before any state modifications occur. This prevents invalid configurations from causing partial state changes and ensures cleaner error handling.apache/kafka3 discussions
- Use parameterized loggingUse parameterized logging with placeholders (`{}`) instead of string concatenation for better performance and readability. When logging exceptions, pass the exception object as a separate parameter to the logger rather than including its message in the format string.apache/kafka3 discussions
- Use condition-based waitingReplace fixed-time delays with condition-based waiting mechanisms to ensure reliable synchronization and avoid timing-dependent race conditions. Fixed delays like `Thread.sleep()` are unreliable because they don't guarantee the expected state change has occurred, leading to flaky tests and potential production issues.apache/kafka3 discussions
- sequence data state updatesWhen working with distributed data systems, ensure that state updates are performed in the correct conceptual order to maintain data consistency and avoid race conditions. Operations that logically depend on each other should be sequenced appropriately, and components should maintain clear ownership of their data state.apache/kafka3 discussions
- maintain naming consistencyEnsure consistent naming conventions and parameter ordering throughout the codebase. This includes maintaining consistent parameter order within classes, using established import aliases consistently, and ensuring method names accurately reflect their expected parameters and behavior.apache/kafka3 discussions
- Add proactive null checksAlways add null checks before accessing methods or properties on objects that can potentially be null, especially when dealing with Java APIs or exceptional conditions like RejectedExecutionException.apache/kafka3 discussions
- Use safe optional defaultsWhen working with optional values, prefer safe extraction methods that provide defaults rather than methods that can panic. Use `unwrap_or()`, `unwrap_or_default()`, or `unwrap_or_else()` instead of `unwrap()` to handle `None` cases gracefully.jj-vcs/jj3 discussions
- Use intuitive descriptive namesChoose names that clearly communicate purpose and intent without requiring additional documentation or context. Names should be self-explanatory to users who encounter them for the first time.jj-vcs/jj3 discussions
- documentation formatting consistencyMaintain consistent formatting and style patterns across all documentation to improve readability and user experience. This includes using proper shell command notation, consistent punctuation choices, and aligned configuration examples.jj-vcs/jj3 discussions
- Config file naming clarityUse descriptive, unambiguous names for configuration files to clearly indicate their scope and prevent user confusion about configuration hierarchy. When introducing new configuration files, especially in systems with multiple configuration layers (user, repo, workspace), choose names that explicitly indicate the scope rather than generic names that could...jj-vcs/jj3 discussions
- Use descriptive namesChoose variable and function names that clearly communicate their purpose, type, and behavior. Names should be self-documenting and immediately understandable to other developers without requiring additional context.menloresearch/jan3 discussions
- Externalize hardcoded configurationsAvoid hardcoding configuration values like ports, URLs, API endpoints, and environment-specific settings directly in source code. Instead, externalize these values to environment variables, configuration files, or dependency injection to improve maintainability and deployment flexibility.menloresearch/jan3 discussions
- Eliminate filler languageRemove unnecessary filler words and repetitive phrases that dilute clarity and assume reader incompetence. Avoid words like "essentially", "basically", "just", "simple", "easy", and repetitive phrases like "at a high level" appearing multiple times in close proximity.menloresearch/jan3 discussions
- Configuration structure clarityEnsure configuration parameters are properly structured, accurately documented, and clearly indicate their scope and purpose. Configuration hierarchies should be explicit (global, assistant-level, thread-level), parameter categories should be well-defined (init vs runtime), and documented values must match actual system behavior.menloresearch/jan3 discussions
- Concise documentation writingWrite documentation that respects user intelligence by being concise and avoiding over-explanation of obvious concepts. Assume users are "lazy but smart" - they don't need explanations like "A thread title is a title of a thread" but do need clear directions to find what they need.menloresearch/jan3 discussions
- maintain consistent naming patternsEnsure naming consistency across related components and throughout the codebase to prevent developer confusion and maintenance issues. When similar concepts use different naming variations, choose one pattern and apply it consistently.istio/istio3 discussions
- leverage kernel network structuresWhen implementing eBPF networking programs, prefer using kernel-native data structures and BPF helpers over maintaining custom eBPF maps that duplicate network routing information. The kernel already tracks IP-to-MAC mappings, interface information, and routing data through its networking stack.istio/istio3 discussions
- Early nil checksAdd nil and empty checks at the beginning of functions to prevent downstream issues and avoid unnecessary processing. This pattern improves code safety and performance by failing fast when inputs are invalid or empty.istio/istio3 discussions
- consistent log formattingMaintain consistent formatting conventions across log messages to improve code readability and debugging effectiveness. Use proper format specifiers (%v for errors, not %s), maintain consistent spacing around punctuation (no spaces before colons), and ensure consistent label semantics when logging similar data structures.istio/istio3 discussions
- Configuration documentation standardsEnsure all user-configurable options are properly documented and discoverable, while keeping configuration files clean and focused. Configuration files serve as APIs that users rely on to understand available options.istio/istio3 discussions
- avoid timing dependenciesEliminate timing dependencies in tests by using proper retry mechanisms and assertions instead of sleep statements. Sleep-based waits make tests flaky and unreliable, while retry mechanisms with conditions provide more robust test execution.istio/istio3 discussions
- avoid repeated expensive operationsAvoid performing expensive computational operations repeatedly when the same result can be achieved through better algorithm design or data structure choices. This includes avoiding sorting on each access, repeated string parsing, or complex comparisons that could be precomputed or cached.istio/istio3 discussions
- Validate stream documentationWhen updating playlist/stream documentation (e.g., .m3u EXTINF entries), ensure **both the URL and the metadata follow the documented stream-description scheme** and are **not based on player-specific behavior**.iptv-org/iptv3 discussions
- Graceful stream validationWhen adding or updating playlist entries, treat common failure causes explicitly: validate identifiers and supported URL/source formats up front, and gracefully degrade for expected runtime failures.iptv-org/iptv3 discussions
- Use descriptive variable namesAvoid single-character variables and abbreviations in favor of descriptive, full-word names that clearly communicate the variable's purpose or content. This improves code readability and makes the codebase more maintainable for other developers.vadimdemedes/ink3 discussions
- Use descriptive namesChoose variable, function, and export names that clearly communicate their purpose and content. Avoid abbreviations and ambiguous terms that could mislead other developers about what the identifier represents.vadimdemedes/ink3 discussions
- Provide clear documentation contextDocumentation should include practical context, clear explanations, and appropriate examples to help users understand both what functionality does and when to use it. Avoid confusing technical jargon and provide concrete use cases.vadimdemedes/ink3 discussions
- Fix linting root causesAddress underlying code issues rather than disabling linting rules or working around auto-formatter conflicts. When linting tools flag legitimate problems, fix the root cause instead of suppressing the warning. When auto-formatters conflict with intentional code patterns, adjust project-wide configuration rather than using local disables.vadimdemedes/ink3 discussions
- explicit type checkingAlways perform explicit type and existence checks before operations that could fail with null or undefined values. Instead of relying on truthiness checks, use specific type guards to prevent runtime errors.vadimdemedes/ink3 discussions
- Consistent code formattingMaintain consistent formatting and alignment throughout the codebase to improve readability and maintainability. This includes proper indentation for multi-line constructs, consistent spacing in documentation, and clear structural organization.vadimdemedes/ink3 discussions
- Type over primitivesUse domain-specific types instead of primitives (like strings, []byte, or generic maps) to represent domain concepts in algorithms. This makes assumptions explicit, prevents errors, and enables stronger type checking. For example, rather than passing raw byte slices for different kinds of series keys:influxdata/influxdb3 discussions
- Secure token lifecycleImplement comprehensive lifecycle controls for authentication tokens to maintain security throughout token creation, usage, and deletion processes. Essential practices include:influxdata/influxdb3 discussions
- Explicit security parametersSecurity-critical features should be implemented as required parameters rather than optional parameters or option functions. This forces developers to make explicit decisions about security settings, preventing accidental omissions that could introduce vulnerabilities.influxdata/influxdb3 discussions
- Document complete data flowsWhen documenting database systems, ensure all documentation includes complete end-to-end data flows. Both diagrams and textual descriptions should clearly indicate:influxdata/influxdb3 discussions
- Complete schema managementWhen working with database systems that have flexible schemas (like InfluxDB), ensure complete schema discovery and proper merging from all data sources before processing operations. Incomplete schema handling leads to missing columns, data corruption, or export failures.influxdata/influxdb3 discussions
- Sanitize external contentAlways sanitize and validate external content before processing or rendering it to prevent security vulnerabilities like XSS (Cross-Site Scripting) and injection attacks. This applies to HTML content from emails, user inputs, URL parameters, and any data from untrusted sources.elie222/inbox-zero3 discussions
- Remove commented out codeDelete commented-out code instead of retaining it in the codebase. Commented code creates confusion, adds maintenance overhead, and clutters the source files. If code is no longer needed, remove it entirely - version control systems will preserve the history if it needs to be referenced later.elie222/inbox-zero3 discussions
- Next.js async behaviorUnderstand and correctly implement the asynchronous behavior of Next.js APIs and components. Follow these guidelines: 1. Add `<Suspense>` boundaries around components that use hooks that can trigger suspense, such as `useSearchParams` in the Next.js App Router:elie222/inbox-zero3 discussions
- Guard against null chainsPrevent null pointer exceptions by validating object chains before accessing nested properties. Use early returns with null checks instead of optional chaining when the rest of the function depends on a non-null value.elie222/inbox-zero3 discussions
- Externalize configuration valuesConfiguration files should not contain hardcoded values for usernames, credentials, hostnames, or environment-specific settings. Instead, use environment variables, templated values, or dynamic references that can adapt to different deployment contexts.elie222/inbox-zero3 discussions
- Database type best practicesSelect appropriate data types and defaults for database columns to ensure data integrity and simplify application code. For timestamp columns, use timezone-aware types (TIMESTAMPTZ) when working across different timezones or with UTC offsets. For ID columns, configure auto-generation at the database level using functions like gen_random_uuid() rather than...elie222/inbox-zero3 discussions
- optimize with bit manipulationUse bit manipulation techniques to optimize memory usage and computational efficiency in data structures and enums. For flag enums, consistently use bit-shift notation `(1 << n)` to make bit positions explicit and enable efficient bitwise operations. For compact data representation, leverage bitfields within unions to pack multiple boolean flags into...hyprwm/Hyprland3 discussions
- configuration consistency validationWhen modifying configuration options, ensure changes are consistently applied across all relevant locations including default configuration files, documentation, example configs, and related codebases. Configuration inconsistencies create user confusion and maintenance burden.hyprwm/Hyprland3 discussions
- API identifier consistencyMaintain consistent naming conventions for API identifiers, configuration keys, and payment method types. Use snake_case for all API identifiers to ensure uniformity across the system. This includes payment method types, configuration field names, and connector specifications.juspay/hyperswitch3 discussions
- Portable, configurable settingsWhen reading environment variables or runtime-specific context, avoid relying on globals or platform-specific APIs that only work on one runtime (e.g., `globalThis.process`, `c.env` on Cloudflare Workers). Instead, use the shared, runtime-agnostic abstraction provided by the framework (e.g., `env()` from `hono/adapter`) so the same code works consistently...honojs/hono3 discussions
- Package.json consistencyWhen editing package.json, ensure all related configuration fields stay in sync. Specifically: (1) Whenever a new module is added to the `exports` map, add a matching entry in `typesVersions` so TypeScript can resolve the types for that subpath, e.g. adding `"./timeout"` to `exports` requires a corresponding `"timeout":...HONOJS/HONO3 discussions
- Minimize complexity in data transformsWhen writing algorithms that transform or traverse collections (e.g., parsing form data into nested objects, walking a trie), explicitly consider computational complexity before merging. Avoid nested-loop patterns that degrade to O(n*m) when a restructured, single- or multi-pass approach can achieve O(n+m). For example, instead of re-scanning every key for...honojs/hono3 discussions
- Eliminate CI redundancyDesign CI/CD pipelines to avoid duplicated or redundant work. Before adding a job or step, check whether its output is already produced elsewhere (e.g., don't collect coverage separately for runtimes whose tests already run as part of a broader test command) and remove jobs that add no unique value. When the same sequence of steps is repeated across...honojs/Hono3 discussions
- Secure boundary enforcementWhen code crosses security boundaries (HTTP auth, subprocess execution, or policy-driven external side effects), it must follow the established secure path and validate before acting.nousresearch/hermes-agent3 discussions
- Safe Configuration HandlingWhen configuration affects scripts (env vars, dotenv files, compatibility gates), treat it as serialized input/output and enforce correctness at three points: (1) safe encoding, (2) correct source scoping, and (3) declared bounds.nousresearch/hermes-agent3 discussions
- Guard Async State UpdatesWhen multiple async operations can be in flight (polling, optimistic mutations, React effects, REST hydration + live WebSocket deltas), older responses may arrive last and overwrite newer state. Standardize a pattern that makes each async result apply only if it is still the current/owned operation.nousresearch/hermes-agent3 discussions
- Enforce API ContractsClient and UI code must explicitly follow the real API/component contract—both for *what state transitions are allowed* and *which side effects/transport paths are actually executed*.nousresearch/hermes-agent3 discussions
- Config Defaults And OverridesWhen introducing or changing configuration options, treat the canonical config defaults and override policy as the single source of truth across runtime and provisioning.nousresearch/hermes-agent3 discussions
- Bounded, Consistent ExtrasWhenever you change feature extras or dependency constraints in config (e.g., `pyproject.toml`), apply the same compatible version range everywhere that dependency is installed or resolved, and follow the dependency policy: bounded ranges only (no bare lower bounds; no conflicting exact pins). Regenerate the lockfile after the update.nousresearch/hermes-agent3 discussions
- Assert behavior; inject inputsWhen code changes affect what the app *sends* (RPC/HTTP payloads/options) or what the app *decides* based on the environment, add targeted tests that (1) assert the exact externally observable behavior and (2) make the inputs deterministic.nousresearch/hermes-agent3 discussions
- consistent identifier namingPrefer clear, consistent, and semantic names for variables, classes, config keys, and section labels. Use these concrete rules when naming: - Use nouns for metrics/objects and verbs for actions. Prefer semantically meaningful units (e.g., use RefusalRate rather than CountRefusals) so scales are interpretable and independent of context:p-e-w/heretic3 discussions
- Explicit Absence HandlingHandle absence/unsupported data explicitly and defensively: return `None` (or a clear error) when a value cannot be produced faithfully, and don’t “auto-fix” by inventing defaults, creating missing prerequisites, or silently dropping problematic entries. This prevents misleading “success” states and subtle contract violations.ogulcancelik/herdr3 discussions
- Effective Config ValidationWhen configuration has multiple sources (env vars, CLI flags, socket overrides) and/or platform-specific test compilation, treat only the *effective* configuration as authoritative.ogulcancelik/herdr3 discussions
- Constrain UI Rule MatchingWhen building text-based state detectors (e.g., parsing a live UI/pane), treat each rule like an algorithmic classifier: make matches precise by localizing the search, anchoring invariants, and gating multi-step prompts.ogulcancelik/herdr3 discussions
- Use realistic doc examplesDocumentation should include concrete, realistic examples that demonstrate practical usage rather than abstract concepts. This helps readers better understand the functionality and improves documentation accessibility for all skill levels.helix-editor/helix3 discussions
- Semantic identifier naming patternsUse consistent naming patterns that reflect the semantic role of identifiers: 1. Constants should use UPPER_SNAKE_CASE: ``` const MAX_RETRY_COUNT = 3;helix-editor/helix3 discussions
- Optimize query performanceWhen writing tree-sitter queries, prioritize performance by choosing efficient predicates and avoiding computationally expensive operations. Use `#any-of?` instead of complex `#match?` patterns when checking against multiple literal values, as it reduces regex compilation overhead. Avoid predicates like `#has-ancestor?` which have poor performance...helix-editor/helix3 discussions
- Nest related configuration optionsGroup related configuration options into nested TOML sections rather than using flat key-value pairs. This improves readability, maintainability, and makes relationships between settings more explicit.helix-editor/helix3 discussions
- Documentation style and formattingMaintain consistent documentation style by following these guidelines: 1. Use concise, descriptive language for configuration and feature descriptionshelix-editor/helix3 discussions
- avoid version-specific documentationWhen writing build and deployment documentation, avoid hard-coding specific version numbers, toolchain assumptions, or environment-specific details that will become outdated or may not apply to all users. Instead, use generic language that describes the underlying requirement or constraint.helix-editor/helix3 discussions
- Thorough, resilient test coverageWrite tests that cover edge cases and realistic variations, not just the simplest happy path. For example, when testing a SQL validation rule for forbidden columns, also test wildcard selects (`SELECT * FROM request_response_rmt`) and nested/sub-queries, since these are common ways the restriction could be bypassed. Likewise, avoid encoding test assertions...Helicone/helicone3 discussions
- Semantically precise identifiersChoose names for variables, fields, methods, and model identifiers that precisely and unambiguously reflect their actual behavior or content, especially when similar concepts could be confused (e.g., read vs. write costs, latest vs. specific version). Avoid encoding metadata into a name when it can instead be represented as a separate structured attribute...Helicone/helicone3 discussions
- Reusable documentation snippetsWhen writing integration guides or other docs that repeat common text (titles, step names, instructions like "Create an account + Generate an API Key"), pull that content from a shared snippets file (e.g. `/snippets/strings.mdx`) instead of hardcoding it in every page. This keeps wording consistent across dozens of similar guides and lets you update copy in...Helicone/helicone3 discussions
- RESTful endpoint and type designDesign API endpoints and their request/response types deliberately. Prefer RESTful resource-based routes over verb-based ones when the HTTP method already conveys the action (e.g., `POST /prompt-2025` instead of `POST /prompt-2025/create`). Keep response types precise and minimal: only include fields that are actually returned by a given endpoint,...Helicone/helicone3 discussions
- Externalize configuration valuesAvoid hardcoding deployment-specific values—such as usernames, channel IDs, thresholds, or other identifiers—directly in source code. Instead, define them as environment variables or config entries (e.g., `CLICKHOUSE_HQL_USER` instead of a literal `"hql_user"`, or `ALERT_BANNER_ID_DELAY_IN_QUEUE`/`FIRE_ALERT_CHANNEL` as env vars rather than inline...Helicone/helicone3 discussions
- Declarative, DRY code constructionFavor declarative, immutable patterns over imperative mutation, and avoid duplicating literals or string concatenation logic across the codebase. - Build arrays/objects declaratively instead of push()-ing into a mutable array. Use spreads with conditional expressions so the structure is clear at a glance:Helicone/helicone3 discussions
- Consolidate configuration filesAvoid proliferating ad-hoc configuration files (e.g. new docker-compose variants) when existing ones can be extended or reused. Before adding a new config file, check whether an existing one (like `docker-compose.yml` for the full stack or `docker-compose-dev.yml` for infra-only) already serves that purpose, and extend it rather than creating a...Helicone/helicone3 discussions
- Proper mocking techniquesUse appropriate mocking approaches for different dependencies in tests to ensure accurate test results and prevent false positives. Different types of dependencies require different mocking strategies:grafana/grafana3 discussions
- Optimize hot pathsIdentify and optimize frequently executed code paths by moving invariant calculations and conditional logic outside of loops, recursive functions, and other performance-critical sections. This reduces repeated evaluations and improves algorithm efficiency.grafana/grafana3 discussions
- Measure before optimizingPerformance optimizations should be validated with measurements rather than assumptions. When implementing performance-sensitive code or optimizations:grafana/grafana3 discussions
- Maintain API version compatibilityWhen implementing or modifying APIs, ensure backward compatibility across versions and client interfaces. Carefully evaluate field structures, method visibility, and response formats for consistency.grafana/grafana3 discussions
- Graceful feature availabilityWhen implementing configurable features, ensure they degrade gracefully based on environment conditions like feature flags, plugin availability, or license status. Instead of showing disabled buttons or non-functional UI elements, provide informative feedback about why a feature is unavailable and how to enable it.grafana/grafana3 discussions
- Feature toggle lifecycleWhen working with feature toggles and configuration flags, manage their entire lifecycle carefully to prevent breaking changes and compatibility issues. grafana/grafana3 discussions
- Design token value consistencyWhen implementing design tokens in code, ensure values accurately represent the intended visual outcome, even if design tools have limitations. Use proper unit types that correctly translate to UI rendering rather than arbitrary numeric values.grafana/grafana3 discussions
- Complete configuration fieldsEnsure all plugin configuration files include the complete set of required fields specific to their plugin type. Missing configuration fields can cause unexpected behavior or failures when the plugin is used.grafana/grafana3 discussions
- Versioned cache coherenceWhen a cache is invalidated asynchronously, ensure *coherence* between (a) the invalidation/version signal and (b) the cached payload/derived artifacts.aaif-goose/goose3 discussions
- Use idiomatic optional patternsPrefer Rust's built-in optional handling methods over manual checks and intermediate variables. Use `if let Some(value) = option` for pattern matching, `option.map(|x| x.field).unwrap_or(default)` for transformations with fallbacks, and `option.is_some_and(|x| condition)` for conditional checks.block/goose3 discussions
- Semantic merges and sortsWhen implementing algorithms that merge incremental updates and compute ordering (grouping/sorting), ensure the algorithm matches the *producer semantics* and uses *semantically correct keys*—don’t rely on heuristic fixes.aaif-goose/goose3 discussions
- Resilient UI Failure HandlingMake UI behavior robust to failure scenarios by aligning (a) what you validate, (b) what you treat as success, and (c) how state is updated when partial failures happen.aaif-goose/goose3 discussions
- Optimize hook dependenciesUnderstand React's built-in optimizations and avoid unnecessary dependencies in hook arrays. React guarantees that state setters maintain referential stability across re-renders, so they don't need to be included in dependency arrays. Similarly, ref objects themselves don't change - only their `.current` property does, and changes to `.current` don't...block/goose3 discussions
- extract duplicated codeIdentify and eliminate code duplication by extracting shared logic into reusable functions, components, or type definitions. When you notice similar code patterns appearing in multiple places, refactor them into a single, well-named abstraction.block/goose3 discussions
- Environment-aware configuration handlingUse environment variables to control application behavior and ensure configuration changes are properly synchronized between in-memory state and persistent storage. When configuration depends on environment context, check for relevant environment variables first before falling back to defaults.block/goose3 discussions
- Document non-obvious codeAdd clear documentation for code elements that aren't immediately self-explanatory to improve readability and maintainability. This includes replacing magic numbers with named constants, adding explanatory comments for complex types, and ensuring documentation remains consistent and synchronized across different contexts.block/goose3 discussions
- default least permissiveWhen implementing security controls, always default to the most restrictive option and require explicit opt-in for more permissive behavior. This applies to authentication mechanisms, user permissions, and security scanning workflows.block/goose3 discussions
- Context-aware React StateIn React components, make UI state transitions and DOM identity depend on the *current* rendered context (route/view/filter) and the *current component instance*. This prevents stale navigation, incorrect optimistic updates, and broken label/control associations.aaif-goose/goose3 discussions
- Use benchmarked thresholdsBase performance-critical constants, limits, and thresholds on empirical benchmarking rather than arbitrary values. When implementing optimizations that involve numeric parameters—such as buffer size limits, inlining costs, or caching thresholds—conduct systematic benchmarking to determine optimal values and document the rationale.golang/go3 discussions
- Go module configurationEnsure Go projects use modern module configuration instead of legacy GOPATH setup. Projects should be created outside of GOPATH directory structure, with proper environment variable configuration and module files.golang/go3 discussions
- Write resilient testsTests should be designed to validate behavior without being brittle or sensitive to implementation details. Avoid direct string comparisons for complex data structures or binary data, as these tests can break due to formatting changes or encoding issues that don't reflect actual functional problems.gin-gonic/gin3 discussions
- Use standard API constantsAlways use standard library constants for HTTP methods and status codes rather than string literals or numeric values. This improves code readability, prevents typos, and makes it easier to maintain API consistency.gin-gonic/gin3 discussions
- Precompute over recalculatePerform expensive calculations during initialization rather than on each request, and avoid unnecessary operations in frequently executed code paths. This significantly improves performance in high-traffic applications.gin-gonic/gin3 discussions
- Early return patternPrefer returning early from functions rather than nesting conditions. When a condition can lead to an early exit, handle it immediately and return rather than wrapping the main logic in else blocks. This approach reduces nesting, improves code readability, and reduces cognitive load.gin-gonic/gin3 discussions
- Configuration file precisionEnsure configuration files are precisely maintained with correct syntax and compatible version declarations. This includes: 1. **Version compatibility**: When using language features, ensure the declared version in configuration files (e.g., go.mod) is compatible. For example, if using Go 1.20 features like `unsafe.StringData()`, ensure go.mod specifies...gin-gonic/gin3 discussions
- Prefer safe optional handlingAlways use Swift's built-in mechanisms for safely handling optional values instead of force unwrapping or manual nil handling. Specifically: 1. Use optional binding (`if let`, `guard let`) instead of checking for nil and force unwrapping:ghostty-org/ghostty3 discussions
- Encapsulate implementation detailsWhen designing APIs, create appropriate abstractions that hide platform-specific or low-level implementation details from consuming code. Avoid exposing raw interfaces outside their designated modules and minimize unnecessary dependencies.ghostty-org/ghostty3 discussions
- Define explicit error setsAlways define explicit error sets for functions that can fail, rather than using inferred error sets. This makes error handling more maintainable and helps catch missing error cases during development. The error set should be defined at the function level, even for simple APIs.ghostty-org/ghostty3 discussions
- Centralize configuration valuesHardcoded configuration values scattered throughout codebases create maintenance burdens and increase the risk of inconsistency. Define configuration values (like versions, paths, and feature flags) in a single location and reference them elsewhere.ghostty-org/ghostty3 discussions
- Centralize configuration managementAvoid hardcoded or duplicated configuration values by centralizing them in a dedicated location. When configurations are needed across multiple components, extract the logic for accessing and applying them so it can be reused. This prevents inconsistencies when configurations change and makes the codebase more maintainable.ghostty-org/ghostty3 discussions
- Remove unsupported runtime versionsWhen maintaining CI/CD pipelines, regularly audit and remove runtime versions that are no longer supported by your project's dependencies or cause build failures. This prevents pipeline instability and reduces maintenance overhead.google-gemini/gemini-cli3 discussions
- Prevent React race conditionsWhen building React components that handle rapid user input or manage complex interdependent state, consolidate state management to prevent race conditions that occur when multiple events are processed in the same React event loop.google-gemini/gemini-cli3 discussions
- Maintain consistent namingEnsure naming consistency across all contexts where an identifier appears - configuration files, code enums, documentation, and user interfaces. Names should be semantically clear and distinguish between related but different entities.google-gemini/gemini-cli3 discussions
- Document configuration defaults clearlyWhen documenting configuration options, always specify exact file paths, explicit default values, and clarify potentially confusing settings to prevent user confusion. This includes documenting where settings are persisted, what happens when optional properties are omitted, and explaining any non-obvious behavior like token budget comparisons.google-gemini/gemini-cli3 discussions
- Minimize API RoundtripsWhen the client performs a state-changing action, design the API contract so it can be completed in as few requests as possible—prefer batch-capable endpoints and responses that include what the client needs to update UI/state without additional “refresh” calls. Also, for one-way boolean updates where the server can infer intent, avoid unnecessary request...freeCodeCamp/freeCodeCamp3 discussions
- Concurrency-safe async flowsWhen UI actions can occur rapidly or in parallel (double-clicks, retries, rapid test submissions), treat them as concurrency problems: synchronize the triggering and centralize the side effects.freeCodeCamp/freeCodeCamp3 discussions
- Simplify CI scriptingKeep CI/CD workflow steps readable and maintainable by consolidating repeated commands and using basic shell utilities for log processing. Apply these rules:EbookFoundation/free-programming-books3 discussions
- Thread safety synchronizationEnsure proper synchronization when accessing shared data structures and coordinate operations across multiple threads to prevent race conditions. **Key practices:**flutter/flutter3 discussions
- Pytest fixture conventionsStandardize tests on pytest and follow its conventions for structure and fixtures. Place tests in a `tests/` directory without an `__init__.py` (pytest treats it as a plain directory, not a package), and name test files `test_*.py` so they are auto-discovered. For setup/teardown logic, prefer `yield` fixtures over `request.addfinalizer`, since they are more...pallets/flask3 discussions
- HTTP protocol correctnessWhen writing code that touches network addressing or HTTP headers, follow the exact protocol semantics rather than relying on convenient shortcuts, since subtle deviations break compatibility.pallets/flask3 discussions
- preserve error contextAlways maintain complete error information when logging or re-throwing errors to enable effective debugging and monitoring. This includes using structured logging instead of console methods, chaining original errors when throwing new ones, and ensuring underlying errors are not masked by generic error handling.firecrawl/firecrawl3 discussions
- Validate security inputsAlways validate security-critical inputs to prevent DoS attacks and injection vulnerabilities. Implement size limits, scheme restrictions, and format validation for user-controlled data that affects security mechanisms.gofiber/fiber3 discussions
- Update documentation proactivelyWhen code behavior changes, new features are added, or potential usage pitfalls are identified, proactively update all relevant documentation including API docs, inline comments, and usage warnings. This ensures developers have accurate information about execution order, blocking operations, and proper usage patterns.gofiber/fiber3 discussions
- Prefer standard library functionsWhen implementing algorithms, prioritize using standard library functions over manual implementations when they provide equivalent or better performance. The standard library is typically optimized and well-tested, making it a more reliable choice for common operations.gofiber/fiber3 discussions
- maintain clean linter configsEnsure linter configuration files are well-maintained by avoiding duplicate entries, using current non-deprecated options, and implementing security-conscious restrictions. Remove any duplicate configuration blocks, replace deprecated linters with their modern equivalents, and configure restrictive policies for dangerous imports that require explicit...gofiber/fiber3 discussions
- explicit CI/CD configurationAlways use explicit configuration in CI/CD workflows rather than relying on defaults or convenience shortcuts. This includes pinning exact tool versions, specifying action parameters explicitly, and choosing reliable installation methods.gofiber/fiber3 discussions
- Enforce secure TLS configurationAlways configure TLS connections with secure minimum version requirements and proper certificate handling. Network communications should enforce TLS 1.2 or higher to prevent security vulnerabilities from outdated protocols.gofiber/fiber3 discussions
- Clear network API documentationEnsure networking-related API documentation and descriptions are specific, clear, and include concrete implementation details rather than vague or generic statements. This helps developers understand exactly what networking functionality does and how to implement it correctly.gofiber/fiber3 discussions
- Choose descriptive property namesProperty and configuration field names should clearly communicate their purpose, behavior, and relationships to other components. Avoid ambiguous or misleading names that require additional context to understand.gofiber/fiber3 discussions
- Consistent Fastify Integration PatternsWhen implementing integrations and plugins using the Fastify framework, maintain consistent coding patterns and conventions: follow Fastify's recommended package naming conventions, ensure integrations provide clear and comprehensive documentation, use Fastify's built-in type definitions and decorators consistently, and include full RFC references when referencing external protocol standards.fastify/fastify3 discussions
- Standardize version transitionsWhen supporting multiple library versions or preparing for version deprecation in configuration-dependent code, use standardized TODO comments with consistent formatting. Always include a space after the # symbol and use the prefix "TODO:" to ensure comments can be found with standard search tools.fastapi/fastapi3 discussions
- Secure JWT authenticationImplement secure authentication using JWT tokens by following these best practices: 1. **Use secure libraries**: Prefer well-maintained libraries like `PyJWT` for JWT handling and `passlib` with bcrypt for password hashing:fastapi/fastapi3 discussions
- Proper response handlingWhen designing APIs, ensure responses adhere to HTTP semantics by: 1. Using semantic status code constants instead of magic numbers ```python # Bad raise HTTPException(status_code=400, detail="Inactive user")fastapi/fastapi3 discussions
- Preserve unset field valuesWhen implementing partial updates in FastAPI, use the `exclude_unset` parameter in Pydantic's `.dict()` or `.model_dump()` method to avoid overriding existing values with defaults. This ensures that only fields explicitly set by the client are updated, while preserving any existing values for fields not included in the request. This pattern is particularly...fastapi/fastapi3 discussions
- Explicit exception propagationAlways be explicit about how exceptions are handled, propagated, and recovered from in your code. When catching exceptions, either re-raise them or raise appropriate new exceptions to ensure proper error flow through the system.fastapi/fastapi3 discussions
- Validate untrusted external inputTreat any data that originates outside the application's trust boundary—URL/route params, HTTP headers, and caller-supplied option objects—as untrusted until it is explicitly validated or the trust relationship is configured. Do not use raw external values directly as object keys, flags, or configuration overrides, since this can lead to prototype...expressjs/Express3 discussions
- Structured release workflowsImplement a clearly defined release strategy that distinguishes between different types of changes. Create separate workflows for patch releases (typo fixes, safe dependency updates, low-risk fixes) and non-patch releases (features, breaking changes):expressjs/express3 discussions
- Purposeful style changesCode style modifications should accompany functional improvements rather than being submitted as standalone changes. When improving code, prefer modern JavaScript syntax like object spread over older patterns or external dependencies.expressjs/express3 discussions
- Preserve config defaults safelyWhen adding or modifying configuration settings, treat default values as part of the public API: do not silently change an existing default (e.g. bumping a parser limit from 1000 to 10000) unless the change is intentional and documented. If a default behavior must change, add a deprecation warning that fires only when the application relies on the implicit...Expressjs/Express3 discussions
- Implement least privilegeApply the principle of least privilege for all repository and system access to enhance security. Each role should be granted only the permissions necessary to perform their specific responsibilities:expressjs/express3 discussions
- Harden CI/CD workflowsTreat GitHub Actions workflows as part of the security attack surface, since they can run with repository write access and secrets. When referencing third-party actions, pin them to a specific commit SHA rather than a mutable tag (e.g. `v1`) to prevent supply-chain attacks if the upstream action is compromised or updated maliciously; document how pinned...expressjs/Express3 discussions
- Document release branching and accessRelease processes must be explicitly documented so that branching strategy and publishing permissions are unambiguous for every supported version. Define, for each major version being maintained, which branch acts as the "current" branch for patch releases (e.g. `master` for the latest major version, `<major>.x` for older ones) and which temporary proposal...expressjs/Express3 discussions
- Changelog observable changesWhen documenting dependency updates in History.md/CHANGELOG, only list the sub-changes that are actually observable to consumers of this module's public API — not every change present in the dependency's own changelog. Before adding a bullet, verify whether the change affects how users interact with this module; if it doesn't (e.g., the dependency dropped...Expressjs/Express3 discussions
- verify platform network compatibilityWhen adding support for new platforms or architectures, thoroughly verify that networking functionality works correctly across different runtime environments and build configurations. This includes validating Go version requirements, cross-compilation toolchain compatibility, and runtime behavior differences.evanw/esbuild3 discussions
- validate external input safelyAlways validate and sanitize external input using established libraries rather than manual string manipulation or custom parsing. External input includes user data, environment variables, command line arguments, and data from untrusted sources. Manual construction of structured data (like JSON) with user input creates injection vulnerabilities.electron/electron3 discussions
- Use semantically accurate namesChoose parameter and method names that accurately reflect their semantic meaning and implementation reality, rather than names that may be misleading or platform-specific.electron/electron3 discussions
- organize code structureMake deliberate structural decisions that improve code maintainability and readability. Consider the appropriate implementation layer, proper encapsulation patterns, and logical organization of code components.electron/electron3 discussions
- Document error handling limitationsWhen documenting error handling mechanisms, always provide complete context about how they work, including any limitations, edge cases, and alternative approaches. This prevents developers from making incorrect assumptions about behavior.electron/electron3 discussions
- defensive null checkingImplement robust null and undefined handling patterns to prevent runtime errors and maintain code reliability. Use optional chaining for safe property access, explicit null checks with early returns, and conditional property assignment to avoid unintended undefined values.electron/electron3 discussions
- Context-aware module loadingChoose appropriate module loading syntax based on your execution context and build configuration settings. Different environments have different module system capabilities that must be respected.electron/electron3 discussions
- async destruction safetyWhen destroying objects asynchronously to avoid crashes from observer notifications or other synchronous destruction issues, ensure proper cleanup ordering and add defensive null checks to handle race conditions.electron/electron3 discussions
- Stage intensive operations carefullyWhen implementing operations that consume significant system resources (CPU, memory, I/O), introduce changes gradually while monitoring performance. This prevents cascading performance issues that can degrade the entire system.elastic/elasticsearch3 discussions
- Scope and document configurationsWhen designing and implementing configuration options, carefully consider two key aspects: 1. **Choose appropriate configuration scope**: Place configuration settings at the level that makes the most sense for their purpose and usage pattern. Avoid overly granular scopes when settings could logically apply at a broader level.elastic/elasticsearch3 discussions
- Design for evolutionWhen designing APIs, prioritize flexibility and independent evolution of components. Avoid tightly coupling related services or wrapping existing components when they might evolve differently over time. Instead, design APIs with extension points and loose coupling to accommodate future changes.elastic/elasticsearch3 discussions
- Simplify and organize codeKeep code simple, direct, and well-organized by avoiding unnecessary complexity and properly structuring components. Remove redundant implementations when existing mechanisms already handle the functionality. Avoid indirect approaches when more straightforward solutions exist. Extract large components into separate files when they become unwieldy.dyad-sh/dyad3 discussions
- use default serialization methodsWhen adding new properties to serialization methods, use `WritePropertyWithDefault` and `ReadPropertyWithDefault` instead of `WriteProperty` and `ReadProperty` to maintain backwards compatibility. This ensures that older versions can still deserialize data written by newer versions by providing sensible defaults for missing properties.duckdb/duckdb3 discussions
- thoughtful configuration designWhen designing configuration options, environment variables, and build settings, follow established patterns and ensure they serve a clear purpose. Consider cross-platform compatibility, use familiar conventions (like PATH-style lists), and align configuration choices with project requirements.duckdb/duckdb3 discussions
- Maintain consistent naming patternsEnsure all new functions, files, and identifiers follow established naming conventions within the codebase. This prevents naming conflicts, maintains API consistency, and improves code readability.duckdb/duckdb3 discussions
- Guard expensive logging operationsAvoid executing expensive operations in logging code paths when logging is disabled or not needed. Always check if logging should occur before performing costly operations like string construction, formatting, or data processing for log messages.duckdb/duckdb3 discussions
- generate test data dynamicallyInstead of adding static test data files to the repository, generate test data programmatically within test cases. This approach improves test modularity, reduces repository bloat, and ensures tests are self-contained. Use temporary directories for any files that need to be written during testing.duckdb/duckdb3 discussions
- Environment variable handlingWhen working with environment variables, follow consistent naming conventions, properly check for their presence, and preserve the environment when spawning subprocesses. Use standard naming patterns (e.g., `OPENSSL_VERSION_OVERRIDE` instead of `OPEN_SSL_VERSION_OVERRIDE`), check both command-line arguments and environment variables for configuration...duckdb/duckdb3 discussions
- avoid redundant lookupsWhen working with associative containers (sets, maps, unordered_set, unordered_map), avoid performing redundant lookups by using single operations that combine lookup and insertion/modification. The common anti-pattern is to first check if an element exists with `find()`, then perform a separate `insert()` operation, which results in two hash table lookups.duckdb/duckdb3 discussions
- preserve thread-local stateWhen launching threads in DSPy, ensure that child threads inherit the parent thread's local overrides to maintain consistent behavior across concurrent executions. DSPy uses thread-local settings that must be properly propagated to avoid subtle runtime issues.stanfordnlp/dspy3 discussions
- Cache key serializationWhen implementing caching for functions that accept complex objects (dictionaries with mixed types, Pydantic models, callables), ensure proper cache key generation by filtering out non-serializable objects and converting complex types to serializable formats.stanfordnlp/dspy3 discussions
- optimize algorithmic performancePrioritize algorithmic efficiency and avoid unnecessary computational overhead, especially in type-level operations and validation logic. When multiple approaches achieve the same result, choose the one with better performance characteristics.drizzle-team/drizzle-orm3 discussions
- Use correct cache scopeWhen using branch-scoped caches (e.g., for dependency caching), make the cache scope key match the ref GitHub uses for that event. Don’t use `github.ref_name` blindly—its value differs by event (and can cause cache misses). Also, for repos with many PRs, mitigate cache thrashing by proactively deleting branch-scoped caches on a faster cadence.github/docs3 discussions
- Correct Config SemanticsWhen multiple configuration keys exist for related settings (e.g., “deployment vs model identity”), verify the runtime meaning of each key and ensure examples/placeholders reflect the correct mapping. Also ensure any conditional config logic (feature flags/version gating) is accurate, necessary, and easy to read, and that expression comparisons use the...github/docs3 discussions
- Validate security-related inputsAlways validate and sanitize all inputs that influence security-related functionality at the application level, rather than relying on underlying systems to handle invalid inputs. This prevents potential security vulnerabilities and provides clearer error messages to developers.django/django3 discussions
- Validate configuration changesBefore modifying default configuration settings, thoroughly understand and test their implications. Django's default configurations often include important safeguards that prevent subtle bugs.django/django3 discussions
- Transaction-aware task enqueuingWhen working with background tasks that depend on database changes, ensure tasks are enqueued only after the related transaction has successfully committed. This prevents tasks from operating on uncommitted or rolled-back data, avoiding race conditions and inconsistent states.django/django3 discussions
- Prefer semantic CSS selectorsUse semantic attribute-based selectors instead of structural or overly specific class names when the semantic meaning is already captured in HTML attributes. This makes CSS more maintainable by connecting styles to the actual meaning of elements rather than their position in the DOM.django/django3 discussions
- Feature flags over vendorsWhen checking for database backend capabilities, always use feature flags rather than checking specific vendor names. This makes your code more maintainable and vendor-agnostic while allowing third-party backends to implement support through the feature flag system.django/django3 discussions
- Fail predictably, loudlyDesign APIs that fail explicitly and predictably when used incorrectly. When an operation is attempted in an inappropriate state, raise a specific exception rather than returning None or an unexpected value. This helps developers catch misuse early rather than encountering subtle bugs later.django/django3 discussions
- Document accessibility decisionsWhen implementing HTML templates, add clear comments documenting accessibility-related decisions. Explain the purpose of semantic HTML elements, ARIA attributes, and screen reader considerations. This ensures that future developers understand the rationale behind these choices and preserves accessibility during code modifications.django/django3 discussions
- Consider related object cleanupWhen implementing migration operations that modify or remove database objects like fields and models, ensure all related objects (indexes, constraints, foreign keys) are properly identified and removed. Failing to handle these dependencies can leave orphaned database objects that may cause issues later.django/django3 discussions
- Break lines for readabilityFormat code with semantic line breaks that enhance readability rather than adhering strictly to character limits. When breaking long lines: 1. Break at natural semantic boundariesdjango/django3 discussions
- Async resource cleanup guaranteesWhen implementing async context managers, always ensure proper resource cleanup even during task cancellation. Use try/finally blocks to guarantee that resources are released and context state is properly restored regardless of how execution terminates.django/django3 discussions
- Validate configuration dependenciesConfiguration settings often depend on other settings or external resources to function correctly. Always implement validation to check these dependencies and provide clear error messages when requirements are not met.discourse/discourse3 discussions
- Safe configuration accessAlways verify configuration properties exist before accessing them to prevent runtime errors. Configuration settings may not be available depending on installed plugins, enabled features, or user preferences.discourse/discourse3 discussions
- prefer CSS custom propertiesUse CSS custom properties (CSS variables) instead of hardcoded values for fonts, spacing, colors, and other design tokens. This improves maintainability, enables consistent theming, and makes design system changes easier to implement across the codebase.discourse/discourse3 discussions
- Include contextual error informationError messages should include relevant contextual information such as IDs, file paths, job identifiers, and other debugging details to make troubleshooting easier. Generic error messages make it difficult to identify the specific instance or operation that failed, especially in systems processing multiple items concurrently.discourse/discourse3 discussions
- CSS modifier namingUse consistent modifier patterns with `--` prefixes for CSS classes and variables. Prefer semantic base names combined with modifiers over long descriptive names. This approach improves maintainability and creates predictable naming schemes.discourse/discourse3 discussions
- Cache expensive operationsIdentify and eliminate duplicate computations by caching results of expensive operations. This includes memoizing method calls, avoiding redundant database queries, and caching computed values that are used multiple times.discourse/discourse3 discussions
- avoid underscore prefixesDo not use underscore prefixes (`_`) for private or internal methods and properties. The team consensus is to avoid this naming convention. Instead, use one of these alternatives:discourse/discourse3 discussions
- Avoid optimization anti-patternsIdentify and eliminate code patterns that appear to be performance optimizations but actually hurt performance or negate their intended benefits. Common anti-patterns include:discourse/discourse3 discussions
- Optimize data structuresChoose appropriate built-in data structures and collection types to improve code efficiency and readability. Python's collections module and built-in data structures often provide more elegant and performant solutions than manual implementations.langgenius/dify3 discussions
- Maintain consistent organizationEnsure proper file organization and consistent import conventions throughout the codebase. Assets should be placed in designated folders, utility functions should be moved to appropriate shared locations, and import paths should follow established patterns.langgenius/dify3 discussions
- Ensure configuration consistencyMaintain consistency across configuration variables to prevent setup confusion and deployment issues. Avoid duplicate or conflicting environment variables, ensure related configuration values align, and use appropriate defaults for the deployment context.langgenius/dify3 discussions
- Conservative configuration managementBe selective and intentional with configuration choices to avoid bloat and unnecessary complexity. This applies to build configurations, development environment settings, and dependency management.langgenius/dify3 discussions
- Configuration defaults appropriatenessEnsure configuration parameters have appropriate default values and avoid hardcoded or overly specific settings. Default values should be conservative and safe for production environments, while avoiding personal assignments or environment-specific assumptions.langgenius/dify3 discussions
- Choose descriptive, unambiguous namesSelect variable, method, and property names that clearly communicate their purpose and avoid ambiguity. Prioritize semantic accuracy over brevity, and consider the context in which names will be used to prevent confusion.langgenius/dify3 discussions
- Balance CI/CD trade-offsWhen configuring CI/CD pipelines, balance comprehensive coverage and security with practical constraints like resource usage, tool compatibility, and project context. Avoid blindly applying best practices without considering their impact on functionality and efficiency.langgenius/dify3 discussions
- Semantic Precision In AlgorithmsWhen writing documentation or implementing algorithm/data-structure logic, make the *semantics* unambiguous: state the defining invariants/behavior, keep each section aligned to its exact step in the workflow, and avoid language-level ambiguity that can change correctness.kamranahmedse/developer-roadmap3 discussions
- Never edit generated JSONTreat any build/CI-generated JSON (and files under similar “public/…-content” paths) as read-only. Don’t patch them directly in PRs—changes will be overwritten or won’t propagate.kamranahmedse/developer-roadmap3 discussions
- Manage Generated ConfigsWhen working with configuration JSON files, treat them as tool- and schema-backed artifacts: - **Never manually edit auto-generated configuration/content files.** If a change is required, update the generator/template or revert the diff.kamranahmedse/developer-roadmap3 discussions
- Enforce shared code styleKeep style consistent by following the team’s codified rules for both formatting and language idioms, and enforce them via shared tooling. Apply this as a checklist:kamranahmedse/developer-roadmap3 discussions
- Lazy initialization patternsAvoid repeatedly performing expensive operations like adding event handlers, loading resources, or fetching preferences. Instead, initialize these resources once when first needed and reuse them thereafter. This prevents memory leaks, reduces unnecessary work, and improves performance.zen-browser/desktop3 discussions
- Use descriptive identifiersChoose names that clearly communicate the purpose, functionality, and usage context of variables, methods, and types. Avoid ambiguous or overly generic names that require additional context to understand.denoland/deno3 discussions
- Use backticks for identifiersWrap all code identifiers, method names, interface names, class names, and API references in JSDoc comments with backticks (`) for proper monospacing and improved readability.denoland/deno3 discussions
- network address validationWhen validating network addresses and interfaces, properly handle special address values and use protocol-specific prefixes to avoid ambiguity. Network address validation should account for standard special addresses like `INADDR_ANY` (0.0.0.0) which allows the operating system to choose an appropriate interface, rather than treating them as invalid. For...denoland/deno3 discussions
- Explain non-obvious decisionsWhen code contains non-obvious parameter choices, conditional logic, or unexpected implementation changes, add comments explaining the reasoning behind these decisions. This helps other developers understand the context and prevents confusion during code reviews.denoland/deno3 discussions
- environment loading orderEnvironment files and variables must be loaded before creating any factories, services, or components that depend on them. This ensures that environment-based configuration propagates correctly throughout the application lifecycle.denoland/deno3 discussions
- Document network APIs comprehensivelyNetwork APIs and interfaces should include comprehensive documentation with clear descriptions, practical examples, and proper configuration guidance. This is especially important for complex protocols like WebSockets, HTTPS, and specialized network transports.denoland/deno3 discussions
- Control cache lifecycleDesign cache systems so that higher-level components control when cache entries are invalidated or cleaned up, rather than having cache operations happen automatically at lower levels. This allows callers to make informed decisions about cache lifecycle based on their broader context and requirements.denoland/deno3 discussions
- Choose appropriate algorithmsWhen implementing functionality, carefully evaluate different algorithmic approaches and data structures to choose the most appropriate solution. Consider factors like performance requirements, correctness, maintainability, and whether existing libraries can be leveraged instead of custom implementations.denoland/deno3 discussions
- Add comprehensive test coverageEnsure that all functionality, especially complex or quirky features, has corresponding unit tests. When adding new features or modifying existing code, proactively identify areas that lack test coverage and add appropriate tests.denoland/deno3 discussions
- Configuration parameter validationAlways validate configuration parameters for type, range, and reasonable values before use. Provide safe defaults for optional settings and prefer explicit parameter passing over runtime environment variable modification.bytedance/deer-flow3 discussions
- Use appropriate logging levelsReserve logging statements for their appropriate purposes and levels. Use debugging-level logs (`sd_debug`) for development-time diagnostic information, and only use standard printing functions (`sd_printf`) for critical user-facing messages or error conditions. Excessive or incorrectly leveled logging creates noise in production systems and can impact...deeplearning4j/deeplearning4j3 discussions
- Parameterize configuration scriptsConfiguration scripts should use variables for values that might change or are used in multiple places, such as paths, versions, and environment-specific settings. This improves maintainability, makes updates easier, and facilitates cross-platform support.deeplearning4j/deeplearning4j3 discussions
- Eliminate redundant codeKeep code clean by removing all forms of redundancy that affect readability and maintainability. This includes: 1. Avoid duplicate macro/constant definitions that could cause conflicts or confusiondeeplearning4j/deeplearning4j3 discussions
- Clear descriptive identifiersChoose clear, self-descriptive names for all code identifiers that accurately reflect their purpose and behavior. Method names should be verbs or verb phrases that indicate their function without ambiguity. For boolean methods, use prefixes like "is", "has", or "should" followed by the condition they check.deeplearning4j/deeplearning4j3 discussions
- Avoid environment-specific pathsAlways use environment variables or configuration mechanisms instead of hardcoding paths to compilers, tools, or directories. Hardcoded paths create dependencies on specific environments and break compatibility across different platforms and CI systems.deeplearning4j/deeplearning4j3 discussions
- Always secure your locksWhen using locks or other synchronization mechanisms in concurrent code, always release locks in a finally block to ensure they are released even when exceptions occur. Failure to do so can lead to deadlocks if other threads need the same lock.deeplearning4j/deeplearning4j3 discussions
- Use explicit types在组件/页面代码中保持表达清晰、类型明确,避免冗余与 `any`。 - 布尔表达式:不要写 `flag ? true : false`,可直接传布尔值本身。 - 例如: ```tsx // bad multiple={data.is_list ? true : false}eosphoros-ai/DB-GPT3 discussions
- Configurable Search ParametersAll retrieval/exploration code (graph + vector/ANN) must be implemented as a staged algorithm with explicit, configurable search hyperparameters, and with correct graph element semantics.eosphoros-ai/DB-GPT3 discussions
- Use exact dependency versionsAlways specify exact dependency versions in package.json files instead of using version ranges (^, ~) to ensure reproducible builds and prevent accidental upgrades that could introduce breaking changes.cypress-io/cypress3 discussions
- structured debug loggingUse structured logging with object notation instead of string interpolation for debug messages to improve readability and provide better structured data. This approach makes logs more consistent and easier to parse, while also helping to consolidate related information into single log statements.cypress-io/cypress3 discussions
- Prefer semantic test selectorsWhen writing tests, prioritize semantic and accessibility-based selectors over data attributes or generic selectors. Use accessible names, roles, and text content to select elements, as these selectors validate both functionality and accessibility simultaneously.cypress-io/cypress3 discussions
- Informative error messagesError messages should be informative and include the actual values that caused the problem, not just generic descriptions. Use centralized error message utilities and ensure both the message and stack trace are properly updated.cypress-io/cypress3 discussions
- Extract inline codeExtract complex inline code elements into separate functions, components, or constants to improve readability and maintainability. This includes hardcoded strings, complex event handlers, and lengthy JSX expressions.cypress-io/cypress3 discussions
- Consistent naming patternsEstablish and enforce consistent naming conventions across different contexts in your codebase. Teams should decide on specific patterns and use linting to maintain consistency rather than mixing approaches.cypress-io/cypress3 discussions
- Clarify testing documentationEnsure that testing documentation, including changelogs, API docs, and guides, uses clear and precise language that doesn't confuse developers. Avoid ambiguous statements that might mislead users who already understand the concepts, use proper technical terminology, and provide concrete examples that reflect real-world usage patterns.cypress-io/cypress3 discussions
- Validate configurations up frontAlways validate configuration parameters and environment variables at initialization time, providing clear error messages for missing or invalid values. This helps catch configuration issues early and makes debugging easier.crewaiinc/crewai3 discussions
- Typed API client abstractionsWhen designing API clients, encapsulate responses in typed objects rather than passing raw JSON throughout your codebase. This improves maintainability, enables better error handling, and provides type safety.crewaiinc/crewai3 discussions
- Thread safety firstWhen implementing features that may run concurrently, always ensure thread safety using appropriate synchronization mechanisms: 1. Use thread-safe context variables for isolating execution contexts:crewaiinc/crewai3 discussions
- Test behavior not callsTests should validate actual system behavior rather than just verifying method calls. When writing tests, focus on asserting the expected outcomes and side effects rather than simply checking if methods were invoked.crewaiinc/crewai3 discussions
- Explicit over implicitAlways explicitly configure important system components rather than relying on implicit defaults or environment variables. Document required configuration combinations and version requirements clearly to prevent subtle errors.crewaiinc/crewai3 discussions
- Clear AI component interfacesWhen designing AI components and tools, use domain-specific terminology and provide clear interface documentation to enhance usability and integration. This includes:crewaiinc/crewai3 discussions
- Guard security state transitionsWhen code crosses a security boundary (e.g., upgrading a connection to TLS via STARTTLS, or recovering from an error during a filesystem operation), explicitly discard or re-validate any state that could have been influenced by an attacker before the boundary was crossed. Buffered plaintext data, cached untagged responses, file descriptors, or paths...python/cpython3 discussions
- Explicit API contractsWhen an API accepts objects via duck typing (e.g., checking hasattr for a method) or restricts input to specific types, make the contract explicit rather than implicit. If a function intentionally narrows behavior to an exact type or restricts duck-typed objects (e.g., `PyDict_CheckExact()` excluding dict subclasses, or a fast path assuming `BytesIO`-like...python/cpython3 discussions
- Clear unambiguous namingPick names (for functions, macros, and variables) that unambiguously convey their purpose and don't collide with existing identifiers that carry a different meaning in the same domain. Before naming, check whether a similar name already exists with different semantics elsewhere in the API/codebase (e.g. `PyFrozenSetWriter_Discard` is confusing next to...python/cpython3 discussions
- Accurate, visibility-aware namingChoose identifier names that precisely and unambiguously describe what the thing represents or does, including its scope and intended visibility. - Reflect actual behavior: a name should match what the code does, not just an initial assumption. For example, a hook described as "pre_execution" but actually used to run/execute a statement was renamed to...python/cpython3 discussions
- Vue component type safetyWhen defining Vue components with TypeScript, use appropriate component definition patterns to ensure proper type inference and avoid breaking type changes. vuejs/core3 discussions
- Use environment flags consistentlyFeature flags like `__DEV__` and `__COMPAT__` are critical configuration mechanisms that control environment-specific behavior. Always wrap development-only code (such as warnings and debug information) in `__DEV__` conditionals to ensure they don't ship to production builds. Remember that these flags are replaced at build time through tree-shaking, so...vuejs/core3 discussions
- Use configuration constantsAlways use predefined constants from `homeassistant.const` instead of string literals when accessing configuration data. For required configuration keys that must be present, use direct dictionary access (`entry.data[CONF_KEY]`) rather than `.get()` with defaults, as this provides better error handling and makes the required nature of the configuration...home-assistant/core3 discussions
- Use asyncio.gather concurrencyWhen performing multiple independent async operations, use `asyncio.gather()` to execute them concurrently instead of sequentially. This improves performance by allowing operations to run in parallel rather than waiting for each to complete before starting the next.home-assistant/core3 discussions
- Lifecycle effects managementProperly manage component lifecycle effects and cleanup in React components to prevent memory leaks and performance issues. Use appropriate dependency arrays in useEffect hooks, and ensure cleanup functions are implemented for subscriptions, event listeners, and other side effects.vuejs/core3 discussions
- configuration status accuracyEnsure that configuration file status values accurately reflect the actual implementation state. Use 'done' only when features are fully implemented, 'todo' for planned but unimplemented features, and 'exempt' for features that don't apply to the integration. Always provide clear, descriptive comments explaining why items are marked as exempt.home-assistant/core3 discussions
- API polling optimizationOptimize API polling patterns to avoid excessive calls and improve performance. Use appropriate update intervals based on data freshness requirements rather than aggressive polling schedules.home-assistant/core3 discussions
- Use established configuration patternsAlways access and set configuration values using established patterns and correct property names. Understanding the structure of configuration objects is essential to prevent bugs in your application.continuedev/continue3 discussions
- Tests must assertTest methods should contain active, uncommented code that includes at least one assertion to verify expected behavior. Commented-out test code provides zero value and creates a false sense of security by appearing to test functionality while actually testing nothing.continuedev/continue3 discussions
- Standardize LLM configurationsWhen configuring LLM providers and their capabilities, always use proper JSON syntax with quoted property names and explicitly declare all relevant capabilities. This ensures your AI models work as expected with the correct features enabled.continuedev/continue3 discussions
- Smart model selectionImplement intelligent model selection mechanisms that adapt to different scenarios instead of hardcoding specific AI models. Create abstraction layers that can:continuedev/continue3 discussions
- Memoize expensive calculationsCache computation results in React components to prevent unnecessary recalculations during re-renders, which can significantly impact application performance. Apply these optimization techniques in three key areas:continuedev/continue3 discussions
- Include concrete examplesTechnical documentation should always include concrete, working examples that demonstrate the described concepts in action. Examples clarify abstract ideas, illustrate correct usage patterns, and provide templates users can adapt to their needs.continuedev/continue3 discussions
- Enforce strict config schemasConfiguration schemas should explicitly define all required fields and validate types at compile time to prevent runtime errors. Use strict typing with clear validation rules, and avoid marking required fields as optional.continuedev/continue3 discussions
- Document configurations completelyEnsure configuration documentation is comprehensive, clear and actionable for developers. This includes: 1. **Document all possible configuration options and behaviors**, not just defaults:continuedev/continue3 discussions
- Complete dependency arraysAlways include all referenced variables in React hook dependency arrays (useEffect, useCallback, useMemo). Missing or incorrect dependencies can lead to stale closures, unexpected behavior, and difficult-to-diagnose bugs.continuedev/continue3 discussions
- Document Config SemanticsWhen adding/changing configuration, make the meaning and lifecycle of defaults explicit and consistent. Apply this standard: - **Unset vs default:** If a value should be optional, represent it as *unset* by default and ensure all code paths preserve that (avoid implicit backstop defaults that change generated behavior, e.g., DNS records).apple/container3 discussions
- Validate before value useAlways validate potentially null or empty values before use, and provide explicit default values when handling optional data. This prevents runtime errors and makes code behavior more predictable.docker/compose3 discussions
- specific defensive error handlingImplement specific exception handling and defensive programming practices to prevent generic errors from masking real issues and provide graceful degradation when operations fail.docker/compose3 discussions
- Schema changes upstream firstWhen modifying configuration schemas, always propose changes to the upstream/source repository first before implementing them locally. This practice prevents schema divergence, maintains version integrity, and ensures a single source of truth for configuration definitions.docker/compose3 discussions
- Safe collection modificationWhen modifying collections during iteration, use safe patterns to avoid subtle bugs and undefined behavior. Common unsafe patterns include modifying map values during range iteration, capturing loop variables by reference, and deleting from slices while iterating.docker/compose3 discussions
- prefer explicit readabilityChoose explicit, readable code constructs over "clever" or overly complex ones. Complex functional programming constructs, intricate ternary operators, and large list comprehensions can make code harder to understand and maintain.docker/compose3 discussions
- Pin build dependency versionsAlways pin specific versions for build dependencies and tools to prevent unexpected build failures, even when the dependency won't be shipped in the final product. While rolling tags may be convenient, explicit version pinning provides build reproducibility and prevents surprises from automatic updates.docker/compose3 discussions
- Network API precisionUse the appropriate Docker network API method based on the specific behavior you need. NetworkList and NetworkInspect have different matching behaviors that can lead to unexpected results if used incorrectly.docker/compose3 discussions
- Maintain documentation consistencyEnsure consistent terminology, precise language, and uniform formatting throughout all documentation to improve clarity and user experience. Use standardized terms consistently (e.g., "V1" and "V2" not "v1" and "v2"), choose precise wording that clearly conveys intent, and maintain consistent formatting patterns.docker/compose3 discussions
- Environment variable safetyAlways use `os.environ.get()` instead of direct dictionary access when reading environment variables to avoid KeyError exceptions. Establish clear precedence rules where command line options override environment variables, and log conflicts appropriately when incompatible configuration sources are detected.docker/compose3 discussions
- CI security boundariesMaintain strict security boundaries in CI/CD workflows by treating CI as a validation-only system and carefully managing third-party dependencies. CI should never automatically modify contributor code or commits - its role is to verify that everything is correct, not to replace proper development practices.docker/compose3 discussions
- avoid mutable defaultsNever use mutable objects (lists, dictionaries, sets) as default parameter values in function definitions. This creates a shared object across all function calls, leading to unexpected behavior where modifications persist between calls.docker/compose3 discussions
- avoid CI resource conflictsDesign CI workflows to prevent resource conflicts when multiple builds run concurrently on shared infrastructure. This includes using unique identifiers for temporary resources, minimizing container privileges, and separating CI-specific operations from local development workflows.docker/compose3 discussions
- Thenable detection and chainingWhen code must support both synchronous values and promises (e.g. user-supplied callbacks that may return a value or a Promise), detect "thenable" values by duck-typing (checking for a `.then` method) rather than using `instanceof Promise`. This is more robust and interoperable with any Promise-like implementation. Only perform async handling (await,...tj/commander.js3 discussions
- Suppress output in CLI testsWhen testing code paths that write to stderr/stdout or call process.exit (e.g. error handling, help, version output), avoid manually hijacking `process.exit`, `console.error`, or spying on `process.stderr.write`. These approaches are brittle, verbose, and pollute test output. Instead, use the library's built-in configuration hooks to suppress output and...tj/commander.js3 discussions
- Accurate documentation examplesCode examples in documentation must be technically correct, complete, and non-misleading. Before merging a doc change: - Verify any new behavior shown in an example is reflected everywhere it affects the docs (e.g., if you add an option, update the corresponding help-text example too), and add an example that demonstrates the resulting behavior (including...tj/commander.js3 discussions
- Prevent path traversalAlways validate and sanitize file paths from user input to prevent directory traversal attacks. Malicious actors can use path manipulation techniques like `../../../` sequences or absolute paths to access files outside intended directories, potentially overwriting critical system files or accessing sensitive data.comfyanonymous/ComfyUI3 discussions
- Optimize cache key designDesign cache keys to avoid performance pitfalls and ensure reliable cache behavior. Cache keys should be lightweight, hashable, and deterministic to prevent unnecessary cache misses and memory bloat.comfyanonymous/ComfyUI3 discussions
- Environment variable consistencyEnsure consistent formatting and proper usage of environment variables in Dockerfiles. Remove unnecessary quotes from ENV declarations and choose between ARG and ENV based on their intended scope - use ARG for build-time configuration that may change between builds, and ENV for runtime configuration that containers need during execution.comfyanonymous/ComfyUI3 discussions
- Propagate errors appropriatelyAllow errors to bubble up to their appropriate handling layers rather than catching them prematurely. Catching errors at incorrect levels can prevent proper error handling, recovery mechanisms, and specialized handlers (like rate limiting logic) from functioning as intended.openai/codex3 discussions
- Extract reusable logicAvoid duplicating logic across the codebase. Instead, extract common functionality into well-named helper functions or standalone utilities. This improves code readability, simplifies maintenance, and centralizes logic for easier updates.openai/codex3 discussions
- Avoid unnecessary operationsOptimize performance by eliminating operations that don't contribute meaningful value to your code's functionality. Look for three common performance drains:openai/codex3 discussions
- validate untrusted inputsAlways validate and sanitize untrusted inputs to prevent injection attacks and security vulnerabilities. This includes path inputs that could lead to directory traversal attacks and content that may contain malicious HTML entities.cline/cline3 discussions
- validate configuration valuesAlways verify configuration values against official documentation and test across target platforms before committing. Invalid configuration values can cause build failures, runtime errors, or platform-specific issues that are difficult to debug.cline/cline3 discussions
- validate algorithmic correctnessAlways verify algorithms work correctly across edge cases and boundary conditions through concrete examples and mathematical validation. Pay special attention to preventing infinite recursion and ensuring mathematical formulas produce expected results.cline/cline3 discussions
- Use theme-based stylingAlways use CSS custom properties (CSS variables) for colors and include proper accessibility attributes instead of hard-coded values. This ensures consistency with the design system and improves accessibility for users with visual impairments or different theme preferences.cline/cline3 discussions
- UI Algorithms With InvariantsWhen implementing event-driven UI behaviors that must remain correct under timing issues and dynamic DOM updates, design the logic as an algorithm with explicit invariants and ownership of state transitions.Cline/Cline3 discussions
- Trusted Hook EnforcementUse hooks and command allow-lists as *best-effort filtering*, not as a security boundary—unless the enforcement is done from a trusted location (workflow/global config), with strict input validation and conservative approvals.cline/CLINE3 discussions
- Trust boundaries and secretsDo not present easily-bypassed mechanisms as security controls, and never let untrusted or externally-controlled content influence security-sensitive behavior or gain access to secrets. Specifically:cline/cline3 discussions
- Stale-while-revalidate cache invalidationWhen caching data fetched from an external source that can change out-of-band (polling, file system, git status, etc.), avoid two common pitfalls: invalidating based on a fragile derived signature, and clobbering fresh data with a late in-flight response.cline/cline3 discussions
- Set evidence-based timeoutsConfigure timeout values based on empirical testing and user experience requirements rather than arbitrary durations. Analyze actual system behavior to determine appropriate timeout thresholds that balance responsiveness with reliability.cline/cline3 discussions
- Safe Lookups And Security CopyWhen security-relevant logic maps user-controlled strings (e.g., file paths, extensions, names) or security settings to behavior, apply two rules: 1) Use own-property lookups for key→value mappings.cline/CLINE3 discussions
- Safe lock reclamationWhen implementing cross-process synchronization with filesystem primitives (e.g. `mkdir` as a mutex), avoid time-of-check-to-time-of-use races between detecting a stale lock and acting on it. Treat lock recovery as its own critical section:cline/cline3 discussions
- Responsive UI StylingWhen styling interactive UI (tabs, drawers, dialogs), ensure layout decisions remain usable under constrained sizes and keep implementation consistent with shared UI primitives.CLINE/CLINE3 discussions
- Resilient failure recoveryDesign UI/async code so it fails safely, cleans up deterministically, and recovers when the environment changes. Apply these rules: 1) Gate irreversible transitions on successCLINE/CLINE3 discussions
- Provide configuration fallbacksAlways provide sensible default or fallback values for configuration properties to prevent undefined states that can block users or cause application errors. Configuration properties should never be left in an undefined state that prevents normal application functionality.cline/cline3 discussions
- prevent unnecessary operationsIdentify and eliminate redundant computations, network requests, and re-renders in React components to improve performance. Common patterns include memoizing functions that recreate on every render, debouncing user input to reduce API calls, and conditionally triggering side effects only when necessary.cline/cline3 discussions
- Prevent async race conditionsIdentify and prevent race conditions in asynchronous operations, especially when operations depend on each other's completion state. Race conditions occur when the timing or order of async operations affects program correctness, often leading to intermittent failures that are difficult to debug.cline/cline3 discussions
- Own-Property Safe LookupsWhen you derive keys (extensions, filenames, paths) from user-controlled input to select behavior or presentation, use *own-property safe lookups* (or `Map`) and fail to a neutral default for unknown keys. This prevents inherited/prototype properties (e.g., `__proto__`, `constructor`, `toString`) from being treated as valid entries.CLINE/cline3 discussions
- Own-Property Lookup SafetyWhen using user-derived strings (e.g., paths, filenames, extensions) to index plain JS objects as lookup tables, do not rely on inherited properties from the prototype chain. Use own-property checks (or `Map`) and add tests for malicious keys.CLINE/CLINE3 discussions
- Loopback proxy bypassWhen building custom network dispatchers, fetch wrappers, or NO_PROXY merging logic, never let proxy environment variables (HTTP_PROXY/HTTPS_PROXY/ALL_PROXY, any casing) route traffic to loopback/local addresses through a proxy. Libraries like undici's EnvHttpProxyAgent proxy everything, including localhost, whenever NO_PROXY is unset — this silently breaks...cline/cline3 discussions
- Lock Scope And WorkersWhen concurrency touches shared state, ensure (a) mutexes don’t guard blocking I/O, (b) slow/blocking operations run on dedicated worker threads, (c) state cleanup is race-safe, and (d) any external probe has a timeout and non-fatal fallback.ClInE/cLiNe3 discussions
- Locale-Safe Responsive UIWhen writing UI code, treat both layout and user-facing strings as part of the “style” contract: - **Keep controls reachable under variable content/window sizes**: prefer utility/CSS patterns that prevent overflow from cutting interactive regions (e.g., use truncation/shrinking instead of a clipping strip for tab labels; cap dialog height and allow...Cline/Cline3 discussions
- Locale-Aware UI TextWhen formatting UI output, treat localization/wording and interactive semantics as part of code style: - Build user-facing summaries from self-contained, fully translated phrases (avoid assembling with hardcoded “read/search/folder” fragments and manual punctuation).cline/CLINE3 discussions
- Identifier clarity & consistencyUse naming that precisely describes meaning (especially booleans/flags) and keep externally-relevant identifiers/assets consistent across call sites. CLINE/cline3 discussions
- Guarded Cache InvalidationWhen caching async data per key, make invalidation race-safe and avoid unnecessary reloads. **1) Invalidate with per-key generations (or version tokens)**Cline/Cline3 discussions
- Guard async state racesHooks that combine optimistic UI updates with async confirmations (debounced state, deferred promises, streamed partial messages) are prone to race conditions across timing gaps and component lifecycle transitions (unmount/remount, navigation away and back). Before writing or rendering based on an async result, validate it against the current state/identity...cline/cline3 discussions
- Graceful, bounded error handlingFor failures and malformed inputs, implement error handling that (1) degrades gracefully instead of panicking, (2) preserves correctness across partial/streamed boundaries, and (3) reports errors safely with strict bounds.CLINE/cline3 discussions
- Failure-aware error handlingAdopt failure-mode-aware error handling that (a) chooses and documents a safe fallback when behavior is ambiguous, (b) degrades gracefully instead of panicking, and (c) makes diagnostics bounded/sanitized while keeping recovery logic race- and platform-semantic correct.ClInE/cLiNe3 discussions
- Config-aware gating and linksEnsure UI and navigation that depends on environment config or feature flags are consistent, preflighted, and deterministic: - Centralize environment-specific link construction (use one URL builder so attribution and resolved base URLs apply to every button/link in the same view).ClInE/cLiNe3 discussions
- Behavior-First DocumentationWhen updating docs, ensure they describe what users and scripts can reliably rely on. Apply these rules: 1) Remove dead/no-op entries - Don’t keep options/fields in docs if they “have no effect” in the current release.ClInE/cLiNe3 discussions
- Avoid blocking with decoupled ownershipWhen concurrency involves shared state and/or synchronous callers (IPC handlers, UI main thread), follow these rules: 1) Keep global locks short - Hold the “sessions”/registry lock only long enough to find or clone a per-session handle. Release it before any blocking work.cline/CLINE3 discussions
- Avoid Blocking While LockedWhen adding or modifying concurrency, follow these rules to prevent deadlocks, UI stalls, and racey shutdowns: 1) Keep lock hold-time minimal - Only hold a shared/global lock (e.g., a sessions HashMap) to look up/replace state.Cline/Cline3 discussions
- Avoid blocking under locksWhen writing concurrent code, keep caller threads (IPC/UI/request handlers) responsive and prevent lifecycle races. Apply these rules: 1) Never perform blocking IO while holding a broad/global lock. Lock briefly to fetch/clone the needed state, then release.CLINE/cline3 discussions
- Async cache coherenceWhen caching data that arrives asynchronously (API/desktop invokes, polling, or snapshot-driven loads), make cache coherence explicit so late/stale responses can’t overwrite fresher state.cline/CLINE3 discussions
- AI provider naming clarityUse specific, unambiguous names for AI providers and models to prevent confusion when working with multiple AI services. Avoid generic names that could be mistaken for other providers or create ambiguity about the underlying service.cline/cline3 discussions
- Verify database state changesWhen testing database operations that modify schema, data, or metadata, always add comprehensive assertions to verify the expected state changes. Database operations often have side effects beyond the primary action, and tests should validate both the intended outcome and related system state.ClickHouse/ClickHouse3 discussions
- validate user inputsAlways validate and properly escape user-controlled input before incorporating it into structured data formats like JSON, SQL, XML, or command strings. Unescaped input can lead to injection vulnerabilities that allow attackers to manipulate application logic or access unauthorized data.ClickHouse/ClickHouse3 discussions
- Validate before unsafe operationsAlways validate values before performing operations that could result in undefined behavior, particularly dynamic casts and arithmetic on unsigned types that might underflow.ClickHouse/ClickHouse3 discussions
- prefer simple optimizationsWhen implementing performance optimizations, favor simple, straightforward approaches over complex solutions unless the complexity is clearly justified by significant performance gains. Complex optimizations often introduce maintenance burden, reduce code readability, and may not provide proportional benefits.ClickHouse/ClickHouse3 discussions
- Documentation completeness standardsEnsure all documentation meets completeness and formatting standards. This includes: (1) Adding language specifications to all fenced code blocks to satisfy linting requirements, (2) Including deprecation notes with clear migration guidance when removing or replacing features, and (3) Following established documentation patterns and embedding guidelines.ClickHouse/ClickHouse3 discussions
- Document mutex responsibilitiesUse Thread Safety Analysis (TSA) annotations to explicitly document which mutexes protect which variables, making thread safety relationships clear to both static analyzers and code readers.ClickHouse/ClickHouse3 discussions
- Consistent naming conventionsMaintain consistent naming conventions within your codebase, even when external specifications or APIs use different naming patterns. Internal consistency should take precedence over matching external naming styles to ensure code readability and maintainability.ClickHouse/ClickHouse3 discussions
- consistent formatting rulesMaintain consistent formatting throughout the codebase to improve readability and maintainability. This includes standardizing function declaration spacing, comment styles, pointer/reference formatting, and type naming conventions.ClickHouse/ClickHouse3 discussions
- Avoid duplicate HTTP headersEnsure HTTP headers are sent only once per response to prevent network protocol violations and connection errors. Sending headers multiple times violates HTTP protocol standards and can cause "Broken pipe" errors and connection failures.ClickHouse/ClickHouse3 discussions
- Validate security configurationsAlways validate security-related configurations and implementations to ensure they follow established security best practices. This includes verifying authentication token formats, communication protocols, and error handling mechanisms.snyk/cli3 discussions
- validate environment variables earlyEnvironment variables should be validated early in the application lifecycle with descriptive, actionable error messages. Use specific, namespaced variable names to avoid conflicts in CI/CD environments and other systems. When possible, avoid hardcoding configuration values and instead use configuration files or well-defined environment variables.snyk/cli3 discussions
- synchronize configuration valuesEnsure configuration values remain consistent and aligned across all related files, environments, and systems. When updating versions, parameters, or settings in one location, verify and update corresponding values in other configuration files to prevent mismatches that can lead to build failures or environment pollution.snyk/cli3 discussions
- optimize CI resource allocationMatch CI/CD resource allocation to actual job requirements rather than using oversized configurations globally. Create specialized executors and resource classes for different job types to optimize cost and performance.snyk/cli3 discussions
- defensive shell script configurationConfigure shell scripts with defensive practices to ensure reliability and debuggability. Use appropriate `set` options for error handling and debugging, implement safe defaults that require explicit opt-in for risky operations, and preserve execution state when changing directories.snyk/cli3 discussions
- Configuration naming consistencyEnsure configuration elements (environment variables, feature flags, config files) maintain consistent naming and clear documentation across code, logs, and documentation. Mismatched names between implementation and logging/documentation create confusion and debugging difficulties.snyk/cli3 discussions
- Balance concurrent operationsWhen implementing concurrent operations, carefully balance performance gains with resource consumption and system stability. Set conservative concurrency limits initially and adjust based on performance metrics rather than assuming higher parallelism is always better.snyk/cli3 discussions
- Standardize shell flagsAlways use `set -eou pipefail` at the beginning of shell scripts to ensure consistent error handling and behavior across the codebase. This combination provides important safety guarantees:chef/chef3 discussions
- Remove commented codeAvoid leaving commented-out code in the codebase. Version control systems already track the history of changes, making commented-out code unnecessary. Removing unused commented code improves readability, reduces confusion, and keeps the codebase clean.chef/chef3 discussions
- Fail fast principleDesign CI/CD pipelines to fail quickly and visibly rather than masking errors through excessive retries or complex conditions. When a build step fails, it should fail immediately with clear error reporting to reduce debugging time and enable faster remediation.chef/chef3 discussions
- Clear abstraction boundariesDesign APIs with clear and consistent abstraction boundaries to maintain code quality and prevent interface leakage between different system layers. chef/chef3 discussions
- Validate configurations correctlyWhen writing validation logic for configurations, ensure you're using the appropriate operators that correctly test for the intended state. Incorrect validation operators can lead to false results and security vulnerabilities.bridgecrewio/checkov3 discussions
- Support all target environmentsWhen managing dependency configurations (Pipfiles, requirements.txt, lock files), ensure compatibility with all supported environments in your project. Package version requirements should work across all supported Python versions and deployment environments.bridgecrewio/checkov3 discussions
- Comprehensive security scanningAlways configure security scanning tools with comprehensive coverage and readable output to maximize vulnerability detection. This includes: 1. **Enable scanning across all files**: Use flags like `--enable-secret-scan-all-files` to ensure no potential vulnerability is missed.bridgecrewio/checkov3 discussions
- Backward compatible parametersWhen evolving API function signatures, maintain backward compatibility by making new parameters optional with sensible defaults. This allows existing code to continue working while supporting new functionality. When modifying parameters, carefully consider the complete data structure being passed, especially for collections and complex objects.bridgecrewio/checkov3 discussions
- Config object design clarityWhen designing constructor or configuration APIs, prefer a single, explicit options object over positional primitive arguments, since primitives like `new Chalk(false)` are ambiguous and hard to extend. Favor `new Chalk({enabled: false})` so the intent is self-documenting and new options can be added without breaking the signature.chalk/chalk3 discussions
- Accurate, consistent doc commentsDoc comments and type definitions must precisely describe the full behavior of the API, not just a subset. If a type or function supports more options than are explicitly listed (e.g., additional colors beyond the named enum values), state this clearly and link to the canonical reference for the complete details, rather than letting the comment imply an...chalk/chalk3 discussions
- Split Dependency InstallsWhen building Docker images, optimize dependency installation for both caching and resource limits. Apply these rules: 1) **Maximize layer caching:** install Python requirements *before* copying your application source.celery/celery3 discussions
- Environment-consistent buildsWhen building/installing Python dependencies in Docker/CI for multiple Python versions, keep the environment deterministic and aligned across interpreters: use the same dependency constraint/lock inputs everywhere and ensure the packaging toolchain is consistent per interpreter.celery/celery3 discussions
- validate business logic constraintsBefore adding database constraints or designing schema relationships, thoroughly understand the underlying business logic and data relationships. Constraints that seem logical at first glance may break existing functionality or prevent valid use cases.calcom/cal.com3 discussions
- Keep API handlers thinAPI handlers should be lightweight and focused on request/response handling, not business logic. Extract specific parameters from requests and delegate complex operations to dedicated services rather than handling everything in the controller.calcom/cal.com3 discussions
- Favor component compositionDesign components to be configurable through props rather than relying on external context like URL paths or modifying shared UI components directly. This approach improves reusability, maintainability, and reduces coupling between components and their usage contexts.calcom/cal.com3 discussions
- Contextual error responsesChoose error response strategies based on the error's origin, caller context, and downstream impact rather than blindly propagating upstream errors. Consider whether throwing a 5xx error will cause harmful retries or mislead about the actual source of the problem.calcom/cal.com3 discussions
- comprehensive security checksEnsure that security checks for authorization, authentication, and information disclosure are comprehensive and consistently applied across all contexts, rather than being conditional on specific scenarios or implementation details.calcom/cal.com3 discussions
- Avoid nested ternariesAvoid using nested ternary operators as they significantly reduce code readability and make debugging difficult. Complex conditional logic should be refactored into clear, readable structures using if-else statements, early returns, or extracted helper functions.calcom/cal.com3 discussions
- Avoid hardcoded configuration valuesExtract hardcoded configuration values into constants, environment variables, or function parameters to improve maintainability and flexibility. Magic numbers, provider names, file size limits, and other configuration values should not be embedded directly in business logic.calcom/cal.com3 discussions
- Verify assertions properlyEnsure test assertions correctly validate the intended behavior by: 1. **Awaiting promise assertions** when testing async code: ```javascript // PROBLEMATIC: Test may pass even if promise never resolvesoven-sh/bun3 discussions
- Technical documentation accuracyDocumentation must precisely reflect the current state of the codebase to prevent confusion and ensure developers can rely on it. Ensure that: 1. References to packages, tools, or features that have been removed or renamed are updated or deleted from documentationoven-sh/bun3 discussions
- Respect existing configurationsWhen integrating with external services or tools, design your configuration options to respect users' existing environment settings rather than overriding them with hardcoded defaults. This ensures your tool works seamlessly within various environments and avoids disrupting users' workflows.oven-sh/bun3 discussions
- Never swallow errorsAlways ensure errors are properly surfaced rather than silently ignored. Silent error handling can lead to confusing behavior where features fail without any indication of what went wrong, making debugging difficult or impossible.oven-sh/bun3 discussions
- Maintain portable config valuesAlways use portable, environment-agnostic values in configuration files. Avoid hardcoded absolute paths, system-specific values, or mismatched feature flags. Instead:oven-sh/bun3 discussions
- Deterministic lock managementAlways ensure locks are acquired and released in a deterministic manner in concurrent code. Use `defer` statements immediately after lock acquisition to guarantee release along all code paths, and acquire locks before accessing the protected resources to prevent race conditions.oven-sh/bun3 discussions
- validate file inputsAll file-related operations must implement comprehensive input validation and sanitization to prevent path traversal attacks, arbitrary file system access, and execution of malicious content. This is especially critical when handling user-provided file paths or when systems interact with AI agents that could be manipulated through prompt injection.browser-use/browser-use3 discussions
- Simplify algorithmic approachesWhen implementing functionality, evaluate whether simpler algorithmic approaches or more appropriate data structures can achieve the same result with less complexity. Look for opportunities to eliminate unnecessary conditional branching, use built-in operations for common tasks, and leverage established patterns like regex for pattern matching.browser-use/browser-use3 discussions
- Safe attribute accessAlways use defensive programming patterns when accessing object attributes, especially when dealing with optional or potentially None values. Use hasattr() checks before accessing attributes, prefer public accessor methods over private attributes, and add null checks when accessing nested properties.browser-use/browser-use3 discussions
- Replace polling with eventsReplace busy-wait polling loops with event-driven async patterns using asyncio.Event() or similar synchronization primitives. Polling loops that continuously check state variables waste CPU cycles and block the event loop, while event-driven patterns allow the thread to yield control until the condition is actually met.browser-use/browser-use3 discussions
- Pin testing dependency versionsAlways specify explicit versions for testing frameworks and tools to ensure reproducible test environments across different deployment contexts. Avoid installing testing dependencies with implicit "latest" versions, which can lead to inconsistent test behavior and difficult-to-debug failures.browser-use/browser-use3 discussions
- optimize Docker layersAvoid unnecessary duplication and bloat in Docker layers by trusting base images to provide standard tools and using appropriate installation methods. Instead of upgrading pip when the base image already provides it, trust the image's version to prevent duplicate copies across layers. When installing application code, use editable installs to avoid creating...browser-use/browser-use3 discussions
- Consistent terminology usageMaintain consistent terminology and naming patterns throughout the codebase to avoid confusion and future conflicts. Use descriptive names that clearly indicate their purpose and remove unnecessary parameters or elements that don't serve a function.browser-use/browser-use3 discussions
- Use ASCII-only URLsURLs in code should exclusively use ASCII characters for maximum security and compatibility. This prevents potential security vulnerabilities like homograph attacks and ensures consistent behavior across systems.Homebrew/brew3 discussions
- Structure test fixtures clearlyTest fixtures should clearly separate input parameters from expected outputs to enhance readability and maintainability. For table-driven tests, use a consistent pattern that explicitly distinguishes between test inputs and expected results. This approach makes tests more understandable and easier to maintain over time.Homebrew/brew3 discussions
- Secure API URL parsingWhen parsing API endpoint URLs, implement rigorous input validation using precise regular expressions. This includes: - Escaping special characters in domain literals (e.g., `github\.com`)Homebrew/brew3 discussions
- Prevent injection vulnerabilitiesAlways sanitize input data before using it in sensitive operations to prevent injection vulnerabilities. This applies to shell commands, file operations, and URL handling.Homebrew/brew3 discussions
- Fail with messagesFunctions and scripts should never fail silently. When detecting error conditions, always provide clear error messages to stderr that include context about what failed and why, then return an appropriate non-zero exit code. For user-facing commands, include guidance about correct usage when applicable.Homebrew/brew3 discussions
- Environment variable safetyWhen configuring environment variables, especially those related to paths, implement these safety practices: 1. Validate path accessibility before use to ensure the environment is properly configuredHomebrew/brew3 discussions
- Document non-obvious decisionsAlways add clear comments explaining non-obvious code decisions such as magic numbers, arbitrary values, truncation limits, or special case handling. Convert magic numbers to named constants with explanatory comments when appropriate. This documentation helps future developers understand the reasoning behind code decisions and makes maintenance easier.Homebrew/brew3 discussions
- Document CI pipeline comprehensivelyEnsure CI/CD pipeline documentation accurately reflects the complete workflow, including job dependencies, execution order, and all operations performed by each step. When documenting CI processes:Homebrew/brew3 discussions
- Manage test environmentsWhen writing tests that interact with environment variables or configuration settings, always (1) preserve the original state and (2) explicitly specify required configurations. boto/boto33 discussions
- Demonstrate canonical API patternsAlways provide examples that demonstrate the recommended and most current API usage patterns. This includes: 1. Using the most up-to-date API operations (e.g., prefer ListObjectsV2 over ListObjects)boto/boto33 discussions
- Consistent naming standardsFollow standard Python naming conventions consistently throughout code and documentation. Use underscores instead of hyphens in variable and parameter names (e.g., `proxies_config` not `proxies-config`). Maintain consistent capitalization of technical terms across all documentation. When working with file paths in code examples, use platform-agnostic...boto/boto33 discussions
- Avoid hidden performance costsWhen designing APIs that interact with remote services, be cautious about implementing convenience features that may introduce significant hidden performance costs. Collection operations like slicing, negative indexing, or operations that process all items can be unexpectedly expensive when they require fetching large amounts of data.boto/boto33 discussions
- Validate and Scope CacheWhen using cached data/artifacts, treat the cache as ephemeral and potentially stale/corrupt. Apply three rules: 1) Make cache scope explicit (and CI-safe)bmad-code-org/bmad-method3 discussions
- Fail-Fast Validation GatesWhen performing checklist-style validations (or any structured verification), implement error handling that is fail-fast, deterministic, and human-actionable:bmad-code-org/bmad-method3 discussions
- Deterministic script error handlingTreat IO and parse failures as first-class outcomes, with behavior that is (a) deterministic, (b) contract-respecting, and (c) strict about “malformed but present” config.bmad-code-org/bmad-method3 discussions
- Deterministic Resolution With ConfidenceWhen your system combines configurations or routes control flow, make the “resolution function” semantics explicit and safe: (1) define merge/override behavior precisely to prevent silent data loss, and (2) treat any heuristic inference from evidence as tentative—gate it with confidence and require explicit confirmation.bmad-code-org/bmad-method3 discussions
- Consistent Markdown FormattingMake Markdown generation deterministic and parser-safe. 1) Quote frontmatter/template variables - When using placeholders like `{{description}}` in Markdown frontmatter, wrap the value in quotes to prevent Antigravity/CLI parsing from breaking on special character sequences (e.g., ` #`, `: `).bmad-code-org/bmad-method3 discussions
- Automation Mode CI ContractWhen authoring/editing CI-driven “step” scripts for automation, treat `{auto_mode}` as a strict, schema-driven contract: - **No interactive dead-ends:** In `{auto_mode}`, avoid halting/asking. If the invocation (e.g., spec file or staged changes context) lets you infer intent, select the correct option automatically; only prompt if inference truly fails.bmad-code-org/bmad-method3 discussions
- API contract clarityDefine and document the interface contract for requests/commands so the system’s behavior is unambiguous, deterministic, and consistent across call paths and modes.bmad-code-org/bmad-method3 discussions
- Group-aware PaginationWhen the client needs a logical unit (run/history group, full resource state), the API must paginate and update in a way that preserves that unit across requests.maximhq/bifrost3 discussions
- Consistent UI FormattingApply consistent, presentation-focused code style to UI components: - Preserve flex/height semantics on “fill” containers: when a layout depends on full-viewport panels, ensure the relevant containers keep the same flex height/overflow utilities (e.g., `flex`, `flex-col`, `h-full`, `min-h-0`, and the intended `overflow-*` behavior).maximhq/bifrost3 discussions
- Config-Aware Startup FailuresWhen adding startup preflight checks (permissions, filesystem writeability, required directories), treat failure as part of error-handling policy: be precise, actionable, and configuration-aware.maximhq/bifrost3 discussions
- Use descriptive namingChoose specific, contextual names over generic terms to improve code clarity and maintainability. Generic names become ambiguous when combined into larger APIs or codebases, making it difficult for developers to understand functionality at a glance.better-auth/better-auth3 discussions
- comprehensive test coverageWhen adding new functionality, configuration options, or plugins, always include corresponding tests that verify the feature works as expected. Tests should comprehensively cover all aspects of the functionality, including input/output validation, data transformations, and edge cases. Additionally, structure tests as focused, single-responsibility test...better-auth/better-auth3 discussions
- API consistency standardsMaintain consistent parameter formats and requirements across all API providers and endpoints. When documentation conflicts with implementation, resolve discrepancies to ensure alignment. Avoid breaking changes by designing API modifications as unions or optional parameters rather than replacing existing structures.better-auth/better-auth3 discussions
- Use standard API abstractionsPrefer established, type-safe abstractions over primitive types or direct property access when designing APIs. This improves maintainability, enables future extensibility, and provides better developer experience.bazelbuild/bazel3 discussions
- explicit null checksUse explicit null/undefined checks instead of methods that silently handle missing values. When you expect a value to be present, use access patterns that will fail fast if the value is missing rather than returning default values or silently continuing.bazelbuild/bazel3 discussions
- Environment-aware configuration testingWhen writing tests for configuration-dependent functionality, implement environment detection and conditional logic to handle platform-specific differences. Tests should detect system capabilities and adjust expectations accordingly rather than assuming uniform behavior across all environments.bazelbuild/bazel3 discussions
- Clarify configuration examplesConfiguration documentation should provide concrete, platform-specific examples rather than generic placeholders, and use precise terminology to avoid confusion. Generic paths like `/path/to/repository` leave developers uncertain about actual implementation.bazelbuild/bazel3 discussions
- Check operation failuresAlways validate inputs and check return values of operations that can fail, providing clear error messages when failures occur. This includes system calls, library functions, and user input validation.bazelbuild/bazel3 discussions
- Avoid eager cache invalidationResist the urge to eagerly invalidate cache entries unless you have definitive proof that the cached data is invalid and cannot provide value for future operations. Cache entries can still be valuable even when their associated remote artifacts have expired or been removed.bazelbuild/bazel3 discussions
- Prefer Explicit ProjectionWhen normalizing/querying, keep output schemas deterministic and readable: - Prefer explicit output selection (`project` / `project-keep`) over `project-away`, so adding new columns later won’t accidentally change results.Azure/Azure-Sentinel3 discussions
- Portable network identityWhen implementing networking-related configuration or telemetry parsing, avoid brittle assumptions about IP/host formats and instead use portable defaults plus canonical resolution.Azure/Azure-Sentinel3 discussions
- Align RBAC and IdentityWhen defining permissions or identities in IaC (ARM/CloudFormation/templates), ensure the security configuration matches the actual runtime auth path and the provider’s supported identity types—avoid “declared-but-unused” privileges and avoid “wrong-scope” resources that create authorization or authentication drift.Azure/Azure-Sentinel3 discussions
- Surface errors appropriatelyEnsure errors are visible and properly handled rather than silently processed or hidden. Provide mechanisms for developers to handle errors explicitly, especially in libraries or frameworks with automated processes. Hidden or automatically handled errors can mask bugs and make debugging difficult.Azure/azure-sdk-for-net3 discussions
- Prefer identity-based authenticationAlways prioritize modern identity-based authentication methods over traditional username/password credentials. This improves security by reducing credential exposure and management overhead.Azure/azure-sdk-for-net3 discussions
- Follow formatting standardsMaintain consistent code formatting by adhering to the defined standards in the .editorconfig file and Azure SDK implementation guidelines at https://azure.github.io/azure-sdk/dotnet_implementation.html. Pay attention to these specific formatting rules:Azure/azure-sdk-for-net3 discussions
- Descriptive consistent identifiersUse clear, descriptive identifiers that accurately reflect their purpose, and maintain consistent naming patterns throughout the codebase. This applies to variables, parameters, methods, and configuration elements.Azure/azure-sdk-for-net3 discussions
- Centralize pipeline configurationsUse centralized templates and variables for pipeline configurations instead of duplicating or hardcoding values. This improves maintainability, ensures consistency, and makes platform-specific adaptations easier to manage.Azure/azure-sdk-for-net3 discussions
- Self-Documenting Calls & ModelsWhen reviewing code, enforce two style rules: 1) **Make complex calls self-documenting**: prefer **named arguments** over positional parameters, and pass **intent variables** instead of literals when the value is logically derived.Azure/azure-powershell3 discussions
- Pinned Spec ConfigurationWhen configuration files drive code generation (e.g., AutoRest README YAML), pin the exact spec snapshot and use the correct configuration semantics. Azure/azure-powershell3 discussions
- Avoid manual SDK editsWhen working on CI/CD pipelines, treat anything under `*Management.Sdk/Generated/*` (or similarly generated folders) as read-only. **Standard** - **Do not manually edit generated SDK/model files.** CI may fail and changes will be overwritten on the next regen.Azure/azure-powershell3 discussions
- CI coverage and scopeWhen changing CI/CD (and related policy configs), ensure your pipeline enforces the expected scope end-to-end: correct review routing, test/version coverage, and validation against the full change set.Azure/azure-cli3 discussions
- Document feature flagsWhen configuring feature flags in Cargo.toml, ensure they are properly structured and documented. Chain feature dependencies correctly, document non-obvious configuration choices with comments, and use appropriate syntax for conditional feature activation.tokio-rs/axum3 discussions
- Hot Path Cost ControlsIn performance-sensitive paths, actively control hidden costs: cap buffering, reuse expensive compiled primitives, and avoid full serialization/large allocations.looplj/axonhub3 discussions
- Explicit Config OverridesImplement configuration in a way that is predictable: define defaults centrally, keep early rollout scope narrow (prefer deployment-level defaults), and make override semantics explicit.looplj/axonhub3 discussions
- Error Handling ConsistencyWhen handling failures, make error semantics explicit and consistent across the stack: - Define retryability precisely: only treat errors as retryable when you can guarantee it won’t duplicate already-delivered output (e.g., transport ended before a usable response). Add regression tests for each retry branch (positive + negative cases).looplj/axonhub3 discussions
- Enforce Layered ReuseWhen changing or adding code, keep logic and dependencies clean: - Centralize invariants in the owning function: if you need to clamp/validate values, apply it inside the core method that produces/returns them (the “source of truth”) rather than at every call site.looplj/axonhub3 discussions
- Deterministic Cache KeysCache keys must be built only from inputs that truly change model output, and must be deterministic, complete, and cheap to compute. **Rules** 1. **Derive keys from a stable message “anchor”.** If using conversation head hashing, explicitly define which roles and how many bytes you consider (e.g., contiguous leading `system`/`developer`, plus first...looplj/axonhub3 discussions
- Proper Axios Configuration and UsageWhen implementing code that uses the Axios library in TypeScript, it is important to follow best practices for configuring and accessing Axios instances and settings. Ensure that Axios instances are properly configured with appropriate defaults, configuration properties are accessed correctly, and request-specific configuration overrides instance-level defaults in a predictable manner.axios/axios3 discussions
- Consistent Naming Conventions for Axios Requests and ResponsesWhen using the Axios library in TypeScript, it is important to follow consistent naming conventions to improve code readability and maintainability. Use the 'on' prefix for Axios event handlers and callbacks, use domain-specific prefixes like 'response' to clarify scope, maintain consistent naming patterns for similar functionality, and align with established conventions.axios/axios3 discussions
- Configuration property standardsAlways define configuration properties with sensible defaults and consistent naming conventions. When adding new configurable features, establish clear defaults that follow platform conventions and document their purpose.axios/axios3 discussions
- Validate configurations with clarityConfiguration validation should use explicit checks and clear conditional logic to improve code readability and prevent errors. When validating configuration values:aws/aws-sdk-js3 discussions
- Test configuration precedenceWhen implementing systems that load configuration from multiple sources, always test the precedence rules explicitly to ensure the correct values are being used. Configuration loading bugs can be subtle and difficult to diagnose in production.aws/aws-sdk-js3 discussions
- Limit cache sizeAlways implement size constraints on caches to prevent memory leaks and performance degradation. Unbounded caches can grow continuously and consume excessive memory, especially in long-running applications.aws/aws-sdk-js3 discussions
- Follow established testing patternsWhen writing tests, use existing patterns and infrastructure already established in the codebase rather than creating custom implementations. This improves consistency, reduces maintenance burden, and helps ensure comprehensive test coverage.aws/aws-sdk-js3 discussions
- Explicit verified configurationsAlways specify configuration values explicitly and verify their accuracy against official documentation or tests. This applies to region configurations, API settings, and credential management. Avoid mutations of global configuration objects, and instead set values explicitly when defined by service APIs.aws/aws-sdk-js3 discussions
- Document APIs completelyAlways provide complete, clear, and contextually rich documentation for all public APIs. Documentation should: 1. Use proper grammar and clear wordingaws/aws-sdk-js3 discussions
- optimize CI efficiencyOptimize CI/CD pipelines by minimizing resource usage and avoiding unnecessary operations. Use lightweight package alternatives when possible (e.g., `vim-nox` instead of `vim` for text processing), implement conditional execution to run steps only when relevant files change, and leverage automatic dependency resolution instead of manual listings.avelino/awesome-go3 discussions
- Enforce coverage thresholdsAll code contributions must meet a minimum test coverage threshold of 80% before being accepted. This ensures adequate testing and helps maintain code quality standards across the project.avelino/awesome-go3 discussions
- Validate configuration appropriatenessEnsure configurations are contextually appropriate and properly validated for their intended use case. This includes verifying that configuration options are suitable for the target resource type, handling configuration state transitions correctly, and choosing appropriate dependencies.argoproj/argo-cd3 discussions
- Extract testable unitsAvoid copying or reimplementing production logic in test files. Instead, refactor the production code to extract small, testable functions that can be unit tested with mocked dependencies. Tests should call the actual production functions rather than duplicating their logic.argoproj/argo-cd3 discussions
- Comprehensive function documentationFunctions should have thorough documentation that follows Go conventions and explains both the "what" and "why" of the code. This includes: 1. **Proper Go doc format**: Start function comments with the function name, e.g., "GetSecretByName returns the Secret..." instead of "Returns the Secret..."argoproj/argo-cd3 discussions
- API documentation clarityEnsure API parameter documentation clearly specifies default values, valid options, error conditions, and precise requirements to prevent user confusion and integration failures. Ambiguous documentation leads to misunderstandings about expected behavior and can cause integration problems.argoproj/argo-cd3 discussions
- Organize and Clean ImportsKeep codebase structure and import usage aligned with the intended architecture and boundaries. - **Place files in the correct feature/module directory** (e.g., shared UI utilities under `src/features/shared/`), rather than leaving them in a generic `utils/` folder when the architecture expects otherwise.coleam00/Archon3 discussions
- Defensive config handlingConfiguration should be treated as untrusted input: validate and normalize it, ignore unknown/invalid fields, and ensure user misconfiguration can’t crash initialization or produce misleading warnings. Also gate checks by what’s actually configured and implement a clear precedence order (env → explicit config → user paths → canonical defaults → PATH lookup)...coleam00/Archon3 discussions
- Version migration dependencies carefullyWhen updating dependencies for migration-related components or making schema changes, verify compatibility and ensure backward compatibility: 1. For dependency updates:appwrite/appwrite3 discussions
- Validate configuration formattingEnsure all JSON configuration files adhere to proper syntax and formatting conventions. Common issues to avoid include: 1. **Invalid key-value syntax**: All JSON properties must use proper key-value format with double-quoted keys.appwrite/appwrite3 discussions
- Use object methods consistentlyWhen working with Document objects, always use their accessor methods rather than array-style syntax. Use `$object->getAttribute('property')` and `$object->setAttribute('property', $value)` instead of `$object['property']`. This ensures proper encapsulation, maintains data integrity through validation, and creates more resilient code that won't break if the...appwrite/appwrite3 discussions
- Self-contained test scenariosTests should be fully self-contained to ensure reliability and prevent unexpected failures. Each test scenario should: 1. Create any prerequisite data it needs rather than assuming it existsappwrite/appwrite3 discussions
- Resilient configuration patternsWhen modifying or defining configuration values, use patterns that are resistant to future changes and silent failures. For configuration files, scripts, and environment variables, implement approaches that remain valid when underlying values change.appwrite/appwrite3 discussions
- OpenAPI spec complianceEnsure all API definitions strictly follow OpenAPI specification standards to maintain compatibility with tooling and clients. This includes: 1. Match default values with their defined types:appwrite/appwrite3 discussions
- Guard database query resultsAlways validate database query results before accessing their methods or properties. Methods like `findOne()`, `getDocument()`, and similar database operations can return null or empty documents. Failing to check these results before access leads to runtime errors.appwrite/appwrite3 discussions
- Active service health checksReplace static delays with active health checks in CI/CD workflows to ensure service readiness. Instead of using fixed sleep times, implement polling mechanisms that verify service health endpoints. This improves workflow reliability and reduces false negatives.appwrite/appwrite3 discussions
- Config precedence and env overridesWhen reading configuration from multiple sources (function arguments, environment variables, config files, defaults), implement and preserve a single, explicit precedence order, and ensure user-provided overrides beat environment-derived values.anthropics/anthropic-sdk-python3 discussions
- Standardize deprecation documentationWhen marking APIs, components, or features as deprecated, use consistent JSDoc @deprecated tags with clear alternative guidance. This ensures smooth migration paths for users and maintains backward compatibility during version transitions.ant-design/ant-design3 discussions
- Optimize expensive operationsMinimize performance impact of costly operations through strategic ordering, batching, and avoiding unnecessary work. Place cheaper conditional checks before expensive operations to enable early exits, batch DOM manipulations using requestAnimationFrame to reduce repaints, and ensure optimizations don't create additional computational overhead.ant-design/ant-design3 discussions
- Centralize configuration managementAvoid duplicate configuration processing and keep configuration data properly centralized. When configuration utilities or hooks already exist, use them instead of manually processing the same data. Keep translations in locale files rather than embedding them directly in data structures, and prefer design tokens over hardcoded values for styling...ant-design/ant-design3 discussions
- Avoid unnecessary memoizationMemoization (useMemo, useCallback, React.memo) should only be used when the performance benefits outweigh the overhead costs. Avoid memoization in these scenarios:ant-design/ant-design3 discussions
- Avoid hardcoded configuration valuesReplace hardcoded values in configuration code with design tokens, parameters, or configurable constants to ensure consistency and maintainability across the codebase.ant-design/ant-design3 discussions
- Verify SSR documentation accuracyEnsure that documentation about server-side rendering (SSR), static site generation (SSG), and related rendering strategies is technically accurate and complete. Avoid making misleading claims about performance characteristics or technical behavior, and include all relevant benefits and use cases.angular/angular3 discussions
- precise build targetingBuild targets should use specific file patterns rather than broad globs to improve build performance, clarity, and maintainability. Avoid capturing unnecessary files that can lead to build system constraints and complexity.angular/angular3 discussions
- limit error handling scopeWhen implementing error handling, carefully limit the scope of try-catch blocks to prevent cascading failures and ensure error handlers themselves cannot cause additional errors. Wrap only the specific operations that may throw, not the error handling logic itself.angular/angular3 discussions
- Clarify configuration option limitationsWhen documenting or designing configuration options, explicitly state both what the option does AND what it doesn't do, including any limitations or side effects. Users often make incorrect assumptions about configuration behavior based on names alone.angular/angular3 discussions
- Build configuration consistencyMaintain consistent build and release configurations across the project by following established patterns and ensuring documentation accuracy. When implementing new build configurations or modifying existing ones, reference how similar components handle the same requirements to maintain uniformity.angular/angular3 discussions
- API terminology consistencyMaintain consistent, precise terminology throughout API documentation and interfaces. Avoid ambiguous or misleading terms that could confuse developers about the API's behavior, and use professional language that clearly communicates the intended functionality.angular/angular3 discussions
- Use constraining typesAPI functions should use specific types and enums to clearly communicate valid parameter values rather than accepting arbitrary generic types that suggest any value is acceptable.alacritty/alacritty3 discussions
- Follow metadata specificationsWhen writing metadata files (such as AppStream, package manifests, or configuration files), always consult and follow the official specifications precisely. Pay special attention to case-sensitive identifiers, valid values, and required formats.alacritty/alacritty3 discussions
- Consistent naming conventionsMaintain consistent naming patterns and capitalization throughout the codebase, especially for configuration options, string values, and identifiers. This includes using consistent capitalization for similar values (e.g., "None" instead of mixing "none" and "None"), adopting uniform naming patterns for related options (e.g., using "duration" consistently...alacritty/alacritty3 discussions
- Choose familiar, intuitive namesWhen naming variables, methods, or configuration options, prioritize terms that are both intuitive to users and familiar within the relevant domain. Avoid technical jargon when simpler, more natural alternatives exist, while also preferring established terminology that the target audience already knows.alacritty/alacritty3 discussions
- Follow naming conventionsUse proper naming conventions to make code more readable and maintainable: 1. **Functions should start with verbs** that describe their action: ```typescriptapache/airflow3 discussions
- Enforce authentication boundariesImplement strict authentication boundaries and access controls to prevent security vulnerabilities: 1. When multiple authentication methods are supported, ensure they are mutually exclusive to prevent confusion about which method is active. Add validation code that raises explicit exceptions when conflicting credentials are provided.apache/airflow3 discussions
- Document intentional choicesAdd explanatory comments for non-obvious code decisions that might appear incorrect, unusual, or suboptimal to future contributors. Without such comments, code that looks unusual might be "fixed" during refactoring, introducing bugs. This is particularly important for:apache/airflow3 discussions
- Use scoped, consistent namesWhen naming identifiers (results, commands, spaces) in shared systems, make names **unambiguous, consistent, and context-aware**. Apply these rules: 1) **Qualify by namespace/scope to avoid collisions**awslabs/aidlc-workflows3 discussions
- Secure Path ConfinementEnforce security boundaries using robust validation and least-privilege isolation. - For filesystem access restricted to a base directory (e.g., a “run folder”), never use string prefix checks like `str(path).startswith(...)` to prevent `../` traversal or sibling-dir prefix bypasses. Instead, use `Path.is_relative_to`.awslabs/aidlc-workflows3 discussions
- Sandbox config boundaryWhen a feature flag like `use_sandbox` changes where code runs (host vs container), treat it as a configuration boundary: (1) explicitly provide the container environment your tools expect, and (2) remove/recreate any stateful artifacts created on the other side.awslabs/aidlc-workflows3 discussions
- Portable Configuration StandardsAll configuration-driven setup and workflow behavior must be (a) convention-based and unambiguous, and (b) portable across environments. Apply this standard:awslabs/aidlc-workflows3 discussions
- Fail Loudly, Degrade SafelyIn session/install hooks, never hide failures. Avoid OS/tool-specific command forms and exit-code-dependent fallbacks, and when an error occurs either (1) stop with a clear message or (2) degrade gracefully while recording structured diagnostics so `--doctor`/health checks can surface what broke.awslabs/aidlc-workflows3 discussions
- Standardize model accessWhen integrating AI models into applications, provide consistent configuration methods that support different access patterns (direct API, chat interfaces, or intermediary services like LiteLLM). Aider-AI/aider3 discussions
- Validate pattern matchingWhen implementing algorithms that involve pattern matching or data parsing, ensure robustness across all edge cases and clearly document the algorithm's behavior. This is particularly important for:vercel/ai3 discussions
- Test before documentingAlways thoroughly test API features and endpoints before documenting them, especially when integrating with third-party services. Documentation should accurately reflect the actual behavior of the API, including:vercel/ai3 discussions
- Provide actionable examplesDocumentation should include concrete, executable code examples rather than vague instructions. Make your examples copy-paste ready with all necessary context and dependencies. When documenting features or APIs, show exactly how they should be used in practice.vercel/ai3 discussions
- Document configuration decisionsWhen modifying configuration files (package.json, tsconfig.json, etc.), document the reasoning behind significant changes and verify they don't introduce unexpected side effects. This is especially important for changes affecting dependencies and build processes.vercel/ai3 discussions
- Async error callbacksWhen handling asynchronous operations, especially those that might continue running in the background after the main consumer has moved on, provide error callback options to ensure errors are properly reported and handled. This pattern prevents silent failures in background tasks and enables proper logging, monitoring, and recovery.vercel/ai3 discussions
- Use descriptive namesChoose clear, descriptive names for variables, methods, types, and parameters that unambiguously convey their purpose and avoid conflicts. Prefer full words over abbreviations and ensure names are specific enough to prevent clashes with inherited or similar functionality.cloudflare/agents3 discussions
- Use definite assignment assertionsWhen you're certain a value will be initialized but TypeScript can't infer this, use the definite assignment assertion operator (`!`) instead of `as any` or suppressing type errors. This maintains type safety while avoiding unnecessary null checks throughout your codebase.cloudflare/agents3 discussions
- Explicit API parametersDesign APIs with explicit parameters rather than implicit defaults or hidden behavior. When an API function requires specific data or configuration, make those requirements clear through the function signature instead of relying on optional parameters with complex fallback logic.cloudflare/agents3 discussions
- Balance organization with constraintsWhen making code organization decisions, consider the broader impact beyond just eliminating duplication or following patterns. Sometimes a slightly less "clean" solution is preferable when it preserves type safety, maintains clear class responsibilities, or avoids exposing unnecessary implementation details.cloudflare/agents3 discussions
- Use Valid API ContractsWhen calling SDK/toolkit APIs, always adhere to the documented method signatures and request/response shapes. Don’t pass guessed or stale keyword arguments, and prefer the project’s canonical starter toolkit abstractions for common lifecycle operations.awslabs/agentcore-samples3 discussions
- Tracing schema and continuityWhen adding or integrating agent frameworks/invocation paths, ensure observability works end-to-end by meeting BOTH requirements: (1) the emitted telemetry conforms to the documented OpenTelemetry/OpenInference schema (not merely “OTLP transport”), and (2) trace context is propagated across boundaries (e.g., Lambda → AgentCore) so traces are continuous and...awslabs/agentcore-samples3 discussions
- Parameterized Runtime ConfigurationEnsure configuration is explicit, supported, and environment-specific values are parameterized. Apply these rules: - Use non-deprecated minimum runtime versions in setup docs (e.g., prefer Python 3.10+ over 3.8/3.9).awslabs/agentcore-samples3 discussions
- Idempotent, Safe ErrorsHandle errors in a way that (a) doesn’t hide real bugs, (b) supports reruns after interruptions, and (c) degrades gracefully when data/operations are incomplete.awslabs/agentcore-samples3 discussions
- Decision-First DocumentationWhen publishing code samples/notebooks, write documentation that is (a) decision-first, (b) API-current, and (c) goal-focused. 1) Add “when to use” differentiation for competing interfacesawslabs/agentcore-samples3 discussions
- Consistent env configFor scripts and tests, load configuration consistently and safely, and make any expensive/external prerequisite behavior opt-in. Apply these rules: 1) Source the same env file(s) across related scripts (deploy/destroy/test) with a guarded “missing file” behavior.awslabs/agentcore-samples3 discussions
- Consent, Secrets, Least PrivilegeAgentic systems that can spend money, handle credentials, or call AWS APIs must enforce three controls: 1) **Require explicit user consent before spending or creating payment sessions**awslabs/agentcore-samples3 discussions
- Lock Writes, Snapshot ReadsUse the lock to protect shared mutable state during mutations, but avoid holding it for read-side convenience/field-by-field getters. **Rules** 1. **Lock only for writes:** Acquire the mutex only around code that mutates shared collections/fields (e.g., `logs[]`, `updates[]`, `notifications[]`).agent0ai/agent-zero3 discussions
- Endpoint Auth ValidationFor security-sensitive flows (WS/API, authenticated cloning, token/API-key auth), don’t rely on generic or heuristic validation. Apply these rules: 1) Validate with explicit allow/deny semanticsagent0ai/agent-zero3 discussions
- Translation layer fidelityWhen building proxy/translation layers between different API or protocol formats (e.g., OpenAI-to-Claude streaming translation, built-in-tool fallback substitution), preserve the exact semantics of the original request/response and never silently alter client-specified behavior. Guard every state transition with explicit flags (e.g. `toolInfo.closed`,...Decolua/9Router3 discussions
- Sanitize untrusted input, fail closedTreat any data that originates outside your own trust boundary—upstream provider responses, client-supplied tool/parameter names, or unconfigured feature state—as potentially hostile, and default to the safest possible behavior rather than optimistically trusting or guessing it.Decolua/9Router3 discussions
- LLM provider translation fidelityWhen writing adapters that translate between different LLM provider wire formats (OpenAI chat/completions, Responses API, Anthropic, Gemini, Zed, etc.) or route model IDs to providers, prioritize completeness and precision over broad assumptions.Decolua/9Router3 discussions
- Extract duplicated logicAvoid duplicating logic across files or within multiple branches of the same function. When the same algorithm, HTTP call, parsing routine, or computation appears in more than one place, extract it into a single shared helper function or module and have all call sites use it. Duplicated code drifts over time—bug fixes and improvements applied to one copy...Decolua/9Router3 discussions
- Use Existing AbstractionsPrefer existing framework/library abstractions for both types and layout styling to avoid redundant code and one-off visual tweaks. - Types: If the framework exposes a prop type, reuse it instead of introducing a duplicate interface.colinhacks/zod2 discussions
- Run Type Resolution ChecksAdd a CI/pre-release gate that validates your published package’s JavaScript + TypeScript type resolution. Use `@arethetypeswrong/cli` to catch broken `exports`/subpath import mappings across CJS/ESM and Node versions, and configure it to your supported runtime matrix (e.g., ignore known/unavoidable legacy Node failures via `--profile`).colinhacks/zod2 discussions
- Deterministic Parse FallbacksWhen parsing inputs that may be invalid (e.g., string → boolean), do not rely on implicit/unclear failure behavior. Instead, decide explicitly how parse errors should be handled and make it deterministic.colinhacks/zod2 discussions
- Consistent Scoped NamingUse consistent, semantic naming patterns for externally visible identifiers—especially package names and command/script names. - **Packages/registry entries:** Prefer the correct scope and canonical name format (typically `@scope/name`) aligned with ownership and established ecosystem conventions. If the project belongs under a scope (e.g., `@zod`), use...colinhacks/zod2 discussions
- Proper documentation linkingDocumentation should use appropriate linking strategies to ensure content remains accessible and navigable across all deployment environments: 1. **Use absolute URLs for repository links**: When referencing files within the codebase (like READMEs or source files), always use absolute GitHub URLs instead of relative paths that may break when documentation...zed-industries/zed2 discussions
- Precise test pattern matchingWhen identifying test patterns in code, use specific equality predicates (`#eq?`) instead of list inclusion predicates (`#any-of?`) when matching against a single value. This improves clarity and can avoid potential false positives in test detection.zed-industries/zed2 discussions
- Minimize credential exposure lifetimeCredentials and secrets should never be stored persistently in memory or written to files. Instead, use ephemeral patterns that limit the lifetime of sensitive data:zed-industries/zed2 discussions
- Explicit over implicitWhen designing APIs, prioritize explicit parameter identification over implicit context. APIs with clear, unambiguous parameters improve implementation, maintenance, and usage. Whenever a function could operate on multiple resources or have ambiguous behavior, include explicit parameters to clarify the intent.zed-industries/zed2 discussions
- Document configuration clearlyWhen adding or modifying configuration parameters, especially in JSON settings files, ensure they are clearly documented with comments that explain: 1. The purpose of the parameterzed-industries/zed2 discussions
- Write focused single-purpose testsTests should focus on validating one specific behavior or scenario rather than combining multiple test cases into complex, multi-purpose tests. Each test should have a clear, meaningful purpose that actually exercises the code under test.facebook/yoga2 discussions
- verify configuration completenessAlways verify that configuration files completely and accurately specify their requirements. This includes ensuring all related files are included and using appropriate minimum versions or glob patterns.facebook/yoga2 discussions
- Use semantic namingChoose semantic, logical names that describe purpose and intent rather than physical characteristics or implementation details. This improves code maintainability, internationalization support, and clarity.facebook/yoga2 discussions
- Use descriptive function namesFunction names should clearly convey their purpose and behavior, not just their signature or implementation details. Avoid names that could be confused with existing functions that have similar but different behavior.facebook/yoga2 discussions
- Use appropriate CI toolchainsEnsure CI/CD workflows use technology-specific setup actions and execute commands in the correct working directories. Avoid using generic or unrelated setup actions that install unnecessary toolchains, as this increases build time and complexity. Always specify the appropriate working directory for technology-specific commands to ensure they execute in the...facebook/yoga2 discussions
- understand undefined value semanticsBefore modifying initialization patterns or removing static variables, investigate the semantic meaning of undefined values and object lifetimes in the existing codebase. What appears to be a memory leak or improper initialization may be intentional design.facebook/yoga2 discussions
- separate formatting from loggingDesign logging utility functions to return formatted strings rather than directly performing logging operations. This separation of concerns improves modularity, testability, and allows callers to control when and how logging occurs.facebook/yoga2 discussions
- Safe configuration definitionsWhen defining configuration flags and options, use practices that ensure compatibility across different preprocessors and build environments. For macro-based configuration flags, use integer values (0/1) instead of boolean literals (true/false) to avoid preprocessor compatibility issues. Additionally, consider using runtime configuration mechanisms (like...facebook/yoga2 discussions
- Reset algorithm state internallyAlgorithms should handle their own state initialization and cleanup internally rather than relying on callers to manage it. This prevents bugs caused by stale data from previous executions and reduces the burden on calling code.facebook/yoga2 discussions
- prevent off-by-one errorsWhen implementing algorithms that involve spacing, gaps, or iterative calculations, carefully verify loop bounds and edge cases to prevent off-by-one errors. These errors commonly occur when calculating spacing between N items (which requires N-1 gaps, not N gaps) or when applying operations to boundary elements.facebook/yoga2 discussions
- Pin dependency versionsAlways specify exact versions for dependencies and avoid pointing to moving targets like "master" branches or "latest" tags in configuration files. This ensures reproducible builds and prevents unexpected breakages when upstream dependencies change.facebook/yoga2 discussions
- Manage resource lifecyclesEnsure proper resource allocation and cleanup pairing, and maintain clear ownership semantics to prevent memory leaks and null reference issues. When allocating resources like GCHandle, always pair allocation with corresponding cleanup calls. Avoid overwriting allocated resources without first cleaning up the previous allocation.facebook/yoga2 discussions
- Keep configuration versions currentRegularly review and update version specifications in configuration files to align with current standards and internal practices. When updating versions, consider both the benefits of newer features and potential compatibility impacts.facebook/yoga2 discussions
- Follow language naming conventionsEnsure all identifiers (properties, methods, classes, variables) follow the established naming conventions of the programming language being used. This improves code readability, maintainability, and consistency across the codebase.facebook/yoga2 discussions
- Extract complex conditionsWhen encountering complex conditional expressions or generic variable references, extract them into clearly named variables or use explicit identifiers to improve code readability and maintainability.facebook/yoga2 discussions
- Enforce style in CIConfigure automated formatting tools in CI/CD pipelines to enforce code style standards rather than silently fix violations. Use validation flags that cause the build to fail when formatting issues are detected, and ensure all commands run non-interactively.facebook/yoga2 discussions
- Control structure formattingAlways use braces for control structures (if, for, while, etc.) even for single statements, and maintain consistent spacing around parentheses and braces. This improves code readability and prevents potential bugs when code is modified later.facebook/yoga2 discussions
- Choose meaningful identifiersAll identifiers including parameters, files, functions, and categories should clearly communicate their purpose and role. Avoid generic or ambiguous names that require additional context to understand.facebook/yoga2 discussions
- Centralize configuration valuesConsolidate all configuration variables, constants, and settings into a centralized configuration object rather than declaring them as scattered variables throughout the codebase. This improves maintainability, reduces duplication, and enables consistent templating patterns.facebook/yoga2 discussions
- Cache expensive computationsIdentify and cache the results of expensive computations to avoid redundant calculations, especially in performance-critical code paths. This includes recursive functions, user-defined callbacks, and complex arithmetic operations that may be called multiple times with the same inputs.facebook/yoga2 discussions
- benchmark performance optimizationsAlways measure and validate performance optimizations through benchmarking before assuming they provide benefits. Performance changes can have unexpected consequences, and what appears to be an optimization may actually degrade performance in real-world scenarios.facebook/yoga2 discussions
- Avoid configuration side effectsConfiguration properties should behave predictably without hidden side effects that override explicitly set values. When a developer sets a configuration value, the system should respect that value rather than applying additional logic that might change the effective behavior.facebook/yoga2 discussions
- avoid build side effectsBuild scripts should avoid performing operations as side effects and instead use explicit, dedicated tasks for each operation. Side effects make build processes unpredictable, harder to maintain, and difficult to debug when issues arise.facebook/yoga2 discussions
- preserve URL integrityWhen manipulating URLs for API calls, prioritize preserving the original URL structure over using convenience APIs that may normalize or modify the URL unexpectedly. This is especially important when appending query parameters or handling URL fragments.mountain-loop/yaak2 discussions
- workflow documentation clarityEnsure all workflow-related documentation, help text, and code comments use proper grammar and punctuation. Workflow systems involve complex orchestration, retries, and fault tolerance mechanisms that require clear, professional documentation for maintainability and developer understanding.cloudflare/workers-sdk2 discussions
- Use configuration placeholdersConfiguration files should use placeholder values like `<TBD>` instead of hardcoded values for fields that need to be dynamically replaced by tooling or build processes. This ensures that automated systems can properly substitute the correct values during project setup or deployment.cloudflare/workers-sdk2 discussions
- telemetry documentation consistencyMaintain consistent formatting and style when documenting telemetry and observability systems. This includes using parallel structure in lists, consistent terminology, and clear explanations of what data is collected and why.cloudflare/workers-sdk2 discussions
- Respect automated toolingAvoid manually updating files or configurations that are managed by automated CI/CD tools. Many modern development workflows rely on automated systems like dependabot for dependency updates, changesets for version management, and other tools for consistent builds and releases.cloudflare/workers-sdk2 discussions
- Provide specific examplesDocumentation should include concrete, actionable examples and use clear, unambiguous terminology to eliminate confusion for developers. Avoid vague instructions that leave developers guessing about implementation details.cloudflare/workers-sdk2 discussions
- maintain clean project structureKeep your codebase organized and clutter-free by removing unnecessary files, directories, and artifacts that serve no functional purpose. When tools have compatibility issues with certain file types, configure appropriate ignore patterns rather than leaving problematic files to cause confusion or errors.cloudflare/workers-sdk2 discussions
- Explicit configuration definitionsEnsure all configuration dependencies and environment variables are explicitly defined rather than relying on implicit behavior or assumptions. This prevents issues from version drift, missing definitions, or unclear dependencies.cloudflare/workers-sdk2 discussions
- document workflow capabilitiesWorkflow methods should include comments that document their orchestration capabilities and data access patterns. This helps developers understand the available temporal execution features and interaction methods.cloudflare/workers-sdk2 discussions
- Design repeatable CI workflowsCI workflows should be idempotent and handle cleanup automatically to avoid manual intervention and ensure reliable execution. When designing workflows that create resources, branches, or temporary artifacts, always include cleanup steps that can run safely multiple times.cloudflare/workers-sdk2 discussions
- Design intuitive API interfacesAPIs should be designed with user experience in mind, accepting inputs in formats users naturally encounter and providing clear customization options with well-documented defaults.cloudflare/workers-sdk2 discussions
- validate post-manipulation stateAlways explicitly validate object state after performing manipulations that could potentially result in null or undefined values. This is especially critical when dealing with global objects, parsing operations, or any transformation that might leave objects in an unexpected state.cloudflare/workerd2 discussions
- Use appropriate API methodsWhen integrating with external APIs or implementing interface methods, ensure you're using the correct API calls for your intended functionality. Consult the official documentation and examples to understand the purpose and proper usage of different methods.cloudflare/workerd2 discussions
- Test comprehensive error scenariosWhen implementing error handling, ensure comprehensive test coverage by testing multiple error scenarios, edge cases, and boundary conditions. Don't just test the happy path - validate that your code properly handles invalid inputs, out-of-range values, and error propagation.cloudflare/workerd2 discussions
- optimize CI resource usageDesign CI workflows to maximize resource efficiency by reusing build artifacts across jobs whenever possible, while carefully evaluating when separate builds are truly necessary. Before creating duplicate build jobs, assess whether different compilation flags or configurations genuinely require separate builds, or if the same artifacts can be reused with...cloudflare/workerd2 discussions
- Optimize algorithm performanceWhen implementing algorithms, prioritize performance by using batching techniques to reduce API call overhead and avoiding unnecessary memory allocations. Convert recursive algorithms to iterative ones when dealing with large datasets, and process elements in batches rather than individually.cloudflare/workerd2 discussions
- Format observability test dataWhen writing tests for observability systems (tracing, metrics, logging), structure test assertions to be easily readable and debuggable. Instead of placing complex JSON outputs or structured data on single lines, split them across multiple lines with proper formatting.cloudflare/workerd2 discussions
- extract repeated expressionsWhen the same expression or computation appears multiple times within a code block, extract it to a variable to improve maintainability and readability. This reduces the risk of inconsistencies when the logic needs to be updated and makes the code's intent clearer.cloudflare/workerd2 discussions
- ensure test cleanupTests must properly clean up resources and handle conditional execution regardless of test outcome. This includes removing temporary files, resetting global state, and gracefully handling feature flag conditions.cloudflare/workerd2 discussions
- Choose appropriate logging functionsSelect the correct logging function based on frequency, severity, and destination to avoid log spam and ensure proper routing. Use LOG_ONCE or LOG_PERIODICALLY for repeated warnings that could spam logs, KJ_LOG(ERROR) for general error logging, and LOG_EXCEPTION only for exceptions intended for Sentry monitoring.cloudflare/workerd2 discussions
- Balance configuration automation complexityWhen implementing configuration management solutions, carefully weigh the benefits of automation against the complexity and maintenance burden it introduces. For infrequent configuration updates, prefer simple manual approaches over complex automated solutions that may break unexpectedly. For frequent updates or version-specific configurations, automation...cloudflare/workerd2 discussions
- avoid unnecessary Arc wrappingDon't wrap atomic types in Arc unless you need to share ownership across multiple owners. Atomic types like AtomicBool, AtomicU64, etc. are already thread-safe and can be used directly in structs that will be wrapped in Arc at a higher level.cloudflare/workerd2 discussions
- Prefer semantic namesMake identifiers convey intent: include meaningful domain fields in types and choose function names that reflect user-facing semantics (not internal storage order). When internal representation differs from user expectations (for example newest items appended to the end, but UI cycles newest-first), rename functions to express the user direction and add a...wavetermdev/waveterm2 discussions
- Include context-rich logsEnsure logs are actionable: always include relevant context identifiers (e.g., full connection name, user or request id) and log any returned errors so failures are visible and debuggable. Mask or redact sensitive fields when necessary and choose an appropriate log level (info for status changes, warn/error for failures).wavetermdev/waveterm2 discussions
- defensive null handlingAlways handle nullable values explicitly and defensively to prevent runtime null/undefined errors and to make intent clear. Why: Nulls and undefined values cause intermittent runtime exceptions and unclear state transitions. Being explicit—both when clearing values and when checking inputs—reduces bugs and documents intent.wavetermdev/waveterm2 discussions
- Config precedenceEstablish a clear configuration precedence and control policy: explicit user-supplied settings take priority over automatic detection, unless a centralized policy (e.g., cloud/service-side limits or security constraints) explicitly disallows client overrides. Motivation: prevents surprising behavior while allowing deliberate overrides and enforcing...wavetermdev/waveterm2 discussions
- config hygieneKeep repository configuration files canonical, documented, and free of personal workspace/debug artifacts. Why: Config files determine runtime behavior and developer onboarding. Committing personal IDE or temporary debug configs pollutes the repo, causes accidental formatting/behavior differences, and hides the canonical way to run the app. Likewise,...wavetermdev/waveterm2 discussions
- centralize sentinel namesDefine and use named constants for special sentinel identifiers (e.g., "local", "connected") and add semantic methods on domain types near their definitions to encapsulate boolean checks (e.g., RemoteType.IsLocal()). Motivation: magic strings and scattered boolean logic reduce clarity and increase risk of inconsistent checks. Placing constants and small...wavetermdev/waveterm2 discussions
- Centralize database operationsKeep all SQL and DB-specific logic in a single dbops layer and expose a small, consistent API that handles common patterns: insert/update (use REPLACE/UPSERT), delete, queries, and serialization of complex fields. Motivation: reduces duplicated SQL across packages, avoids mismatch between INSERT vs UPDATE code paths, and centralizes...wavetermdev/waveterm2 discussions
- centralize configuration valuesKeep layout constants, feature flags, and user-configurable settings in centralized configuration modules (not hardcoded in components). Motivation: makes it easy to find and change UI "magic" values (e.g., tab width, spacing) and ensures behavior can be toggled per-environment or per-user (e.g., suppressing update banners when users turn off update checks).wavetermdev/waveterm2 discussions
- Avoid chatty mouse eventsMotivation: High-frequency events like mousemove are "chatty" and can cause excessive CPU usage and layout thrashing. Prefer lower-rate pointer events (mouseenter/mouseleave) or throttled handlers attached to specific elements, and minimize repeated DOM writes by toggling classes. Always attach and remove listeners in lifecycle hooks and guard against null...wavetermdev/waveterm2 discussions
- Workflow safety defaultsWhen authoring CI/CD workflows, make configuration choices that (1) match the actual capabilities required by downstream steps and (2) use conservative, contributor-safe defaults for automated cleanup.warpdotdev/warp2 discussions
- Optional Fallback DisciplineWhen working with nullable/optional values or external/runtime-provided fields, never assume presence or a specific concrete type/spelling. Instead: (1) explicitly treat inputs as optional, (2) provide deterministic fallbacks (often empty string/None/previous-state), (3) avoid dereferencing missing values, and (4) add tests for both “value present” and...warpdotdev/warp2 discussions
- Explicit logging for channelsWhen log behavior depends on configuration (e.g., `WARP_CHANNEL`) or when scripts auto-select an environment/tool (e.g., which Xcode app to use), make the behavior explicit and observable:warpdotdev/warp2 discussions
- Canonical Naming SourcesUse canonical, source-verified naming for identifiers and for artifact locations. Avoid guesses, stale references, or incidental structure (like username folders).warpdotdev/warp2 discussions
- Reproducible Docs With GuaranteesWhen updating technical docs, write them as executable, environment-aware workflows and as reliable behavioral descriptions. **1) Encode real constraints/workarounds**microsoft/VSCode2 discussions
- Prefer state inheritanceWhen styling component states (e.g., selected/active), keep descendant visuals consistent by using inheritance and tightly scoped rules—and manage the cascade without descendant-state selectors or `!important`.microsoft/VSCode2 discussions
- Descriptive semantic namingNames should accurately reflect their purpose and behavior, providing users and developers with clear expectations. For identifiers, use specific qualifiers that indicate their intended context rather than generic terms. For UI elements like commands, ensure the name accurately represents the behavior (e.g., only use ellipsis '...' when additional input...microsoft/vscode2 discussions
- Configuration naming conventionsWhen adding new configuration settings, follow these naming conventions to maintain consistency and clarity: 1. **For related components**: Use a unified setting with resource scope instead of creating duplicate settings. For example, instead of having separate `typescript.maximumHoverLength` and `javascript.maximumHoverLength` settings, create a single...microsoft/vscode2 discussions
- Use latest patch versionsWhen configuring dependencies in Dockerfiles and other configuration files, use the latest patch versions while keeping major and minor versions fixed. Patch versions typically contain important security fixes and bug corrections without introducing breaking changes. For example, prefer `golang:1.23.7` over `golang:1.23.0`, as "small versions will fix some...volcano-sh/volcano2 discussions
- Use controlled concurrency patternsImplement proper concurrency control mechanisms to prevent resource exhaustion and ensure thread-safe operations. Use sync.Once for thread-safe initialization to avoid memory leaks, and employ goroutine pools or semaphores to limit concurrent operations instead of spawning unlimited goroutines.volcano-sh/volcano2 discussions
- Review security permissionsCarefully review all security permissions and privileges to ensure they follow the principle of least privilege. Avoid coupling unrelated permissions together and verify that elevated privileges are truly necessary.volcano-sh/volcano2 discussions
- Resource-specific optimization factorsConfigure different optimization parameters for different resource types (CPU, memory, GPU) rather than applying uniform settings across all resources. Different resources have distinct characteristics and usage patterns that require tailored optimization strategies for maximum performance and utilization.volcano-sh/volcano2 discussions
- Protocol-specific network discoveryWhen implementing network topology discovery features, use discovery methods that are appropriate for the specific network protocol being used. Different network protocols have different architectures and require different approaches for topology discovery.volcano-sh/volcano2 discussions
- network topology plugin configurationWhen implementing network topology-aware scheduling, ensure that the appropriate topology plugins are properly configured for different scheduling modes. In hard mode, the scheduler should strictly enforce topology constraints, while in soft mode, it should prefer network locality but allow cross-topology scheduling when necessary.volcano-sh/volcano2 discussions
- Implement simulation testingWhen developing complex systems like schedulers or resource managers, create simulation-based testing frameworks to validate functionality in scenarios that cannot be easily reproduced in development environments. This approach enables testing of hardware configurations you don't have access to (GPU/NPU nodes), large-scale cluster behaviors, and parameter...volcano-sh/volcano2 discussions
- Avoid external configuration dependenciesWhen designing configuration management systems, avoid strong dependencies on external projects for configuration logic and data structures. External projects may not evolve at the same pace as your codebase, creating maintenance burdens and potential compatibility issues.volcano-sh/volcano2 discussions
- API validation consistencyEnsure API validation rules and type definitions remain consistent across all validation layers and components. When implementing validation logic, verify that kubebuilder annotations, manual validation functions, and API type definitions all enforce the same constraints and use compatible data types.volcano-sh/volcano2 discussions
- Optimize tensor memory operationsWhen working with PyTorch tensors, use memory-efficient operations that avoid unnecessary copies. Specify memory formats directly during tensor creation instead of applying operations like `.t().contiguous()`. For C++/CUDA kernel interfacing, use `.data_ptr()` instead of `.view(dtype)` to ensure safe memory access and maintain compatibility with future...vllm-project/vllm2 discussions
- Optimize GPU executionEnsure GPU code is optimized for both proper thread utilization and correct architecture dispatching: 1. **Maximize thread parallelism** - Design CUDA kernels to fully utilize available threads. When appropriate, use multi-dimensional grid configurations to parallelize across all relevant dimensions of your problem.vllm-project/vllm2 discussions
- Match reference namesEnsure that filenames and paths referenced in scripts, commands, or configuration files exactly match the actual names of the files they reference. Name mismatches between references and actual files can cause commands to fail during execution.vllm-project/vllm2 discussions
- Environment-aware configuration valuesWhen creating configuration files or defining configuration constants, ensure they properly adapt to different environments (Python versions, hardware architectures, etc.) with clear documentation. This prevents compatibility issues and helps other developers understand configuration choices.vllm-project/vllm2 discussions
- Combine identical CSSWhen multiple CSS selectors share identical styling properties, combine them using comma separation rather than duplicating the same rules. This reduces code duplication, improves maintainability, and makes stylesheets more concise.vllm-project/vllm2 discussions
- AI model persistenceWhen containerizing AI applications, ensure proper model persistence by mounting volumes to the default cache locations used by AI frameworks and setting appropriate environment variables. This prevents redundant downloads of large models and improves development efficiency.vllm-project/vllm2 discussions
- Validate environment configurationsEnsure that all environment-specific configurations work properly across all target environments, particularly when managing multiple architectures or CI systems. Test changes thoroughly in the actual environments where code will run. Document the purpose of specialized configurations and don't remove configuration blocks without verifying they're no longer...vitessio/vitess2 discussions
- Size fields appropriatelyWhen designing database schemas, choose field types and sizes that accommodate both current and anticipated future data volumes. Undersized fields can cause production issues and limit functionality when data grows beyond initial expectations. Additionally, ensure consistency between related fields that store similar data or participate in the same...vitessio/vitess2 discussions
- Pin environment versionsAlways use explicit version tags for CI/CD environments (runners, containers, images, tool versions) instead of floating references like 'latest'. This practice prevents unexpected breakages when upstream environments are updated and gives the team control over when to upgrade. When upgrading is necessary, do it in a dedicated PR to properly test the...vitessio/vitess2 discussions
- Manage workflow state transitionsWhen working with temporal workflows, always implement explicit state transitions rather than abrupt deletions. Workflows should proceed through well-defined states (like running, stopped, or frozen) to ensure proper lifecycle management and durable execution.vitessio/vitess2 discussions
- Justify CI resource additionsBefore adding new resources (Dockerfiles, jobs, images) to CI/CD pipelines, provide clear justification for their necessity and document how they will be maintained. Consider whether the resource will actually run in your CI environment, if existing resources could be reused, and who will maintain version updates. For example, instead of creating a new...vitessio/vitess2 discussions
- Document configuration precedenceWhen implementing multiple configuration methods (e.g., config files, command-line flags, environment variables), clearly document the precedence order and warn users about potential conflicts. Unclear precedence rules can lead to unexpected system behavior and difficult troubleshooting.vitessio/vitess2 discussions
- Database configuration best practicesWhen implementing or modifying database-related configurations, follow these principles: 1. Use semantically appropriate types for configuration parameters (e.g., `Duration` instead of `float` for time values)vitessio/vitess2 discussions
- Consistent database APIsDesign database APIs with consistent patterns for response structures and error handling. Follow established conventions in your codebase, even when it means returning empty response objects for error-only operations.vitessio/vitess2 discussions
- Clear metric documentationWhen adding, modifying, or deprecating metrics, ensure comprehensive and clear documentation. Include: 1. Descriptive names for new metrics that reflect their purposevitessio/vitess2 discussions
- Avoid skipping e2e testsDo not use the `skip_e2e` flag to bypass end-to-end tests that fail. Instead, fix the test implementation by providing appropriate test data or modifying the test to make it pass correctly. This maintains the integrity of the test suite and ensures that code changes are properly validated.vitessio/vitess2 discussions
- Vue component import handlingWhen working with Vue single-file components, pay special attention to how imports are processed, particularly with query parameters. URL handling can significantly impact module resolution and hot module replacement (HMR).vitejs/vite2 discussions
- Targeted yet comprehensiveWrite focused tests that verify specific functionality without unnecessary setup, while still ensuring complete coverage of edge cases. Instead of duplicating complex structures, create minimal test cases that target individual features directly.vitejs/vite2 discussions
- Separate configuration responsibilitiesDesign configuration files with clear separation of responsibilities and maintain flexibility for future changes. Avoid unnecessarily bundling configurations together when they serve different purposes, as this can create tight coupling and make future transitions difficult.vitejs/vite2 discussions
- Self-referential worker URLsWhen creating Web Workers for network communication, use self-referential URL patterns that are resilient to file renaming. This improves portability and reliability of your networking code.vitejs/vite2 discussions
- React transformation tool clarityWhen working with React in Vite projects, be precise about which transformation tools (Babel, SWC, Oxc, esbuild) handle specific aspects of React code processing. Different plugins use different tool combinations for JSX/TSX transformation versus React fast-refresh, and these can vary between development and build environments.vitejs/vite2 discussions
- Precise documentation languageUse specific and clear language in all documentation to improve user understanding and avoid ambiguity. Favor precise terminology over vague descriptors, while balancing specificity with maintainability concerns.vitejs/vite2 discussions
- Explicit version requirementsAlways specify explicit Node.js version requirements in configuration files to ensure compatibility with language features and APIs. When updating supported versions, verify feature compatibility and document reasoning behind version constraints.vitejs/vite2 discussions
- Document protocol configurations clearlyWhen documenting network protocol configurations (TLS, HTTP/2, CORS), provide specific details about required options, default values, and explicit behavior. Avoid ambiguous terminology like "sufficient values" and instead specify exactly what options are needed and how different settings interact.vitejs/vite2 discussions
- Configure SSR environmentsWhen implementing server-side rendering in Next.js projects that use Vite as a bundler, ensure proper environment separation between client and server code. Create distinct module execution environments to prevent leaking server-only code to the client and to support hot module replacement (HMR) during development.vitejs/vite2 discussions
- Complete deployment commandsAlways ensure build commands in CI/CD configurations include all necessary steps for successful deployment, particularly dependency installation. Incomplete commands are a common source of deployment failures.vitejs/vite2 discussions
- Code example consistencyEnsure code examples in documentation and comments are syntactically correct and properly marked with the appropriate language identifier. This maintains a professional appearance and prevents readers from copying incorrect code.vitejs/vite2 discussions
- Clean network resourcesAlways properly close and clean up network connections to prevent memory leaks and resource exhaustion. When establishing WebSocket connections or other network resources, ensure they are explicitly closed and event listeners are removed when no longer needed. Additionally, implement resilient error handling strategies for network operations by using...vitejs/vite2 discussions
- use `-prod` for performanceAlways use the `-prod` compiler flag when building performance-critical code or running benchmarks. The `-prod` flag automatically enables essential optimization settings including `-O3` and `-flto` (Link Time Optimization), eliminating the need to manually specify these common performance flags.vlang/v2 discussions
- Test deployment edge casesEnsure that code paths handling different deployment environments (installation prefixes, target directories, etc.) have proper test coverage. Without tests for these scenarios, it's difficult to trust that the functionality works correctly across all supported environments.astral-sh/uv2 discussions
- Optimize docker build cachingLeverage Docker BuildKit's cache and bind mount capabilities to dramatically improve CI build times and reduce image sizes. Instead of copying source files into intermediate layers, use bind mounts to provide build context and cache mounts for package managers and build artifacts.astral-sh/uv2 discussions
- Document build configurationsWhen setting Rust build configurations, especially in CI/Docker environments, explicitly document optimization choices and their tradeoffs. Consider whether configurations should live in Cargo.toml, .cargo/config.toml, or as environment variables in CI scripts. For Docker builds, document RUSTFLAGS options like optimization levels, relocation models, and...astral-sh/uv2 discussions
- Cache sharing strategyWhen implementing caching in build systems, carefully configure cache sharing behavior based on your concurrency requirements. Improper sharing settings can lead to build failures when multiple processes attempt to access the same cache simultaneously.astral-sh/uv2 discussions
- Avoid unnecessary constraintsWhen specifying dependencies and version requirements in project configuration files, avoid adding unnecessary constraints that could limit future compatibility. Unless there's a specific known incompatibility issue:astral-sh/uv2 discussions
- Validate API parameter formatsEnsure API parameters match the expected format and structure of target APIs before runtime. Validate parameter types, required fields, and data structures during development rather than discovering mismatches through runtime errors.Unstructured-IO/unstructured2 discussions
- Use descriptive specific namesChoose names that clearly indicate their context and purpose rather than generic terms. Generic names can be ambiguous and make code harder to understand, especially when the same codebase handles multiple contexts or domains.Unstructured-IO/unstructured2 discussions
- separate formatting changesKeep formatting and style changes separate from functional code changes to maintain clear, reviewable diffs. When making functional changes, avoid simultaneously reordering imports, adjusting whitespace, or making other cosmetic modifications that obscure the actual logic changes. If formatting improvements are needed, submit them as standalone pull...Unstructured-IO/unstructured2 discussions
- Python version standardizationEstablish and document a consistent Python version standard for dependency compilation across the project. Team confusion about which Python version to use for pip-compile leads to build inconsistencies, compatibility issues, and wasted development time.Unstructured-IO/unstructured2 discussions
- Parameterize hardcoded configuration valuesReplace hardcoded values in configuration files with parameterized variables to improve flexibility and maintainability. Use build arguments (ARG) and environment variables (ENV) in Dockerfiles instead of embedding specific versions, paths, or other configuration values directly in the code.Unstructured-IO/unstructured2 discussions
- maintain established naming conventionsEnsure all naming follows established patterns and conventions already present in the codebase. When introducing new identifiers or modifying existing ones, they must conform to the team's built-in expectations and standard patterns to maintain consistency across the system.Unstructured-IO/unstructured2 discussions
- intentional naming patternsRecognize when seemingly redundant naming patterns serve specific technical purposes rather than being mistakes or oversights. Some naming conventions that appear duplicative are actually intentional and necessary for technical reasons.Unstructured-IO/unstructured2 discussions
- improve code readabilityFormat code to enhance readability and maintainability by breaking long lines and extracting repeated values into variables. Long command lines with multiple parameters should be split across multiple lines with proper line continuation, placing each parameter on its own line. When the same value (like URLs, paths, or configuration strings) appears multiple...Unstructured-IO/unstructured2 discussions
- Enhance documentation detailDocumentation should provide comprehensive detail that enables users to understand impacts and developers to understand implementation. For breaking changes, include migration guidance, deprecated features, and specific functional changes. For technical documentation, provide granular step-by-step explanations that trace execution flow.Unstructured-IO/unstructured2 discussions
- embedding provider configurationWhen configuring embedding providers in AI integrations, ensure proper dimension specification and use dedicated test files for different providers. Always specify the embedding dimension that matches your chosen provider (e.g., 384 for huggingface embedders) and avoid modifying existing configurations for testing purposes.Unstructured-IO/unstructured2 discussions
- Document configuration parameters clearlyWhen documenting configuration objects and their parameters, provide clear explanations of each parameter's purpose, whether it's required or optional, and why optional parameters are useful for development. Use backticks to format code symbols, parameter names, class names, and error types for better readability.Unstructured-IO/unstructured2 discussions
- Centralize configuration sourcesMaintain configuration settings in a single authoritative source to avoid duplication and inconsistencies across multiple files. When possible, use `pyproject.toml` as the primary configuration file and remove redundant specifications from other files like `.pre-commit-config.yaml` and `Makefile`.Unstructured-IO/unstructured2 discussions
- avoid hardcoded secretsNever include real API keys, passwords, or other sensitive credentials directly in source code, including example files and configuration. This creates security vulnerabilities and risks credential exposure in version control systems.Unstructured-IO/unstructured2 discussions
- Version serializable structuresAll serializable data structures that may evolve over time must include explicit versioning to enable backward and forward compatibility during migrations. This prevents breaking changes when schemas need to evolve and allows for graceful handling of different versions.unionlabs/union2 discussions
- Validate network addressesAlways validate network addresses according to their specific protocol requirements and maintain consistent encoding throughout the application. Different blockchain networks have distinct address formats and validation rules that must be enforced to prevent communication failures.unionlabs/union2 discussions
- validate input uniquenessAlways validate that input data is unique and matches expected values to prevent replay attacks and data manipulation vulnerabilities. This includes checking for duplicate submissions and verifying data integrity through hash comparisons.unionlabs/union2 discussions
- preserve original error codesWhen handling errors, preserve the original error information rather than replacing it with generic error constants. This maintains better debugging information and error traceability throughout the system.unionlabs/union2 discussions
- organize for readabilityStructure code to minimize repetition and improve clarity through appropriate abstraction and import organization. When code contains repetitive patterns, create wrapper functions to eliminate boilerplate. For modules with structured exports (like ADTs), prefer qualified imports over individual named imports to maintain clear namespace organization.unionlabs/union2 discussions
- Optimize database queriesWhen writing database queries, prioritize both performance and correctness. Avoid unnecessary joins that can significantly impact query performance - fetch only essential data and use separate services or caches for additional lookups. Also ensure your filtering logic doesn't inadvertently exclude valid records, particularly with boundary conditions.unionlabs/union2 discussions
- Mock external dependenciesAlways mock external dependencies in tests to ensure isolation and reliability. Unit tests should not make real network calls, database queries, or interact with external services. Mock implementations must provide the same interface and requirements as their live counterparts to maintain test validity.unionlabs/union2 discussions
- Environment-specific configuration valuesAvoid hardcoding configuration values that should vary between different deployment environments (testnet, mainnet, development). Instead, use environment variables, configuration files, or conditional logic to handle environment-specific settings.unionlabs/union2 discussions
- Environment-aware logging configurationConfigure logging behavior dynamically based on the current environment to ensure appropriate log levels and destinations for development, staging, and production contexts. Development environments should use verbose logging (Trace/Debug) for debugging, while production should use minimal logging (Warning/Error) for performance. External logging services...unionlabs/union2 discussions
- Ensure semantic precisionChoose names and identifiers that precisely convey their intended semantic meaning and avoid ambiguity or conflicts. Names should be specific enough to prevent confusion and clearly communicate their purpose within the codebase.unionlabs/union2 discussions
- Ensure comprehensive test coverageAll new functionality must include corresponding tests that verify both success and failure scenarios. When adding new functions or modifying existing behavior, write tests that cover the main functionality as well as edge cases and error conditions.unionlabs/union2 discussions
- Clean documentation linksWhen writing Rust documentation links, separate the display name from the full path to improve readability of generated docs. Use the short type name as the display text and provide the full path as the link target. This makes the documentation less noisy and easier to read.unionlabs/union2 discussions
- avoid unnecessary memory operationsBe mindful of memory usage when working with large data structures. Avoid unnecessary clones of large objects, remove unused large fields from data structures, and prefer references when possible. Large data structures can significantly impact both memory usage and execution speed.unionlabs/union2 discussions
- avoid suppressing TypeScript errorsDo not use `@ts-expect-error` comments to suppress TypeScript errors, especially those related to null, undefined, or type safety. These errors are designed to catch potential runtime issues and should be properly resolved instead of silenced.unionlabs/union2 discussions
- Use concise methodsPrefer built-in methods and properties that achieve the same result with less code. This improves readability, reduces potential bugs, and makes your code more maintainable.shadcn-ui/ui2 discussions
- Use cross-platform build commandsReplace native shell commands in package.json scripts with cross-platform alternatives to ensure build consistency across different operating systems. Native commands like `rm -rf` fail on Windows, breaking CI/CD pipelines that run on mixed environments.bytedance/UI-TARS-desktop2 discussions
- Native fetch over dependenciesPrefer Node.js native fetch API over external HTTP client libraries like `node-fetch` when the target Node.js version supports stable native functionality. While fetch is available from Node.js 18+, it's considered stable from version 21 onwards.bytedance/UI-TARS-desktop2 discussions
- Externalize configuration valuesAvoid hard-coding configuration values directly in source files. Instead, externalize them using environment variables, configuration files, or external resources. This improves maintainability, enables environment-specific settings, and reduces bundle sizes.bytedance/UI-TARS-desktop2 discussions
- Preprocess data earlyTransform and prepare data structures at their source rather than during consumption. This includes flattening nested objects, sorting collections, and other manipulations that make data more efficient to process downstream.shadcn-ui/ui2 discussions
- Optimize documentation for usabilityWhen creating component documentation, prioritize the developer experience by providing clear, usable examples and configurations. For Storybook components, configure props documentation thoughtfully—rather than removing props like `children` from the table entirely, consider using more specific controls:shadcn-ui/ui2 discussions
- Consistent import pathsEstablish and follow consistent import path conventions throughout the codebase. Prefer aliased imports using the project's path aliases (e.g., `@/src/utils/get-initial-values`) over relative imports to ensure consistency and improve maintainability. This practice creates uniform import statements across files regardless of their location in the project...shadcn-ui/ui2 discussions
- Use TypeScript-specific testsAlways use fourslash tests (for IDE/language service features) or compiler tests (for TypeScript compilation behavior) instead of direct unit tests. Place tests in the correct directories: `tests/cases/compiler` or `tests/cases/fourslash`.microsoft/typescript2 discussions
- Use absolute pathsWhen specifying file paths in configuration files (like ESLint or TypeScript configs), use absolute paths rather than relative paths to avoid path resolution issues. Tools may interpret relative paths differently based on their internal working directory, leading to unexpected behavior.microsoft/typescript2 discussions
- Streamline workflow configurationsMaintain efficient and properly structured CI/CD workflows by removing unnecessary dependencies and using consistent formatting patterns. Each workflow step should serve a specific purpose for the job it's part of, and matrix configurations should follow a consistent structure.microsoft/typescript2 discussions
- Consistent module resolutionConfigure consistent module resolution strategies across related projects and ensure package.json files are properly set up for the chosen strategy. Different strategies (Node10, NodeNext) have distinct behaviors regarding package.json handling, which can cause subtle resolution errors and confusing tracing output.microsoft/typescript2 discussions
- Consistent message terminologyUse clear, consistent terminology in all error messages and user-facing text. Avoid technical jargon that might confuse users, and maintain consistency in language patterns across the codebase:microsoft/typescript2 discussions
- Actionable error messagesWhen designing APIs, provide error messages that are contextually accurate, descriptive, and actionable. Generic error suggestions can confuse users when they don't apply to the specific situation. Instead, tailor error responses to include:microsoft/typescript2 discussions
- Single source of truthEstablish a single authoritative source for each piece of data in your API interfaces rather than maintaining duplicate or parallel state. Derive computed values from the authoritative source instead of storing them separately.twentyhq/twenty2 discussions
- optimize data structure lookupsChoose data structures that provide optimal time complexity for your access patterns. When you need frequent lookups by key, use Map instead of Record with Array.find() operations to achieve O(1) instead of O(n) complexity.twentyhq/twenty2 discussions
- Follow React component patternsReact components should be rendered as standard JSX elements, not called as functions, and should follow established architectural patterns. This ensures consistency with React conventions and maintainability.twentyhq/twenty2 discussions
- Enforce restrictive security defaultsAlways start with the most restrictive security settings and only grant additional permissions when absolutely necessary. This principle applies to user authorization, iframe sandboxing, API access, and any security-sensitive features.twentyhq/twenty2 discussions
- Verify test commandsAlways verify that test commands documented in project guides work exactly as written. Test commands should be copy-paste executable without modification. When adding or updating test command examples in documentation:vercel/turborepo2 discussions
- Use workspace dependencies consistentlyAlways use workspace-level dependency declarations (`workspace = true`) rather than specifying exact versions in individual crates. This ensures consistency across your project, simplifies maintenance, and reduces the risk of version conflicts.vercel/turborepo2 discussions
- Use JSDoc deprecation standardsWhen marking code as deprecated, use JSDoc standards to provide clear guidance for developers. Always use the `@deprecated` tag followed by when it was deprecated and what should be used instead. Additionally, use the `{@link}` tag to create clickable references to replacement functionality.vercel/turborepo2 discussions
- Use environment-aware configurationsConfigure paths and system references dynamically to ensure they work across all environments (development, testing, production). Avoid hardcoded paths or environment-specific values that will break when code is packaged or deployed.vercel/turborepo2 discussions
- Link terms, provide examplesWhen writing technical documentation, link to related concepts the first time they are mentioned, and include concrete examples to illustrate complex features or functionality.vercel/turborepo2 discussions
- Hybrid monorepo testingWhen working with tests in a monorepo, implement a hybrid testing approach that balances local development experience with CI performance. Set up local Vitest configurations in each package while also configuring a root workspace for unified testing. This preserves Turborepo's caching benefits in CI while providing a better developer experience.vercel/turborepo2 discussions
- Handle errors appropriatelyImplement appropriate error handling strategies based on the criticality of operations. For non-critical operations that could fail (like file operations and JSON parsing), use try/catch blocks to handle errors gracefully and continue execution with proper logging. For critical operations where execution cannot reasonably continue, provide clear error...vercel/turborepo2 discussions
- Graceful error recoveryImplement error handling that accumulates diagnostics rather than failing immediately, especially for operations that could help users identify and fix problems. Design systems to continue functioning when possible, with configurable strictness levels.vercel/turborepo2 discussions
- Framework-specific entrypoints organizationWhen creating libraries that integrate with Next.js or other frameworks, organize your code with separate entrypoints for each supported framework. This approach improves bundling efficiency, prevents dependency conflicts, and makes framework-specific code easier to maintain.vercel/turborepo2 discussions
- Design for testabilityExtract complex logic into separate, pure functions to improve testability. Functions with clear inputs and outputs are easier to test in isolation without complex mocking or setup.vercel/turborepo2 discussions
- Consider config generation methodsWhen implementing code to handle configuration files like lockfiles or environment settings, carefully consider the trade-offs between direct serialization and template-based approaches. While direct serialization from data structures is often simpler and less error-prone, template-based generation may provide better control over formatting, whitespace...vercel/turborepo2 discussions
- validate inputs earlyFunctions should validate input parameters at the beginning and return appropriate error indicators (like false, null, or error codes) rather than proceeding with invalid data. This prevents downstream errors and provides clear feedback to callers about invalid usage.tree-sitter/tree-sitter2 discussions
- validate algorithmic inputsAlways validate inputs and handle edge cases before performing algorithmic operations, especially when dealing with indices, state transitions, or data structure traversals. Check for boundary conditions, invalid states, and null/undefined values that could cause out-of-bounds access or undefined behavior.tree-sitter/tree-sitter2 discussions
- target-specific CMake configurationsUse target-specific CMake commands instead of global ones to ensure proper scoping and avoid polluting the global build environment. This improves maintainability and prevents unintended side effects when building multiple targets.tree-sitter/tree-sitter2 discussions
- Strategic configuration exclusionsWhen configuring build exclusions in package manifests or configuration files, be strategic and minimal. Only exclude files that cause actual build issues (like non-source files that generate compilation warnings), while preserving important files such as licenses and directories that may be relevant for future features. Modern tooling often handles file...tree-sitter/tree-sitter2 discussions
- optimize memory usage patternsFocus on reducing memory footprint and improving cache efficiency through careful data structure design and function parameter optimization. Consider using smaller data types when the value range permits, and design function interfaces to minimize memory overhead.tree-sitter/tree-sitter2 discussions
- measure performance implicationsWhen making design decisions that could impact performance, evaluate resource implications and provide concrete measurements rather than assumptions. Consider memory usage, binary size, and allocation patterns in your choices.tree-sitter/tree-sitter2 discussions
- Ensure semantic naming clarityNames should clearly convey their semantic purpose and avoid conflicts that reduce code readability. This applies to imports, types, variables, and methods.tree-sitter/tree-sitter2 discussions
- Document configuration changesWhen modifying configuration files (tsconfig.json, environment configs, build settings, etc.), always provide clear explanations for why the changes are necessary, what benefits they provide, and any potential impacts. Configuration changes can significantly affect build processes, development workflows, and application behavior, so reviewers and future...tree-sitter/tree-sitter2 discussions
- descriptive naming patternsUse descriptive names that clearly indicate the expected format, convention, or constraints. This applies to template variables, configuration keys, and validation patterns. Names should communicate not just what something is, but how it should be formatted or what rules it follows.tree-sitter/tree-sitter2 discussions
- Cross-platform configuration examplesEnsure configuration examples and documentation work across different operating systems and clearly distinguish between required and optional configuration steps. Avoid platform-specific syntax that may not work universally, and explicitly state when configuration steps are optional versus mandatory.tree-sitter/tree-sitter2 discussions
- consolidate related loggingWhen logging information about the same operation or context, combine multiple related log statements into a single, comprehensive message rather than using separate log calls. This reduces log noise, improves readability, and can enhance performance by reducing the number of logging function calls.tree-sitter/tree-sitter2 discussions
- Complete technical documentationWhen documenting technical features, APIs, or data structures, provide comprehensive coverage that includes related functionality and detailed explanations rather than minimal inline comments. tree-sitter/tree-sitter2 discussions
- CMake custom command designWhen implementing CMake build automation for code generation, carefully choose between `add_custom_command` and `add_custom_target` based on your execution requirements. Use `add_custom_command` with explicit OUTPUT and DEPENDS for files that should be automatically generated when missing or when dependencies change. Add `add_custom_target` only when you...tree-sitter/tree-sitter2 discussions
- Clarify API documentationAPI documentation should provide clear, unambiguous explanations of function behavior, return values, and edge cases. Avoid vague or obscure wording that leaves developers guessing about implementation details.tree-sitter/tree-sitter2 discussions
- automate frequent releasesImplement automated release workflows to publish updates frequently and consistently across all distribution channels. Manual release processes create bottlenecks that force consumers to pin dependencies to specific commit SHAs instead of using stable releases.tree-sitter/tree-sitter2 discussions
- Assert null before accessWhen asserting conditions on potentially null pointers, always check for null first before accessing the pointer's properties or members. This prevents segmentation faults and makes null expectations explicit in the code.tree-sitter/tree-sitter2 discussions
- API type definition consistencyWhen modifying API type definitions, ensure all related definition files are updated consistently and dependencies are properly managed. API types often exist in multiple formats (TypeScript definitions, JSON schemas, etc.) and must be kept in sync to maintain a coherent client interface.tree-sitter/tree-sitter2 discussions
- API documentation synchronizationEnsure that all API documentation, including code examples and integration guides, accurately reflects the current API state. When API changes occur (such as import/export modifications, new entry points, or version compatibility updates), corresponding documentation must be updated immediately to prevent developer confusion and integration errors.tree-sitter/tree-sitter2 discussions
- provide contextual error informationEnsure error messages and logging provide sufficient context to understand what failed and why. Include relevant details such as server addresses, operation types, configuration values, or other identifying information that helps with debugging and troubleshooting.traefik/traefik2 discussions
- proper context handlingAlways propagate contexts consistently throughout the call chain and handle context cancellation properly in concurrent operations. When a context is available in the current scope, reuse it instead of creating a new background context. For operations that may block (like time.Sleep), use context-aware alternatives to prevent goroutine leaks when requests...traefik/traefik2 discussions
- optimize selection algorithmsWhen implementing selection algorithms that choose from a pool of candidates, design the algorithm to filter invalid options during the selection process rather than using retry logic after selection. Additionally, always include termination conditions to prevent infinite loops when no valid candidates remain.traefik/traefik2 discussions
- Health check lifecycle completenessEnsure health check systems are not only created but also properly launched and integrated with observability infrastructure. Health checkers must follow the complete lifecycle: creation, launch, and metrics integration.traefik/traefik2 discussions
- avoid external dependenciesUnit tests should not depend on external components like databases, Redis, or Kubernetes clusters. Instead, create fake implementations or use mocks to isolate the code under test. Reserve integration tests for scenarios that require real external services.traefik/traefik2 discussions
- Follow established naming conventionsAdhere to established naming conventions consistently throughout the codebase, prioritizing official documentation standards when available. Use appropriate case conventions (ALL_CAPS for constants, descriptive names for variables) and maintain consistency with external API standards.bytedance/trae-agent2 discussions
- Externalize hardcoded configurationsConfiguration values should be externalized to environment variables rather than hardcoded in the source code. This improves flexibility, security, and deployment across different environments.bytedance/trae-agent2 discussions
- Concise, Consistent StateAdopt a style rule that keeps code (1) concise in data derivation, (2) consistent in input normalization, and (3) correct in conditional logic by using the right source of state.TauricResearch/TradingAgents2 discussions
- Cache deterministic resultsWhen an operation is deterministic and expensive (often due to external IO like `yfinance`), avoid doing the same work twice. Use bounded memoization for repeated lookups and explicitly short-circuit cases where two inputs resolve to the same underlying entity. Also ensure caches don’t leak between tests.TauricResearch/TradingAgents2 discussions
- Align Mount PathsWhen configuring Docker bind mounts (or any persistence paths), set the container mount target to exactly where the application writes at runtime—especially when code uses relative paths like `Path.cwd() / "..."`. Don’t pick mount targets by convention; derive them from the actual path resolution logic.TauricResearch/TradingAgents2 discussions
- Test production configurations tooInclude testing configurations that mirror production environments to catch issues that might only manifest in release builds. For example, testing with panic=abort can reveal issues that wouldn't appear when testing with the default panic=unwind setting. Similarly, when using specialized testing tools like Miri, configure the appropriate flags to ensure...tokio-rs/tokio2 discussions
- Test diverse configurationsConfigure test suites to run under multiple specialized environments to catch issues that might not appear in standard test runs. This includes testing with different compiler configurations, using specialized testing tools, and properly preserving environment variables when adding test-specific flags.tokio-rs/tokio2 discussions
- Simplify configuration flagsKeep configuration flags, feature toggles, and build settings concise and well-organized. Use simpler names where appropriate and consolidate related flags when possible to improve readability and maintainability.tokio-rs/tokio2 discussions
- Version AI dependencies appropriatelyWhen adding or updating dependencies for AI/ML libraries in your project, follow these two key practices: 1. **Set appropriate version constraints** that balance stability with access to improvements. For rapidly evolving AI libraries like HuggingFace Hub, avoid overly restrictive upper bounds that prevent compatible updates, but also avoid excessively...huggingface/tokenizers2 discussions
- Use explicit assertionsTests should assert specific expected values rather than just verifying general functionality. This practice makes tests more robust against subtle regressions and helps catch "under the radar" bugs where behavior is modified unintentionally.huggingface/tokenizers2 discussions
- Test algorithmic behaviorWhen testing algorithms, verify their actual functionality rather than just checking for proper instantiation or property modification. Ensure your tests capture the core behaviors of the algorithm under various parameters.huggingface/tokenizers2 discussions
- Smart configuration defaultsPrefer smart configuration defaults that auto-detect the environment instead of requiring explicit configuration flags. When possible, implement automatic detection of the runtime context and provide sensible defaults while still allowing explicit overrides.huggingface/tokenizers2 discussions
- Robust workflow configurationsEnsure CI/CD workflow configuration files follow best practices for maintainability and correctness: 1. Use centralized dependency management approaches like setup tools extras instead of hardcoding dependencies in workflow files:huggingface/tokenizers2 discussions
- Prioritize tokenizer simplicityWhen implementing AI model components like tokenizers, favor simplicity over rarely-used features that significantly increase code complexity. This is especially important for performance-critical paths in machine learning pipelines. Consider removing or deferring implementation of features that:huggingface/tokenizers2 discussions
- Flexible tokenizer implementationWhen implementing tokenizers for AI models, ensure flexibility and robust behavior across different contexts: 1. Initialize tokenizers with all relevant parameters to maintain consistent behavior:huggingface/tokenizers2 discussions
- Document for comprehensionAdd comprehensive documentation that helps others understand both the interface and implementation of your code. This includes: 1. **Detailed parameter documentation** in docstrings with type information and purpose descriptions, especially for new or non-obvious parametershuggingface/tokenizers2 discussions
- Consistent API designWhen designing and modifying APIs, ensure consistency in parameter naming, default values, and which functionality is exposed. Each API design decision should:huggingface/tokenizers2 discussions
- Secure checkout configurationsWhen configuring GitHub Actions workflows, pay special attention to the checkout action's configuration to ensure both correctness and security: 1. In `pull_request_target` workflows, always specify the reference explicitly to ensure you're working with the intended branch:hashicorp/terraform2 discussions
- Explicit dependency graphWhen implementing algorithms involving dependencies between components or operations, model the dependency graph explicitly rather than relying on implicit ordering. Explicit graph modeling facilitates cycle detection, enables parallel execution of independent operations, and provides clear visualization of relationships between components.hashicorp/terraform2 discussions
- Descriptive migration functionsName migration-related functions descriptively to convey their exact purpose and context of use. Include detailed documentation explaining when and how each function should be executed in the migration workflow. For example, instead of ambiguous names like `maintenancerelease`, use more specific terms like `setupBackportBranch` or `prepareMaintenanceBranch`...hashicorp/terraform2 discussions
- Specify security requirementsAlways explicitly declare security requirements and provide clear security guidance in both configuration files and user-facing content. When operations require elevated privileges, specify the security context to ensure proper UAC prompting. When features have security implications, include explanatory text to help users make informed decisions.microsoft/terminal2 discussions
- Protocol response formattingWhen implementing terminal protocol responses (CSI, DCS, OSC sequences), ensure proper formatting with correct terminators and maintain protocol transparency. Terminal protocols require specific response formats with appropriate terminators - CSI responses should use the same C1 mode as the request, DCS responses need proper DCS/ST framing, and OSC...microsoft/terminal2 discussions
- API clarity over convenienceWhen designing APIs, prioritize clarity and self-documentation over implementation convenience. Choose interface patterns that make the code's intent immediately obvious to consumers and debuggers.microsoft/terminal2 discussions
- Add comprehensive explanatory commentsWhen code involves complex relationships between multiple components or non-obvious usage patterns, add comprehensive explanatory comments that consolidate key information in one accessible location. This is especially important for files with multiple structs, classes, or APIs that work closely together.microsoft/terminal2 discussions
- Verify platform compatibility firstWhen writing networking code that interacts with platform-specific features, always check for the existence of platform-specific functions or resources before attempting to use them. This prevents runtime errors when your code runs in different environments (Windows, Linux, macOS, containers) that might have different capabilities or implementations.tensorflow/tensorflow2 discussions
- Use modern assertionsAlways use current assertion methods in test code to ensure clarity and future compatibility. Specifically, replace deprecated methods with their modern equivalents, such as using `assertRaisesRegex` instead of `assertRaisesRegexp` when validating exceptions. This approach allows you to verify both the exception type and the specific error message content...tensorflow/tensorflow2 discussions
- Secure infrastructure maintenanceMaintain CI/CD infrastructure with security and currency as top priorities. This includes: 1. **Keep build tools updated**: Always use the latest stable versions of build tools and dependencies in CI/CD environments to benefit from bug fixes, security updates, and improved features.tensorflow/tensorflow2 discussions
- Parameterize ci/cd scriptsAvoid duplicating CI/CD scripts by leveraging configuration files and parameterization instead of creating multiple similar scripts for different platforms or build scenarios. Use platform-specific configuration options in shared config files (like .bazelrc) or make scripts accept parameters for variant behaviors.tensorflow/tensorflow2 discussions
- Framework migration instructionsWhen documenting AI framework migrations (like TensorFlow/Keras version changes), provide complete instructions covering both installation and code modifications. Include:tensorflow/tensorflow2 discussions
- Format lines and commentsEnsure all code follows formatting guidelines for readability and consistency. Keep lines under 80 characters, splitting longer lines appropriately across multiple lines when needed. All comments should be written as complete sentences with proper capitalization and ending punctuation.tensorflow/tensorflow2 discussions
- Document non-obvious codeAdd clarifying comments to improve code readability and maintainability when code behavior isn't immediately obvious. Two key practices to follow: 1. **Label non-obvious function arguments** with the `/*arg=*/` prefix to clarify their purpose. This is especially important for boolean flags, magic numbers, or default values where the meaning isn't...tensorflow/tensorflow2 discussions
- Consistent variable namingUse ALL_CAPS for constants and environment variables in shell scripts, and reference these variables consistently throughout the script with proper quoting. This improves code readability and prevents errors when handling paths with spaces.tensorflow/tensorflow2 discussions
- Build dependency synchronizationWhen adding new imports to code files, always synchronize by updating the corresponding dependencies in BUILD files. Different build environments enforce dependency rules with varying strictness, so proper configuration is essential even if local builds succeed. This helps prevent errors like:tensorflow/tensorflow2 discussions
- Be explicit in referencesWhen writing documentation, always be specific and explicit when referring to files, tools, configurations, or other elements. Vague references create confusion and require readers to make assumptions or search for additional context.tensorflow/tensorflow2 discussions
- Protocol buffer organizationWhen defining protocol buffer messages, prioritize good organization and reuse: 1. Reuse existing message types instead of duplicating structures. This reduces maintenance effort and prevents potential bugs from diverging implementations.temporalio/temporal2 discussions
- Protobuf extensibility patternsWhen designing Protocol Buffer APIs, use `oneof` fields to create extensible message structures that maintain compatibility while providing type safety. This pattern allows APIs to evolve over time by adding new message variants without breaking existing clients.temporalio/temporal2 discussions
- Optimize API consumptionWhen interacting with APIs, minimize network requests and improve code maintainability by: 1. Extracting repetitive API call patterns into reusable functionstemporalio/temporal2 discussions
- Explicit CI configuration conditionsWhen writing CI/CD workflow configurations, always use explicit and precise conditions, paths, and selectors to ensure that actions only execute when necessary and operate on the exact intended targets. This prevents wasted compute resources, unintended side effects, and improves workflow reliability.temporalio/temporal2 discussions
- Configure OpenTelemetry programmaticallyConfigure OpenTelemetry programmatically rather than through environment variables or command-line flags. This creates a more maintainable and standardized approach to observability. Additionally, ensure all observability components like collectors are explicitly included in your deployment configurations.temporalio/temporal2 discussions
- Analyze algorithm tradeoffsWhen implementing functionality that involves multiple possible algorithmic approaches, explicitly analyze the complexity tradeoffs between alternatives before making a decision. Consider factors such as:temporalio/temporal2 discussions
- validate before accessAlways check for null, empty, or unset values before accessing or processing them, and return meaningful errors when validation fails. This prevents runtime panics and provides clear feedback about missing required data.gravitational/teleport2 discussions
- Use semantic HTML elementsWhen creating interactive components in React, use proper HTML semantic elements as the foundation, even when using styled-components. Interactive elements should be actual buttons, links, or form controls rather than generic divs or spans with click handlers.gravitational/teleport2 discussions
- Safe null handlingAlways handle potentially null or undefined values defensively using appropriate JavaScript patterns. Choose the right technique based on your specific needs:gravitational/teleport2 discussions
- parameterize configuration valuesAvoid hardcoded values in configuration files and templates. Make settings parameterizable with sensible defaults to accommodate different environments and use cases. Even when you're unsure if a setting needs to be configurable, err on the side of flexibility - most users will stick with defaults, but those who need customization will appreciate the option.gravitational/teleport2 discussions
- Network address clarityWhen documenting or configuring network addresses, DNS names, and IP addresses, be explicit about traffic direction and ensure uniqueness to prevent conflicts and ambiguity.gravitational/teleport2 discussions
- Follow platform naming conventionsAlways use the correct naming conventions for the platform you're working with, particularly React and HTML standards. React has specific prop naming requirements that differ from HTML attributes, and using incorrect names can cause functionality to break or behave unexpectedly.gravitational/teleport2 discussions
- Environment variable precedenceWhen working with environment variables in configuration management, ensure proper precedence handling and use clean fallback patterns. Environment variables can be inherited by subprocesses unexpectedly, potentially overriding command-line flags or other configuration sources.gravitational/teleport2 discussions
- Environment-specific configuration identifiersUse distinct, environment-specific identifiers in configuration to prevent conflicts between different application contexts (development vs production, different versions, etc.) and ensure semantic clarity.gravitational/teleport2 discussions
- Design intuitive query interfacesWhen designing algorithms for querying, filtering, or data manipulation, prioritize user-friendly function names and interfaces over technically precise but obscure terminology. Users should be able to understand and use your algorithmic interfaces without deep technical knowledge of the underlying implementation.gravitational/teleport2 discussions
- Design comprehensive metricsWhen designing observability metrics, ensure they are explicit about all possible states, comprehensive in scope, and clearly documented to avoid ambiguity. Metrics should accurately represent what is being monitored and make their limitations transparent.gravitational/teleport2 discussions
- defensive error handlingImplement defensive programming practices to prevent runtime errors and provide meaningful error information when failures occur. This includes validating object state before operations and ensuring error messages contain specific contextual details.gravitational/teleport2 discussions
- Database query parameter hygieneEnsure all database query parameters serve a clear purpose and are properly utilized. Remove unused filter parameters that create confusion and verify that necessary filtering conditions are not accidentally omitted during refactoring.gravitational/teleport2 discussions
- avoid platform-specific CI featuresAvoid using CI platform-specific features in workflows to prevent vendor lock-in and ensure portability. Instead of relying on GitHub Actions artifacts, Docker Hub registries, or other platform-specific storage mechanisms, use cloud-agnostic alternatives like S3 for artifact storage and transfer between jobs.gravitational/teleport2 discussions
- Assess optimization necessityEvaluate whether performance optimizations are actually needed based on your specific context, data size, and operation cost. Avoid implementing optimizations that add complexity without meaningful benefit.gravitational/teleport2 discussions
- Swift style consistencyMaintain consistent Swift style conventions throughout all code, including examples in documentation and comments. Follow these specific guidelines: 1. Use 4-space indentation for all Swift codetensorflow/swift2 discussions
- Minimize cross-device transfersData transfers between different compute devices (CPU/host to GPU/accelerator and back) can significantly impact performance in heterogeneous computing environments. Each transfer introduces latency and can block computation pipelines. Pay special attention to round-trip patterns where data moves from device A to B and back to A, as these create...tensorflow/swift2 discussions
- Follow Swift conventionsWhen designing and documenting APIs in Swift, adhere to Swift's established naming conventions and documentation practices: 1. **Use correct initializer syntax**: Swift initializers should not form phrases with argument labels. Avoid prepositions in argument labels.tensorflow/swift2 discussions
- Handle AI provider inconsistenciesWhen integrating with AI model providers, implement defensive programming to handle API inconsistencies, bugs, and unexpected return types. AI provider libraries often have implementation bugs or return different types than documented, requiring robust error handling and type checking.SWE-agent/SWE-agent2 discussions
- Document configuration decisionsWhen making configuration changes, especially those involving version specifications or constraints, include explanatory comments with links to relevant issues, PRs, or documentation. This provides context for future maintainers and makes the reasoning behind configuration decisions transparent and traceable.SWE-agent/SWE-agent2 discussions
- Document configuration clarityEnsure all configuration options and setup instructions are clearly documented with their intended purposes, use cases, and the most accessible implementation paths. When introducing new configuration classes or setup steps, include contextual descriptions that help users understand when and why to use each option.SWE-agent/SWE-agent2 discussions
- Write clear test casesTests should be written with clear intent and expectations. Use descriptive names that accurately reflect what the test validates, and include both positive and negative test cases to demonstrate expected behavior through contrast. Organize tests in appropriate suites based on their purpose (e.g., validation tests vs. runtime tests).sveltejs/svelte2 discussions
- Validate configuration interdependenciesWhen configuration options have logical dependencies or constraints, implement both smart defaults and validation checks to ensure consistent behavior. Set dependent options to appropriate default values based on other configuration values, and validate that the final combination of options represents a valid state.sveltejs/svelte2 discussions
- SSR documentation clarityEnsure server-side rendering documentation is grammatically correct and clearly explains the differences between server and client contexts. Documentation should explicitly describe hydration behavior, performance implications, and function availability constraints.sveltejs/svelte2 discussions
- Runtime HTML escapingHTML escaping must occur at runtime, not during compilation or build time, to properly prevent XSS vulnerabilities. When content is escaped too early in the process, it may not account for dynamic values or runtime context that could introduce security risks.sveltejs/svelte2 discussions
- optimize computational complexityWhen implementing algorithms, especially in runtime or performance-critical code, prioritize computational efficiency by minimizing redundant operations and simplifying mathematical expressions. Look for opportunities to reduce the number of multiplications, divisions, and variable assignments.sveltejs/svelte2 discussions
- Justify configuration changesWhen making configuration changes, especially dependency upgrades, provide clear justification for why the change is necessary rather than simply updating to the latest version. Explain the specific benefits, required features, or problems being solved.sveltejs/svelte2 discussions
- Format complex CSS selectorsWhen working with complex CSS selectors that include multiple nested pseudo-selectors like `:is()`, `:where()`, `:not()`, and `:has()`, maintain consistent formatting and consider breaking long selector chains for better readability. This is particularly important in Svelte components where selectors may need `:global()` wrappers.sveltejs/svelte2 discussions
- Follow snake_case conventionConsistently use snake_case naming throughout the codebase for variables, methods, and identifiers to maintain established conventions. When the codebase has adopted snake_case as the standard, all new code should follow this pattern rather than introducing camelCase or other naming styles.sveltejs/svelte2 discussions
- Document non-obvious behaviorWrite documentation that explains behavior and context that may not be obvious to newcomers, even if it seems clear to experienced developers. Include explanations for domain-specific concepts, data structure representations, and implicit behaviors that could confuse someone unfamiliar with the codebase.sveltejs/svelte2 discussions
- avoid unclear abbreviationsUse clear, descriptive names instead of abbreviated variable names that reduce code readability. Abbreviations like `mult` should be replaced with more conventional or descriptive alternatives. Additionally, maintain consistent naming conventions: use `snake_case` for internal code and `camelCase` for user-facing APIs.sveltejs/svelte2 discussions
- Sync API contractsEnsure API interfaces are trustworthy and API calls fail safely. - Keep typed client contracts aligned with backend reality: if an endpoint exists but is missing from the typed client, prefer updating the contract (or generating client types) over using `disableValidation`. If you must bypass validation temporarily, add a tracked justification.supermemoryai/supermemory2 discussions
- Use null strategicallyWhen handling empty or missing values, be intentional about using `null`, `undefined`, or empty strings based on how downstream systems interpret these values. In particular, when working with database operations (like PostgreSQL), use `null` instead of empty strings for fields that need to be cleared or constraints that should be dropped.supabase/supabase2 discussions
- Use appropriate HTTP methodsChoose HTTP methods that align with the actual operation being performed. Use GET for retrieving data with query parameters, and POST for operations that modify state or require complex request bodies.supabase/supabase2 discussions
- Sync environment variablesWhen converting hardcoded values to environment variables in configuration files (like docker-compose.yml), always update corresponding example files (e.g., .env.example) with appropriate default values. This ensures that developers can use standard setup processes without additional manual configuration.supabase/supabase2 discussions
- Safe database operationsWhen modifying database structures or executing dynamic SQL queries, prioritize both performance and safety: 1. **Use non-blocking operations** for schema changes in production databases. For example, when creating indexes on potentially busy tables, use `CREATE INDEX CONCURRENTLY` instead of standard `CREATE INDEX`:supabase/supabase2 discussions
- Optimize large field queriesWhen working with database queries that process large text fields or arrays, choose operations that minimize data conversion and processing overhead. This can lead to dramatic performance improvements.supabase/supabase2 discussions
- Consistent case styleUse consistent case styles in your codebase, adapting to the conventions of the ecosystem you're interacting with. When working with systems that use snake_case (like many Python-based backends, databases, or MCP servers), maintain that convention in your interfaces to those systems.supabase/supabase2 discussions
- Connection resilience patternsImplement resilient networking connections with retry mechanisms for all client-service interactions. When establishing connections to external services or databases, include proper retry logic with backoff strategies to handle temporary network instabilities or service unavailability. Monitor connection counts and states across different connection types...supabase/supabase2 discussions
- Concise performance documentationWhen documenting performance metrics, benchmarks, or scalability information, prioritize clarity and conciseness. Avoid redundant wording, use consistent terminology when listing features, and structure information in a scannable format. Clear performance documentation helps developers understand system capabilities, set appropriate expectations, and make...supabase/supabase2 discussions
- Avoid code duplicationMaintain clean, maintainable code by avoiding duplication and following proper code organization principles: 1. Place utility functions in dedicated utility files rather than defining them inline within component filessupabase/supabase2 discussions
- Keep build scripts portableBuild scripts should remain environment-agnostic and free from personal customizations or assumptions about end-user needs. Avoid including local-specific commands (like clipboard operations) and let consumers make their own decisions about optimizations like minification.browserbase/stagehand2 discussions
- Control caching through instantiationWhen implementing optional caching functionality, control cache behavior through conditional instantiation at higher abstraction levels rather than adding conditional logic within cache implementations themselves. This approach maintains cleaner separation of concerns and avoids scattered conditional checks throughout cache methods.browserbase/stagehand2 discussions
- AI provider naming standardsMaintain consistent and proper naming conventions for AI model providers throughout code, documentation, and comments. Use official capitalization (e.g., "OpenAI" not "openai") and provide clear documentation about which AI services are required versus optional.browserbase/stagehand2 discussions
- AI dependency classificationWhen adding AI/ML libraries to a project, carefully consider whether they belong in `dependencies` or `devDependencies`. Libraries used for examples, experimentation, or development tooling should be classified as `devDependencies` to avoid bloating production bundles. Maintain consistency by avoiding install scripts in package.json for dev-only AI...browserbase/stagehand2 discussions
- Verify operation semanticsWhen implementing algorithms that process collections or use conditional logic, always verify the exact semantics of operations across different data structures. spring-projects/spring-framework2 discussions
- Use documentation features properlyUtilize Asciidoc features correctly when writing or updating Spring Framework documentation. Instead of hardcoded links, use defined attributes where available. For example, replace:spring-projects/spring-framework2 discussions
- Structured log message qualityDesign log messages to be clear, concise, and properly structured to maximize their utility for debugging and monitoring. When using structured logging, configure reasonable limits for data complexity to prevent resource exhaustion and ensure logs remain usable.spring-projects/spring-boot2 discussions
- Stable observability componentsAlways use stable, production-ready versions of observability components (libraries, dependencies, and documentation references) in your applications. Monitoring and observability systems are critical infrastructure that should prioritize stability over cutting-edge features.spring-projects/spring-boot2 discussions
- Include database-specific migration dependenciesWhen implementing database migrations with tools like Flyway, ensure you include the appropriate database-specific dependency for your target database. As of Flyway V10.0.0, all databases except in-memory or file-based ones (such as H2 or SQLite) require their own specific dependency package.spring-projects/spring-boot2 discussions
- Environment variables best practicesWhen working with environment variables in configuration files, follow these practices to ensure reliability and testability: 1. Use placeholder syntax `${ENV_VAR}` to reference environment variables in both properties and YAML configuration filesspring-projects/spring-boot2 discussions
- Consistent terminology usageWhen referring to technical concepts in documentation and code comments, use proper full names and consistent terminology: 1. Use full official names instead of abbreviations or shortened forms (e.g., "Kubernetes" instead of "K8s")spring-projects/spring-boot2 discussions
- Clear structured logging documentationDocument structured logging implementations with clarity, explicitly noting precedence rules and interactions with other logging configurations. Always highlight important considerations (such as custom configurations taking precedence) prominently in the main documentation rather than as footnotes or warnings that might be missed.spring-projects/spring-boot2 discussions
- Bean lifecycle managementWhen using containers and external services in Spring applications (especially with Testcontainers), declare them as Spring beans rather than static fields to ensure proper lifecycle management. This approach ensures that the application context will shut down clients first and then containers, preventing connection errors during shutdown.spring-projects/spring-boot2 discussions
- validate before data accessAlways validate for null or None values before accessing data elements, especially when working with collections or optional parameters. Avoid direct indexing or attribute access without first ensuring the data exists and is valid.apache/spark2 discussions
- Test algorithmic performance scalingWhen implementing or modifying algorithms, especially data structures like hash tables, bloom filters, or pattern matching logic, ensure performance characteristics are validated across different input scales. Many algorithms exhibit degraded performance or correctness issues that only become apparent with large datasets.apache/spark2 discussions
- prefer system properties directlyWhen detecting operating system or environment characteristics, prefer direct access to system properties over external library dependencies for basic checks. Use `System.getProperty("os.name")` with `regionMatches()` for case-insensitive OS detection instead of relying on third-party utilities like Apache Commons Lang3's SystemUtils.apache/spark2 discussions
- optimize expensive operationsBefore executing computationally expensive operations, implement conditional checks to determine if the operation is actually necessary. This optimization technique can significantly improve performance by avoiding costly computations when simpler alternatives exist or when the operation can be skipped entirely.apache/spark2 discussions
- ensure test isolationTests must properly clean up resources and avoid side effects that can impact other tests, especially when running in parallel. This prevents non-deterministic failures and ensures reliable test execution.apache/spark2 discussions
- Eliminate unnecessary complexityRemove unnecessary default parameters and consolidate related conditional logic to improve code clarity and maintainability. When parameters are always provided in practice, avoid adding default values that create false optionality. Similarly, combine related conditions into single, more readable expressions.apache/spark2 discussions
- consistent null handlingMaintain consistency in null handling patterns across the codebase. When multiple approaches exist for representing absent or disabled values, choose one approach and apply it uniformly throughout the project.apache/spark2 discussions
- Complete method documentationAll public methods, especially in interfaces and APIs, must have comprehensive JavaDoc documentation that clearly describes their purpose, return values, and behavior. Avoid vague or ambiguous descriptions that leave developers guessing about the method's functionality.apache/spark2 discussions
- Numeric API completenessWhen designing APIs that handle numeric values, ensure comprehensive support for different integer types (Int64, Uint64) based on range requirements and use case needs. Consider practical constraints such as migration costs and legacy system compatibility when deciding between unified or separate configuration options.bytedance/sonic2 discussions
- Meaningful comment practicesComments should explain the reasoning behind code decisions rather than restating what the code obviously does. Focus on the "why" rather than the "what" to provide value that isn't immediately apparent from reading the code itself.bytedance/sonic2 discussions
- Maintain consistent formattingEnsure all code follows the established project formatting standards consistently across the codebase. This includes adhering to specific indentation rules, import statement formatting, and other style conventions defined for the project. When contributing code, always match the existing formatting patterns rather than introducing inconsistencies.bytedance/sonic2 discussions
- Function documentation standardsFunction documentation comments must follow Go conventions by starting with the function name, and all parameters should have clear explanations of their purpose and current functionality.bytedance/sonic2 discussions
- Empty vs nil distinctionAlways distinguish between nil and empty values when handling nullable types, as they carry different semantic meanings and can affect program behavior. Nil represents the absence of a value, while empty represents a zero-length but initialized value.bytedance/sonic2 discussions
- Defensive error handlingImplement defensive checks when managing error state to prevent overwriting existing errors and add safeguards even when theoretically unnecessary. This approach helps avoid subtle bugs and makes code more robust against future modifications.bytedance/sonic2 discussions
- consistent code formattingMaintain consistent indentation and brace alignment throughout the codebase to improve readability and code organization. Use 4-space indentation consistently across all files and align closing braces with their corresponding opening statements.bytedance/sonic2 discussions
- bounds checking firstAlways validate array and buffer bounds before accessing elements to prevent out-of-bounds access and potential security vulnerabilities. This is critical in algorithms that iterate through data structures or perform string operations.bytedance/sonic2 discussions
- validate before accessingAlways validate bounds, nil pointers, and other potentially unsafe conditions before accessing values to prevent runtime panics and undefined behavior. This includes checking array/slice bounds, validating pointer references, and ensuring data structures are in expected states before use.SigNoz/signoz2 discussions
- Use descriptive namesVariable and function names should clearly communicate their actual purpose and behavior, not just their initial intent. Avoid vague or misleading names that don't accurately reflect what the code does.SigNoz/signoz2 discussions
- reuse existing utilitiesBefore creating new utility functions, check if existing ones can be reused or extended. Avoid code duplication by leveraging established utilities and creating single sources of truth for repeated patterns.SigNoz/signoz2 discussions
- provide defaults when destructuringWhen destructuring properties from objects that might contain undefined values, use the nullish coalescing operator (??) to provide explicit default values at the point of assignment. This prevents undefined values from propagating through your code and eliminates the need for repeated null checks later.SigNoz/signoz2 discussions
- Prefer realistic testingWrite tests that closely mirror real user interactions and application behavior rather than relying on artificial test-specific constructs. This approach creates more robust and maintainable tests.SigNoz/signoz2 discussions
- orchestrate observability servicesWhen setting up observability infrastructure in build systems, use proper dependency management and descriptive naming. Define service dependencies explicitly rather than embedding commands, and use specific names that clearly identify the observability tools being orchestrated.SigNoz/signoz2 discussions
- Optimize React architecturePrefer direct hook usage over prop drilling and carefully consider context provider placement to maintain clean component architecture. When custom hooks are available, use them directly in components rather than passing their values through props. For context providers, aim for global placement when possible, but be mindful of routing and component...SigNoz/signoz2 discussions
- Observability correctness and maintainabilityEnsure observability implementations prioritize both mathematical correctness and code maintainability. Observability systems must produce accurate metrics and telemetry data while remaining easy to understand and modify.SigNoz/signoz2 discussions
- meaningful ABC usageOnly inherit from ABC when you have abstract methods that subclasses must implement. Avoid using ABC inheritance for classes that don't define any abstract methods, as this adds unnecessary complexity without providing the intended benefits of the abstract base class pattern.SigNoz/signoz2 discussions
- justify caching strategiesWhen implementing caching solutions, clearly document and justify your caching strategy decisions based on access patterns, performance requirements, and complexity trade-offs. Consider whether the benefits of complex caching approaches outweigh simpler alternatives.SigNoz/signoz2 discussions
- Explicit configuration managementConfiguration changes should be intentional, well-documented, and implemented using clean, understandable patterns. Avoid hacky workarounds like counter-based state management when simpler alternatives exist.SigNoz/signoz2 discussions
- Ensure log message clarityLog messages should be clear, unambiguous, and avoid creating confusion for developers and operators. This means explicitly logging when no-op operations occur (rather than staying silent) and avoiding duplicate log entries with identical information that can mislead readers.SigNoz/signoz2 discussions
- Configuration migration fallbacksWhen configuration structures evolve, implement fallback mechanisms to handle both old and new formats gracefully. This ensures backward compatibility during transitions and prevents breaking changes.SigNoz/signoz2 discussions
- avoid inline object creationInline objects and functions created within render methods are recreated on every render, causing unnecessary re-renders of child components when passed as props. This impacts performance by triggering component updates even when the actual functionality hasn't changed.SigNoz/signoz2 discussions
- Add tests for new codeAll new code additions, regardless of complexity, should include corresponding unit tests to ensure functionality works as expected and to prevent regressions. This applies to new modules, utility functions, and any other code components.SigNoz/signoz2 discussions
- Precision Resize and Singleton StyleWhen performance or visual stability matters (e.g., zoom/antialiasing), prefer precision-first measurement and avoid expensive DOM churn. Apply these rules:paper-design/shaders2 discussions
- CUDA compatibility verificationWhen modifying CUDA versions or GPU architecture configurations in AI/ML projects, verify compatibility across three critical dimensions: CUDA version support, GPU architecture coverage, and dependent library requirements. Check official compatibility matrices, test with target hardware, and validate that AI libraries maintain their functionality.sgl-project/sglang2 discussions
- consolidate duplicated logicWhen you identify duplicated code patterns across different branches or functions, consolidate the shared logic into a unified implementation to improve maintainability and reduce code bloat. This applies whether the duplication occurs within conditional branches, across similar functions, or in separate files.sgl-project/sglang2 discussions
- Avoid broad exception catchingAvoid using overly broad exception handling like `except Exception` as it can mask specific errors and make debugging difficult. Instead, catch specific exception types when possible, or convert generic exceptions to more informative, specific error types with meaningful messages.sgl-project/sglang2 discussions
- AI model documentation consistencyEnsure consistent parameter names and configuration instructions across AI model documentation. Inconsistent documentation about model parsers, parameters, and configuration options leads to developer confusion and implementation errors.sgl-project/sglang2 discussions
- AI dependency justificationWhen modifying AI library dependencies, always provide clear justification for version choices, especially when using non-standard sources like git commits or release candidates. This is critical for AI projects where library compatibility and stability directly impact model performance and inference reliability.sgl-project/sglang2 discussions
- validate subprocess errors comprehensivelyWhen executing external commands via subprocess, don't rely solely on return codes for error detection. Some tools may return 0 even when they fail. Instead, check multiple error indicators including return codes, stderr output, and stdout content to ensure robust error handling.servo/servo2 discussions
- Network request configurationWhen creating network requests, ensure all security-sensitive parameters are properly configured including origin, referrer, CORS mode, and destination. Incomplete request configuration can lead to test failures, security vulnerabilities, and incorrect cross-origin behavior.servo/servo2 discussions
- implement security validationEnsure all security-related functionality includes complete validation checks and proper testing. This applies to both cryptographic operations and security policy configurations.servo/servo2 discussions
- enhance testing interfacesDesign testing tool interfaces to be both flexible and discoverable. Support multiple keyword variations for test-related functionality and provide pass-through parameter options to enable advanced debugging scenarios.servo/servo2 discussions
- configuration parameter handlingWhen working with configuration parameters and values, follow these best practices to ensure maintainable and correct configuration handling: 1. **Use collections for multiple related values**: When checking against multiple related configuration values, use the `in` operator with a list or set rather than chaining multiple OR conditions. This makes the...servo/servo2 discussions
- Algorithm edge case validationEnsure algorithmic implementations properly handle edge cases and boundary conditions before considering them complete. Many algorithm failures stem from insufficient consideration of special inputs, parameter combinations, or state transitions that occur at the boundaries of normal operation.servo/servo2 discussions
- maintain proper formattingEnsure code and configuration files follow proper formatting standards that maintain both syntactic validity and visual readability. This includes correct indentation for nested structures and appropriate line length management to prevent horizontal scrolling.serverless/serverless2 discussions
- maintain naming consistencyEnsure consistent naming patterns across related components and configurations. When naming properties, methods, or identifiers that relate to the same concept, use the same form (singular/plural, casing, terminology) throughout the codebase.serverless/serverless2 discussions
- maintain configuration standardsEnsure configuration files maintain both consistency and currency across all services. Configuration values should follow established patterns within the codebase and use up-to-date versions for runtimes and dependencies.serverless/serverless2 discussions
- explicit observability configurationEnsure observability features are configured explicitly with clear documentation about their scope and impact. Avoid relying on implicit defaults or ambiguous configuration that could mislead users about what monitoring capabilities are being enabled or disabled.serverless/serverless2 discussions
- Complete CI/CD documentationEnsure all CI/CD documentation is comprehensive and technically accurate, covering complete workflows and tooling capabilities. Incomplete or incorrect documentation leads to deployment failures, misconfigurations, and developer confusion.serverless/serverless2 discussions
- prefer marketplace actionsBefore implementing custom tool installation steps in GitHub Actions workflows, check if there's an existing setup action available on the GitHub Actions marketplace. Marketplace actions are typically more reliable, better maintained, and reduce workflow complexity compared to custom installation scripts.oraios/serena2 discussions
- Inline configuration dictionariesAvoid storing simple configuration data in separate JSON files. Instead, define configuration as Python dictionaries directly within the relevant modules. This approach reduces file overhead, improves maintainability, and keeps related code together.oraios/serena2 discussions
- Use acks_late for reliabilityConfigure Celery tasks with `acks_late=True` when task reliability is critical and you prefer to risk duplicate processing rather than task loss. This setting ensures tasks aren't acknowledged until successfully completed, allowing them to be reprocessed if a worker crashes or a deployment occurs during task execution.getsentry/sentry2 discussions
- Reduce code nestingExcessive indentation makes code harder to read and understand. Two common techniques can help flatten your code structure: 1. **Use early returns** for guard conditions instead of nesting the main logic in else blocks:getsentry/sentry2 discussions
- Keep testing dependencies currentRegularly update testing framework dependencies (PHPUnit, PHPStan, etc.) to maintain compatibility with your project's PHP version requirements and ensure access to new testing features. When updating dependencies, consider future compatibility needs by using appropriate version constraints. getsentry/sentry-php2 discussions
- Ensure test isolationTests should be independent and isolated from each other to prevent state leakage and ensure reliable results. When testing components that maintain state (like singletons) or require specific environments (like PHP version-specific features), choose appropriate isolation strategies:getsentry/sentry-php2 discussions
- Dynamic error configurationDesign error handling systems that respect runtime changes to error settings rather than fixing configurations at initialization time. When handling errors, dynamically evaluate error reporting flags to allow for temporary error silencing and context-specific error handling behavior. Preserve user-specified error levels when processing exceptions to ensure...getsentry/sentry-php2 discussions
- Document configuration comprehensivelyWhen adding or modifying configuration options, ensure they are documented with complete context. Group related changes together (like deprecation and default value changes), include reference numbers, and explain the purpose and effect of configuration options. This helps users understand how to properly configure the system without confusion.getsentry/sentry-php2 discussions
- Optimize lookup operationsChoose appropriate data structures to minimize computational complexity when performing lookups. Prefer direct lookups (maps/dictionaries) over repeated array traversals, and use set-based inclusion checks for membership testing rather than multiple conditionals.getsentry/sentry2 discussions
- Migration model importsWhen writing Django migrations, avoid importing and referencing external models directly. Django migrations use auto-generated model classes based on the migration state at that point, not the current model definitions. These migration-specific models ensure compatibility with the database schema as it existed at that migration's point in time.getsentry/sentry2 discussions
- Meaningful test designWrite tests that focus on unique edge cases and avoid redundancy. When designing test suites: 1. Consolidate similar test cases that don't provide additional coveragegetsentry/sentry2 discussions
- Validate CI pipeline inputsAlways validate and sanitize dynamic inputs in CI/CD pipelines before using them in URLs, file operations, or other system interactions. This includes environment variables, repository names, file paths, and user-provided parameters that could contain special characters, spaces, or unexpected formats.semgrep/semgrep2 discussions
- Use proper URI parsingWhen working with URLs and URIs in networking code, use proper URI parsing libraries and types instead of string manipulation or regex validation. This approach is more robust, handles edge cases correctly, and provides better type safety.semgrep/semgrep2 discussions
- use consistent JavaScript syntaxMaintain consistent use of modern JavaScript syntax throughout networking code to improve reliability and maintainability. Use `const` or `let` instead of `var` for variable declarations, and prefer strict equality (`===`) over loose equality (`==`) for comparisons.semgrep/semgrep2 discussions
- use appropriate test markersTest markers and annotations should match the test type and context they're applied to. Different test categories (unit tests, e2e tests, integration tests) require different markers to ensure proper test organization and execution.semgrep/semgrep2 discussions
- justify error handling designWhen implementing error handling mechanisms, ensure that design decisions are well-justified and properly reasoned. This applies to both architectural choices (like global state for error correlation) and technical analysis (like exception flow paths).semgrep/semgrep2 discussions
- CI blocking with overridesWhen implementing CI checks that can block pull request merges, always provide clear override mechanisms for exceptional cases. Hard-failing CI checks should be strong signals to developers, but teams need escape hatches when legitimate exceptions arise.strands-agents/sdk-python2 discussions
- Balance configuration practicalityWhen making configuration changes, balance technical best practices with developer workflow requirements and real-world usage scenarios. Configuration decisions should not only be technically sound but also support practical development needs.strands-agents/sdk-python2 discussions
- AI dependency managementWhen integrating AI libraries and SDKs, carefully manage dependencies by pinning versions with upper bounds to prevent breaking changes and minimize scope by implementing simple types locally when possible.strands-agents/sdk-python2 discussions
- Synchronize configuration filesEnsure all related configuration files are updated consistently when making changes to dependencies, versions, or other configuration settings. When updating a dependency version in one file (e.g., package.json), ensure that all related files (e.g., lockfiles, version specifications) are also updated to maintain consistency. This prevents subtle integration...rust-lang/rust2 discussions
- Optimize dependency configurationsWhen configuring project dependencies, be mindful of feature flags that may introduce unnecessary build dependencies or slow down compilation. For libraries like serde, separate the core functionality from derive macros to improve build parallelization:rust-lang/rust2 discussions
- Normalize variable test outputWhen writing tests that capture output (like UI tests, stderr, or stdout), ensure you normalize any variable content that might change between runs or versions to prevent fragile tests. This includes version numbers, debug information, instruction identifiers, and other implementation details that don't affect the functionality being tested.rust-lang/rust2 discussions
- Conditional CI resource managementConfigure CI workflows to intelligently manage system resources through conditional execution rather than duplicating steps. Use matrix variables or job conditions to determine when resource-intensive operations should run.rust-lang/rust2 discussions
- Use utility macrosUse predefined utility macros for common operations instead of repeating manual calculations throughout your code. This improves readability, consistency, and reduces the likelihood of errors in calculations.dotnet/runtime2 discussions
- Platform-aware algorithm optimizationWhen implementing performance-critical algorithms, design your code to detect and utilize platform-specific hardware features while maintaining compatibility across different architectures. Create abstraction layers that allow the same algorithm to run on various platforms but take advantage of specialized instruction sets (like AVX extensions) when...dotnet/runtime2 discussions
- Optimize aligned SIMD operationsAlways use proper memory alignment for SIMD (Single Instruction, Multiple Data) operations to maximize performance. When implementing vector operations:dotnet/runtime2 discussions
- Names reflect actual purposeName variables, properties, and functions to accurately reflect their purpose and actual usage in code, not just their technical classification. This ensures other developers can understand the intent without having to analyze implementation details.dotnet/runtime2 discussions
- Memory barrier pairingWhen implementing low-level synchronization mechanisms in multi-threaded code, ensure that memory barriers are correctly paired between reader and writer operations. For each read barrier, implement a corresponding write barrier to maintain memory consistency and prevent race conditions.dotnet/runtime2 discussions
- Maintain configuration compatibilityWhen modifying configuration systems, prioritize backward compatibility unless there's an explicit breaking change planned. If a breaking change is necessary, implement compatibility handlers for older configurations and clearly communicate the transition plan.dotnet/runtime2 discussions
- Honor API contractsWhen implementing or modifying APIs, carefully preserve the historical behavior and semantic contracts of existing interfaces, even when those behaviors seem counterintuitive. This includes maintaining consistent exception throwing patterns and honoring the distinct purposes of method overloads.dotnet/runtime2 discussions
- Feature flag implementationWhen implementing feature flags, ensure consistency between runtime and compiled scenarios. Feature switches marked with `FeatureSwitchDefinition` must properly return the AppContext switch value when defined:dotnet/runtime2 discussions
- Explicit API versioningWhen extending interfaces with new methods or functionality, always implement proper versioning to ensure compatibility across different clients. Breaking changes should increment major versions, while additive changes should increment minor versions. More importantly, implement version checks in your code to gracefully handle compatibility.dotnet/runtime2 discussions
- Enable configurable instrumentationAlways provide configurable options for performance instrumentation and hardware acceleration in your codebase. These options should be clearly documented and defaulted appropriately for common scenarios.dotnet/runtime2 discussions
- Document non-obvious logicAdd clear comments explaining the purpose and reasoning behind complex or non-obvious code logic. Comments should explain 'why' certain implementation choices were made or how specific variables and conditions function, rather than just restating what the code does. This is especially important for security-related checks, timing mechanisms, interruption...dotnet/runtime2 discussions
- Document function contractsAlways document function contracts completely, even when surrounding code lacks documentation. Include header comments that describe the function's purpose and behavior, and explicitly specify preconditions using appropriate annotations (like `PRECONDITION`) to clarify execution requirements.dotnet/runtime2 discussions
- Centralize platform configurationsPlatform-specific code and API usage should be centralized in designated configuration files rather than scattered throughout the codebase. When adding code that might not be available on all supported platforms:dotnet/runtime2 discussions
- Test edge casesWhen writing tests, prioritize coverage of edge cases and non-standard code patterns to ensure robust functionality. Particularly for linting rules or code transformations, identify scenarios that might behave unexpectedly or require special handling.astral-sh/ruff2 discussions
- Single yield algorithmContext managers must follow a crucial algorithmic constraint: each execution path must yield exactly once. Multiple yields in the same path lead to unpredictable behavior, while no yields prevent proper resource management.astral-sh/ruff2 discussions
- Logical content organizationOrganize code and documentation logically based on functionality and dependencies. Place files in directories that reflect their purpose rather than superficial characteristics. Structure documentation so prerequisite concepts appear before concepts that depend on them.astral-sh/ruff2 discussions
- Clear and relevant commentsEnsure all comments in the codebase provide value and clarity rather than creating confusion. Remove comments that are: 1. Not applicable to the current framework (e.g., linter directives for tools you're not using)astral-sh/ruff2 discussions
- Prioritize code legibilityWrite clear, explicit code that prioritizes readability over brevity. Remove unnecessary operations and use straightforward syntax patterns. This is especially important in library code where clarity benefits all consumers.TanStack/router2 discussions
- Optimize React patternsPrefer derived values over state and use appropriate React hooks for better performance and cleaner code. When a value can be computed from existing state, props, or context, derive it instead of storing it in separate state. This reduces unnecessary re-renders and simplifies state management.TanStack/router2 discussions
- optimize file-based routingImplement lazy loading patterns and strategic code-splitting in file-based routing systems to improve performance and reduce unnecessary processing. Root routes should never be code-split since they're always needed, while other routes can benefit from lazy instantiation to avoid parsing route trees when not required.TanStack/router2 discussions
- memoize for render optimizationUse React memoization techniques strategically to prevent unnecessary re-renders and recomputations when values change infrequently. Apply React.memo to components that receive stable props, and useMemo for expensive computations that depend on rarely-changing values.TanStack/router2 discussions
- Intentional async usageBe deliberate about when to use the `async` keyword and `await` expressions. Making a function `async` changes its behavior - it will always return a Promise, even for early returns. This can break conditional logic that checks for synchronous vs asynchronous behavior.TanStack/router2 discussions
- defensive null checkingAlways perform explicit null and undefined checks before accessing object properties or methods to prevent runtime errors. This defensive programming approach ensures code robustness when dealing with potentially missing data.TanStack/router2 discussions
- comprehensive test validationTests should validate all relevant aspects of the system to ensure comprehensive coverage. This includes incorporating type checking into test execution, validating file operations and generation processes, and ensuring end-to-end functionality works correctly. Different types of tests serve different validation purposes and should be used strategically.TanStack/router2 discussions
- Clear contextual error messagesError messages should be specific, contextually relevant, and provide actionable guidance to developers. Avoid generic or ambiguous error text that could apply to multiple scenarios.TanStack/router2 discussions
- break complex expressionsBreak down complex boolean expressions and conditions into well-named intermediate variables to improve code readability and maintainability. Instead of writing dense one-liners, use descriptive variable names that clearly communicate the intent of each condition.TanStack/router2 discussions
- avoid unnecessary workflow restrictionsRemove unnecessary approval gates, custom tokens, and restrictive conditions in CI/CD workflows when existing security measures are sufficient. Over-restrictive workflows create friction without meaningful security benefits.TanStack/router2 discussions
- Avoid repeated object creationPrevent performance degradation by avoiding the creation of functions, objects, regular expressions, and other expensive operations inside loops or frequently executed code paths. Instead, hoist these creations outside the loop or to a higher scope where they can be reused.TanStack/router2 discussions
- Verify documentation referencesEnsure all references in documentation (file paths, commands, code examples) actually exist in the codebase and accurately reflect the current system state. Additionally, verify that translations maintain correct meaning and grammar in all supported languages.RooCodeInc/Roo-Code2 discussions
- Sanitize user inputsAlways validate and sanitize user-provided inputs before using them in security-sensitive operations to prevent XSS attacks and unsafe redirections. RooCodeInc/Roo-Code2 discussions
- Avoid hardcoded configurationsAlways extract configuration values from appropriate sources (config files, environment variables, etc.) rather than hardcoding them in your code. Include validation to ensure the configuration is valid before use, and provide sensible defaults with the ability to override when needed.RooCodeInc/Roo-Code2 discussions
- Separate multiple importsWhen importing multiple items from the same module, use separate import statements instead of combining them on a single line. This improves code readability and makes it easier to track individual imports during code reviews and refactoring.smallcloudai/refact2 discussions
- prefer simpler implementationsWhen writing code, favor simpler, more straightforward implementations over complex ones. Look for opportunities to consolidate logic paths, reduce unnecessary branching, and reuse existing resources instead of recreating them.smallcloudai/refact2 discussions
- optimize timing intervalsChoose appropriate timing intervals for asynchronous operations to improve performance and responsiveness. For frequent polling of cheap operations, use shorter intervals (200ms instead of 1s) to reduce latency. For potentially blocking file system operations, use atomic patterns like rename-then-delete to avoid blocking the async runtime.smallcloudai/refact2 discussions
- Follow API design conventionsEnsure API endpoints adhere to established design conventions including proper HTTP methods, authorization requirements, and clean route organization. Use GET for data retrieval operations and include appropriate authorization headers for protected endpoints. Avoid creating unnecessary routers when prefixes can be incorporated directly into route...smallcloudai/refact2 discussions
- Ensure semantic naming clarityNames should clearly communicate their actual behavior and preserve sufficient context for meaningful identification. For functions with conditional behavior, use descriptive suffixes like `_if_needed` or `_maybe` to indicate optionality. For paths and identifiers, maintain enough context to ensure usability - avoid over-shortening that removes essential...smallcloudai/refact2 discussions
- Complete model configurationsWhen adding new models to configuration files, ensure all required configuration fields are populated, not just the model name in the running_models list. Models need complete configuration in both JSON (known_models.json) and YAML (provider files) with all necessary fields specified.smallcloudai/refact2 discussions
- avoid problematic identifier namesChoose identifier names that avoid system compatibility issues and follow proper naming conventions. Avoid reserved words, system-problematic names, and invalid characters that can cause issues across different platforms or violate language standards.smallcloudai/refact2 discussions
- Validate security-critical dataWhen code consumes security-critical data—either to perform privileged state changes at runtime or to download/execute external artifacts—it must validate integrity/invariants before proceeding.redis/redis2 discussions
- Semantic Naming AccuracyEnsure names and naming-related metadata are semantically accurate and unambiguous. - Don’t reuse a helper/identifier whose name is tied to a specific command if it creates confusion. Prefer a dedicated, clearly named function per command.redis/redis2 discussions
- Secure Workflow PermissionsApply two security practices to GitHub Actions workflows: 1) Enforce least privilege - Set `permissions: {}` at the workflow level (or default deny) and only add the minimal scopes required for each job/step.redis/redis2 discussions
- Intentional Error HandlingHandle errors based on intent: make operations idempotent for known conflicts, and explicitly classify/propagate errors for known transient conditions.redis/redis2 discussions
- Explicit Build FlagsEnsure build configuration explicitly sets (1) include paths and (2) required language/toolchain modes to prevent environment-dependent header resolution and compiler-mode breakages.redis/redis2 discussions
- Evidence-Based Failover TargetsWhen proposing performance/SLA goals (e.g., failover completion time), require an evidence-based rationale and a repeatable way to validate them—especially for worst-case behavior.redis/redis2 discussions
- Write readable conditionalsStructure conditionals for maximum clarity and comprehension. Avoid unnecessary negation in boolean expressions, use else clauses appropriately, and organize compound conditions to reduce cognitive load.facebook/react2 discussions
- Standardize URL handlingWhen working with URLs in networking code, always use the standard `URL` constructor to properly resolve relative URLs against a base URL instead of manual string concatenation or ad-hoc replacements.facebook/react2 discussions
- Structure documentation interfacesOrganize interfaces and component props documentation to improve API clarity and maintainability. Extract reusable interfaces into separate declarations to generate dedicated documentation pages, and ensure prop documentation accurately represents the code structure, especially for rest/spread operators.remix-run/react-router2 discussions
- Remove obsolete configuration optionsProactively remove configuration options that are no longer functional or relevant to prevent developer confusion and potential bugs. When configuration options become obsolete due to architectural changes or package migrations, removing them from type definitions and interfaces is preferable to keeping them as non-functional placeholders.remix-run/react-router2 discussions
- Pin problematic dependenciesWhen external dependencies or tools in CI/CD pipelines have known regressions or bugs, pin them to stable versions and document the reasoning with issue links. Include TODO comments to track when temporary measures can be reverted.remix-run/react-router2 discussions
- organize test scripts properlyKeep base test scripts generic and create specialized variants for specific workflows. Base scripts like "test" should remain simple and flexible, allowing developers to pass additional arguments via CLI. For specialized workflows, create separate scripts with descriptive names.remix-run/react-router2 discussions
- Implement recursive safeguardsWhen implementing recursive algorithms, always include cycle detection and early termination conditions to prevent infinite recursion and improve performance. This is especially critical in graph traversal, AST processing, and dependency analysis where circular references can occur.remix-run/react-router2 discussions
- Handle SSR hydration mismatchesWhen implementing server-side rendering, proactively handle scenarios where server and client rendering may produce different outputs to prevent hydration errors. This commonly occurs with dynamic URLs, route matching, and encoded characters.remix-run/react-router2 discussions
- distinguish falsy vs nullishWhen handling potentially null or undefined values, carefully choose between the logical OR (`||`) and nullish coalescing (`??`) operators based on whether you want to preserve other falsy values.remix-run/react-router2 discussions
- Configure React build environmentsEnsure proper environment and module configuration for React applications to load the correct versions and entrypoints across different build contexts. This includes setting NODE_ENV appropriately and configuring import paths for optimal React loading.remix-run/react-router2 discussions
- configure build tools properlyEnsure build configurations use proper package.json exports fields and TypeScript settings to avoid hard-coded paths and module format inconsistencies. Build tools should be configured to handle module resolution and output formats correctly to prevent runtime issues.remix-run/react-router2 discussions
- Complete accurate documentationDocumentation should provide complete, accurate guidance that doesn't mislead developers about correct usage patterns. Avoid documentation structures that suggest incorrect import paths or API usage, and ensure that configuration examples are accompanied by practical usage demonstrations.remix-run/react-router2 discussions
- avoid timing-dependent testsTests should not rely on fixed delays, arbitrary timeouts, or assume deterministic ordering of asynchronous operations. Instead, use proper waiting mechanisms and sort results when order doesn't matter.remix-run/react-router2 discussions
- Proper Usage of React HooksWhen using the React library in TypeScript, ensure that you are correctly implementing the recommended React hooks based on the version of ESLint being used in your project.facebook/react2 discussions
- Proper Scoping and Usage of React VariablesWhen implementing React components, it is important to ensure that variables are properly scoped and used throughout the component lifecycle. This reviewer provides guidance on best practices for managing variable declarations and usage in React code.facebook/react2 discussions
- Validate configuration formatsEnsure configuration values use the correct data format expected by target systems and avoid duplication by sourcing from authoritative locations when possible. Mismatched formats can cause runtime failures, while duplicated configurations create maintenance overhead and inconsistency risks.facebook/react-native2 discussions
- Use proper documentation formatUse the appropriate documentation format for the target programming language. In Kotlin files, use KDoc formatting instead of Javadoc formatting for consistency and proper tooling support.facebook/react-native2 discussions
- Use Kotlin testing idiomsWhen writing tests in Kotlin, prefer Kotlin-specific testing libraries and language features over their Java equivalents. Use Mockito Kotlin instead of standard Mockito for more idiomatic syntax, and leverage Kotlin language features like `apply` blocks to make test setup code more concise and readable.facebook/react-native2 discussions
- Use appropriate log levelsChoose logging levels that match the intended audience and purpose of the message. Use debug or silent logging for internal operations, optional behaviors, and retry logic that shouldn't be visible to end users. Reserve console output and higher log levels (info, warning, error) for user-relevant information.facebook/react-native2 discussions
- Replace magic numbersReplace magic numbers with named constants to improve code readability and maintainability. Magic numbers make code harder to understand and maintain, as their purpose and significance are not immediately clear to other developers.facebook/react-native2 discussions
- prefer explicit codeWrite code that explicitly states its intent rather than relying on implicit behavior or complex constructs. This improves readability and maintainability by making the code's purpose immediately clear to other developers.facebook/react-native2 discussions
- platform-aware configuration messagesConfiguration-related error messages, troubleshooting guidance, and feature flags should be accurate and account for platform-specific differences. When providing configuration instructions or enabling features conditionally, ensure the guidance reflects the actual capabilities and limitations of each target platform.facebook/react-native2 discussions
- platform API consistencyWhen implementing cross-platform functionality, prioritize consistency and avoid replicating platform-specific bugs or inconsistencies. Consider the broader architectural impact of API choices, especially when they require significant migrations or affect multiple components.facebook/react-native2 discussions
- Optimize CI platform buildsWhen configuring CI/CD build pipelines, limit builds to only the platforms your project actively supports and avoid building for out-of-tree (OOT) platforms that maintain separate forks. This reduces unnecessary CI overhead and build times. Additionally, design your build configuration to support parallelization by allowing platforms to be passed as...facebook/react-native2 discussions
- Optimize algorithmic choicesWhen implementing algorithms, prioritize both correctness and efficiency by selecting the most appropriate data structures and computational approaches for each specific task. Ensure mathematical calculations follow established specifications and standards, and choose data structures that match the operation's requirements.facebook/react-native2 discussions
- manage component state dependenciesEnsure React components have all necessary state information before rendering and that lifecycle events don't cause unintended state interactions. Components should validate they have required data (like sizing information) before updating, and state changes should be carefully managed to prevent side effects.facebook/react-native2 discussions
- maintain cross-platform API consistencyWhen designing APIs that work across multiple platforms, ensure consistent return types and behavior to avoid breaking changes and maintain a unified developer experience. Use Platform.select() to handle platform-specific implementations rather than hardcoded conditional logic.facebook/react-native2 discussions
- maintain API backwards compatibilityWhen modifying existing public APIs, prioritize backwards compatibility to avoid breaking external consumers. Before making changes that alter method signatures, property access patterns, or introduce new abstract methods, first investigate whether existing functionality can be preserved or extended.facebook/react-native2 discussions
- Follow existing naming conventionsWhen adding new variables, methods, or constants, always follow the naming conventions already established in the codebase. Before introducing new identifiers, examine existing code in the same file and related files to understand the established patterns, including prefixes, suffixes, and naming styles.facebook/react-native2 discussions
- Follow established naming conventionsEnsure all identifiers (variables, methods, classes) adhere to the project's established naming conventions and accurately reflect their purpose. Consistency in naming patterns improves code readability and maintainability across the codebase.facebook/react-native2 discussions
- Environment variable validationEnvironment variables should be properly validated with correct type checking and without redundant conditions. Common issues include comparing strings to integers and using unnecessary double-checks that can lead to unexpected behavior.facebook/react-native2 discussions
- configuration consistency managementMaintain consistent configuration references across all code branches and document temporary configuration code for future cleanup. Configuration inconsistencies can lead to compilation errors and maintenance debt.facebook/react-native2 discussions
- Component initialization stateEnsure components properly handle initialization state during their lifecycle, particularly when being recycled or updated. Components should explicitly track whether they have been initialized and force initial value setting when necessary, rather than relying on property comparison alone.facebook/react-native2 discussions
- avoid unnecessary component complexityWhen designing React components and their APIs, resist the temptation to add features, props, or methods that provide limited or no real value to developers. Components should expose only functionality that serves genuine use cases and avoids introducing maintenance burden or developer confusion.facebook/react-native2 discussions
- avoid unnecessary allocationsWhen implementing algorithms and data structure operations, avoid unnecessary memory allocations, object creation, and data copying that can impact performance. Look for opportunities to leverage existing objects, references, and lazy evaluation patterns.facebook/react-native2 discussions
- Multi-stack config settingsWhen creating configuration files for development environments that use multiple technology stacks, ensure settings are properly scoped to accommodate different file types and tools within the same project.facebook/react2 discussions
- Explicit CSP nonce managementWhen implementing Content Security Policy (CSP) protections, always explicitly pass nonce values to components rather than auto-applying them. This gives developers more control over security aspects and prevents potential security bypasses when integrating components from different sources.facebook/react2 discussions
- Dry configuration patternsApply DRY (Don't Repeat Yourself) principles to all configuration files to improve maintainability. Extract shared configuration options into reusable constants, especially for values used across multiple environments or settings.facebook/react2 discussions
- Document code intentAdd clear comments that explain the intent and behavior of code that might not be immediately obvious to other developers. Meaningful comments should provide context about why the code exists and how it works.facebook/react2 discussions
- Defensive Handling of Nullable React ComponentsWhen working with React components that may return null or undefined values, implement defensive coding patterns to prevent runtime errors and improve code reliability.facebook/react2 discussions
- Test helpers for maintainabilityCreate reusable helper methods for common testing operations to improve test maintainability and consistency. Design these helpers to be appropriate for their specific test context (integration vs system tests) and resilient to implementation changes.rails/rails2 discussions
- Use enum constantsWhen a value represents a named domain concept (e.g., Theme), use the corresponding enum type/constant (e.g., `ThemeEnum`) instead of duplicating raw string literals (`'light'`, `'dark'`). This keeps identifier naming consistent across schema definitions and UI/component logic.infiniflow/ragflow2 discussions
- Semantic identifier namingUse semantic, unambiguous names for every externally visible identifier (API parameters/endpoints, config/env vars, and build/version tags). Names must reflect meaning and supported behavior; if an operation is not supported, document that constraint next to the relevant field/behavior.infiniflow/ragflow2 discussions
- PascalCase constantsUse a consistent PascalCase naming convention for constants (especially exported ones). Avoid mixed styles like snake_case, and keep acronym casing consistent (e.g., API).infiniflow/ragflow2 discussions
- Maintain dependency lockfilesWhen changing dependency declarations in configuration files like `pyproject.toml`, treat group placement and lockfile updates as part of the change. infiniflow/ragflow2 discussions
- Documentation Wiring AccuracyEnsure technical documentation is both semantically correct and operationally precise: (1) use the exact product terms for what a setting applies to (scope/terminology), and (2) when describing component internals/graphs, specify the exact wiring rule for references (use the internal managing node, not an external component), aligned with the documented...infiniflow/ragflow2 discussions
- Centralize API InterfacesEnforce consistent API client construction: (1) centralize all REST endpoint paths and interface definitions in a shared module (e.g., `api.ts`) to prevent scattered string literals, and (2) when reading/writing request inputs like query params, use the correct standard APIs and keep TypeScript types aligned.infiniflow/ragflow2 discussions
- API Contract VerificationWhen adding/updating model-to-endpoint configuration, verify it against the provider’s official API docs and enforce the expected request/response contract.infiniflow/ragflow2 discussions
- AI library version compatibilityWhen documenting AI/ML model deployment and inference procedures, always test and specify compatible library versions to prevent runtime failures. Version incompatibilities in AI libraries can cause critical errors like inference failures, probability tensor issues, or model output corruption.QwenLM/Qwen32 discussions
- Validate Configuration ContractsConfiguration docs/examples and runtime behavior must stay aligned, and configuration must be explicit and validated. Apply two rules: 1) **No silent no-ops:** If a config field is accepted by schema/docs, it must actually affect runtime behavior—or be removed from examples and clearly documented as unused/ignored. Add validation/tests that cover example...QwenLM/qwen-code2 discussions
- Test regex alternationsWhen unit tests depend on filename/path classification via regex (e.g., routing maintainers, detecting test files), add explicit test cases that exercise *every alternation token and mapping entry* in the regex/table. Uncovered alternations can fail silently if someone introduces a typo or refactors part of the pattern.QwenLM/qwen-code2 discussions
- I18n Translation PolicyTreat every newly added user-facing string key as a documentation/UX contract for all supported locales. When you add `t()` keys: 1) Classify the keys against the project’s translation policy (e.g., `MUST_TRANSLATE_KEYS`).QwenLM/qwen-code2 discussions
- Graceful Failure HandlingWhen an action depends on daemon capabilities or other availability checks, never fail silently or hard-fail the whole UI. Instead: (1) gate capability-dependent parameters/requests so missing capabilities degrade gracefully, and (2) treat dependency outcomes as real failures—don’t return “handled/success” if the operation wasn’t actually performed; surface...QwenLM/qwen-code2 discussions
- Ensure CI-tested WorkflowsAll CI/CD-related script/workflow tests must be executed in CI, and they must assert the behaviors that matter in production—especially fail-closed security gates and correct step ordering.QwenLM/qwen-code2 discussions
- Deterministic Set LogicWhen implementing set-based selection/reconciliation algorithms, ensure **(1) deterministic outcomes** and **(2) invariant-preserving persisted state** across runs.QwenLM/qwen-code2 discussions
- Vue example correctnessWhen writing Vue (including Nuxt) code snippets or API docs, ensure the example is correct for the shapes the API truly supports and for the Nuxt/Vue environment.tanstack/query2 discussions
- Type Parameter NamingEnforce a single, strict naming convention for TypeScript generic type parameters using ESLint, and migrate the rule to `error` after a short “warn” rollout.tanstack/query2 discussions
- Test TanStack Query ProperlyWhen writing Angular unit/SSR tests for TanStack Query, align with Angular’s task tracking and keep caches isolated: - Prefer Angular injection helpers: test components/services should call `injectQuery`/`injectMutation` (not ad-hoc query execution) so Angular can track in-progress work via `PendingTasks` (Angular 19+).tanstack/query2 discussions
- Stable Index MappingPrefer stable data-structure lookups over recomputing indices in update paths—especially when the underlying collection can reorder. **Guideline** 1. **Avoid linear searches in hot paths**: if you need an element’s position during frequent updates, don’t use patterns like `array.indexOf(x)` repeatedly. Use a map (e.g., `WeakMap`/`Map`) that gives the...tanstack/query2 discussions
- Silence Unused Query UpdatesTo optimize performance, prevent components from re-rendering when they don’t need to react to query updates. **Rule:** If you use `useQuery`/`useFocusEffect` for *prefetching* or *side effects* and intentionally *ignore the result*, disable change notifications so the hook doesn’t subscribe to updates that would trigger re-renders.tanstack/query2 discussions
- Resolve predicates, seed reducersWhen building or extending algorithmic pipelines (streaming, reduction, conditional processing), ensure two correctness points: 1) Resolve dynamic conditions before actingtanstack/query2 discussions
- Redact Transported ErrorsWhen you serialize/dehydrate async results (queries, promises, RSC/RPC payloads), treat error objects as sensitive and do not transport raw server error details to the client/shared layer. Use a default redaction policy and make the behavior explicitly configurable and documented.tanstack/query2 discussions
- Null-Safe Optional HandlingWhen dealing with possibly missing or nullable values (especially globals and config), make null/undefined handling explicit and never call a value unless you’ve verified its type.tanstack/query2 discussions
- Meaningful Identifier NamingUse names that clearly reflect the thing being identified, and ensure renamed identifiers don’t accidentally couple to old data or misleading conventions.tanstack/query2 discussions
- Maintain Predictable ConfigsConfiguration files should be predictable for every developer and remain maintainable over time. - Prefer explicit, stable values in runtime/version files (pin a specific version) so `nvm use`/install instructions work consistently. If you use an alias (like an LTS channel), ensure the exact alias form is supported (e.g., correct casing) and document why...tanstack/query2 discussions
- Lockfile Change HygieneLockfiles (e.g., pnpm-lock.yaml) are configuration artifacts and should only change when the dependency configuration (package.json / workspace manifests) changes. If there are no package.json changes, do not commit lockfile updates; treat any lockfile-only diffs as accidental/experimental output and revert them.tanstack/query2 discussions
- Keep API Types SyncedAny runtime API you expect developers to use must be discoverable and accurate in the public contract: update README/API docs and ensure the method is declared in the shipped `.d.ts`. Avoid “hiding” APIs behind missing typings or relying on long-lived `@ts-expect-error` type suppressions; fix the types/integration so the typed contract matches runtime...tanstack/query2 discussions
- Deterministic Async LifecycleEnsure async features that depend on a query/promise’s lifecycle (e.g., cancellation hooks, query function availability) are wired using a deterministic initialization order. Don’t write code paths that assume `query`/`query.promise` already exists; either (a) centralize initialization (e.g., reuse a prefetch-like path) or (b) explicitly create/transition...tanstack/query2 discussions
- Dependency-Aware ChangesetsWhen using CI/CD release automation based on Changesets, declare only the minimal packages that drive the release (so CI/CD doesn’t process redundant package updates), and ensure the release workflow is documented in an operationally explicit way.tanstack/query2 discussions
- Spring DI precedence rulesWhen developing Quarkus extensions that interact with classes containing Spring annotations (like `@Service`, `@Component`, etc.), ensure your extension respects Spring DI's scope definitions by setting appropriate annotation transformer priorities.quarkusio/quarkus2 discussions
- Prevent metrics cardinality explosionWhen implementing metrics and telemetry in your application, avoid using dynamic values like path parameters or user IDs directly as metric tags or dimensions. This practice causes cardinality explosion, which leads to excessive memory usage, degraded performance, and can overwhelm your monitoring systems.quarkusio/quarkus2 discussions
- Optimize elimination pathsWhen implementing algorithms that process large data structures or complex computational paths, prioritize opportunities for dead code elimination (DCE) and path optimization. Different initialization strategies (like build-time vs. runtime initialization) can dramatically affect which code paths are evaluated and optimized.quarkusio/quarkus2 discussions
- Keep configurations currentAlways use the latest stable and supported versions in configuration files. This applies to runtime environments, build plugins, and dependencies. Outdated configurations can limit functionality, miss security updates, or prevent access to newer features.quarkusio/quarkus2 discussions
- Document observability context flowsWhen implementing observability features like OpenTelemetry exporters, metrics collection, or distributed tracing, clearly document the context flow and environment limitations. Make explicit which features are available in specific environments (development vs. production), how context is propagated between components, and provide proper error handling for...quarkusio/quarkus2 discussions
- Design fluent HTTP APIsWhen designing HTTP-related APIs, prioritize readability and intuitiveness through well-crafted fluent interfaces. API methods should read naturally in code, expressing the developer's intent clearly and concisely.quarkusio/quarkus2 discussions
- Consolidate duplicate configurationsMaintain a single source of truth for configuration files instead of duplicating them across the codebase. Duplicated configurations (like banned-signatures.txt files) lead to maintenance challenges, potential inconsistencies, and confusion about which version is authoritative.quarkusio/quarkus2 discussions
- Type-appropriate null representationAlways use type-appropriate mechanisms to represent the absence of a value. For objects, use default constructors rather than nullptr. For potentially absent values, consider using optional types. For pointers, use null checks before performing operations on them.pytorch/pytorch2 discussions
- Reuse existing algorithmsBefore implementing common algorithms or utilities, check if the codebase already contains an appropriate implementation. Reusing existing, tested code reduces bugs, improves maintainability, and often provides better performance characteristics.pytorch/pytorch2 discussions
- Preserve API compatibilityWhen modifying existing APIs, always prioritize backward compatibility to avoid breaking client code. Before changing API signatures, function names, or return types, first consider the impact on existing consumers.pytorch/pytorch2 discussions
- Optimize container operationsMinimize CPU overhead in container operations by using efficient data structure patterns: 1. **Use static containers** for fixed lookup tables or maps that are frequently accessed but rarely changed. This avoids reconstruction overhead on each function call:pytorch/pytorch2 discussions
- Hardware acceleration considerationsWhen implementing hardware-accelerated operations for AI models, ensure support for the latest architectures while considering determinism requirements.pytorch/pytorch2 discussions
- Descriptive unambiguous namesAlways use descriptive variable names that clearly indicate their purpose without requiring readers to check call sites or implementation details. Avoid single-letter variables like `t` or vague abbreviations, especially in public interfaces and open-source code. Additionally, ensure clear distinction between similarly named variables, particularly when...pytorch/pytorch2 discussions
- Choose data structures wiselyWhen designing algorithms, select data structures that accommodate all possible scenarios, not just the common case. For static analysis algorithms where certainty isn't guaranteed, prefer collections that can represent one-to-many relationships even when most instances will contain only one element. This prevents having to redesign your algorithm later...pytorch/pytorch2 discussions
- Choose appropriate pointer typesSelect the right pointer type based on ownership semantics to prevent null reference issues and memory leaks. Follow these guidelines: 1. Use smart pointers (`shared_ptr`, `unique_ptr`) when ownership transfer is neededpytorch/pytorch2 discussions
- Centralize configuration detectionAlways use centralized configuration detection mechanisms (like CMake finder modules) instead of hardcoding paths or environment variables. This approach ensures compatibility across different installation methods and environments.pytorch/pytorch2 discussions
- Actionable error messagesWhen writing error messages in PyTorch code, include not only what went wrong but also clear guidance on how to fix the issue. This helps users quickly understand and resolve problems without digging through documentation.pytorch/pytorch2 discussions
- Use semantic namesUse intention-revealing, consistent, and unique names for CI workflow, jobs, and steps (avoid generic labels like `build`). Names should tell the reader what the unit actually does.TheAlgorithms/Python2 discussions
- Idiomatic Style CommandsWhen writing style guidance (including README/CONTRIBUTING snippets), keep examples concise and readable: 1) Use idiomatic tool invocations (avoid redundant arguments)TheAlgorithms/Python2 discussions
- Avoid stray commasWhen running linters/formatters in CI or scripts, keep command arguments syntactically precise and standardized—remove any stray or meaningless punctuation (like a standalone comma) and normalize whitespace so commands are unambiguous.TheAlgorithms/Python2 discussions
- Specific types for performanceUsing concrete types instead of abstract container classes in data models improves validation performance. More specific types require fewer checks and coercion attempts, resulting in faster validation. Additionally, ensure proper model parametrization to prevent unnecessary revalidation, which can trigger validators repeatedly.pydantic/pydantic2 discussions
- Enforce style with lintersUse automated linting tools to enforce consistent code style across the project, but be deliberate about which rules to include or exclude. When adding new linters or rules, evaluate their impact on the codebase before fully adopting them.pydantic/pydantic2 discussions
- Data structure correctnessEnsure data structures are accurately represented with their proper constraints and valid implementations, particularly for recursive structures. When documenting or implementing collections:pydantic/pydantic2 discussions
- Avoid unnecessary operationsCheck conditions early to skip unnecessary processing and reuse computed values where possible to optimize performance. This reduces CPU cycles and improves execution speed, especially in performance-critical code paths.pydantic/pydantic2 discussions
- Avoid shared structure mutationWhen implementing algorithms that manipulate complex nested data structures, avoid directly mutating shared objects that might be referenced elsewhere in the system. Mutations can lead to unexpected side effects and hard-to-trace bugs, particularly when the same structure is referenced in multiple places.pydantic/pydantic2 discussions
- Write objectivelyUse an impersonal, objective tone in technical documentation. Avoid using second-person pronouns ("you") and subjective terms like "simple" or "easy" which make assumptions about reader knowledge.prowler-cloud/prowler2 discussions
- Task signature methodsWhen chaining Celery tasks, choose the correct signature method: - Use `.s()` when a task needs the output from the previous task in the chain - Use `.si()` (immutable signature) when a task doesn't need any output from the previous taskprowler-cloud/prowler2 discussions
- Prefer server componentsDefault to server components in Next.js applications to maximize the benefits of server-side rendering. Avoid adding "use client" directives unnecessarily, especially at the page level. prowler-cloud/prowler2 discussions
- Parameterize configuration valuesAlways extract configuration values (like versions, paths, or other changeable settings) into parameters rather than hardcoding them directly in multiple places. This creates a single source of truth, simplifies updates, and makes your code more maintainable.prowler-cloud/prowler2 discussions
- Log exceptions with contextWhen handling exceptions in your code, ensure they are properly logged with sufficient context to aid debugging. For critical exceptions, use Sentry to track them alongside regular logging. For handled exceptions, include both the object being processed and the exception details in your log message.prowler-cloud/prowler2 discussions
- Format AI code identifiersWhen documenting AI systems, always format code identifiers, function names, agent names, model names, and other technical references with backticks (`) to improve readability and clearly distinguish them from regular text. This is particularly important in AI documentation where specialized components like agents, models, and functions need to be visually...prowler-cloud/prowler2 discussions
- Flexible AI model versionsWhen integrating LLM or AI models into your application, implement model selection in a way that accommodates the rapid evolution of AI capabilities without requiring frequent code deployments.prowler-cloud/prowler2 discussions
- Environment variables for configurationsStore all configurable values such as URLs, API endpoints, and external service locations in environment variables rather than hardcoding them in the codebase. This makes the application more maintainable, secure, and environment-adaptable.prowler-cloud/prowler2 discussions
- Endpoints for evolving dataDesign dedicated API endpoints for data that changes frequently or grows over time, rather than hardcoding such information in frontend files. This pattern ensures that applications remain maintainable as backend data evolves.prowler-cloud/prowler2 discussions
- Enable database resilienceAlways configure appropriate resilience features for database services to ensure data durability and high availability. This includes: 1. **Enable regular backups with sufficient retention periods** for all database clusters to prevent data lossprowler-cloud/prowler2 discussions
- Consistent environment variable namingWhen naming environment variables, ensure that names are both technically accurate and follow established project conventions: 1. Use terminology that precisely reflects the actual content and purpose of the variable, especially for security-related configurations.prowler-cloud/prowler2 discussions
- Configure observability variablesAlways define all necessary environment variables for observability tools in configuration files, even if using default values. For error tracking services like Sentry, include both connection strings and contextual variables to ensure comprehensive error reporting. This improves troubleshooting by providing environment and release information with each...prowler-cloud/prowler2 discussions
- Use proper configuration toolingWhen working with configuration files and values, prefer dedicated tools and canonical sources over manual text manipulation or secondary configuration files. Use language-specific tools for modifications (e.g., `go mod edit -go=1.23` instead of `sed` commands on go.mod) and extract configuration values from their primary sources rather than derived files.prometheus/prometheus2 discussions
- test practical monitoring scenariosWhen writing tests for observability features like metrics, functions, and alerting expressions, ensure test cases cover practical, real-world monitoring scenarios in addition to edge cases. Focus on common usage patterns that developers will actually use in production monitoring and alerting.prometheus/prometheus2 discussions
- Make build steps visibleBuild processes should provide clear, visible feedback about the operations being performed rather than suppressing output or running silently. This transparency helps developers understand what's happening during builds, aids in debugging when issues occur, and builds confidence that expected operations (like code signing) are actually executing.prometheus/prometheus2 discussions
- leverage standard algorithmsWhen implementing common algorithmic tasks like string parsing, sorting, or comparison operations, prefer built-in utilities and standard library functions over custom implementations. Standard algorithms are typically more efficient, well-tested, and maintainable than custom solutions.prometheus/prometheus2 discussions
- consistent parameter namingMaintain consistent naming and symbol choices throughout code and documentation, prioritizing readability and avoiding ambiguity. When choosing between equivalent representations (like φ vs phi), select the more widely understood option and use it consistently across all related contexts.prometheus/prometheus2 discussions
- Centralize shared configurationsWhen adding common functionality like help targets, build rules, or other configuration elements that will be used across multiple projects or subdirectories, prefer centralizing them in shared configuration files rather than duplicating the implementation.prometheus/prometheus2 discussions
- Validate sensitive operationsAlways implement safety checks before performing operations that could expose sensitive data or cause destructive changes. This includes validating targets before file deletion and sanitizing credentials in error messages.prisma/prisma2 discussions
- Research configuration format supportWhen migrating configuration files to newer formats, research current ecosystem support before defaulting to compatibility layers. Many tools and plugins may already support modern formats even if documentation suggests otherwise.prisma/prisma2 discussions
- Prioritize searchable namesChoose names that are easily searchable and immediately understandable, avoiding unclear abbreviations and symbols that hinder discoverability. Names should communicate their purpose clearly without requiring domain knowledge to decode.prisma/prisma2 discussions
- Official product namingWhen referencing external products, libraries, or services in documentation and code, always use their official names exactly as specified by the vendor, and treat them as proper nouns without articles.prisma/prisma2 discussions
- Document network configurationWhen configuring network settings in containerized services, always document the reasoning behind specific choices, especially for port mappings and security-related flags. This helps other developers understand the configuration and prevents accidental misconfigurations.prisma/prisma2 discussions
- Document configuration alternativesWhen documenting configuration setup, provide multiple formats and approaches to accommodate different tools, platforms, and environments. Include both the base command and tool-specific configuration examples when applicable.prisma/prisma2 discussions
- Design runtime-specific API exportsWhen designing APIs that need to work across different JavaScript runtimes (Node.js, edge environments, browsers), create explicit export configurations that account for runtime-specific implementations. Different runtimes may require different API implementations that aren't interchangeable, so provide separate entry points rather than trying to create a...prisma/prisma2 discussions
- Accurate method descriptionsAPI documentation must precisely describe method behavior, especially return values and cardinality. Inaccurate descriptions mislead developers about what methods actually return, potentially causing runtime errors or incorrect assumptions.prisma/prisma2 discussions
- Vue syntax parsing robustnessWhen processing Vue components, ensure parsing logic handles edge cases correctly and selects appropriate parsers safely. This includes proper validation of directive syntax and careful parser selection based on explicit language declarations.prettier/prettier2 discussions
- Use example configuration filesWhen providing team configuration files that developers might want to customize, use `.example` suffixes and implement automatic copying mechanisms to avoid conflicts with personal settings.prettier/prettier2 discussions
- Use descriptive namesChoose names that clearly communicate purpose and meaning rather than implementation details or obscure abbreviations. Names should be easily understood by other developers and reflect what the identifier actually represents or does.prettier/prettier2 discussions
- Use cross-platform commandsWhen writing CI/CD scripts and documentation, prefer Node.js APIs over shell commands for file operations to ensure cross-platform compatibility. Shell commands like `echo "content" > file` don't work consistently across different operating systems, particularly Windows, which can cause CI/CD pipelines to fail.prettier/prettier2 discussions
- Test all variationsEnsure comprehensive test coverage by testing all behavioral variations, configuration options, and edge cases rather than just single scenarios. When adding new functionality, preserve existing tests and add new ones to cover both old and new behaviors.prettier/prettier2 discussions
- targeted CSS modificationsMake targeted, purposeful CSS modifications that either enhance visual presentation or fix specific functionality issues without disrupting existing styles. When adding new styles, focus on specific improvements like centering text or adjusting colors. When modifying existing styles, preserve the original intent and make minimal changes to address the...prettier/prettier2 discussions
- Document CI workflow rationaleAlways include clear comments explaining the reasoning behind CI workflow decisions, including test environment separation, version matrix choices, and build requirements. This prevents confusion about when different workflows should be used and helps maintain consistency across the team.prettier/prettier2 discussions
- cache invalidation strategyImplement comprehensive cache invalidation mechanisms that automatically handle format changes between versions while providing clear manual removal options. When cache formats change, automatically detect and remove incompatible cache files to prevent runtime errors. Additionally, document cache locations and provide accurate removal commands for manual...prettier/prettier2 discussions
- Benchmark performance optimizationsAlways measure and validate performance optimizations with concrete benchmarks before implementing them. Performance assumptions can be misleading, and minor gains may not justify added complexity or reduced correctness.prettier/prettier2 discussions
- Angular syntax parsingWhen implementing Angular syntax parsing, ensure robust handling of Angular-specific constructs by properly distinguishing AST node types and normalizing flexible syntax patterns.prettier/prettier2 discussions
- Validate LLM ConfigEnsure any LLM configuration is provider/model compatible by (1) validating cross-parameter constraints (especially token budget vs max output) and (2) applying only parameters supported by that specific provider/model (e.g., don’t set `temperature` for configs that don’t allow it). This prevents runtime BadRequest errors and reduces wasted latency/cost.the-pr-agent/pr-agent2 discussions
- Secure CI InvocationWhen updating CI/CD pipeline configuration for third-party tools, apply two security rules: (1) never embed secret values directly in command-line arguments; (2) pin third-party images/actions to immutable digests to prevent supply-chain drift.the-pr-agent/pr-agent2 discussions
- Safe, Optional API ContractsWhen designing API responses and client-triggered actions, keep contracts accurate and defaults safe: 1) Make optional data optional in response schemasthe-pr-agent/pr-agent2 discussions
- Verify error handling pathsWhen implementing error handling logic, ensure that both the behavior and reasoning are clear, and that error paths are properly tested at appropriate levels. For methods that handle missing data, the default behavior should be explicitly documented and the method name should clearly indicate what the return value represents. For exception handling, verify...PostHog/posthog2 discussions
- validate schema decisionsWhen reviewing database schema changes or data structure modifications, ensure that field inclusion/exclusion decisions are explicitly justified and documented. Question ambiguous schema choices and require clear rationale for data organization patterns.PostHog/posthog2 discussions
- validate before useAlways validate that values are truthy or defined before using them, even when they are expected to exist. This prevents runtime errors and unexpected behavior when assumptions about data presence are violated.PostHog/posthog2 discussions
- Use error chain iteratorsWhen traversing error chains in Rust, prefer using the `chain()` iterator method over manual source traversal with while loops. The `chain()` method provides a more idiomatic and readable approach to walking through error chains, eliminating the need for manual loop management and making the code more concise.PostHog/posthog2 discussions
- two-phase filtering algorithmsWhen working with large datasets or complex matching operations, implement algorithms that use a two-phase approach: first filter candidates using efficient broad criteria, then verify matches with precise logic. This pattern significantly improves performance by reducing the number of expensive operations.PostHog/posthog2 discussions
- Test edge cases comprehensivelyEnsure your tests cover not just the happy path, but also edge cases, empty states, error conditions, and boundary scenarios. This includes testing with empty datasets, validating pagination logic, handling unusual input values, and verifying error handling behavior.PostHog/posthog2 discussions
- Optimize database query patternsAvoid N+1 query problems and overly complex conditional SQL construction. When loading related data, prefer batch operations or dedicated endpoints that can fetch all required data in fewer queries. For conditional SQL parameters, consider using null values with database defaults instead of constructing different query strings.PostHog/posthog2 discussions
- minimize expensive operationsAvoid triggering expensive operations (queries, API calls, computations) on every user input or state change. Instead, use appropriate triggers that balance responsiveness with performance.PostHog/posthog2 discussions
- Local configuration exclusionExclude personal and local configuration files from version control while ensuring they are properly handled during environment setup. Personal configurations should use patterns like `*.local.*` or be placed in designated directories that are gitignored to prevent accidental commits of developer-specific settings.PostHog/posthog2 discussions
- leverage framework capabilitiesStructure workflows and activities to take full advantage of the orchestration framework's built-in capabilities for fault tolerance, retries, and durable execution rather than implementing custom solutions.PostHog/posthog2 discussions
- Keep state in KeaReact components should focus on presentation and user interaction, not state management logic. All state logic should be contained within Kea stores, with components only pulling in actions and values. This separation improves testability, reusability, and maintainability.PostHog/posthog2 discussions
- Follow CSS naming patternsMaintain consistency with established CSS naming conventions already used in the codebase. For CSS classes, follow BEM methodology when that's the existing pattern. For custom properties, use semantic names that clearly indicate their purpose and work across themes.PostHog/posthog2 discussions
- Environment-based configuration managementPrefer environment variables over file mounting for configuration values, and avoid hardcoded environment-specific conditionals like `isCloud()`. Instead, rely purely on configuration environment variables that can be set differently across environments. When setting default configuration values, consider the constraints and limits of downstream systems to...PostHog/posthog2 discussions
- Enrich telemetry contextAlways include relevant contextual metadata when capturing telemetry data (events, exceptions, logs, metrics) to improve debugging and operational visibility. This includes user information, team ownership, product areas, IP addresses, user agents, geographic data, and other relevant context that helps with troubleshooting and error assignment.PostHog/posthog2 discussions
- Configuration naming clarityEnsure configuration variable names, display labels, and feature flag names accurately reflect their actual purpose and behavior. Misleading or outdated names create confusion for both developers and users, making the codebase harder to maintain and understand.PostHog/posthog2 discussions
- API parameter semanticsEnsure API parameters have clear semantic meaning and avoid sending null values for optional fields. When designing API endpoints, use parameter names that accurately reflect their purpose and data type. For optional fields, omit them entirely from the payload rather than setting them to null, as this creates cleaner API contracts and prevents confusion...PostHog/posthog2 discussions
- API initialization side effectsWhen initializing API clients, prefer bootstrap/configuration patterns over method calls that may trigger unintended side effects like billing events, data capture, or state changes. Method calls during initialization can have unexpected consequences that users may not anticipate or want to pay for.PostHog/posthog2 discussions
- Add monitoring metricsCritical code paths, especially error handling and exception scenarios, should include metrics or counters to enable monitoring and alerting. This prevents systems from failing silently and provides visibility into system health.PostHog/posthog2 discussions
- Use consistent temporal typesWhen implementing or modifying temporal operations, maintain consistent data types that align with existing temporal functions. Specifically, use Int8 for datetime components with small ranges (months, days, hours, minutes, seconds) and Int32/Int64 for larger values (years, microseconds). This approach reduces unnecessary type casting, improves code...pola-rs/polars2 discussions
- Edge case algorithm handlingWhen implementing algorithms, pay special attention to edge cases, particularly empty collections. Define and document how your algorithm behaves in these boundary conditions following consistent mathematical or programming conventions.pola-rs/polars2 discussions
- Cross-platform feature flagsWhen documenting package installation commands with feature flags, ensure compatibility across different operating systems. Windows handles quoted package specifications differently than Unix-based systems, which can lead to installation failures.pola-rs/polars2 discussions
- Verify configuration optionsAlways verify that configuration file options and command flags are correct and properly documented. Incorrect configuration syntax can cause silent failures or unintended side effects that are difficult to debug.python-poetry/poetry2 discussions
- specify tool version requirementsWhen documenting CI/CD tools and integrations, always specify exact version requirements and compatibility constraints. This prevents integration failures and ensures reproducible builds across different environments.python-poetry/poetry2 discussions
- Pin tool versions explicitlyAlways specify exact versions for tools and dependencies in CI/CD workflows to ensure reproducible builds and avoid issues with cached or default system versions. Use package managers and version pinning rather than relying on system-installed tools.python-poetry/poetry2 discussions
- Network request configurationWhen implementing or documenting network functionality, ensure proper configuration options are provided and compatibility across different environments is considered. Network requests should have configurable timeouts and work reliably across platform variations.python-poetry/poetry2 discussions
- consistent semantic namingNames should follow established team conventions while accurately reflecting their purpose and functionality. Inconsistent naming schemes and misleading identifiers create confusion and maintenance overhead.python-poetry/poetry2 discussions
- Add missing code documentationEnsure all methods have docstrings and complex logic includes explanatory comments to help contributors understand code intent and functionality. Missing documentation creates barriers for new contributors and makes code maintenance more difficult.python-poetry/poetry2 discussions
- validate input rigorouslyAlways validate and sanitize input data against established standards to prevent injection attacks and ensure consistent behavior. This includes validating ARIA attributes according to W3C specifications and encoding potentially dangerous content in CSS or HTML contexts.microsoft/playwright2 discussions
- Use semantically clear namesNames should clearly communicate their actual purpose and be consistent across similar contexts. Avoid names that mislead about functionality or create confusion about the component's role.microsoft/playwright2 discussions
- Secure authentication state filesAuthentication state files (such as browser session files, cookies, or tokens) contain sensitive credentials that can lead to full account takeover if exposed. These files must never be committed to version control systems as they could be used to impersonate users or test accounts.microsoft/playwright2 discussions
- Python syntax consistencyEnsure Python code follows proper naming conventions and syntax rules. Use snake_case for variable and parameter names instead of camelCase, and use capitalized boolean literals (True/False) instead of lowercase variants from other languages.microsoft/playwright2 discussions
- Justify dependency changesAlways provide clear justification when modifying dependency configurations, including version updates, dependency types, or new additions. Consider the impact on stability, compatibility, and end users before making changes.microsoft/playwright2 discussions
- Handle errors explicitlyAlways provide explicit error handling instead of allowing silent failures or blank screens. Any place where an error can occur but is not handled explicitly is a bug. When errors occur, communicate clearly to users what went wrong and suggest recovery actions when possible.microsoft/playwright2 discussions
- graceful process terminationImplement systematic cleanup mechanisms that handle process termination signals without generating excessive error output. Use a generic disposable pattern to manage resources that need cleanup during exit, SIGINT, or other termination scenarios.microsoft/playwright2 discussions
- Document network limitationsWhen documenting network-related features, clearly specify compatibility constraints, browser limitations, and potential side effects. This is especially critical for experimental features or those with platform-specific restrictions.microsoft/playwright2 discussions
- Document configuration formats explicitlyWhen documenting environment variables and configuration options, explicitly list all supported value formats rather than using vague descriptions. Use individual backticks around each supported value for clear formatting.microsoft/playwright2 discussions
- Document build configuration changesWhen modifying build tool configurations, especially during migrations, provide detailed technical justification for each change. Document why specific options, plugins, or flags are being added, removed, or modified with concrete reasoning.microsoft/playwright2 discussions
- Comprehensive contextual error handlingImplement thorough error handling that goes beyond basic logging and provides contextually accurate, actionable error messages. Error handling should include proper propagation, recovery mechanisms where appropriate, and messages that reflect the actual system state and available options.microsoft/playwright2 discussions
- API documentation precisionAPI documentation must use specific, well-defined types instead of generic ones, and clearly define behavior for all scenarios including edge cases. When documenting return types, use explicit union types or named type aliases rather than generic strings. For complex APIs with multiple options, document the interaction between different parameters and their...microsoft/playwright2 discussions
- API consistency and decouplingAPIs should maintain consistent behavior and avoid tight coupling to implementation details or environmental dependencies. Don't make API methods conditionally available based on state, and avoid exposing filesystem paths or other environment-specific concerns in component interfaces.microsoft/playwright2 discussions
- Reliable integration testsIntegration/E2E tests should be structured and isolated: use consistent fixture setup/teardown to avoid flakiness and leftover files, and organize higher-level tests using reusable helpers and known-good inputs/models.earendil-works/pi2 discussions
- No Console LoggingAvoid direct `console.log`/`console.warn` (and other `console.*`) in application code—especially in TUI/interactive flows—because it can break rendering and other runtime behavior. Route all log/diagnostic output through the project’s logging/UI abstraction so messages are formatted and displayed consistently.earendil-works/pi2 discussions
- Minimize Resource ChurnPrefer designs that avoid unnecessary resource usage—especially filesystem churn and redundant persistence/reload. - For temporary artifacts, use the OS-managed temp directory (so cleanup is automatic) rather than creating long-lived app-specific temp folders.earendil-works/pi2 discussions
- Intentional Cache DesignCache behavior should be justified by real reuse and measured impact. Apply this standard: 1) Scope the cache correctly: for per-process/per-session data, prefer in-memory caching and avoid disk persistence unless it measurably reduces recomputation time on restart/resume.earendil-works/pi2 discussions
- Intentful Comments And LimitsAdd comments that explain *why* the code behaves as it does—especially for platform-specific/terminal/UI quirks—and explicitly document any partial implementation.earendil-works/pi2 discussions
- Domain-aligned Identifier NamingWhen introducing identifiers that represent external/domain data (e.g., tool calls, event payloads) and shared utilities, keep naming and placement semantically aligned and avoid redundant typing.earendil-works/pi2 discussions
- Specific Test CoverageWhen tests target a particular guard, ordering, or threshold, ensure the test inputs actually exercise that exact logic (and not an earlier rejection/acceptance). Also pin threshold behavior with both sides.firecrawl/pdf-inspector2 discussions
- Optimize With CorrectnessWhen optimizing for performance, first determine whether the computation truly depends only on the requested subset or on document-wide/global evidence.firecrawl/pdf-inspector2 discussions
- Ecosystem Version HygieneWhen automating builds and publishing, apply two rules for version metadata correctness: 1) Keep registry ecosystems independent unless you’re doing an explicit coordinated migration. If crates.io/PyPI/npm/WASM have separate release cadences, don’t force matching numbers across them—bump based on the target registry’s current release state and workflow.firecrawl/pdf-inspector2 discussions
- Consistent Binding APIsWhen exposing a Rust library through multi-language bindings, treat the binding surface as a single canonical API: mirror the underlying Rust types/surfaces instead of reshaping them differently per client, and ensure exported classes/functions are actually registered so clients can import them.firecrawl/pdf-inspector2 discussions
- organize import groupsImports should be organized into distinct groups with proper spacing for better readability. Group all third-party library imports together in one contiguous block, followed by a blank line, then group all local/relative imports in another block. This separation makes it immediately clear which dependencies are external versus internal to the project.emcie-co/parlant2 discussions
- Make test descriptions specificTest scenarios and steps should use specific, descriptive language that clearly communicates what is being tested and what behavior is expected. Avoid vague or ambiguous terms that leave room for interpretation.emcie-co/parlant2 discussions
- Implement graceful error handlingReplace assertions, unhandled exceptions, and error-suppression mechanisms with proper error handling that provides clear, actionable feedback to users. Instead of allowing applications to crash or silently hide issues, implement structured error handling that communicates what went wrong and suggests next steps.emcie-co/parlant2 discussions
- Document meaningful complexityDocumentation should add genuine value by explaining non-obvious behavior, complex approaches, or important context that isn't immediately clear from the code itself. Remove redundant docstrings and comments that merely restate what the code obviously does, while ensuring that sophisticated algorithms, design decisions, or non-trivial implementations are...emcie-co/parlant2 discussions
- Configuration design clarityDesign configuration with clear semantics and appropriate scope. Avoid global constants for values that can be handled locally, and ensure configuration parameters have logical, non-contradictory meanings.emcie-co/parlant2 discussions
- Use relative documentation linksWhen documenting error handling mechanisms, always use relative path references (`../path/to/file.mdx`) instead of absolute paths (`/docs/path/to/file`) when creating documentation links. This ensures documentation about error handling, assertions, validations, and error recovery patterns remains navigable even when documentation structures change.opentofu/opentofu2 discussions
- Review consistency assumptionsPeriodically reassess your database operations based on updated consistency guarantees offered by storage technologies. As database services evolve over time, operations initially designed to work around consistency limitations may become unnecessary overhead that impacts performance.opentofu/opentofu2 discussions
- Provider instance managementEnsure proper configuration of provider instances when using environment-specific settings. When using `for_each` with providers, carefully manage the lifecycle of provider instances to avoid warnings or errors during resource operations.opentofu/opentofu2 discussions
- Protect infrastructure secretsInfrastructure-as-code tools like OpenTofu may store sensitive information in plaintext state files, creating security risks for passwords, API keys, and other secrets. Always implement proper protection measures:opentofu/opentofu2 discussions
- Document phased migration pathsWhen replacing an existing system feature with a new implementation, provide a clear and well-documented phased migration path. Design your system to support both old and new approaches simultaneously during a transition period, allowing users to migrate gradually without disruption.opentofu/opentofu2 discussions
- Contextualize security findingsWhen reporting security vulnerabilities, include sufficient context beyond just vulnerability IDs or codes. Always preserve standard identifiers (like GO-YYYY-NNNN) in titles while adding descriptive information about affected components, versions, and modules. This makes vulnerabilities easier to prioritize, track, and remediate.opentofu/opentofu2 discussions
- Clear relationship descriptionsWhen documenting algorithms or data structures with graph-like relationships, use precise terminology to describe connections between elements. This is especially important when explaining how operations traverse or transform structured data.opentofu/opentofu2 discussions
- Use proper testing frameworksAlways leverage established testing frameworks and APIs over custom bash scripts or direct Python execution for test automation. Using proper testing frameworks improves maintainability, provides better error handling, and enables more flexible test configuration.open-telemetry/opentelemetry-python2 discussions
- Track observability API changesStay informed about API changes in observability libraries like OpenTelemetry, especially during their active development phases. Ensure that both implementation code and documentation are updated to reflect the current API patterns.open-telemetry/opentelemetry-python2 discussions
- Telemetry version pinningWhen specifying observability frameworks like OpenTelemetry in requirements files, use the compatible release operator (~=) with only the major and minor version numbers, omitting the patch version. This ensures you receive bug fixes in patch releases while protecting against potential breaking changes in minor versions.open-telemetry/opentelemetry-python2 discussions
- Adapt for linter compatibilityWhen writing or modifying code, design patterns and templates to be compatible with linting tools. This is especially important for generated code and template systems.open-telemetry/opentelemetry-python2 discussions
- Use authoritative data sourcesWhen working with network-related data, always read from the most direct and authoritative source available rather than making assumptions or relying on indirect indicators. This ensures accuracy and robustness in network operations.commaai/openpilot2 discussions
- Platform-specific socket configurationWhen configuring TCP socket options, always check the platform and apply appropriate settings for each operating system. Different platforms support different socket options and may require different approaches for connection management.commaai/openpilot2 discussions
- pin external action versionsAlways pin external GitHub Actions to specific commit hashes rather than using tags or branch names, and prefer built-in runner capabilities when available. This improves security by preventing supply chain attacks and ensures reproducible builds.commaai/openpilot2 discussions
- Parameterize hardcoded API valuesWhen designing APIs or interfaces, avoid hardcoding string literals, configuration values, or identifiers that could be made configurable through parameters. This makes the API more flexible, reusable, and maintainable by allowing callers to specify their own values rather than being locked into fixed behavior.commaai/openpilot2 discussions
- optimize mathematical mappingsUse consistent units and data representations throughout mathematical calculations to avoid unnecessary computational overhead. When working with value ranges, prefer direct mathematical mappings over multiple conversions, and leverage utility functions for range transformations.commaai/openpilot2 discussions
- Optimize git network operationsWhen performing git operations that involve network communication, use proper syntax and efficient strategies to minimize data transfer and ensure correct remote branch handling.commaai/openpilot2 discussions
- maintain CI/CD parityEnsure CI/CD pipeline tools run with the same configuration, flags, and behavior as developers use locally. This prevents masking errors in CI/CD that developers would encounter in their local environment and maintains consistency in the development workflow.commaai/openpilot2 discussions
- Explicit value specificationsAlways use explicit value specifications and type-safe handling to prevent undefined behavior and ensure predictable code execution. This includes specifying appropriate default values for configuration parameters and using platform-independent format specifiers for data types.commaai/openpilot2 discussions
- Design convenient APIsAPIs should provide convenient methods that handle common operations directly, rather than requiring users to write helper functions or use verbose patterns. This improves developer experience and reduces boilerplate code.commaai/openpilot2 discussions
- Consistent terminology choicesWhen introducing new terminology or naming conventions, ensure consistency with existing patterns in the codebase while prioritizing clarity and universal understanding. Before adding new names, identifiers, or terminology, review existing usage patterns and adopt the established conventions. When multiple options exist, choose the most widely understood...commaai/openpilot2 discussions
- Centralize error handling utilitiesCreate reusable error handling functions that accept custom error callbacks instead of duplicating error handling logic across multiple files. This approach provides flexibility in error response while maintaining consistent error handling patterns throughout the codebase.commaai/openpilot2 discussions
- Cache expensive operationsIdentify operations that are expensive and called frequently, then optimize them by caching results, moving to appropriate lifecycle events, or replacing with faster alternatives. Expensive operations like parameter reads, system calls, or complex computations should not be repeated unnecessarily in hot code paths.commaai/openpilot2 discussions
- Idempotency key normalizationWhen implementing caching/idempotency for tools that generate external media, make cache keys stable and semantically accurate. **Rules** 1. **Normalize before hashing:** Resolve optional fields through `input_schema` defaults; treat an explicit `None` as “unset”, so omitted and defaulted inputs produce the same key.calesthio/OpenMontage2 discussions
- Idempotency Key CompletenessWhen implementing API endpoints/clients that use idempotency keys, ensure the idempotency key includes **all request fields that can change the output** (including aliases/variants). Otherwise, different calls can collide and incorrectly deduplicate.calesthio/OpenMontage2 discussions
- Extract duplicated logicWhen you notice the same code pattern appearing in multiple places, extract it into a reusable function rather than copy-pasting. Duplicated code is error-prone and harder to maintain. Look for repeated logic, data structure creation patterns, or similar operations that can be abstracted.opengrep/opengrep2 discussions
- Ensure cross-platform compatibilityWrite code that works consistently across different platforms and environments. Avoid using Unicode symbols or special characters that may not render properly in all terminals or logging systems, as they can cause display issues or interfere with automated processing. Use portable system paths and commands that work across different operating systems.opengrep/opengrep2 discussions
- Thread-safe resource cleanupWhen implementing resource cleanup in concurrent applications, avoid using deprecated finalizers and instead use PhantomReference-based cleanup mechanisms that ensure thread safety.opencv/opencv2 discussions
- Maintain build compatibilityWhen modifying build scripts or configurations, ensure compatibility across all supported environments and properly test changes through CI pipelines. For tools with version-dependent features, add version checks and provide alternative implementations for older versions.opencv/opencv2 discussions
- Document configuration version requirementsMake build configuration options explicit and document their version dependencies. When introducing configuration parameters that are version-specific, clearly indicate compatibility requirements and provide command-line options to make constraints optional when appropriate.opencv/opencv2 discussions
- Check nulls directlyCheck objects directly for null/empty state instead of using separate tracking variables. Always perform null checks early in your functions, before entering resource-intensive blocks or operations that assume non-null values.opencv/opencv2 discussions
- Tailwind v4 Z SyntaxWhen using Tailwind CSS v4, follow the v4-supported utility syntax for z-index and similar numeric utilities. Prefer the non-bracket form `z-<number>` (e.g., `z-150`, `z-200`) instead of `z-[<number>]`; the JIT compiler will handle arbitrary numeric values and won’t drop these classes.opencut-app/opencut2 discussions
- Consistent Imports And ConstantsKeep code style consistent by (1) avoiding redundant imports and (2) centralizing shared UI values. - Imports: Use only what you actually need. If the project uses the modern JSX transform, don’t import a default `React` namespace just for JSX.opencut-app/opencut2 discussions
- validate AI model configurationsWhen adding or modifying AI model configurations, ensure proper validation through both pattern-based matching and functional testing. Avoid hardcoding specific model IDs when existing patterns can handle multiple models generically. Always test model functionality before adding to production configurations.sst/opencode2 discussions
- Separate configuration concernsKeep persistent user configuration separate from transient state, setup flags, and derived values. Persistent configuration should only contain user-defined settings that need to be saved across sessions. Transient state like cached detection results, setup completion flags, or runtime-derived values should be stored separately using dedicated state...sst/opencode2 discussions
- maintain JSON response consistencyWhen designing API responses that need to handle different data types or display states, maintain consistent JSON structure and use established encoding standards to preserve backward compatibility. Avoid changing response schemas that would break existing client integrations.sst/opencode2 discussions
- Ensure proper error signalingErrors must be communicated through appropriate mechanisms for their execution context. In CLI applications, use proper exit codes to indicate error states (non-zero for failures). For shell command execution, implement proper error handling to prevent unexpected crashes and provide graceful failure modes.sst/opencode2 discussions
- coordinate concurrent initializationWhen implementing expensive initialization operations that may be triggered concurrently, use a shared promise to coordinate multiple requests and prevent duplicate initialization. This pattern is especially important for operations like downloading dependencies, starting external processes, or establishing connections that take significant time to complete.sst/opencode2 discussions
- Contextualize documentation decisionsDocumentation should provide contextual guidance about when and why to use features, not just how to configure them. Additionally, strategically link to external documentation rather than duplicating content to reduce maintenance overhead.sst/opencode2 discussions
- Documentation DedupingWhen updating technical docs, avoid duplicating environment-specific setup or repeated troubleshooting steps. Prefer linking to the canonical upstream documentation for shell/env configuration, and keep only minimal project-specific commands (e.g., where you truly provide “permanent activation” instructions). Also consolidate identical “fix-it” guidance...openai/openai-python2 discussions
- Azure AD token responsibilityWhen adding Azure Active Directory authentication (Security), make token acquisition and dependency responsibility explicit and align it with your SDK’s lifecycle.openai/openai-python2 discussions
- Shared API ContractsDesign API endpoints so they orchestrate transport only, and keep domain logic + contract identifiers centralized. Apply these rules: 1) **Don’t couple libraries to route handlers**: HTTP-specific code (request/response/headers/params) stays in `route.ts`; core behavior (embeddings, memory indexing, etc.) lives in shared services used by both the API route...diegosouzapw/OmniRoute2 discussions
- Follow test constraintsWhen adding UI logic or tests, align with the repository’s existing CI/test guardrails—especially global checks and test discovery conventions. - **Respect cross-cutting test rules (e.g., i18n parity):** Don’t introduce changes that require mass updates across all locales/fixtures unless you’re prepared to complete them. If full compliance is out of scope,...diegosouzapw/OmniRoute2 discussions
- Fail-Closed Credential ChecksWhen validating security state (e.g., whether credentials are encrypted, authorized sessions exist, tokens exist, etc.), treat any inability to inspect sensitive data as a security failure—don’t silently default to a permissive/incorrect outcome. In practice:diegosouzapw/OmniRoute2 discussions
- Externalize config copyTreat user-facing UI text (help text, labels, descriptions, toggle text) as configuration: do not hardcode it in components. Instead, source it from the appropriate translation/config namespace using the team’s i18n helpers. Keep only upstream/system-provided constants (e.g., IDs, template metadata) as raw values when they are not user copy.diegosouzapw/OmniRoute2 discussions
- Explicit Undefined HandlingWhen a value is intentionally absent (e.g., an optional callback prop or required classification fields), represent that absence explicitly and don’t let missing/nullable data silently pass as “valid”.diegosouzapw/OmniRoute2 discussions
- Consistent Accessible UIWhen adding expandable/conditional UI in React/TSX, keep the structure consistent within the surrounding component *and* ensure accessibility attributes are applied uniformly.diegosouzapw/OmniRoute2 discussions
- Config precedence and canonical sourcesEstablish a single, explicit source-of-truth approach for configuration resolution: (1) honor user-supplied overrides first, (2) otherwise derive from the active context/environment, and (3) only then fall back to defaults; additionally, treat repository-level configuration/lock files as canonical entrypoints for developer tooling.diegosouzapw/OmniRoute2 discussions
- Purpose-reflecting file namesFile names should clearly communicate their purpose and functionality. Avoid generic, ambiguous, or numbered names (like "Makefile2") that don't convey the file's actual role or lead to recurring questions.ollama/ollama2 discussions
- Path traversal preventionImplement multiple validation layers to prevent path traversal attacks. File paths provided by users or external systems must be validated before use in filesystem operations:ollama/ollama2 discussions
- Optimize memory allocationsBe strategic about memory allocations to improve performance in your C++ code. Consider two key optimization patterns: 1. **Pre-reserve container capacity**: When using containers like vectors that will grow to a predictable size, use `reserve()` with a reasonable initial capacity to reduce allocation overhead. This prevents multiple small reallocations as...ollama/ollama2 discussions
- Model precision mattersWhen deploying AI models on specialized hardware accelerators (GPUs, NPUs), ensure you're using compatible model precision formats. Different hardware platforms have different optimal precision requirements that significantly impact performance and compatibility.ollama/ollama2 discussions
- Keep container images currentAlways use up-to-date and supported container images in Dockerfiles and configuration files. Before specifying a base image or version: 1. Verify the image hasn't been deprecatedollama/ollama2 discussions
- Extract duplicated codeIdentify repeated code segments and extract them into reusable functions or variables. This improves maintainability, reduces the risk of inconsistencies, and makes the code more concise.ollama/ollama2 discussions
- Complete HTTP protocol handlingWhen implementing HTTP client functionality, ensure comprehensive support for all standard HTTP status codes and secure connection scenarios: 1. Support all standard redirect status codes (301, 302, 303, 307, 308), not just a subset:ollama/ollama2 discussions
- Complete documentation coverageDocumentation should comprehensively cover all supported options, variations, and potential future use cases. When creating documentation: 1. Use generic titles and structures that can accommodate future additionsollama/ollama2 discussions
- AI dependency decoupling strategyImplement clear boundaries between your core AI system and external machine learning libraries through abstraction layers. This facilitates future library updates or replacements as AI technology evolves. When integrating external libraries (like llama.cpp), establish documented synchronization processes and gradually work toward independence, especially...ollama/ollama2 discussions
- Verify documentation linksAlways ensure external links in documentation are valid, secure, and point to authoritative sources. This includes: 1. Use HTTPS instead of HTTP links for securityoctokit/octokit.net2 discussions
- Use appropriate framework targetsWhen configuring .NET projects, always use the correct target framework elements and versions: 1. Use the singular `<TargetFramework>` element when targeting a single framework:octokit/octokit.net2 discussions
- Secure permission modelingWhen implementing security-related models such as permissions, carefully design the properties to prevent unauthorized modifications and maintain appropriate constraints:octokit/octokit.net2 discussions
- Precise and consistent namingNames should clearly indicate their specific purpose and context, while maintaining correct capitalization of brand names and products. When naming variables, parameters, or targets:octokit/octokit.net2 discussions
- File-specific indentation standardsMaintain consistent indentation based on file type to ensure code readability and prevent unwanted whitespace changes in PRs. Use 4 spaces for C# (.cs) files and 2 spaces for configuration files (like JSON, devcontainer files).octokit/octokit.net2 discussions
- Use precise terminologyAlways use specific, accurate terminology rather than vague or generic terms when naming sections, referencing products, or writing documentation. Ensure grammatical correctness and technical precision in all naming contexts.nrwl/nx2 discussions
- Use explicit identifiersChoose explicit, unambiguous names for functions, variables, and parameters to avoid conflicts with common types and reduce reliance on implicit assumptions. Prefer descriptive names that clearly indicate purpose over generic terms that might be confused with built-in types or require string parsing.nrwl/nx2 discussions
- Thread ownership clarityWhen designing concurrent systems, ensure data ownership is explicit and clear at thread boundaries. Avoid passing references across threads or using indirect access patterns that obscure ownership responsibilities.nrwl/nx2 discussions
- synchronize declared versionsEnsure that version declarations in configuration files accurately reflect the versions actually being used in runtime environments. Configuration drift occurs when declared versions diverge from deployed versions, leading to inconsistent environments and potential deployment issues.nrwl/nx2 discussions
- standardize TODO commentsUse version-specific TODO comments with a consistent format to ensure actionable items are properly tracked and easily searchable across the codebase. Include the target version in parentheses immediately after "TODO" to make it clear when the item should be addressed.nrwl/nx2 discussions
- Provide actionable error messagesWhen handling errors, transform technical exceptions into user-friendly messages that include clear remediation steps and actionable guidance. Avoid exposing raw technical errors to users, and instead provide context about what went wrong and how to resolve the issue.nrwl/nx2 discussions
- organize testing documentation clearlyEnsure testing documentation is properly categorized and uses precise terminology to maintain clarity and accessibility. Testing concepts should be organized into appropriate sections (e.g., "Testing Tools" rather than generic categories) and described with accurate language that clearly conveys the intended meaning.nrwl/nx2 discussions
- externalize configuration valuesConfiguration values should be externalized from code and read from standard locations like package.json or environment variables. Implement environment-aware validation that fails fast in production when required configuration is missing, while providing sensible defaults for development environments.nrwl/nx2 discussions
- Ensure informative log messagesLog messages should be clear, informative, and include specific details to help users understand what is happening. Avoid vague messages that could cause confusion, and ensure proper stream handling to prevent garbled output in concurrent scenarios.nrwl/nx2 discussions
- Context-aware configuration logicConfiguration logic should adapt based on environmental context rather than using static values. Examine the current environment state (file system, process hierarchy, feature flags) and adjust configuration accordingly to ensure optimal behavior in different scenarios.nrwl/nx2 discussions
- Clean CI configurationsMaintain clean and well-documented CI configurations by removing dead code and properly documenting temporary changes. Avoid leaving commented-out code in CI files - either remove unused configurations entirely or add proper TODO comments with context when temporarily disabling features.nrwl/nx2 discussions
- cache isolation boundariesWhen documenting caching systems, clearly specify cache isolation boundaries and access scopes to prevent confusion about cache behavior. Distinguish between global shared caches and isolated caches, and explain how different access levels affect cache storage and retrieval patterns.nrwl/nx2 discussions
- Avoid runtime API callsComponents should not make external API calls for data that can be pre-generated at build time. Instead of fetching dynamic data during component rendering, inject pre-computed values as props to improve performance and reduce external dependencies.nrwl/nx2 discussions
- API documentation accuracyEnsure API documentation examples use types, interfaces, and imports that actually exist in the documented versions. Verify that code examples can be successfully imported and executed before publishing documentation.nrwl/nx2 discussions
- accessibility attributes for decorative elementsDecorative images, icons, and other visual elements that don't convey meaningful content should include `aria-hidden="true"` to prevent screen readers from announcing them. This ensures a cleaner experience for users with assistive technologies and maintains consistent accessibility markup patterns across the codebase.nrwl/nx2 discussions
- Use proper HTTP utilitiesWhen handling HTTP cookies and headers, use dedicated utility functions instead of manual string manipulation. Manual parsing of HTTP headers, especially cookies, can lead to incorrect behavior due to the complexity of HTTP header formats.nuxt/nuxt2 discussions
- semantic names with countersWhen generating unique identifiers that may have multiple instances, combine semantic base names with counters or indices to ensure both readability and uniqueness. Use meaningful component names, scope IDs, or descriptive strings as the base, then append a counter to distinguish multiple instances.nuxt/nuxt2 discussions
- safe error data handlingWhen processing error data that may contain unsafe or undefined values, use safe parsing methods and defensive programming techniques to prevent secondary exceptions during error handling.nuxt/nuxt2 discussions
- Preserve HTTP header semanticsHTTP headers have specific semantics that must be respected when processing, merging, or deduplicating them. Avoid naive approaches that treat headers as simple key-value pairs, as this can break protocol compliance and cause unexpected behavior.nuxt/nuxt2 discussions
- organize accessibility attributesSystematically organize HTML elements by adding appropriate accessibility attributes (aria-label, role) to improve code structure and semantic clarity. Place accessibility attributes immediately after class attributes for consistent code organization and enhanced readability.nuxt/nuxt2 discussions
- optimize CI/CD configurationsReview CI/CD workflow configurations for both performance optimizations and accuracy in conditional logic. This includes minimizing resource usage where possible and ensuring all conditional statements use correct values.nuxt/nuxt2 discussions
- improve code readabilityAdd line breaks and proper spacing between logical blocks within functions to improve code readability. When functions become complex with multiple logical sections, consider extracting nested logic into separate functions.nuxt/nuxt2 discussions
- Filter sensitive data server-sideAlways filter sensitive data at the API/server level before sending responses to the client. Never rely on client-side filtering or assume that data not displayed in the UI is secure. Any data sent to the client should be considered public and accessible to anyone with malicious intent.nuxt/nuxt2 discussions
- consistent code formattingMaintain consistent formatting standards across code and documentation to improve readability and maintainability. This includes proper ordering of logical conditions and consistent use of backticks for code values in comments.nuxt/nuxt2 discussions
- conditional component bundlingWhen adding conditional components to your application, ensure they are only bundled when actually needed to avoid unnecessary bundle bloat. This is especially important for optional features or components that depend on specific configurations.nuxt/nuxt2 discussions
- Use constructor.name contextAlways set logger context using `this.constructor.name` and configure it via the `setContext()` method rather than hardcoding context strings or passing context as parameters to individual log calls.novuhq/novu2 discussions
- Strategic error handlingImplement strategic error handling by properly checking exception types and using try/catch blocks to distinguish between user errors and system errors. Avoid runtime errors from improper type checking and categorize exceptions based on their source and required response.novuhq/novu2 discussions
- Pin dependency versionsAlways pin dependency versions by removing caret (^) and tilde (~) prefixes in package.json files to prevent build failures and ensure consistency across different environments and packages in a monorepo.novuhq/novu2 discussions
- Event listener managementImplement comprehensive event listener management by registering listeners on multiple relevant sources and providing appropriate fallback mechanisms. This ensures robust event handling across different environments and prevents missed events that could lead to inconsistent application state.novuhq/novu2 discussions
- consistent authentication patternsUse standardized authentication decorators consistently across all endpoints to ensure proper security coverage and follow the principle of least privilege. Always use @RequireAuthentication() as the primary way to protect endpoints, and explicitly use @SkipPermissionsCheck() for authenticated routes that don't require permission validation.novuhq/novu2 discussions
- comprehensive null checksWhen checking for null or undefined values in conditional statements, ensure all related nullable dependencies are validated together in the same condition. Partial null checks can lead to runtime errors when some dependencies are validated while others are not.novuhq/novu2 discussions
- avoid @Optional decoratorAvoid using the @Optional decorator in NestJS dependency injection as it disables runtime DI validation during bootstrap. This can cause missing provider dependencies to go undetected during compilation, leading to runtime failures without clear error messages.novuhq/novu2 discussions
- Validate network request parametersAlways validate and sanitize all network request parameters to prevent injection attacks. This includes: 1. **URL validation**: Consider restricting URLs to trusted origins only (e.g., localhost/loopback interfaces) to reduce the attack surface.nodejs/node2 discussions
- Secure resource loadingAlways validate and securely load external resources like libraries, configuration files, and modules to prevent tampering and hijacking attacks. When implementing security features that depend on system components:nodejs/node2 discussions
- Descriptive behavior-based testsTests should be named to describe the expected behavior or outcome being verified, not the input parameters or implementation details. This makes tests more meaningful as documentation and easier to understand when they fail.nodejs/node2 discussions
- Choose appropriate containersSelect data structures based on expected collection size and usage patterns. For small collections (typically fewer than 30 elements), consider using ordered containers like `std::map` instead of hash-based ones like `std::unordered_map`. With small collections, the theoretical O(log n) vs O(1) lookup time difference becomes negligible in practice, while...nodejs/node2 discussions
- Validate Next.js Configuration UsageWhen implementing Next.js in your application, ensure that you are correctly using the framework's documented configuration options and patterns. Configuration in Next.js is handled in specific ways, and improper usage can lead to runtime errors or unexpected behavior.vercel/next.js2 discussions
- Robust Error Handling in Next.js ComponentsWhen building Next.js components, it is crucial to implement robust error handling to ensure the stability and predictability of your application. Always explicitly check for error conditions before proceeding with normal execution flow.vercel/next.js2 discussions
- Proper panic chainsWhen implementing panic handlers, follow these critical practices to ensure robust error handling: register panic handlers early, chain new handlers with existing ones, and use appropriate error type downcasting methods.vercel/next.js2 discussions
- Non-blocking observability mechanismsWhen implementing observability mechanisms like telemetry or status monitoring, ensure they don't block or interfere with critical application operations. Use background processes for telemetry submissions and dedicated endpoints for status checks.vercel/next.js2 discussions
- Document configuration sourcesWhen providing configuration instructions, document the exact location and method to obtain required values. Include specific paths, URLs, or UI navigation steps needed to find configuration settings.vercel/next.js2 discussions
- Dependency conscious APIsDesign APIs with dependency implications in mind. Carefully consider how your API design choices might force dependencies on consumers, which can lead to dependency bloat or tight coupling between components.vercel/next.js2 discussions
- Complete error handling flowsImplement robust error handling patterns that ensure both proper resource cleanup and error context preservation.vercel/next.js2 discussions
- Complete data structuresWhen implementing data structures such as tries, trees, or graphs, ensure all critical operations (insertion, deletion, traversal) are fully implemented with proper cleanup logic. Incomplete implementations can lead to memory leaks, stale data, and incorrect application behavior.vercel/next.js2 discussions
- Choose optimal data structuresSelect data structures based on their performance characteristics and actual usage patterns. When implementing algorithms, consider usage patterns, understand API differences, and match data structures to access patterns.vercel/next.js2 discussions
- Validate parameter boundariesAlways validate that parameters contain expected types and values within safe boundaries, not just null/undefined checks. Optional parameters can receive unexpected types (like event objects), and numeric parameters need boundary validation to prevent invalid operations.ChatGPTNextWeb/NextChat2 discussions
- React hooks best practicesAlways call React hooks at the top level of components and custom hooks to comply with the Rules of Hooks. Handle conditional logic inside hook bodies rather than conditionally calling hooks. When optimizing performance, choose the appropriate hook: use `useMemo` for computed values and `useCallback` for function references.ChatGPTNextWeb/NextChat2 discussions
- Prevent security vulnerabilitiesProactively identify and prevent common security vulnerabilities in code, particularly around sensitive data handling and input validation. Avoid logging sensitive information like API keys, tokens, or passwords that could be exposed in log files. Implement robust input validation using proper parsing methods rather than simple string operations that can be...ChatGPTNextWeb/NextChat2 discussions
- Package manager consistencyMaintain consistent package manager usage throughout the project lifecycle. When a project uses yarn (indicated by yarn.lock), avoid committing npm's package-lock.json file, as having both lock files can cause dependency resolution conflicts and inconsistent builds across different environments.ChatGPTNextWeb/NextChat2 discussions
- Implement stable sortingWhen implementing sorting algorithms for collections, ensure stable and predictable ordering to avoid inconsistencies from operations like Object.values(). Use multi-level sorting criteria and consider sequence-based approaches for complex ordering requirements.ChatGPTNextWeb/NextChat2 discussions
- Consistent styling approachMaintain consistency in styling approaches within components and across the codebase. Avoid mixing className and inline styles in the same component - choose one approach and stick with it throughout the component. When working with reusable UI library components, keep them generic by using className for styling rather than adding component-specific inline...ChatGPTNextWeb/NextChat2 discussions
- Configuration backward compatibilityWhen modifying configuration schemas or adding new configuration options, always ensure backward compatibility with existing deployments. Long-running systems with many user deployments require smooth migration paths from old configurations to new ones.ChatGPTNextWeb/NextChat2 discussions
- Enable header validationAlways enable HTTP header validation to prevent request/response splitting vulnerabilities. These attacks can occur when untrusted data containing CRLF sequences is inserted into HTTP headers, allowing attackers to inject additional headers or even response body content.netty/netty2 discussions
- Check feature compatibilityWhen using kernel-specific networking features like io_uring, always implement runtime detection of feature support before enabling them. This ensures your code remains compatible across different kernel versions while taking advantage of newer optimizations when available.netty/netty2 discussions
- Test dependency managementTesting tools and libraries should be placed in `devDependencies` rather than regular dependencies in package.json. Regularly review testing dependencies to identify and remove outdated or redundant packages. For example, if a newer testing tool now includes functionality previously provided by a separate package (like 'nyc' now depending on...nestjs/nest2 discussions
- Manage testing dependenciesProperly manage testing-related dependencies by placing them in devDependencies and regularly auditing them to remove redundant tools. Test-only packages should never appear in regular dependencies, and outdated testing libraries should be removed when newer alternatives are already present in the project.nestjs/nest2 discussions
- Document CI/CD changesAlways document changes to CI/CD configurations and scripts, and ensure pull requests remain focused on their intended purpose. When modifying build scripts, dependencies, or deployment processes:nestjs/nest2 discussions
- optimize data structure operationsWhen working with data structures, prioritize efficiency through proper memory management and compact data representation. Use appropriate conversion patterns that handle memory cleanup correctly, and leverage bit manipulation techniques for space-efficient data storage.neovim/neovim2 discussions
- follow protocol standardsWhen implementing network protocols or communication formats, prioritize standardized specifications over legacy or device-specific formats, even when existing code uses older approaches. Legacy formats may work but can cause compatibility issues and confusion for applications that expect standard compliance.neovim/neovim2 discussions
- Document connection scopeWhen documenting network connection operations, clearly specify the scope of when operations are supported and their limitations. Include information about initial connection requirements, fallback behaviors, and unsupported scenarios to help users understand operational boundaries.neovim/neovim2 discussions
- defer expensive operationsAvoid performing expensive operations (like module loading, event emissions, or resource allocation) until they are actually needed. This pattern significantly improves startup time and runtime performance by reducing unnecessary work.neovim/neovim2 discussions
- avoid Lua ternary trapsAvoid using the `condition and expr1 or expr2` pattern when `expr1` can be `nil` or `false`, as this will always return `expr2` regardless of the condition result. This is a common source of subtle bugs in Lua code.neovim/neovim2 discussions
- API extensibility parametersAlways design API functions with extensible parameter structures to accommodate future feature expansion without breaking changes. Use `Dict opts` parameters instead of individual boolean or primitive parameters, unless you are absolutely certain no expansion will ever be needed (which is usually wrong).neovim/neovim2 discussions
- Reliable concurrency synchronizationWhen handling concurrent operations, prefer completion signals and proper thread management over arbitrary timeouts. This improves code reliability and prevents hangs or deadlocks.neondatabase/neon2 discussions
- Proper metrics designWhen designing metrics for observability systems like Prometheus, follow established best practices to ensure your metrics are useful, queryable, and maintainable:neondatabase/neon2 discussions
- Optimize what mattersFocus optimization efforts on performance-critical paths rather than applying micro-optimizations everywhere. Balance code clarity and maintainability against performance gains, and only optimize when there's a measurable benefit.neondatabase/neon2 discussions
- Modern shell syntaxPrefer double brackets (`[[ ]]`) over single brackets (`[ ]`) in shell scripts for improved functionality and consistency. While double brackets don't strictly require quotes around variables, maintaining consistent quoting practice is recommended even with double brackets:neondatabase/neon2 discussions
- Mind transaction boundariesBe conscious of implicit transaction boundaries when working with databases. Programming constructs can create unexpected transaction scopes that affect behavior and performance.neondatabase/neon2 discussions
- Limit concurrent access slotsDesign concurrency mechanisms based on actual usage patterns rather than theoretical maximum connections. When implementing locking or state tracking for concurrent operations, limit the number of concurrent slots to a reasonable value (e.g., 128) that reflects the expected concurrency level, rather than scaling to the maximum number of possible backends...neondatabase/neon2 discussions
- Handle network interrupts safelyNetwork code must properly handle interrupts and maintain consistent connection state at all potential interruption points. When implementing network operations:neondatabase/neon2 discussions
- Feature flag implementation clarityWhen implementing feature flags in the system, clearly document both the evaluation strategy and its performance implications. For HTTP evaluation vs. local evaluation, include expected request volumes and latency impacts. Always provide configuration examples that demonstrate proper usage.neondatabase/neon2 discussions
- Document parameter choicesAlways add explanatory comments for parameters or configuration options that aren't self-explanatory from their names or context. These comments should explain:neondatabase/neon2 discussions
- Document connection transitionsWhen implementing systems that involve network connection state changes (such as during failovers, restarts, or component promotions), explicitly document and implement connection handling strategy for all affected components. neondatabase/neon2 discussions
- Database replica promotion safeguardsWhen implementing database replica promotion logic, avoid temporary workarounds that bypass validation checks. Instead, design a comprehensive approach that maintains data integrity throughout the promotion process. Consider these best practices:neondatabase/neon2 discussions
- Balance flexibility with performanceWhen designing APIs, carefully balance flexibility against performance constraints. More flexible APIs often come with implementation complexity and potential performance costs. Start by understanding how clients actually use your API, then optimize for those common patterns while providing just enough flexibility for legitimate edge cases.neondatabase/neon2 discussions
- Use exact math semanticsWhen implementing performance-critical algorithms (e.g., pooling, math kernels, SIMD/ISA code), preserve the algorithm’s true numeric semantics and parameterization:Tencent/ncnn2 discussions
- Stable Benchmarking PracticesWhen collecting performance numbers, ensure both (1) benchmark parameters match the target hardware and (2) the execution environment is stable/isolated—otherwise results can be misleading.Tencent/ncnn2 discussions
- Preserve Backward CompatibilityWhen making schema/proto changes, never remove (or repurpose) legacy layer parameters that existing models/configs rely on. For backward compatibility migrations, keep the old message/field definitions, mark them deprecated if appropriate, and implement translation/mapping to the new schema rather than dropping support.Tencent/ncnn2 discussions
- Config Contract EnforcementWhen introducing or updating environment/configuration behavior, ensure the documented meaning, runtime inputs (CLI/feature flags), and build-time discovery (CMake/pkg paths) all point to the same intended target. Avoid “it compiles” success that doesn’t enable the feature, and avoid “it builds” that accidentally links against a mismatched dependency set.Tencent/ncnn2 discussions
- Build Script OrderingIn build/configuration files (e.g., CMakeLists), keep statements organized so that they are (1) scoped to the conditions that actually enable the associated sources/targets, and (2) ordered deterministically (e.g., alphabetical for registration lists).Tencent/ncnn2 discussions
- Cache keys drive rebuildsWhen using uv to build Python extensions via PEP 517 (e.g., maturin), ensure cache invalidation is keyed to the actual build inputs. Configure `tool.uv.cache-keys` so builds rerun only when the underlying sources for the compiled artifact change—especially Rust sources and Cargo manifests—rather than rebuilding whatever project owns the root...karpathy/nanochat2 discussions
- Sanitize user inputAlways sanitize and validate user-controlled input before using it in sensitive operations, and never hard-code credentials in source code. **For command execution:**n8n-io/n8n2 discussions
- Remove commented code immediatelyCommented-out code should be removed immediately rather than committed to the codebase. Keeping commented code creates confusion, adds unnecessary noise, and makes the codebase harder to maintain. If code is no longer needed, delete it - version control systems will preserve the history if it needs to be referenced later.n8n-io/n8n2 discussions
- Preserve icon font familiesWhen working with icon elements in CSS, maintain the specialized font families designed for icon rendering. Replacing icon fonts (like 'element-icons') with standard text fonts (like 'Inter') will break icon displays that depend on specific glyph mappings in the icon font.n8n-io/n8n2 discussions
- Optimize Vue watchersWhen implementing watchers in Vue applications, ensure they are configured appropriately for the data structures they observe. Two common pitfalls to avoid:n8n-io/n8n2 discussions
- Avoid hardcoded configurationsNever hardcode environment-specific values or feature states directly in your code. Instead, use environment variables, configuration files, or feature flag systems to manage these values dynamically.n8n-io/n8n2 discussions
- Use pytest parameterizationStructure unit tests using pytest's parameterize decorator instead of manual loops or wrapper functions. This approach improves test readability, makes failure cases easier to identify, and allows individual test cases to be run separately.apache/mxnet2 discussions
- Use named constantsIn AI model implementations, avoid using magic numbers directly in code as they reduce readability and make maintenance difficult. Always define constants with meaningful names, especially for values related to tensor dimensions, indices, and type identifiers.apache/mxnet2 discussions
- Pre-compute reused dataWhen data will be accessed multiple times during processing, avoid redundant calculations by pre-computing values upfront rather than using lazy evaluation. This pattern significantly improves performance in iterative operations like machine learning training, inference, or repeated data transformations.apache/mxnet2 discussions
- Consistent API documentationMaintain high-quality, consistent documentation as a critical component of API design. Documentation should feature: 1. Correct grammar and spelling, including proper punctuation and sentence structureapache/mxnet2 discussions
- avoid stale ref valuesWhen using React refs in hooks like useLayoutEffect or useEffect, pass the ref object itself rather than ref.current to avoid stale values. The ref.current value captured at hook definition time may be outdated when the effect callback executes.rocicorp/mono2 discussions
- avoid manual error handlingPrefer centralized error handling mechanisms and specialized utilities over manual error handling in individual components. Instead of implementing error handling logic directly in each function or component, leverage global error handlers and purpose-built utilities.rocicorp/mono2 discussions
- avoid global stateAvoid global state in concurrent environments where multiple instances, workers, or clients may share the same JavaScript context. Global variables and singletons can lead to unpredictable behavior when accessed concurrently.rocicorp/mono2 discussions
- API parameter designWhen designing API functions and types, prioritize maintainability and extensibility through proper parameter and type design patterns. For functions with multiple parameters, especially multiple boolean flags, consolidate them into a single options object to improve readability and future extensibility. This prevents parameter lists from becoming unwieldy...rocicorp/mono2 discussions
- surface failures earlyMake rendering/runtime failures observable instead of silently tolerated. Apply two concrete rules: 1) **Cover failure-prone inputs in tests**: when your code parses special syntaxes (e.g., `@{ ... }` blocks), add variations that stress spacing/quoting/formatting so broken input is exercised.mermaid-js/mermaid2 discussions
- Semantics-Preserving FormattingCode-style changes (formatting, spacing, selector tweaks, spell/lint adjustments) must not alter semantics or intended content. - CSS: scope styling to the minimal element needed (avoid global or overly broad selectors). Prefer targeted selectors like:mermaid-js/mermaid2 discussions
- Preserve API ContractsWhen an endpoint or syntax is already used as a contract (e.g., chart grammar shared across features, or a stateful editor URL), avoid creating parallel interfaces or polluting the contract with unrelated concerns.mermaid-js/mermaid2 discussions
- Document intent consistentlyWhen code changes affect how people understand or use behavior—especially grammar directives/annotations or feature support—add documentation that explains intent and keeps docs aligned with current functionality.mermaid-js/mermaid2 discussions
- Document API ChangesWhen you change an exported/non-trivial API (or add new function parameters), update JSDoc so it is complete and directly helpful: - For every added/changed parameter: include a `{type}` and a short description of what the parameter controls.mermaid-js/mermaid2 discussions
- Comprehensive Test CoverageWhen implementing or extending functionality, ensure tests (primarily unit tests for non-renderer code) cover the full supported behavior surface—not just a subset.mermaid-js/mermaid2 discussions
- Add screenshot coverageWhen adding a new rendering demo or introducing a new configuration/YAML option, always update the relevant Cypress integration/screenshot tests so the feature is exercised and captured automatically.mermaid-js/mermaid2 discussions
- Version pre-bump for releasesWhen your release workflow automatically bumps versions (e.g., increments the patch number), do not set the manifest version to the final release you want. Instead, set it to the documented pre-bump “magic” value so the workflow transforms it into the intended release.awslabs/mcp2 discussions
- Validated Observability GuidanceWhen updating observability docs, dashboards, or diagnostic query packs, ensure the guidance is both actionable and correct: 1) Add critical alerting/scale guidanceawslabs/mcp2 discussions
- Consistent Configuration WiringConfiguration must be internally consistent: what you declare in `pyproject.toml` and document (e.g., env vars) must match what the code actually does, and dependency/tooling choices must align with the project’s toolchain.awslabs/mcp2 discussions
- Write timeless documentationDocumentation should be written to remain clear and useful regardless of when it's read. Avoid references to temporary contexts like "in this PR," "original behavior," or "current implementation" that will lose meaning over time. Instead, precisely describe behaviors, changes, and functionality in a way that will remain clear to developers reading the code...mui/material-ui2 discussions
- Use screen queriesWhen writing component tests, prefer using global `screen` queries from Testing Library instead of container-specific queries or passing query functions as parameters. This approach keeps the test environment simple and consistent across the codebase.mui/material-ui2 discussions
- Use direct path importsFor optimal performance, use direct path imports instead of barrel imports when working with UI component libraries like Material UI. This practice improves both production bundle size through better tree-shaking and significantly enhances development server performance.mui/material-ui2 discussions
- Secure API endpointsAlways implement appropriate security measures for API endpoints that perform sensitive operations. This includes: 1. **Verify request authenticity**: Ensure requests come from legitimate sources using mechanisms like SDK verification, API keys, or signatures.mui/material-ui2 discussions
- Prefer direct property accessWhen property names are known at development time, use direct property access (e.g., `object.property`) over computed property access (e.g., `object[propertyName]`). This approach enhances code readability, enables better IDE autocompletion, improves type checking, and makes the code more maintainable.mui/material-ui2 discussions
- Parameterize build processesWhen designing build scripts for multi-package repositories, use parameterization to handle special cases rather than creating duplicate scripts with minor variations. This approach maintains consistency while accommodating package-specific needs. For example, instead of hardcoding different behaviors, add flags that can modify behavior:mui/material-ui2 discussions
- Parameter interaction designDesign APIs with clear parameter interactions and priority rules to create intuitive interfaces. When multiple parameters could affect the same behavior, establish and document a consistent priority order rather than making parameters conditionally required.mui/material-ui2 discussions
- Optimize CI/CD infrastructureContinuously optimize and maintain your CI/CD infrastructure to keep development velocity high while ensuring quality. Proactive maintenance prevents disruptions that can impact the entire team.mui/material-ui2 discussions
- Next.js integration patternsWhen integrating with Next.js, follow framework-specific patterns carefully and stay updated with API changes to ensure proper server-side rendering and optimal code.mui/material-ui2 discussions
- Isolate DOM security boundariesWhen developing UI components, establish clear DOM manipulation boundaries to prevent security risks. Components that modify aria attributes (like aria-hidden) on parent or ancestor elements can create security vulnerabilities by unexpectedly exposing content that was intentionally hidden from assistive technologies or hiding content that should be...mui/material-ui2 discussions
- Graceful component errorsUse descriptive error messages and appropriate error severity based on component maturity and usage patterns. For newer components, throwing errors is acceptable when constraints are violated. For established components, consider using development-mode warnings instead of throwing errors to avoid breaking existing implementations.mui/material-ui2 discussions
- Follow library recommendationsWhen writing tests, prioritize following the official recommendations and best practices of testing libraries (like Playwright) even if they appear more verbose than alternatives. Library recommendations typically address edge cases, improve reliability, and future-proof your tests.mui/material-ui2 discussions
- Document design decisionsWhen making architectural choices or modifying existing APIs, document your reasoning directly in the code or in type definitions. This helps other developers understand the "why" behind changes and prevents future regressions.mui/material-ui2 discussions
- Consistent package namingUse consistent and meaningful naming patterns for packages based on their purpose, visibility, and scope. This improves clarity in build scripts, dependencies, and during development.mui/material-ui2 discussions
- Use semantic null handlingWhen designing APIs and data structures, be intentional about null and undefined usage. Use null and undefined with distinct semantic meanings rather than interchangeably. For example, undefined can indicate "not yet loaded" while null indicates "does not exist". However, avoid nullable types when simpler alternatives serve the same purpose - if an empty...mastodon/mastodon2 discussions
- Safe proxy configurationWhen configuring proxy settings for network applications, always use proper compilation methods to prevent runtime errors and ensure consistent IP address handling across different connection types. Improper proxy configuration can cause server crashes when IP addresses are accessed, particularly when using string-based configurations with multiple values.mastodon/mastodon2 discussions
- Review configuration currencyRegularly audit and update configuration to align with current tool capabilities and best practices. Remove obsolete settings that are no longer needed due to tool evolution, and consolidate fragmented configuration approaches into more unified solutions.mastodon/mastodon2 discussions
- remove redundant codeIdentify and remove code elements that no longer serve a purpose, including unused imports, redundant function calls, and obsolete ESLint disable directives. This improves code readability and maintainability by eliminating unnecessary clutter.mastodon/mastodon2 discussions
- prefer findBy async queriesWhen testing components that require waiting for elements to appear, prefer using findBy* queries over waitFor + getBy* combinations. The findBy* queries have built-in waiting functionality that makes tests more readable and reliable.mastodon/mastodon2 discussions
- prefer established configuration patternsWhen making configuration choices, prioritize existing centralized configuration values and established patterns over ad-hoc solutions or deprecated frameworks. This reduces technical debt and maintains consistency across the codebase.mastodon/mastodon2 discussions
- Optimize React hooksAvoid unnecessary useCallback and useEffect dependencies to improve performance and code clarity. When event handlers are only used within a useEffect, define them locally inside the effect rather than using useCallback. This eliminates the need for the callback hook and reduces re-renders. Additionally, understand that refs don't need to be included in...mastodon/mastodon2 discussions
- Minimize HTML attack surfaceWhen allowing HTML attributes or rendering user-generated content, explicitly limit the attack surface by restricting allowed properties to a minimal, vetted set rather than permitting broad categories of attributes.mastodon/mastodon2 discussions
- markdown formatting consistencyEstablish and maintain consistent formatting standards for Markdown files to improve readability and maintainability. This includes adhering to line length limits and consistent styling choices within documents.mastodon/mastodon2 discussions
- leverage build tool automationModern build tools like Vite automatically handle many performance optimizations that previously required manual implementation. Trust these automated capabilities rather than duplicating effort with manual resource hints and preloading directives.mastodon/mastodon2 discussions
- Framework-aware text compositionWhen writing user-facing text (error messages, notifications, labels), understand how your framework automatically processes and modifies that text before it reaches users. Many frameworks like Rails automatically combine messages with attribute names or apply other transformations that can result in redundant or grammatically incorrect output.mastodon/mastodon2 discussions
- Environment variable descriptive namingEnvironment variables should use descriptive, specific names that clearly indicate their purpose and scope to avoid conflicts and improve maintainability. Generic names can lead to confusion when multiple features need similar configuration options.mastodon/mastodon2 discussions
- Documentation audience appropriatenessEnsure documentation content matches its intended audience and location. High-level documentation like README files should focus on essential information for the primary audience, while detailed technical information should be placed in developer-specific documentation. Avoid adding overly detailed or redundant information that may confuse or overwhelm...mastodon/mastodon2 discussions
- consistent route nestingMaintain consistent URL patterns and nesting structures across similar API endpoints to ensure predictable and intuitive interfaces. When designing routes for related resources, apply the same nesting strategy throughout the application rather than mixing top-level and nested approaches.mastodon/mastodon2 discussions
- consistent dependency versioningMaintain consistent version constraint patterns across all dependencies in configuration files and avoid unstable versions that can cause build issues. Use caret (^) constraints uniformly for predictable updates within compatible ranges, and employ resolutions when necessary to prevent automatic resolution to beta or unstable versions.mastodon/mastodon2 discussions
- Configuration value safetyEnsure configuration values are properly encoded and dependencies use specific versions to prevent runtime failures and security issues. When embedding dynamic values in YAML configuration files, use proper encoding methods like `.to_json` to handle special characters safely. For external dependencies in workflows and configuration, specify exact versions...mastodon/mastodon2 discussions
- comprehensive authorization checksAlways implement thorough authorization checks at the earliest appropriate point in request processing, rather than relying solely on downstream filtering. This includes verifying user permissions, access rights, and relationship constraints (such as blocking status) before granting access to resources.mastodon/mastodon2 discussions
- complete React ESLint setupWhen configuring ESLint for React projects, ensure you include comprehensive React-specific configurations beyond the basic setup. Include both the React import plugin configuration and JSX runtime configuration to get enhanced linting rules and automatic fixes.mastodon/mastodon2 discussions
- avoid redundant computationsIdentify and eliminate computations that are performed repeatedly when they could be executed once. This includes moving loop-invariant checks outside of loops and reducing callback overhead that creates unnecessary function declarations.mastodon/mastodon2 discussions
- avoid deprecated SASS syntaxAlways use modern SASS and CSS syntax instead of deprecated functions to ensure future compatibility and avoid build warnings. Replace deprecated division operators with calc() or math.div(), and use native CSS functions instead of deprecated SASS color functions.mastodon/mastodon2 discussions
- accessibility interaction securityEnsure that accessibility features do not create security vulnerabilities by allowing unintended interactions or providing misleading information to assistive technologies. This includes proper ARIA attribute usage and ensuring hidden or inactive elements are truly inaccessible.mastodon/mastodon2 discussions
- Validate configuration assumptionsBefore adding or modifying configuration settings, understand the underlying tool capabilities and test your assumptions. Many configuration issues arise from assumptions about what's needed without investigating whether the tool already provides the desired functionality or has specific constraints.microsoft/markitdown2 discussions
- validate before processingAlways validate input state and types before performing operations to prevent runtime errors and unexpected behavior. This includes checking data types before applying type-specific operations and preserving object state when performing validation checks.microsoft/markitdown2 discussions
- Handle async concurrency properlyWhen writing async endpoints, ensure that long-running CPU-bound operations don't block the event loop and that concurrent requests don't conflict over shared resources. CPU-bound operations should be offloaded to thread pools using asyncio.run_in_executor() or similar mechanisms. Additionally, avoid using predictable file paths or shared resources that can...microsoft/markitdown2 discussions
- Follow configuration best practicesAlways adhere to official guidelines and proper validation when setting up configurations, whether for dependencies, file formats, or environment setup. This prevents subtle issues that can cause tests to pass incorrectly or create environment conflicts.microsoft/markitdown2 discussions
- Variable evaluation contextBe mindful of when and where environment variables and configuration values are evaluated in shell scripts, especially when working across different execution contexts (like host vs. container environments). Improper quoting can cause variables to be evaluated in the wrong context, leading to unexpected behavior.maplibre/maplibre-native2 discussions
- Use specific test assertionsAlways use the most specific test assertion method available for your test case rather than generic assertions. Specific assertions provide better error messages and make test failures easier to debug.maplibre/maplibre-native2 discussions
- Style-compliant example codeExample code in documentation and tutorials should adhere to project style guidelines and demonstrate best practices. Avoid using internal classes or implementation details that are inaccessible to users. Instead, use public APIs and concrete resources that developers can directly copy into their applications.maplibre/maplibre-native2 discussions
- Standard configuration filesUse standardized, tool-specific configuration files instead of embedding configurations in CI scripts or other build files. This improves discoverability, ensures consistency between local development and CI environments, and provides self-documentation for required settings.maplibre/maplibre-native2 discussions
- Optimize compilation flagsWhen optimizing application performance, carefully select compiler flags based on your optimization goals. For size-critical applications or accurate size measurements, use `-Oz` to prevent aggressive inlining that can distort metrics. Additionally, implement compiler caching with tools like `ccache` to significantly improve build times in development and...maplibre/maplibre-native2 discussions
- Numerical precision considerationsWhen implementing algorithms involving floating-point calculations, choose epsilon values based on the specific domain requirements rather than defaulting to system-defined constants. Standard values like `std::numeric_limits<double>::epsilon()` are often too small for practical geometric or graphical applications.maplibre/maplibre-native2 discussions
- Lock responsibly, alwaysEnsure proper management of locks and concurrent resources throughout their lifecycle. When implementing concurrency: 1. Encapsulate locking/unlocking in appropriate methods rather than duplicating codemaplibre/maplibre-native2 discussions
- Document containerized buildsWhen using Docker for build environments, provide complete, tested instructions that users can copy-paste without modification. Include proper user permission handling to prevent file ownership issues, and ensure commands work as documented.maplibre/maplibre-native2 discussions
- Cross-platform test managementWhen working with tests that run across multiple platforms (iOS, Android, etc.), ensure proper configuration and handling of platform-specific issues:maplibre/maplibre-native2 discussions
- Configuration over hardcodingWhen designing APIs, prefer exposing behavior through configuration options rather than hardcoding logic, especially for aspects that might vary across implementations or require customization. This creates more flexible APIs that can adapt to changing requirements without code modifications.maplibre/maplibre-native2 discussions
- Conditional observability instrumentationWrap all tracing, profiling, and debugging instrumentation in appropriate conditional compilation blocks (like `MLN_TRACY_ENABLE`) to prevent performance overhead in production builds. When adding trace points:maplibre/maplibre-native2 discussions
- Accurate documentation referencesEnsure all code documentation includes appropriate reference links that are current and accurate. When porting code or migrating between frameworks, preserve all documentation comments with their external references. For API documentation, verify that links point to the correct and up-to-date specification documentation.maplibre/maplibre-native2 discussions
- Strategic dependency versioningUse strategic versioning approaches for dependencies based on their impact and maintenance status. Pin exact versions for dependencies that inject global styles, configurations, or behaviors to prevent unintended breaking changes during automatic updates. For unmaintained dependencies, evaluate alternatives or consider forking if there are useful pending...logseq/logseq2 discussions
- Simplify naming conventionsPrioritize simple, enforceable naming conventions over complex guidelines that are difficult to follow consistently. When establishing naming standards, focus on what serves a clear purpose and can be realistically maintained by the team.logseq/logseq2 discussions
- Respect existing formattingWhen modifying existing files, maintain the formatting and style conventions already established in those files rather than imposing new formatting standards. This includes respecting existing whitespace patterns, indentation styles, and structural formatting choices.logseq/logseq2 discussions
- Prevent command injection vulnerabilitiesWhen implementing shell command execution or CLI features, prioritize security by avoiding direct shell execution and implementing robust input validation. Simple allow/deny lists for dangerous commands may not provide sufficient protection against command injection attacks.logseq/logseq2 discussions
- Extract reusable hooksWhen you identify React logic that handles complex state management or event handling patterns that could be reused across multiple components, extract it into a custom hook. This promotes code reusability, reduces duplication, and makes components more focused on their primary responsibilities.logseq/logseq2 discussions
- CSS comment standardsAlways use proper CSS comment syntax (`/* */`) instead of inline comments (`//`) for better cross-browser compatibility and code consistency. Additionally, rely on autoprefixer configuration for vendor prefixes rather than manually adding them, which reduces code duplication and maintenance overhead.logseq/logseq2 discussions
- Check undefined before useAlways verify that values are not undefined before accessing or using them, whether they are object properties or function parameters. This prevents TypeScript compilation errors and potential runtime issues.logseq/logseq2 discussions
- Verify configuration documentationEnsure that all configuration documentation accurately reflects the actual implementation, especially for build tools, tech stack, and architectural decisions. When documenting configurations that deviate from standard practices, provide clear rationale for the choices made.lobehub/lobe-chat2 discussions
- Use semantic namingChoose names that reflect purpose and meaning rather than visual appearance, position, or implementation details. This improves code clarity, supports internationalization, and makes the codebase more maintainable.lobehub/lobe-chat2 discussions
- Respect browser behaviorAlways consider and respect browser native behaviors when implementing web application features. Avoid conflicts with built-in browser shortcuts and choose appropriate client vs server-side approaches based on the execution environment.lobehub/lobe-chat2 discussions
- Provide contextual guidanceDocumentation should provide clear contextual information that helps users understand when they need to take specific actions versus when configurations are automatically handled. Include deployment-specific details and maintain consistent cross-referencing syntax throughout.lobehub/lobe-chat2 discussions
- Pin Docker base versionsAlways specify exact version numbers for Docker base images instead of using floating tags like `lts` or `latest`. Floating tags can introduce unexpected breaking changes when they automatically update to newer versions, potentially causing build failures or runtime issues in production environments.lobehub/lobe-chat2 discussions
- Next.js auth configurationFollow auth.js standardized environment variable naming conventions and use explicit function declarations for OAuth providers. Use the `AUTH_[PROVIDER_ID]_ID` format for environment variables as auth.js automatically reads these. Avoid deprecated naming patterns that will be removed in future versions. Explicitly declare scope and profile handling...lobehub/lobe-chat2 discussions
- Explicit type checkingUse explicit type checks instead of just undefined checks to prevent null values from being passed to functions or APIs that don't expect them. Checking only for undefined can still allow null values to pass through, which may cause runtime errors.lobehub/lobe-chat2 discussions
- Environment-specific configuration handlingWhen writing configuration scripts, ensure they handle environment-specific differences properly by using predefined path variables and adapting commands for different operating systems. Use consistent variable naming for paths that may vary between environments, and implement OS detection when commands have different syntax across platforms.lobehub/lobe-chat2 discussions
- Contextual error handlingImplement error handling that is both architecturally localized and contextually specific to provide better user experience and system resilience. Use localized error boundaries to prevent cascading failures while ensuring error messages are specific to the actual problem and provide actionable guidance.lobehub/lobe-chat2 discussions
- Choose hooks wiselyUse React hooks only when you need reactivity and component re-rendering. For accessing instantaneous values or one-time data retrieval, prefer plain functions to avoid unnecessary re-renders and improve performance.lobehub/lobe-chat2 discussions
- Account for model variationsWhen implementing features that interact with AI models, consider the behavioral differences between various models and adjust parameters accordingly. Different AI models have distinct characteristics such as output speed, token generation patterns, and response formats that can significantly impact user experience.lobehub/lobe-chat2 discussions
- Simplify configuration interfacesDesign configuration interfaces that prioritize user experience by providing sensible defaults, using clear naming conventions, and logically grouping related options. Complex tools with many configuration parameters should minimize the cognitive load on users through thoughtful interface design.LMCache/LMCache2 discussions
- Remove redundant AI commandsEliminate duplicate or redundant commands when setting up AI infrastructure, model serving, or ML library installations. Redundant commands create confusion, increase maintenance overhead, and can lead to unexpected behavior in AI workflows.LMCache/LMCache2 discussions
- network service identificationUse descriptive string identifiers instead of numeric ports or generic IDs when designing network services to avoid conflicts and improve maintainability. Different network services should have clearly distinguishable communication channels.LMCache/LMCache2 discussions
- Check before using valuesAlways validate that values are not null, undefined, or empty before using them in operations that depend on their content. This prevents downstream errors and unexpected behavior when collections are empty or strings are null.LMCache/LMCache2 discussions
- Avoid hardcoded configuration valuesConfiguration files and scripts should use placeholders, environment variables, or parameterized values instead of hardcoding specific configuration values. Hardcoded values make configurations inflexible and difficult to adapt across different environments or deployments.LMCache/LMCache2 discussions
- Write accessible documentationDocumentation should be written with clarity and completeness to serve readers who may not have deep domain expertise. Use precise, unambiguous language that avoids technical jargon when simpler alternatives exist, and provide necessary context about origins, rationale, and background information.llvm/llvm-project2 discussions
- structure contextual log messagesLog messages should include sufficient contextual information and structured formatting to enable effective debugging and filtering. This means including relevant metadata, level information, and clear prefixes that help developers understand the source and severity of logged events.llvm/llvm-project2 discussions
- specify network protocol endiannessAlways explicitly specify byte order (endianness) in network protocol documentation and implementations. Even when a specification mandates a particular endianness, make it clear in your documentation to avoid confusion and implementation errors.llvm/llvm-project2 discussions
- protect shared dataAlways protect shared data that can be accessed by multiple threads using appropriate synchronization mechanisms. Identify potential race conditions where shared state could be modified concurrently and choose the right protection mechanism.llvm/llvm-project2 discussions
- preserve known test issuesWhen tests exhibit known false positives or false negatives, preserve these test cases with clear documentation rather than removing them. This practice prevents accidental "fixes" that mask underlying problems and helps track when issues are genuinely resolved.llvm/llvm-project2 discussions
- Match function names to behaviorFunction names and their documentation must accurately reflect what the function actually does. When a function handles more data than its name suggests, either rename the function or split the functionality.llvm/llvm-project2 discussions
- match API complexity appropriatelyDesign APIs with complexity that matches their actual use cases and adopt established patterns that improve clarity. Avoid over-engineering interfaces when simpler alternatives suffice, and prefer modern, well-established patterns over legacy approaches.llvm/llvm-project2 discussions
- improve code readabilityWhen code expressions become complex or difficult to understand at first glance, refactor them for better readability. This can be achieved through several techniques: extracting complex expressions into well-named variables, using named regex groups instead of numeric indices, or reformatting conditional logic into more concise forms.llvm/llvm-project2 discussions
- explicit invalid value handlingWhen designing enums or working with type casting, explicitly define and handle invalid states rather than relying on undefined behavior. Use designated invalid values that stand out clearly, and employ equality assertions for type compatibility checks.llvm/llvm-project2 discussions
- Explicit configuration requirementsAlways specify explicit configuration parameters rather than relying on default settings that may vary across different build environments or target platforms. This is particularly critical in test files where assumptions about default compiler settings, target triples, or language standards can cause failures in cross-compilation scenarios or different...llvm/llvm-project2 discussions
- Ensure comprehensive documentationDocumentation should be complete, properly formatted, and clearly explain purpose with adequate examples. When writing documentation, ensure that: 1. **Code examples are properly formatted** - Match indentation requirements and follow established formatting conventionsllvm/llvm-project2 discussions
- consistent error diagnosticsWhen implementing attributes, language features, or compiler diagnostics, always provide explicit error diagnostics rather than default warnings for misuse scenarios. Error messages should be clear, specific about the violation, and consistent with existing diagnostic patterns in the codebase.llvm/llvm-project2 discussions
- Choose appropriate string typesSelect the most efficient string type based on ownership and lifetime requirements to optimize memory usage and prevent safety issues. Use `StringRef` for parameters and when you don't need to own the string data, `std::string` when you need ownership and persistence, and avoid storing `Twine` objects as member variables.llvm/llvm-project2 discussions
- Use strongly typed configurationsPrefer strongly typed configuration values over primitive types to improve code safety and clarity. Use enum classes instead of raw strings for categorical options, and proper boolean types instead of integer flags for binary settings.ggml-org/llama.cpp2 discussions
- Use precise documentation detailsDocumentation should provide specific, actionable information rather than vague or generic references. This applies to both technical specifications and descriptive text.ggml-org/llama.cpp2 discussions
- Use environment variablesPrefer environment variables over hardcoded paths and configuration values in build scripts and configuration files. This approach improves portability, flexibility, and maintainability by allowing different environments to specify their own paths without modifying the codebase.ggml-org/llama.cpp2 discussions
- Specify naming formats explicitlyWhen defining naming conventions in documentation, specifications, or APIs, explicitly specify the exact format and patterns to be used. Avoid ambiguous descriptions that could lead to inconsistent implementations.ggml-org/llama.cpp2 discussions
- semantic configuration validationWhen designing configuration systems, prefer semantic parameters over generic key-value approaches for common features, and implement runtime validation to detect incompatible configuration combinations.ggml-org/llama.cpp2 discussions
- prefer const variablesAdd the `const` qualifier to variables that are not modified after initialization. This improves code clarity, prevents accidental modifications, and makes the code's intent more explicit to both compilers and other developers.ggml-org/llama.cpp2 discussions
- optimize code placementEnsure code is placed in its most logical and efficient location to improve maintainability and performance. This includes consolidating duplicate functionality into shared headers or utility files, and moving loop-invariant conditions outside of loops.ggml-org/llama.cpp2 discussions
- Metal shared memory sizingWhen allocating shared memory for Metal compute shaders, ensure proper sizing that accounts for both SIMD group requirements and Metal platform constraints. Metal requires shared memory buffer sizes to be multiples of 16 bytes. Consider using simplified allocation strategies that meet platform requirements while maintaining correctness.ggml-org/llama.cpp2 discussions
- implement or fail explicitlyAlgorithmic functions should either correctly implement their intended behavior or explicitly fail with an error, rather than silently returning potentially incorrect or unchanged results. This prevents subtle bugs where callers assume the algorithm was applied when it wasn't.ggml-org/llama.cpp2 discussions
- explicit performance handlingWhen writing performance benchmarking and measurement code, always be explicit about all possible cases and organize related constants clearly. Avoid catch-all else clauses that could mask bugs or unexpected values in performance-critical code paths.ggml-org/llama.cpp2 discussions
- Enable callback chainingWhen designing APIs that accept callbacks or configuration functions, always return the previous callback/configuration to enable chaining and composition. This allows multiple components to layer their functionality without losing existing behavior.ggml-org/llama.cpp2 discussions
- consistent clear namingEnsure variable and identifier names are both consistent and unambiguous within their context. When multiple equivalent naming options exist (such as `tile_B::I` vs `tile_C::J` for the same value), choose one approach and apply it consistently throughout the codebase. Additionally, select names that clearly distinguish their purpose and avoid confusion with...ggml-org/llama.cpp2 discussions
- Prioritize naming clarityChoose names that are immediately self-explanatory and unambiguous, even if they are more verbose. Names should convey their full meaning and context without requiring additional documentation or guesswork.BerriAI/litellm2 discussions
- Incremental dependency updatesWhen updating dependencies in configuration files like requirements.txt, break large changes into smaller, focused pull requests that can be individually tested and validated. Each dependency update should include clear justification for why the change is necessary, especially when it triggers cascading updates to other packages.BerriAI/litellm2 discussions
- Follow documentation standardsEnsure all documentation follows established patterns and standards for components, formatting, and code examples. This includes using proper imports for documentation components (like Image imports instead of markdown syntax) and maintaining consistent formatting for code samples with standardized attributes.BerriAI/litellm2 discussions
- Document configuration purpose clearlyWhen documenting configuration features, always provide clear explanations of their purpose, use cases, and how they map to underlying parameters. Users should understand not just how to use a configuration option, but why they would want to use it and what problem it solves.BerriAI/litellm2 discussions
- configurable security settingsSecurity configurations should be made configurable through environment variables or runtime settings rather than hardcoded in the application logic. This allows teams to adapt security measures to different deployment environments and regulatory requirements without code changes.BerriAI/litellm2 discussions
- Use semantic identifiersChoose semantically appropriate identifiers and types that clearly represent their purpose. This includes using the correct data type (e.g., boolean for flags instead of integers) and ensuring proper spelling of all identifiers.torvalds/linux2 discussions
- Prefer early returnsWhen a function can determine an early result based on input validation or special cases, return immediately rather than assigning to a temporary variable and having a single exit point. Early returns reduce nesting, improve readability, and often result in more efficient code by making guard conditions more visible.torvalds/linux2 discussions
- Type-safe focused testsWrite tests that are both type-safe and narrowly focused on supported behavior. Use small, typed test helpers or fixtures to eliminate repeated casts and noisy "as any"/"as T" in tests, and ensure test cases reflect the product's validation rules (don’t test unsupported scenarios).likec4/likec42 discussions
- Respect provider contextEnsure library-provided integration points are used so styles and portals behave correctly in host environments (e.g., shadow roots, webcomponents). Motivationlikec4/likec42 discussions
- Guard nullable valuesAlways check for null/undefined before accessing values or rendering UI instead of relying on non‑null assertions or unconditional usage. Prefer optional chaining and explicit guards in logic and conditional rendering in JSX.likec4/likec42 discussions
- Gate UI featuresEnsure UI elements (buttons, icons, tooltips, overlays) are only registered or rendered when the corresponding configuration or feature flag is enabled. Also ensure feature flags are passed into components or a central store so components make rendering decisions from configuration rather than hard-coded assumptions.likec4/likec42 discussions
- Use Atomic OwnershipWhen coordinating concurrent work (threads or processes), make “ownership” explicit and authoritative, and ensure every consumer uses the same claimed/produced result.mvanhorn/last30days-skill2 discussions
- Secure Actions InputsIn GitHub Actions, treat workflow inputs/expressions as potentially unsafe and follow two rules: (1) avoid interpolating `${{ ... }}` directly inside shell-script logic, and (2) do not persist Git credentials from `checkout`; instead, scope tokens to only the step that needs to push.mvanhorn/last30days-skill2 discussions
- Deterministic Release GatingWhen automating CI/CD releases, make “release vs non-release” and downstream publishing deterministic by (1) gating on explicit signals and (2) explicitly triggering the next workflow step.mvanhorn/last30days-skill2 discussions
- Deterministic Config HandlingTreat configuration inputs as a deterministic contract: normalize/parsing should be robust and centralized, and config-file reading must use an explicit encoding matching the write path.mvanhorn/last30days-skill2 discussions
- Cache Scope And IdentityEnsure caching is both lifecycle-correct and identity-safe. - Lifecycle: Cache invalidation/reset must match the intended scope (e.g., “run” not “process”). If long-lived workers exist, reset at deterministic pipeline boundaries (e.g., external pipeline entry) and not in internal sub-runs.mvanhorn/last30days-skill2 discussions
- Proper configuration placementPlace configuration files and settings at the appropriate level in your repository structure. In monorepos, some configurations must be at the root level while others belong at the package level.langfuse/langfuse2 discussions
- Materialize database indexesAlways materialize database indexes after creation to ensure they are fully built and immediately available for queries. This is especially important in migration scripts where database performance shouldn't be compromised during or after the migration process. Without materialization, indexes may not be immediately usable, causing potential performance...langfuse/langfuse2 discussions
- Consistent descriptive namingUse naming conventions that are both consistent with existing patterns and descriptively clear about purpose. Follow established patterns in the codebase for similar entities while ensuring names are specific and self-explanatory.langfuse/langfuse2 discussions
- Capitalize acronyms consistentlyUse standard capitalization for acronyms in all identifiers, method names, variables, and other code elements. Common acronyms like 'API', 'URL', 'JSON', 'HTML', and 'XML' should be written in all uppercase letters.langfuse/langfuse2 discussions
- Validate migration conflictsBefore applying database migrations, systematically validate existing data and check for potential conflicts with current schema constraints. This prevents migration failures and ensures backward compatibility.langflow-ai/langflow2 discussions
- validate API inputs comprehensivelyEnsure thorough validation of API inputs and outputs using robust validation techniques rather than simple string checks or partial validation. Use proper libraries for validation (like urllib.parse for URLs) and validate all required components, not just a subset.langflow-ai/langflow2 discussions
- Standardize naming patterns consistentlyEstablish and follow consistent naming conventions for similar types of elements throughout the codebase and documentation. When multiple instances of the same type of element exist, ensure they follow the same naming pattern to avoid confusion and improve maintainability.langflow-ai/langflow2 discussions
- sanitize trace metadataAlways sanitize trace metadata and attributes before sending to observability platforms to ensure compatibility with OpenTelemetry attribute type restrictions. Complex objects, custom types, and non-primitive values should be converted to supported types (str, int, float, bool, None) or JSON strings to prevent warnings and ensure reliable trace data.langflow-ai/langflow2 discussions
- precise workflow conditionsWhen implementing conditional logic in CI workflows, ensure boolean expressions are precise and comprehensive to avoid unintended workflow execution or bypassing. Use multiple filter conditions combined with logical operators to create accurate triggers based on file changes.langflow-ai/langflow2 discussions
- Implement concurrent safety patternsWhen designing concurrent systems, implement comprehensive safety patterns that handle resource lifecycle management, race conditions, and proper cleanup mechanisms. This includes setting resource limits to prevent exhaustion, implementing timeout-based cleanup for idle resources, and handling database race conditions with proper rollback and retry logic.langflow-ai/langflow2 discussions
- Ensure comprehensive test coverageAlways add test coverage for new functionality, especially when introducing integrations or services. Use mocks and patches when testing external dependencies. Additionally, configure coverage reporting to exclude irrelevant paths like legacy components, deactivated features, and test files themselves to maintain meaningful coverage metrics.langflow-ai/langflow2 discussions
- Document log level optionsWhen documenting logging configuration parameters, always provide the complete list of available log level options and use consistent naming conventions. This ensures developers understand all available choices and prevents confusion from incomplete documentation.langflow-ai/langflow2 discussions
- Document implementation reasoningAdd comments that explain WHY implementation decisions were made, not just WHAT the code does. This is especially important for backwards compatibility hacks, workarounds, non-obvious logic checks, and temporary solutions.langflow-ai/langflow2 discussions
- Database session lifecycleEnsure all database operations and access to database objects occur within the appropriate session scope. Database objects become invalid once their session is closed, leading to runtime errors when accessed later.langflow-ai/langflow2 discussions
- Comprehensive coverage collectionConfigure Jest to collect coverage data from all source files, not just those with existing tests, while avoiding test failures due to coverage thresholds. Coverage enforcement should be handled by external reporting tools rather than the test runner itself.langflow-ai/langflow2 discussions
- avoid internal object accessAvoid accessing internal object attributes like `__dict__` or using unpacking syntax when cleaner alternatives exist. Instead, prefer stable public methods or direct assignment patterns that don't couple to object internals.langflow-ai/langflow2 discussions
- Update documentation configurationWhen adding new files or components to the project, ensure that documentation configuration is updated accordingly. This includes adding new files to TypeDoc options in tsconfig.json to maintain complete API documentation coverage. Additionally, clearly mark deprecated components and direct developers to use the recommended alternatives instead of extending...langchain-ai/langchainjs2 discussions
- Simplify code organizationMaintain clean code organization by eliminating unnecessary abstractions and preventing codebase fragmentation. This applies both at the component level and module level:langchain-ai/langchainjs2 discussions
- Platform-appropriate environment variablesAlways use the correct syntax for accessing environment variables based on the target platform. In JavaScript/Node.js environments, use `process.env.VARIABLE_NAME` instead of syntaxes from other languages (e.g., Python's `os.environ`).langchain-ai/langchainjs2 discussions
- Match configuration documentationConfiguration documentation must accurately reflect implementation details and behavior. Ensure that: 1. Code examples in documentation use the exact same property names and structure as the actual implementationlangchain-ai/langchainjs2 discussions
- Follow standard namingUse established naming patterns and correct capitalization throughout the codebase and documentation. For test fixtures and recordings, follow common conventions like `__snapshots__` instead of custom directory names:langchain-ai/langchainjs2 discussions
- Notebook dependency installWhen authoring AI/LLM tutorials in Jupyter notebooks, ensure dependency installation is done with correct notebook syntax and that nearby explanatory text is unambiguous.langchain-ai/langchain2 discussions
- Explicit Unset SemanticsFor any API field that is optional or whose zero-value may be ambiguous, make “unset/absent” semantics explicit and implement them consistently. Apply this standard:kUbernetes/kUbernetes2 discussions
- Deterministic Security Profile SemanticsWhen defining security-policy APIs (e.g., seccomp/AppArmor profiles), make the effective policy computation and schema evolution unambiguous and compatibility-safe.kUbernetes/kUbernetes2 discussions
- Config Default SemanticsWhen defining configuration API fields (including proto/API surface), make defaults and special values deterministic, consistent, and compatible with existing behavior.kUbernetes/kUbernetes2 discussions
- Collision-Safe NamingUse standardized, collision-resistant naming for public identifiers—especially versioned module paths and generated-code symbols. Apply this in two common cases:kUbernetes/kUbernetes2 discussions
- Benchmark performance changesAlways measure and validate performance impact through benchmarking before making changes that could affect system performance, even when changes appear to be obvious optimizations. Removing seemingly redundant configurations or adding new features can have unexpected performance consequences that only surface during integration testing or production use.kubernetes/kubernetes2 discussions
- Validate model optimizationWhen implementing AI model optimization techniques such as early stopping algorithms or hyperparameter tuning, include proper validation mechanisms to help users effectively reduce model overfitting and improve accuracy. kubeflow/kubeflow2 discussions
- Validate inputs explicitlyAlways validate input parameters and respond with appropriate HTTP status codes when invalid values are detected, even when inputs appear controlled by your frontend. Backend validation should explicitly check for invalid or unexpected values (like "NaN" or values outside an allowed set) and raise appropriate exceptions with clear error messages.kubeflow/kubeflow2 discussions
- Use enums for stateWhen handling nullable or undefined states, use enumerations instead of primitive types like boolean or null/undefined. Enums provide more descriptive and type-safe representations of different states, including the absence of a value or an unknown state.kubeflow/kubeflow2 discussions
- Use CSS classes properlyAvoid inline styles and `!important` declarations in your HTML templates. Instead, define and use CSS classes that encapsulate styling needs. This improves code maintainability, readability, and reduces CSS specificity issues.kubeflow/kubeflow2 discussions
- Unique workflow step namesWhen defining CI/CD workflows, always ensure task/step names are unique to prevent execution failures. Workflow engines like Argo will reject pipelines with duplicate step names, which becomes particularly important when:kubeflow/kubeflow2 discussions
- Type-appropriate default valuesInitialize variables with type-appropriate default values to prevent type errors and null reference exceptions during operations. When a variable is expected to hold a collection type (list, dictionary, set), use the corresponding empty collection (`[]`, `{}`, `set()`) rather than other falsy values like `None` or empty strings.kubeflow/kubeflow2 discussions
- Structure for navigationDocumentation should be structured to optimize user navigation and information discovery. When organizing documentation elements: 1. Group related information into logical categories to help users find relevant content fasterkubeflow/kubeflow2 discussions
- Standardize style scriptsMaintain consistent code style enforcement scripts across all projects by standardizing linting and formatting configurations in package.json. Use modern, supported tools instead of deprecated ones (like tslint).kubeflow/kubeflow2 discussions
- Standardize metrics collectionUse the appropriate metric types for the data being collected and consider centralizing monitoring code to ensure consistency across components. For accumulating values like request counts, use counters rather than gauges:kubeflow/kubeflow2 discussions
- Stable configuration managementAlways ensure configuration values are managed consistently and sourced from stable locations. 1. Use defined constants instead of string literals for configuration values to improve maintainability and reduce errors when values changekubeflow/kubeflow2 discussions
- Safe URL operationsWhen handling URLs for API interactions and navigation, use precise methods for both comparison and construction to avoid subtle bugs: 1. For URL path comparison, use `startsWith()` instead of `includes()` to prevent false positives from substring matches:kubeflow/kubeflow2 discussions
- Reduce nesting depthImprove code readability by reducing nesting depth with early returns and functional approaches. Use early returns to handle edge cases first, and prefer functional operators over nested conditionals when working with streams or collections.kubeflow/kubeflow2 discussions
- Private variable naming conventionUse the 'prv' prefix for private class members and ensure they're explicitly declared with the 'private' access modifier. This maintains consistency with established team conventions and improves code readability by clearly indicating variable scope.kubeflow/kubeflow2 discussions
- Prefer external configurationDesign applications to use external configuration sources rather than hardcoding values directly in source code. This allows for configuration changes without requiring code modifications or redeployment.kubeflow/kubeflow2 discussions
- Optimize container build configurationsConfigure containerized application builds to be efficient and flexible by avoiding hardcoded architecture decisions and using appropriate compiler flags. Let the build system determine architecture targeting instead of maintaining architecture-specific code blocks in your Dockerfiles. For Go applications, use appropriate build flags like `CGO_ENABLED=0` to...kubeflow/kubeflow2 discussions
- Match algorithms to purposeSelect algorithmic constructs and control structures that are appropriate for the specific task. Common issues include: 1. Using loops when conditional checks are sufficientkubeflow/kubeflow2 discussions
- Isolate test casesCreate separate test functions for distinct functionality to improve test clarity and make failure points more obvious. When writing tests, avoid combining multiple scenarios into a single test function.kubeflow/kubeflow2 discussions
- Enforce least privilegeConfigure all systems with the minimum permissions required to function. For Kubernetes deployments, use security contexts that prevent privilege escalation and running as root:kubeflow/kubeflow2 discussions
- Document networking annotationsWhen using Istio or other networking-related annotations in configuration files, always include detailed comments explaining their purpose, behavior, and effects. This makes networking constraints and logic transparent to developers and users who need to understand the system's behavior.kubeflow/kubeflow2 discussions
- Document migration pathsWhen implementing version changes or migrations, provide comprehensive documentation and tools to support users through the transition process. This includes:kubeflow/kubeflow2 discussions
- Descriptive consistent namingUse descriptive and consistent names throughout the codebase. Prefer full, meaningful names over acronyms or abbreviations to improve readability and understanding, especially for newcomers. Maintain naming consistency across different files, configurations, and references to the same entity.kubeflow/kubeflow2 discussions
- Consistent separator conventionsUse appropriate separators in compound identifiers to improve readability and ensure naming consistency across the codebase. Specifically: 1. Use hyphens to separate words in multi-word paths, repository names, and other resources:kubeflow/kubeflow2 discussions
- Consistent descriptive namingMaintain consistency in naming patterns across related resources while ensuring names accurately reflect their purpose. When naming components, files, or configurations:kubeflow/kubeflow2 discussions
- Component-agnostic styling principlesCreate reusable components with styles that don't make assumptions about parent contexts or affect their positioning in different applications. Keep positioning styles (like margins) in the parent components that use them rather than in the reusable component itself. Prefer properties that don't assume parent styling context.kubeflow/kubeflow2 discussions
- Centralize dependency configurationsWhen adding or updating package dependencies, place them in centralized configuration files rather than duplicating them across multiple services. Keep dependencies up-to-date with the latest stable versions and replace deprecated packages with their recommended successors. Always verify backward compatibility when upgrading dependency versions.kubeflow/kubeflow2 discussions
- Automate style enforcementConfigure your development environment to automatically enforce code style standards rather than relying on manual checks during code review. This includes:kubeflow/kubeflow2 discussions
- API structure balanceMaintain a clear separation between resource-specific API handlers and common utilities. Resource-specific handlers should remain in their dedicated modules to reduce dependencies, while common functionality should be extracted into shared helpers for consistency.kubeflow/kubeflow2 discussions
- Use modern test infrastructureAlways add new tests to the current recommended test infrastructure rather than legacy systems that are being phased out. This reduces technical debt and ensures tests remain maintainable as the codebase evolves.JetBrains/kotlin2 discussions
- Minimize not-null assertionsAvoid using not-null assertions (`!!`) when safer alternatives exist. Instead: 1. Use safe calls (`?.`) when accessing properties or methods on nullable referencesJetBrains/kotlin2 discussions
- Dependency verification configurationWhen adding new dependencies to build.gradle.kts files, always update the corresponding verification metadata to prevent build failures. Use the Gradle command `./gradlew --write-verification-metadata md5,sha256 help` to generate the necessary metadata, but review the output carefully as it may add more dependencies than required. Consider manually adding...JetBrains/kotlin2 discussions
- Copy external string inputsWhen storing string pointers from external sources (like command-line arguments), always validate the input and create managed copies to prevent null references and lifetime issues. This practice ensures that your stored references remain valid throughout your program's execution and prevents potential crashes from null or invalid pointers.JetBrains/kotlin2 discussions
- YAML Message FoldingWhen writing YAML string fields intended for one-line or sentence-like messages, prefer folded block scalars (`>`) so embedded newlines render as spaces. Use literal block scalars (`|`) only when you explicitly need to preserve line breaks.Kong/kong2 discussions
- Release note formattingWhen updating documentation that is consumed by automated release tooling (such as changelog YAML), verify both the semantic classification and the generated markdown rendering.Kong/kong2 discussions
- prefer simple null-safe patternsUse straightforward null-safe patterns instead of complex undefined/empty distinctions. Avoid `any` types that can hide potential null/undefined issues at runtime.kilo-org/kilocode2 discussions
- organize test setupReduce test code duplication by organizing common setup logic and grouping related tests appropriately. Move repeated setup code into beforeEach hooks and use describe blocks to group tests that share similar setup or test the same feature area.kilo-org/kilocode2 discussions
- Justify configuration overridesBefore adding manual configuration entries, verify that the tool doesn't already provide the desired behavior automatically. Document why the override is necessary and what specific problem it solves.kilo-org/kilocode2 discussions
- Follow consistent semantic namingEnsure that names accurately reflect their purpose and maintain consistency with established patterns in the codebase. Method names should clearly indicate their behavior - avoid misleading conventions when they don't match the actual functionality. Similarly, maintain consistent naming patterns across similar contexts.kilo-org/kilocode2 discussions
- Ensure proper React keysAlways provide meaningful keys for React components and fragments to ensure proper rendering and re-rendering behavior. Use composite keys when component identity depends on multiple values, and include keys even for Fragment components when rendering lists.kilo-org/kilocode2 discussions
- enhance poor error messagesWhen external APIs or dependencies provide cryptic or unhelpful error messages, wrap them with user-friendly, actionable guidance. This is especially important when the external service returns terse responses that don't help users understand what went wrong or how to fix it.kilo-org/kilocode2 discussions
- Document performance tool lifecycleWhen creating performance optimization tools, especially temporary dev-only utilities, clearly document their purpose, scope, and removal criteria in the README or documentation. This helps teams make informed decisions about maintenance vs. performance benefits over time.kilo-org/kilocode2 discussions
- Document configuration requirementsAlways document configuration requirements, environment variables, and version specifications to ensure consistent development environments and proper system setup. This includes documenting environment variables that enhance workflow, specifying exact versions in configuration files, and providing clear setup instructions.kilo-org/kilocode2 discussions
- Consider semantic contextWhen choosing names for variables, methods, classes, or configuration sections, consider both the current purpose and potential future extensions. Names should be semantically accurate and align with established conventions in the codebase.kilo-org/kilocode2 discussions
- Consider async function contractsBe intentional when marking functions as async, as it changes the function's contract and caller expectations. Avoid using async unnecessarily when you're just returning a promise explicitly, and consider whether making a function async implies that callers should await its completion.kilo-org/kilocode2 discussions
- Configuration bounds validationAlways validate configuration values against system limits and constraints, implementing automatic adjustment when values exceed acceptable bounds. This prevents runtime errors and ensures configurations remain within operational parameters.kilo-org/kilocode2 discussions
- avoid expensive operationsIdentify and mitigate costly operations that can significantly impact performance. This includes CPU-intensive processing, expensive I/O operations, and repeated function calls that involve file system access or complex computations.kilo-org/kilocode2 discussions
- Document precise security requirementsSecurity documentation must specify exact permission requirements with clear scope and timing details. Vague or outdated security requirements can lead to insufficient ACL configurations, creating security gaps or deployment failures.apache/kafka2 discussions
- Document configuration constraintsConfiguration documentation must explicitly specify when settings should or should not be used, including conditional requirements and mutually exclusive options. This prevents misconfigurations and helps developers understand the proper context for each setting.apache/kafka2 discussions
- condition-based network synchronizationWhen waiting for network state propagation or distributed system synchronization, avoid using fixed sleep times and instead implement condition-based waiting that verifies the actual desired state. Fixed delays are unreliable in network environments due to variable latency and don't guarantee the expected state has been reached.apache/kafka2 discussions
- comprehensive test assertionsWrite test assertions that are both comprehensive and maintainable. Ensure all relevant fields and behaviors are validated, while using generic matchers where appropriate to reduce brittleness.apache/kafka2 discussions
- Centralize configuration valuesAvoid duplicating configuration values across multiple files by maintaining a single source of truth for environment variables, build arguments, version specifications, and other configuration parameters. When the same value appears in build scripts, Dockerfiles, documentation, or configuration files, consolidate it to one authoritative location and...apache/kafka2 discussions
- avoid overly specific examplesWhen documenting configuration options, use generic examples that don't unnecessarily tie documentation to specific versions, environments, or exact default values. This keeps documentation maintainable and prevents examples from becoming outdated or environment-specific.apache/kafka2 discussions
- API response completenessEnsure API responses contain all necessary data fields and provide mechanisms for clients to verify operation results. When building API responses, successful operations should include complete metadata (such as topic IDs, timestamps, or other identifiers), while failed operations should contain appropriate error information. Additionally, provide...apache/kafka2 discussions
- Verify test assertionsAlways use appropriate assertion methods in tests to ensure proper verification of command behavior. When you don't need to examine command output, use `.success()` to verify the command completed without errors. When the output content is meaningful for testing the functionality, capture and snapshot it for verification.jj-vcs/jj2 discussions
- specify configuration scopeAlways explicitly specify the configuration scope using `--user` or `--repo` flags when setting configuration values with `jj config set`. This prevents ambiguity about where the configuration should be stored and ensures settings are applied at the intended level.jj-vcs/jj2 discussions
- require explicit security consentAlways require explicit user consent and validation before executing potentially dangerous operations, especially those involving external configuration or dynamic user inputs. This prevents security vulnerabilities from being introduced through seemingly innocent features.jj-vcs/jj2 discussions
- precise algorithmic terminologyWhen documenting or describing algorithmic operations, use precise, unambiguous terminology that clearly distinguishes between different types of operations. Avoid reusing terms that already have specific meanings in the domain, as this can lead to confusion about the actual algorithmic behavior.jj-vcs/jj2 discussions
- Pin actions to commitsUse specific commit hashes instead of version tags when referencing GitHub Actions in CI/CD workflows. Version tags can be moved or updated, potentially introducing security vulnerabilities or breaking changes, while commit hashes are immutable and provide reproducible builds.jj-vcs/jj2 discussions
- optimize remote fetch operationsWhen implementing network operations that fetch data from remote sources, configure specific refspecs or patterns to fetch only the required data rather than everything available. This reduces network bandwidth usage, improves performance, and ensures future operations remain efficient.jj-vcs/jj2 discussions
- Multiple remote configurationWhen documenting or implementing features that involve multiple remote repositories, provide clear guidance on different remote configuration strategies and their appropriate use cases. This includes explaining the distinction between remotes you have write access to (typically `origin`) versus read-only upstream remotes, and when to track or sync different...jj-vcs/jj2 discussions
- GitHub Actions security reviewAlways review GitHub Actions workflows for security implications before merging, particularly focusing on authentication mechanisms and credential handling. Understand what permissions like `id-token: write` grant and their potential attack vectors. Ensure secure defaults are explicitly configured, such as disabling credential persistence.jj-vcs/jj2 discussions
- ensure cross-platform compatibilityWhen creating configuration files and build tasks, prioritize cross-platform compatibility by avoiding shell-specific syntax and considering how tools discover their configuration files across different environments.jj-vcs/jj2 discussions
- document test configurationsWhen modifying test configurations or tooling settings, provide clear explanations of what the changes actually do and why specific options were chosen. Test configuration changes can be confusing without proper context.jj-vcs/jj2 discussions
- Use platform-specific endpointsWhen configuring API integrations, always use the actual platform-specific endpoints and identifiers rather than generic placeholders. Generic configurations often lead to integration failures and confusion for users following documentation.menloresearch/jan2 discussions
- Use centralized model stateAlways access AI model information, parameters, and configuration through centralized state management rather than direct access or hardcoded values. This ensures consistency, maintainability, and proper separation of concerns when working with AI models.menloresearch/jan2 discussions
- Use centralized logging frameworkAlways use the established logging infrastructure instead of creating custom logging solutions or multiple logging systems. This prevents fragmentation and ensures consistent log management across the codebase.menloresearch/jan2 discussions
- simplify error handlingWrite concise and appropriate error handling code by avoiding unnecessary complexity and verbose constructions. Remove try-catch blocks when they serve no purpose, and use streamlined approaches for error message construction.menloresearch/jan2 discussions
- leverage existing solutionsAvoid duplicating functionality by leveraging existing libraries and creating reusable components. Instead of redefining common utilities or creating similar components for each use case, use established libraries and build generic, reusable components that can be configured for different scenarios.menloresearch/jan2 discussions
- externalize configuration valuesConfiguration values, especially sensitive data like API keys and environment-specific settings, should be externalized to environment variables rather than hardcoded in source code. This prevents sensitive information from being permanently stored in git history and enables proper configuration management across different environments.menloresearch/jan2 discussions
- Ensure proper event sequencingWhen working with event-driven systems, ensure that events are emitted at the appropriate time and in the correct context to prevent race conditions and incorrect behavior. Consider whether the function's purpose aligns with event emission - single-response functions should not broadcast events meant for streaming contexts. Additionally, be mindful of...menloresearch/jan2 discussions
- consolidate build scriptsWhen creating multiple build variants (debug, publish, etc.), avoid duplicating build commands by reusing the base build script. This reduces maintenance overhead, ensures consistency across build targets, and shortens complex build commands.menloresearch/jan2 discussions
- consistent localhost addressingUse 127.0.0.1 instead of 'localhost' for network requests and implement broad localhost detection rather than specific port-based checks. This ensures consistent behavior across different environments and avoids issues with DNS resolution or host file configurations.menloresearch/jan2 discussions
- API interface consistencyEnsure that API function signatures, return types, and interface implementations are consistent and properly declared. When modifying functions to be asynchronous or changing their return types, update both the implementation and any related type declarations to maintain contract integrity.menloresearch/jan2 discussions
- verify logging configuration functionalityEnsure that logging configuration options actually perform the behavior their names suggest and provide real value. Before implementing or maintaining logging features, verify that they work as advertised and aren't just cosmetic labels.istio/istio2 discussions
- validate access scopeWhen implementing security features that involve access control, authentication, or authorization, carefully validate that the changes don't inadvertently grant broader access than intended. This is particularly critical when dealing with secret access, trust domains, or credential handling.istio/istio2 discussions
- Security behavior clarityWhen documenting or describing security-related changes, especially bug fixes and behavioral modifications, ensure clear and explicit communication of security implications. Use proper security terminology and clearly describe both the problematic behavior and the fix.istio/istio2 discussions
- optimize hot path performanceIdentify and eliminate expensive operations in frequently executed code paths, particularly in packet processing and network handling contexts. Hot paths are code sections that execute repeatedly at high frequency, where even small performance penalties can significantly impact overall system performance.istio/istio2 discussions
- Flexible configuration defaultsConfiguration values should provide sensible defaults while remaining adaptable to different environments and deployment contexts. Use conditional assignment and guards to handle variations in runtime environments, deployment tools, and system configurations.istio/istio2 discussions
- Document observability clearlyEnsure observability documentation is clear, accessible, and grammatically correct. This includes defining technical acronyms and ensuring proper sentence structure in configuration explanations.istio/istio2 discussions
- Verify package.json accuracyEnsure that package.json configuration entries accurately reflect the actual project structure and include complete, working settings. Incorrect or incomplete package.json configuration can cause runtime failures and deployment issues.vadimdemedes/ink2 discussions
- useEffect for measurementsWhen using functions that depend on rendered layout or DOM measurements, call them within useEffect hooks to ensure they execute after the component has rendered and layout calculations are complete.vadimdemedes/ink2 discussions
- Use React.FC consistentlyUse React.FC (or React.FunctionComponent) for typing functional components instead of verbose function type definitions. React.FC provides built-in typing for common props like children, key, and ref, reducing boilerplate and ensuring consistency across the codebase.vadimdemedes/ink2 discussions
- Use descriptive parameter namesChoose parameter names that clearly communicate their purpose and avoid confusion with similar concepts. Avoid generic or ambiguous names that could be misinterpreted.vadimdemedes/ink2 discussions
- React interface clarityEnsure React interfaces have descriptive names and accurate documentation that clearly communicate their purpose and usage. Interface names should be specific to their context (e.g., `StdoutContextProps` instead of `StdoutProps` for Context-related interfaces), and API documentation should accurately reflect how methods are called (e.g., distinguishing...vadimdemedes/ink2 discussions
- optimize iteration patternsWhen implementing loops and iteration logic, evaluate whether your current approach is the most efficient and readable option available. Look for opportunities to simplify complex iteration patterns and eliminate unnecessary loops.vadimdemedes/ink2 discussions
- Ensure documentation usabilityDocumentation should be practical and serve its intended audience effectively. Examples must be runnable out-of-the-box or include clear setup instructions, while API documentation should focus on public interfaces that users actually need.vadimdemedes/ink2 discussions
- Documentation quality standardsEnsure documentation follows proper formatting standards and provides complete, practical information for developers. Use JSDoc tags correctly - `@default` should contain actual TypeScript values, not descriptive sentences. When the default value is conditional or complex, use plain text descriptions instead.vadimdemedes/ink2 discussions
- Documentation code qualityEnsure documentation code blocks use appropriate syntax highlighting and provide comprehensive, functional examples. For shell commands in markdown, use `sh` syntax highlighting rather than `console` for better highlighting accuracy and copy functionality. When documenting APIs or components, provide multiple complete examples that demonstrate different...vadimdemedes/ink2 discussions
- Clear API interfacesEnsure API interfaces are clearly defined with proper formatting and comprehensive documentation. Type definitions should use consistent formatting with appropriate line breaks for complex objects, and documentation should precisely explain callback behavior, timing, and parameters.vadimdemedes/ink2 discussions
- Document versioning strategiesEstablish and clearly document versioning strategies in configuration files, both for your application and its dependencies. For application versioning, include detailed explanations of each component in the version string:influxdata/influxdb2 discussions
- Document function signaturesAlways document function parameters and return values in the function header comment or interface definition. This is particularly important when a function returns multiple values or when the meaning of return values might not be immediately obvious.influxdata/influxdb2 discussions
- Centralize workspace configurationsCentralize configuration settings like dependency versions and feature flags at the workspace level rather than duplicating them across individual crate files. This reduces maintenance overhead, prevents inconsistencies, and simplifies dependency management.influxdata/influxdb2 discussions
- Semantic naming consistencyEnsure all model and field names semantically reflect their actual purpose and maintain consistency with their usage throughout the codebase: 1. Choose names that accurately represent the entity's role without misleading prefixes.elie222/inbox-zero2 discussions
- Ensure schema-migration consistencyWhen modifying database schemas, ensure complete alignment between schema definitions and SQL migration scripts. Every field, column, constraint, or relationship defined in your schema must have a corresponding migration operation.elie222/inbox-zero2 discussions
- Eliminate documentation redundancyDocumentation should be concise and avoid repeating the same information in multiple places. Redundant content confuses readers, makes maintenance more difficult, and can lead to inconsistencies when only one copy gets updated.elie222/inbox-zero2 discussions
- Consistent code organizationMaintain consistent patterns when organizing code elements within schema files. Place standard fields (like IDs and timestamps) first in all models to establish a predictable structure. Group similar elements together and position enum definitions at the bottom of schema files.elie222/inbox-zero2 discussions
- Collections use plural namesAlways use plural names for properties representing collections (arrays/lists) in interfaces, types, and destructuring patterns. This ensures consistency between interface definitions and their usage throughout the codebase.elie222/inbox-zero2 discussions
- weak pointer callback safetyWhen capturing objects in callbacks or lambdas that may execute asynchronously, use weak pointers instead of raw pointers or shared pointers to prevent use-after-free bugs. Always validate the weak pointer before dereferencing it, and avoid redundant lock() calls on the same weak pointer.hyprwm/Hyprland2 discussions
- validate environment variablesAlways validate that environment variables are properly defined and consistently named before using them in scripts or build processes. Undefined or misnamed variables can cause silent failures or unexpected behavior in builds and deployments.hyprwm/Hyprland2 discussions
- optimize workflow triggersDesign CI/CD workflows with intentional triggers and conditions to avoid unnecessary executions, rate limiting, and contextually inappropriate behavior. Use specific event triggers and conditional statements to ensure workflow steps run only when needed and appropriate.hyprwm/Hyprland2 discussions
- Explain documentation rationaleWhen writing user-facing documentation, always explain WHY a guideline or requirement exists, not just WHAT users should do. Users are more likely to follow instructions when they understand the reasoning behind them.hyprwm/Hyprland2 discussions
- Avoid unintentional defaultsWhen designing configuration interfaces, be intentional about default values and consider their impact on user behavior and data quality. Avoid defaults that users might unconsciously accept without proper consideration, especially for critical settings.hyprwm/Hyprland2 discussions
- API input/output validationEnsure robust parsing of API inputs and proper formatting of outputs to prevent parsing errors and unexpected behavior. API implementations must handle edge cases where command identifiers might appear within parameter values, and all output formats must properly escape special characters.hyprwm/Hyprland2 discussions
- Use defensive SQL clausesAlways use defensive SQL clauses like `IF NOT EXISTS` and `IF EXISTS` in migration scripts to make them idempotent and prevent failures when run multiple times or in different environments. This ensures migrations can be safely re-executed without causing errors due to existing schema elements.juspay/hyperswitch2 discussions
- Minimize API test dataKeep API test configurations lean by including only the fields necessary for the specific test scenario. Avoid bloated request/response objects that contain extraneous data, and resist creating duplicate API test patterns when existing ones can be reused.juspay/hyperswitch2 discussions
- explicit database constraintsBe explicit about database constraints and avoid relying on database-level defaults. Always specify NOT NULL constraints where appropriate and let the application layer handle default values rather than the database schema. Use appropriate primary key strategies like SERIAL for auto-incrementing IDs.juspay/hyperswitch2 discussions
- consistent configuration namingConfiguration variable names should follow consistent patterns and be descriptive enough to clearly convey their purpose and scope. When naming similar configuration parameters, maintain uniform naming conventions throughout the codebase.juspay/hyperswitch2 discussions
- Centralize shared configurationsAvoid duplicating configuration values across multiple files. Instead, define shared configurations in centralized locations and import them where needed. This prevents inconsistencies and makes configuration management more maintainable.juspay/hyperswitch2 discussions
- avoid hard-coded test dataHard-coded test data creates maintenance burdens and unrealistic test scenarios. Instead of manually defining static values or adding workarounds for dynamic fields, leverage existing test utilities and generation functions.juspay/hyperswitch2 discussions
- JSX runtime compatibilityWhen building or extending a JSX/React-compatible module, aim for full conformance with the standard JSX/React behavior rather than a partial subset, so consumers (and tools built on top, like HonoX) can rely on familiar APIs and correct rendering semantics.honojs/Hono2 discussions
- Stop Infinite Error PollingIn long-running UI workflows that poll (e.g., QR status, task panels, gateway actions), treat failures as **transient vs permanent**, and ensure your state transitions **cannot loop forever**.nousresearch/hermes-agent2 discussions
- Lock and Retry RulesWhen coordinating async work with shared resources, (1) tie lock/flag state transitions to the real lifecycle of the work (e.g., confirmed detached handoff or confirmed error) rather than to generic function scope, and (2) treat resource contention as transient by using bounded retry + backoff for cleanup/claims.nousresearch/hermes-agent2 discussions
- Localize configuration UIIn configuration/settings UI (including timezone, system defaults, and messaging), do not introduce or hardcode user-visible text. Always source strings from the appropriate i18n catalog/keys so all locales (e.g., desktop Japanese/Chinese) get consistent wording.nousresearch/hermes-agent2 discussions
- Integration tests for focusWhen behavior depends on library primitives (e.g., Radix) and real browser focus/pointer flows (including `document.body` portals), unit tests that reimplement internal handlers are not enough. Write tests that render the actual component tree and assert user-observable outcomes.nousresearch/hermes-agent2 discussions
- Failure-Safe State HandlingWhen error handling affects control-flow invariants (dedupe keys, stale-session guards, correctness checks), make failures safe and reversible: - Cleanup on every failure path: If you “remember”/lock/dedupe before completing the operation, ensure that early returns and catch blocks restore the pre-operation state (e.g., remove the remembered key).nousresearch/hermes-agent2 discussions
- Enforce Security End-to-EndWhen implementing security controls, treat them as end-to-end requirements across *all* navigation paths and *all* auth/transport interfaces. Two common failure modes are (1) hidden/aux renderer windows that still allow unintended credential/WebAuthn UI via a fallback path, and (2) security-sensitive flows that accept security context but some callers pass...nousresearch/hermes-agent2 discussions
- Deterministic algorithm workflowsWhen you describe an algorithm (retrieval pipeline, scoring, ranking, etc.), ensure the implementation includes the complete promised workflow and produces deterministic outputs.nousresearch/hermes-agent2 discussions
- Collision-Safe KeysWhen an algorithm derives a decision key (dedupe) or signal (parsed config) that can suppress/merge data, make that derivation collision- and normalization-safe, and define precedence explicitly.nousresearch/hermes-agent2 discussions
- Canonical Identifier SemanticsWhen code maps or normalizes external identifiers (tool names, locale tags, etc.), it must preserve the identifier’s real semantics and use canonical names.nousresearch/hermes-agent2 discussions
- Accessible React State HandlingIn React components and hooks, changes to focus/interaction state or derived UI state must preserve correct behavior for all users and reflect the actual semantic state transitions.nousresearch/hermes-agent2 discussions
- Precise Selection LogicWhen implementing any selection algorithm (lookup/search/pick-next based on state or identifiers), make the selection rule precise and the state transitions intentional.ogulcancelik/herdr2 discussions
- Optimize Without GuessingWhen performance-critical code interacts with OS/process state or remote services, optimize by reducing unnecessary work *only when correctness is preserved*.ogulcancelik/herdr2 discussions
- Consistent UI formattingWhen formatting UI text for alignment (padding/truncation like `{position:<N}`), keep the visual rules consistent across all related components and validate against the actual available width. If the change would alter the product’s visual language/layout rules (e.g., needing new rules to display a dot for 100+), treat it as a design/discussion item rather...ogulcancelik/herdr2 discussions
- Consistent Event ContractsWhen a single user action or state transition can be reached via multiple entrypoints (e.g., tab close vs workspace close), the externally observable behavior (especially emitted events) must be consistent with the actual underlying changes.ogulcancelik/herdr2 discussions
- Behavioral Regression TestsWrite regression tests that (1) are portable across platforms where behavior is shared and (2) are “behaviorally decisive,” meaning they must fail if the real logic is removed.ogulcancelik/herdr2 discussions
- Target documentation to audienceWrite documentation that matches both your audience's expertise level and the language's conventional formats. For technical documentation, use language-specific conventions (like Rust's doc comments). For tutorials or learning materials, prefer step-by-step explanations that minimize cognitive load.helix-editor/helix2 discussions
- omit redundant configurationRemove configuration keys that explicitly set values identical to their defaults. This reduces visual clutter, minimizes maintenance overhead, and prevents confusion about which settings are intentionally customized versus accidentally duplicated.helix-editor/helix2 discussions
- API documentation accuracyEnsure API documentation accurately describes actual behavior and avoids subjective commentary that may become outdated. Documentation should clearly explain how features interact, what the expected behavior is, and avoid qualitative assessments about performance or quality that can change over time.helix-editor/helix2 discussions
- Minimize client component scopeDefault to server components and only add `"use client"` to the smallest possible component that truly needs it (state, effects, event handlers, or browser APIs). Do not mark a parent/page as client just because a nested component is client-side - Next.js already interleaves server and client components, and adding the directive higher up unnecessarily...Helicone/helicone2 discussions
- Workflow permission boundariesAlways define explicit and minimal permission boundaries in GitHub Actions workflows to adhere to the principle of least privilege. By default, workflows have broad permissions that could be exploited if compromised. Specify permissions at either the workflow or job level to restrict the GITHUB_TOKEN to only required access levels.grafana/grafana2 discussions
- Use dynamic port allocationWhen writing tests that require network services (HTTP, gRPC, or custom protocols), use port 0 to let the operating system assign available ports rather than hard-coding specific port numbers. Hard-coded ports can cause conflicts when multiple tests run simultaneously, leading to flaky tests.grafana/grafana2 discussions
- Stable test assertionsWrite tests that focus on behavior rather than implementation details to create more stable and maintainable test suites. Avoid using arbitrary timeouts and assertions that frequently break with implementation changes.grafana/grafana2 discussions
- Sort with clarityEnsure sorting functions are named to accurately reflect their behavior and implement consistent sorting approaches throughout the codebase. When implementing sort operations:grafana/grafana2 discussions
- Opt-in configurable cachingImplement caching mechanisms as opt-in features with explicit configuration options rather than as defaults. This approach prevents unexpected behavior and allows teams to deliberately enable caching where beneficial.grafana/grafana2 discussions
- Object parameters for readabilityWhen a function has 3 or more parameters, use object destructuring instead of positional arguments. This improves code readability by making parameter names explicit at call sites and making the function signature more maintainable as parameters are added or modified.grafana/grafana2 discussions
- Document translatable UI textAll user-facing text in UI components should be properly documented for translation using the application's internationalization (i18n) framework. This ensures that the application can be easily localized for different regions and improves maintainability.grafana/grafana2 discussions
- Defense in depthAlways implement multiple layers of security controls, even when they might seem redundant. This strategy ensures protection remains effective even if one security measure fails or is bypassed.grafana/grafana2 discussions
- Contextual structured loggingLog messages should provide sufficient context to be meaningful and actionable while following structured logging patterns. Include relevant metrics, ratios, or identifiers that help diagnose issues. Use semantic conventions and structured key-value pairs rather than embedding values in message strings.grafana/grafana2 discussions
- Check before calculatingImplement preliminary validation checks before executing expensive operations to avoid unnecessary processing. When handling operations that may be computationally intensive (like text layout calculations, data transformations, or complex rendering), add targeted checks that can early-exit or skip work when the operation would have no effect or be redundant.grafana/grafana2 discussions
- Balance flexibility with simplicityWhen designing component APIs, strive to find the optimal balance between providing flexible configuration options and maintaining simplicity. Start with essential functionality before adding complex features that may complicate the API surface.grafana/grafana2 discussions
- Assert with precisionTests should verify actual behavior rather than just successful execution. When writing assertions, favor precise equality checks that verify the exact content and ordering rather than loose containment checks.grafana/grafana2 discussions
- Validate object availabilityAlways verify that objects and their properties exist before accessing them to prevent null reference errors. This includes checking for undefined global objects, optional parameters, and nested properties.block/goose2 discussions
- Validate model limitsWhen integrating LLM providers, don’t assume the provider’s model spec equals what the specific API endpoint will actually accept. Enforce two checks in your model configuration: (1) set `context_limit` to a safe upper bound that matches the endpoint’s effective cap, and (2) restrict model selection to a curated allowlist of chat-capable models instead of...aaif-goose/goose2 discussions
- validate IPC inputsAlways validate and sanitize inputs to IPC handlers to prevent unauthorized access to system resources. Implement allowlists or blocklists for file system operations and maintain secure Electron configuration.block/goose2 discussions
- Use width-safe stringsWhen implementing string operations that depend on the environment (terminal/UI rendering or filesystem paths), avoid naive `.length`/single-separator logic. Use algorithms that are correct for Unicode/code points and for the actual width/splitting rules of the runtime.aaif-goose/goose2 discussions
- Use self-documenting namesChoose variable, function, and constant names that clearly express their purpose and eliminate the need for explanatory comments. Break down complex expressions into well-named intermediate variables rather than relying on comments to explain the logic.block/goose2 discussions
- Use established logging librariesAvoid using print statements (println!, eprintln!) or custom logging implementations for application logging. Instead, use established logging libraries like `tracing` that provide proper log levels, structured output, and configurable destinations.block/goose2 discussions
- Use configuration enumsReplace hardcoded string matching and magic values with proper configuration enums or flags. This improves maintainability, reduces errors, and makes configuration behavior explicit and type-safe.block/goose2 discussions
- Sanitize untrusted inputAlways sanitize or escape untrusted input before using it in security-sensitive contexts to prevent injection attacks. This includes HTML content that could lead to XSS vulnerabilities and user-provided strings used in regex patterns.block/goose2 discussions
- Optimize algorithmic efficiencyAlways consider the computational complexity of your algorithms and leverage efficient built-in methods when available. Look for opportunities to reduce time complexity and avoid unnecessary operations like redundant loops or object creation.block/goose2 discussions
- leverage TypeScript nullabilityWhen dealing with values that may be null or undefined, explicitly leverage TypeScript's nullable types to identify dependencies and guide null handling decisions. Make values nullable when their availability is uncertain, then let TypeScript reveal where null checks are needed.block/goose2 discussions
- Keep dependencies currentAlways use the latest stable versions of dependencies in configuration files like Cargo.toml, and avoid deprecated or unmaintained packages. Outdated dependencies can introduce security vulnerabilities, compatibility issues, and technical debt.block/goose2 discussions
- Incremental CI developmentDevelop CI/CD workflows incrementally, starting with simpler versions and adding complexity gradually. This approach makes testing easier and reduces the risk of introducing breaking changes. When adding new steps or jobs, consider their performance impact and dependencies on other workflow components.block/goose2 discussions
- Immutable Setup PinningWhen your tooling downloads/execut es external installers or scripts, treat both the *source* and the *workspace* as security-sensitive: - **Pin remote code to an immutable reference** (tag/commit SHA) before executing it, so the fetched content can’t change between reviews/runs.aaif-goose/goose2 discussions
- Idempotent Async InitializationWhen async flows drive UI state (events, config reads, resume/load), never assume timing/order will be favorable. Make initialization idempotent and conditionally applied so missed/early events or late async completions can’t leave the UI stuck or clobber user intent.aaif-goose/goose2 discussions
- Harden Packaged InputsApply a production/packaged hardening rule: in release builds, only use trusted origins and trusted code/resources. Treat environment variables, URLs, and “implicit” host paths as untrusted inputs, and explicitly gate/validate them so they cannot redirect critical behavior.aaif-goose/goose2 discussions
- Extract duplicate constantsEliminate code duplication by extracting repeated values and components into well-organized constants. This applies at both the variable level (extracting duplicate literal values) and file level (separating reusable components).block/goose2 discussions
- Enforce Security Boundaries EarlyApply security controls at the controlling layer and before triggering any side effects. - **Iframe/sandbox:** Treat `sandbox` on ancestor iframes as the effective policy for descendants. Ensure the default sandbox includes any permissions required by the hosted app (otherwise functionality may break or be silently over-restricted).aaif-goose/goose2 discussions
- Document API contractsEnsure all API interfaces have clearly documented contracts specifying expected request/response formats, data encoding standards, and return types. This prevents integration issues and enables reliable external consumption.block/goose2 discussions
- Deterministic Docs PipelinesFor CI/CD that builds/publishes documentation (or any release-time artifacts), ensure two things: 1) **Correct trigger coverage**: docs-only changes must run the docs build via an explicit workflow path (don’t assume upstream jobs will run). If you use `paths-ignore` to skip heavy pipelines on doc changes, add a separate workflow (or separate trigger) that...aaif-goose/goose2 discussions
- dependency version precisionChoose appropriate version constraints in package.json based on stability requirements and risk tolerance. Use tilde (~) for patch-level updates when you want stability but need bug fixes, caret (^) for minor updates when you can tolerate feature additions, or exact versions for maximum control. For critical dependencies requiring precise version control,...block/goose2 discussions
- Database migration isolationWhen performing database migrations or schema changes, use containerized environments to ensure isolation and comprehensive testing. This approach prevents migration issues from affecting development environments and allows for reliable rollback scenarios.block/goose2 discussions
- containerize sensitive workflowsUse containerization to isolate operations that could access sensitive data, modify critical systems, or execute untrusted code. Containers provide a secure boundary that prevents workflows from affecting the host environment or accessing resources beyond their intended scope.block/goose2 discussions
- Conditional telemetry flushingAvoid fixed delays for telemetry flushing. Instead, make flushing conditional on whether telemetry endpoints are configured and use dynamic timeouts when possible.block/goose2 discussions
- Bound parallel async lifecycleFor any async workflow that fans out (e.g., Promise.all over providers) or mutates shared session state, apply two rules: 1) Bound/cancel all external async work (timeouts must abort the underlying operation, not only the awaiting caller).aaif-goose/goose2 discussions
- API Config ConsistencyDeclarative API/provider configurations must be internally consistent with (a) the canonical identifiers used by the model registry/discovery layer and (b) the request-building logic that actually emits fields for the selected engine/path. This prevents mismatches, silent capability drops, and confusing “it’s configured but doesn’t work” behavior.aaif-goose/goose2 discussions
- wrap errors properlyWhen creating error messages that include information from underlying errors, use fmt.Errorf with the %w verb instead of string concatenation with err.Error(). This preserves the error chain, enabling proper error unwrapping and better debugging capabilities.golang/go2 discussions
- Use conventional descriptive namesVariable names should follow established language conventions and clearly communicate their purpose and context. Avoid abbreviated or cryptic names in favor of descriptive identifiers that make code self-documenting.golang/go2 discussions
- maintain backward compatibilityWhen modifying existing APIs, preserve original parameter types and return signatures to avoid breaking client code. Even when internal implementations change or new functionality is added, the public interface should remain stable for existing consumers.golang/go2 discussions
- go:build directive syntaxEnsure go:build directives follow correct syntax with no space between "//" and "go", and use proper logical operators for multiple conditions. Incorrect spacing causes the directive to be ignored by the compiler, potentially including wrong code for target environments.golang/go2 discussions
- Documentation quality standardsEnsure all documentation comments follow proper formatting conventions and are placed where developers will most likely read them. Documentation should use correct grammar, complete sentences, and end with periods. Additionally, place documentation at the most relevant location - typically at interface definitions rather than implementation details, since...golang/go2 discussions
- Use standard HTTP constantsAlways use the standard HTTP status constants from the `http` package instead of raw numeric values in your networking code. This practice improves code readability, maintainability, and helps prevent errors when working with HTTP responses.gin-gonic/gin2 discussions
- Select algorithms by complexityChoose appropriate algorithms based on computational complexity requirements and context. When implementing lookups, prefer O(1) direct access over O(n) iterations whenever possible. For infrequent operations or small datasets, simpler linear algorithms may outperform more complex logarithmic approaches due to lower constant factors and better locality.gin-gonic/gin2 discussions
- Preserve security configurationsAlways respect explicitly set security attributes and properly sanitize user inputs to prevent security vulnerabilities. When modifying security-related configurations:gin-gonic/gin2 discussions
- Pin dependency versionsAlways specify exact versions of tools and dependencies in CI/CD workflows rather than using 'latest' or floating versions. This ensures build reproducibility, prevents unexpected failures when upstream dependencies change, and makes debugging easier.gin-gonic/gin2 discussions
- Minimize configuration complexityKeep configuration files clean and maintainable by regularly reviewing and removing unnecessary settings and outdated version support. This includes: gin-gonic/gin2 discussions
- Initialize before null-checkingWhen handling potentially nil values, ensure proper initialization order to prevent race conditions and null reference errors. This is critical for maintaining thread safety and following idiomatic Go patterns.gin-gonic/gin2 discussions
- Document API behaviorThoroughly document how your API endpoints handle data binding and processing, especially non-obvious behaviors that affect how client data is mapped to server-side structures. This includes:gin-gonic/gin2 discussions
- Declare .PHONY targetsAlways explicitly declare all Makefile targets that don't create files as `.PHONY`. This prevents conflicts with potential files of the same name, makes build intentions clear, and increases reliability in CI/CD pipelines.gin-gonic/gin2 discussions
- Close resource handles properlyAlways close file resources and other system handles after use to prevent resource leaks. Resource leaks can cause system instability, memory issues, and limit scalability, especially in long-running services handling many requests.gin-gonic/gin2 discussions
- Prefer flat control flowMinimize code nesting by using Swift features like `guard` statements and early returns instead of deeply nested if-else structures. When multiple code branches end with a return statement, avoid nesting with `else` clauses.ghostty-org/ghostty2 discussions
- Pipeline-friendly script designDesign scripts to be easily integrated into build pipelines and CI/CD workflows by using standard I/O streams instead of hardcoded file paths. Scripts that read from stdin and write to stdout can be easily composed in pipelines, redirected, and incorporated into various build systems without modification.ghostty-org/ghostty2 discussions
- Generate dynamic configurationsAlways generate configuration files programmatically when they contain dynamic content that changes frequently or needs to stay in sync with the application (like version numbers, release dates, or build timestamps). Manual maintenance of such files is tedious, error-prone, and creates maintenance overhead.ghostty-org/ghostty2 discussions
- Format for readabilityDocumentation should be formatted to optimize readability and information retention. Apply these principles to make documentation more user-friendly: ghostty-org/ghostty2 discussions
- Prefer up-to-date docsWhen building Gemini/LLM integrations, always use the most current and indexed API documentation/spec first, and avoid inefficient fallback behaviors.google-gemini/gemini-skills2 discussions
- Use appropriate logging levelsUse console.debug() for debug information instead of console.log() to prevent cluttering user-facing output. Debug information should be hidden from normal users but available when debugging is enabled.google-gemini/gemini-cli2 discussions
- Prefer lightweight composable APIsWhen designing APIs, favor lightweight, composable solutions that allow callers to maintain control over their specific use cases, rather than imposing centralized, monolithic systems that take control away from the caller.google-gemini/gemini-cli2 discussions
- optimize React hooks usageAvoid useRef unless strictly necessary and ensure useEffect has proper dependencies to prevent unnecessary re-renders. useRef makes logic harder to reason about and should be replaced with more straightforward patterns when possible. For useEffect, extract values outside the effect when they don't need to be dependencies, and ensure the dependency array...google-gemini/gemini-cli2 discussions
- minimize performance overheadReduce unnecessary overhead in performance-related code by creating reusable patterns and avoiding verbose implementations. This applies to both production performance monitoring and development workflows like testing.google-gemini/gemini-cli2 discussions
- avoid non-null assertionsAvoid using the non-null assertion operator (`!`) and instead use union types or explicit null checks for better type safety. Non-null assertions bypass TypeScript's null safety checks and can lead to runtime errors if the assumption is incorrect.google-gemini/gemini-cli2 discussions
- Validate security-critical inputsAlways implement thorough validation for user-controllable inputs that could pose security risks. Particularly: 1. **Path validation**: Protect against path traversal attacks by rejecting paths containing directory traversal sequences (`..`) or by resolving paths against a safe base directory.fatedier/frp2 discussions
- Focus documentation contentMaintain streamlined primary documentation (like README files) that focuses only on currently supported functionality and recommended approaches. Move specialized details, legacy systems, or deprecated methods to secondary documentation sources like wikis or specialized guides.fatedier/frp2 discussions
- Document code decisionsAlways include clear documentation for important code decisions and metadata. This includes preserving copyright notices and explaining the reasoning behind specific values and constants.fatedier/frp2 discussions
- Check context cancellationAlways implement proper cancellation mechanisms in concurrent code to prevent goroutine leaks and enable timely shutdown. Two key practices: 1. Add context checks at the beginning of loops in goroutines:fatedier/frp2 discussions
- Use Config SafelyTreat configuration/feature-flag-driven logic as potentially different between tests and runtime, and standardize how you branch on it. Apply this by:freeCodeCamp/freeCodeCamp2 discussions
- Use canonical invariantsWhen implementing algorithmic parsing/validation, base ordering/state on the canonical structured source, and keep validation logic split by invariant (local vs global) with explicit intent.freeCodeCamp/freeCodeCamp2 discussions
- RESTful endpoint responsesWhen designing API routes, make the HTTP method and response contract match the operation’s intent and the client’s needs. - Pick the correct verb: use DELETE for destructive/reset-like removal semantics when appropriate, and reserve POST for creation/processing actions.freeCodeCamp/freeCodeCamp2 discussions
- Mock Only What MattersWhen writing tests, avoid introducing unnecessary fakes/mocks that hide real integration behavior. - If your goal is to validate how code interacts with DOM dependencies, don’t “fake” core event/data shapes more than needed; use the real DOM/events interface (or a higher-fidelity fixture) so failures reflect real breakage.freeCodeCamp/freeCodeCamp2 discussions
- Avoid Unnecessary Type AssertionsIn route/controller code, don’t rely on repeated `as` casts to satisfy TypeScript—normalize/validate types once, then keep the rest of the logic strongly typed.freeCodeCamp/freeCodeCamp2 discussions
- Stateful Parsing CorrectnessWhen implementing stateful parsing (e.g., direction/context tracking with stacks), treat correctness as a property of the whole scan loop—not just the “main” match.EbookFoundation/free-programming-books2 discussions
- Least-privilege Actions tokensTreat CI workflow tokens as sensitive credentials: configure GitHub Actions `permissions` explicitly and keep token usage minimal. Apply this standard when workflows need to create PR comments/reviews:EbookFoundation/free-programming-books2 discussions
- Precise testing dependency versioningWhen specifying testing library dependencies, always use explicit minimum patch versions rather than development branches or broad version constraints. This practice ensures consistent and reproducible test environments across development, CI systems, and production builds.laravel/framework2 discussions
- Mark sensitive parametersAlways use the `#[\SensitiveParameter]` attribute for parameters containing sensitive information such as passwords, tokens, API keys, and personal identifiable information. This prevents accidental exposure of sensitive data in logs, stack traces, and debugging information, which could otherwise lead to security breaches.laravel/framework2 discussions
- Use named constantsReplace hardcoded string literals and magic values with named constants to improve code maintainability and readability. This practice prevents typos, makes the code self-documenting, and provides a single source of truth when the same value is used in multiple places.flutter/flutter2 discussions
- Manage state dependencies properlyEnsure components establish explicit dependencies when they need to react to external changes, and avoid state updates during build phases to prevent rendering conflicts.flutter/flutter2 discussions
- Secure session lifecycle managementSession destroy, regenerate, and state-tracking logic must fully and correctly invalidate or update session state to prevent fixation/hijacking vulnerabilities. Never implement destroy/regenerate as a no-op in a shared base class — any class managing session storage must ensure that destroying a session clears both the client-side token (e.g., cookie) and...pallets/flask2 discussions
- validate environment variables earlyEnvironment variables should be validated at startup or module initialization rather than at runtime usage. Use non-null assertion operators or explicit validation checks to fail fast when required configuration is missing, preventing delayed runtime errors and making configuration issues immediately apparent during development and deployment.firecrawl/firecrawl2 discussions
- preserve raw network dataAlways preserve raw network response data early in the processing pipeline before applying any transformations or parsing. Once network data is processed or encoded, critical information may be permanently lost and cannot be recovered later.firecrawl/firecrawl2 discussions
- preserve null semanticsWhen null or undefined values represent meaningful absence of data, preserve them rather than converting to default values like empty strings, arrays, or placeholder text. Converting these values can lose semantic meaning and create unnecessary data storage or processing overhead.firecrawl/firecrawl2 discussions
- optimize frequent operationsIdentify code paths that execute frequently and ensure they use performant, non-blocking solutions. Frequent operations should avoid expensive database queries, CPU-intensive synchronous processing, or anything that can block the event loop.firecrawl/firecrawl2 discussions
- Minimize database roundtripsAvoid making multiple database queries when a single query can retrieve the required data. Each database roundtrip adds latency and increases system load. Before making a database call, check if the data is already available or if multiple queries can be combined into one.firecrawl/firecrawl2 discussions
- Avoid async race conditionsEnsure proper async/await handling and consider concurrent execution patterns to prevent race conditions and improve performance. When working with asynchronous operations, always use await for promises and avoid mixing promise chains with async/await syntax. Additionally, identify opportunities to run independent operations concurrently rather than...firecrawl/firecrawl2 discussions
- API endpoint simplicityDesign API endpoints with concise, direct naming that clearly communicates their purpose without unnecessary verbosity. Avoid redundant prefixes or overly descriptive names that make endpoints harder to remember and use. Choose built-in language features over custom implementations when possible to improve reliability and maintainability.firecrawl/firecrawl2 discussions
- simplify logging integrationsWhen implementing custom logging integrations, prioritize simplicity and completeness over complex abstractions. Avoid creating overly complicated wrapper structures that developers must recreate for basic logging functionality. Instead, provide simple, reusable patterns that support all necessary logging levels and are easy to understand and maintain.gofiber/fiber2 discussions
- minimize unsafe reference lifetimeWhen working with methods that return potentially unsafe references or data that could become invalid, pass the results directly to safety/copy methods rather than storing them in intermediate variables. This minimizes the lifetime of unsafe references and reduces the risk of using invalidated data.gofiber/fiber2 discussions
- justified nolint exceptionsWhen style linters cannot be applied universally across a codebase due to architectural constraints or legitimate use cases, use targeted `//nolint` comments with clear explanations rather than disabling the linter entirely. This approach maintains code style standards while allowing necessary exceptions.gofiber/fiber2 discussions
- Document error conditions clearlyAlways provide clear documentation for error conditions, unsafe usage patterns, and failure scenarios in API documentation. Include explicit warnings about potential data races, undefined behavior, and error propagation to help developers avoid common pitfalls.gofiber/fiber2 discussions
- Configurable logging controlsMake logging behavior configurable rather than hardcoded, and avoid manipulating global state for logging purposes. Provide configuration options to enable/disable specific log messages, especially for warnings or debug information that could become spammy. Instead of overwriting global variables like os.Stdout and os.Stderr for testing, use dependency...gofiber/fiber2 discussions
- avoid `-count=1` flagAvoid using the `-count=1` flag in Go test commands unless specifically required to disable test caching. Removing this flag enables concurrent test execution, which not only improves test performance but more importantly allows for better detection of data races during testing.gofiber/fiber2 discussions
- API design clarityMaintain clear separation of concerns in API design by avoiding feature overlap and ensuring each method has a distinct, well-defined purpose. When designing APIs, resist the temptation to add convenience features that blur the boundaries between different configuration approaches, as this leads to user confusion and maintenance issues.gofiber/fiber2 discussions
- Verify types in testsUse explicit type assertions in TypeScript tests to verify that types behave as expected across various scenarios. Include assertions for inheritance relationships, property types, and different response status codes.fastify/fastify2 discussions
- Use bot identityWhen configuring Git operations in GitHub Actions workflows, especially for automated commits, use the GitHub Actions bot identity instead of personal user accounts. This clearly distinguishes automated actions from manual ones, provides better audit trails, and avoids personal attribution for system-generated changes.fastify/fastify2 discussions
- Support flexible loggingWhen designing logging interfaces, create flexible APIs that accommodate both standard and custom logging needs. This includes supporting custom log levels, allowing message format customization, and enabling level selection based on context.fastify/fastify2 discussions
- Secure Fastify Code ImplementationThis review focuses on secure implementation patterns when using the Fastify web framework in TypeScript: prevent Prototype Pollution Attacks by avoiding direct property access on untrusted objects, and protect Against Denial-of-Service Attacks by configuring appropriate request timeouts.fastify/fastify2 discussions
- Proper IPv6 address formattingWhen constructing URLs with IP addresses, ensure IPv6 addresses are properly formatted according to RFC standards by wrapping them in square brackets. This applies to all IPv6 addresses, not just specific cases like localhost. Additionally, use appropriate event handlers for network events that should only be handled once per connection.fastify/fastify2 discussions
- Ensure Proper Null Handling When Using Fastify DecoratorsWhen working with Fastify decorators, always perform explicit null checks before accessing potentially undefined properties. Relying on implicit null handling can lead to subtle bugs and unexpected behavior.fastify/fastify2 discussions
- Consistent Fastify Package Naming and ReferencesWhen implementing code using the Fastify package in TypeScript, it is important to use consistent and accurate naming conventions for Fastify-related references: always use the actual Fastify package name, use correct Fastify terminology and casing, and organize Fastify-related imports and references alphabetically.fastify/fastify2 discussions
- Use universally understandable identifiersWhen naming variables, functions, routes, and other code elements, use clear, neutral terminology that will be understood by all developers regardless of their cultural or domain-specific knowledge. This is especially important in tests, examples, and documentation where context may not be obvious.fastapi/fastapi2 discussions
- Use streaming generatorsWhen processing large files or datasets, implement generator functions that yield data incrementally rather than loading everything into memory at once. This approach significantly improves memory efficiency and enables handling of arbitrarily large datasets that wouldn't fit in memory.fastapi/fastapi2 discussions
- Use appropriate documentation formatsChoose the most suitable documentation format based on context to maximize readability and information value. For Pydantic models: - Use class-level docstrings for comprehensive documentation that supports rich formatting including newlines and emphasisfastapi/fastapi2 discussions
- Optimize IO with asyncFastAPI's performance advantage comes from its asynchronous foundation built on Starlette and Uvicorn, using `uvloop` which is significantly faster than Python's default asyncio implementation. To maximize application performance, use asynchronous programming patterns for IO-bound operations such as database queries, API requests, and file operations.fastapi/fastapi2 discussions
- Environment-specific database configurationConfigure database connections differently based on the environment. Use lightweight file-based databases like SQLite for development and testing, but deploy robust server-based databases like PostgreSQL in production. This approach simplifies local development while ensuring your application has appropriate scalability and reliability in production.fastapi/fastapi2 discussions
- Consistent dependency versioningWhen updating dependency version constraints in requirements files, ensure consistency with versions pinned by other dependencies in your project. Check what versions are used by major dependent packages before setting your own constraints to avoid compatibility issues.fastapi/fastapi2 discussions
- Clear informative errorsError messages should be clear, specific, and provide enough context to understand the issue without exposing unnecessary implementation details. When handling errors:fastapi/fastapi2 discussions
- Avoid blocking in asyncWhen working with asynchronous code, ensure that I/O operations (like file reads/writes) don't block the event loop. Blocking operations in async contexts can lead to performance degradation, deadlocks, or unexpected behavior.fastapi/fastapi2 discussions
- Secure CI workflow configurationsCI/CD workflow files (e.g., GitHub Actions) must be hardened against supply-chain and injection attacks since they often run with privileged access to secrets and repository write permissions. Specifically:Expressjs/Express2 discussions
- Modern TypeScript styleUse modern TypeScript syntax and conventions throughout the codebase. This includes: - Using `const` instead of `var` for variable declarations unless reassignment is neededexpressjs/express2 discussions
- Method chaining for clarityDesign API methods that favor chaining over multiple parameters to improve readability and maintainability. When implementing methods that require both a resource and configuration options (like status codes), prefer method chaining patterns that clearly separate concerns and make the purpose of each parameter explicit.expressjs/express2 discussions
- Maintain API typesEnsure API type definitions accurately reflect current implementations. When maintaining TypeScript definitions for APIs, regularly audit them against the actual source code to prevent developers from using non-existent or deprecated features.expressjs/express2 discussions
- Exclude sensitive configurationsDo not commit sensitive, time-limited, or environment-specific configuration files to version control. Instead: 1. For files with expiration dates (like SSL certificates):expressjs/express2 discussions
- Clear array operationsWhen working with arrays, prioritize clarity and explicitness over terse or clever constructs. For array membership checks, use `array.indexOf(item) === -1` rather than less obvious expressions like `!~array.indexOf(item)` or `array.indexOf(item) < 0`. This improves readability and makes code intent immediately clear to other developers.expressjs/express2 discussions
- Accurate JSDoc documentationAlways ensure JSDoc comments accurately reflect the actual code implementation. Parameter types, optionality, and function behavior must be precisely documented to prevent confusion and bugs.expressjs/express2 discussions
- minimize test maintenanceAvoid unnecessary test maintenance overhead by eliminating duplicate test coverage and implementing automated test update mechanisms. When the same functionality is already covered by equivalent tests (e.g., end-to-end tests that exercise the same code paths), remove redundant test implementations rather than maintaining multiple versions. Additionally,...evanw/esbuild2 discussions
- Follow configuration conventionsWhen working with configurations, maintain consistency by following established conventions and proper categorization. This includes using naming patterns that match related tools/frameworks and organizing configuration entries in appropriate sections based on actual capabilities.evanw/esbuild2 discussions
- cross-platform API consistencyDesign APIs to provide consistent behavior and user experience across different runtime environments and module systems. Abstract platform-specific differences behind a uniform interface so users don't need to handle environment-specific logic.evanw/esbuild2 discussions
- Scope configuration impactWhen implementing configuration settings, carefully consider and limit their scope to prevent unintended broad impact across systems or workflows. Configuration changes should be targeted and controlled rather than applied globally when only specific contexts require them.electron/electron2 discussions
- Protocol-specific network handlingWhen implementing custom network protocol behavior, ensure that modifications are properly scoped to only the intended protocol types and include upstream context documentation. Avoid applying protocol-specific changes broadly across all network protocols, as this can break assumptions and cause unintended side effects.electron/electron2 discussions
- extract reusable workflow componentsAvoid duplicating workflow steps across multiple CI/CD pipelines by extracting common functionality into reusable actions. This improves maintainability, reduces inconsistencies, and ensures proper cross-platform compatibility when needed.electron/electron2 discussions
- consistent platform identifiersWhen naming platform identifiers, choose one naming convention and use it consistently throughout the codebase. Prefer established ecosystem standards when available, such as Node.js `process.platform` values (`win32`, `darwin`, `linux`) over custom variations.electron/electron2 discussions
- avoid runtime credential resolutionSecurity credentials and access control mechanisms should be pre-configured at deployment or configuration time rather than resolved dynamically at runtime. Dynamic credential fetching introduces injection risks and makes security boundaries harder to audit and control.electron/electron2 discussions
- Use current configuration patternsAlways use the current recommended configuration patterns for your project, avoiding deprecated approaches. When configuring tests, features, or resource access:elastic/elasticsearch2 discussions
- Specify explicit REST formatsAlways specify explicit request formats in REST API tests rather than relying on default behaviors. This includes: 1. Set appropriate Content-Type headers (typically application/json for REST APIs) elastic/elasticsearch2 discussions
- Document security requirements explicitlyAlways document security-related configurations, permissions, and behaviors explicitly and comprehensively. When documenting security features: 1. Clearly specify required permissions and roleselastic/elasticsearch2 discussions
- Document performance tradeoffsAlways explicitly document the performance implications of API parameters, limit changes, and features that could significantly impact resource usage. When introducing functionality that offers a tradeoff between capabilities and performance, provide clear warnings and specific details about:elastic/elasticsearch2 discussions
- Complete API parameter documentationAPI endpoints must include comprehensive documentation for all parameters. For each parameter, clearly specify: 1. Whether it's required or optional 2. The data type and formatelastic/elasticsearch2 discussions
- Avoid flaky testsDesign tests to be deterministic and reliable across different environments. Tests that occasionally fail due to timing, race conditions, or environmental differences waste development time and reduce confidence in the test suite.elastic/elasticsearch2 discussions
- use robust test selectorsE2E tests should use stable, reliable selectors and waiting strategies to prevent flaky test failures. Prefer test IDs over CSS class names for element selection, as class names may change during refactoring and break tests. Use condition-based waits instead of arbitrary timeouts to ensure tests wait for the actual state changes rather than fixed time...dyad-sh/dyad2 discussions
- Use parameter objectsDesign API methods to accept parameter objects instead of individual parameters or complex optional fields. This approach makes interfaces more maintainable and flexible when requirements evolve, avoiding breaking changes when adding or removing fields.dyad-sh/dyad2 discussions
- separate model-specific configurationAvoid mixing model-specific features with provider-level configuration or hard-coding model-specific logic in generic handlers. This creates architectural debt and maintenance burden as new AI models are added to the system.dyad-sh/dyad2 discussions
- Maintain naming consistencyEnsure naming follows consistent patterns within the codebase and adheres to official framework conventions. When creating related types or functions, use matching naming schemes to maintain clarity and prevent synchronization issues. Prefer established conventions over custom variations unless there's a compelling reason to deviate.dyad-sh/dyad2 discussions
- Use specialized sensitive typesWhen handling sensitive data like encryption keys, choose data types based on the data's lifecycle and security requirements. Use specialized types (e.g., `EncryptionKey`) for actual sensitive data that persists in memory, as these provide memory locking and secure deletion. Use regular strings only for temporary user input that gets immediately processed...duckdb/duckdb2 discussions
- secure sensitive data handlingWhen handling sensitive data like encryption keys, passwords, or authentication tokens, avoid using standard string types that can be easily copied and may persist in memory. Instead, use specialized secure data structures that prevent accidental copying and provide controlled memory management.duckdb/duckdb2 discussions
- Preserve API backward compatibilityWhen modifying existing APIs, ensure that current usage patterns continue to work unchanged. This applies to command-line interfaces, library APIs, REST endpoints, and any client-facing interfaces. Always provide migration paths that maintain existing behavior while introducing improvements.duckdb/duckdb2 discussions
- prefer environment variablesWhen configuring behavior that needs to work across different execution contexts (CI workflows, manual runs, different build systems), prefer environment variables over command-line flags or hardcoded options. Environment variables provide broader compatibility and can be easily overridden without modifying scripts or commands.duckdb/duckdb2 discussions
- maintain formatting consistencyEnsure consistent formatting patterns and styles throughout the codebase, both when writing new code and refactoring existing code. When making style improvements or refactoring, preserve the original behavior while applying consistent formatting standards.duckdb/duckdb2 discussions
- maintain API backwards compatibilityNever modify existing stable API versions in ways that could break backwards compatibility. When adding new functionality, always introduce it in unstable API versions first before stabilizing in new releases. For serialization formats, avoid renaming existing fields - instead use property mapping or add new fields alongside deprecated ones.duckdb/duckdb2 discussions
- ensure comprehensive test coverageTests should validate all relevant code paths and actually exercise the functionality they claim to test. When adding tests for new features, ensure they stress the new behavior rather than just existing functionality that was already covered.duckdb/duckdb2 discussions
- avoid redundant computationsMove loop-invariant conditions and computations outside of iteration blocks to improve performance and reduce redundant processing. When the same check or calculation doesn't depend on loop variables, extract it to run once before the loop rather than repeating it for each iteration.duckdb/duckdb2 discussions
- Use relative documentation linksAlways use relative links instead of absolute links in documentation files to enable proper broken link detection and ensure compatibility with documentation generators like MkDocs.stanfordnlp/dspy2 discussions
- synchronize configuration environmentsEnsure configuration values remain consistent between local development and CI/CD environments, and document the rationale behind environment-specific settings. Version mismatches and undocumented configuration behavior can lead to unexpected failures and developer confusion.stanfordnlp/dspy2 discussions
- Dependency lock file managementAlways commit dependency lock files (poetry.lock, package-lock.json, etc.) to version control and maintain their consistency across development environments. Lock files ensure reproducible builds and prevent environment mismatches that can cause unexpected changes or build failures.stanfordnlp/dspy2 discussions
- AI signature consistencyEnsure AI model signatures maintain consistency between field types and descriptions, and avoid redundant prompting techniques when the desired behavior is already captured in the signature definition.stanfordnlp/dspy2 discussions
- Add comprehensive test coverageWhen introducing new functionality, always include corresponding test coverage that extends existing test infrastructure and validates the feature across multiple scenarios. This ensures robustness and maintains code quality standards.stanfordnlp/dspy2 discussions
- track migration state immediatelyEnsure migration state is recorded in the database immediately after each migration file is successfully applied, rather than batching all state updates at the end. This prevents inconsistent states where migrations are partially applied but not tracked, leaving users unable to determine which migrations have been executed.drizzle-team/drizzle-orm2 discussions
- intuitive API method designDesign API methods with intuitive names and signatures that follow established conventions and provide good ergonomics. Avoid method names that conflict with well-known patterns from other domains, and prefer streamlined method signatures that reduce unnecessary verbosity.drizzle-team/drizzle-orm2 discussions
- consistent naming patternsMaintain consistent naming conventions across similar constructs in your codebase. This includes using consistent prefixes for related methods and following established patterns for file imports and extensions.drizzle-team/drizzle-orm2 discussions
- avoid cosmetic formatting changesAvoid including purely cosmetic formatting changes in pull requests that serve a functional purpose. Automatic formatter changes (like Prettier reformatting, bracket placement, or line breaks) should be separated from functional changes to keep PRs focused and easier to review and merge.drizzle-team/drizzle-orm2 discussions
- Organize by functionalityPlace code in files that match its functionality. When functionality applies to multiple components, use a general-purpose file rather than component-specific ones. This improves maintainability and makes the codebase easier to navigate.django/django2 discussions
- AI documentation targetingWhen writing technical documentation, consider AI systems as a direct audience that may read and act upon your text. Include explicit instructions addressed to AI models that might process your content.django/django2 discussions
- Domain-appropriate data structuresDesign data structures that accurately reflect the constraints and behavior of your problem domain. Choose data types that match the natural constraints of your values, and design structural patterns that align with expected usage.wagoodman/dive2 discussions
- Use safe navigation operatorPrefer Ruby's safe navigation operator (`&.`) over explicit nil checks when calling methods on potentially nil objects. This approach makes code more readable, reduces boilerplate, and prevents NoMethodError exceptions in a clean, idiomatic way.discourse/discourse2 discussions
- Self-documenting identifiersChoose names that are immediately understandable without requiring additional context, documentation lookup, or guessing. Identifiers should clearly communicate their purpose, units, and behavior to reduce cognitive load for developers.discourse/discourse2 discussions
- Prevent async race conditionsWhen handling multiple concurrent async operations (like user input triggering API calls or messageBus updates), implement mechanisms to prevent race conditions where stale results could overwrite newer state.discourse/discourse2 discussions
- prefer async/await patternsConvert promise chains to async/await syntax for better readability, error handling, and proper cleanup operation placement. Async functions automatically return promises, so avoid redundant Promise.resolve() calls or manual promise wrapping.discourse/discourse2 discussions
- optimize data structure choicesChoose data structures that optimize for your access patterns and computational complexity requirements. When you need frequent membership testing or existence checking, prefer Set over Array to achieve O(1) lookup complexity instead of O(n) linear scanning.discourse/discourse2 discussions
- MessageBus subscription practicesWhen using MessageBus for network communication, follow these essential practices to ensure reliable message handling and prevent memory leaks: 1. **Use consistent channel names** between subscribe and unsubscribe calls to avoid subscription leaksdiscourse/discourse2 discussions
- Log errors for debuggingAlways log errors in catch blocks and use named functions to improve debugging and error traceability. Empty catch blocks make it impossible to diagnose issues, while anonymous functions provide poor stack traces.discourse/discourse2 discussions
- Limit plugin outlet APIsWhen creating plugin outlets or extension points, avoid exposing entire component instances, controllers, or large objects. Instead, pass explicit, minimal arguments that represent only the data and actions that plugins actually need.discourse/discourse2 discussions
- Control event propagationPrevent unintended network requests and interface conflicts by properly controlling event propagation in interactive elements. Use `event.stopImmediatePropagation()` when multiple event listeners on the same element or its ancestors could trigger conflicting network operations.discourse/discourse2 discussions
- Consistent text formattingEnsure text formatting follows established guidelines and maintains consistency within the same context. This applies to documentation strings, localization files, user interface text, and error messages.discourse/discourse2 discussions
- avoid dynamic test generationAvoid using loops (forEach, for, etc.) to dynamically generate tests from arrays or objects, as this pattern makes debugging significantly harder. When a test fails, it's difficult to set breakpoints on specific cases or identify which iteration caused the failure.discourse/discourse2 discussions
- Validate before accessingAlways validate preconditions before performing operations that could throw runtime errors. This includes checking object property existence, verifying context validity, and ensuring required data is available before proceeding.langgenius/dify2 discussions
- Separate AI instructionsAlways separate AI model instructions from user input to prevent prompt injection vulnerabilities and maintain clear architectural boundaries. Use system messages for AI instructions and user messages for actual user content, rather than embedding user input directly into instruction templates.langgenius/dify2 discussions
- Responsible AI managementEnsure AI models are managed responsibly throughout their lifecycle and have appropriate boundaries on their decision-making authority. When deprecating AI models, maintain backward compatibility by marking old models as deprecated rather than removing them entirely. Additionally, prevent AI models from controlling sensitive parameters that could lead to...langgenius/dify2 discussions
- prefer nullish coalescing operatorUse the nullish coalescing operator (`??`) instead of logical OR (`||`) when you want to provide default values only for null or undefined, while preserving other falsy values like empty arrays, empty strings, or zero.langgenius/dify2 discussions
- Offload heavy operationsMove heavy operations, especially those involving large data processing or bulk deletions, from synchronous request handlers to asynchronous Celery tasks. This prevents request timeouts, improves user experience, and allows for better resource management.langgenius/dify2 discussions
- Manage side effects properlyAvoid performing side effects directly in component render functions. Use useEffect for side effects like API calls, DOM manipulations, or state changes that should occur after render. Wrap functions with useCallback when they need to be optimized or used as dependencies, and use async/await for proper asynchronous handling.langgenius/dify2 discussions
- Document for team readabilityEnsure code includes appropriate documentation to improve readability and help team members understand and work with the codebase effectively. This includes adding JSDoc comments for new components and features, and preserving existing documentation patterns like internationalization keys that serve as format specifications.langgenius/dify2 discussions
- Document configuration choicesConfiguration scripts and files should clearly document non-obvious choices, especially numeric IDs, special values, and environment-specific commands. Include comments explaining the purpose and reasoning behind configuration decisions to help future maintainers understand why specific values or approaches were chosen.langgenius/dify2 discussions
- CI testing tool integrationWhen integrating new testing or analysis tools into CI pipelines, use graceful failure patterns during initial adoption phases to prevent breaking existing workflows. Add tools as development dependencies and allow them to fail without blocking builds using `|| true` until they are stable and properly configured.langgenius/dify2 discussions
- API payload structureDesign API request and response payloads to match their specific purpose rather than forcing them to conform to existing application types. When API payloads require different structures or optional fields compared to internal data models, create dedicated API-specific types instead of adding placeholder values or compromising type safety.langgenius/dify2 discussions
- React Docs With ScopeWhen adding or updating React documentation, include usage-scoped, actionable guidance—not just headings. Apply this checklist: - **Purpose (what it is):** Start with a plain-language definition.kamranahmedse/developer-roadmap2 discussions
- Consistent Network DocsEnsure all networking-related documentation uses consistent terminology, clean markdown formatting, and readable structure. Apply this standard to any page covering protocols/features like Pub/Sub, WebSockets, SSE, MQTT, etc. kamranahmedse/developer-roadmap2 discussions
- Concise Performance GuidanceWhen writing performance optimization standards/docs, keep the lead section brief and immediately actionable: provide a short overview plus a checklist of the key techniques, and move any deep technical explanation into linked resources.kamranahmedse/developer-roadmap2 discussions
- Auth-Gated ValidationApply security controls at the UI/component level and ensure input validation is centralized. 1) Auth-state gating (authorization/flow correctness) - Don’t render or enable actions when the user’s authentication state makes them invalid. Check auth state at the component boundary.kamranahmedse/developer-roadmap2 discussions
- Platform-specific configuration separationConfiguration options should be separated between common/shared settings and platform-specific settings to avoid build failures and ensure proper cross-platform compatibility. When a configuration option is not supported on all target platforms or architectures, it must be moved from common configuration files to individual platform-specific configuration...zen-browser/desktop2 discussions
- event delegation patternsWhen handling events in web applications, especially those involving network-triggered UI updates or real-time data streams, prefer event delegation over individual element listeners for better performance and maintainability. Use container-level event listeners and check the event target rather than attaching listeners to each individual element.zen-browser/desktop2 discussions
- consistent CSS spacingEnsure consistent spacing across UI components by using CSS custom properties for padding/margins and applying spacing only when elements exist. This prevents visual inconsistencies between different UI states and modes.zen-browser/desktop2 discussions
- Verify algorithm correctnessEnsure algorithms produce expected results by validating data flow and checking that all execution paths return meaningful values rather than undefined or incorrect results. Pay special attention to conditional logic that filters or processes data, and verify that functions receive the necessary arguments to perform their intended operations.denoland/deno2 discussions
- validate configuration schemasConfiguration schemas should be actively validated, well-documented, and kept up-to-date through automated testing. Use appropriate schema types (enums vs strings) based on whether values are constrained, provide comprehensive descriptions that include examples and supported formats, and implement automated tests to ensure schemas remain current with code...denoland/deno2 discussions
- Use standard API interfacesAlways prefer established API interfaces and patterns over custom or alternative approaches. This ensures compatibility, maintainability, and follows expected conventions.denoland/deno2 discussions
- remove unnecessary prefixesRemove vendor prefixes from CSS properties that have achieved sufficient browser support across modern browsers. Before removing prefixes, verify browser compatibility using resources like MDN documentation to ensure the unprefixed property is well-supported.denoland/deno2 discussions
- prevent prototype pollutionWhen implementing security measures around JavaScript's `__proto__` property, disable the setter to prevent prototype pollution attacks while carefully considering whether getter access is needed for compatibility. Prototype pollution occurs when attackers can modify Object.prototype, potentially affecting all objects in the application.denoland/deno2 discussions
- prefer efficient built-insWhen multiple built-in methods can accomplish the same algorithmic task, prefer the single comprehensive method over combining multiple operations. This reduces computational overhead, simplifies code logic, and often provides better performance characteristics.denoland/deno2 discussions
- null checks before operationsAlways check for null or undefined values before performing operations on objects, accessing properties, or calling methods. This prevents runtime errors that occur when attempting to operate on null/undefined values.denoland/deno2 discussions
- Mirror related API methodsWhen designing APIs with related method pairs (such as send/receive, input/output, or request/response), ensure their signatures and parameter structures mirror each other for consistency and developer ergonomics.denoland/deno2 discussions
- Manage async operation lifecycleWhen working with async operations, carefully manage execution context and resource references across await boundaries to prevent context corruption and resource leaks.denoland/deno2 discussions
- Extract complex inline logicWhen functions contain complex inline logic or duplicated code, extract this logic into separate functions or shared utilities to improve readability and maintainability. Complex inline code makes functions harder to understand and test, while duplication creates synchronization issues and increases the likelihood of bugs.denoland/deno2 discussions
- Enhance error message clarityError messages should be both specific about what went wrong and provide contextual information to help developers locate and fix the issue. Even in performance-critical or low-level APIs, basic validation with clear error messages is essential because "there's no easy way for the developer to get feedback on failures" otherwise.denoland/deno2 discussions
- comprehensive test verificationWrite tests that comprehensively verify functionality by covering related scenarios and testing complete outputs rather than partial matches. This approach makes tests more resilient to code changes and ensures thorough validation.denoland/deno2 discussions
- comprehensive test coverageEnsure tests cover both happy path scenarios and edge cases, including error conditions and boundary behaviors. Always wrap test code in proper test functions to leverage framework benefits like sanitizers and proper test isolation.denoland/deno2 discussions
- benchmark performance assumptionsAlways validate performance assumptions with concrete benchmarks rather than making optimization decisions based on intuition. When considering performance trade-offs between different implementation approaches, write targeted benchmarks to measure the actual impact.denoland/deno2 discussions
- avoid tooling workaroundsAvoid code patterns that require workarounds for tooling limitations or create maintenance burdens. This includes using contextual keywords as identifiers that cause formatter edge cases, and relying on @ts-ignore comments to suppress type checking.denoland/deno2 discussions
- avoid redundant observability dataWhen implementing observability features like tracing and monitoring, avoid exposing redundant information that can be inferred from existing data, and use appropriate abstraction levels rather than exposing internal implementation details through public APIs.denoland/deno2 discussions
- Explicitly Initialize InputsEnsure every required value is explicitly initialized/propagated across both configuration variants and process boundaries. Do not rely on “it will be set implicitly” behavior—new fields or external inputs can end up effectively undefined/empty.Hmbown/DeepSeek-TUI2 discussions
- Type-safe numerical algorithmsWhen implementing numerical algorithms, always use appropriate data types to prevent overflow and preserve precision: 1. Use `Nd4jLong` or `auto` instead of `int` for array indices, dimensions, and strides, especially when working with potentially large data structures:deeplearning4j/deeplearning4j2 discussions
- Prevent memory leaksAlways ensure proper memory management when using dynamic allocation. Memory leaks are a critical performance issue that can degrade application performance over time and eventually lead to resource exhaustion.deeplearning4j/deeplearning4j2 discussions
- Preserve API compatibilityWhen evolving APIs, prioritize backward compatibility to protect existing client code. Make new parameters optional whenever possible to allow existing code to continue functioning. If breaking changes are necessary, evaluate how users typically interact with your API before proceeding.deeplearning4j/deeplearning4j2 discussions
- Optimize validation checksWhen implementing validation and requirement checks, balance thoroughness with performance considerations. Critical validations should remain unconditional, but optimize their implementation to minimize performance impact:deeplearning4j/deeplearning4j2 discussions
- Optimize hardware accelerationAI systems should use the most performant hardware acceleration libraries and carefully manage hardware-specific dependencies. Prefer Intel MKL over OpenBLAS for CPU operations as it provides superior performance for matrix calculations critical to neural networks and machine learning algorithms. Keep CPU and GPU dependencies cleanly separated to support...deeplearning4j/deeplearning4j2 discussions
- Modular adaptive configurationsStructure configuration scripts with modularity and adaptability in mind. Extract repeated parameters into variables, separate parameter construction from command execution, and use dynamic detection for environment-specific values instead of hardcoding them. This approach improves readability, maintainability, and resilience to changes in the environment.deeplearning4j/deeplearning4j2 discussions
- Maintain proper capitalizationAlways use correct and consistent capitalization for product names, class names, and method names throughout code and documentation. Pay special attention to:deeplearning4j/deeplearning4j2 discussions
- Ensure test determinismCreate reliable and reproducible tests by explicitly controlling test inputs and verifying function behavior doesn't have unintended side effects. Two key practices to follow:deeplearning4j/deeplearning4j2 discussions
- Document in-code decisionsAlways include explanations for implementation decisions, non-obvious constructs, and specialized functions directly within the code as comments, rather than relying on external systems like commit messages or GitHub discussions. This practice ensures that future developers can understand the code's purpose and behavior without having to search through...deeplearning4j/deeplearning4j2 discussions
- Document AI implementation referencesWhen implementing AI algorithms or neural network operations, document the sources of specific implementation choices, especially for parameters or techniques that might appear arbitrary or unusual at first glance. Include references to established AI frameworks, research papers, or model implementations that informed your approach.deeplearning4j/deeplearning4j2 discussions
- Docs accuracy checksWhen writing documentation in code (comments, docstrings, example snippets), ensure every instruction and external link precisely matches the actual package extras and the implemented service/provider.eosphoros-ai/DB-GPT2 discussions
- Use descriptive testing namesEnsure all testing-related identifiers, scripts, and messages use clear, descriptive names rather than abbreviations or overly specific terminology. This improves maintainability and reduces confusion for both developers and users.cypress-io/cypress2 discussions
- Test version compatibilityWhen testing across different versions of dependencies, proactively address version compatibility issues to prevent compilation failures and ensure proper behavior validation. Use mocking or stubbing techniques to resolve dependency conflicts, and explicitly test version-specific behaviors including error messages.cypress-io/cypress2 discussions
- Strengthen test assertionsWrite specific, regression-proof test assertions that validate exact expected values rather than allowing ambiguous matches. Avoid assertions that could pass with incorrect but similar values.cypress-io/cypress2 discussions
- standardize API patternsEstablish consistent patterns for API design, particularly for request/response formats and parameter structures. This improves predictability, type safety, and developer experience across the codebase.cypress-io/cypress2 discussions
- Safe null access patternsAlways provide fallbacks when accessing properties or methods on values that could be undefined or null to prevent runtime errors. Use defensive programming patterns like logical OR operators, conditional checks, or nullish coalescing when available.cypress-io/cypress2 discussions
- Prioritize naming clarityChoose names and aliases that clearly communicate their purpose and meaning rather than optimizing for brevity or perceived elegance. Avoid abbreviated aliases that obscure the actual location or purpose of code elements, and resist adding premature complexity like numerical suffixes unless multiple variants actually exist.cypress-io/cypress2 discussions
- Prioritize JSX readabilityFavor inline conditional rendering in JSX over extracting logic to variables before the return statement, as it maintains better flow control visibility and reduces cognitive overhead when reading components. Additionally, use descriptive variable names that clearly convey their purpose and state.cypress-io/cypress2 discussions
- prioritize backward compatibilityWhen evolving APIs, prioritize maintaining backward compatibility over enforcing strict design constraints. Teams should choose approaches that allow existing code to continue working rather than forcing breaking changes for theoretical purity.cypress-io/cypress2 discussions
- Prefer standard terminologyUse widely accepted industry-standard names and conventions rather than descriptive but non-standard alternatives. This improves code readability and maintainability by leveraging established terminology that developers are already familiar with.cypress-io/cypress2 discussions
- optimize dynamic loadingWhen using dynamic imports, implement timing controls and strategic naming to ensure reliable and efficient resource loading. Use minimal delays (like setTimeout with 0ms) to control initialization timing and prevent race conditions that could cause failures. Additionally, use descriptive chunk names with webpackChunkName comments to create readable,...cypress-io/cypress2 discussions
- Network data encodingEnsure network-related data like URLs and IP addresses are properly encoded and typed to prevent validation failures and type mismatches. When working with network protocols, use precise types that match the actual return values and apply consistent encoding across all network operations.cypress-io/cypress2 discussions
- Improve code expressivenessWrite code that clearly communicates its intent through expressive method names and simplified control flow. Replace complex inline conditions with descriptive method calls that encapsulate the logic, and use early returns to reduce cyclomatic complexity and focus functions on their primary responsibility.cypress-io/cypress2 discussions
- ensure async synchronizationWhen dealing with async operations that depend on external systems (servers, backends, etc.), ensure proper synchronization to avoid race conditions. Don't rely on client-side polling or workarounds when the root cause is improper async handling.cypress-io/cypress2 discussions
- Document non-obvious codeAdd explanatory comments when code logic is unclear, implements workarounds, or has special reasoning that isn't immediately apparent to other developers. Comments should explain the "why" behind the implementation, not just the "what".cypress-io/cypress2 discussions
- Choose appropriate type comparisonsWhen implementing algorithms that compare or process different data types, carefully consider the level of type strictness required for your use case. Overly strict type checking (like `Object.prototype.toString`) may prevent useful operations, while overly loose checking may produce meaningless results.cypress-io/cypress2 discussions
- await promise-returning functionsAlways await functions that return promises to ensure proper asynchronous execution and avoid potential race conditions or unexpected behavior. When converting from promise chains to async/await, verify that all promise-returning function calls include the await keyword.cypress-io/cypress2 discussions
- avoid redundant I/O operationsIdentify and eliminate repeated expensive operations, particularly file system access, by implementing caching, batching, or data sharing strategies. When the same file or resource is accessed multiple times within a short timeframe, consider caching the result or restructuring the code to perform the operation once and reuse the data.cypress-io/cypress2 discussions
- Avoid brittle CSS patternsWrite CSS that prioritizes maintainability and reduces the likelihood of conflicts or brittleness. This includes using semantic class names instead of raw HTML element selectors, and avoiding explicit z-index values when possible.cypress-io/cypress2 discussions
- Functional code examplesEnsure all code examples in documentation are complete, accurate, and ready to run without modification. Since developers frequently copy and paste examples directly into their projects, include all required parameters and follow consistent patterns.crewaiinc/crewai2 discussions
- Fail securely by defaultWhen designing systems that handle sensitive operations, always default to the most secure behavior rather than prioritizing convenience. This practice applies to error handling, execution environments, and security-critical fallbacks.crewaiinc/crewai2 discussions
- Consistent configuration declarationsEnsure configuration specifications (such as version requirements, environment settings, and tool declarations) are consistent and not duplicated across project files. Redundant or contradictory configuration declarations create maintenance issues and confusion.crewaiinc/crewai2 discussions
- Review configuration constants regularlyConfiguration constants and mappings require regular maintenance to stay aligned with evolving platform capabilities. Outdated configurations can introduce unnecessary complexity, while incomplete mappings can cause functionality loss.home-assistant/core2 discussions
- Restrict administrative accessImplement proper authorization controls for sensitive operations that can modify system configuration or create new entries. Administrative functions like service calls that create config entries should be restricted to admin-level access at minimum, or better yet, exposed as scoped integration APIs rather than general-purpose services. Additionally, ensure...home-assistant/core2 discussions
- Prefer safe DOM manipulationsWhen manipulating DOM content, prefer safer alternatives to innerHTML when possible to prevent Cross-Site Scripting (XSS) vulnerabilities. For example, when clearing element content, use textContent instead of innerHTML:vuejs/core2 discussions
- Optimize build scriptsImprove CI/CD pipeline efficiency by optimizing package.json scripts. Run compatible tasks in parallel using pattern matching capabilities of your package manager, and implement thorough cleanup scripts that remove all build artifacts and caches. This reduces build times and ensures consistent build environments.vuejs/core2 discussions
- Maintain inline documentationEnsure inline code comments are accurate, current, and provide meaningful explanations for complex or unclear code sections. Comments should be updated whenever the associated code changes to prevent misleading documentation.home-assistant/core2 discussions
- comprehensive error handlingEnsure error handling mechanisms are comprehensive and graceful rather than limited or forceful. Use persistent event listeners (`process.on()`) instead of one-time listeners (`process.once()`) for critical error scenarios to handle all occurrences, not just the first one. Similarly, prefer graceful shutdown methods that allow proper cleanup over forceful...adonisjs/core2 discussions
- API response transformationWhen integrating external APIs, implement a translation layer that transforms responses into a standardized, user-friendly format. This protects consumers from upstream API changes and ensures responses are self-documenting without requiring external documentation.home-assistant/core2 discussions
- Align configurations with usageConfiguration files should accurately reflect the actual requirements and characteristics of your codebase. When setting up TypeScript configurations:vuejs/core2 discussions
- User-friendly configuration retrievalWhen retrieving configuration values like API keys or environment variables, include helpful error messages that guide users on how to fix missing configurations. Consider centralizing configuration retrieval logic in the appropriate classes based on their usage patterns.continuedev/continue2 discussions
- Use async/await patternPrefer async/await syntax over promise chains or callback patterns when working with asynchronous operations. This improves code readability, makes error handling more straightforward, and maintains consistency across the codebase.continuedev/continue2 discussions
- Mutually exclusive promisesEnsure that promises are either resolved or rejected, but never both. When handling promise resolution in callbacks or event handlers, use proper conditional logic to guarantee mutual exclusion between success and error paths.continuedev/continue2 discussions
- Logging levels hierarchyUse appropriate logging levels to prevent debug noise from leaking into production environments. Reserve console.log() for important application events, and use console.debug() for development information that should not be visible to end users.continuedev/continue2 discussions
- Layer documentation by complexityStructure documentation to be approachable for beginners while remaining comprehensive for all users. Keep main pages focused on common use cases with simplified examples, and move advanced configurations to separate, linked sections. When documenting features, start with basic usage before detailing exceptions or edge cases.continuedev/continue2 discussions
- Avoid duplicated codeIdentify and extract shared functionality between classes into reusable components. Code duplication increases maintenance burden and risk of inconsistent behavior when changes are needed.continuedev/continue2 discussions
- Workflow least-privilegeWhen writing GitHub Actions workflows, apply security best practices for (1) permissions scope and (2) trust boundaries around PR data. **1) Use least-permissive permissions**apple/container2 discussions
- Deterministic Integration TestsWhen modifying integration-test execution or environment setup, prioritize determinism and behavioral equivalence. 1) Don’t assume test-runner flags are interchangeableapple/container2 discussions
- CI Workflow Safety CheckWhen reviewing GitHub Actions used for CI/CD automation, verify three things: 1) Repo context is available - If the workflow reads files from the repository (e.g., `.github/labeler.yml`), ensure `actions/checkout` is present.apple/container2 discussions
- API Versioning And SemanticsDefine and document your public API contract with two guarantees: (1) versioning/compatibility rules, and (2) unambiguous parameter semantics (source of truth and precedence). apple/container2 discussions
- Consistent Markdown TablesWhen adding or editing tables in documentation, ensure the Markdown table is both syntactically continuous (so rows actually belong to the table) and stylististically consistent with existing docs.ossu/computer-science2 discussions
- Use structured logging frameworkPrefer structured logging frameworks like logrus over direct fmt output functions for consistency, proper log levels, and better log management. This ensures uniform logging behavior across the codebase and enables proper log level filtering and formatting.docker/compose2 discussions
- Pin git dependenciesWhen using git references for dependencies in configuration files like requirements.txt, always pin to specific commit SHAs instead of branch names to ensure reproducible builds and prevent unexpected changes from being automatically pulled in.docker/compose2 discussions
- optimize Docker layer cachingOrder Dockerfile instructions from least frequently changing to most frequently changing to maximize Docker layer caching efficiency and reduce build times in CI/CD pipelines.docker/compose2 discussions
- Isolate test dependenciesKeep test dependencies separate from production code dependencies to avoid polluting the main module. Use separate modules for test code when test-specific dependencies would otherwise be included in the main module's dependency tree.docker/compose2 discussions
- evaluate dependency API compatibilityBefore adding or updating dependencies, thoroughly evaluate API compatibility and understand the implications of using forks versus upstream versions. This prevents recurring dependency issues and ensures long-term maintainability.docker/compose2 discussions
- Document complex codeWhen code elements become complex—whether functions performing multiple operations or data structures with multiple attributes—they require proper documentation to aid understanding and maintenance. Complex functions should include docstrings explaining their purpose, parameters, and behavior. Data structures should document their attributes and types for...docker/compose2 discussions
- Document CI/CD workflows clearlyWhen documenting CI/CD processes, build pipelines, or deployment workflows, use clear and precise language that helps developers understand the sequence of operations. Write in present tense to describe what tools do, and provide explicit references when explaining examples.docker/compose2 discussions
- Avoid variable name conflictsChoose variable names that prevent conflicts with system variables, external tools, and variables in overlapping scopes. Use prefixes or distinct naming to differentiate purpose and avoid unintended overrides.docker/compose2 discussions
- Avoid hardcoded configuration valuesConfiguration values should be parameterized rather than hardcoded in scripts and tools. Hardcoded values make code less reusable and require manual updates when used in different contexts or projects.docker/compose2 discussions
- avoid external test dependenciesTests should not depend on external resources like real URLs, remote servers, or external APIs as these dependencies make tests flaky and unreliable. Instead, use local mock servers, stub responses, or dependency injection to simulate external behavior.docker/compose2 discussions
- Avoid confusing namesChoose clear, unambiguous names that don't shadow existing identifiers or create confusion about their purpose. Avoid variable names that shadow method names, class names, or built-in functions, as this makes code harder to understand and can suggest incorrect behavior like recursive calls.docker/compose2 discussions
- Use optional chaining operatorsUse optional chaining (`?.`) and nullish coalescing (`??`) operators instead of manual null checks to safely access nested properties and provide fallback values. These operators prevent runtime errors when dealing with potentially null or undefined values and result in cleaner, more readable code.comfyanonymous/ComfyUI2 discussions
- Structure documentation comprehensivelyDocumentation should provide complete, practical information while maintaining logical organization and information hierarchy. Ensure sections include all necessary details for users to successfully implement or understand the feature, and organize content to flow logically from basic to advanced concepts.comfyanonymous/ComfyUI2 discussions
- Optimize tensor operation chainsWhen working with PyTorch tensors, look for opportunities to optimize operation chains for better performance and memory efficiency. This involves two key strategies:comfyanonymous/ComfyUI2 discussions
- leverage native configuration featuresWhen configuring applications in containerized environments, prefer using the application's built-in configuration mechanisms over extensive external configuration like multiple volume mounts or environment variable overrides. This approach reduces complexity, improves maintainability, and leverages the application's intended configuration patterns.comfyanonymous/ComfyUI2 discussions
- Container security best practicesImplement comprehensive security measures in containerized applications to prevent privilege escalation, injection attacks, and unauthorized access. This includes proper user configuration, variable quoting, and secure process handling.comfyanonymous/ComfyUI2 discussions
- centralize configuration constantsConfiguration values, constants, and default settings should be defined in a single location and referenced from there, rather than duplicated across multiple files or functions. This prevents inconsistencies, reduces maintenance burden, and ensures that changes to configuration values only need to be made in one place.comfyanonymous/ComfyUI2 discussions
- avoid hardcoded valuesReplace hardcoded styling values and configuration constants with flexible alternatives to improve maintainability and consistency. Use CSS variables for colors and theming, backend-provided values for limits and ranges, and semantic CSS properties instead of absolute positioning.comfyanonymous/ComfyUI2 discussions
- AI hardware platform supportAI applications must properly handle different GPU platforms (NVIDIA CUDA, AMD ROCm, Iluvatar Corex, etc.) through both build-time configuration and runtime capability detection. This ensures models can run efficiently across diverse hardware environments.comfyanonymous/ComfyUI2 discussions
- Workspace version configurationStandardize version management across multi-crate Rust projects by using workspace versioning. This reduces duplication and ensures consistency across all crates in your project.openai/codex2 discussions
- Verify state before executionWhen scheduling asynchronous operations in concurrent environments, always verify the system state hasn't changed before executing critical operations to prevent race conditions. This is especially important in interactive applications where user actions (like cancellations) might occur between the time an operation is scheduled and when it executes.openai/codex2 discussions
- Validate persisted selectionsWhen accepting previously recorded state (digests, coverage manifests, etc.), revalidate it against the current computed/authoritative data before proceeding. If the value no longer matches, fail fast with a message that tells the user exactly what to do next. If you tighten validation rules, preserve backward compatibility by versioning the stricter...openai/codex-security2 discussions
- Stream and Exclude for SpeedOptimize scan/diff/hash pipelines by (1) preventing large in-memory buffering and (2) shrinking the input set early. Apply these rules: - Measure first: when changing digest/patch handling, record memory/size deltas on realistic fixtures (e.g., large binary diffs) and use deterministic comparisons (streaming output must match buffered output).openai/codex-security2 discussions
- Race-safe concurrencyWhen multiple workflow runs mutate or publish to the same shared external resource (labels, registries, “latest”), make synchronization explicit and resource-scoped, and handle conflicts by re-verifying state before proceeding.openai/codex-security2 discussions
- Public API Contract CompletenessWhen adding or extending an API/CLI surface that routes to backend providers, ensure the *public contract* is fully implemented end-to-end and that the payloads you generate for downstream systems are deterministic.openai/codex-security2 discussions
- Secure CI/CD pipelinesImplement strict security controls in continuous integration and deployment workflows: 1. Pin external GitHub Actions to immutable commit hashes rather than mutable tags:openai/codex2 discussions
- Provider-agnostic API designDesign your API interfaces to be provider-agnostic rather than tightly coupled to specific service providers. This improves flexibility, maintainability, and makes future provider changes less disruptive.openai/codex2 discussions
- Provider-agnostic AI codeDesign AI integration code to be provider-agnostic, avoiding assumptions that all models will come from a single provider. Implement explicit handling for known models while maintaining fallback mechanisms for others.openai/codex2 discussions
- Proper package.json structureMaintain clean and properly structured package.json files by following these principles: 1. Categorize dependencies correctly - place development tools and testing libraries in `devDependencies`, not in regular `dependencies`. This ensures smaller production builds and clearer dependency management.openai/codex2 discussions
- Pin external action dependenciesUse full commit hashes instead of version tags when referencing third-party GitHub Actions in workflows to prevent unexpected behavior changes if the action is modified at its source. This ensures reproducible builds and improves security by protecting against supply chain attacks.openai/codex2 discussions
- Configure loggers consistentlyAlways configure module-level loggers with a consistent pattern across the codebase. Use `logging.getLogger(__name__)` to create loggers that match the module hierarchy, set appropriate default levels (typically WARNING for library code), use standardized formatting that includes timestamp, logger name, level, and message, and provide mechanisms to adjust...salesforce/cloudsplaining2 discussions
- Use null meaningfullyChoose between null and undefined based on semantic intent rather than convenience. Use null when operations can explicitly fail and you want to represent that failure state, allowing consumers to handle it appropriately. Use optional properties (?) when a value may simply not be provided or initialized.cline/cline2 discussions
- Timeouts With Safe BiasWhen adding timeouts around external/IPC checks (especially those triggered from UI/closing handlers), ensure you both bound execution time *and* choose a timeout fallback that favors the lowest-impact, most likely failure.CLINE/CLINE2 discussions
- Test user interaction contractsWhen you change keyboard handling or interactive UI elements, update tests to lock in the user-visible interaction contract—not just internal logic. Concretely:Cline/Cline2 discussions
- Test Shortcut PropagationAdd targeted tests whenever keyboard shortcut logic changes to prevent accidental shortcut/event leakage. Requirements: - Verify shortcut suspension lifecycle: if your code uses a suspension mechanism (e.g., `suspendShortcuts()` + `areShortcutsSuspended()`), include a unit test that proves shortcuts remain inactive until *all* suspensions are released.cline/CLINE2 discussions
- Test Interaction BoundariesWhen code changes affect keyboard/focus behavior or interactive UI semantics, add regression tests that prove the intended interaction boundary. Apply this by:CLINE/cline2 discussions
- Targeted API DecisionsWhen an API call is made to decide what to show/enable or what to persist, ensure the API usage is precise, consistent with the correct source of truth, and race-safe.Cline/Cline2 discussions
- Stable API Evolution RulesWhen evolving any API surface that produces structured, machine-readable data (JSON event streams, protobuf messages), design for safe evolution: 1) Document a stable parse contractcline/CLINE2 discussions
- Safe Startup Error HandlingFor startup/OS-specific code paths, handle failures predictably: don’t panic on edge cases; when recovery is possible, retry with backoff; when you must fail, surface bounded, non-sensitive diagnostics.cline/CLINE2 discussions
- Safe Own-Property LookupsWhen you look up values in plain objects using strings derived from user input (e.g., file paths, names, extensions), only accept *own* properties. Use `Object.hasOwn(...)` (or `Object.prototype.hasOwnProperty.call`) so special/inherited keys like `__proto__`, `constructor`, and `toString` can’t influence results.ClInE/cLiNe2 discussions
- Respect runtime constraintsWhen UI behavior depends on the user’s environment, resolve it at runtime with safe defaults (clamping) and preference-aware behavior to prevent jank, layout collapse, and unnecessary animation work.cline/CLINE2 discussions
- Remove production console logsConsole logs should not appear in production code, especially debug statements that can expose sensitive information or clutter output. When error logging is necessary, log detailed information internally while presenting sanitized messages to users.cline/cline2 discussions
- Pin deps, run testsFor CI/CD, make builds deterministic and ensure verification steps actually run. - Dependency determinism: allow semver ranges in `package.json` (e.g., caret), but require CI to install using a frozen/pinned lockfile so the resolved versions are consistent across runs.Cline/Cline2 discussions
- organize environment configurationsEnvironment variables in CI/CD workflows should be organized consistently using structured `env` sections rather than inline declarations, and should account for platform-specific requirements. This improves maintainability, readability, and prevents environment-related failures across different operating systems.cline/cline2 discussions
- optimize workflow maintainabilityDesign CI/CD workflows for long-term maintainability by using consolidated commands and extracting reusable components. Instead of listing individual build steps that may change over time, prefer consolidated npm scripts like `npm run pretest` that encapsulate the full build process. This approach reduces the need to update workflows when underlying build...cline/cline2 discussions
- Locale and semantic UIAdopt UI composition rules that keep both text and interactions correct, readable, and accessible. 1) Localize and compose strings safely - Avoid hardcoded concatenation/punctuation (e.g., manual `", "` joins, ad-hoc prefixes/suffixes).ClInE/cLiNe2 discussions
- isolate mock configurationsWhen using Vitest mocking, avoid multiple `vi.mock` calls for the same module within a single test file, as mock calls are hoisted and can interfere with each other. Instead, organize tests requiring different mock configurations into separate test files or test suites with proper setup/teardown.cline/cline2 discussions
- Idempotent React InitializationEnsure React components that are shown/hidden or re-initialized during async reconnects preserve user state while preventing unintended re-bootstrapping.CLINE/cline2 discussions
- Handle async operations safelyAlways wrap asynchronous operations in try-catch blocks to prevent unhandled promise rejections and provide graceful error recovery. This is especially important for browser APIs that may fail due to user permissions, network issues, or browser compatibility.cline/cline2 discussions
- Generation-Based Cache InvalidationWhen caching async results, ensure stale responses can’t overwrite fresh data, and only refetch when the cached value’s lifecycle actually changes. **Rules**ClInE/cLiNe2 discussions
- Fail safely and recoverWhen handling startup/runtime failures, ensure code (1) never panics on expected edge cases, (2) captures only safe, bounded diagnostics, and (3) recovers deterministically with explicit timeouts/backoff that tolerate real OS/process semantics.Cline/Cline2 discussions
- Explicit UI State ModelingWhen UI behavior depends on time, repeated events, streaming content, or resize, implement it with explicit state modeling (state machine + invariants), not ad-hoc event heuristics.CLINE/CLINE2 discussions
- Event-Driven State InvariantsWhen implementing UI/device event behavior (key holds, scrolling, resize compensation), treat the logic as an explicit state machine with clear invariants: track the source of events, preserve correctness across async updates, and don’t infer “intent” from ambiguous signals.CLINE/cline2 discussions
- Ensure CI reproducibilityKeep CI pipelines deterministic and comprehensive: - Reproducible dependencies: allow `@ai-sdk/*` (or similar) dependencies to use caret ranges for normal maintenance, but ensure CI installs with a frozen lockfile so the build uses the exact pinned versions.CLINE/cline2 discussions
- Durable, idempotent orchestrationMulti-step orchestrated operations (git push + task creation, remote command execution, etc.) must tolerate process restarts, disconnects, and retries without producing duplicate side effects or hanging indefinitely. Avoid storing critical orchestration state only in ephemeral, process-local structures (e.g., in-memory WeakMaps in a sidecar); if a step can...cline/cline2 discussions
- Document configuration assumptionsWhen documenting configuration settings, environment setup, or system requirements, explicitly state assumptions about the target environment and provide accurate default values. Avoid making implicit assumptions that may not apply to all users or deployment scenarios.cline/cline2 discussions
- Document caveats accuratelyWhen documenting behavior, never leave exception cases implicit. **Standard** 1. **Use a dedicated “Caveats” (callout) section/table** for any rule that has exceptions, ignored inputs, timeouts, or different behavior by environment (CLI vs extension vs provider, OS, etc.).cline/CLINE2 discussions
- Document and Verify ConfigFor any feature flags/rollout settings or build/packaging configuration that affects runtime behavior, ensure (1) the docs accurately describe the exact config key, supported values, and override/rollout semantics, and (2) packaging/ignore rules are verified against the actual tool/script defaults so you don’t keep stale or redundant entries.cline/CLINE2 discussions
- Doc as Parsing ContractTreat docs for CLI/SDK outputs as a strict, parseable contract. - Match reality: ensure every documented option, default, ordering, and behavior is consistent with `--help`/implementation. If an option is omitted/unsupported or would be “accepted but ignored,” remove it from the contract tables rather than implying it can be relied on.Cline/Cline2 discussions
- Deterministic deps and testsEnsure CI/CD runs with deterministic dependencies and executes all intended test suites. - Deterministic installs: keep dependency version intent in `package.json` (e.g., caret ranges), but make CI (and release builds) install using the lockfile in frozen mode so results are reproducible.CLINE/CLINE2 discussions
- Deterministic Builds, Verified TestsIn CI/CD, keep builds reproducible and ensure newly added verification steps actually run. 1) Dependency determinism via frozen lockfiles - It’s OK to use caret ranges in `package.json` (e.g., `@ai-sdk/*`), but CI/builds must install with a frozen lockfile so the resolved versions are pinned and PR scope stays predictable.ClInE/cLiNe2 discussions
- Deterministic API DecisionsWhen an app’s behavior depends on an external API, ensure the API call is both necessary (authoritative) and deterministic (verifiable). Concretely: 1) Don’t add “auxiliary” API calls when existing state already determines the outcome equivalentlyCLINE/CLINE2 discussions
- Cross-platform config correctnessConfiguration guidance must be a precise, testable contract across environments: don’t assume path expansion semantics (like `~`) work identically on all OSes, and don’t duplicate packaging rules that the tooling already enforces.Cline/Cline2 discussions
- Consistent identifier semanticsWhen code exposes an identifier outward—via UI semantics (ARIA) or via string-based integration points (paths/keys/command names)—make it match the contract expected by the consuming layer.CLINE/CLINE2 discussions
- Configure formatting tools consistentlyProperly configure development tools to maintain consistent code formatting across the entire codebase and development environments. This includes setting up formatter ignore files, git attributes, and other configuration files that ensure uniform code style regardless of developer setup or platform differences.cline/cline2 discussions
- Canonical naming consistencyUse canonical, consistently normalized identifiers across layers so the same concept is easily verifiable in code. Apply this in two ways: 1) Match existing consumer normalization (e.g., whitespace handling) where the system already expects it.ClInE/cLiNe2 discussions
- avoid unnecessary custom hooksBefore creating custom hooks, evaluate whether existing solutions or simpler patterns can address the need. Custom hooks should provide clear value beyond what's available through established libraries, built-in React patterns, or direct component logic.cline/cline2 discussions
- Avoid premature memoizationDon't automatically reach for useMemo and useCallback for every computation or function. These hooks add complexity and should only be used when there's a measurable performance benefit. Consider the actual cost of the operation and frequency of re-renders before memoizing.cline/cline2 discussions
- Avoid lock-held blockingWhen code performs concurrent I/O and lifecycle management, apply these rules: 1) Don’t hold broad/shared locks across blocking work - Pattern: acquire the shared map/registry lock only long enough to locate/clone a per-session handle; immediately release it before calling anything that can block (e.g., `write_all`, `wait`, `read`).CLINE/CLINE2 discussions
- API Contract AlignmentEnsure API/event schemas and field names stay consistent across all products and generated artifacts. Apply this standard when you add/rename fields in request/response payloads, tool/event hooks, or persisted protocol types.Cline/Cline2 discussions
- Analyze async operation dependenciesBefore choosing between sequential awaits and parallel execution (Promise.all), carefully analyze whether operations have dependencies that require specific execution order. Operations that depend on each other's results or shared state must be executed sequentially to prevent race conditions.cline/cline2 discussions
- AI provider consistencyEnsure consistent patterns and configurations across all AI model providers to maintain code maintainability and scalability. This includes providing proper default configurations for all providers and minimizing provider-specific conditional logic that can become unwieldy as more AI models are integrated.cline/cline2 discussions
- AI capability documentationWhen documenting AI systems, models, or assistants, ensure technical terminology is precise and capabilities are clearly scoped. Use consistent language to describe what the AI can and cannot do, avoiding vague or overstated claims. For AI agents or assistants, explicitly detail their tools, permissions, and limitations.cline/cline2 discussions
- Accurate, Cross-Platform DocsWhen updating technical documentation, ensure it is operationally accurate across supported platforms and matches the actual behavior of the software.CLINE/CLINE2 discussions
- Write focused, clear testsTests should be simple, focused on a single concern, and easy to understand. When a test combines multiple potential failure conditions or verification points, split it into separate, focused test cases. Avoid over-engineering tests with unnecessary complexity.ClickHouse/ClickHouse2 discussions
- Recognize nullable type contextBefore adding nullable casts or special null handling logic, verify whether the type or context already provides the necessary nullability semantics. This prevents redundant operations and ensures appropriate handling of different type categories.ClickHouse/ClickHouse2 discussions
- preserve existing environment variablesWhen modifying environment variables in code, always preserve existing values by appending or merging rather than overwriting. This prevents breaking existing configurations that may have been set by the system, other tools, or previous code execution.ClickHouse/ClickHouse2 discussions
- Document implementation rationaleWhen implementing networking or system-level functionality where multiple approaches exist, always document the rationale behind your implementation choice. This is especially critical when the chosen method may not be the most obvious one or when platform-specific considerations influence the decision.ClickHouse/ClickHouse2 discussions
- Document API parameters inlineWhen designing APIs, prioritize clarity and self-documentation by adding inline comments for non-obvious parameters and choosing descriptive method names. This reduces the need for external documentation and makes the code more maintainable.ClickHouse/ClickHouse2 discussions
- consistent mutex protectionEnsure consistent mutex usage across all access points to shared data structures and clearly document what each mutex protects. Inconsistent locking can lead to race conditions, data corruption, and crashes.ClickHouse/ClickHouse2 discussions
- Comprehensive database testingDatabase tests should verify both query execution and optimization behavior through comprehensive scenario coverage. When testing query optimizations, include EXPLAIN PLAN verification to ensure the optimizer produces expected execution plans. For database features like row policies or security constraints, test multiple scenarios including edge cases and...ClickHouse/ClickHouse2 discussions
- avoid redundant cache lookupsWhen implementing cache functionality, avoid performing the same cache lookup multiple times. Instead, store and reuse the result from the first lookup to improve performance.ClickHouse/ClickHouse2 discussions
- verify downloaded file integrityAlways verify the integrity of downloaded files before using them, especially in security-sensitive applications. At minimum, validate downloaded files using checksums (SHA256, etc.) provided by the source. For higher security requirements, implement cryptographic signature verification using GPG keys.snyk/cli2 discussions
- Use file locksWhen multiple processes or goroutines need to access shared file system resources concurrently, use file locks (flock) to prevent race conditions and ensure mutual exclusion. This is particularly important for operations like certificate file management, directory creation, and other file system modifications that could conflict.snyk/cli2 discussions
- Use descriptive parameter namesParameter names should clearly indicate their purpose and avoid ambiguity or conflicts with existing constructs in the codebase context. Names should be self-explanatory without requiring additional comments or context to understand their function.snyk/cli2 discussions
- Use descriptive identifier namesChoose specific, descriptive names for variables, functions, types, and parameters that clearly indicate their purpose and avoid generic terms that could be overloaded or ambiguous. Generic names like `Command`, `Config`, or `Data` can become confusing when multiple similar concepts exist in the same codebase.snyk/cli2 discussions
- separate build from runtimeDependencies and build requirements should be installed during Docker image creation or environment setup, not in runtime execution scripts. This separation improves pipeline reliability, reduces execution time, and maintains clear boundaries between build and deployment phases.snyk/cli2 discussions
- maintain CI/CD boundariesEnsure clear separation between different CI/CD concerns and maintain accurate documentation of automated processes. Release artifacts like release notes should not be committed to main development branches, and testing workflows should be clearly documented with accurate branch-specific behaviors.snyk/cli2 discussions
- maintain build environment parityEnsure that local development and CI/CD environments use identical build commands and dependency management strategies to prevent deployment issues and environment drift. When introducing local-specific build targets, consider whether the same approach should be adopted in CI pipelines to maintain consistency.snyk/cli2 discussions
- Explain complex logicAdd explanatory comments for non-obvious code sections, complex business logic, and public methods to clarify their purpose and reasoning. Comments should explain the "why" behind decisions and the "what" for functions that aren't immediately clear from their implementation.snyk/cli2 discussions
- API interface designDesign interfaces that balance simplicity with extensibility. Consolidate related parameters into cohesive data structures to reduce interface complexity, while using interfaces to enable future implementations and maintain flexibility.snyk/cli2 discussions
- Fail fast principleWhen writing security-sensitive shell scripts, use strict error handling to fail immediately on errors rather than attempting fallbacks or continuing silently. Always include `set -euo pipefail` to exit on errors, treat unbound variables as errors, and propagate pipeline failures. This prevents partial application of security configurations that could leave...anthropics/claude-code2 discussions
- Maintain naming consistencyEnsure field names, method names, and identifiers are consistent across different contexts including cross-language SDKs, API specifications, and data structures. When multiple naming options exist, prioritize alignment with established patterns and accurate representation of the underlying functionality or data.anthropics/claude-agent-sdk-python2 discussions
- Verify automated documentationWhen using automated tools to generate documentation, always verify the output for accuracy and document any additional manual steps required for completion. Automated documentation can inherit incorrect properties or miss crucial steps in the process.chef/chef2 discussions
- Structure CI/CD scriptsImprove CI/CD shell scripts' readability and maintainability by using appropriate shell script patterns. Use heredocs for multiline output generation (especially for YAML configurations) and extract repetitive operations into functions. This approach reduces duplication, makes scripts easier to understand, and simplifies future updates.chef/chef2 discussions
- Standardize bash error-handlingAlways use `set -eou pipefail` at the beginning of bash scripts to ensure consistent and robust error handling. This combination ensures scripts fail immediately on errors (`-e`), treat unset variables as errors (`-u`), and properly handle pipeline failures (`-o pipefail`), preventing silent failures and making debugging easier.chef/chef2 discussions
- Log message qualityEnsure all log messages are consistent in formatting and clear in purpose. Complete sentences in logs should end with proper punctuation (especially periods), and messages should precisely describe what is happening in the system. When logging phase transitions or significant events, explicitly state where one phase ends and another begins rather than using...chef/chef2 discussions
- Use correct encryption propertiesWhen configuring security features in Azure ARM templates, always use the correct property names as specified in the Azure documentation. For double encryption of Azure Compute disks, use "enableDoubleEncryption" rather than "doubleEncryptionEnabled". Using incorrect property names may result in security features not being properly applied, potentially...bridgecrewio/checkov2 discussions
- Target core resourcesWhen implementing network security checks for serverless functions like AWS Lambda, ensure you target the core function resources rather than just their endpoints. Security checks for configurations like CORS policies should be applied to the primary Lambda resources (`AWS::Lambda::Function`, `aws_lambda_function`) rather than only their URL interfaces...bridgecrewio/checkov2 discussions
- Secure API endpointsAlways configure proper authorization for API endpoints to prevent unauthorized access to back-end resources. Avoid combinations that create open access, such as using `AuthorizationType.NONE` together with `api_key_required=False` in API Gateway configurations.bridgecrewio/checkov2 discussions
- Minimize workflow complexityKeep GitHub Actions workflows efficient and maintainable by eliminating redundant configurations and ensuring comprehensive test coverage: 1. **Avoid redundant environment variables** - Use the minimum number of variables needed to achieve your workflow goals. When one variable can be derived from another, don't store both.bridgecrewio/checkov2 discussions
- Lambda CORS protectionWhen implementing network security checks for AWS Lambda functions, ensure that CORS (Cross-Origin Resource Sharing) policies are verified on the core Lambda function resources, not just on function URL endpoints. This prevents open CORS policies that could expose your Lambda functions to unauthorized cross-origin requests.bridgecrewio/checkov2 discussions
- Implement pre-commit hooksAutomate quality and security checks by implementing pre-commit hooks in your Git repositories to catch issues early in the development process. Pre-commit hooks run specified checks automatically when files change, before code is committed, helping to enforce standards without manual intervention.bridgecrewio/checkov2 discussions
- Ensure dependency compatibilityWhen adding or updating dependencies in configuration files (Pipfile, requirements.txt), ensure compatibility with all supported Python versions in the project. Generated lock files and specific version constraints should work with the minimum supported Python version to prevent CI failures or production issues.bridgecrewio/checkov2 discussions
- Configure security scanners completelySecurity scanning tools must be fully configured to maximize detection capabilities. When implementing tools like Checkov in CI/CD pipelines: 1. For Docker-based scanners, use the `--tty` flag for better output handling:bridgecrewio/checkov2 discussions
- Azure encryption property namesWhen configuring encryption settings for Azure resources in ARM templates, always use the correct property names as documented in the Azure API specifications. Specifically for Azure Compute disks, use `enableDoubleEncryption` instead of `doubleEncryptionEnabled` to configure double encryption. Using incorrect property names can result in security...bridgecrewio/checkov2 discussions
- Optimize AI interactionsWhen working with AI models and LLMs, optimize both prompts and input data to improve model performance and reduce token usage. For prompts, be specific about the AI's role, requirements, and expected output format rather than using vague instructions. For input data, preprocess and clean content to remove unnecessary elements that could confuse the model...ChatGPTBox-dev/chatGPTBox2 discussions
- Context-aware null checkingChoose null checking patterns based on your function's purpose and intended behavior with empty values. For functions with fallback strategies, consider whether empty strings should trigger alternative methods or be treated as valid results.ChatGPTBox-dev/chatGPTBox2 discussions
- Synchronized Async HandoffsWhen delegating work to concurrent/asynchronous execution (tasks, workers, background processes), ensure: 1) **State ordering:** the async code cannot observe missing/partial state. For DB-backed workflows, enqueue/start tasks only after the transaction commits.celery/celery2 discussions
- Protocol-Safe EncodingAny data placed into connection URIs or transmitted over the network (e.g., JSON payloads/headers) must be encoded/serialized according to the protocol’s rules.celery/celery2 discussions
- Celery Integration CorrectnessCelery should only execute tasks when its assumptions about state and message format are guaranteed. Apply these rules: 1) Django: trigger tasks after the DB commitcelery/celery2 discussions
- Api examples clarityAPI docs and interface examples must be unambiguous and cover defaults. Apply this standard when writing or updating API documentation: - **Validate example syntax**: For query strings, use **one** `?` to start the query and **`&`** for every additional parameter. Avoid ambiguous/incorrect examples like multiple `?` in the same query string.celery/celery2 discussions
- Use unstable_cache directlyWhen implementing server-side caching in Next.js applications, prefer using `unstable_cache` with direct repository method calls instead of tRPC callers. This approach provides better performance and proper integration with Next.js caching mechanisms.calcom/cal.com2 discussions
- Specify stable dependency versionsAlways use specific semantic versions or caret ranges for stable releases in package.json and other dependency configuration files. Avoid using "latest" or development/pre-release versions as they can introduce unpredictable behavior and breaking changes that affect build reproducibility and team consistency.calcom/cal.com2 discussions
- optimize component memoizationWhen implementing React.memo for performance optimization, ensure props are structured to enable effective memoization. Pass individual primitive props separately rather than complex objects to allow React.memo to correctly detect unchanged props and prevent unnecessary re-renders.calcom/cal.com2 discussions
- CI conditional job handlingWhen implementing CI workflows with path-based filtering, ensure that conditional jobs don't inadvertently block PR merges when they don't execute. Maintain proper path filtering to run jobs only when relevant files change, but account for scenarios where filtered jobs are listed as required dependencies.calcom/cal.com2 discussions
- Centralize workflow schedulingAvoid scattering workflow scheduling logic across multiple handlers. Instead, create dedicated service methods for different workflow contexts to improve maintainability and reduce duplication.calcom/cal.com2 discussions
- Validate workflow filesEnsure all CI/CD workflow configuration files are validated for accuracy and consistency. Small errors in workflow files can prevent automation from triggering correctly or cause unexpected behavior. Pay special attention to:oven-sh/bun2 discussions
- Validate network inputsNetwork code must validate all inputs and handle error conditions properly to prevent security vulnerabilities and reliability issues. This includes: oven-sh/bun2 discussions
- Validate loop boundary conditionsWhen implementing iterative algorithms, ensure comprehensive handling of edge cases and boundary conditions. This includes: 1. Using while loops instead of if-else chains for repetitive operationsoven-sh/bun2 discussions
- Use branch predictionOptimize performance-critical algorithms by using branch prediction hints to guide the CPU. Add `UNLIKELY` macros for error conditions, boundary checks, or exceptional cases that rarely evaluate to true, and `LIKELY` for common execution paths. This helps the CPU's branch predictor make better decisions, reducing pipeline stalls and improving execution...oven-sh/bun2 discussions
- Thread-safe state transitionsWhen modifying shared state in multithreaded code, implement proper checks and state transitions to prevent race conditions. This applies to flags, counters, and resource management.oven-sh/bun2 discussions
- Path comparison precisionWhen implementing file path matching or exclusion algorithms, use precise comparison techniques that respect directory boundaries rather than simple string operations. Naïve prefix matching using `startsWith()` can lead to unexpected behavior by accidentally matching unrelated paths that share prefixes.oven-sh/bun2 discussions
- Optimize database interactionsWhen working with database operations, prioritize efficiency by avoiding redundant query executions. Instead of executing statements multiple times to gather different pieces of information (like metadata or column types), cache or collect all necessary data during the initial execution.oven-sh/bun2 discussions
- Match API conventionsEnsure API implementations match established conventions and reference implementations to maintain compatibility and predictability. When implementing APIs that parallel existing systems (like Node.js APIs or REST services), follow their error codes, response formats, and naming conventions precisely.oven-sh/bun2 discussions
- Judicious move semanticsApply C++ move semantics and lambda modifiers only when necessary. The `mutable` keyword should only be used in lambdas when you need to modify captured variables, including when using move operations on them:oven-sh/bun2 discussions
- Initialize default valuesAlways initialize class attributes with default values to prevent AttributeError exceptions when accessing potentially undefined values. Use defensive coding patterns:oven-sh/bun2 discussions
- Hide implementation detailsWhen designing APIs, carefully consider which elements of your implementation become part of the public interface. Avoid exposing internal types, naming patterns, and implementation details that could confuse API consumers or lock you into supporting implementation details as part of your contract.oven-sh/bun2 discussions
- Function invocation syntaxUse the appropriate invocation syntax for functions based on their intended usage. Regular functions should be called directly without the `new` keyword, while constructor functions (typically capitalized) should be instantiated with `new`.oven-sh/bun2 discussions
- Follow standard API specificationsEnsure API implementations strictly adhere to published specifications, even when adding features or optimizations. Deviating from standard behavior can create compatibility issues with other implementations (like Node.js) that rely on specification-compliant behavior.oven-sh/bun2 discussions
- Document configuration variationsWhen documenting or implementing configuration options, always include variations needed for different environments and use cases. Ensure that your configuration files, installation guides, and rule definitions cover all common scenarios.oven-sh/bun2 discussions
- Cache repeated accessesWhen accessing the same property or calling the same function multiple times, especially in loops or performance-critical sections, cache the result in a local variable. This reduces redundant memory access operations and improves execution speed.oven-sh/bun2 discussions
- validate connection timeoutsAlways validate network connection states and implement explicit timeout handling to prevent zombie connections and ensure robust network operations. Connection objects can appear valid while actually being disconnected, and network operations without timeouts can hang indefinitely.browser-use/browser-use2 discussions
- preserve exception contextWhen handling exceptions, always preserve the original error context to aid in debugging and error diagnosis. This involves two key practices: (1) Include the exception class name when converting exceptions to strings, and (2) Use exception chaining when re-raising exceptions.browser-use/browser-use2 discussions
- organize tests by categoryStructure test suites into clear, logical categories and run them as separate CI jobs for better parallelization, maintainability, and failure identification. This approach makes it easier to understand test failures, enables targeted testing, and improves CI performance through parallel execution.browser-use/browser-use2 discussions
- Model initialization formattingMaintain consistent formatting when initializing AI models and agents. Use proper spacing around assignment operators and consistent indentation for constructor parameters to improve code readability and follow Python style conventions.browser-use/browser-use2 discussions
- Maintain configuration consistencyWhen modifying configuration settings, especially environment variables, ensure changes are consistent with existing codebase usage patterns and maintain backward compatibility. Before changing configuration names or values, audit the codebase to understand current usage and dependencies.browser-use/browser-use2 discussions
- Document configuration decisionsConfiguration files should be self-explanatory and maintainable by including explicit version constraints and explanatory comments for non-obvious choices. This prevents future confusion and ensures reproducible environments.browser-use/browser-use2 discussions
- Configuration documentation completenessConfiguration documentation should include all necessary constraints and limitations while avoiding redundant information that's already documented elsewhere. Always document critical constraints that could cause runtime issues, such as resource conflicts or usage limitations. Remove duplicate explanations that repeat information available in other parts of...browser-use/browser-use2 discussions
- Avoid logging sensitive contentBe cautious about what data gets included in log messages to prevent security risks and performance issues. Before logging file contents or user data, consider whether it could contain:browser-use/browser-use2 discussions
- Avoid hardcoded API assumptionsAPI interfaces should not contain hardcoded implementation details or assume specific underlying technologies. Instead, make them configurable and implementation-agnostic to support different backends and configurations.browser-use/browser-use2 discussions
- Resolve naming conflicts clearlyWhen naming components, packages, or files that conflict with existing names in your system or related ecosystems, follow a systematic approach to ensure uniqueness while maintaining semantic clarity:Homebrew/brew2 discussions
- Prefer flags over conditionalsWhen implementing environment-specific or version-dependent behavior, use feature flags or configuration variables instead of complex conditional logic. This approach makes configuration management more maintainable and easier to adjust when requirements change.Homebrew/brew2 discussions
- Pin GitHub actionsAlways pin GitHub Actions to specific commit hashes rather than version tags (like @v4). Using version tags is a security vulnerability as the tag owner could change what commit the tag points to, potentially introducing malicious code into your workflow. This is a common supply chain security best practice.Homebrew/brew2 discussions
- Document configuration decisionsWhen making configuration changes, especially those that deviate from standard practices or involve deprecation notices, always include clear explanatory comments. Temporary modifications to configuration settings should document both the reason and expected duration of the exception.Homebrew/brew2 discussions
- Decouple CI from codeSeparate CI configuration from code that serves other purposes. When variables or settings affect both user-facing behavior and CI pipeline behavior, extract CI-specific logic into dedicated configuration files. This prevents unintended CI pipeline changes when updating user-facing functionality and allows for better coordination between code changes and CI...Homebrew/brew2 discussions
- Use appropriate comment syntaxChoose the correct comment syntax based on the file type and processing system to ensure documentation serves its intended purpose. For template files (like Jinja), use template-specific comments rather than HTML comments to prevent documentation from appearing in rendered output. Always include explanatory comments for files that might seem unnecessary but...boto/boto32 discussions
- Keep CI configurations updatedRegularly review and update CI configuration files to remove obsolete settings and use appropriate version specifications based on current platform capabilities. This minimizes configuration overhead, reduces maintenance burden, and ensures your CI pipeline remains efficient.boto/boto32 discussions
- Function-focused code organizationFiles should contain only code related to their named purpose, with proper organization and formatting. When adding functionality: 1. Place code in files that match their purpose (e.g., theme-related code belongs in general utilities, not in specialized modules)boto/boto32 discussions
- Follow flake8 style guidelinesAdhere to the project's established flake8 style guidelines as defined in setup.cfg. This includes: 1. Maintain line length limits of 80 characters for consistency and readability across all files.boto/boto32 discussions
- Avoid identifier name stutteringDo not repeat the resource name in identifier names. This form of stuttering makes code less readable and inconsistent. Instead, use simple, descriptive identifiers without redundancy.boto/boto32 discussions
- Stable Interface NormalizationDefine and enforce normalization rules for all user/client-facing inputs (CLI flags, request fields, option keys) so matching behavior is consistent with the documented interface contract—then harden implementations against dependency/API drift.bmad-code-org/bmad-method2 discussions
- Single-writer parallel joinWhen using concurrency/parallel subagents, enforce synchronization and determinism: 1) Parallelize independent work - Start independent steps concurrently (e.g., multiple subagents), each operating on immutable inputs.bmad-code-org/bmad-method2 discussions
- Single Source ConfigEnsure configuration is maintainable and compatible by (1) using a single authoritative field and deriving dependent values at runtime, and (2) pinning configuration-relevant dependency versions when they enforce runtime compatibility (e.g., CommonJS vs ESM) until you intentionally migrate.bmad-code-org/bmad-method2 discussions
- Preserve and Structure FailuresWhen errors occur—especially in multi-step operations—avoid accidental data loss and avoid “leaking” raw failures. Instead, preserve rollback artifacts and convert errors into documented, structured outcomes.bmad-code-org/bmad-method2 discussions
- Graceful Null ChecksAlways treat null/empty/missing required values as first-class cases: validate early, and either stop with a clear “HALT-and-ask” (for inputs needed to proceed) or conditionally render safe output (to avoid blank placeholders).bmad-code-org/bmad-method2 discussions
- Deterministic Validation AggregationWhen implementing checklist/workflow validation, treat the process like a deterministic algorithm: - **Total coverage**: execute steps in order; evaluate **every** checklist item/section; never skip.bmad-code-org/bmad-method2 discussions
- Deterministic Parse-Merge RulesWhen writing parsing or data-merge algorithms, ensure the logic is context-aware and unambiguous: - Scope semantics to the correct regions. If a formatter/markup has “non-semantic” contexts (e.g., fenced code blocks), your parser must ignore content inside them and only interpret the intended regions.bmad-code-org/bmad-method2 discussions
- Deterministic File OperationsWhen implementing concurrent or bulk filesystem operations, ensure deterministic execution and atomicity: avoid async wrappers/behavior that introduce retry queues or event-loop interleaving that can reorder unlinks/overwrites.bmad-code-org/bmad-method2 discussions
- Control Agent Context BudgetsAlways cap and actively prevent generative-agent context bloat. 1) Enforce explicit context/prompt budgets in code (hard max + warning threshold) so inputs never silently grow.bmad-code-org/bmad-method2 discussions
- Consistent Identifier NamingUse deterministic, normalized identifiers everywhere. Apply two rules: 1) Single source of truth: derive canonical identifiers from one stable place (e.g., directory name), and don’t trust optional/conflicting metadata fields.bmad-code-org/bmad-method2 discussions
- Strict auth schema validationSecurity-related Helm/config schemas should fail fast on invalid or unintended authentication settings. Apply: - Close security-sensitive objects with `additionalProperties: false` so typos/mistyped fields are rejected at `helm template`/validation time (instead of silently producing insecure runtime behavior).maximhq/bifrost2 discussions
- Prefer safe tag invalidationWhen a server mutation (e.g., model discovery refresh) changes data that feeds multiple cached selectors/queries, use RTK Query tag invalidation to refresh all dependent caches—especially indirect ones.maximhq/bifrost2 discussions
- Graceful Degradation PolicyFor external dependencies that are *additive* (e.g., mirrors/archives) rather than required for correctness, prefer **fail-open** behavior: log errors and continue operating using the primary source of truth. Reserve **fail-fast** for dependencies that are *hard requirements* for correctness or API functionality.maximhq/bifrost2 discussions
- Graceful config validationWhen configuration has conditional dependencies, make the system fail fast only for cases that break invariants (correctness/safety), but allow secure graceful degradation for “optional feature” toggles when prerequisites may be missing.maximhq/bifrost2 discussions
- Explicit React UI BehaviorWhen building React components, make user interaction and lifecycle behavior explicit—particularly for accessibility and ref/state initialization. - Tooltips + disabled controls: If a disabled element can’t receive focus, put the focusable/hoverable semantics on a wrapper inside `TooltipTrigger asChild`, and use conditional `tabIndex` to avoid adding extra...maximhq/bifrost2 discussions
- Explicit Null SafetyWhen templating, explicitly distinguish three states: **missing**, **explicit false**, and **null**. Relying on truthiness can silently drop intended configuration.maximhq/bifrost2 discussions
- Document behavior preciselyWhen updating documentation, ensure every statement about requirements, capabilities, and behavior is (1) correct for the current implementation, (2) explicit about when the requirement matters (e.g., render-time vs apply-time vs run-time), (3) consistent across related doc artifacts, and (4) does not imply unsupported configuration paths. Follow house...maximhq/bifrost2 discussions
- Deterministic test setup/teardownE2E tests should be deterministic by (1) registering mocks/fixtures before any action that triggers network calls (e.g., `goto()`), and (2) handling cleanup failures in a way that doesn’t skip subsequent tests/hooks.maximhq/bifrost2 discussions
- Consistent Test ID NamingWhen adding or modifying UI elements, ensure their test/automation identifiers follow the existing naming conventions and remain stable. Apply these rules:maximhq/bifrost2 discussions
- Config Contract ValidationEnsure API configuration endpoints (e.g., `PUT /api/config`) define and enforce a precise request/response contract across schema shape, merge semantics, validation behavior, and persistence.maximhq/bifrost2 discussions
- Concurrency-safe retriesWhen concurrency is involved, ensure two things: (1) your tests/operations can’t accidentally contend on shared resources, and (2) any concurrency-handling you add (e.g., retrying on 409) is only applied to errors that are truly reachable from the concurrent scenario you’re mitigating.maximhq/bifrost2 discussions
- Await Connection DrainsWhen async work depends on a connection that may still be resolving, prevent startup race conditions by (1) deferring the work to an “early” queue instead of silently skipping, and (2) awaiting the connection setup promises before concluding/awaiting the deferred work.maximhq/bifrost2 discussions
- Optimize database queriesAvoid inefficient database query patterns by using batch operations and appropriate query types. Instead of making multiple individual queries, use batch queries with `in` clauses. When you only need counts, use count queries rather than fetching full records.better-auth/better-auth2 discussions
- Intentional configuration managementConfiguration choices should be intentional, balancing production requirements with developer experience while keeping configuration logic centralized in dedicated files rather than embedded inline.better-auth/better-auth2 discussions
- Improve documentation clarityWrite clear, accessible, and consistent documentation by using descriptive link text and providing complete, realistic examples. Avoid generic link text like "here" or "click here" - instead, describe what the link leads to. Ensure code examples are comprehensive and consistent across all documentation.better-auth/better-auth2 discussions
- Document configuration requirementsEnsure that configuration requirements, dependencies, and options are clearly documented and communicated to users. When introducing features that require external configuration or have configurable behavior, explicitly state what must be configured and provide clear guidance on the implications of different settings.better-auth/better-auth2 discussions
- API endpoint correctnessAPI endpoints must behave according to their intended design, properly handling special values and executing expected operations like validation. This includes preserving meaningful null values (e.g., null representing "no limit") rather than replacing them with default values that change the intended behavior, and ensuring validation runs when expected.better-auth/better-auth2 discussions
- Write specific test assertionsMake test assertions specific and verifiable rather than relying on generic metrics or counts. Use explicit checks for expected behaviors and implement proper error handling to ensure tests fail fast when something goes wrong.bazelbuild/bazel2 discussions
- Organize code for readabilityStructure code to minimize complexity and improve readability through logical organization. This includes using early returns to reduce nesting levels and ordering operations in a logical sequence.bazelbuild/bazel2 discussions
- Document network interface purposesWhen implementing multiple network-related interfaces or classes that handle similar operations (like downloading), clearly document the purpose, scope, and differences between each interface to prevent confusion and misuse.bazelbuild/bazel2 discussions
- Document algorithmic reasoningWhen implementing algorithms that involve data transformations, platform-specific behavior, or non-obvious computational choices, always include comments explaining the underlying reasoning and assumptions. This is especially critical for:bazelbuild/bazel2 discussions
- comprehensive edge case testingWrite comprehensive tests that cover edge cases and platform-specific scenarios to uncover underlying implementation issues rather than masking them with workarounds. When encountering failures, investigate the root cause through targeted testing before implementing fallback mechanisms.bazelbuild/bazel2 discussions
- avoid brittle algorithmsReplace fragile algorithmic approaches with robust, well-tested alternatives. Brittle algorithms that rely on manual parsing, string manipulation, or assumptions about data format are prone to failure and difficult to maintain.bazelbuild/bazel2 discussions
- Automate sensitive CI artifactsLarge files and security-sensitive artifacts should be automatically generated in CI/CD pipelines rather than manually committed to version control. This reduces security risks from potentially malicious content and ensures artifacts stay current with the codebase.bazelbuild/bazel2 discussions
- Triage-Ready TelemetryWhen implementing observability detections/parsers, ensure alerts/fields are (1) schema-correct and vendor-correct, and (2) triage-ready with the exact raw context that triggered the signal.Azure/Azure-Sentinel2 discussions
- Timeout-Aware ChunkingFor any long-running ingestion/connectors, optimize for throughput while preventing timeout failures. Implement (1) near-timeout early exit and (2) realistic, configurable chunk/batch sizing.Azure/Azure-Sentinel2 discussions
- Match Template Parameter NamesWhen documenting or wiring configuration inputs for infrastructure/templates, use the *exact* identifier names from the underlying template (including casing and punctuation), and keep descriptions semantically aligned with the producing service.Azure/Azure-Sentinel2 discussions
- Deterministic sortingWhen your code builds collections or performs comparisons, normalize inputs to a consistent representation and enforce a deterministic order before iterating/outputting.Azure/Azure-Sentinel2 discussions
- Use higher-level telemetryWhen implementing observability for Azure services, prefer higher-level telemetry packages and configuration methods over low-level implementations. For Azure Monitor integration, use the Azure.Monitor.OpenTelemetry.AspNetCore package instead of the lower-level Azure.Monitor.OpenTelemetry.Exporter, as it provides simpler integration and is the recommended...Azure/azure-sdk-for-net2 discussions
- Preserve protocol data integrityWhen working with network protocols (like AMQP, NFS, or SMB), maintain the integrity of the original protocol data structures during serialization, deserialization, and transformation operations. Modifying protocol-specific data can lead to unintended changes in the service contract and unexpected behavior for clients.Azure/azure-sdk-for-net2 discussions
- Match CI commands locallyAlways use the same build and test commands locally that are used in your CI pipeline to ensure consistency between environments. This practice significantly increases the likelihood that code passing locally will also pass in CI, reducing integration delays and failed builds.Azure/azure-sdk-for-net2 discussions
- Handle external process errorsWhen calling external processes (like dotnet, msbuild, etc.), always implement proper error handling and output management: 1. Check exit codes to detect failures and propagate errorsAzure/azure-sdk-for-net2 discussions
- Eliminate repeated codeReduce code duplication by extracting repeated patterns into variables, loops, or helper functions. When you find yourself writing similar lines of code multiple times, refactor to a more DRY (Don't Repeat Yourself) approach to improve maintainability and readability.Azure/azure-sdk-for-net2 discussions
- Document non-obvious codeAdd clarifying comments to code elements whose purpose or behavior may not be immediately apparent to other developers. This includes conditional logic blocks, empty configuration properties, and any code structures whose intent requires context to understand.Azure/azure-sdk-for-net2 discussions
- Document maintenance decisionsAdd clear documentation for any decisions that affect future code maintenance. This includes: 1. Providing explanatory comments for non-obvious default values in parametersAzure/azure-sdk-for-net2 discussions
- Document AI changes thoroughlyWhen updating AI libraries and SDKs, ensure all changes are thoroughly documented in changelogs with clear categorizations (Features Added, Breaking Changes) and explicit migration paths for breaking changes. For complex AI features, include links to detailed documentation.Azure/azure-sdk-for-net2 discussions
- Complete pipeline configurationsEnsure all CI/CD configuration files have their required fields properly populated with specific values rather than empty strings or placeholders. Missing or incomplete configuration values can cause pipeline failures, prevent proper asset publishing, or create unnecessary maintenance overhead. Regularly review configurations to validate they're accurate...Azure/azure-sdk-for-net2 discussions
- Approve AI dependencies conditionallyAll AI-related dependencies (Microsoft.Extensions.AI.*, etc.) require explicit approval before inclusion and must be restricted to specific packages using conditional blocks in Packages.Data.props. Prefer version 8.x dependencies when available, and document any exceptions (such as using 9.x) with clear comments explaining the approval scope and reasoning.Azure/azure-sdk-for-net2 discussions
- Address not maskAlways address the root cause of CI/CD pipeline issues rather than masking them with quick fixes. This applies to encoding problems, build failures, and other CI-related issues.Azure/azure-sdk-for-net2 discussions
- Test template defaultsWhen testing a template’s behavior, avoid overriding it with explicit parameter values. Remove parameter values from the parameters file so the template’s `defaultValue(s)` are used, ensuring the default-path is actually exercised.Azure/azure-quickstart-templates2 discussions
- Env-Aligned ConfigurationWhen a solution has environment-specific configuration (e.g., public vs US Gov) or requires cloud-context values, ensure: 1) **Environment-specific UI/artifacts are derived from the declared support matrix** (e.g., `metadata.json` → `environments`). If an environment is not supported, do not render its corresponding badge/button/link.Azure/azure-quickstart-templates2 discussions
- Enforce Security PrereqsEnsure infrastructure/code templates explicitly and correctly handle the two most common security failure points: (1) required authorization for identities to perform discovery/monitoring, and (2) strict validation of user-supplied parameters.Azure/azure-quickstart-templates2 discussions
- Unit tests for cmdlet pathsAdd isolated unit tests for cmdlet production paths using mocked client operations. Tests must validate more than a “happy path” scenario run: - Verify exact client call arguments (including resource identifiers and IDs).Azure/azure-powershell2 discussions
- Production-Safe ConfigurationWhen changing build/test/configuration files, ensure they are (1) platform-correct and (2) production-safe. Apply this standard: 1) Platform-correct environment/config updatesAzure/azure-powershell2 discussions
- Generated docs truthWhen documentation or module metadata files are produced by a generator (e.g., AutoRest), treat those outputs as **generated artifacts**, not as the place to apply fixes. Instead:Azure/azure-powershell2 discussions
- Fail Fast Input ValidationValidate customer-supplied, security-relevant settings up front and fail deterministically with explicit errors when values/config combinations are invalid. Add tests that cover most customer-input parameters and assert the expected provisioning/result behavior and returned properties.Azure/azure-powershell2 discussions
- Documentation Source And ToneWhen updating documentation (assembly metadata, cmdlet HelpMessage, generated stubs, etc.), ensure (1) you change the correct source of truth and (2) the text is written for users, not for internal implementation.Azure/azure-powershell2 discussions
- Consistent Identifier NamingUse naming rules that keep identifiers consistent, unambiguous, and resilient to change: - Centralize repeated string keys/labels used as identifiers (e.g., dictionary/property-bag keys) into named constants so the same literal can’t drift across methods.Azure/azure-powershell2 discussions
- Deterministic External TestingWhen external services are flaky or untestable, make CI deterministic by (1) pruning recorded interactions to the stable outcomes your playback will actually match, and (2) using narrowly-scoped linter/test exclusions only when a dependency prevents meaningful coverage.Azure/azure-cli2 discussions
- Canonical naming semanticsWhen configuring or referencing named entities, use the *canonical identifier* required by the consuming system and ensure the identifier’s *semantic type* matches what the field expects (e.g., “team” vs “label”). If a system normalizes names, reference the normalized form—not the on-disk/path form—and don’t substitute a label for a team.Azure/azure-cli2 discussions
- Avoid editing generated historyIf a file is explicitly documented (or implied by the repo’s process) as auto-generated—such as changelog/history files—do not manually edit it in code changes. Instead, revert those edits and update the upstream inputs that drive generation (e.g., PR release-note metadata, templates, or generator configuration), then confirm the regenerated output contains...Azure/azure-cli2 discussions
- Use Appropriate Concurrency Patterns with AxumWhen building asynchronous Axum applications that share mutable state, it's important to select the right concurrency mechanisms. Use Axum's built-in Mutex or RwLock for general shared state, prefer connection pools for shared I/O resources, and consider the actor pattern for complex shared operations.tokio-rs/axum2 discussions
- Implement Distributed Tracing in Axum ApplicationsAs an Axum code reviewer, I recommend implementing proper distributed tracing in your Axum-based web applications to ensure observability across service boundaries. Use Axum's built-in middleware layers to consistently instrument your code.tokio-rs/axum2 discussions
- Type-safe query contractsWhen a UI route consumes or produces URL search/query parameters, treat those parameters as a contract: validate and type them at the route boundary, update them through typed helpers (no `as any`), and normalize/omit default-derived fields so the resulting query set is consistent.looplj/axonhub2 discussions
- Semantic Merge And Deep CopyWhen your code incrementally merges or inherits structured data (JSON payloads, rule trees, settings), correctness should be enforced by (a) semantic, lossless reconciliation and (b) deep-copying every nested mutable component.looplj/axonhub2 discussions
- Scoped Provider TransformationsWhen implementing AI/LLM request transformers (especially for proxies), make provider-specific shaping: 1) **Scoped and structured**: Clone the incoming `llm.Request` and apply provider/CLI-specific changes via existing structured fields **before** delegating to the shared/base transformer whenever possible. Avoid raw `[]byte` request-body manipulation...looplj/axonhub2 discussions
- Deep-copy cached stateWhen cached data (e.g., `row.settings`) is used to initialize mutable UI state (forms, editors, draft objects), do not pass cached object references directly. Always deep-clone cached objects on entry to editable state to prevent unintended cache mutations and ensure copied/duplicated initialization is isolated.looplj/axonhub2 discussions
- User-friendly error messagesError messages should be concise and clearly communicate what went wrong without unnecessary verbosity. When implementing error handling, maintain consistent code style and organize related operations logically within appropriate blocks.axios/axios2 discussions
- Flexible configuration designDesign configuration interfaces to be flexible and extensible rather than overly specific. When creating configuration objects, make configuration parameters optional when possible with sensible defaults and allow for arbitrary additional properties rather than creating specific fields for custom configurations.axios/axios2 discussions
- Consistent semicolon usageAlways terminate statements with explicit semicolons to maintain consistency with the existing codebase style. Avoid relying on JavaScript's automatic semicolon insertion (ASI) feature, as this can lead to inconsistent code appearance and potential subtle bugs.axios/axios2 discussions
- Consistent Axios Usage PatternsMaintain consistent usage of the Axios library throughout your TypeScript codebase. Pay special attention to consistent error handling, Axios configuration options, Axios request patterns, and Axios response handling.axios/axios2 discussions
- Standardize API promise patternsWhen adding promise support to API methods, implement a consistent pattern that handles both callback-style and multi-parameter methods. Use a standardized promisification approach that appends the promise-determining callback as the last argument.aws/aws-sdk-js2 discussions
- Semantic type organizationOrganize types and interfaces in intuitive namespace hierarchies and use specific types instead of generic ones. Types should be accessible through logically related namespaces, and method signatures should accurately reflect their parameters and return values. This improves code clarity, discoverability, and type safety.aws/aws-sdk-js2 discussions
- Organize type declarationsStructure TypeScript declarations to improve maintainability and developer experience. Organize related types into appropriate namespaces and use inheritance to avoid duplication.aws/aws-sdk-js2 discussions
- Example documentation standardsOrganize API documentation examples for maximum clarity and usefulness. Place hand-written examples before generated examples since they're typically more valuable to users. When using @example tags, include only the descriptive title without redundant 'Example:' prefixes.aws/aws-sdk-js2 discussions
- Document sdk version requirementsAlways explicitly document AWS SDK version requirements in your project, and include configuration instructions for different deployment environments. This is especially critical for Lambda functions where the runtime may include its own SDK version.aws/aws-sdk-js2 discussions
- Complete configuration type definitionsEnsure configuration type definitions are complete and consistent between global and service-specific settings. When designing configuration classes, include service identifiers as optional instance variables and ensure update methods accept all relevant option types that might be used at both global and service-specific levels.aws/aws-sdk-js2 discussions
- Accurate type signaturesWhen defining API interfaces in TypeScript, ensure that method signatures accurately reflect the actual behavior and requirements of the implementation. Pay special attention to:aws/aws-sdk-js2 discussions
- Verify URL security and validityAlways ensure external URLs use HTTPS when available and verify that links resolve correctly before including them in documentation or code. HTTP links expose users to potential security risks through unencrypted connections, while broken or incorrect URLs create poor user experience and may indicate outdated dependencies.avelino/awesome-go2 discussions
- Verify markdown sanitizationWhen processing markdown content, always verify what sanitization your chosen markdown library provides to prevent XSS vulnerabilities while avoiding redundant security measures. Some libraries like `github_flavored_markdown` include built-in sanitization, while others like `blackfriday` require explicit sanitization of their output.avelino/awesome-go2 discussions
- Follow Go style guidelinesCode should adhere to the recommended Go style guidelines as outlined in the official Go Code Review Comments. While perfect adherence isn't always required, aim for minimal golint issues and follow established Go conventions for naming, formatting, and code organization.avelino/awesome-go2 discussions
- exported functions documentationAll exported functions, types, and methods must include Go-style documentation comments that clearly explain their purpose, parameters, return values, and usage. This is a fundamental requirement for code quality and maintainability.avelino/awesome-go2 discussions
- Environment variable defaultsConfiguration values should be externalized to environment variables with sensible defaults to avoid hard-coding values in source code. This approach improves flexibility, security, and maintainability by allowing different configurations across environments without code changes.avelino/awesome-go2 discussions
- Categorize by primary purposeWhen organizing configuration tools, environment management utilities, and settings-related projects, classify them based on their primary function and intended use case rather than their implementation details or secondary benefits. This ensures clear, consistent categorization that helps developers quickly identify the right tools for their configuration...avelino/awesome-go2 discussions
- validate conceptual API typesWhen defining API types, enums, or interfaces, ensure they represent accurate conceptual distinctions within the domain model rather than implementation details or delivery mechanisms. Each type should correspond to a meaningful category that users and developers can clearly understand and differentiate.argoproj/argo-cd2 discussions
- Use clear, descriptive namesChoose names that accurately describe their purpose and avoid unnecessary verbosity. Field names should semantically match what they contain or validate, and component names should be concise without redundant prefixes that don't add clarity.argoproj/argo-cd2 discussions
- structured condition evaluationWhen implementing health checks, use comprehensive condition evaluation patterns instead of simple field comparisons. Check multiple condition attributes (type, status, reason, message) to ensure accurate health status determination.argoproj/argo-cd2 discussions
- standardize commit tracing metadataWhen CI/CD pipelines make automated commits (such as image bumps or manifest updates), use standardized git commit trailers to maintain traceability back to the original code changes. This enables developers and tools to trace deployment artifacts to their source commits.argoproj/argo-cd2 discussions
- simplify nested conditionalsCombine multiple nested if statements using logical operators (and/or) to improve code readability and reduce unnecessary indentation. Remove redundant nil checks when they are unnecessary, especially when subsequent checks would naturally handle the nil case.argoproj/argo-cd2 discussions
- Remove unnecessary elementsEliminate superfluous syntax and words that don't add value to improve code readability and maintain consistent style. This includes removing unnecessary quotes in YAML files and avoiding redundant words in documentation.argoproj/argo-cd2 discussions
- Prevent silent failuresEnsure that user actions and validations provide clear feedback rather than failing silently. When operations cannot be performed, disable UI elements or provide explicit error messages to inform users of the system state.argoproj/argo-cd2 discussions
- prefer modern React patternsFavor modern React patterns over legacy approaches to improve code maintainability and prepare for future React upgrades. Use functional components with hooks instead of class components, and prefer `React.useContext` over the `<Context.Consumer>` render prop pattern to reduce JSX nesting and improve readability.argoproj/argo-cd2 discussions
- Organize CSS systematicallyWhen working with CSS/SCSS, prioritize organization and avoid duplication by following these principles: 1. **Extract related styles into dedicated files** - Group thematically related CSS rules (like motion controls, accessibility overrides, or component variants) into separate SCSS files and import them centrally for better maintainability.argoproj/argo-cd2 discussions
- null-check before method callsAlways verify that properties are not null or undefined before calling methods on them to prevent runtime errors. This is especially important when filtering, mapping, or processing arrays where some objects may have missing or undefined properties.argoproj/argo-cd2 discussions
- Follow established naming patternsWhen introducing new identifiers (variables, methods, flags, metrics, etc.), examine existing code to identify and follow established naming conventions rather than creating new patterns. This ensures consistency across the codebase and maintains predictability for users and developers.argoproj/argo-cd2 discussions
- Environment variable validationScripts that depend on environment variables should validate their presence and values early, providing clear error messages that guide users toward resolution. When checking environment variables, ensure logical flow doesn't create unreachable code blocks.argoproj/argo-cd2 discussions
- Document observability prerequisitesWhen documenting observability features such as metrics, debugging capabilities, or monitoring tools, always include clear information about their prerequisites, enabling conditions, and limitations. This ensures developers understand when these features are available and how to access them.argoproj/argo-cd2 discussions
- Document configuration risks comprehensivelyWhen documenting configuration options, provide comprehensive information including current default values, recommended settings, future behavioral changes, and potential security implications. Configuration comments should clearly explain not just what the option does, but also warn about risks and provide guidance on proper usage.argoproj/argo-cd2 discussions
- Configuration UI consistencyEnsure that configuration user interfaces accurately reflect the underlying configuration behavior and data structures. UI controls should provide clear, transparent mapping to the actual configuration values, including precedence rules and field relationships.argoproj/argo-cd2 discussions
- API parameter extensibilityDesign APIs to support multiple parameters from the beginning rather than limiting them to single parameter inputs. This prevents future refactoring needs and provides better extensibility for complex operations.argoproj/argo-cd2 discussions
- Subprocess stream lifecycleWhen you stream a subprocess’s stdout/stderr into an async generator, treat process exit, stream end/close, abort, and timeout escalation as concurrent events that can race.coleam00/Archon2 discussions
- Isolate process-global mocksWhen a test uses process-global/irreversible module mocking, prevent cross-test contamination by isolating the affected test files into separate `bun test` runs (batch isolation). Keep mocks narrowly scoped so tests don’t need to mock large dependency graphs, and avoid importing “config/provider” chains in units where tests shouldn’t require them.coleam00/Archon2 discussions
- Include API VersionWhen configuring client access to an external API, store the provider’s base endpoint as a fully-qualified URL that already includes the required API version (and defaults). Avoid splitting “base URL” and “version” in ways that can drift or be forgotten—make the endpoint unambiguous.coleam00/Archon2 discussions
- API contract regressionWhen adding or changing API-like functions (parsers, clients, helpers), treat them as having a stable contract: define the accepted inputs and exact output shape, cover tricky edge cases with regression tests, and remove/deprecate superseded code paths so the API surface stays unambiguous.coleam00/Archon2 discussions
- Validate documentation linksAlways verify that URLs in documentation resolve correctly (return HTTP 200) before merging changes. Broken links create a poor user experience and reduce the credibility of documentation.appwrite/appwrite2 discussions
- Prevent API documentation duplicationWhen maintaining API specification files (like OpenAPI or Swagger), ensure consistency and avoid duplication that can confuse documentation generators and API consumers:appwrite/appwrite2 discussions
- Match defaults to typesWhen specifying default values in schemas or configurations, ensure they match the declared type to prevent validation errors and unpredictable behavior. For object types, use empty objects (`{}`) not null, undefined, or arrays. For string types that should be empty by default, use empty strings (`""`) not null. This practice improves type safety and...appwrite/appwrite2 discussions
- Flexible network handlingWhen working with network connections and HTTP requests, implement flexible configuration patterns and robust response handling to prevent flaky behavior and ensure compatibility across environments.appwrite/appwrite2 discussions
- Context-appropriate API authenticationAlways use the authentication method appropriate for your API client's execution context. Server-side SDKs should use API key authentication (with `setKey()`) rather than session-based authentication, which is meant for client-side applications.appwrite/appwrite2 discussions
- Consistent language in namingUse a single language (preferably English) consistently throughout your codebase for all identifiers including interface names, classes, variables, and properties. Avoid mixing languages as this reduces code readability and creates inconsistent naming patterns.appwrite/appwrite2 discussions
- Consistent database parametersMaintain consistency and clarity in database-related parameters and configuration variables. Follow these practices: 1. Use descriptive variable names that match parameter names for clarityappwrite/appwrite2 discussions
- Trace semconv and completenessMake observability outputs standards-compliant and fully observable. Apply this when writing instrumentation and when publishing tracing/telemetry examples:apache/apisix2 discussions
- Self-Contained Secure NetworkingEnsure networking-related docs/examples and configurations are both runnable and secure: (1) every referenced endpoint/service/backend in an example manifest must be defined so the config works when copied, and (2) TLS-related defaults (e.g., certificate verification) must default to secure behavior and be treated as potentially breaking—clearly...apache/apisix2 discussions
- Fail-fast artifact downloadsFor required build/CI artifacts, make the reference configurable (with a sensible default) and fetch them with fail-fast settings so HTTP errors, missing files, or bad refs stop the build immediately.apache/apisix2 discussions
- Deterministic, scoped CICI jobs that build artifacts must be deterministic and guarded, and CI tests must be scoped to avoid unnecessary heavy work. **Apply these rules** 1) **Guard CI assumptions (fail loudly):** If a build-time tweak is required (e.g., removing -march=native leakage), make the script error when the expected input/state isn’t found—never allow a “no-op” edit...apache/apisix2 discussions
- Manage network resourcesWhen working with streaming or TCP options, be explicit and defensive: 1) Closing streams: If you terminate a stream early (e.g., you don’t fully consume an HTTP/SSE iterator), ensure you close the underlying network resource—not just a wrapper/decoder that may not implement `close()`.anthropics/anthropic-sdk-python2 discussions
- Explicit None ChecksWhen working with nullable/optional values, treat `None` (absence) differently from other falsy values like `""` (empty string) or `0` (zero). Use explicit `is not None` checks when empty values are valid, and avoid repeating null checks after you’ve already established a non-null invariant via an early return/guard.anthropics/anthropic-sdk-python2 discussions
- Actionable normalized errorsWhen adding error handling for failure scenarios (infinite/looping behavior, retries, or other unbounded processes), ensure two things: 1) Normalize/validate error-relevant inputs before they affect control flow.anthropics/anthropic-sdk-python2 discussions
- Test network performanceAlways validate network performance and connectivity before suggesting alternative endpoints or making routing decisions. Implement timeout-based checks to ensure alternatives are actually faster or more accessible for the user's specific network conditions.ant-design/ant-design2 discussions
- Pin CI dependencies securelyAlways pin CI/CD dependencies (GitHub Actions, external tools) to specific commit hashes or exact versions rather than using floating tags like @v1 or @latest. This prevents supply chain attacks and ensures reproducible builds. However, pinned dependencies must be regularly updated to avoid using outdated or vulnerable versions.ant-design/ant-design2 discussions
- Enforce CI workflow gatesEstablish and enforce proper CI/CD workflow gates to maintain code quality and release safety. This includes preventing direct commits to protected branches and validating CI status before releases.ant-design/ant-design2 discussions
- consistent dependency formattingMaintain consistent formatting and organization when managing dependencies in package.json files. Use semver range notation (^) consistently for all dependencies to allow compatible updates, and make targeted changes rather than bulk updates to preserve clean git history and blame information.ant-design/ant-design2 discussions
- Use design system colorsAlways use design system color variables instead of hardcoded color values in stylesheets. This ensures consistent theming, automatic dark/light mode support, and maintainable code.angular/angular2 discussions
- Pin GitHub Actions SHAGitHub Actions should be pinned to specific SHA commits rather than mutable tag references to ensure security and reproducibility. Tags can be moved or updated by malicious actors, potentially introducing supply chain vulnerabilities, while SHA commits are immutable and provide guaranteed consistency across builds.angular/angular2 discussions
- Optimize configuration specificityEnsure configuration files use precise patterns and avoid redundant dependencies. Configuration specifications should be as specific as necessary to match their intended purpose, and unnecessary or duplicate entries should be removed to maintain clean, efficient configurations.angular/angular2 discussions
- Guard unsafe API callsAlways check the availability or state of data before accessing potentially unsafe API methods that can throw runtime errors. Many Angular APIs provide guard methods to safely check state before accessing values.angular/angular2 discussions
- Consider accessibility in markupWhen writing HTML markup, consider the accessibility implications of your formatting and structural choices. This includes avoiding text formatting that may negatively impact screen readers and ensuring proper semantic HTML usage.angular/angular2 discussions
- Centralize configuration managementExtract configuration state, feature flags, and version-dependent settings into dedicated services rather than hardcoding values or prop drilling through component hierarchies. This approach improves maintainability, testability, and allows for easier updates without code changes.angular/angular2 discussions
- User-friendly network descriptionsWhen documenting network-related features like URL handling, hyperlinks, or web protocols, prioritize user-understandable descriptions over technical implementation details. Users care about what functionality they gain, not the internal mechanics of how it works.alacritty/alacritty2 discussions
- unsafe code practicesEnsure proper use and documentation of unsafe code to prevent security vulnerabilities. The `unsafe` keyword should only be used for operations that can violate memory safety contracts, not for general thread safety or global state concerns. All unsafe functions must include comprehensive safety documentation explaining the contracts that callers must...alacritty/alacritty2 discussions
- synchronize platform configurationsWhen making configuration changes that affect multiple platform-specific files, ensure all related configuration files are updated consistently and test the changes on each target platform.alacritty/alacritty2 discussions
- Keep documentation togetherDocumentation should keep related information physically close together rather than separating it across different sections. When documenting configuration options, provide detailed explanations and defaults directly with each option definition instead of collecting them in distant sections.alacritty/alacritty2 discussions
- centralize workspace dependenciesDefine shared dependencies at the workspace level in the root Cargo.toml to ensure version consistency and prevent conflicts across the project. This approach centralizes dependency management and makes it easier to maintain uniform versions throughout the codebase.alacritty/alacritty2 discussions
- Assess security trade-offsWhen introducing dependencies or features that have security implications, explicitly evaluate whether the benefits justify the potential risks. Prefer safer alternatives when available, and clearly document security considerations.alacritty/alacritty2 discussions
- Validate configuration source changesWhen switching between different configuration sources (like APIs or configuration values), ensure data structure compatibility and consistent behavior. Configuration endpoints may return different data structures that require proper transformation.apache/airflow2 discussions
- Use proper access patternsAccess configurations through documented abstraction layers rather than bypassing them with direct database or low-level access. For example, in Airflow, XCom operations should be performed through the Task Context using `get_current_context()` rather than directly accessing the database model:apache/airflow2 discussions
- Use guards over assertionsPrefer explicit type guards and null checks over TypeScript's type assertions (`as`) when handling potentially null or undefined values. Type assertions bypass TypeScript's type checking system and can lead to runtime errors.apache/airflow2 discussions
- Share documentation configsDocumentation tooling and configuration files should leverage shared/centralized resources rather than maintaining duplicate copies across repositories. This reduces maintenance burden, ensures consistency, and simplifies updates.apache/airflow2 discussions
- Quote shell variablesAlways quote shell script variable expansions using double quotes to prevent word splitting issues and ensure consistent behavior. This is particularly important in conditionals and when passing variables as command arguments.apache/airflow2 discussions
- Optimize CI configurationsWhen designing CI/CD workflows, prioritize both resource efficiency and clear documentation. Incorporate dynamic configuration where beneficial, but avoid creating separate jobs for simple tasks that can be handled within existing steps. Ensure all comments and configurations accurately reflect version requirements across all supported branches,...apache/airflow2 discussions
- Natural language translationsWhen providing translations for user interface elements and documentation, prioritize natural and idiomatic expressions in the target language rather than literal translations. Consider the grammatical rules and cultural context of each language to ensure the translated text sounds native to users.apache/airflow2 discussions
- Use Correct Null SemanticsTreat “missing/unknown” differently from “present/true” and from “known false”. Two common pitfalls: 1) CLI flags: frameworks may represent valueless options as the string `"true"`, which breaks guards that only check truthiness.awslabs/aidlc-workflows2 discussions
- Security Trust BoundariesWhen software ingests extensions (plugins) or external artifacts (actions/images/deps), security standards must explicitly state the trust model and maintenance cadence.awslabs/aidlc-workflows2 discussions
- Scoped Hash-Based IdempotencyWhen implementing idempotency or caching via markers/ledger “done” signals, treat cached state as valid only if (a) the key reflects the content/version being applied and (b) the signal is scoped to the current execution context.awslabs/aidlc-workflows2 discussions
- Pinned Releases For CIEnsure release and versioning behavior is deterministic and pipeline-owned. - For CI/CD workflows/rules: if it’s experimental, tracking the “head” is acceptable; for anything users rely on in production, pin to an explicit release (tag/zip/release branch) rather than “always latest” via submodule auto-update.awslabs/aidlc-workflows2 discussions
- No Silent Null ArtifactsWhen a workflow stage can legitimately have missing data, treat the missing artifact as an explicit, validated state—not as an absent file/implicit default.awslabs/aidlc-workflows2 discussions
- Explicit Environment ContractsWhen code depends on runtime configuration (tooling paths, IDE/CLI context, feature flags), treat environment variables as an explicit contract and don’t rely on implicit process state.awslabs/aidlc-workflows2 discussions
- Concise Factual InstructionsWhen writing AI rules or workflow instructions, keep the language concise and unambiguous, and for any factual/time-sensitive output require the model to derive it from runtime results (never placeholders or estimates). Overusing high-salience markers (e.g., many `MANDATORY/CRITICAL` tags) can reduce compliance; instead, make requirements explicit via...awslabs/aidlc-workflows2 discussions
- CI/CD Workflow PredictabilityWhen configuring GitHub Actions for CI/CD, keep workflow outputs and triggers predictable: 1) Use safe, stable identifiers for artifacts/reports. Don’t build artifact names from values that can be invalid (e.g., raw branch/ref names). Prefer constants or explicitly sanitized values.awslabs/aidlc-workflows2 discussions
- CI Security DefaultsDefault CI/security configuration to minimize risk while keeping automated findings meaningful. Apply these rules: 1) Enforce least-privilege GitHub Actions permissionsawslabs/aidlc-workflows2 discussions
- Check mode must mirrorWhen a pipeline script supports `--check`, it must validate *all* artifacts that the corresponding “write” path generates, using deterministic comparisons, and it must cover the full, intended target scope (prefer discovery over hardcoding).awslabs/aidlc-workflows2 discussions
- Behavior-Correct, Versionless DocsDocumentation and inline comments should be (1) strictly aligned with what the code actually does and (2) resilient to future version bumps. Actionable standards:awslabs/aidlc-workflows2 discussions
- Thread-safe message dispatchingWhen implementing communication between multiple threads, ensure that messages are correctly routed to their intended recipients. Avoid designs where all worker threads consume from a single shared queue when messages are intended for specific threads, as this creates race conditions where messages can be processed by the wrong thread.Aider-AI/aider2 discussions
- Isolate test environmentsTests should be isolated from the production environment to prevent side effects and ensure reproducibility. This principle has two main applications:Aider-AI/aider2 discussions
- Compatible null annotationsWhen annotating optional or nullable types in Python, ensure compatibility across all supported Python versions. For codebases supporting Python 3.9: Aider-AI/aider2 discussions
- Versioning for migrationsUse appropriate version bumps to signal migration requirements and maintain clear upgrade paths. Flag breaking changes with major version bumps to help with release notes and upgrade guides. External contributors should use patch bumps only, while minor and major version changes are reserved for the core team.vercel/ai2 discussions
- Optimize CI type checkingConfigure separate TypeScript type-checking strategies for CI environments and local development. CI pipelines should run complete type checks that validate the entire codebase, while local development can use faster configurations to improve developer productivity.vercel/ai2 discussions
- Format for rendering compatibilityDocumentation should be formatted appropriately for its intended rendering context and ensure discoverability. Consider how documentation files will be displayed in different environments (GitHub, websites, etc.) and choose appropriate file formats and structures.vercel/ai2 discussions
- Flexible API inputsDesign APIs to accept flexible input formats and schema structures, ensuring a better developer experience while maintaining consistency in internal implementation.vercel/ai2 discussions
- Consistent camelCase namingUse camelCase consistently for all property names, method names, and configuration options, even when interacting with external APIs that use different conventions (like snake_case). This maintains codebase consistency and makes interfaces more predictable for developers.vercel/ai2 discussions
- Consistent AI interfacesMaintain consistent naming patterns and parameter structures across AI provider implementations. This makes the SDK more intuitive and reduces developer friction when switching between different AI models or providers.vercel/ai2 discussions
- Validate environment bindingsAlways validate that environment bindings exist and are of the expected type before using them, and ensure external dependencies are properly configured in build scripts. Runtime binding validation prevents cryptic errors when bindings are missing or misconfigured, while proper build configuration prevents dynamic import issues in serverless environments.cloudflare/agents2 discussions
- validate connection protocolsAlways validate network connection types, required parameters, and protocol-specific headers before processing requests. This prevents runtime errors and ensures proper connection handling across different network protocols.cloudflare/agents2 discussions
- Test security boundariesSecurity mechanisms should be tested for both success and failure scenarios to ensure they properly enforce boundaries. Don't just test that security features work when enabled - also verify they correctly block unauthorized access when disabled or misconfigured.cloudflare/agents2 discussions
- Use OTEL Env OverridesWhen configuring OTLP tracing exporters in observability code, rely on the runtime-provided `OTEL_EXPORTER_OTLP_ENDPOINT` and `OTEL_EXPORTER_OTLP_HEADERS` environment variables, rather than hardcoding or redundantly passing `endpoint=` and `headers=` into `OTLPSpanExporter`. This prevents configuration drift and duplicated settings.awslabs/agentcore-samples2 discussions
- Safe diagnostic loggingWhen adding logs or debug output, use them to improve traceability and troubleshooting without leaking secrets. **Do** - Log **correlation identifiers** (e.g., `session_id`) in a **consistent, known format** (e.g., UUID) so issues can be followed end-to-end.awslabs/agentcore-samples2 discussions
- Manage Session LifecyclesTo optimize performance and avoid wasted compute (vCPU/memory), ensure AgentCore sessions end promptly—either by setting an appropriate idle timeout or by explicitly stopping the session when work is complete.awslabs/agentcore-samples2 discussions
- Explicit memory disablingWhen building LLM agents for AgentCore/runtime environments, don’t rely on framework defaults for memory. If your agent does not use conversational/session memory, explicitly disable it (e.g., set `memory_mode='NO_MEMORY'`) to prevent the runtime/framework from automatically creating/using STM.awslabs/agentcore-samples2 discussions
- Enforce Boundary Least-PrivilegeSecurity-sensitive controls must be enforced at the boundary (before business logic) and granted with the minimum required scope. Avoid designs where access is only checked after the request reaches handlers or where automation receives broad credentials.awslabs/agentcore-samples2 discussions
- Deterministic dependency sourcingAll CI/CD build environments must be reproducible and based on reliable dependency sources. Standards: 1) Prefer official published packages/artifactsawslabs/agentcore-samples2 discussions
- Avoid Hardcoded EnvironmentsDo not commit configuration that is (a) unnecessary/stale or (b) hardcoded to specific environments (e.g., `gamma`, `beta`, `no-prod`, or other prod variants). Keep repo configuration environment-agnostic by parameterizing values and deriving environment-specific behavior at runtime/deployment.awslabs/agentcore-samples2 discussions
- Avoid brittle AI heuristicsWhen building agent evaluation and agent runtime logic, avoid ad-hoc, brittle inference from unstructured strings or hardcoded scenario lists. Instead:awslabs/agentcore-samples2 discussions
- Async status over loopsWhen using AgentCore Runtime for long-running/async jobs, manage concurrency by relying on the runtime’s status mechanisms rather than blocking or implementing unbounded wait loops. Clients should start the async job, return immediately, and then use the provided status API/methods or the /ping health signal to determine progress.awslabs/agentcore-samples2 discussions
- Unified extension API contractsWhen building WebUI plugin/extension systems, treat the backend as the source of truth for (1) resolving extension contents and (2) providing a stable context schema to JS extensions.agent0ai/agent-zero2 discussions
- Single Source Error LogicWhen handling failures or optional data, make the decision exactly once and reuse the result everywhere. Apply two concrete rules: 1) **Normalize once, then use the normalized values for both validation and execution.** Don’t validate one set of fields and execute using separately-fallbacked canonical fields.agent0ai/agent-zero2 discussions
- Config source precedenceWhen configuration is moved/renamed or when settings are derived from environment variables, ensure (1) the dotenv loader points to the correct file path/name and (2) there is an explicit precedence order for derived settings (env-provided values override generated/default values).agent0ai/agent-zero2 discussions
- AI Boundary CompatibilityWhen building AI/LLM-related tooling (tool-calls, background execution, inference/image generation), enforce compatibility at the boundaries: 1) Use team-standard LLM-friendly IDsagent0ai/agent-zero2 discussions
- Prefer nonmutating multiset checksWhen doing algorithmic equality checks for arrays where order doesn’t matter (multiset equality), avoid (a) mutating the input with `.sort()` and (b) sort+join/stringify approaches when a linear-time counting strategy is available. Use a non-mutating sort (`toSorted`) only if sorting is truly the chosen approach; otherwise prefer counting maps (expected...vercel-labs/agent-skills2 discussions
- Effect cleanup and subscriptionsWhen using React hooks that interact with external systems (browser events, subscriptions, async requests), write code so it cannot leak resources or update state after the component unmounts.vercel-labs/agent-skills2 discussions
- Isolate errors, avoid cascadesWhen a feature depends on multiple probes/loads, ensure that failures in secondary/best-effort steps don’t corrupt primary state or cause cascading failures.decolua/9router2 discussions
- Encapsulate Memoization CacheWhen implementing in-memory caching (e.g., memoization), use a `Map` for the cache and keep the cache implementation private. - Use `Map` instead of plain objects to avoid prototype/key pitfalls and to support non-string keys safely.30-seconds/30-seconds-of-code2 discussions
- Define error contractsWhen handling invalid input or terminal conditions, explicitly define and implement your error-handling contract. Avoid “surprising exits” (e.g., returning `false` or silently stopping) unless it’s part of the documented API. Either:30-seconds/30-seconds-of-code2 discussions
- Async for slow workWhen code performs potentially slow CPU/crypto work, avoid blocking the event loop. Prefer a Promise/callback-based asynchronous wrapper so the runtime can continue handling other work, and keep the function’s API surface consistent so it can replace a sync version without call-site changes. Also ensure your team’s documentation defines async accurately...30-seconds/30-seconds-of-code2 discussions
- Warn against sudoApplications that may need elevated privileges should explicitly warn against running the entire application with sudo. Instead, implement and document proper privilege escalation mechanisms (like polkit on Linux) for specific tasks requiring higher permissions.zed-industries/zed1 discussion
- avoid eval() functionThe eval() function executes arbitrary JavaScript code from strings, creating significant security vulnerabilities including code injection attacks. This is especially dangerous when processing external data like API responses, user input, or browser logs that could contain malicious code.facebook/yoga1 discussion
- Privacy documentation clarityWhen documenting data collection practices, telemetry, or analytics features, explicitly enumerate what sensitive information is NOT collected to ensure transparency and build user trust. Privacy statements should be clear, comprehensive, and easily understandable.cloudflare/workers-sdk1 discussion
- prefer standard crypto functionsUse Node.js built-in crypto module functions instead of third-party cryptographic libraries when possible. The built-in crypto module is well-maintained, follows established standards, and provides better security guarantees than external alternatives.cloudflare/workers-sdk1 discussion
- audit third-party dependenciesBefore using third-party actions, libraries, or dependencies that require access to sensitive data (tokens, secrets, credentials), conduct a thorough security audit. Third-party code, especially when source is obfuscated or built/compiled, poses significant security risks when granted access to sensitive resources.cloudflare/workers-sdk1 discussion
- Configure secret scanning exceptionsWhen embedding test certificates or cryptographic keys in code for testing purposes, configure secret scanning tools to exclude these legitimate test artifacts to prevent false positive alerts. This ensures security tooling remains effective while avoiding alert fatigue that could lead to ignoring genuine security issues.cloudflare/workerd1 discussion
- use strong keysAlways use secure cryptographic algorithms and minimum key sizes—even for dummy, test, or helper keys. Avoid generating or shipping 1024-bit RSA keys (they are considered weak). Prefer modern algorithms (ed25519) when supported; otherwise use at least 2048-bit RSA. Mark any ephemeral/dummy keys clearly in code, avoid persisting them, and follow library...wavetermdev/waveterm1 discussion
- Sanitize CSS valuesWhen generating CSS from external data (JSON, user input, theme files), validate and sanitize both CSS property names and values before injecting them into style elements to prevent style-breaking input and XSS/style injection.wavetermdev/waveterm1 discussion
- Use Sudo HelperWhen writing shell scripts that run privileged operations, never call `sudo` directly or execute such commands silently. Centralize privilege escalation in a helper that (1) prints the exact command being run, (2) prompts for confirmation by default, and (3) provides an explicit, documented non-interactive escape hatch for CI (e.g., an env var like...warpdotdev/warp1 discussion
- Update security patches regularlyAlways keep dependencies, runtime environments, and libraries updated with the latest security patches to mitigate known vulnerabilities. Prioritize security updates even for minor version changes.microsoft/vscode1 discussion
- Shell-specific input escapingWhen processing user input that will be used in shell commands, implement shell-specific escaping mechanisms to prevent command injection vulnerabilities. Different shells (bash, PowerShell, zsh, fish) have different escaping requirements that must be handled appropriately.microsoft/vscode1 discussion
- Document security implicationsWhen writing documentation that involves handling sensitive data or security-related operations, always include explicit warnings about security implications and provide references to security best practices. Users may not be aware of default security behaviors that could expose sensitive information.volcano-sh/volcano1 discussion
- avoid unnecessary privilege toolsDo not install privilege escalation tools like sudo, su, or doas in containers unless they are explicitly required for the application's functionality. Most containers run as root by default, making sudo redundant and potentially creating security vulnerabilities by expanding the attack surface.volcano-sh/volcano1 discussion
- Verify dependency integrityAlways verify the integrity of external dependencies, especially those downloaded from non-official or personal repositories. This helps prevent supply chain attacks where compromised packages could introduce security vulnerabilities.vitessio/vitess1 discussion
- Permission hierarchy awarenessWhen implementing permission checks, understand the hierarchical nature of permissions and avoid redundant checks. Higher-level permissions typically include lower-level ones. Ensure your authorization logic accounts for permission relationships to maintain security while keeping code efficient.vitejs/vite1 discussion
- Escape HTML content properlyAlways use specialized HTML escaping functions when outputting dynamic content to prevent Cross-Site Scripting (XSS) vulnerabilities. Don't rely on general serialization methods like JSON.stringify which may not correctly escape all HTML-sensitive characters or may add unnecessary escapes.vitejs/vite1 discussion
- explicit cryptographic parametersAlways explicitly specify security-critical parameters in cryptographic operations rather than relying on default values. This prevents vulnerabilities that could arise from misunderstood defaults or future changes to default behavior.vlang/v1 discussion
- Document cryptographic requirementsSecurity-critical functions, especially those involving cryptographic operations, must include clear and accurate documentation about their security requirements and assumptions. This is essential for preventing misuse that could lead to vulnerabilities.vlang/v1 discussion
- Mask sensitive tokensAlways mask sensitive tokens, credentials, and secrets in CI/CD workflows to prevent accidental exposure in logs or build outputs. In GitHub Actions, use the `::add-mask::` command before outputting or storing sensitive values in environment variables.astral-sh/uv1 discussion
- Document credential formatsWhen documenting security-sensitive parameters such as private keys, certificates, API tokens, or other authentication credentials, always specify the expected format including any required headers, footers, and structural elements. This prevents configuration errors that could lead to authentication failures or security vulnerabilities.Unstructured-IO/unstructured1 discussion
- validate input constraintsAlways validate user inputs against expected formats, constraints, and business rules before processing them. Implement explicit validation checks that fail fast with clear error messages when inputs don't meet requirements. This prevents security vulnerabilities from malformed or malicious inputs.unionlabs/union1 discussion
- Validate input before submissionAlways validate user input before enabling form submission to prevent processing of invalid or malicious data. This includes checking for empty required fields, format validation, and business logic constraints. Implement validation checks in the form's disabled state or submission handler to ensure only valid data can be processed.unionlabs/union1 discussion
- Add interactive element rolesWhen adding event handlers like `onClick` to non-interactive elements such as `div`, always include appropriate ARIA roles and keyboard event handlers. This prevents accessibility issues and reduces security vulnerabilities by ensuring all interactive elements are properly identified and managed.shadcn-ui/ui1 discussion
- Accessible security indicatorsEnsure all security-related UI elements such as warnings, error messages, and destructive action buttons meet WCAG contrast standards. Poor contrast in these elements creates an accessibility issue that can prevent users from noticing important security warnings or destructive actions, potentially leading to security vulnerabilities.shadcn-ui/ui1 discussion
- Precise documentation linksWhen creating error messages related to security, permissions, or access controls, always provide specific links to relevant documentation. Use query parameters, anchors, or other mechanisms to direct users to the exact section of documentation that addresses their issue, rather than linking to generic pages.vercel/turborepo1 discussion
- validate file pathsAlways validate and sanitize file paths when processing external input to prevent directory traversal attacks, zip slip vulnerabilities, and other path-based security issues. Check for minimum required path components, reject paths with suspicious patterns, and ensure paths stay within expected boundaries.traefik/traefik1 discussion
- Use authenticated env tokensAny service exposed to the network (e.g., via Docker `ports`) must be protected with authentication, and any secret used for that auth (e.g., Jupyter token/password) must come from environment variables (e.g., `.env`) rather than being hardcoded in versioned files. If a compose file uses placeholder defaults, treat them as non-production scaffolding and...TauricResearch/TradingAgents1 discussion
- Avoid unsafe codePrioritize memory safety and security over performance optimizations by avoiding unsafe code blocks, especially in libraries. Even when bounds are checked, unsafe code can introduce subtle security vulnerabilities and maintenance challenges. Prefer using safe Rust patterns and abstractions, even if it means a slight performance overhead (like an additional...huggingface/tokenizers1 discussion
- Sanitize command inputsWhen constructing commands that will be executed, always sanitize input values to prevent command injection vulnerabilities. Never directly substitute user-supplied or externally-sourced data into command strings without proper validation and sanitization.hashicorp/terraform1 discussion
- Least privilege for tokensAlways apply the principle of least privilege when configuring access tokens for CI/CD workflows and other automated processes. Use fine-grained tokens or permissions that grant only the minimum necessary access required for the specific operations. hashicorp/terraform1 discussion
- Unicode homoglyph validationValidate Unicode characters and detect potential homoglyph attacks where visually similar characters from different scripts could be used maliciously. Avoid overly broad patterns that automatically allow non-ASCII characters without proper validation, as these can hide security vulnerabilities.microsoft/terminal1 discussion
- Maintain package verificationAlways keep signature verification enabled in package managers, even in development environments, Docker containers, or when facing initialization challenges. Disabling signature verification creates a significant security vulnerability by allowing potentially compromised or malicious packages to be installed.tensorflow/tensorflow1 discussion
- Minimize credential data exposureWhen handling security credentials (particularly TLS certificates) in data structures intended for transmission or serialization, include only the minimum necessary identifying information. Avoid passing complete certificate chains or redundant fields that have already been validated upstream.temporalio/temporal1 discussion
- Minimize authentication complexityAvoid implementing redundant authentication steps when secure, direct methods are already available. Multiple authentication layers can introduce unnecessary complexity and potential security vulnerabilities. When identity files or tokens are already being used, evaluate whether additional login steps are truly required.gravitational/teleport1 discussion
- defer authentication promptsDefer mounting components that trigger authentication prompts (MFA, per-session authentication) until they are actually visible or needed by the user. This prevents multiple concurrent authentication requests that can cause failures due to hardware token limitations or daemon mutex conflicts.gravitational/teleport1 discussion
- Scope 401 LogoutAvoid triggering sensitive auth actions (like logout) based solely on a generic HTTP status (e.g., “any 401”). Instead, logout only when the 401 is clearly an authentication/session failure for known auth endpoints.supermemoryai/supermemory1 discussion
- Normalize host IPsWhen performing security checks on hosts/IPs (e.g., blocking private/loopback access), don’t rely on brittle string equality. Normalize `URL.hostname` first, because IPv6 literals are often returned in bracket form (e.g., `"[::1]"`, `"[::]"`), causing dead-code comparisons like `hostname === "::1"`.supermemoryai/supermemory1 discussion
- Avoid direct web fontsIn security-sensitive or privileged contexts like browser extensions, avoid directly loading fonts (or other static assets) from arbitrary remote URLs at runtime. Remote loading can break due to CORS and may create long-term reliability/security-review issues.supermemoryai/supermemory1 discussion
- Validate security-sensitive inputsAlways use appropriate validation mechanisms for security-sensitive inputs to prevent vulnerabilities. When implementing validation for headers, origins, user inputs, or any security-related data, consult security documentation and use established validators rather than creating custom validation logic.spring-projects/spring-framework1 discussion
- Inherit organization security policiesBefore implementing custom security documentation or procedures, check if your organization already provides standardized security policies that your repository can inherit. This avoids duplication, ensures consistency across projects, and leverages platform-specific security features. For GitHub repositories, organization-level security policies (.github...spring-projects/spring-boot1 discussion
- Keep secrets outDo not commit secret keys, credentials, or signing material to source code or public repos. Store secrets in environment variables or a managed secret store, load them at runtime, and ensure they are not present in repository history. Design signed tokens so that the server validates them and they are short-lived, and have a plan to rotate/revoke keys if...openai/skills1 discussion
- Use secure credential storageAvoid storing sensitive credentials like usernames and passwords in environment variables. Instead, use dedicated secrets management systems such as HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, or your CI/CD platform's built-in secrets management.SigNoz/signoz1 discussion
- validate external system inputsWhen integrating with external systems that receive repository or organizational information, always implement server-side validation to ensure the provided data belongs to authorized organizations or repositories. This prevents potential abuse where attackers could exploit organizational resources by spoofing repository information.servo/servo1 discussion
- maintain IAM role isolationEach resource should use the IAM role assigned to its associated function rather than sharing roles across different functional boundaries. Sharing roles between different functions or resources can create security vulnerabilities and potential privilege escalation paths.serverless/serverless1 discussion
- Safe URL navigationAlways use sanitized navigation utilities instead of directly manipulating `window.location` with potentially user-influenced data to prevent cross-site scripting (XSS) vulnerabilities. User-provided values can contain malicious scripts that execute when inserted into navigation contexts.getsentry/sentry1 discussion
- Secure dependency constraintsWhen specifying dependency version constraints, always include lower version bounds that exclude versions with known security vulnerabilities. For dependencies used directly in your code (not just transient dependencies), you have a responsibility to prevent users from inadvertently installing vulnerable versions, as this makes your own package vulnerable.getsentry/sentry-php1 discussion
- Comprehensive authentication notificationsAuthentication notifications must include specific context about the triggering action, clear instructions for legitimate use, expiration details, and explicit steps to take if the action was unauthorized. This enhances security by helping users identify potential account compromises and take appropriate action.getsentry/sentry1 discussion
- configurable security controlsDesign security mechanisms with configurable behavior to handle different threat scenarios and use cases. Avoid rigid, one-size-fits-all security implementations that may not suit all deployment contexts.strands-agents/sdk-python1 discussion
- Constant-time cryptographic validationAlways use constant-time comparison methods when validating cryptographic values to prevent timing side-channel attacks. Operations like comparing authentication tags, MACs, hashes, or any security-sensitive values should use dedicated APIs such as `CryptographicOperations.FixedTimeEquals()` rather than standard equality operators or methods.dotnet/runtime1 discussion
- Harden installation securityAny install/setup instructions and scripts must avoid common supply-chain and remote execution risks, and must clearly communicate the security posture.ruvnet/ruflo1 discussion
- Use explicit permission notationsWhen setting file permissions through system calls like `chmod`, always use explicit octal notation (with the `0o` prefix) rather than decimal integers. Decimal integers in permission contexts can lead to unintended access rights, creating security vulnerabilities through incorrect file permissions.astral-sh/ruff1 discussion
- validate client inputsAlways validate and sanitize client-provided data on the server side before processing. Client-side data, including form inputs, query parameters, and request bodies, should never be trusted without proper validation as it can be easily manipulated by malicious users.TanStack/router1 discussion
- Serialize dynamic code inputsAlways serialize or sanitize user-controlled data before embedding it in dynamically generated code to prevent code injection vulnerabilities. Unsanitized inputs containing special characters like quotes can break JavaScript syntax or enable malicious code execution.TanStack/router1 discussion
- Escape XML content securelyAlways use proper XML entity escaping instead of CDATA blocks when embedding XML-like content within XML documents. CDATA sections can be vulnerable to XML injection attacks if the content isn't properly validated or controlled. RooCodeInc/Roo-Code1 discussion
- API authorization validationAll API endpoints must implement proper authorization checks before processing requests, especially when authentication mechanisms like tokens are available. When adding new API routes, verify that appropriate authorization validation is in place to prevent unauthorized access to sensitive functionality.smallcloudai/refact1 discussion
- minimize public API exposureKeep internal implementation details private to reduce security attack surface. Public properties in header files can be accessed and potentially manipulated by external code, creating security vulnerabilities. Store internal state using private instance variables in the implementation file instead of exposing them through public properties.facebook/react-native1 discussion
- Use OAuth Authorization HeaderWhen authenticating requests with bearer tokens or OAuth-derived credentials, transmit them using the standards-based `Authorization` request header as required by the relevant OAuth specification. Avoid sending secrets via custom headers like `api_key`, and ensure documentation/examples match the OAuth flow requirements.infiniflow/ragflow1 discussion
- Use exec-form commandsWhen configuring container commands (e.g., Docker Compose), pass commands in exec/array form for any arguments that include secrets or externally provided values. This prevents shell parsing/whitespace issues and reduces the risk of injection via malformed values (including empty credentials).infiniflow/ragflow1 discussion
- Centralize input boundsWhen validating user-controlled numeric inputs, define allowed min/max values in one place and reuse them across both the UI/component props and the validation schema. Prevent mismatches where the UI permits one range but the schema enforces another (or vice versa), since this breaks input validation guarantees.infiniflow/ragflow1 discussion
- Scrub Tokens From URLsSensitive authentication tokens must not remain in the browser URL after they are consumed. Tokens in query parameters (`?token=`) will leak via browser history, server access logs, and `Referer` headers when users navigate away; removing URL fragments alone is insufficient if `?token=` is supported.QwenLM/qwen-code1 discussion
- Prefer modern securityWhen implementing security features (such as artifact signing), use current best practices and prefer pure-Java security libraries over native executables whenever possible. This approach simplifies configuration, improves portability, and reduces security risks associated with native executable dependencies and their complex configurations.quarkusio/quarkus1 discussion
- Test authentication dependenciesWhen updating authentication-related dependencies or adding new authentication capabilities (like SAML, OAuth, etc.), thoroughly test all authentication flows to prevent security vulnerabilities. Authentication components often have complex interdependencies that can lead to unexpected failures when versions change.prowler-cloud/prowler1 discussion
- Precise CSP configurationWhen integrating third-party services into your web application, carefully configure Content Security Policy (CSP) headers by explicitly specifying only the necessary domains for each directive. Understand the complete technical requirements of each service, including resources they might dynamically load. Add domains to appropriate directives based on how...prowler-cloud/prowler1 discussion
- Fix dependency vulnerabilitiesSecurity vulnerabilities in dependencies must be addressed immediately rather than bypassed with flags like `--no-verify`. When security scans identify vulnerabilities in libraries like the one detected in pyjwt:prowler-cloud/prowler1 discussion
- Avoid localStorage for credentialsDo not store user profiles, authentication tokens, or other sensitive user information in client-side storage mechanisms like localStorage or sessionStorage. This creates security vulnerabilities as these storage mechanisms are accessible to any JavaScript running on the page, including potential XSS attacks.prowler-cloud/prowler1 discussion
- Validate and normalize untrusted pathsWhen accepting file paths or names from untrusted input (e.g., prompts, API payloads) that will be written to disk or used to run external tools, enforce strict allow-list validation before use: reject absolute paths (both POSIX and Windows styles), path traversal segments, control characters, reserved device names (CON, PRN, AUX, NUL, COMn, LPTn), trailing...promptfoo/promptfoo1 discussion
- HTTP security headersEnsure that HTTP security headers are properly implemented and documented to prevent web vulnerabilities such as cache poisoning, clickjacking, and content type sniffing attacks. Security headers should be explicitly added to API responses and web endpoints as defensive measures.prometheus/prometheus1 discussion
- Force re-sign Darwin binariesWhen building binaries for macOS (Darwin), always force re-sign them to prevent compatibility issues caused by pre-existing signatures. Use the `--force` flag with codesign to overwrite any existing signatures that might interfere with binary execution.prometheus/prometheus1 discussion
- explicit authentication logicMake authentication and security-related boolean conditions explicit and direct rather than using intermediate variables that obscure the logic. This improves code readability, reduces the risk of misconfiguration, and makes security decisions more auditable.prometheus/prometheus1 discussion
- avoid GitHub template injectionAvoid using GitHub workflow template expressions `${{ }}` directly in shell commands within `run:` steps, as this can lead to template injection vulnerabilities. Untrusted input like branch names, PR titles, or commit messages can be crafted to execute arbitrary code since GitHub template expansion happens before workflow execution.prometheus/prometheus1 discussion
- vet third-party actionsBefore using third-party GitHub Actions or similar external dependencies, thoroughly review their security implications. Specifically: 1) Understand what tokens or credentials they require and how they use them, 2) Verify that permission checks and security features work as expected, 3) Avoid providing unnecessary credentials (like PATs when not required),...prisma/prisma1 discussion
- Store Tokens in SecretsDo not commit authentication credentials (e.g., GitHub personal access tokens, API keys, passwords) in versioned configuration files. Keep them in a dedicated secrets source such as `.secrets.toml` (or your secret manager), and ensure the committed config only contains placeholders/defaults.the-pr-agent/pr-agent1 discussion
- Verify HTML escapingAlways verify that user-controlled content in templates is properly HTML-escaped to prevent XSS attacks. Don't just assume framework defaults are working - actively test with potentially malicious input to confirm that HTML tags are rendered as text rather than executed.PostHog/posthog1 discussion
- Use proper authorization attributesAvoid using Django framework attributes like `is_staff` and `is_impersonated` for application role checking, as these serve different purposes (admin panel access and user impersonation respectively). Instead, use application-specific role validation methods to ensure proper authorization.PostHog/posthog1 discussion
- Use allowlists over blocklistsWhen filtering data for security purposes, prefer allowlists (explicitly defining what is permitted) over blocklists (explicitly defining what is forbidden). Blocklists are inherently less secure because they can miss new threats, require constant maintenance as infrastructure changes, and operate on the assumption that anything not explicitly blocked is...PostHog/posthog1 discussion
- Redact sensitive credentialsWhen implementing authentication or handling credentials, always redact sensitive information (keys, tokens, passwords) in logs and debug output. Using placeholder text like "<redacted>" or obfuscation techniques ensures credentials aren't accidentally exposed through logs, which could lead to security breaches.pola-rs/polars1 discussion
- Pin GitHub ActionsIn CI/CD workflows, mitigate supply-chain risk by ensuring every `uses:` action (first- and third-party) is pinned to an immutable full commit SHA, not a moving tag/branch. Optionally preserve the intended human version in a trailing comment. Also, set critical inputs explicitly when supported (e.g., toolchain selection) to keep builds deterministic.firecrawl/pdf-inspector1 discussion
- Secure encryption key backupsAlways implement proper encryption key management procedures, including secure backups of encryption keys before enabling encryption features. Without proper key backups, encrypted data can become permanently inaccessible, creating security and operational risks.opentofu/opentofu1 discussion
- Preserve sensitive data marksCarefully handle data marked as sensitive throughout the codebase to maintain security properties. Ensure that sensitive marks are only removed when necessary, and be aware that operations on marked data (such as reordering from nested to top level) could have security implications.opentofu/opentofu1 discussion
- Safe Static ParsingWhen parsing configuration or design-token files from external/untrusted sources, never execute their contents as part of scanning. Default to static, deterministic extraction and “fail closed” (e.g., return `null`/empty) when the config requires evaluation.calesthio/OpenMontage1 discussion
- Validate imported payloadsWhen ingesting untrusted data (e.g., JSON pasted/uploaded by users), validate the *entire* payload against a schema (including nested structures) before writing to storage or otherwise trusting it. Avoid relying on top-level presence checks or unsafe type casts; these can let malformed nested content persist and only fail later.opencut-app/opencut1 discussion
- Secure postMessage handlingWhen handling cross-window `postMessage`, don’t rely on a single `window.location.origin` check—loopback flows (e.g., `localhost` vs `127.0.0.1`) can be legitimate but have different origins. For security, combine: (1) strict message type checking, (2) a whitelist of allowed origins that includes known legitimate loopback variants, and (3) a correlation ID...diegosouzapw/OmniRoute1 discussion
- Disable install scriptsIn security-sensitive build environments (e.g., Docker/CI), prevent dependency install/postinstall hooks from executing arbitrary code. Use `npm ci` with `--ignore-scripts` to reduce supply-chain risk, but explicitly rebuild and validate any known native/runtime dependency that truly must compile/bind for the target platform.diegosouzapw/OmniRoute1 discussion
- Secure path resolutionWhen validating or resolving filesystem paths that cross trust boundaries (e.g., clone/checkout destinations, or pointer files copied from another repository), never trust lexical or unresolved paths — they can be disguised via symlinks or `..` traversal to escape intended boundaries or to keep referencing the original source's data after a copy....can1357/oh-my-pi1 discussion
- Escape interpolated template contentWhen building structured templates that embed untrusted or dynamically generated content (e.g., model output inserted into tag-delimited LLM prompts, or user input inserted into HTML/XML), always escape special characters before interpolation. Failing to do so lets the embedded content break out of its intended boundary—closing a wrapper tag and injecting...can1357/oh-my-pi1 discussion
- Audit dependency lifecycle scriptsWhen restricting which dependencies may run lifecycle (install/postinstall) scripts, explicitly maintain and audit the `trustedDependencies` list, and verify that your CI pipeline actually enforces the intended security behavior rather than silently succeeding. Package managers like Bun will skip untrusted lifecycle scripts by default and still report a...can1357/oh-my-pi1 discussion
- Validate CI/CD timing checksWhen implementing timing-based security checks in CI/CD workflows, ensure that timestamp comparisons use tamper-proof data sources that cannot be manipulated through commit history manipulation or force pushes. Always verify that the timestamps being compared (such as PR updated_at vs comment created_at) come from authoritative sources that reflect actual...nuxt/nuxt1 discussion
- Enforce permission-based UI controlsAlways implement proper authorization checks in UI components that expose sensitive functionality. Wrap buttons, forms, and other interactive elements that perform create, update, delete, or other privileged operations with permission-based controls to prevent unauthorized access.novuhq/novu1 discussion
- Scope security settingsAvoid modifying global security state in favor of connection-specific or context-bound security settings. Global security state changes can lead to unexpected security vulnerabilities when modified by dependencies without application awareness.nodejs/node1 discussion
- Document security attributesWhen handling security-related attributes (like nonces, integrity hashes, or CSP directives), always document the logic and prioritize explicitly passed values over automatically provided ones.vercel/next.js1 discussion
- Decode before validationAlways decode URL paths before performing security validations to prevent bypass attacks using URL encoding. Security mechanisms that rely on string pattern matching can be circumvented when attackers use URL-encoded characters.vercel/next.js1 discussion
- Secure proxy endpointsProxy endpoints that forward requests to external services can be exploited by malicious actors if left unsecured. Always implement proper authentication, authorization, and destination validation for proxy endpoints, especially in production deployments.ChatGPTNextWeb/NextChat1 discussion
- Use secure hash algorithmsAlways use strong, modern cryptographic hash algorithms for security-sensitive operations. Avoid deprecated or weak algorithms that might be vulnerable to attacks. When selecting hash algorithms, consider both security requirements and performance characteristics.nestjs/nest1 discussion
- Secure hash algorithmsAlways use cryptographically secure hash algorithms for sensitive operations instead of weak or broken ones. Weak algorithms can compromise security and make your application vulnerable. Prefer modern algorithms like SHA-256 over older or non-cryptographic hash functions.nestjs/nest1 discussion
- Proactive dependency securityAlways maintain dependencies at their latest secure versions, even when automated vulnerability scanning tools (like `npm audit`) don't report issues. Regularly check release notes and security advisories for your dependencies, as some security fixes may not be detected by automated tools.nestjs/nest1 discussion
- Comprehensive dependency security checksRegularly check dependencies for security vulnerabilities using multiple sources, not just npm audit. As shown in the discussion, some vulnerabilities may not be reported by npm audit but are still present and documented elsewhere.nestjs/nest1 discussion
- Security warnings need guidanceSecurity-related warnings and error messages should provide clear, actionable guidance on how users can safely resolve the issue, not just inform them of the problem. When displaying security warnings, include specific instructions that guide users through the secure workflow.neovim/neovim1 discussion
- Prefer opt-in securityWhen implementing security features that modify data presentation or alter normal data access patterns (like anonymization, masking, or redaction), design them to be explicitly enabled by users rather than activated by default. Default-enabled data transformation creates security and usability concerns as users may not expect or desire their data to be...neondatabase/neon1 discussion
- Harden CI/CD runnersAll CI/CD workflow jobs must implement security controls for network traffic, particularly using the step-security/harden-runner action or equivalent technology. This prevents potential supply chain attacks or unauthorized data exfiltration during automated builds and tests.neondatabase/neon1 discussion
- Escape SQL parametersAlways escape parameters in database connection strings to prevent SQL injection attacks. Direct string concatenation with user-provided or database-sourced values creates security vulnerabilities that can be exploited.neondatabase/neon1 discussion
- Validate by File HeaderWhen parsing untrusted files (e.g., images), do not choose decode/encode logic based on filename suffix/substring (e.g., “.pgm/.ppm/.jpg”). Instead, detect the actual format using file content (magic bytes/header) and only proceed if it matches supported signatures; otherwise fail safely.Tencent/ncnn1 discussion
- Secure credential managementNever hardcode sensitive information like passwords, API keys, or access tokens directly in code or configuration files (including Dockerfiles). These credentials can be exposed through version control systems, shared images, or when files are accessed by unauthorized users.n8n-io/n8n1 discussion
- Restrict database accessNever allow unrestricted public access (0.0.0.0/0) to database instances. Restrict database network access to only specific trusted IP ranges or VPC networks that require it, following the principle of least privilege. This prevents potential unauthorized access and data breaches.n8n-io/n8n1 discussion
- Avoid hardcoded credentialsNever hardcode sensitive information such as passwords, API keys, or authentication tokens in source code, configuration files, or container definitions. These can be exposed through version control systems, shared repositories, or compromised container images.n8n-io/n8n1 discussion
- Avoid eval functionNever use the `eval()` function in Python code as it creates serious security vulnerabilities by executing arbitrary code at runtime. This can lead to code injection attacks when processing user inputs or data from untrusted sources.apache/mxnet1 discussion
- Safe URL/SVG EscapingWhen building URL-like strings that will be embedded into SVG attributes (e.g., `marker-end="url(...)"`), do not rely on upstream HTML escaping. Apply context-specific escaping/encoding for the exact attribute syntax, ensuring correct escaping order (notably escape backslashes first) and covering all unsafe characters—not just parentheses.mermaid-js/mermaid1 discussion
- Pin Actions SHAsFor security-sensitive CI workflows, pin third-party GitHub Actions to immutable commit SHAs (not floating tags like `v3`/`v4`). This prevents supply-chain risk from upstream tag changes. Use Dependabot (or equivalent) to keep pinned SHAs updated automatically.mermaid-js/mermaid1 discussion
- Bundle Static AssetsAvoid directly linking UI/static assets (e.g., icons, images) to external domains. Keep them inside the repository and reference them via local paths so builds don’t depend on third-party availability, reduce tracking/privacy exposure, and minimize supply-chain risk.mermaid-js/mermaid1 discussion
- Least Privilege CI PermissionsIn CI/CD (e.g., GitHub Actions), follow least-privilege for the built-in `GITHUB_TOKEN`. Avoid granting broad, workflow-wide permissions. Default to no permissions at the top level, then explicitly grant only what a specific job needs.awslabs/mcp1 discussion
- Use 404 over 403When blocking access to security-sensitive endpoints or directories, return HTTP 404 (Not Found) instead of 403 (Forbidden) to prevent information disclosure. A 403 response reveals that the resource exists but access is denied, which can provide valuable reconnaissance information to attackers. A 404 response makes it harder for attackers to determine what...mastodon/mastodon1 discussion
- referrer header privacyWhen implementing features that link to external sites, carefully consider referrer policies to prevent unintended disclosure of sensitive information about users or the origin server. HTTP referrer headers can inadvertently expose details about what type of community, instance, or service users belong to, which may have privacy or safety implications.mastodon/mastodon1 discussion
- Default to minimum permissionsAlways default to the least invasive privacy settings and explicitly request elevated permissions only when necessary for specific functionality. For location-based features, start with reduced accuracy and request precise location only when required with a clear purpose explanation.maplibre/maplibre-native1 discussion
- Buffer bounds validationAlways validate buffer boundaries before performing memory operations to prevent buffer overflow vulnerabilities. When copying data into a buffer at a specified offset, verify that the combination of size and offset doesn't exceed the buffer's allocated capacity.maplibre/maplibre-native1 discussion
- Prevent credential exposureEnsure that sensitive authentication data such as API keys, tokens, passwords, and other credentials are never exposed in documentation, client-side code, logs, or configuration files. This includes both preventing accidental inclusion in documentation and implementing proper secure handling in application code.lobehub/lobe-chat1 discussion
- Design extensible permission systemsWhen implementing authorization features, design permission systems that can accommodate future security requirements rather than adding permissions directly to existing tables. Create dedicated permission tables with proper relationships to entity tables to ensure authorization can be properly enforced.BerriAI/litellm1 discussion
- avoid hardcoded credentialsNever embed sensitive credentials, passwords, API keys, or other secrets directly in source code. Hardcoded credentials create security vulnerabilities by exposing sensitive data in version control systems and making it accessible to anyone with code access.BerriAI/litellm1 discussion
- disallow unsafe schemesTreat resource URIs and external references as untrusted input: normalize and validate schemes, and reject anything not on an explicit allowlist. Motivation: schemes such as file: (and other unsafe schemes like javascript: or data: when used for resources) can expose local files or enable injection attacks, and are commonly blocked by browsers — so they...likec4/likec41 discussion
- avoid raw injectionWhen generating and inserting HTML or CSS as raw strings, treat it as untrusted input and avoid direct injection into the DOM. Constructing <style> tags or innerHTML from dynamic values can enable XSS if any part of those values is attacker-controlled.likec4/likec41 discussion
- Secure env lookupWhen writing security-sensitive shell hooks/scripts, resolve credential *presence* safely: don’t read or print secret values, avoid `eval` for variable indirection, and enforce a deterministic, documented precedence order between `ENV_<KEY>` and raw env vars, falling back to OS keychain presence checks.mvanhorn/last30days-skill1 discussion
- Encrypt sensitive credentialsSensitive credentials such as API keys, passwords, access tokens, and secret keys should never be stored in plain text in databases or configuration files. This creates significant security risks if the database is compromised or if unauthorized access occurs.langfuse/langfuse1 discussion
- Avoid automatic package executionUsing `npx --yes` bypasses security prompts and automatically installs packages without verification, which could lead to supply chain attacks if package names are typosquatted or compromised. Always install required tools as explicit dependencies in your project.langfuse/langfuse1 discussion
- Use fake sample dataAlways use completely fictional personal information in sample files, documentation, test data, and code examples to prevent privacy violations and unintentional exposure of real people's data. Real names, email addresses, phone numbers, and social media profiles should never appear in sample data as they can link to actual individuals and create privacy...langflow-ai/langflow1 discussion
- Treat Jinja2 as UnsafeDon’t trust “sandboxed” templating when any part of template text (or dangerous expressions) can be influenced by an untrusted party. For security-sensitive code, assume Jinja2 (and similar template engines) is dangerous with untrusted inputs and enforce strict trust boundaries.langchain-ai/langchain1 discussion
- minimize security dependenciesFor security-sensitive operations like shell argument parsing, input validation, or cryptographic functions, prefer copying minimal, well-understood code over adding external dependencies, especially when:kubernetes/kubernetes1 discussion
- minimize RBAC permissionsWhen defining RBAC rules and authorization policies, grant only the minimum necessary permissions required for the intended functionality. Avoid copying broad permission sets or including unnecessary verbs that expand the attack surface.kubernetes/kubernetes1 discussion
- Private vulnerability reportingNever expose security vulnerabilities in public issue trackers. Security issues require confidential handling to prevent exploitation before fixes are available. Use private reporting channels such as:kubeflow/kubeflow1 discussion
- Prevent XSS vulnerabilitiesNever directly concatenate untrusted data (like user inputs or API responses) into HTML strings, as this creates cross-site scripting (XSS) vulnerabilities. Instead, create the HTML structure first, then populate content using safe DOM manipulation methods like jQuery's .text() or native JavaScript's .textContent that automatically escape special characters.kubeflow/kubeflow1 discussion
- Harden container securityWhen building container images, ensure they're compatible with restricted Kubernetes security contexts. Use numeric UIDs instead of symbolic usernames, and test compatibility with the following security constraints:kubeflow/kubeflow1 discussion
- Enforce HTTPS protocolAlways validate that URLs use the HTTPS protocol in both implementation code and validation error messages. Even if your application might handle HTTP-to-HTTPS redirects, enforce HTTPS from the outset as a security best practice to prevent man-in-the-middle attacks and data exposure.kubeflow/kubeflow1 discussion
- Control header modificationWhen allowing user-configurable HTTP headers in your application, implement strict validation to prevent security bypasses. Users should never be allowed to override security-critical headers that could compromise authentication or authorization mechanisms.kubeflow/kubeflow1 discussion
- Configurable security with defaultsMake security features configurable through environment variables or configuration files, but always implement secure defaults. This allows teams to adapt security controls to their specific deployment environments while maintaining a secure baseline.kubeflow/kubeflow1 discussion
- Document security implementationsAlways document non-obvious security implementations, especially authentication mechanisms, with explanatory comments and references to underlying implementation details or documentation. Security-related code should be explicit and clear to prevent misunderstandings that could lead to vulnerabilities.JetBrains/kotlin1 discussion
- Verify Downloaded ArtifactsAny CI/install workflow that downloads a binary or other external artifact must verify its integrity before use. Apply this standard: - Prefer immutable references (commit SHA/immutable artifact IDs) when your tooling supports it.Kong/kong1 discussion
- No Blanket Vulnerability IgnoresSecurity scanner ignore files must not use broad “blanket” suppression that can hide future real issues. **Standard** - Avoid rules that ignore by coarse attributes (e.g., `fix-state: unknown`) for wide sets of findings.Kong/kong1 discussion
- Evaluate CI secret exposureBefore using secrets in CI/CD workflows that can be triggered by external contributors (forks, dependabot), assess the "blast radius" of potential secret compromise. Differentiate between high-risk secrets that provide infrastructure access and limited-scope secrets with constrained permissions.kilo-org/kilocode1 discussion
- verify authorization permissionsEnsure that authorization checks use the appropriate permission level for the specific operation being performed. Operations that only read data should use READ permissions, while operations that modify data should use WRITE permissions. Using overly permissive authorization can lead to privilege escalation vulnerabilities.apache/kafka1 discussion
- Secure GPG verificationWhen downloading and verifying packages using GPG signatures, follow secure practices to ensure authenticity and prevent security vulnerabilities. Use hardcoded GPG keys rather than dynamic ones, employ reliable keyservers, set proper GNUPGHOME environment, and clean up GPG processes after verification.apache/kafka1 discussion
- avoid password conversionsWhen handling sensitive data like passwords, avoid unnecessary type conversions that create additional copies in memory. Pass char[] arrays directly to methods that accept them instead of converting to String and back to char[]. This minimizes the number of sensitive data copies in memory and reduces the attack surface.apache/kafka1 discussion
- Avoid external URLsLinks to external repositories or domains in documentation and code can create security vulnerabilities through URL hijacking attacks. Malicious actors could potentially gain control of external domains and redirect users to harmful content or credential harvesting sites.menloresearch/jan1 discussion
- Document security behavior referencesWhen implementing security-related functionality such as certificate parsing, cryptographic validation, or authentication mechanisms, always document the expected behavior and include references to official documentation that explains the underlying security decisions.istio/istio1 discussion
- audit license dependenciesAlways verify the licensing compatibility of all dependencies, especially in security-critical networking code. GPL and other restrictive licenses can create legal compliance issues and security vulnerabilities through forced disclosure requirements or usage restrictions.istio/istio1 discussion
- Validate URL Query SecretsWhen accepting user-provided stream URLs, treat them as security-sensitive input: parse the URL and reject links that appear to contain expiring-session credentials or secrets in the query string. These are typically short/unsigned tokens, hashes, or random identifiers (e.g., nimblesessionid, authid, key, secret, hmac, token, e, ip, st). Such URLs are...iptv-org/iptv1 discussion
- Vet security-critical dependenciesWhen introducing new dependencies, especially those handling sensitive operations like language interpreters, perform comprehensive security due diligence before adoption. Evaluate each dependency against these security criteria:influxdata/influxdb1 discussion
- Secure dependency managementAlways maintain secure dependencies by following these two critical security practices: 1. **Keep dependencies updated with the latest security patches** - Regularly check for and apply updates that contain security fixes. Pin to specific versions but review them frequently.elie222/inbox-zero1 discussion
- Quote shell substitutionsAlways enclose command substitutions in double quotes when assigning to variables or using in shell scripts to prevent word splitting vulnerabilities. Unquoted command substitutions can lead to unexpected behavior or security vulnerabilities if the output contains spaces or special characters, potentially enabling command injection attacks.elie222/inbox-zero1 discussion
- Enforce user scopingAll database queries must include appropriate user scoping to prevent unauthorized data access and Insecure Direct Object Reference (IDOR) vulnerabilities. Every query should filter results based on the authenticated user's context using `emailAccountId`, `userId`, or equivalent identifiers in WHERE clauses.elie222/inbox-zero1 discussion
- prefer specific cryptographic librariesWhen adding cryptographic dependencies, critically evaluate whether broad libraries like OpenSSL are necessary or if more specific, focused alternatives can meet your requirements. Broad cryptographic libraries often include extensive functionality that may not be needed, potentially increasing the attack surface and complexity.juspay/hyperswitch1 discussion
- Preserve signing entitlementsOn macOS, treat re-signing (including ad-hoc re-sign after quarantine stripping) as a security-sensitive operation: preserve the app’s entitlements for the main bundle and any helper apps. Otherwise, macOS TCC access (mic/screen audio) may break or continuously prompt because the re-signed artifacts no longer carry the expected entitlements. Also ensure...nousresearch/hermes-agent1 discussion
- Enforce auth preconditionsSecurity-sensitive state (e.g., creating/persisting a profile that assumes a working remote connection) must not be created when required authentication material is missing or invalid. If downstream token-auth/config saving will reject empty/placeholder tokens, block the flow up front or use a staged/OAuth flow so the local profile is only finalized after...nousresearch/hermes-agent1 discussion
- sanitize filesystem inputsWhen constructing filesystem paths or filenames from external input (model names, user-provided identifiers, etc.), treat those strings as untrusted. Whitelist allowed characters, disallow dots and path separators, and verify the final path stays inside the intended directory to prevent path traversal or accidental file access/deletion.p-e-w/heretic1 discussion
- limit CI tokensAlways prefer the built-in GITHUB_TOKEN, explicitly document why it’s needed, and grant it only the minimum permissions required. For third‑party actions that call the GitHub API, pin them and justify token usage in the workflow so reviewers can verify scope and intent.p-e-w/heretic1 discussion
- Sanitize Unicode ControlsAny dynamically generated text that will be displayed (e.g., status/tab text from command output, runtime data, or user/config input) must be sanitized to prevent rendering-based attacks (bidi overrides, zero-width/invisible manipulations).ogulcancelik/herdr1 discussion
- Enforce Sensitive File PermissionsWhen creating or updating files that persist user-controlled commands/state for later execution (hooks, observer/session forwarding, etc.), treat the contents as sensitive and enforce least-privilege permissions at install/write time. Verify the permissions in an automated install/integration test so regressions are caught early.ogulcancelik/herdr1 discussion
- Least-privilege database grantsEnabling Row Level Security (RLS) alone is not sufficient to secure a new table—Postgres/Supabase grants default privileges to roles like `anon` and `authenticated` that can allow unintended access even with RLS enabled unless explicit policies are also defined. When creating tables for sensitive or system-level data, always explicitly revoke default...Helicone/helicone1 discussion
- Use appropriate permission checksWhen implementing role-based access control (RBAC), ensure you use the correct permission verification method based on the security context. Distinguish between:grafana/grafana1 discussion
- Update vulnerable dependenciesAlways update dependencies with known security vulnerabilities to their patched versions. Dependencies with security issues can introduce vulnerabilities into your application even if your own code is secure.grafana/grafana1 discussion
- Avoid plaintext credentialsNever include plaintext passwords or credentials in connection strings, configuration files, or documentation examples. This creates security vulnerabilities as credentials could be exposed in logs, version control, or to unauthorized personnel.grafana/grafana1 discussion
- Separate auth and routingWhen using OpenAI-compatible providers/proxies, treat authentication and endpoint routing as separate concerns: - **Auth comes only from the API key** (e.g., `OPENAI_API_KEY`). If the key is missing/unloaded, requests may be sent with no auth and you’ll typically see `401` (e.g., `No api key passed in`).aaif-goose/goose1 discussion
- Secure extension installWhen publishing extension/server install options (especially deep-links or Install buttons), default to a secure-by-default path: require explicit/manual installation for binary-first or otherwise security-sensitive extensions. Only enable an automated install/deeplink if the target is explicitly allowlisted.aaif-goose/goose1 discussion
- inline external dependenciesFor security-critical applications, prefer inlining external dependencies (JavaScript libraries, CSS frameworks) rather than loading them from CDNs or external sources at runtime. This approach eliminates risks from compromised external sources, network-based attacks, and supply chain vulnerabilities.block/goose1 discussion
- Secure temporary filesAlways use `mktemp` instead of manually constructing temporary file paths with random values. Manually constructed paths with elements like `$RANDOM` or timestamp values can be vulnerable to race conditions, predictability issues, and permission problems, potentially leading to security exploits.ghostty-org/ghostty1 discussion
- Sanitize debug outputNever print or log sensitive information such as tokens, passwords, or secrets that might be present in environment variables or configuration. When debugging with environment variables, always sanitize the output by filtering out sensitive keys.ghostty-org/ghostty1 discussion
- test security end-to-endSecurity features must be tested using the actual executable or CLI rather than just module-level unit tests. This ensures the complete security mechanism works end-to-end in the real execution environment, not just individual components in isolation.google-gemini/gemini-cli1 discussion
- secure authentication flowsAuthentication flows should be designed to provide a seamless user experience while maintaining security standards. Avoid implementing temporary workarounds that require users to perform multiple steps, quit and restart applications, or follow complex sequences to authenticate successfully.google-gemini/gemini-cli1 discussion
- Generic security configuration namingWhen implementing security-related configuration options, use generic, implementation-agnostic naming conventions rather than tying them to specific tools or runtimes. This approach ensures flexibility as the underlying technology stack evolves and prevents vendor lock-in in security configurations.google-gemini/gemini-cli1 discussion
- Non-root container usersAlways run containers with a non-root user to reduce the security attack surface. Modern Docker allows non-root users to bind to privileged ports (80, 443), eliminating a common reason for using root. Create a dedicated user and group in your Dockerfile and ensure your application runs with that user's privileges.fatedier/frp1 discussion
- Encode International URLsWhen adding or modifying external URLs, ensure international/non-ASCII URLs are **percent-encoded** (UTF-8 → percent-encoding). Do not treat “escape” as a vague idea—use proper URL encoding so links render correctly across clients and avoid malformed/ambiguous URL behavior.EbookFoundation/free-programming-books1 discussion
- secure XML parsingWhen configuring XML parsing options, carefully evaluate security implications of each setting, especially those that enable potentially risky features like DTD processing. Document the business justification for enabling such features and verify that the chosen library provides adequate protection against common XML-based attacks (XXE, DTD attacks, etc.).firecrawl/firecrawl1 discussion
- remove unnecessary authenticationAvoid initializing authentication mechanisms, credentials, or identity objects when they are not actually used in the code. This follows the security principle of least privilege and reduces potential attack surface by minimizing credential exposure.firecrawl/firecrawl1 discussion
- Secure Content-Type validationWhen implementing Content-Type validation, ensure regular expressions start with '^' or include ';?' to properly detect the essence MIME type. Improper validation patterns may create vulnerabilities to CORS attacks.fastify/fastify1 discussion
- Vet third-party dependenciesBefore adding any new dependency, verify it is legitimate, actively maintained, and actually necessary—never add a package that merely duplicates or shadows built-in functionality (e.g., the npm 'path' package, which is just a copy of Node's core 'path' module). Unvetted or redundant dependencies expand the supply-chain attack surface and can introduce...Expressjs/Express1 discussion
- Use unique password saltsWhen implementing password hashing, always use unique, randomly generated salts for each user. Using constant or shared salts significantly reduces security by allowing identical passwords to produce identical hashes, making them vulnerable to rainbow table attacks.expressjs/express1 discussion
- Team-based access controlAuthorization to repositories and organizations must follow the principle of least privilege and be as auditable and revocable as possible. Prefer managing permissions through GitHub Teams rather than granting access to individual accounts: assign a role (e.g., Technical Committee, Triage) to a team, then add/remove members from that team to grant or revoke...expressjs/Express1 discussion
- Prefer team-based access controlWhen defining authorization models for repositories or organizations, prefer granting permissions to GitHub Teams rather than to individual accounts. Team-based access lets you grant and revoke a whole set of permissions by simply adding or removing a member from the team, which is far less error-prone and easier to audit than manually setting bespoke...Expressjs/Express1 discussion
- Pin action commit hashesAlways pin third-party GitHub Actions to specific commit hashes rather than semantic version tags (like `@v1`). This prevents automatic execution of potentially malicious code if the maintainer updates the tag. Additionally, minimize permission scopes for any tokens used in workflows, and consider replacing third-party actions with direct implementations...expressjs/express1 discussion
- No committed certificates or secretsNever check SSL/TLS certificates, private keys, tokens, or other security-sensitive credentials into version control, even in examples or test fixtures. Certificates expire and committed ones quickly become stale or invalid, and storing any cryptographic material in a repo creates unnecessary security risk and encourages bad habits. Instead, generate these...expressjs/Express1 discussion
- Avoid committing certificatesNever commit SSL/TLS certificates, private keys, or other generated cryptographic material into the repository. These artifacts expire, can leak sensitive key material, and quickly become stale or invalid. Instead, exclude them via .gitignore and provide a script or documented steps (e.g., in README.md) for generating them locally, optionally referencing an...Expressjs/Express1 discussion
- strip event parametersWhen exposing IPC event handlers through contextBridge in Electron applications, always strip the event parameter before calling renderer callbacks to prevent security vulnerabilities. The event object contains `event.sender` which can be exploited by malicious code in the renderer process to send arbitrary IPC messages, leading to privilege escalation.electron/electron1 discussion
- Remove internal APIsDelete internal system properties and APIs after use to prevent application code from accessing protected functionality. This security practice ensures that internal methods cannot be called by user code, protecting system integrity and preventing potential security vulnerabilities.electron/electron1 discussion
- Enforce least privilegeAlways assign the minimum permissions necessary for functionality when implementing role-based access controls. This fundamental security principle reduces the potential attack surface and minimizes the impact of compromised accounts.elastic/elasticsearch1 discussion
- Limit postMessage data exposureWhen using postMessage for inter-window communication, avoid sending raw event data or generic message types that could expose sensitive information. Instead, use specific, predefined message types and only send the minimum necessary data.dyad-sh/dyad1 discussion
- Escape untrusted inputAlways use appropriate escaping mechanisms when handling input from untrusted sources to prevent injection attacks. User-provided data that contains special characters or operators can be interpreted in unintended ways if not properly escaped, leading to security vulnerabilities like XSS, SQL injection, or command injection.django/django1 discussion
- use Guardian authorization classesAlways implement authorization checks using Guardian classes rather than ad-hoc permission logic. Guardian classes provide a centralized, consistent approach to authorization that helps prevent security vulnerabilities from inconsistent or missing permission checks.discourse/discourse1 discussion
- enforce consistent SSO flowsWhen single sign-on (SSO) is enabled as the primary authentication mechanism, ensure all authentication entry points consistently redirect to the SSO endpoint without complex conditional logic. Avoid respecting secondary authentication parameters that could create inconsistent behavior or potential security gaps.discourse/discourse1 discussion
- disable sensitive data defaultsFeatures that handle sensitive data such as credit card information, passwords, or personal details should never be enabled by default. These features must require explicit user opt-in to ensure users consciously consent to the handling of their sensitive information.zen-browser/desktop1 discussion
- Normalize security inputsFor any security-sensitive policy/matching logic (authZ/exec policies, allow/deny rules, pattern matching), always canonicalize the relevant inputs before matching, and ensure edge cases like absolute-path `..` are handled safely to prevent bypass.Hmbown/DeepSeek-TUI1 discussion
- Use safe URL encodingWhen constructing connection strings/URIs that embed user credentials, always URL-encode username/password (and other URI components as needed) using an encoder that safely handles reserved characters. Avoid `urllib.parse.quote` for credentials where characters like `@` and `#` may appear; prefer `quote_plus`.eosphoros-ai/DB-GPT1 discussion
- Document security policy trade-offsWhen implementing security policies like Content Security Policy (CSP), always include clear documentation explaining the reasoning behind each directive choice and any security trade-offs being made. This prevents confusion during code reviews and ensures team members understand the security implications.cypress-io/cypress1 discussion
- Clear security error messagesWhen implementing security restrictions or policies, ensure error messages clearly explain what the security boundary is, why it exists, and what specifically triggered the violation. Vague or technical jargon can leave developers confused about security requirements.cypress-io/cypress1 discussion
- Obfuscate test secretsDo not commit cryptographic material that looks like a real secret (private keys, signed certificates, passwords, tokens) into the repository in plain text, even when it is intentionally generated for tests (e.g., a "distrusted" or revoked test certificate/key). Automated secret scanners used by mirrors, CI systems, and security report pipelines cannot...python/cpython1 discussion
- trust server-side validationWhen integrating with external APIs or services that implement their own input validation, avoid duplicating that validation logic on the client side. Trust the authoritative server's validation mechanisms rather than attempting to replicate them locally.home-assistant/core1 discussion
- classify data sensitivityProperly evaluate whether data contains sensitive information before applying security measures like redaction. Not all identifiers or structured data require protection - understand the nature and content of the data to make informed security decisions.home-assistant/core1 discussion
- Prevent injection vulnerabilitiesWhen constructing templates or dynamic content that will be parsed, always implement robust escaping mechanisms to prevent injection vulnerabilities. Avoid using delimiters in template strings that might appear in the content itself, as this could break formatting or enable code injection attacks.continuedev/continue1 discussion
- Accessible security controlsSecurity controls and interactive elements must be accessible to all users to prevent unequal security access. When non-standard elements (like divs) are used for interaction, they must include proper accessibility attributes to ensure users with disabilities can access security features.continuedev/continue1 discussion
- Require Download DigestsWhen downloading remote security-sensitive artifacts (e.g., kernels, binaries, containers), require an expected cryptographic digest (e.g., `sha256:<hex>`) and verify it before use. Treat missing digests for custom/variable URLs as a policy violation (fail closed) to prevent unverified or tampered downloads.apple/container1 discussion
- Check Privilege EarlyWhen a script performs privileged or security-sensitive actions (e.g., deleting/installing application files in system directories), explicitly enforce the required authorization before proceeding.apple/container1 discussion
- Use organizational secretsWhen working with GitHub Actions workflows that require shared credentials or tokens, leverage organizational-level secrets instead of duplicating them across individual repositories. This approach centralizes secret management, reduces the attack surface, and simplifies maintenance.docker/compose1 discussion
- precise security pattern matchingWhen checking for security features or configurations in shell scripts, use precise pattern matching to avoid false positives and limit information exposure. Instead of broad substring matches that could match unintended content, use specific patterns and restrict output to only necessary information.docker/compose1 discussion
- minimize credential access scopeApply the principle of least privilege when managing credentials in CI/CD pipelines and application code. Use credentials that are limited to only the specific permissions required for the task, and remove credentials entirely when they're not needed. This reduces security risk by limiting potential access if credentials are compromised and makes credential...docker/compose1 discussion
- Redact All LogsSecurity diagnostic output must not leak sensitive data. If you enable verbose modes (e.g., `--verbose`) or change log sinks (stdout vs stderr), ensure (and document) that *all* emitted diagnostic streams are actually redacted.openai/codex-security1 discussion
- Restrict command whitelistWhen configuring command whitelists for auto-approval, include only commands with limited capabilities that cannot be exploited for malicious purposes. Powerful tools like text editors (e.g., vim) should be avoided as they provide broad system access and functionality that could introduce security vulnerabilities if auto-approved.openai/codex1 discussion
- Prevent command injectionAlways use child_process.spawn() with array arguments instead of exec() with string concatenation when executing system commands. This prevents command injection vulnerabilities that can occur when untrusted input is incorporated into command strings.openai/codex1 discussion
- Explicit security bypassWhen implementing functionality to bypass security controls (like sandboxing), ensure the bypass is complete and explicit rather than just configuring existing security mechanisms to be permissive. Create dedicated code paths for unrestricted operation that truly bypass all security layers.openai/codex1 discussion
- validate SVG security contextSVG files can execute code when loaded, making them a potential security vulnerability. Before using SVGs, evaluate the deployment context and security requirements. Different environments have different restrictions - for example, VS Code marketplace prohibits user-provided SVGs due to security concerns, while webview-hosted SVGs may be acceptable. When...cline/cline1 discussion
- Scope secret-scan allowlists narrowlyWhen adding exemptions to secret-scanning tools (e.g., gitleaks), avoid broad allowlist patterns that could mask real credentials. Tie each exemption to a specific rule ID and combine match conditions (e.g., condition = AND, regexTarget = match) so only the exact known-safe values (such as synthetic model IDs used in tests) are excluded. After adding an...cline/cline1 discussion
- Restrict external dependenciesDependencies from packages outside your organization's trusted domain pose security risks and should be avoided in pull requests. When package-lock.json files include external dependencies, they introduce potential vulnerabilities that bypass internal security controls.cline/cline1 discussion
- Protected Publish ApprovalFor any CI/CD workflow that publishes or deploys to a protected environment, treat the environment-approval gate as an authorization boundary: require human maintainer approval for releases/publish actions and never bypass that gate via API calls (e.g., `gh api`). Also ensure release artifacts are integrity-checked before any publish (e.g., tag must match...CLINE/CLINE1 discussion
- Narrow secret allowlistsWhen suppressing secret-scan findings (e.g., via gitleaks allowlists), keep exemptions narrowly scoped and verify the suppression boundaries. Use specific rule types and matching criteria (e.g., condition + regexTarget) rather than broad path-based ignores, and confirm that only the intended false positives are ignored while unrelated credentials at the...CLINE/CLINE1 discussion
- Guard against prototype pollutionWhen using plain objects as lookup tables/dictionaries keyed by external or derived strings (file names, extensions, folder names, user input, etc.), never access values with direct bracket notation alone. Doing so lets keys like `constructor`, `__proto__`, or `toString` resolve to inherited `Object.prototype` members instead of `undefined`, causing...cline/cline1 discussion
- avoid interactive authentication automationWhen building scripts or applications that require user authentication, avoid automating interactive authentication processes that could cause system instability or security issues. Instead, check authentication status programmatically and delegate the actual authentication to the user.cline/cline1 discussion
- Document authentication precedenceWhen implementing systems that support multiple authentication methods, always clearly document which authentication method takes precedence when multiple options are provided. This prevents security misconfigurations and ensures predictable behavior.ClickHouse/ClickHouse1 discussion
- Use secure hash functionsWhen hashing sensitive data such as authentication tokens, always use cryptographically secure hash functions like SHA-256 instead of faster but insecure alternatives like MD5 or CRC32. Secure hash functions provide protection against reverse engineering and rainbow table attacks, which is critical for maintaining the confidentiality of sensitive...snyk/cli1 discussion
- Pin dependency versionsAlways pin external dependencies to specific commit hashes rather than mutable references like tags or branch names to prevent supply chain attacks. This applies to GitHub Actions, package dependencies, Docker images, and similar resources - even if they're from your own repositories.anthropics/claude-code1 discussion
- Least privilege networkingRestrict network access to only what's necessary for your application to function, using explicit allowlisting rather than trying to block malicious traffic. Network traffic should be denied by default and only specifically required destinations should be allowed.anthropics/claude-code1 discussion
- Avoid privileged installationsAlways recommend user-level package installations rather than using administrative/root privileges. Installing packages with elevated permissions can compromise system security and stability. Documentation and scripts should explicitly guide users toward safer installation practices.anthropics/claude-code1 discussion
- Update security-critical dependenciesRegularly audit and update third-party libraries and dependencies to address known security vulnerabilities. Pay special attention to components that handle sensitive operations such as file system access, encryption, or network communication. Implement a systematic process to monitor CVEs and security bulletins relevant to your dependencies, and document...chef/chef1 discussion
- Expand IAM wildcardsAlways expand IAM wildcard permissions (`*`) to specific actions for thorough security analysis. Wildcard permissions can unintentionally grant excessive access, creating security vulnerabilities. bridgecrewio/checkov1 discussion
- Avoid wildcard permissionsImplement the principle of least privilege by avoiding wildcard permissions (e.g., '*') in access control policies. Always specify only the exact permissions required for a resource or action. When analyzing existing policies with wildcards, use tools that expand wildcards into specific permissions to understand the full security implications.bridgecrewio/checkov1 discussion
- Avoid hardcoded secretsNever include hardcoded secrets or credentials in your infrastructure as code files. Secrets in configuration files pose significant security risks as they may be inadvertently exposed through version control systems or shared repositories.bridgecrewio/checkov1 discussion
- Prefer safe serializationAvoid `pickle` unless you have a documented, justified need and you can guarantee the serialized data never comes from untrusted sources. Prefer safe, data-only formats (e.g., JSON) for serialization/deserialization in tests and production code.celery/celery1 discussion
- Verify cryptographic function behaviorWhen implementing cryptographic algorithms, always verify the exact behavior and return values of security-critical functions. Misinterpreting how functions signal success or equality can lead to severe security vulnerabilities.oven-sh/bun1 discussion
- Validate buffer boundariesWhen calling functions that process buffers, especially external C functions, always provide explicit buffer size parameters to prevent buffer overflow vulnerabilities. Buffer overflows are a common security vulnerability that can lead to memory corruption, unauthorized data access, and even remote code execution.oven-sh/bun1 discussion
- Secure credentials handlingWhen handling credentials or secrets in code, avoid passing them directly through command substitution or template literals in shell commands, as this can lead to security vulnerabilities. Instead, write sensitive data to temporary files with restricted permissions, use those files for operations requiring credentials, and ensure proper cleanup afterward.oven-sh/bun1 discussion
- prefer authentication tokensWhen configuring authentication in CI/CD workflows, prefer using tokens over passwords for enhanced security. Tokens can be scoped with specific permissions, rotated more easily, and provide better audit trails compared to passwords. This is particularly important for service-to-service authentication where credentials are stored as secrets.browser-use/browser-use1 discussion
- Evaluate security control effectivenessSecurity measures should be evaluated against realistic threat models to avoid creating a false sense of security. When implementing security controls like checksums, consider whether they actually protect against likely attack vectors.Homebrew/brew1 discussion
- Use standard example credentialsWhen including API keys, access tokens, or other credentials in documentation, examples, or test code, always use clearly marked standard formats that won't trigger security scanners or be mistaken for real credentials. boto/boto31 discussion
- File-Based Command SafetyWhen invoking CLI/shell or external tools, treat all generated/ingested content (LLM output, web research, imported facts) as untrusted and never embed it directly into command-line strings.bmad-code-org/bmad-method1 discussion
- Escape and whitelistWhen rendering HTML (or HTML-like outputs) from structured data, treat every field as potentially hostile—even if produced internally. Apply two layers:bmad-code-org/bmad-method1 discussion
- Harden build-time pathsWhen Dockerfile (or build scripts) use build-args/variables to choose target directories for `chown`/`chmod`, validate those paths at build time and fail if they target sensitive directories. This prevents overly-permissive ownership (e.g., group 0 write access) from becoming reachable via undocumented/override knobs.maximhq/bifrost1 discussion
- Auth config documentationWhen Helm (or other config) controls authentication for a protected endpoint, treat credential source, key names, and auth enablement paths as security-sensitive behavior. Ensure both the implementation and the accompanying docs/changelog precisely describe:maximhq/bifrost1 discussion
- prefer authentication wrappersUse authentication wrapper functions or higher-order functions that automatically handle unauthenticated calls rather than manually checking authentication status. These wrappers provide built-in security by ensuring that authentication edge cases are handled consistently and reducing the risk of forgetting to validate authentication in handlers.better-auth/better-auth1 discussion
- temporary security workaroundsWhen implementing workarounds for OS-level security restrictions, ensure they are explicitly temporary and include clear plans for proper long-term solutions. Avoid recommending users bypass security features through unofficial methods, and instead guide them toward sanctioned approaches when possible.bazelbuild/bazel1 discussion
- Externalize sensitive identifiersDo not hardcode subscription/workspace/tenant/customer identifiers in scripts or source code—even if they’re not “secrets.” These are identifying information that can leak via logs, UI, demos, screenshots, or reviews. Pass them in via parameters or configuration (env vars, secure pipeline variables, secret stores) and avoid echoing them.Azure/Azure-Sentinel1 discussion
- Avoid Logging Sensitive DataDo not log raw function parameters (e.g., `kwargs`, request bodies, headers, tokens, credentials, or any data that could include PII). Logging can expose sensitive information via application logs, monitoring systems, or log sharing.Azure/Azure-Sentinel1 discussion
- Redact sensitive informationAlways sanitize configuration data or any potentially sensitive information before logging or displaying it. When logging configurations, API responses, or user inputs, use pattern matching to identify and redact secrets, passwords, API keys, and other credentials.Azure/azure-sdk-for-net1 discussion
- Externalize sensitive credentialsNever hardcode sensitive values such as client identifiers, API keys, connection strings, or passwords directly in code or configuration files. Instead, use secure mechanisms like environment variables, secret managers, or pipeline variable groups to inject these values at runtime. This practice reduces the risk of credential exposure in version control...Azure/azure-sdk-for-net1 discussion
- Complete authentication testingAlways verify both positive and negative authentication scenarios in your security tests. For each authentication mechanism, test that credentials are properly included when required and correctly absent when not needed. This comprehensive approach prevents potential authentication bypasses and ensures proper access control.Azure/azure-sdk-for-net1 discussion
- Secure Parameter Placeholders...Azure/azure-quickstart-templates1 discussion
- Scope APT Signing KeysWhen configuring APT repositories in install scripts, scope trust to a dedicated signing key and avoid deprecated/global keys. Don’t hardcode `amd64`; derive the architecture so the repo source is correct for non-amd64 systems.Azure/azure-cli1 discussion
- Avoid glob file mutationWhen automation modifies local files, don’t use broad filename globs that could match unexpected or attacker-controlled artifacts. Prefer deterministic, explicit paths/filenames (or fail closed). If a glob is unavoidable, validate that the matched file is exactly the expected artifact (e.g., match a known versioned filename pattern) before changing it.Azure/azure-cli1 discussion
- Secure cookie configurationAlways set appropriate security flags on cookies, especially those used for authentication or session management. At minimum, include HttpOnly, Secure, and SameSite flags to prevent cookie theft, session hijacking, and cross-site request forgery attacks.tokio-rs/axum1 discussion
- Isolate sensitive buffer dataWhen handling sensitive data in Node.js, protect against data leakage by isolating sensitive content in dedicated buffers. Node.js can create Buffers that aren't fully isolated, where `buf.byteLength !== buf.buffer.byteLength`, meaning sensitive data might be accessible to other code through the shared buffer memory.aws/aws-sdk-js1 discussion
- Vet dependency supply chainsWhen adding new dependencies, especially security-related ones, thoroughly evaluate them for supply chain attack risks. Look for red flags such as: repositories with many empty or automated commits, lack of transparent build processes (prefer GitHub Actions over opaque automation), use of unofficial forks instead of original packages, and suspicious account...avelino/awesome-go1 discussion
- validate external URLsAlways validate and sanitize external URLs before opening them or using them in navigation operations to prevent URL injection attacks. Implement domain allowlists to restrict which external domains are permitted, and avoid directly passing user-controlled or external URL data to functions like window.open() without proper validation.argoproj/argo-cd1 discussion
- consolidate RBAC permissionsAvoid duplicating RBAC permissions across different deployment configurations or installation modes. When the same service or controller needs permissions in multiple contexts (e.g., cluster-wide vs namespace-scoped deployments), consolidate these permissions into a unified, well-defined role structure rather than maintaining separate, potentially...argoproj/argo-cd1 discussion
- Token Precedence SafetyWhen multiple authentication tokens are supported (e.g., generic GitHub tokens vs Copilot-specific tokens), enforce a deterministic, documented precedence and require explicit opt-in for fallback behavior.coleam00/Archon1 discussion
- Verify authentication logicEnsure authentication validation logic follows expected semantics and intuitive implementation. Authentication checks should correctly interpret the presence or absence of security tokens, with clear and accurate logging that reflects the actual security state.appwrite/appwrite1 discussion
- Use proper authenticationAlways implement the correct authentication method for API clients as specified in the SDK documentation. Incorrect authentication methods can lead to security vulnerabilities, API access failures, or unintended behavior.appwrite/appwrite1 discussion
- Secure file uploadsAlways implement and maintain robust scanning mechanisms for user-uploaded files to prevent malware distribution. When modifying infrastructure or services related to file handling, ensure alternative security controls are in place before removing existing protections.appwrite/appwrite1 discussion
- Secure credentials managementNever store sensitive credentials (passwords, API keys, tokens, etc.) in plain text within code repositories. This practice poses a significant security risk as it can lead to unauthorized access if the repository is compromised or accidentally made public.appwrite/appwrite1 discussion
- Verify Download IntegrityWhen your code/CI downloads third-party binaries or packages and then installs them, verify integrity before installation (preferably SHA256/SHA256+signature). Store the expected checksum in versioned configuration keyed by the artifact/runtime version, and update it whenever you bump that version. Fail closed on mismatch.apache/apisix1 discussion
- validate disabled state accessibilityWhen UI components with interactive elements (like buttons with href attributes) are disabled, ensure they maintain proper accessibility standards and don't create security vulnerabilities. Disabled states should properly prevent user interaction while maintaining clear visual and programmatic indication of their state.ant-design/ant-design1 discussion
- Prioritize secure token storageWhen implementing authentication token handling, prioritize more secure storage mechanisms over less secure ones. Specifically, prefer retrieving tokens from properly configured cookies (with Secure and HttpOnly flags) before falling back to localStorage, which is vulnerable to XSS attacks.apache/airflow1 discussion
- Document security exceptionsWhen disabling security-related linter rules or bypassing security best practices, always include comments that explain why the exception is necessary, why it remains secure, and link to relevant security policies. This creates an audit trail and ensures future developers understand the security implications.apache/airflow1 discussion
- Secure-by-default integrationsWhen adding configurable external services/integrations (e.g., registries, MCP servers, plugins), apply security-by-default and supply-chain controls—especially when the integration can access credentials.awslabs/aidlc-workflows1 discussion
- Secret scan baselinesWhen using secret-scanning tools (e.g., gitleaks) ignore or baseline files, treat those artifacts as sensitive because they may contain previously detected secret text.awslabs/aidlc-workflows1 discussion
- Least-privilege secret scopingWhen granting IAM access to Secrets Manager, avoid broad resource wildcards (e.g., `arn:aws:secretsmanager:...:secret:*`). Prefer narrowing by the exact secret ARN(s) or by a well-known secret-name prefix for the specific service/feature. Also remove redundant policy constraints that don’t add additional security beyond what the ARN already enforces.awslabs/agentcore-samples1 discussion
- Ignore secrets in imagesWhen building container images, never copy the entire build context blindly. Add a `.dockerignore` (and/or use targeted `COPY` paths) to ensure sensitive files and local artifacts can’t be baked into the image—especially when using `COPY . .`.awslabs/agentcore-samples1 discussion
- Sanitize untrusted tagsTreat any tag/markup coming from user input, LLM output, or external commands as untrusted. Validate and sanitize it at the earliest boundary before embedding into JSON or rendering in the UI—e.g., strip/escape disallowed tags so they can’t break parsers or visuals.agent0ai/agent-zero1 discussion
- Sanitize Model OutputWhen handling untrusted model/text output that will be serialized into JSON (or rendered in a UI), normalize it before output generation—specifically strip or escape tag-like content (e.g., “<think>…</think>”) so it cannot corrupt JSON or break downstream parsing.agent0ai/agent-zero1 discussion
- Sanitize Upstream Stream ErrorsWhen handling upstream streaming responses (SSE/streaming APIs), treat any non-stream payload (e.g., HTML error pages) as untrusted input: do not pipe it through streaming transforms, and do not reflect raw upstream text/HTML into client errors.decolua/9router1 discussion
Nothing matches these filters.