@ai-support-agent/cli 0.1.32-beta.1 → 0.1.33-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/commands/claude-code-args.d.ts +1 -0
  2. package/dist/commands/claude-code-args.d.ts.map +1 -1
  3. package/dist/commands/claude-code-args.js +3 -0
  4. package/dist/commands/claude-code-args.js.map +1 -1
  5. package/dist/commands/claude-code-runner.d.ts.map +1 -1
  6. package/dist/commands/claude-code-runner.js +2 -1
  7. package/dist/commands/claude-code-runner.js.map +1 -1
  8. package/dist/commands/plugin-dir.d.ts +20 -0
  9. package/dist/commands/plugin-dir.d.ts.map +1 -0
  10. package/dist/commands/plugin-dir.js +71 -0
  11. package/dist/commands/plugin-dir.js.map +1 -0
  12. package/dist/plugin/.claude-plugin/plugin.json +9 -0
  13. package/dist/plugin/LICENSE +26 -0
  14. package/dist/plugin/README.md +86 -0
  15. package/dist/plugin/SYNC.md +113 -0
  16. package/dist/plugin/agents/build-error-resolver.md +159 -0
  17. package/dist/plugin/agents/code-reviewer.md +277 -0
  18. package/dist/plugin/agents/django-reviewer.md +159 -0
  19. package/dist/plugin/agents/infra-reviewer.md +172 -0
  20. package/dist/plugin/agents/investigator.md +75 -0
  21. package/dist/plugin/agents/nextjs-reviewer.md +191 -0
  22. package/dist/plugin/agents/php-reviewer.md +167 -0
  23. package/dist/plugin/agents/planner.md +184 -0
  24. package/dist/plugin/agents/python-reviewer.md +161 -0
  25. package/dist/plugin/agents/react-reviewer.md +150 -0
  26. package/dist/plugin/agents/silent-failure-hunter.md +158 -0
  27. package/dist/plugin/agents/typescript-reviewer.md +179 -0
  28. package/dist/plugin/agents/ui-reviewer.md +203 -0
  29. package/dist/plugin/commands/add-feature.md +301 -0
  30. package/dist/plugin/commands/build-fix.md +47 -0
  31. package/dist/plugin/commands/code-review.md +228 -0
  32. package/dist/plugin/commands/fix-defect.md +393 -0
  33. package/dist/plugin/commands/learn-eval.md +94 -0
  34. package/dist/plugin/commands/learn.md +84 -0
  35. package/dist/plugin/commands/plan.md +211 -0
  36. package/dist/plugin/commands/test-coverage.md +64 -0
  37. package/dist/plugin/commands/update-docs.md +98 -0
  38. package/dist/plugin/hooks/hooks.json +59 -0
  39. package/dist/plugin/hooks/scripts/auto-format.sh +63 -0
  40. package/dist/plugin/hooks/scripts/check-secrets-before-commit.sh +50 -0
  41. package/dist/plugin/hooks/scripts/guard-dangerous-commands.sh +55 -0
  42. package/dist/plugin/hooks/scripts/on-command-resume.sh +112 -0
  43. package/dist/plugin/hooks/scripts/on-command-stop.sh +200 -0
  44. package/dist/plugin/hooks/scripts/protect-sensitive-files.sh +58 -0
  45. package/dist/plugin/rules/common/coding-guidelines.md +73 -0
  46. package/dist/plugin/rules/documentation/api-docs.md +46 -0
  47. package/dist/plugin/rules/documentation/docs-site.md +60 -0
  48. package/dist/plugin/rules/documentation/source-docs.md +89 -0
  49. package/dist/plugin/rules/documentation/test-docs.md +39 -0
  50. package/dist/plugin/rules/logging/logging-rules.md +83 -0
  51. package/dist/plugin/rules/php/coding-rules.md +40 -0
  52. package/dist/plugin/rules/python/coding-rules.md +40 -0
  53. package/dist/plugin/rules/typescript/coding-rules.md +45 -0
  54. package/dist/plugin/skills/api-design/SKILL.md +269 -0
  55. package/dist/plugin/skills/backend-patterns/SKILL.md +312 -0
  56. package/dist/plugin/skills/database-migrations/SKILL.md +323 -0
  57. package/dist/plugin/skills/docker-patterns/SKILL.md +308 -0
  58. package/dist/plugin/skills/docs-site/SKILL.md +341 -0
  59. package/dist/plugin/skills/e2e-testing/SKILL.md +334 -0
  60. package/dist/plugin/skills/frontend-patterns/SKILL.md +318 -0
  61. package/dist/plugin/skills/integration-testing/SKILL.md +273 -0
  62. package/package.json +2 -2
