Awesome Reviewers

Documentation & Knowledge

Reference material, curated lists and learning resources — mostly writing and structure guidance.

61 instructions from 6 repositories. Last updated 2026-05-08.


Documentation clarity rules

When 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.

Apply these rules:

Example pattern (description vs explanation):

# --description--
To run the program, use:
```bash
python main.py

–explanation–

The command must be run from the folder that contains main.py.


---

## Consistent Snippet Style

<!-- source: freeCodeCamp/freeCodeCamp | topic: Code Style | language: Markdown | updated: 2026-05-08 -->

All 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.

Apply these rules:
- **Formatting:** use the team’s standard indentation (e.g., 2 spaces) and include semicolons consistently.
- **No broken snippets:** seed code examples must compile/parse; avoid syntax errors and duplicate declarations.
- **Quote-robust tests/hints:** when matching user code, support **both** single and double quotes and (when relevant) ensure the same quote type is used via backreferences.
- **Pattern consistency:** hints should prefer the same DOM/API patterns the seed uses (to avoid ambiguity), unless there’s an explicit reason to allow alternatives.

Example (quote-robust hint regex):
```js
// Matches: document.getElementById('income') or document.getElementById("income")
assert.match(code, /document\.getElementById\(\s*(['"])income\1\s*\)/);

Example (style-correct TS):

function f(): void {
  const x = 1;
  console.log(x);
}

Example (avoid duplicate seed declarations):

const cardDisplay = document.querySelector<HTMLElement>("#current-card")!; 
// (don’t redeclare cardDisplay again)

Express error handling

For Express apps, standardize error handling as follows:

Example (safe ordering + async propagation):

const express = require('express');
const app = express();

// Routes
app.get('/', (req, res) => {
  throw new Error('Something went wrong');
});

// 404 handler (after routes, before error handler)
app.use((req, res) => {
  res.status(404).send('Sorry, that route does not exist.');
});

// Async error helper (optional)
function asyncHandler(fn) {
  return (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
}

app.get('/user', asyncHandler(async (req, res) => {
  const user = await getUserFromDatabase();
  res.send(user);
}));

// Error-handling middleware (LAST)
app.use((err, req, res, next) => {
  console.error(err); // log details internally
  res.status(500).send('Internal Server Error'); // user-friendly response
});

Apply this checklist consistently when adding new routes or refactoring middleware order to prevent unhandled promise rejections, ensure consistent HTTP responses, and avoid leaking sensitive error details.


Middleware and Status Semantics

When building API endpoints with Express, make request lifecycle control-flow and response semantics explicit and consistent:

Example:

const express = require('express');
const app = express();

// Global middleware (runs in order)
app.use((req, res, next) => {
  console.log(req.method, req.url);
  next(); // continue the lifecycle
});

const api = express.Router();
api.use('/v1', (req, res, next) => {
  // router-level middleware
  next();
});

api.get('/v1/resource', (req, res) => {
  // terminal handler: choose status code + body that match the outcome
  return res.status(200).json({ ok: true });
});

api.post('/v1/resource', express.json(), (req, res) => {
  if (!req.body || !req.body.name) {
    return res.status(400).send('Bad Request');
  }
  return res.status(201).json({ created: true });
});

app.use(api);
app.listen(3000);

Use this checklist in reviews: 1) Does every middleware either call next() or send a response (intentionally terminating)? 2) Are middleware/routers mounted in the intended order/module boundaries? 3) Do your route handlers return status codes and response bodies that accurately represent success/client error/server error?


Middleware ordering and chaining

When 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().

Apply this standard:

Example:

const express = require('express')
const cors = require('cors')
const morgan = require('morgan')
const app = express()

// 1) Parse/prepare request (built-in)
app.use(express.json())

// 2) Middleware behavior depends on order (third-party)
app.use(cors())
app.use(morgan('tiny'))

// 3) Intercept/transform request, then continue
app.use((req, res, next) => {
  req.requestId = req.header('x-request-id')
  next() // must be called to reach the next middleware/route
})

// 4) Serve static assets via middleware (register intentionally)
app.use(express.static('public'))

app.get('/', (req, res) => res.send('Hello'))

app.listen(3000)

Outcome: predictable HTTP behavior, fewer “why didn’t my route run?” issues, and middleware effects (auth, logging, parsing, static serving) that are consistent across the app.


Docstring Standards

Apply a single documentation rule set across the codebase:

Example (illustrates the “no type duplication” + clear behavior):

def time_period_of_satellite(mass: float, radius: float, height: float) -> float:
    """Calculate the orbital period of a satellite.

    Uses T = 2π * sqrt((R + h)^3 / (G * M)).

    Units: mass in kg, radius/height in meters.
    """
    ...

Operationally: during review, enforce these as checklist items for every new/changed file and function/method docstring.


Validate Inputs Explicitly

Enforce 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.

Guideline checklist:

Example pattern:

import math

def calculate_refraction_angle(n1: float, n2: float, incident_angle_degrees: float) -> float:
    # precondition: physical/numerical domain
    if n1 <= 0 or n2 <= 0:
        raise ValueError("Refractive indices must be positive")

    theta1 = math.radians(incident_angle_degrees)
    refraction_sine = (n1 / n2) * math.sin(theta1)

    # physical validity in one place; message stays truthful
    if not -1.0 <= refraction_sine <= 1.0:
        raise ValueError("Total Internal Reflection or invalid physical inputs")

    return math.degrees(math.asin(refraction_sine))

Apply the same approach across data structures and educational utilities: validate configuration (raise on invalid mode), validate parameter types/relationships, and make failure modes deterministic and easy to understand.


Algorithm Correctness Standards

When implementing algorithms, enforce correctness and reliability by following this checklist:

1) Validate stated preconditions (and document them)

2) Handle numerical/semantic edge cases explicitly

3) Ensure algorithm invariants are implemented (especially graph/search)

4) Avoid unnecessary extra passes

Example pattern (single-pass grouping + clear precondition validation):

from collections import defaultdict

def group_by_priority(items: list[dict]) -> dict[str, list[dict]]:
    grouped: dict[str, list[dict]] = defaultdict(list)
    for item in items:
        grouped[item["priority"]].append(item)
    return dict(grouped)

def cyclic_sort_guard(nums: list[int]) -> None:
    n = len(nums)
    if any(x < 1 or x > n for x in nums):
        raise ValueError("Cyclic sort requires all values in the range [1, len(nums)]")
    if len(set(nums)) != n:
        raise ValueError("Cyclic sort requires no duplicates")

Adopting this standard will reduce subtle correctness bugs (wrong logic/invariants), runtime failures (invalid inputs/infinite loops), and precision-related issues, while also improving efficiency for larger inputs.


Consistent Identifier Naming

When 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).

Checklist

Example

// JSX/TSX: use className
return <img src=".../pele.jpg" alt="Pelé headshot" className="card-image" />;

// Spec/tests: ensure variable names match exactly
const utilitiesInputs = document.querySelectorAll("#utilities input[type='number']");

Automate All Behavior Tests

For every algorithmic change (and every public function/class), require automated tests that lock in both correctness and failure modes.

Minimum standard:

Example pattern (doctest with edge + failure):

def interpolation_search(sorted_collection: list[int], item: int) -> int | None:
    """
    >>> interpolation_search([1, 2, 3, 4, 5], 2)
    1
    >>> interpolation_search([1, 2, 3, 4, 5], 6) is None
    True
    >>> interpolation_search([], 1) is None
    True
    """
    ...

if __name__ == "__main__":
    import doctest
    doctest.testmod()

This standard directly prevents regressions (new validation rules, edge-case fixes, and invariants) and makes behavior verification repeatable and reviewable.


Performance-Sensitive Efficiency

When 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.

Apply these checks:

Example patterns (correct-by-construction + faster):

# 1) Avoid insert-at-front in recursion: use append + reverse
result = []
# ... DFS fills `result` with descendants-first
return list(reversed(result))

# 2) Compute expensive support once
candidate_counts = {}
for c in candidates:
    support = get_support(c, transactions)
    if support >= min_support:
        candidate_counts[c] = support

# 3) Check length before mapping
tokens = input().split()
if len(tokens) > MAX_SEQUENCE_LENGTH:
    ...
user_input = list(map(int, tokens))

# 4) Optional expensive simplify
def maybe_simplify(expr, *, simplify: bool = False):
    return sp.simplify(expr) if simplify else expr

# 5) Avoid redundant conversion
if not isinstance(arr, np.ndarray):
    arr = np.array(arr)

Self-Documenting Naming Rules

Use self-documenting identifiers: variable/function/class names should explain intent without relying on comments, and avoid confusing or ambiguous abbreviations.

Practical rules:

Example (before/after):

# Before
def trapezoidal_rule(f, boundary, steps):
    h = (boundary[1] - boundary[0]) / steps
    a = boundary[0]
    b = boundary[1]
    x_i = make_points(a, b, h)

# After
def trapezoidal_rule(
    f: callable,
    boundary: list[float],
    steps: int,
) -> float:
    lower_bound, upper_bound = boundary
    step_size = (upper_bound - lower_bound) / steps
    x_points = make_points(lower_bound, upper_bound, step_size)
    result = 0.0
    # ...
    return result

Apply the same principle to all algorithm modules: ensure names are clear to someone who only reads the code.


Pure Functions and Main Guard

Keep 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.

Example (move prints + examples):

def quick_select(items: list[int], index: int) -> int:
    # reusable logic: no printing, no prompting
    ...


def _demo() -> None:
    prices = [7, 1, 5, 3, 6, 4]
    print("Example:", quick_select(prices, 3))