@@ -0,0 +1,60 @@
1
+ # Documentation Site Conventions (Docusaurus / i18n)
2
+
3
+ The documentation site standardizes on Docusaurus and supports switching between locales. For concrete build and integration steps and templates, see the docs-site skill. This document defines what must be upheld.
4
+
5
+ ## i18n (multiple languages)
6
+
7
+ - Support exactly two locales: a **default** locale and a secondary locale (e.g., `en` as default, `ja` as secondary — pick and declare the pairing per project).
8
+ - **Hand-written guides and conceptual pages must exist in both locales.** Any PR that updates the source-language page must also update the translation.
9
+ - If a translation unavoidably lags behind, add an "untranslated" notice at the top of the translated page (including the date the source was last updated). This notice is something the update-docs workflow should detect.
10
+ - Auto-generated reference pages (see below) only need to exist in the default locale — this is a deliberate decision to keep translation-sync costs down.
11
+
12
+ ## Page categories and generation method
13
+
14
+ | Page type | Method | i18n |
15
+ |---|---|---|
16
+ | Guides, concepts, tutorials | Hand-written | Both languages required |
17
+ | NestJS API reference | Auto-generated from OpenAPI (no hand-transcription) | Default locale only |
18
+ | TypeScript library function reference | Recommended: auto-generated from TypeDoc | Default locale only |
19
+ | Python / PHP function reference | Hand-written from a template, with a consistency check | Default locale only |
20
+
21
+ ## Sidebar organization (structuring the function list)
22
+
23
+ - Organize function references in the sidebar as a **category (module / functional area) → function name** hierarchy.
24
+ - Auto-generated pages use the sidebar the plugin outputs; hand-written pages must always be registered in the category definitions in `sidebars.js` — never leave a page unregistered (i.e., undiscoverable from the index).
25
+ - Order categories by usage frequency and learning path, not mechanically by alphabetical order.
26
+
27
+ ## Required sections on a function detail page (the canonical template)
28
+
29
+ Whether hand-written or auto-generated, every function detail page must include:
30
+
31
+ 1. **Overview** — 1–3 sentences on what the function is for.
32
+ 2. **Signature** — the declaration, matching the implementation exactly.
33
+ 3. **Parameters table** — name / type / required / description (**name and required-ness must match the implementation character-for-character**).
34
+ 4. **Output (return value)** — type and content, including how it varies by condition if applicable.
35
+ 5. **Errors** — exceptions thrown or error codes returned, and the condition that triggers each.
36
+ 6. **Usage example** — a minimal, working code snippet.
37
+ 7. **Tests** — a link to the relevant test file (optional but recommended).
38
+
39
+ ## Keeping docs in sync with source (verification convention for transcribed content)
40
+
41
+ - **Hand-written reference pages must include a `source` key in frontmatter.**
42
+
43
+ ```yaml
44
+ ---
45
+ source: src/services/estimateApproval.ts#requiresDirectorApproval
46
+ ---
47
+ ```
48
+
49
+ - `source` is the machine-readable anchor for consistency checking. The update-docs workflow uses this key as a starting point to read the implementation and verify:
50
+ - **Incorrect** function or parameter names (mismatched against the implementation)
51
+ - **Missing** parameters or error entries (present in the implementation but absent from the page)
52
+ - **Stale leftovers** (present on the page but removed from the implementation)
53
+ - The page must always describe the implementation **as it actually behaves**. If you believe the implementation itself is wrong, propose fixing the implementation — don't just edit the page to match a mistake.
54
+
55
+ ## Linking to tests
56
+
57
+ - Use **repository-absolute URLs anchored to the default branch** (e.g., `https://github.com/<org>/<repo>/blob/main/src/services/estimateApproval.spec.ts`).
58
+ - Don't use commit-SHA-pinned links — they're costly to maintain and inevitably go stale.
59
+ - For linking from auto-generated TypeDoc pages, use the TSDoc `@see` tag.
60
+ - The update-docs workflow verifies that linked files exist.
@@ -0,0 +1,89 @@
1
+ # In-Source Documentation Conventions
2
+
3
+ Building on the commenting principles in `rules/common/coding-guidelines.md`, this document defines the format and language for doc comments.
4
+
5
+ ## Declaring the designated language
6
+
7
+ - Declare your documentation language in each project's CLAUDE.md, using a section like this:
8
+
9
+ ```markdown
10
+ ## Documentation conventions
11
+ - Designated language: English | Japanese | Bilingual
12
+ - Adopted conventions: list which files under rules/documentation/ this project follows (e.g., source-docs, api-docs, docs-site, test-docs)
13
+ ```
14
+
15
+ - **If undeclared, the default is English** (adjust this default to whatever fits your project/organization).
16
+ - Public libraries and repositories with external collaborators should favor "English" or "Bilingual."
17
+ - Reviewers should only flag mismatches against the *declared* language. If you spot mixed languages in a project with no declaration, propose adding the declaration rather than flagging the mix itself.
18
+
19
+ ## General principles
20
+
21
+ - Doc comments are required only for **public APIs, exported functions, and shared library code** — not for internal helpers whose name and signature are already self-explanatory.
22
+ - Required elements: a one-sentence summary, parameter descriptions, return value description, and any exceptions thrown (if applicable).
23
+ - Favor explaining "why this exists / what constraints apply" over "what it does." Don't write a comment that just restates the implementation.
24
+ - Don't repeat information the signature (type declarations) already conveys.
25
+
26
+ ## Format by language
27
+
28
+ ### TypeScript — TSDoc
29
+
30
+ ```typescript
31
+ /**
32
+ * Determines whether the estimate amount exceeds the approval threshold.
33
+ *
34
+ * @param estimate - The estimate to evaluate. Must already be finalized.
35
+ * @param threshold - The threshold (pre-tax, in the base currency). Falls back to the system setting if omitted.
36
+ * @returns true if the amount exceeds the threshold
37
+ * @throws {EstimateNotFixedError} if the estimate has not been finalized
38
+ * @see tests/services/estimateApproval.spec.ts
39
+ */
40
+ ```
41
+
42
+ - Use `@param` / `@returns` / `@throws`. Let the signature carry the type information — don't restate types in the comment.
43
+ - Use `@see` to reference related tests or functions (this also becomes a link on the documentation site).
44
+
45
+ ### Python — docstrings (Google style)
46
+
47
+ ```python
48
+ def calculate_invoice_total(invoice_id: int) -> Decimal:
49
+ """Calculates the total amount for an invoice.
50
+
51
+ Args:
52
+ invoice_id: The target invoice ID. Must already be finalized.
53
+
54
+ Returns:
55
+ The tax-inclusive total amount.
56
+
57
+ Raises:
58
+ InvoiceNotFoundError: If the invoice does not exist.
59
+ """
60
+ ```
61
+
62
+ - Use Google style (Args / Returns / Raises) as the default. If a project already uses NumPy or reST style, follow the existing convention instead.
63
+
64
+ ### PHP — PHPDoc
65
+
66
+ ```php
67
+ /**
68
+ * Confirms an order and allocates inventory for it.
69
+ *
70
+ * @param Order $order The order to confirm. Must be in draft status.
71
+ * @return Order The confirmed order
72
+ * @throws InventoryShortageException If there is insufficient inventory.
73
+ */
74
+ ```
75
+
76
+ - Omit type annotations that duplicate native type declarations (parameter and return types). Don't write a bare `@param Order $order` line with no description.
77
+
78
+ ## Bilingual format
79
+
80
+ When the designated language is "Bilingual," write the primary language first, followed by the secondary language, within the same block.
81
+
82
+ ```typescript
83
+ /**
84
+ * Determines whether the estimate amount exceeds the approval threshold.
85
+ * (secondary-language translation of the same sentence)
86
+ */
87
+ ```
88
+
89
+ - The summary is required in both languages. Parameter descriptions are required in the primary language and optional in the secondary language, to keep the maintenance burden reasonable.
@@ -0,0 +1,39 @@
1
+ # Test Documentation Conventions
2
+
3
+ Tests are a specification. The goal is that reading the list of test names alone gives you a list of the spec's requirements, and reading a test's body gives you the detail (what it covers and why).
4
+
5
+ ## Writing describe / it blocks
6
+
7
+ - **describe**: names the subject under test (class, function, or endpoint). Use nested describes to represent different scenarios ("when inventory is insufficient," "when the user has admin privileges").
8
+ - **it / test**: write a **complete specification sentence that includes an observable outcome**, in the project's designated language.
9
+
10
+ ```typescript
11
+ describe('EstimateApprovalService.approve', () => {
12
+ describe('when the estimate amount exceeds $10,000', () => {
13
+ it('does not become approved until director approval is complete', () => { ... });
14
+ it('throws PendingDirectorApprovalError when only the manager has approved', () => { ... });
15
+ });
16
+ });
17
+ ```
18
+
19
+ - Forbidden names: uninformative labels like "happy path," "error case 1," "test1," "works," "OK" — anything that doesn't convey the spec on its own.
20
+ - **Whatever outcome the test name claims must actually be asserted in the body.** A name like "throws an exception" with no assertion verifying the exception is a mismatch that the update-docs workflow and code review should catch.
21
+
22
+ ## Structuring the test body
23
+
24
+ - Separate Arrange / Act / Assert with blank lines so the flow is easy to follow.
25
+ - For complex setup, add a comment explaining what scenario is being constructed.
26
+ - Annotate meaningful test data with its rationale (e.g., `1_000_001 // one above the $10,000 threshold boundary`). Don't annotate values that have no particular significance.
27
+
28
+ ## Conventions by stack
29
+
30
+ | Stack | Test naming | Notes |
31
+ |---|---|---|
32
+ | Jest / Vitest / Playwright | describe + it (as above) | Nest with `test.describe` where helpful |
33
+ | pytest | Test function name (e.g., `test_requires_director_approval_above_threshold`, in the designated language if appropriate) | For complex cases, put the summary and intent in a docstring |
34
+ | PHPUnit | Test method name | The `@testdox` annotation can spell out the spec sentence; `#[TestDox('throws an exception when inventory is insufficient')]` is recommended |
35
+
36
+ ## Scope of application
37
+
38
+ - All new tests must follow this convention.
39
+ - Rename existing tests opportunistically, as part of a change that already touches them — a rename-only bulk change isn't worth the review cost on its own.
@@ -0,0 +1,83 @@
1
+ # Logging Conventions
2
+
3
+ Goal: make it possible for both humans and AI to complete debugging **by reading only the source comments and the logs**. The standard is that logs alone should let you reconstruct "which user's, which request's, which function, with what input, passed through and failed where."
4
+
5
+ ## Adoption and cost tuning
6
+
7
+ - Projects adopting this convention should add `logging` to the "adopted conventions" list in the "## Documentation conventions" section of their CLAUDE.md.
8
+ - Log volume translates directly into cost, so **control output level via an environment variable** and tune it per project (typical default: INFO in production, DEBUG in development/investigation as a debug mode).
9
+ - For high-traffic code paths, consider sampling DEBUG output (emit only a fraction of events). Document any such tuning in CLAUDE.md.
10
+
11
+ ## Basics
12
+
13
+ - **Structured logging (JSON) is the standard.** Emit a `message` plus fields — don't embed information via string concatenation.
14
+ - Field names are **full English words in snake_case, never abbreviated** (`request_id`, not `req_id`; `user_id`, not `uid`; also `duration_ms`, `function_name`).
15
+ - Write messages in the project's designated language (same as the documentation convention; default to English if undeclared). Field names are always in English.
16
+
17
+ ### Choosing a log level
18
+
19
+ | Level | Use |
20
+ |---|---|
21
+ | ERROR | A failure that requires action. Always include the exception, correlation ID, and the ID of the affected resource. |
22
+ | WARN | An anomaly that self-recovered, a retry, approaching a threshold — anything worth monitoring. |
23
+ | INFO | Business events (start/completion of order confirmation, invoice issuance, etc.; state transitions). The standard production level. |
24
+ | DEBUG | For investigation: function start/end, inputs/outputs, and the data behind branching decisions. |
25
+
26
+ ## Correlation IDs (end-to-end tracing)
27
+
28
+ To let you trace all logs from a single request across the system, **attach the following to every log entry automatically** — never pass them manually at each call site.
29
+
30
+ - `request_id`: capture the `X-Request-Id` header at the request entry point (generate one if absent), set it in the logging context, and echo it back in the response header.
31
+ - `user_id` (set after authentication), `tenant_code` (in multi-tenant systems, also useful for verifying tenant isolation).
32
+ - `trace_id`: if you have AWS X-Ray (or an equivalent tracing system) enabled, include the trace ID as well, so logs and traces can be cross-referenced (for Lambda, enabling active tracing propagates the header automatically).
33
+ - **Propagation into async work**: when enqueuing a job, include `request_id` in the message and restore it into the logging context on the worker side. For batch-originated processing, generate a `job_id` per execution unit.
34
+
35
+ ### Implementing context propagation, by stack
36
+
37
+ | Stack | Implementation |
38
+ |---|---|
39
+ | NestJS | nestjs-pino + AsyncLocalStorage (set request_id / user_id in middleware). On Lambda, AWS Lambda Powertools Logger + `injectLambdaContext`. |
40
+ | Django / Flask | structlog + contextvars. Bind in middleware; propagate to Celery etc. via headers. |
41
+ | Laravel | Set Log Context (`Context::add()`) in middleware. Propagate to queued jobs via Context dehydration. |
42
+ | CakePHP | Attach common fields via a Monolog Processor. |
43
+
44
+ ## Debug mode (DEBUG level)
45
+
46
+ - **Log the start and end of each function**: `function_name`, the input (INPUT) at start, and the output (OUTPUT) plus `duration_ms` at end.
47
+ - Apply this to public methods in the service/use-case layer by default; skip trivial getters and one-line utilities.
48
+ - Don't scatter this by hand — implement it cross-cuttingly (decorators, interceptors, etc.).
49
+
50
+ ```typescript
51
+ // NestJS example: a method decorator that logs start/end/input/output at DEBUG level
52
+ @LogExecution() // implementation lives in a shared project library
53
+ async approveEstimate(input: ApproveEstimateInput): Promise<EstimateResult> { ... }
54
+ // DEBUG: {"message":"function start","function_name":"approveEstimate","input":{...},"request_id":"..."}
55
+ // DEBUG: {"message":"function end","function_name":"approveEstimate","output":{...},"duration_ms":42,"request_id":"..."}
56
+ ```
57
+
58
+ ### Masking (required even at DEBUG level)
59
+
60
+ - Never log passwords, tokens, API keys, or personal information (name, email, address, etc., per your project's definition) — **even at DEBUG level**. Route these through a shared masking function.
61
+ - Truncate large payloads (file contents, large arrays) down to a count/size summary.
62
+
63
+ ## Recording errors
64
+
65
+ - Every ERROR log must include: the exception object (with stack trace), `request_id`, the ID of the affected resource (e.g., `order_id`), and what operation was being attempted.
66
+ - **If the project uses Sentry, capture unhandled exceptions there too.**
67
+ - Send them via a single global exception handler (a NestJS exception filter, or the equivalent in Django/Laravel) rather than manually capturing at each call site. (Rule of thumb: only manually capture "handled" exceptions — ones that don't propagate to the caller — when they're operationally worth knowing about.)
68
+ - Set `request_id` / `user_id` as Sentry tags/context so they can be cross-referenced with logs and traces.
69
+ - Don't report exceptions that were caught and handled as part of normal flow — that's just noise and duplicate alerting.
70
+ - The discipline of error handling itself (never swallow, preserve the cause) follows the standards in rules/common and the silent-failure-hunter criteria.
71
+
72
+ ## Checklist: logs an AI can debug from
73
+
74
+ Confirm new feature logging design satisfies the following:
75
+
76
+ - [ ] Every log for a given request (including async work) can be retrieved by `request_id`.
77
+ - [ ] The retrieved logs alone reveal the order of functions traversed and their inputs/outputs (at DEBUG level).
78
+ - [ ] On failure, the ERROR log has everything: where it happened, what was being attempted, what went wrong, and what resource was affected.
79
+ - [ ] Read together with the source comments (constraints, intent), you can form a root-cause hypothesis without running the code.
80
+
81
+ ## Naming and clarity (a prerequisite shared with logging)
82
+
83
+ Readable logs depend on readable naming in the implementation. Follow the naming rules in `rules/common/coding-guidelines.md` (**avoid abbreviations, use full English words; name functions so they read as a sentence describing what they do**). Ideally, `function_name` alone should read like a spec.
@@ -0,0 +1,40 @@
1
+ # PHP Coding Rules
2
+
3
+ For language-agnostic rules, see `rules/common/coding-guidelines.md`. This document covers only PHP-specific rules.
4
+
5
+ ## Language and types
6
+
7
+ - Add `declare(strict_types=1)` to every new file (except views such as Blade templates).
8
+ - Declare parameter and return types on public methods. Reserve `mixed` for cases that genuinely can't be expressed as a union type.
9
+ - Mark constructor-promoted properties `readonly` when they're never reassigned.
10
+ - Leave formatting to Pint / PHP CS Fixer (PSR-12) — don't debate formatting in review.
11
+ - Never commit `var_dump()` / `dd()` / `dump()` calls.
12
+
13
+ ## Error handling
14
+
15
+ - Empty `catch (\Exception $e) {}` blocks are forbidden. Log the error and handle it (propagate, retry, notify).
16
+ - When re-throwing, preserve the cause: `throw new XxxException('...', previous: $e)`.
17
+ - Don't ignore the return value of APIs that return `false` on failure (e.g., `save()`).
18
+
19
+ ## Laravel
20
+
21
+ - Define `$fillable` on every model. `$guarded = []` is forbidden.
22
+ - Don't pass `$request->all()` directly into a save. Define a FormRequest and use `$request->validated()`; implement `authorize()` too.
23
+ - Use `with()` / `load()` for eager loading whenever you access a relation in a loop.
24
+ - Any user input passed into `DB::raw()` / `whereRaw()` must use parameter binding.
25
+ - Never use Blade's `{!! !!}` on user-supplied data. If you must, comment the sanitization rationale.
26
+ - Implement `failed()` on queued jobs and configure `$tries` / `$backoff`. Write jobs to be idempotent.
27
+ - Authorize via `auth` middleware plus `Gate` / `Policy` — don't rely on hiding UI elements alone.
28
+ - Define `$casts` for date, JSON, and boolean columns.
29
+
30
+ ## CakePHP
31
+
32
+ - Never set `'*' => true` in an Entity's `$_accessible`. Explicitly list which fields allow mass assignment.
33
+ - Use `contain()` when accessing related data in a loop.
34
+ - Use `validationDefault()` for input format validation, and `buildRules()` for domain rules like uniqueness/existence checks — keep the two separate.
35
+ - Always check the return value of `save()`.
36
+ - Never interpolate variables directly into query conditions (`"field = '$value'"`). Use array conditions or parameter binding instead.
37
+
38
+ ## Documentation
39
+
40
+ - For PHPDoc format and comment language, see `rules/documentation/`.
@@ -0,0 +1,40 @@
1
+ # Python Coding Rules
2
+
3
+ For language-agnostic rules, see `rules/common/coding-guidelines.md`. This document covers only Python-specific rules.
4
+
5
+ ## Type hints and syntax
6
+
7
+ - Add type hints to public functions. Reserve `Any` for receiving data at external boundaries — narrow it to a concrete type internally.
8
+ - Make optionality explicit with `X | None` (3.10+) or `Optional[X]`.
9
+ - Mutable default arguments (`def f(items=[])`) are forbidden. Default to `None` and construct the value inside the function.
10
+ - Never compare against `None` with `==`. Use `is None` / `is not None`.
11
+ - Don't shadow builtin names (`list`, `dict`, `id`, `type`).
12
+ - Leave formatting and import ordering to ruff / black — don't debate them in review.
13
+
14
+ ## Error handling
15
+
16
+ - Bare `except:` and `except Exception: pass` are forbidden. Catch specific exceptions and handle them (log and propagate, retry, or notify).
17
+ - Manage files, connections, and locks with `with` (context managers).
18
+ - When re-raising, preserve the cause with `raise ... from e`.
19
+
20
+ ## Django
21
+
22
+ - Always use `select_related` (FK/OneToOne) or `prefetch_related` (M2M/reverse relations) when accessing related objects in a loop.
23
+ - Never do a read-increment-save cycle for counters; update atomically with an `F()` expression.
24
+ - Wrap multiple writes in `transaction.atomic()`.
25
+ - Every model change needs a migration; drop columns via a two-phase deploy (make nullable → remove references → drop the column in a later release).
26
+ - DRF: `fields = '__all__'` on a Serializer is forbidden. List fields explicitly and set `read_only_fields`. List endpoints must be paginated.
27
+ - Use `save(update_fields=[...])` for partial updates so you don't clobber concurrent writes.
28
+ - Don't use signals for intra-app model-to-model coordination; prefer explicit calls from the service layer.
29
+
30
+ ## Flask
31
+
32
+ - Use the application factory pattern (`create_app()`). Don't instantiate `app` at module level.
33
+ - Split routes into feature-scoped Blueprints.
34
+ - Validate `request.json` / `request.args` with marshmallow or pydantic before use.
35
+ - Keep request-scoped state in `g` and configuration in `app.config`. Don't share state through mutable module-level globals.
36
+ - Ensure `db.session.commit()` failures trigger a `rollback()` (via try/except/finally or a teardown handler).
37
+
38
+ ## Documentation
39
+
40
+ - For docstring format (Google style) and comment language, see `rules/documentation/`.
@@ -0,0 +1,45 @@
1
+ # TypeScript Coding Rules
2
+
3
+ For language-agnostic rules, see `rules/common/coding-guidelines.md`. This document covers only TypeScript-specific rules.
4
+
5
+ ## Types
6
+
7
+ - Assume `strict: true`. Any change that weakens tsconfig strictness needs justification in review.
8
+ - `any` is forbidden as a rule. Receive external data as `unknown` and narrow it. If you must use `any`, comment why.
9
+ - Give public/exported functions an explicit return type.
10
+ - Prefer type guards and early returns over the non-null assertion (`value!`).
11
+ - Don't silence a type error with an `as` cast — if a cast feels necessary, fix the type definition instead.
12
+ - Consider type aliases or branded types for domain values (avoid parameter lists that are all bare `string`).
13
+
14
+ ## Asynchronous code
15
+
16
+ - Always `await` a Promise, or mark an intentional fire-and-forget with a `void` prefix and a comment explaining why.
17
+ - `array.forEach(async ...)` is forbidden. Use `for...of` (sequential) or `Promise.all` (parallel).
18
+ - Don't sequentially `await` independent async operations — batch anything that can run in parallel with `Promise.all`.
19
+ - Set a timeout on external calls via `AbortController` or client configuration.
20
+
21
+ ## Modules and syntax
22
+
23
+ - Default to `const`; use `let` only when reassignment is required. Never use `var`.
24
+ - Use only `===` / `!==` for equality comparisons.
25
+ - Prefer a union type (`type Status = 'active' | 'inactive'`) or `as const` over `enum`.
26
+ - Don't overuse barrel files (re-exporting everything through `index.ts`) — they cause circular imports and bundle bloat.
27
+
28
+ ## NestJS
29
+
30
+ - Always receive input through a DTO with class-validator decorators. Set `whitelist: true` on the global `ValidationPipe`.
31
+ - Explicitly attach a Guard (authentication + authorization) to protected routes. Any use of `@Public()` needs justification in review.
32
+ - Direct access to `process.env` is forbidden. Use `ConfigService` with startup-time schema validation.
33
+ - If you find yourself needing `forwardRef()`, treat it as a signal to revisit the design (extract a shared module, or move to an event-driven approach instead).
34
+ - Convert exceptions via `HttpException` subclasses or an exception filter — never leak internal details into the response.
35
+
36
+ ## Next.js
37
+
38
+ - Place `"use client"` close to the interactive leaf component that needs it — not at the top of a page or layout.
39
+ - Treat Server Actions and Route Handlers as public endpoints: check the session, authorize, and validate the schema at the top of each one.
40
+ - Never put secrets in `NEXT_PUBLIC_*` variables.
41
+ - Use `next/image` for content images and `next/link` for internal navigation.
42
+
43
+ ## Documentation
44
+
45
+ - For TSDoc format, comment language, and the OpenAPI workflow (NestJS → Next.js type generation), see `rules/documentation/`.