if __name__ == "__main__":
    _demo()

Checklist:


Explicit Optional Nulls

When a value can be absent, represent that absence explicitly and consistently.

Do

Example (segment-tree style):

from dataclasses import dataclass
from typing import Optional

@dataclass
class Node:
    start: int
    end: int
    value: int = 0
    left: Optional["Node"] = None
    right: Optional["Node"] = None

class SegmentTree:
    def __init__(self, nums: list[int]) -> None:
        self.root: Optional[Node] = None
        if not nums:
            return
        self.root = self.build(0, len(nums) - 1, nums)

Applying this standard prevents null-reference bugs, removes confusing placeholder behavior, and makes absence handling readable and enforceable by both humans and type checkers.


Null-Safe Defaults

Write code assuming inputs (arrays, objects, DOM nodes) may contain undefined, null, or “empty slots/holes”, and normalize them early with explicit defaults.

Standards

Example

function groupByZone(actions) {
  return actions.reduce((acc, action) => {
    const zone = action?.item?.zone ?? 'general'; // default when missing/undefined
    (acc[zone] ??= []).push(action);
    return acc;
  }, {});
}

// Null-safe DOM access
const el = document.querySelector('.container > div');
console.assert(el?.classList.contains('output'));
console.assert(el?.classList.contains('hide'));

// Example for array-hole aware compaction
function compactFragments(arr) {
  return arr.filter(Boolean); // removes undefined/null and also skips holes
}

Concurrency-safe async flows

When 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.

Apply two rules: 1) Guard “repeatable” actions (submit/reset/etc.) with stable synchronization and cleanup.

const SUBMIT_DEBOUNCE_MS = 1000;

export function useSubmit() {
  const dispatch = useDispatch();

  const submitRef = useRef(() => dispatch(submitChallenge()));
  submitRef.current = () => dispatch(submitChallenge());

  const debouncedSubmitRef = useRef(
    debounce(() => submitRef.current(), SUBMIT_DEBOUNCE_MS, {
      leading: true,
      trailing: false,
    })
  );

  useEffect(() => {
    const debouncedSubmit = debouncedSubmitRef.current;
    return () => debouncedSubmit.cancel();
  }, []);

  return () => debouncedSubmitRef.current();
}

2) Centralize API + store mutation in a single orchestrator (e.g., saga).

Result: fewer race-condition bugs, more deterministic behavior under fast user input and automated rapid submissions, and clearer ownership of async workflows.


Mock Only What Matters

When writing tests, avoid introducing unnecessary fakes/mocks that hide real integration behavior.

Example (minimal mocking in a hook test):

import { renderHook } from '@testing-library/react';
import { vi } from 'vitest';

const { mockDispatch } = vi.hoisted(() => ({
  mockDispatch: vi.fn(),
}));

// inline mock for the second dependency to keep the hook isolated and readable
vi.mock('./some-module', () => ({
  useSingleton: () => ({
    dispatch: mockDispatch,
    initialize: vi.fn(),
  }),
}));

// renderHook(...) 

Practical checklist:


Validate Block JSON

Ensure every curriculum/structure/blocks/*.json file matches the CI-validated schema and constraints.

Example (schema-compliant style):

{
  "isUpcomingChange": false,
  "dashedName": "workshop-envelope-budget-app",
  "helpCategory": "HTML-CSS",
  "blockLayout": "challenge-grid",
  "blockLabel": "workshop",
  "challengeOrder": [
    { "id": "<valid-id-length-and-format>", "title": "Step 1" }
  ]
}

Deterministic Array Algorithm Contracts

For algorithm-heavy code that transforms arrays (multi-step pipelines, scheduling, deduping, cyclic traversal), require clear, testable function contracts and deterministic behavior:

Example pattern (flatten → score → stable dedupe):

function flattenPlaylists(playlists) {
  if (!Array.isArray(playlists)) return [];

  const out = [];
  playlists.forEach((pl, playlistIndex) => {
    if (!Array.isArray(pl)) return;
    pl.forEach((track, trackIndex) => {
      out.push({
        ...track,
        source: [playlistIndex, trackIndex],
      });
    });
  });
  return out;
}

function scoreTracks(tracks) {
  return tracks.map(t => ({
    ...t,
    score: t.votes * 10 - Math.abs(t.bpm - 120),
  }));
}

function dedupeTracks(tracks) {
  const seen = new Set();
  const out = [];
  for (const t of tracks) {
    if (seen.has(t.trackId)) continue;
    seen.add(t.trackId);
    out.push(t);
  }
  return out; // keeps the earliest occurrence
}

Apply this standard anytime you see multi-step array algorithms or any logic depending on order/cycles—make those rules explicit in the functions’ behavior.


CI workflow correctness

All 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). 2) Condition + command belong together: put if: on the same step as the run: (or uses:). 3) Triggers must match the repo: ensure the referenced branches in on: push / on: pull_request actually exist; avoid paths-ignore patterns that skip directories containing code. 4) Version pinning clarity: when pinning a GitHub Action to a commit SHA, the inline comment must match the intended release version. 5) Avoid duplicate work: don’t rerun linters/tests already covered by dedicated lint/test workflows or pre-commit jobs. 6) Respect project runtime policy: don’t hardcode an older Python version if the project expects testing against the latest production CPython; align job installs with the intended uv dependency groups.

Example (valid conditional step):

- name: Build docs artifact
  if: ${{ success() }}
  run: |
    scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md

Example (pin comment matches intent):

- name: Set up uv
  uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0

Example (sanity on triggers):


Use canonical invariants

When 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.

How to apply:

Example pattern (sketch):

const fs = require('fs');

function getStepOrder(blockJsonPath) {
  const block = JSON.parse(fs.readFileSync(blockJsonPath, 'utf8'));
  return block.steps.map(s => s.order); // derive ordering from canonical data
}

function isLastStep(stepOrder, currentOrder) {
  return currentOrder === Math.max(...stepOrder);
}

function validateSeeds(seeds) {
  // Local invariant: per-seed-file
  for (const seed of seeds) {
    const markers = findRegionMarkers(seed);
    if (markers > 2) throw new Error('Per-file: too many markers');
  }

  // Global invariant: across all seeds
  const totalMarkers = seeds.reduce((sum, seed) => sum + countMarkers(seed), 0);
  if (totalMarkers !== 2) throw new Error('Workshop: exactly two total markers');
}

This approach improves algorithmic reliability (correct ordering/state) and correctness of constraint enforcement (no accidental gaps from removing “seemingly redundant” checks).


Prefer clear, semantic code

Write code that’s easy to read and matches intent (mutability, string composition, UI semantics), and remove obvious clutter.

Apply these rules:

1) Avoid reassignable variables

2) Build static paths/strings directly

3) Don’t add redundant conditionals when UI state already guarantees behavior

<Button disabled={isClassroomAccount} onClick={updateIsClassroomAccount} />


4) Render links as links; actions as buttons
- If the user is navigating to/copying/opening a URL, use a link element/component. Avoid “button that opens a new tab” when a link is available—this improves accessibility and expected browser features.

5) Remove duplicate/unused imports
- Keep imports unique and ensure every import is used (e.g., don’t import the same symbol in multiple places).

---

## Use Config Safely

<!-- source: freeCodeCamp/freeCodeCamp | topic: Configurations | language: TSX | updated: 2026-03-10 -->

Treat configuration/feature-flag-driven logic as potentially different between tests and runtime, and standardize how you branch on it.

Apply this by:
1) Verify config-derived outputs with real environment values
- If you compose strings/URLs from config (e.g., base URL + path), ensure runtime values produce the expected final result.
- Don’t rely solely on tests that stub config differently—run locally with the real `GITHUB_LOCATION`/`env.json` setup and confirm the generated links actually work.

2) Prefer the standard feature-flag mechanism for UI
- When the project provides an abstraction (e.g., `IfFeatureEnabled`), use it for feature-controlled UI rather than mixing ad-hoc boolean wrappers that reduce readability and consistency.

3) Keep conditional UI layout consistent
- When rendering conditionally, ensure spacing/layout remains stable and visually intentional.

Example pattern (feature-controlled UI):
```tsx
<IfFeatureEnabled feature='classroom-mode'>
  <Spacer size='m' />
  <ClassroomMode
    isClassroomAccount={isClassroomAccount}
    updateIsClassroomAccount={updateIsClassroomAccount}
  />
</IfFeatureEnabled>

Minimize API Roundtrips

When 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 bodies.

Apply this as follows:

Example (batch endpoint shape):

// Instead of calling per block with rate-limit delays
// await deleteResetModule({ blockId: currentBlock }) in a loop

// Prefer one request with all IDs
await deleteResetModules({ blockIds: blockIds });

Example (mutation returns data to update client state):

const res = await resetModule({ moduleId });
// res should include the updated state the UI needs
setStateFromResponse(res);
// Don’t call a separate fetchUser() just to refresh UI.

Canonical Documentation Entries

When 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.

Apply this checklist:

Example (YouTube playlist bullet):

* [React JS Tutorial Series (Kannada)](https://www.youtube.com/playlist?list=<PLAYLIST_ID>) - <Channel/Creator Name>

Example (escape pipe):

* [Material UI Complete in One Video \| (Hindi)](https://www.youtube.com/playlist?list=<PLAYLIST_ID>) - <Creator>

Avoid Unnecessary Type Assertions

In 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.

Apply this style rule:

Example (mimic the proposed approach):

// Normalize once to the correct element shape
const normalizeChallenges = (arr: unknown) => arr as Array<{ id: string }>;

const filteredCompletedChallenges = normalizeChallenges(user.completedChallenges)
  .filter(c => !challengeIdsToReset.includes(c.id));

await fastify.prisma.user.update({
  where: { id: req.user!.id },
  data: {
    completedChallenges: filteredCompletedChallenges,
  },
});

RESTful endpoint responses

When designing API routes, make the HTTP method and response contract match the operation’s intent and the client’s needs.

Example pattern:

fastify.delete('/account/reset-module', {
  schema: schemas.resetModule
}, async (req, reply) => {
  // ...remove/reset items
  return reply.code(204);
});

// OR if the client needs a summary:
return {
  blockId,
  completedChallengesRemoved,
  savedChallengesRemoved,
  partiallyCompletedChallengesRemoved
};

When adding/updating entries in markdown lists, follow the repository’s lint-safe formatting and platform/link conventions.

Checklist:

Example (correct pipe escaping):

* [React JS Tutorial in Hindi \| React JS for Beginner to Advanced \| Step by Step Video Tutorials](https://www.youtube.com/playlist?list=PLjVLYmrlmjGdnIQKgnTeR1T9-1ltJEaJh) - WsCubeTech

Example (avoid invented titles/ensure lint-safe formatting):

* [.NET Rocks!](https://dotnetrocks.com) - Carl Franklin, Richard Campbell (podcast)

Never edit generated JSON

Treat 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.

How to apply:

Example (PR rule of thumb):


Stateful Parsing Correctness

When 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.

Apply these rules:

Example pattern (process all <div dir> tags on a line, in order):

# Find all opening and closing <div> tags on the line
div_tags = re.findall(
    r"(<div[^>]*dir=['\"](rtl|ltr)['\"][^>]*>|</div>)",
    line,
    re.IGNORECASE,
)

for tag, direction in div_tags:
    if tag.startswith('<div') and 'markdown="1"' in tag:
        block_context_stack.append(direction.lower())
    elif tag == '</div>' and len(block_context_stack) > 1:
        block_context_stack.pop()

Add/keep tests that cover: (1) multiple tags on the same line and (2) cases where skipping tokens would drop nearby output characters (e.g., punctuation around inline spans).


Canonical IDs and Titles

Adopt canonical naming rules for both identifiers (anchors/ids) and display names (titles) to prevent broken links and inconsistent labeling.

Rules

  1. Anchor ids must be explicit and stable
    • If a section/subsection is referenced by an in-page link, ensure there is an explicit matching id.
  2. Use consistent casing for ids
    • Prefer lowercase ids (avoid relying on markdown-generated casing differences).
  3. Keep anchor sections ordered predictably
    • When adding headings/anchors, place them in alphabetical order within their group.
  4. Do not invent or paraphrase resource titles
    • Use the exact title provided by the resource/creator.
  5. Avoid honorifics/extra prefixes in names
    • Don’t add titles like “Professor” or similar honorifics to the listed display name.

Example (anchor/id)

### <a id="yapay-zeka"></a>Yapay Zeka

<!-- later: link must match the id exactly -->
[Go to Yapay Zeka](#yapay-zeka)

Example (title)

<!-- Good: exact source title -->
* [TypeScript — Frontend & Backend (file setup, types, generics, React + TS)](https://github.com/...)

<!-- Avoid: modified/invented title -->
* [TypeScript Cheatsheet](https://github.com/...)  <!-- only if this is the exact resource title -->

Encode International URLs

When 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.

Apply this during link updates:

Example (conceptual):

Incorrect (not encoded):  http://example.com/புத்தகம்?q=தேர்வு
Correct (encoded):        http://example.com/%E0%AE/....?q=%E0%AE/....

If you’re unsure, re-encode the URL using your language/runtime’s URL/URI utilities before committing documentation or code changes.


Avoid stray commas

When 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.

Also, standardize on the team’s chosen linter (e.g., use Ruff instead of Flake8 when Ruff is the agreed replacement) to keep behavior consistent across environments.

Example (CI lint step):

- name: Lint code
  run: |
    uv run ruff check --output-format=github

Avoid patterns like:

run: uv run ruff check , --output-format=github

Use semantic names

Use 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.

Apply:

Example (GitHub Actions):

name: Build CI/CD Pipeline

jobs:
  build_and_test:
    name: Build and Test
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v5
      - name: Set up uv
        uses: astral-sh/setup-uv@v3
      - name: Install dependencies
        run: uv sync --group=test

  directory_writer:
    name: Directory Writer
    # ...

This improves readability and reduces confusion when multiple workflows/jobs/steps exist.


Enforce shared code style

Keep 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:

Go example (idioms):

// Package/global: prefer var
var x int // zero value

func f() {
    y := 1          // ok: inside function
    if z := y + 1; true {
        _ = z       // ok: temp in if init
    }

    // Redeclare semantics: one variable must be new
    a, b := 1, 2
    a, b = 3, 4 // plain assignment
    a, c := 5, 6 // redeclare with := where one LHS name is new
}

Semantic Precision In Algorithms

When 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.

Apply as follows:

Example (language semantics that affect algorithm correctness):

// Prefer strict equality to avoid coercion-based bugs in comparisons.
if (candidate === target) {
  // correct: value and type must match
}

Use this standard to guide review checklists for algorithm docs and implementations so contributors don’t accidentally change meaning while only “rephrasing” or reorganizing content.


Validate Security Inputs

Security-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 cryptography, clearly distinguish public parameters from secret material and ensure computations use the correct one (don’t derive a peer’s values from the wrong party’s parameter set or mistakenly treat a public parameter as secret).

Example pattern:

def ip_to_decimal(ip_address: str) -> int:
    parts = ip_address.split(".")
    if len(parts) != 4:
        raise ValueError("Invalid IPv4 address format")

    octets = []
    for part in parts:
        if not part.isdigit():
            raise ValueError("Invalid IPv4 address: non-numeric octet")
        n = int(part)
        if not (0 <= n <= 255):
            raise ValueError("Invalid IPv4 address: octet out of range")
        octets.append(n)

    decimal_ip = 0
    for n in octets:
        decimal_ip = (decimal_ip << 8) + n
    return decimal_ip

Crypto-specific checklist:


Auth-Gated Validation

Apply security controls at the UI/component level and ensure input validation is centralized.

1) Auth-state gating (authorization/flow correctness)

export function SubscribeToChangelog({ isLoggedIn }: { isLoggedIn: boolean }) {
  if (isLoggedIn) return null; // or an alternative message
  return <button onClick={/* show subscribe flow */}>Subscribe</button>;
}

2) Centralize validation rules (input validation consistency)

const USERNAME_REGEX = /^[a-zA-Z0-9]{0,20}$/; // includes length constraint
export function isUsernameValid(value: string) {
  return USERNAME_REGEX.test(value);
}

// usage
const isValid = isUsernameValid(value);

This prevents unauthorized/incorrect flows from appearing to the user and reduces the risk of inconsistent validation logic across the codebase.


Manage Generated Configs

When working with configuration JSON files, treat them as tool- and schema-backed artifacts:

Example pattern:

// Bad: violates the config contract
{ "type": "DevOps Roadmap" }

// Good: use an allowed value
{ "type": "button" }

Process guidance:


Environment variable defaults

Configuration 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.

When accessing configuration through environment variables, always provide appropriate fallback values to ensure the application functions correctly even when optional environment variables are not set.

Example implementation:

var (
    githubApiAuthorizationToken = os.Getenv("GITHUB_API_TOKEN")
    userAgent = getEnvWithDefault("USER_AGENT", "MyApp/1.0")
)

func getEnvWithDefault(key, defaultValue string) string {
    if value := os.Getenv(key); value != "" {
        return value
    }
    return defaultValue
}

// Usage in HTTP request
request.Header.Set("User-Agent", userAgent)

This pattern ensures that sensitive values like API tokens can be injected at runtime while maintaining reasonable defaults for non-sensitive configuration like user agent strings.


Concise Performance Guidance

When 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.

How to apply:

Example (Markdown template):

## Performance Optimization (Overview)
To improve performance, focus on reducing initial load time, minimizing unnecessary work during rendering, and identifying bottlenecks early.

- Lazy-load components to reduce upfront cost
- Prevent unnecessary re-renders (use appropriate conditional rendering patterns)
- Reduce bundle size (code splitting, tree shaking)
- Virtualize long lists/tables to cut DOM overhead
- Monitor/profiling to find bottlenecks
- Minimize dependencies that increase payload/work

Learn more:
- [Resource A](https://...)
- [Resource B](https://...)
- [Resource C](https://...)

This ensures the document is fast to scan, consistent with performance best practices, and doesn’t bury developers in overly deep content where a quick orientation is expected.


Accurate AI Content

When 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.

Apply these rules:

Example (claiming citations safely):


For roadmap/technical documentation pages, follow these rules:

Example (intro without code + clean heading + resources):

## Example (concept only)

This page provides a brief introduction to the concept and what it’s used for.
For deeper details and usage, see the resources below.

Learn more from the following resources:

- [@official@Concept Overview](https://example.com/official)
- [@article@Concept Deep Dive](https://example.com/deep-dive)
- [@article@Best Practices](https://example.com/best-practices)

Applying this consistently will improve readability, reduce duplicated content, and prevent broken/incorrect resource links.


Use Approved Naming

Use precise, guideline-approved naming for identifiers (tags), technical terminology, and headings—so names are unambiguous, consistent, and match the actual meaning.

Apply this by:

Examples:


Consistent Network Docs

Ensure 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.

Example (pattern to follow in Markdown):

# Topic Title

## What is topic?
Short, plain-language definition of the networking concept.

## How it works
1–3 sentences describing the flow/behavior.

## Key commands / options
- `COMMAND_1`
- `COMMAND_2`

Learn more from the following resources:
- [@official@Topic documentation](https://example.com)

Idiomatic Style Commands

When writing style guidance (including README/CONTRIBUTING snippets), keep examples concise and readable:

1) Use idiomatic tool invocations (avoid redundant arguments)

Example:

# Prefer (defaults to current directory)
ruff check

# Only specify a path when you truly need it
ruff check path/to/package

2) Format lists in sentences with consistent punctuation

Example:

List comprehensions and generators are preferred over the use of `lambda`, `map`, `filter`, and `reduce`.

Categorize by primary purpose

When 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 needs.

For example, a dependency injection library that uses reflection should be categorized under “Dependency Injection” rather than “Reflection” because dependency injection is its primary purpose. Similarly, when documenting configuration management tools, focus on what they primarily accomplish (environment management, config file handling, feature flags) rather than the underlying technology they use.

This approach prevents confusion and maintains logical organization where developers can intuitively find tools based on what they need to accomplish, not how the tools work internally. Apply this principle when creating configuration documentation, tool recommendations, and project categorization within your development environment.


Fail-Fast CI/CD Steps

When building CI/CD pipelines, keep them scope-focused and deterministic, and add explicit quality gates so failures stop the deployment.

Apply:

Example (GitHub Actions):

name: CI/CD
on: [push]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build/Test
        run: |
          echo "run tests/build here"

      - name: Validate (fail fast)
        run: |
          terraform fmt -check
          terraform validate

      - name: Deploy
        if: success()
        run: |
          terraform init
          terraform plan -out=tfplan
          terraform apply -auto-approve tfplan

Treat Untrusted Data Safely

Security 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.

How to apply

Example patterns

const LoginSchema = z.object({ email: z.string().email(), password: z.string().min(1), });

export function parseLogin(body: unknown) { return LoginSchema.parse(body); // runtime validation }

- XSS-safe output (Angular):
  - Prefer normal template bindings/interpolation so Angular sanitizes/escapes by default.
- Risky bypass guarded by proof (Angular):
```ts
import { DomSanitizer } from "@angular/platform-browser";

export class ExampleComponent {
  trustedUrl: any;

  constructor(private sanitizer: DomSanitizer) {
    // Only bypass when you *proved* the value is not attacker-controlled
    // and you constructed it from trusted sources.
    const trusted = "https://example.com/safe-path";
    this.trustedUrl = this.sanitizer.bypassSecurityTrustUrl(trusted);
  }
}

Team checklist


Valid Angular Examples

When adding Angular examples (docs, snippets, templates), ensure they are both syntactically/semantically valid and shown in the correct template context.

Key rules:

Example (template context):

<div class="user-container">
  @if (count() === 1) {
    <b>Count is 1</b>
  } @else {
    <b>Count is not 1</b>
  }
</div>

(And ensure count is a signal defined in the component, e.g., const count = signal(0);.)


Enforce coverage thresholds

All 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.

When reviewing code or adding new libraries, verify that test coverage meets or exceeds the 80% requirement. Coverage below this threshold should result in a request for additional tests before approval.

Example feedback:

Test coverage: 72%, the minimum required coverage is 80%.

This standard helps ensure that new code is properly tested and reduces the risk of introducing bugs into the codebase. Teams should configure their CI/CD pipelines to automatically check coverage and fail builds that don’t meet this threshold.


exported functions documentation

All 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.

The documentation comments should:

Example of proper Go-style documentation:

// Get makes an HTTP GET request through the proxy pool with automatic
// retries and load balancing. It returns the response body and any error
// encountered during the request.
func Get(url string) (*http.Response, error) {
    // implementation
}

// Client represents an HTTP client with proxy pool capabilities
// for fault tolerance and load balancing.
type Client struct {
    // fields
}

This requirement ensures that all public APIs are self-documenting and accessible to other developers. Projects lacking proper documentation comments for exported elements should not be accepted until this standard is met, as it directly impacts the usability and professional quality of the codebase.


React Docs With Scope

When adding or updating React documentation, include usage-scoped, actionable guidance—not just headings.

Apply this checklist:

Example (pattern):

`someHook` is a React hook that ...

Use it to ...
Avoid using it when ...

Resources:
- React docs: https://react.dev/... 
- More: https://...

optimize CI efficiency

Optimize 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.

For package optimization, prefer minimal variants:

- name: Install Vim
  run: apt-get update; apt-get install -y vim-nox;

For conditional execution, use file change detection:

- name: Verify Changed Files
  uses: tj-actions/verify-changed-files@v16
  with:
    files_ignore: |
      *.md

For dependency management, use automatic resolution:

- name: Get dependencies
  run: go get -t -v ./...

This approach reduces CI execution time, minimizes resource consumption, and prevents unnecessary workflow runs while maintaining functionality. It’s particularly important for repositories with frequent contributions that don’t affect core functionality.


Vet dependency supply chains

When 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 activity patterns.

Before accepting any dependency, verify:

Example of concerning patterns to reject:

// Red flags identified in review:
- Empty commits: "c1a4854ffb9e83f903469490b44d640f233889c8"
- Account automation without visible GitHub Actions
- Packaging unofficial Go fork of asciinema instead of official version
- Underlying tracker with suspicious commit patterns

Supply chain attacks are a critical security vector - taking time to properly vet dependencies protects the entire ecosystem from potential compromise.


Simplify CI scripting

Keep CI/CD workflow steps readable and maintainable by consolidating repeated commands and using basic shell utilities for log processing.

Apply these rules:

Example (PR log cleanup + artifact):

# Run lint and capture output
fpb-lint ./books/ &>> output.log || echo "Analyzing..."
fpb-lint ./casts/ &>> output.log || echo "Analyzing..."
fpb-lint ./courses/ &>> output.log || echo "Analyzing..."
fpb-lint ./more/ &>> output.log || echo "Analyzing..."

# Prepare artifact
mkdir -p ./pr
echo "$PR_URL" > ./pr/PRurl

# Bash cleanup (single-line transformation + dedupe)
cat output.log | sed -E 's:/home/runner/work/free-programming-books/|⚠.+::' | uniq > ./pr/error.log

If the cleanup logic becomes complex enough that shell becomes unreadable, then (and only then) consider a script—but default to the simplest working approach.


Least-privilege Actions tokens

Treat 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: 1) Do not use insecure token workarounds that broaden or misuse GITHUB_TOKEN. 2) Split producer/consumer logic into separate workflows: have one workflow generate the content and upload it as an artifact, then a second workflow reads that artifact and performs the PR write. 3) Declare least-privilege permissions at the job level. If a job comments on PRs, set only what’s needed (e.g., pull-requests: write). Avoid “write by default” repo settings for public repos.

Example (job-level permissions + artifact-based handoff):

# consumer workflow: posts PR comment/review
on:
  workflow_run:
    workflows: ["free-programming-books-lint"]
    types: [completed]

jobs:
  post:
    permissions:
      pull-requests: write
    steps:
      - name: Download artifact from producer
        uses: actions/download-artifact@v4
        with:
          name: pr-message
      - name: Post message to PR
        run: |
          # read file produced earlier and use it to comment
          MSG_FILE=./message.txt
          cat "$MSG_FILE"
          # call GitHub API using default GITHUB_TOKEN with only PR write permission

This prevents authorization failures while reducing the blast radius of the token in CI/CD (a core security best practice for authentication/authorization in workflows).


Verify markdown sanitization

When 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.

Before adding sanitization calls, check the library documentation to understand its security features. For libraries without built-in sanitization:

// blackfriday requires explicit sanitization
body := string(blackfriday.MarkdownCommon(input))
sanitized := bluemonday.UGCPolicy().SanitizeBytes([]byte(body))

For libraries with built-in sanitization, avoid double-sanitization:

// github_flavored_markdown already sanitizes - no additional sanitization needed
body := string(gfm.Markdown(input))

This prevents both security gaps from missing sanitization and performance issues from redundant sanitization calls.


Consistent Markdown Tables

When 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.

Apply these rules:

Example (use the same structure/pattern as the surrounding docs):

Courses | Duration | Effort
:-- | :--: | :--:
[Machine Learning by Andrew Ng](https://www.coursera.org/learn/machine-learning) | - | -

If a row appears missing in the rendered preview, first check for stray/extra lines that break the table block, then verify the header/separator pattern matches the established one.


Verify URL security and validity

Always 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.

When adding external links:

  1. Prefer HTTPS over HTTP for security (e.g., use https://bit.ly/go-slack-signup instead of http://bit.ly/go-slack-signup)
  2. Test that URLs actually resolve to the intended resource
  3. For repository links, verify the correct path (e.g., https://github.com/anacrolix/torrent/tree/master/dht for source code or https://godoc.org/github.com/anacrolix/torrent/dht for documentation)

This practice protects users from security vulnerabilities and ensures reliable access to referenced resources.


Follow Go style guidelines

Code 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.

High-quality Go code typically follows these standards naturally, and requiring this adherence helps filter out packages where insufficient care was taken in code quality. For existing, well-established packages, some flexibility may be acceptable, but new code should strive to follow these guidelines closely.

Consider using automated tools like golint or services like goreportcard.com to validate style compliance, though remember that these tools provide suggestions rather than absolute requirements. The goal is readable, idiomatic Go code that follows community standards.