# Development Policies

> Revision 1 November 5, 2026

The woodger policies set out common principles for working with code, tests, documentation, and project maintenance. They help explain the reasons behind decisions and choose an approach suited to the current task. The documents are published here so that projects can refer to a shared source.

## How to use

The change policy is a useful starting point; the other documents can be selected according to the task. Examples for a particular language, framework, or application type illustrate the principles in that context. Their use in a project follows its needs and existing decisions.

| Change or Question | Politics |
| --- | --- |
| Do I need to make an edit and how can I limit the diff? | [Making changes](./change-policy.md) |
| Responsibilities and dependencies between parts of a project | [Architecture](./architecture.md) |
| Removing unused code | [Vitality of code](./code-liveness-policy.md) |
| Production comments | [Comments](./comment-style.md) |
| Comments in tests | [Comments in tests](./test-comment-style.md) |
| Visual code structure | [Code style](./code-style.md) |
| Names in code and runtime | [Naming](./naming-policy.md) |
| Scripts, build and test pipeline | [Scripts and assembly](./scripts-policy.md) |
| Reader tasks, document roles, and contract sources | [Documentation](./documentation-policy.md) |
| Observability and Instrumentation | [Metrics](./metrics-policy.md) |
| Reusable modules | [Isolation of abstractions](./abstraction-policy.md) |
| Selecting libraries | [Dependencies](./dependencies-policy.md) |
| Structure and sufficiency of tests | [Testing](./testing-policy.md) |

## Languages and platforms

Conventions for JavaScript, TypeScript, Node.js, Svelte, SvelteKit, and web interfaces are collected in [Languages and platforms](./languages-and-platforms.md). This document complements the shared principles with technology-specific guidance and explains their scope for Python projects.

## Standard limits

The policies set out working principles. A project's code, contracts, and documentation describe its particular architecture, APIs, data formats, URLs, configuration, infrastructure, and commands. Changes to those decisions are considered within a task for that project.

If there is a discrepancy, keep the current contract and report the conflict. The scope clarification is added to the overall standard rather than to a separate copy of the project policy. Explicit instructions from the owner regarding the current task take precedence.

## Justified exceptions

Exceptions to the standard's rules are allowed when justified. The justification must appear in a code comment next to the affected code. The comment must identify the rule and explain why an exception is justified at that location.

## Project connection

The project documentation uses the same link:

```md
Политики разработки: [единый стандарт woodger](https://woodger.org/development).
```

In the instructions for the agent, indicate the same entry point and the need to read the rules before work. Nearby there are links to the architecture and instructions of a specific repository. Local sections with copies of general policies are deleted after all project contracts have been migrated and incoming references have been corrected.

## Editions and sources

HTML pages and Markdown have the same source: the `content/development` files in the site repository. The Markdown of each page is available under the "Original Markdown" link. [Full standard](./all.md) allows you to read all policies in one request.

The change in normative meaning is accompanied by a new entry in [editorial histories](./revisions.md). Migrating documentation itself does not require massive renaming, formatting, or rewriting of working code.


---

# Change Policy

> Type: Policy. How to limit editing to the minimum required amount.

## Connecting a change to its task

Work starts with the result the user needs. For each proposed edit, it helps to identify which requirement it serves, which parts of the project it affects, and whether a smaller change would solve the task. Existing code and observable behavior provide the starting point until project evidence shows a reason to change them.

This makes it easier to distinguish necessary work from an independent improvement. Work on a task preserves the project's behavior and compatibility where the task does not require changes. If the solution requires changing them, describe the expected result in the task and verify it through checks.

Material questions about data, security, behavior, or architecture that remain after examining code and documentation are discussed with the owner.

## Minimal changes

Diff should be the minimum required to solve the problem.

Prohibited:

- major refactoring without request
- cleanup without justification
- style change outside the affected area
- changes to architecture, including module boundaries
- pipeline change
- change scripts
- change in behavior beyond the desired result

These changes include redesigning subsystems and moving files in bulk.

## Local improvements

Small improvements are allowed when they directly serve the task. A poor structure need not be preserved merely because it already exists.

Acceptable:

- eliminate local duplication
- improve naming
- simplify readability
- correct adjacent obvious defect
- improve local tests
- clarify a module’s responsibility
- move a small amount of code to improve readability

Terms:

- behavior does not change
- change remains local
- improvement helps solve the current problem

If an improvement is outside the scope of the task, it should be proposed separately.

## Examples

Acceptable:

- fix a specific defect in one module without rewriting adjacent code
- add point test for new requirement without changing existing test pipeline
- expand the already used branch `if`, if this is directly required by the task

Invalid:

- make unrelated renames, including bulk renames solely for consistency
- rewrite the entire module instead of fixing one branch
- change the file structure just because it seems more convenient

## Environmental problems

Do not change the project code due to environmental problems.

If the check fails to run due to missing tools, permissions, cache, shell utilities, or container restrictions, stop the blocked operation and describe the exact limitation. You need to request a decision when it is impossible to continue without the owner’s participation.

It is acceptable to use a local temporary cache/workdir only if it does not change the project or extend the task.

A safe equivalent command is valid if it preserves the meaning of the operation, for example `python3` instead of the missing `python`. Such replacement is indicated in the report. Installing software, changing rights, global configuration or package manager settings require explicit permission.

## Saved UI properties

If the task does not require the opposite, the change is saved:

- SSR and hydration;
- keyboard navigation, focus order and available names;
- native semantics controls and ARIA;
- responsive layout and hit targets;
- props, callbacks, snippets and value formats;
- order side effects and network requests;
- URL/query semantics, storage keys, versions and fallback behavior;
- handling loading, error and disabled states;
- lifecycle Canvas, Worker, listeners, timers and other runtime resources;
- existing build output and production entrypoints.

Visual edits affect behavior if they change control accessibility, navigation, data readability, or the size of the interactive area.

## General working copy

Before editing, `git status` is checked. Existing changes belong to the owner or concurrent work until proven otherwise. They cannot be rolled back, overwritten, or included in your commit. When files intersect, both tasks are saved; if a secure association is not possible, clarification is needed.

## Checking the result

A narrow relevant check is performed first. It should be expanded or repeated in case of new changes, errors or remaining risk. You cannot use the old build as proof of the work of the modified source.

The report distinguishes between successful, unsuccessful, not running, and checks blocked by the environment. You cannot assert the passage of a command that was not successfully executed.


---

# Architecture Policy

> Type: Policy. Principles for organizing code, assigning responsibilities, and working with dependencies.

This policy sets out a common approach to organizing code: how to assign responsibilities to different parts of a project and arrange their interaction. Each project's architecture documentation describes its particular structure.

The principles help explain who owns a behavior, what it depends on, and what an alteration will affect. Their application takes account of the task, the application's complexity, and decisions already made in the project.

## Module responsibilities

A module brings together code that serves one clear purpose. That purpose explains its name, its place in the project, and its connections to other modules.

For example, calculating a price, saving preferences, and displaying a form are different tasks. Separating them allows storage or presentation to change while the calculation stays the same. In a small component, a few local functions may provide this separation; separate layers and directories become useful as the need arises.

Finding a place for code starts with understanding its role. Existing architecture documentation and nearby modules help identify a suitable home. If several materially different options remain after examining them, discussing the intent with the project owner helps settle the decision before changing code.

## Dependencies

Domain rules remain independent of how data enters the application, is stored, and is displayed. A change of database, HTTP client, or UI framework can then affect the corresponding integration while core calculations stay the same.

An interaction with an external system can be expressed through a small interface that describes the application's needs. An implementation connects that interface to a particular technology. Such an interface is useful where the interaction has a distinct responsibility; the number of wrappers alone says little about architectural quality.

In an application organized into layers, the roles might look like this:

| Role | Responsibility | Examples |
| --- | --- | --- |
| Domain logic | Concepts, calculations, and rules of the task | Price calculation, checking domain conditions |
| Application scenarios | Sequences of actions and use of external capabilities | Loading data, saving a result |
| Integrations | Work with particular technologies and conversion of external data | HTTP, filesystem, storage |
| Presentation | Displaying data and handling user interaction | Form, table, loading state |
| Composition and startup | Selecting implementations, resolving settings, and connecting parts | Entry point, preparing dependencies |

This table illustrates a division of responsibilities. Layer names, directories, and separate modules follow the project's structure. A simple component or library may use fewer parts.

For example, in a project with `domain`, `application`, `infrastructure`, `presentation`, and `bootstrap` layers, domain rules stay in `domain`, scenarios use them through `application`, and concrete integrations are connected when the application is assembled. Presentation calls the scenarios while details of the external API remain in the integration. Shared pure utilities have their own technical role.

## Settings and external data

Defaults and pure configuration can be used across an application when reading them is deterministic and performs no external operations. Domain types help express the meaning of such settings.

For example, if a project uses `src/config.ts` for static configuration, that module may contain defaults and resource limits. Reading environment variables, files, and network resources stays in application setup code; the resolved values are passed explicitly to consumers.

Types from external SDKs and transport formats are best converted near the integration. Internal modules can then use stable application concepts and depend less on changes made by the provider.

## Contract sources

Each contract has a primary source that defines its exact form: a signature, data format, or set of values. Other representations rely on that source. Documentation explains meaning and usage, while tests check observable behavior.

| Subject | Source of the exact form | How documentation helps |
| --- | --- | --- |
| Domain models and rules | Types, value models, and validation functions | Explains domain meaning |
| Scenarios, external capabilities, and errors | Interfaces and input/output types | Describes a scenario and its result |
| Component properties and events | Property declaration or exported component type | Shows usage and interaction |
| Presentation model API | Exported factory or model interface | Explains state, actions, and lifetime |
| Page URLs and HTTP behavior | Route handler and its inputs | Explains parameters, statuses, and examples |
| External API | Provider's versioned schema | Identifies the version in use and how to update it |
| Request proxying | Handler and integration module | Explains allowed requests and response forwarding |
| Preference storage | Storage interface, format consumer, and adapter | Describes keys, versions, validation, and recovery |
| npm commands | `scripts` in `package.json` | Explains how to run commands and what they do |
| Dependency composition | Application composition code | Shows implementation selection and data flow |

A contract change starts at its primary source. Consumers, tests, generated representations, and documentation are updated with it so that all parts describe the same behavior. Generated declarations are reproduced from the source contract.

For persisted preferences, it helps to distinguish three tasks: the application describes the storage capability, the consumer defines its data key, version, and validation, and the adapter handles serialization and environment details. This separation supports recovery from damaged data and allows storage technology to change independently of data meaning.

## UI applications

In a user interface, it is especially useful to distinguish domain rules, user scenarios, and display state. They change for different reasons: a calculation rule follows the product's task, while an open panel or selected row follows the current interaction.

Domain calculations remain ordinary code that can be called and checked without a UI framework, DOM, or network client. An application scenario coordinates the work and returns a result. Presentation displays that result and handles `loading`, `error`, `empty`, `selected`, and `expanded` states.

HTTP, WebSocket, storage, and external SDK details are concentrated in integrations. Converting data and errors near the request lets a component work with a meaningful scenario result. For example, the component displays that no record was found, while the integration describes which HTTP status corresponds to that outcome.

### Components and presentation models

A component combines markup, local state, and actions related to its presentation. For a reusable UI component, a clear API of properties, callbacks, and markup snippets reduces coupling to a particular page or domain.

Local state stays close to the component while that keeps the code readable. If a component coordinates several actions, asynchronous operations, or repeated reactive behavior, a presentation model can collect that work in one place. An extracted model retains its presentation role even without markup.

Pure calculations, parsing, and normalization can form a separate computation module. This extraction helps when it makes behavior clearer and independently testable. A simple calculation can stay near its use.

### User features

A coherent user scenario helps identify a module's components, state, and local data transformations. Search, for example, may combine query input, a result list, and record selection.

A page assembles several such features and coordinates their interaction. A shared API allows them to connect through the page or an application scenario while each module retains its own internal structure.

Shared code emerges when there is a clear common task and real consumers. Reusing a component does not by itself make it independent of the domain: a product selection form retains knowledge of products even when used on several pages.

The [abstraction policy](./abstraction-policy.md) discusses shared code in more detail.

## State ownership

Mutable state has a clear owner that creates it, provides actions for changing it, and manages the lifetime of associated resources. Keeping it close to its use usually makes these connections clearer: in a component, a related scenario, a page, or the whole application.

Shared state emerges when independent consumers actually need it. An API with selection or reload actions helps keep data consistent. The location and lifetime of that state remain explicit, including when one instance is shared across the application.

Values entirely determined by other data are naturally expressed as calculations. This preserves a single source for a value and removes the need to synchronize several mutable copies.

### Asynchronous operations

An asynchronous operation's model reflects its actual states and valid transitions. For example:

```ts
type AsyncState<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'ready'; value: T }
  | { status: 'error'; error: AppError };
```

The specific form depends on the scenario. Explicit states help explain which data is available during loading or an error and avoid accidental contradictions between independent flags.

A request has an owner for its result. When requests compete, cancellation or checking whether a response is still current helps retain the result of the user's latest action.

### External effects and resources

A user action explicitly starts its associated scenario. Calculations express dependencies between values, while external effects connect state to the network, DOM, storage, and other systems.

A timer, subscription, event listener or Worker lives with the owner of the operation. Resources must be released when the corresponding lifecycle ends. Considering creation and release together makes behavior easier to understand when a page reopens, an action is canceled or a component is destroyed.

The application of these principles in [Svelte 5](./languages-and-platforms.md#svelte-5) and [SvelteKit](./languages-and-platforms.md#sveltekit) is described in Languages and platforms.

## File names and placement

A file's name and location help explain its role before reading the implementation. Existing project conventions provide guidance for new code; the [naming policy](./naming-policy.md) explains the general principles for choosing names.

A directory brings together code with a clear shared purpose. Names such as `utils`, `helpers`, or `shared` are useful only alongside a clear description of their contents. Framework directories such as `src/lib` and `src/routes` already have a purpose in its conventions.

A new directory or a file move is useful when it expresses a real change in responsibility. That reason becomes part of the change description and architecture documentation. An existing directory alone does not explain which behavior belongs there.

## Architecture changes

Project architecture documentation describes the system's current structure. An ADR can preserve a decision's history: its context, the options considered, and the reasons for the choice. The [documentation policy](./documentation-policy.md) explains these document roles in more detail.

Moving code is justified when it clarifies responsibility or corrects a mismatch with the project's current structure. A shorter import or directory symmetry can be convenient, but the code's role explains the main reason for the change.

Small, sequential changes allow moves, renaming, and behavioral changes to be assessed separately. Observable application properties, external operation order, and public interfaces are preserved unless the task explicitly changes them. The [change policy](./change-policy.md) describes this approach in more detail.

Significant interfaces include exported module APIs, component properties and handlers, URLs, HTTP statuses, storage formats, Worker messages, environment variables and startup commands. The process for changing them is described in [Contract sources](#источники-контрактов).

Several questions help assess a decision:

- What task does this code perform, and who owns it?
- Where does the state live, and how long does it live?
- Which dependencies does this work need?
- What will change if an external system or UI framework is replaced?
- Which observable properties confirm the result?


---

# Code Vitality Policy

> Type: Policy. How to classify code during refactoring audit, deletion audit and cleanup pass.

## Purpose

An audit helps find code that has lost its role in the working application and determine what can be removed or moved to the roadmap. The evidence comes from verifiable connections to startup, a supported API, configuration, or an adopted project policy. Compilation, exports, and tests alone do not show how code is used.

The sections below describe how to trace those connections and classify findings for a decision. Implementations used only by tests are considered separately; future ideas can remain on the roadmap rather than as placeholders in `src`.

An ADR explains a decision’s origin. When code is retained for a current requirement without an active consumer, that requirement remains in a current policy or contract.

## Production graph and test graph

### Production Graph

Production graph starts from runtime entrypoints and project work connections:

- `package.json` `main`, `bin`, `exports` and runtime scripts;
- `src/index.ts`;
- bootstrap and command registry;
- CLI command handlers;
- application use-cases, pipelines, services and ports, which are actually connected to the runtime flow;
- infrastructure adapters, transport, persistence and runtime configuration;
- dynamic runtime bindings, if supported by code or configuration.

Code reachable from the production graph cannot be deleted as dead code.

For a UI project, the framework's routes and loaders, HTML entrypoints, Workers, `new URL(..., import.meta.url)`, CSS/static assets and browser bindings are also taken into account. The supported developer showcase and build graph are considered separately. A file cannot be considered unused just because a regular import is missing.

### Test Graph

Test graph starts from `*.test.ts` and test runner.

Tests confirm that the code has testable behavior. Tests do not prove that the code is used by the application at runtime.

Use by tests alone is considered separately; see [Test-only Implementation](#test-only-implementation).

## Categories

| Category | Distinguishing features |
| --- | --- |
| [Active Runtime Code](#active-runtime-code) | The code has a confirmed path from the production graph. |
| [Unused File](#unused-file) | The file has no incoming links. |
| [Placeholder](#placeholder) | The file contains only a TODO, a comment, or an empty architectural template. |
| [Test-only Implementation](#test-only-implementation) | The real implementation is used only by tests. |
| [Barrel-only Export](#barrel-only-export) | The code is exported via `index.ts` or another barrel, but is not used by production code. |
| [Orphaned Island](#orphaned-island) | A group of files uses each other, but the entire group does not have an incoming production reference. |
| [Roadmap Code](#roadmap-code) | The code expresses a future intent but has no current consumer. |

### Active Runtime Code

Other reasons to retain code, such as its role in builds or a supported API, are listed under [Keep](#keep).

Decision: `keep`.

### Unused File

Signs:

- no imports;
- no barrel exports;
- no test references;
- no docs references;
- no package script / entrypoint references;
- no dynamic string references;
- file is not a declaration/config/entrypoint file.

Solution: `delete candidate` if there is no architectural intent or public contract.

### Placeholder

Signs:

- no executable code;
- no meaningful exports;
- no production usage;
- text describes a future idea, not a current implementation.

Solution: `move to roadmap` or `delete candidate`.

### Test-only Implementation

Signs:

- is executable code;
- is tests; The
- no production imports;
- no CLI/use-case/bootstrap/runtime usage.

Solution: `needs owner decision`.

Such code cannot be removed mechanically: first you need to understand whether it is an outdated implementation, a lost runtime flow, or a deliberately saved contract.

### Barrel-only Export

Signs:

- is `export * from ...` or named re-export;
- symbols are not imported by active runtime code;
- tests may or may not exist;
- package public API not confirmed by `package.json`.

Solution: `needs owner decision`.

Barrel export in itself does not prove the viability of the code.

### Orphaned Island

Signs:

- module appears to be in use because another file imports it;
- this other file is not itself reachable from the production graph;
- island can have tests and internal utilities;
- deleting one file requires considering the entire group.

Solution: `needs owner decision` or a separate small deletion pass after confirmation of the owner.

An internal dependency within an island does not make the island active.

### Roadmap Code

Examples include a planned port, strategy, service, adapter or design example that is not used by the running application. An empty interface, stub or TODO-only implementation also has the characteristics of a [Placeholder](#placeholder).

Decision: `move to roadmap`.

## Solutions

| Decision | When it applies |
| --- | --- |
| [Keep](#keep) | The code is used or needed for builds, types, configuration, a supported API, or a current policy or contract. |
| [Delete Candidate](#delete-candidate) | The code is unused and meets all the conditions listed below for consideration for deletion. |
| [Move To Roadmap](#move-to-roadmap) | Record a future capability with no current consumer in documentation, an issue or a plan when its intent is better expressed as a description than a source-code placeholder. |
| [Needs Owner Decision](#needs-owner-decision) | The owner’s decision is needed when the use or purpose of code remains unclear. |

### Keep

Used if code:

- reachable from production graph;
- is needed by assembly, types, declarations or runtime config;
- is package entrypoint;
- is supported as public/internal API;
- has a valid documented contract;
- is required by a valid policy or contract, even if it temporarily does not have a consumer feature.

### Delete Candidate

Used if code:

- does not have production usage;
- does not have a public/internal API role;
- does not need a test harness as a conscious contract;
- is not declaration/config/entrypoint;
- does not contain important architectural intent.

Removal is performed only by small batches.

### Move To Roadmap

This decision applies to [Placeholder](#placeholder) and [Roadmap Code](#roadmap-code).

### Needs Owner Decision

Cases requiring an owner decision are described under [Test-only Implementation](#test-only-implementation), [Barrel-only Export](#barrel-only-export) and [Orphaned Island](#orphaned-island). Architecturally significant code without a confirmed path from the production graph also needs separate consideration.

Such code must not be deleted during automatic cleanup.

## Audit checklist

Before deletion pass you need to check:

- imports by file name;
- imports by exported symbols;
- barrel exports;
- test references;
- docs references;
- package `main`, `bin`, `exports` and scripts;
- tsconfig include/exclude;
- CLI command registry;
- bootstrap wiring;
- infrastructure bindings;
- runtime config;
- dynamic string references;
- applicable current policies and contracts;
- related ADR as rationale and history of owner decision;
- whether the file is part of orphaned island.

## Minimum Removal Rule

Deletion is limited to the files listed in advance and follows the [change policy](./change-policy.md).

Prerequisites:

- do not update dependencies;
- do not delete owner-decision candidates without confirmation;
- do not delete infrastructure baseline assigned by current architecture policy or contract; if the replacement passes the ADR admission gate, first accept the new ADR;
- run build, tests, lint and diff checks;
- show diff summary.

If there is any doubt about the file, it remains in `needs owner decision`.


---

# Comment Policy

> Type: Policy. How to write comments in production code.

## Purpose

A comment helps a colleague understand a decision whose reasons are difficult to recover from code alone. Module purpose, important constraints, and invariants provide useful context. Clear names and code structure already explain ordinary mechanics; the comment adds what is needed for maintenance.

## Basic rules

1. An optional local comment explains a decision, invariant or constraint that is hard to recover from code alone. It adds context rather than repeating obvious actions.

2. Keep comment style and language consistent within a file. Write natural-language text in Russian. API, type and protocol names and established technical terms may remain in English when translation would reduce precision.

3. A comment does not extend the code’s contract. Guarantees, invariants, execution order, safety and constraints must be supported by code, types or tests.

4. Refactoring history belongs in Git, ADRs and design notes. Comments describe the current reason for the current decision.

## Upper architectural block

Each production module that participates in runtime, defines a layer contract or has a nontrivial responsibility must have one top-level architectural comment, subject to the exceptions below. It describes the module as a whole: the file’s role, allowed responsibility, boundaries and responsibilities that belong elsewhere.

Template:

> The module's role in the system is [file role].
>
> That role covers [responsibility 1], [responsibility 2], and [responsibility 3].
>
> [Responsibility outside this scope] belongs to another module.

Good example:

> The application use-case module orchestrates one application scenario through ports.
>
> - Coordinates application services.
> - Calls ports and checks application invariants.
> - Builds the final response contract.
>
> CLI and HTTP details and direct SDK calls belong to other modules.

Bad example:

> File for network fit.

Such a comment does not explain the role of the module, its boundaries and acceptable responsibilities.

## Exceptions

Upper architectural block is optional for:

* `index.ts` / barrel export files;
* generated files;
* test fixtures;
* trivial files with one obvious type or constant;
* temporary local helper files that do not define a production contract;
* [trivial Svelte composition](./languages-and-platforms.md#компоненты) under the conditions described there.

## Functions and methods in utility modules

Every function and method in a module serving as a utility or tool must have a comment. This includes private and nested helpers, returned handlers, and object methods. The rule also applies to build tools and test helper modules. A module's role is determined by its purpose, rather than its filename or directory.

Place the comment before the declaration and describe the operation's purpose and any relevant constraints, side effects, or local state. A clear name does not remove this requirement. A module comment does not replace comments on individual operations; do not restate implementation lines.

## JSDoc public contracts

JSDoc for public functions, classes and interfaces must be concise and specific. It describes only contract details:

* input restrictions;
* side effects;
* errors;
* lifecycle;
* important guarantees;
* external API restrictions.

In other modules, JSDoc may be omitted if the meaning is completely clear from the name, types, and code.

Bad:

> `getCandles()` returns candles.

Better:

> `getCandles()` returns normalized candles for the application layer. External provider errors propagate to the calling scenario.

## When a comment is needed

A comment is needed if it explains:

* module role;
* layer boundary;
* is a non-obvious invariant;
* workaround;
* external API limitation;
* the reason for the unusual branch;
* reason for cleanup logic;
* maintaining compatibility with the old contract;
* intentionally empty branch if the lack of action is part of the logic;
* placeholder / TODO with an explanation of why there is no implementation yet;
* the reason why the dependency is allowed here.

Good:

> The external runtime starts only when processing the first range with enough data.

```ts
session ??= await this.trainer.start(request.training);
```

Good:

> An empty batch counts as a successful use-case result because the caller already applied its filters.

```ts
if (ranges.length === 0) {
  return emptyResult();
}
```

Good:

> The output includes the legacy profile field expected by the CLI caller. Within the pipeline, the profile has already been selected through `mlProfile`.

```ts
response.featureProfile = profile.featureProfile.name;
```

## When a comment is not needed

No additional comment is needed if:

* the meaning is already clear from the function name, type and code;
* comment repeats the line literally;
* comment describes trivial mechanics;
* comment explains the syntax of the language;
* comment becomes outdated faster than the code itself;

Bad:

> Start trainer

```ts
session = await this.trainer.start(request.training);
```

Bad:

> Check if ranges is empty

```ts
if (ranges.length === 0) {
  return emptyResult();
}
```

Bad:

> Increment counter

```ts
count++;
```

Remove an optional comment if it can be deleted without losing meaning.

## TODO and placeholder

TODO is valid only if it explains:

* why the implementation was postponed;
* what restriction is currently in effect;
* Under what condition should you return to this place.

Good:

> TODO. Move target normalization to the ML profile when a second target profile is added. Production profiles currently share one target contract.

Bad:

> TODO: fix later

If a module or branch is intentionally empty, this must be indicated explicitly.

Good:

> The module is reserved for an application hook for post-training diagnostics. Diagnostics are CLI-only until the application response stabilizes. Writing to stdout and handling CLI flags belong to the CLI.

## Workaround-comments

Workaround should explain the external constraint, not just describe a workaround.

Good:

> PyTorch BCE with AMP can produce unstable values in mixed precision. Training on probability targets uses the logits contract.

```ts
loss = binaryCrossEntropyWithLogits(predictedLogits, targetProbability);
```

Bad:

> Use BCEWithLogits

```ts
loss = binaryCrossEntropyWithLogits(predictedLogits, targetProbability);
```

## Comments and architectural boundaries

A comment is useful when it protects the boundary of a layer.

Good:

> The infrastructure adapter maps data from an external market data SDK to an application-level port.
>
> - Calls T-Invest SDK.
> - Converts SDK DTOs into domain/application DTOs.
> - Normalizes external provider errors.
>
> Feature engineering, ML profile selection, and use-case orchestration belong to other modules.

This block helps not to mix adapter, domain logic and application use-case.

## Comments and tests

Comments do not replace tests.

If a comment captures an important invariant, it is desirable that it be protected by a test.

For example, if a comment says that the order features is a production contract, this should be checked by the registry/profile test.

> Indicator order is part of the feature matrix's production contract. The Python model receives a positional matrix without column names.

```ts
const indicators = [
  'CloseLocationValue',
  'SignedStreak',
  'VolRatio',
];
```

## Application practice

1. Write clear code first.
2. Then add required comments; add other comments only where their absence would hide the reason for a decision.
3. When reviewing, remove noisy comments as confidently as dead code.
4. After refactoring, check comments for relevance.
5. Do not use a comment to excuse a poor name or an unclear module responsibility.


---

# Test comment policy

> Type: Policy. Rules for comments in tests; complement [testing policy](./testing-policy.md).

## Contents

- [Purpose](#назначение)
- [General rule](#общее-правило)
- [When a comment is needed in a test](#когда-комментарий-в-тесте-нужен)
- [When a comment is not needed in the test](#когда-комментарий-в-тесте-не-нужен)
- [Test script block](#блок-тестового-сценария)
- [Comment inside the test](#комментарий-внутри-теста)
- [Regression-comments](#regression-комментарии)
- [Comments on expected value](#комментарии-к-expected-value)
- [Comments on test fixtures](#комментарии-к-test-fixtures)
- [Comments on mock/stub/fake](#комментарии-к-mockstubfake)
- [Comments to snapshot / golden tests](#комментарии-к-snapshot--golden-tests)
- [Given / When / Then blocks](#блоки-given--when--then)
- [Comments on intentional omissions](#комментарии-к-intentional-omissions)
- [Comments and test names](#комментарии-и-имена-тестов)
- [Commentary language](#язык-комментариев)
- [Prohibited comments](#запрещенные-комментарии)

## Purpose

A test comment helps explain a risk, the behavior being checked, or an unusual setup. This is especially useful for a regression: the next reader can understand which property the check protects. The test name and actions already show the ordinary scenario; the explanation adds important context.

## General rule

Start with clear names for `describe()` and `test()`. If a better test name can replace a comment, improve the name. A comment adds important context that the name and test actions do not explain; these cases are listed below.

## When a comment is needed in a test

A comment is needed if it explains:

* a risk to the running application or one of its invariants;
* regression case;
* is a historically fragile place;
* non-obvious data preparation;
* the reason for the strange expected value;
* external API limitation;
* difference between mock/stub and real behavior;
* why exactly this behavior is checked;
* why the test does not intentionally check for adjacent liability;
* which contract captures snapshot or golden output.

## When a comment is not needed in the test

Comments that repeat code, language syntax or the test name are not allowed. An explanation is also unnecessary when the expected value and purpose of the check are clear from the input, test name and assertion. Labeling obvious preparation, execution and verification steps merely repeats the code’s structure.

Bad:

> Arrange · Act · Assert

```ts
test('returns empty result for empty ranges', () => {
  const ranges = [];

  const result = buildResult(ranges);

  assert.deepEqual(result, []);
});
```

Better:

```ts
test('returns empty result for empty ranges', () => {
  const result = buildResult([]);

  assert.deepEqual(result, []);
});
```

## Test script block

If a group of tests protects an important production contract, a separate script block is allowed before it.

Template:

> The scenario describes [behavior under test].
>
> - First protected invariant — [invariant 1].
> - Second protected invariant — [invariant 2].
>
> [Adjacent responsibility] has its own tests.

Good:

> This scenario checks explicit completion of writes through `BufferedTextFileWriter`.
>
> - Buffered chunks are flushed before the stream closes.
> - The last line is preserved.
> - Calling `close()` again is safe.
>
> File-system permissions and the behavior of Node.js streams are tested separately.

- `BufferedTextFileWriter`
  - `#close`

Bad:

> BufferedTextFileWriter tests.

- `BufferedTextFileWriter`

This comment does not add any meaning: subject is already visible from the name `describe()`.

## Comment inside the test

A local test comment is needed when the reason for preparing data, choosing an expected result or making an unusual check would otherwise be unclear. Place it next to what it explains. After refactoring, remove it if the meaning has become clear from the code. Do not add a comment to every assertion automatically.

Good:

> The last line deliberately omits `\n`. It was previously lost when the stream closed without an explicit flush.

```ts
test('flushes last line when file is closed without trailing newline', async () => {
  await writer.writeLine('last');

  await writer.close();

  assert.equal(await readFile(path, 'utf8'), 'last');
});
```

Bad:

> Write line · Close writer · Check result

```ts
test('writes line and closes file', async () => {
  await writer.writeLine('last');

  await writer.close();

  assert.equal(await readFile(path, 'utf8'), 'last');
});
```

## Regression-comments

Regression comment is needed if without it it is not clear why the test captures exactly this scenario.

Good:

> An empty frame list contains no training data. Starting Python in this case wastes time on an external process.

```ts
test('does not start trainer when frame list is empty', async () => {
  const result = await useCase.execute(emptyRequest);

  assert.equal(result.predictedRows, 0);
  assert.equal(trainer.started, false);
});
```

Bad:

> Bugfix test

```ts
test('does not start trainer when frame list is empty', async () => {
  const result = await useCase.execute(emptyRequest);

  assert.equal(result.predictedRows, 0);
  assert.equal(trainer.started, false);
});
```

Regression comment should explain the production risk, and not refer to the fact of the existence of an old bugfix.

## Comments on expected value

A comment to expected value is needed if the value looks like a magic number, but is actually part of the contract.

Good:

> The expected row count of `51` follows from the warmup rules. With `lookback` set to 60 and `seqLen` set to 10, the first complete sequence appears after warmup.

```ts
test('creates rows only after sequence warmup is complete', () => {
  const rows = buildRows({ lookback: 60, seqLen: 10 });

  assert.equal(rows.length, 51);
});
```

Bad:

> Check rows length

```ts
test('creates rows only after sequence warmup is complete', () => {
  const rows = buildRows({ lookback: 60, seqLen: 10 });

  assert.equal(rows.length, 51);
});
```

If the expected value is obvious from the input data, no comment is needed.

## Comments on test fixtures

Fixture comment is needed if the test data looks strange, but was chosen intentionally.

Good:

> Zero volume is deliberate. Some historical candles arrive without trades, and price features still need to be computed from OHLC.

```ts
const candle = {
  open: 100,
  high: 101,
  low: 99,
  close: 100.5,
  volume: 0,
};
```

Bad:

> Test candle

```ts
const candle = {
  open: 100,
  high: 101,
  low: 99,
  close: 100.5,
  volume: 0,
};
```

The comment should explain the reason for the fixture, not its type.

## Comments on mock/stub/fake

Mock, stub or fake should only be commented if its behavior is intentionally different from real behavior and it is important to the boundaries of the test.

Good:

> The stub models an external provider error so the test can check its mapping in the application layer. Provider retries belong to a separate scenario.

```ts
const marketData = new FailingMarketDataStub();
```

Bad:

> Create mock

```ts
const marketData = new FailingMarketDataStub();
```

If fake is completely obvious from the class name and setup, no comment is needed.

## Comments to snapshot / golden tests

Snapshot or golden test should explain which contract is being recorded.

Good:

> The golden output pins the CLI response format. Shell scripts read `stdout`, so changing the order of fields is an explicit breaking change.

```ts
test('prints stable CLI summary', () => {
  const output = renderNetworkTestSummary(result);

  assert.equal(output, expectedOutput);
});
```

Bad:

> Compare output

```ts
test('prints stable CLI summary', () => {
  const output = renderNetworkTestSummary(result);

  assert.equal(output, expectedOutput);
});
```

Golden test without contract reason often fixes random formatting and complicates refactoring.

## Given / When / Then blocks

Comments `Given`, `When`, `Then` are only valid in long tests where they actually improve readability.

They are not a required style and should not appear in short tests.

Acceptable:

> Given. Python receives a positional matrix without column names, making indicator order part of the production contract.

```ts
test('preserves feature order from profile registry', () => {
  const profile = getMarketFeatureProfile('default');

  const names = profile.indicators.map(getIndicatorName);

  assert.deepEqual(names, [
    'CloseLocationValue',
    'SignedStreak',
    'VolRatio',
  ]);
});
```

Not necessary:

> Given · When · Then

```ts
test('returns true for valid FIGI', () => {
  const figi = 'BBG004730N88';

  const result = isFigi(figi);

  assert.equal(result, true);
});
```

For short tests, the structure should be obvious from the code itself.

## Comments on intentional omissions

If the test intentionally does not check adjacent responsibility, this can be indicated by a comment at the scenario level or next to the setup.

Good:

> This scenario checks normalization of network fit arguments.
>
> - Mapping `argv` to an application request.
> - Default runtime options.
>
> Use-case execution, the Python trainer, and file-system side effects have separate tests.

- `parseNetworkFitArgs`

Bad:

> Test the CLI.

- `parseNetworkFitArgs`

Intentional omission is useful where the test boundary may be incorrectly extended by future changes.

## Comments and test names

The comment should not compensate for a bad test name.

Bad:

> Check that the trainer stays idle when all ranges are skipped during warmup.

- `works correctly`

Good:

> The Python runtime starts lazily. The application layer calls it when training data is available.

- `does not start trainer when all ranges are skipped by warmup`

Even better if the comment is not needed:

```ts
test('does not start trainer when all ranges are skipped by warmup', async () => {
  const result = await useCase.execute(requestWithOnlySkippedRanges);

  assert.equal(result.predictedRows, 0);
  assert.equal(trainer.started, false);
});
```

## Commentary language

The natural text of comments in tests must be written in Russian, just like the production comments of the project.

It is acceptable to use technical English terms if they are part of a sustainable vocabulary project:

* regression;
* fixture;
* mock;
* stub;
* fake;
* snapshot;
* golden output;
* runtime;
* contract;
* mapping;
* fallback.

There is no need to artificially translate such terms if the translation makes the comment less accurate.

## Prohibited comments

Comments that:

* describe the temporary history of change without production meaning;
* contain TODO without reference to issue, decision or owner decision;
* justify fragile test instead of fixing test structure;
* mask too large test case.

Bad:

> TODO: improve test later

Bad:

> This test is complicated because the code is complicated

If a test requires such a comment, you first need to simplify the test setup or split the test case.


---

# Code Style Policy

> Type: Policy. Rules for the visual structure of production and test code.

## Purpose

Formatting makes the flow of a method and its separate steps visible, helping readers and reviewers focus on behavior. These conventions apply to production and test code; a more specific file contract remains in effect. The scope of an edit follows the [change policy](./change-policy.md).

## Vertical padding

Independent logical steps within a method are separated by one blank line.

A multiline call, object creation, or state declaration forms a visual block. Such a block is followed by an empty line if the next instruction begins another operation rather than continuing the current one.

In production code, separate blocks can be when they are truly separated by meaning:

* receiving or preparing state;
* validation;
* data conversion;
* external call;
* result processing;
* return value.

This list does not specify a mandatory order and does not require artificially creating all phases in each method. Logical grouping is more important than the mechanical rule “empty line after every `);`”.

When a check and its immediate action form one operation, they stay in the same visual block.

## Exceptions

Should not be mechanically changed:

* generated code;
* contents of SQL and string literals;
* fields type/interface/object literals;
* a combination of verification and immediate action;
* short related announcements of one preparatory step.

## Making changes

Bringing existing code to this rule is done in separate style-only commits. In such a change, only empty lines are allowed: you cannot change hyphens, statement order, names, behavior, or refactor at the same time.

Splitting a calculation into variables, extracting a function, and changing branching are refactorings. They are not included in tasks limited to whitespace and line breaks. Preserve evaluation order, short-circuit behavior, and reactive dependencies.

Statement formatting, types, markup, and styles are covered in [Languages and platforms](./languages-and-platforms.md).

## Logical steps in expressions

One statement represents one logical step. Do not combine finding data, accessing the search result, extracting a value, and checking its presence in one expression.

Separate these operations into sequential statements with meaningful names for intermediate variables. Check a result before using it. Preserve existing data guarantees, evaluation order, short-circuit behavior, missing-value behavior, and reactive dependencies.

Multiple calls are acceptable when they express one obvious logical step. Do not split code mechanically by the number of calls. Line length helps formatting but does not make an expression readable by itself.

## Independent operations in methods

A method shows the main flow and the structure of its result. If the details of several independent operations obscure that flow, extract them into meaningfully named functions. Intermediate calculations and variables needed by only one operation stay inside it.

The extraction boundary is a complete task, such as calculating navigation or building a list of links. Do not extract every expression to shorten a method or create chains of trivial helpers. Local decomposition does not itself require a new module or layer.

## Tests

Arrange, Act and Assert are separated by empty lines if they are truly different phases. Related assertions of the same result remain one block.

## Git commit messages

Format: `<type>(<scope>): <short action>`. Scope is indicated when it helps to understand a change.

Valid types:

| Type | When to use it |
| --- | --- |
| `feat` | Adding a new capability |
| `fix` | Fixing a bug |
| `refactor` | Changing code structure without changing its behavior |
| `docs` | Updating documentation |
| `test` | Adding or updating tests |
| `chore` | Project maintenance, such as updating tools or dependencies |

The message is written in English. The description begins with a lowercase letter, uses the imperative form, and does not end with a period or exclamation point. One commit contains one logical change; The message does not list files, tests, hashes, or minor details.


---

# Naming Policy

> Type: Policy. How to name entities in code and runtime.

## Contents

- [Target](#цель)
- [Name notation](#нотация-имени)
- [External and published names](#внешние-и-опубликованные-имена)
- [Runtime names](#runtime-names)
- [Prohibition of renaming without a task](#запрет-переименований-без-задачи)
- [Check](#проверка)

## Target

A name helps explain an entity’s role before its implementation is read. Consistent names make searching and moving between modules easier, while familiar notation indicates whether something is a type, a function, or an operational scenario name.

The examples below illustrate conventions using particular entities. Domain concepts and actual names follow the project’s context; published external contracts retain their existing identifiers.

## Name notation

Identifiers and files follow the notation of their language and framework. JavaScript, TypeScript, and Svelte conventions are collected in [Languages and platforms](./languages-and-platforms.md#именование-в-javascript-и-typescript).

## External and published names

Published public APIs, compatibility aliases, generated declarations, and framework-prescribed names are preserved verbatim. Changing their notation is not an ordinary rename.

The names of URL and storage keys, serialized fields and Worker messages are compatibility-sensitive and do not change like a regular cleanup. The stable terms of the project are preserved in the code and documentation.

## Runtime names

Names of runtime scenarios, profiles, and commands are distinct from code identifiers.

For these, it is preferable to use `kebab-case`.

Acceptable:

```ts
const profileName = 'mean-return-l5-prenorm';
const commandName = 'print-predictions';
const optionName = '--target-diagnostics';
```

It is prohibited to use `ALL_CAPS` runtime-name without external need:

```ts
const profileName = 'PRODUCTION_CORE_V2';
```

## Prohibition of renaming without a task

The scope of a rename follows the [change policy](./change-policy.md). Naming rules alone do not authorize bulk renames.

Renaming is allowed only if:

* it is directly required by the task;
* it corrects a violation of this policy;
* minimal modification required;
* program behavior does not change.

When a rename is needed, check imports, exports, tests, docs, CSS selectors, storage/URL keys and dynamic references.

## Check

Violations of this policy should be blocked at the review level.


---

# Script and build policy

> Type: Policy. When can you change scripts, build and test pipeline.

Changing a startup command can affect operation order, output files, and reproducibility. Work on scripts therefore starts with the task: which command behavior changes, and why the existing process is insufficient. Existing commands are preserved when the task only concerns the code they call.

Prohibited:

- add file deletion, including cleanup of build output before builds or tests, through a separate command or a call from code
- change the order of commands
- add &&

Node.js and npm conventions and examples are collected in [Languages and platforms](./languages-and-platforms.md#скрипты-npm).

If, after moving the files to `dist`, stale artifacts remain, remove them point by point in a separate operation. Don't change the project's permanent build/test pipeline for this.

Deleting files is allowed only if the task is explicitly specified.

## Additional examples

Acceptable:

- add a new script only if the task directly requires a new entrypoint
- change the implementation of the called file without changing the launch script itself, if the task is about the behavior of this file

## Good practices

- consider scripts as part of the project contract, and not as a service detail
- before changing the script, check if the order of steps, side effects and entry points has changed

## Configuration and verification

Compiler, bundler, framework and test config are part of the build/runtime wiring. A change to alias, adapter, SSR, include pattern, test environment or assertion requirements is considered a change to the contract. This change should not suppress an application defect or environmental problem.

Generated output is not edited manually and does not serve as confirmation of the operation of the new source. Build-time and runtime variables retain the owners described in the project's configuration and documentation. Secrets do not go into package scripts, public variables, or examples with real values.

Each affected command is checked separately: exit status, side effects, output artifacts and compatibility of local and production workflow. A failed command is indicated explicitly in the report.


---

# Documentation Policy

> Type: Policy. How to help readers complete a task and find current project information.

## Purpose

A reader opens a document to do something, understand a decision, or look up precise information. The page's purpose helps determine its content, the order of explanation, and the right level of detail.

## The reader and their task

The text takes account of the reader's knowledge and the context they bring. Each explanation helps them act, make a decision, or understand a significant project detail. Information already familiar to that audience and ordinary tool capabilities are useful where they actually affect the reader's decision.

A practical guide starts with a task and leads to a result. For example, installation commands can be introduced by explaining how to add the library to a project. Imperatives such as “use” and “run” are natural when the reader understands the goal and context of the action.

Compatibility conditions, exact versions, and limitations retain their precision. A guide presents them before the step they affect; detailed reference material can be linked. Several version ranges are easier to find in an environment reference than to decipher in the introduction to getting started.

A policy explains a principle, the reasons for choosing it, and its application in different circumstances. A reference helps readers quickly find a particular value or contract. Choosing the form this way provides the help the reader came for.

Questions that help review the text:

- Who will read this section, and what do they already know?
- What does the reader want to understand or do here?
- Which decision or action does this paragraph help with?
- Where are details needed immediately, and where is a link enough?

## Contract sources

Documentation helps readers find a current contract and explains how to work with it. The exact interface remains in code, a schema, or another verifiable project source. Linking to that source allows details to be checked and updated in one place.

Permanent reference pages explain meaning, scenarios, and limitations. A complete copy of commands, arguments, or schemas would need separate maintenance and could drift from the working interface.

## Document roles

A document's primary role helps readers understand which answer the page provides.

| Type | Answers the question | Character |
| --- | --- | --- |
| `Navigation` | Where can I find the material I need? | Pointers to relevant documents without a separate system contract |
| `Contract` | What interface or obligation currently applies? | Current binding contract |
| `Policy` | Which principles guide our work, and why? | Working principles and guidance on their application |
| `Reference` | What interface or behavior currently applies? | Current reference with a link to a verifiable source |
| `Overview` | How are the main parts of the system connected? | Overview of the current structure |
| `Design Note` | How does a particular part of the system work, and why? | Explanation of an existing design without a new obligation |
| `Experiment Record` | What was observed in a particular run? | Dated historical record stating the completeness of evidence; new results are added separately |
| `Operational Guide` | How do I complete an operational task? | Steps for the current system |
| `Deployment` | How do I install or initially deploy the application? | Deployment instructions |
| `ADR` | Why was this decision chosen at that time? | Historical decision record |
| `Roadmap` | Which accepted change has been deferred? | Plan for future work |

A document's type describes its purpose, while its status describes how current it is. A historical design note retains its type, snapshot date, and explicit completion or replacement status. An open discussion remains a proposal until a decision is made.

Navigation pages lead to current guides and references; historical material is listed separately. A current document starts with its role and primary information source when that source is in another file. A historical document retains its date, status, original problem, and results.

## Architecture Decision Records

An ADR (Architecture Decision Record) is a document that records an architectural decision and explains why it was chosen. It preserves the context, options considered, decision, and consequences as of the decision date. It helps recover the reasons for a choice later. Current system structure and working instructions are described in separate current documents; the ADR links to them.

An architectural decision is recorded in an ADR when at least one of these circumstances applies:

- several realistic options were considered;
- reversing the decision would be difficult or expensive;
- it affects several components;
- the choice establishes a long-term architectural constraint;
- the reasons would be difficult to recover from code alone six months later.

Descriptions of an existing component, API, settings, or directory structure usually belong in a reference or overview. A useful way to identify the decision itself is to remove the choice's context, alternatives, and reasons: the remaining system description may form a separate current document.

After the status `Принято`, the substantive content of an ADR is preserved as a historical record. Later edits are limited to typos without semantic changes, link repairs, status changes, and a link to a replacement ADR. Revising an accepted decision creates a new record; the previous one receives the status `Заменено ADR-NNNN`.

An ADR uses a four-digit sequential number and an immutable filename. Its contents include title, status, date, context, decision, realistic alternatives, consequences, and links to current documentation.

Statuses describe the decision's state:

| Status | Meaning |
| --- | --- |
| `Предложено` | The decision is being discussed |
| `Принято` | The decision has been accepted |
| `Заменено ADR-NNNN` | A newer record replaces it |
| `Отклонено` | The option was considered and rejected |

## Application command help

To find the current commands and parameters of an application with a CLI, readers can use its built-in help. For example, in an npm project with the entry point `cli`:

- general help: `npm run cli -- --help`;
- command help: `npm run cli -- <command> --help`.

Command, argument, and help text definitions live in the CLI code. Project documentation points to that source and describes workflows: where to get help, how the relevant process works, and which documents provide further explanation.

## When CLI changes

A change to a command, argument, help text, lifecycle option, or public behavior affects several related representations:

- the CLI contract and definitions in code;
- user-facing help generation;
- command parsing and help tests;
- the README summary when commands or startup usage change;
- contract source links and navigation when the information moves.

Updating them within one task keeps the working interface and documentation consistent.

## When a separate Markdown document helps

A separate page, such as `docs/cli.md`, helps when the reader has a task of their own: understanding part of the system, completing a workflow or learning how to operate it. A link to CLI help supplies the exact parameters. If all the material is already in the built-in help, linking to it gives readers current information without maintaining another copy.


---

# Metrics Policy

> Type: Policy. Boundaries of observability metrics and instrumentation.

## Purpose

Metrics help explain a running application’s condition: for example, where latency is growing or how often an error occurs. Measurements are chosen to answer a concrete operational question. A small, stable set is usually easier to use and maintain.

Application state, storage and synchronization remain the responsibilities of the corresponding project mechanisms.

## Metric Design

- Use only limited and predictable sets of measurement values.
- Do not use `requestId`, tool IDs, timestamps, error texts, stack trace and other high cardinal values ​​as measurements unless explicitly necessary.
- Do not record secrets, tokens, credentials, or sensitive data in metrics.
- Do not duplicate information in metrics that is already fully presented in the logs.

## Instrumentation limits

- The specific metrics system code must remain within the existing metrics layer or infrastructure.
- Domain and the main application logic should not directly depend on the metrics system.
- You should instrument existing execution boundaries rather than rebuild the application for the sake of collecting metrics.
- Metric collection cannot be extended to unrelated components without first agreeing on the scope of the change.

## Reliability

Metrics are auxiliary observability data and are collected by best effort. Their collection should consume limited resources and not create unlimited queues, endless retry, memory growth, or significant delay to the main operation.

Metric collection and delivery remain independent of the main operation: an unavailable monitoring system must leave the business result, control flow and API behavior unchanged.

## Consistency between projects

Use consistent metric names, units and field semantics for the same operations and concepts across projects, including Node.js and Python projects. Also aim for compatible document structures.

You cannot change the overall metrics contract in just one project if this would lead to divergence of equivalent metrics between components.


---

# Abstraction Policy

> Type: Policy. How to recognize when shared code makes a project easier to work with.

A shared module is useful when it brings together a clear responsibility and simplifies its consumers. Repeated behavior, a complex independent operation, shared infrastructure work, or the need to verify a result independently can motivate extraction.

## Reuse and decomposition

When code is used in one place, keep it there; in two places, consider whether a shared module is useful; in many places, extract the repeated part into a shared module.

This guideline helps assess reuse. Decomposition within the original module addresses a different task: an independent operation with a clear responsibility can become a function even when called only once.

## Assessing an extraction

Matching lines do not necessarily mean matching behavior. Before extraction, it helps to understand which parts change for the same reason and which API would help their consumers. A clear module name and task make its value easier to assess.

Reusable code gets tests for the extracted behavior. These help preserve the shared contract as several consumers change.

## Examples

Repeated configuration parsing can be collected in one module, and filesystem operations in an adapter, when several consumers need them.

A wrapper around a standard call is useful when it expresses an additional responsibility. If it merely repeats the call, the code is usually easier to read at the point of use. A `utils.ts` file makes sense when its task and consumers are clear.

Combining two similar fragments can hide an important behavioral difference. Clearer consumers and preservation of that difference help identify a suitable form for shared code. Preparing an abstraction for possible future use alone does not demonstrate that value.


---

# Dependency Policy

> Type: Policy. How to choose a library for the current task and assess its maintenance.

## The library's task

Choosing a dependency starts with the task it solves in the project. A clear API, support, and documentation help assess how convenient the library and its integration will be to maintain.

Comparing it with the standard library and existing packages shows what the new dependency adds. If the operation is already one standard call, an extra wrapper usually adds more maintenance than value. A library with a distinct, lasting purpose can simplify several parts of an application.

## Maintenance cost

Alongside API convenience, the choice takes account of updates, compatibility, distribution size, and reliance on an external interface. These considerations help explain why a particular package is useful and why existing tools are insufficient.

Adding a dependency serves current needs. A small syntax difference or possible future use alone says little about its value to the project.

## Compatibility and reproducibility

Checks whether the runtime package is needed or only the development circuit, whether it is compatible with supported versions of the platform and whether it adds an extra browser bundle. For the UI, SSR, accessibility, and the ability to localize external APIs are taken into account. The facade is justified by the actual contract boundary rather than being created on a per-packet basis.

The selected package manager and supported platform versions are indicated in the project documentation. A dependency update is not mixed with a feature or visual edit if it is not needed for the current task. Major update requires checking the migration guide. Before updating, release notes, peer ranges and the actual dependency graph are studied.

After the change, the consistency of the manifest and lockfile, lint, types, affected tests, build and relevant runtime smoke are checked. Security audit is performed at the level accepted in the project.

Updating dependency files and using `overrides` in npm are covered in [npm dependencies](./languages-and-platforms.md#зависимости-npm).


---

# Testing Policy

> Type: Policy. Requirements for testability, structure and naming of tests.

## Contents

- [Purpose](#назначение)
- [Mandatory tests](#обязательность-тестов)
- [Which usually does not require a separate test](#что-обычно-не-требует-отдельного-теста)
- [Test requirements](#требования-к-тестам)
- [Insulation](#изоляция)
- [Current test circuit](#текущий-тестовый-контур)
- [Test data](#тестовые-данные)
- [Naming test case](#именование-test-case)
- [Preferred behavior verbs](#предпочтительные-behavior-verbs)
- [Public behavior instead of private implementation](#публичное-поведение-вместо-private-implementation)
- [Error cases and boundary cases](#error-cases-и-boundary-cases)
- [Regression tests](#regression-tests)
- [Current contract instead of project history](#актуальный-контракт-вместо-истории-проекта)
- [Comments in tests](#комментарии-в-тестах)
- [Communication with change policy](#связь-с-политикой-изменений)
- [Good practices](#хорошие-практики)

## Purpose

A test helps establish that a change preserves the required behavior and covers important boundary cases. The expected result relates to a contract relied on by users or other parts of the program. Describing the check this way keeps it useful when the internal implementation changes.

## Mandatory tests

All reusable code must have tests. This includes shared modules, boundaries between layers and processing of external data.

Tests cover:

* shared modules and reusable application services;
* reusable domain logic: calculations, condition checks, rules and data conversions;
* adapters and infrastructure code, including filesystem access and external services;
* parsing configuration, command-line arguments and environment variables;
* input validation and normalization, and mapping external errors to application errors;
* pipelines, as well as orchestration that contains branching or decisions about the next action;
* code paths with multiple valid or error scenarios;
* boundary cases that could silently corrupt data;
* scenarios that have already failed or have a high risk of regression.

## Which usually does not require a separate test

Usually there is no need to separate the following:

* one-time merging of calls inside bootstrap, if it is not reused;
* trivial passthrough without its own logic;
* simple argument passing without branching, normalization or contract mapping;
* private helper if its behavior is fully verifiable through the public API;
* framework boilerplate without its own project-specific logic.

The absence of a test is only acceptable if the code actually does not contain its own behavior. If branching, normalization, fallback, mapping errors or a non-standard edge case appear, the test becomes mandatory.

## Test requirements

Tests should be:

* isolated;
* deterministic; The
* readable;
* minimal, but sufficient;
* focused on one behavior;
* focused on the observable result, and not on internal implementation.

One test should check one behavior.

It is acceptable to have several assertions in one test if they describe the same contract. If assertions test different reasons for behavior change, they need to be separated into separate tests.

## Insulation

The test should minimize dependence on:

* of the real file system, if it is not filesystem behavior that is checked;
* network;
* current time;
* order of running tests;
* external processes;
* global mutable state;
* stale build artifacts.

If dependency on an external resource is the essence of a test, it must be clearly visible from the test name, suite or fixture.

## Current test circuit

Commands and boundaries of unit, integration and end-to-end checks are defined in the documentation and configuration of a specific project. Fast Loop does not use the network, external services, or other external infrastructure. It prohibits hidden conditionals `skip` that depend on environment variables or service availability.

A successful unit check does not confirm real integration or end-to-end behavior. The unavailability of the desired environment is reported explicitly and does not translate into a successful check.

## Test data

Test data should be minimal but sufficient for the scenario.

Synthetic test documents and fixtures should only use test-owned identities and explicitly created test dependencies. They must not import, read, or reference production configurations, configured defaults, and deployment-specific identities by name or path. If the parser or resolver being tested needs a catalog, loader, or other owner dependency, the test must pass its synthetic implementation explicitly. Changing operational configuration not related to a test should not break such a test.

An exception is allowed only for a separate conformance test, the subject of which is the production artifact itself. This dependency must be explicitly specified in the name of the test suite or test case; production artifact is read unchanged and is not used as a general fixture to test other behavior.

Arrange should be visible in the test itself. You should not transfer test data, setting up the environment or playing production orchestration into common `*.fixture.ts`, `test-utils` and similar modules. Such abstractions hide the essential conditions of the script, create implicit dependencies between test suites and begin to require testing themselves.

A local auxiliary construct is valid when it represents a stateful test double, controls the lifecycle of a temporary resource, or expresses a repeatable boundary structure that cannot be shortened without losing readability. Parameters that affect the behavior being tested must remain explicit within `test()`. One-time wrapper functions and factories with random values ​​or current times are not allowed.

There is no need to create a realistic dataset if one object with three fields is enough for testing.

Good:

```ts
test('returns false for invalid FIGI length', () => {
  assert.equal(isFigi('BBG004730N8'), false);
});
```

Bad:

```ts
test('validates instrument', () => {
  const instrument = {
    figi: 'BBG004730N8',
    ticker: 'SBER',
    name: 'Sberbank',
    currency: 'rub',
    exchange: 'MOEX',
    lot: 10,
  };

  assert.equal(isFigi(instrument.figi), false);
});
```

Extra fields hide the reason for the test and increase the cost of support.

Conventions for grouping tests with `describe()` are in [Languages and platforms](./languages-and-platforms.md#группировка-тестов).

## Naming test case

`test()` calls only expected behavior.

The test name must not repeat the subject or method name if they are already specified in `describe()`.

Good:

- `BufferedTextFileWriter`
  - `#close`
    - `flushes buffered chunks before closing stream`
    - `keeps repeated close safe`

Bad:

- `BufferedTextFileWriter`
  - `#close`
    - `BufferedTextFileWriter close flushes buffered chunks`

Repeating subject makes the name noisy and impairs the readability of test output.

If a test is hard to name, it likely checks too much or lacks a clear contract.

## Preferred behavior verbs

Preferred verbs for `test()`:

| Name opening | Behavior described |
| --- | --- |
| `returns ...` | The returned result |
| `throws ...` | An exception thrown during an operation |
| `rejects ...` | An asynchronous operation completing with an error |
| `parses ...` | Parsing input data |
| `formats ...` | Formatting the result |
| `writes ...` | Writing data |
| `reads ...` | Reading data |
| `keeps ...` | Keeping a state or property unchanged |
| `skips ...` | Skipping an action under specified conditions |
| `uses ...` | Selecting and using data or a dependency |
| `does not ...` | The absence of an action or unwanted effect |
| `handles ...` | Handling a particular case |
| `preserves ...` | Preserving data or a guaranteed property |
| `computes ...` | The result of a calculation |
| `maps ...` | Converting one data representation into another |
| `normalizes ...` | Bringing data into a consistent form |
| `ignores ...` | Ignoring data or an event under specified conditions |

Good:

- `returns empty result for empty ranges`
- `throws when FIGI has invalid format`
- `does not start trainer when all ranges are skipped by warmup`

Bad:

- `works correctly`
- `test invalid input`
- `should process data`

`should` is not technically prohibited, but the preferred style is a direct description of the observed behavior without an extra modal word.

## Public behavior instead of private implementation

Private implementation details should not normally have dedicated suite names.

Private details need to be tested through public behavior.

Good:

- `CandleRangePolicy`
  - `#split`
    - `keeps ranges within provider limit`

Bad:

- `CandleRangePolicy`
  - `#calculateInternalOffset`
    - `returns offset`

An exception is only allowed if the helper is a reusable export and itself becomes part of the module contract.

## Error cases and boundary cases

Reusable code must have tests not only for the happy path, but also for erroneous and boundary scenarios.

It is especially important to test:

* empty input;
* minimum acceptable input;
* maximum allowed input;
* invalid format;
* unsupported enum value;
* missing required field;
* duplicate input;
* out-of-order input;
* repeated call;
* idempotency;
* fallback behavior;
* error mapping;
* skipped branch.

Not every module is required to have all of these scripts. Only those that correspond to his responsibility are needed.

## Regression tests

Regression test is needed if the behavior has already broken or the risk of a repeat defect is high.

Regression test should fix the production contract, and not a specific old erroneous implementation.

Good:

- `does not start trainer when frame list is empty`

Bad:

- `fixes bug from yesterday`

The regression case context can be revealed with a comment if without it the reason for the test is not obvious.

## Current contract instead of project history

The test checks the current production contract and supported behavior. It should not depend on the sequence of changes through which the project arrived at its current state.

Prohibited:

* import timestamped migration classes and check intermediate versions of schema, order of historical SQL operations or `down()` in unit tests;
* build test fixture from the previous version of schema only for the sake of checking the migration path;
* check for the absence of a remote source file, contract file, export, alias, CLI path or environment variable;
* save the test after deleting the checked compatibility surface only as a negative assertion under the previous name.

If the current contract is closed, you need to check its positive form and the deviation of the neutral unknown input. The real historical name should not become part of the new test contract.

Removing a production path means deleting the fixtures and tests dedicated to it. Git history remains a source of information about past behavior.

## Comments in tests

The normative rules for commenting in tests are found only in [comment policy in tests](./test-comment-style.md).

## Communication with change policy

Work on tests follows the [change policy](./change-policy.md). A test for a local defect must not impose a new architecture.

Acceptable changes include:

* adding a minimal test for a new requirement;
* adding a regression test for the defect being fixed;
* renaming a test case when its current name obscures the behavior under test;
* improving a fixture locally when the test otherwise cannot express its scenario.

## Good practices

* do not use production credentials, real networks or mutable external state;
* prefer an explicit expected value over checking that execution did not fail.

## Asynchronous behavior and snapshots

The test expects a `Promise` to be tested. Instead of an arbitrary delay, a managed timer, `Promise`, or observable state is used. Modified clocks, listeners, spies, mocks and globals are cleared after the script.

If the application is protected from a late response, it checks that the old result does not overwrite the new state after a second action, reset or unmount. The check for the absence of a callback must take place at the time of its expected activation.

A snapshot is allowed for a stable output contract when targeted assertions express the intent less clearly.

Published deprecated props and aliases remain under contract as long as the project supports them. Their tests are not removed due to historical origin.

DOM, accessibility, responsive layout, and browser integration checks are covered in [Web interfaces](./languages-and-platforms.md#проверки-в-браузере).


---

# Languages and platforms

> Type: Policy. Conventions for languages, runtimes, and frameworks.

Technology-specific conventions complement the [shared development policies](./index.md). Choose the sections relevant to your project: JavaScript and TypeScript, Node.js, Svelte, SvelteKit, web interfaces, or Python. Platform versions, startup commands, and application structure are described in the project’s own documentation.

- [JavaScript and TypeScript](#javascript-и-typescript)
- [Naming in JavaScript and TypeScript](#именование-в-javascript-и-typescript)
- [Grouping tests](#группировка-тестов)
- [Node.js](#nodejs)
- [Svelte 5](#svelte-5)
- [SvelteKit](#sveltekit)
- [Web interfaces](#веб-интерфейсы)
- [Python](#python)

## JavaScript and TypeScript

### Formatting

Handwritten TypeScript/Svelte code uses two spaces, semicolons, and single quotes in TypeScript. Configuration, declaration and generated files retain their own existing format.

For TypeScript, JavaScript, `<script>` and tests, the width guideline is 100 characters, including indentation. Long URLs, paths, regular expressions and string literals are not broken down into calculations or concatenations for the sake of width.

An independent instruction is written on a separate line. Do not concatenate state declarations, side effects, or assertions across multiple `;`s on a line. Callback and lifecycle blocks are expanded when they contain multiple actions.

Choose braces according to context and readability. For independent data checks, error handling, and early returns, prefer an expanded form with the condition and action on separate lines. A short form without braces is acceptable for an obvious local action if it does not obscure branch boundaries. Expand multiline conditions and actions, nested branches, and chains with inconsistent formatting. Do not shorten a clear block for compactness or add braces mechanically to every condition.

`else` and `else if` start on the line after the closing brace of the preceding block, at the same indentation level.

`catch` starts on the line after the closing brace of its `try` block, at the same indentation level.

Nested `try/catch` statements within one function or at module scope are prohibited. Do not place an inner `try` in the outer statement's `try`, `catch`, or `finally` block. Extract an operation that needs its own error handling into a named function. Preserve exception boundaries, operation order, and resource cleanup.

Exceptions follow the [general justification rule](./index.md#обоснованные-исключения).

Whenever possible, keep a method or function signature on one line if the full signature fits within 100 characters, including indentation.

Long signatures, destructuring, objects, and calls are expanded so that each field or argument of a multiline list begins on a separate line. Short visual literals and arguments remain compact. Simple ternary expressions are allowed; complex choices should not be hidden inside a long expression.

### Types and data checks

- Prefer clear types on module boundary and inference within small implementation.
- Do not add decorative type aliases that only repeat the expression.
- Use `unknown` and narrowing for external input; don't replace checking unconditional cast.
- Guard clause is preferable to deep nesting if it does not hide the lifecycle.
- One class is defined in one file.
- Do not change the order of side effects for the sake of visual symmetry.

The `!` operator does not replace checking a result before using it.

### Naming in JavaScript and TypeScript

#### Basic naming rules

The following rules are used in TypeScript/JavaScript code:

* `camelCase` - variables, functions, values, exported const;
* `PascalCase` - classes, types, interfaces, enum;
* `kebab-case` — runtime names, CLI names, profile names, file names;
* `SCREAMING_SNAKE_CASE` / `ALL_CAPS` - prohibited for internal project identifiers.

Examples:

```ts
const maxRetryCount = 3;

const mlProfileCatalog = loadMlProfiles();
```

- Function `resolveMarketMlProfile`.
- Type `MarketMlProfile`.
- Interface `MarketFeatureProfile`.
- Class `MarketDatasetBuilder`.

#### Prohibition `ALL_CAPS` / `SCREAMING_SNAKE_CASE`

In internal TypeScript/JavaScript code, it is prohibited to use `ALL_CAPS` / `SCREAMING_SNAKE_CASE` for TypeScript/JavaScript identifier names.

The ban applies to:

* local variables;
* exported constants;
* functions;
* classes;
* types;
* interfaces;
* enum members;
* registry/resolver/map/catalog-variables.

Prohibited:

```ts
export const ML_PROFILE_CATALOG = {};

const MAX_RETRY_COUNT = 3;

enum Status {
  ACTIVE = 'active',
  DISABLED = 'disabled'
}
```

Acceptable:

```ts
export const mlProfileCatalog = {};

const maxRetryCount = 3;

enum Status {
  Active = 'active',
  Disabled = 'disabled'
}
```

Exporting a value or keeping it immutable does not change the naming rule for internal identifiers.

#### Symbolic codes

`SCREAMING_SNAKE_CASE` is allowed for string symbolic codes if the value is stable machine code and not a variable, function, class, or runtime-name.

Acceptable cases:

* application error codes;
* scenario codes;
* machine-readable diagnostic codes;
* compatibility codes;
* external protocol/status codes;
* semi-external string contracts between application layers.

Acceptable:

```ts
export type FrameBuildErrorCode =
  | 'NOT_ENOUGH_CANDLES';

const frameBuildErrorMessages: Record<FrameBuildErrorCode, string> = {
  'NOT_ENOUGH_CANDLES': 'Not enough candles'
};
```

Acceptable:

```ts
export type ValidationErrorCode =
  | 'INVALID_FIGI'
  | 'INVALID_DATE_RANGE'
  | 'UNSUPPORTED_INTERVAL';
```

Prohibited:

```ts
const NOT_ENOUGH_CANDLES = 'Not enough candles';
const FRAME_BUILD_ERROR_MESSAGES = {};
const INVALID_FIGI = 'Invalid FIGI';
```

If `SCREAMING_SNAKE_CASE` is used as a string value, it must be a consciously stable code and not a replacement for a regular name.

A good rule of thumb:

```text
ALL_CAPS identifier  -> запрещено
ALL_CAPS string code -> допустимо, если это stable symbolic code
```

For an object literal with symbolic code keys, it is preferable to explicitly write the keys in quotes to emphasize that this is a string contract and not an identifier naming style.

Preferred:

```ts
const frameBuildErrorMessages: Record<FrameBuildErrorCode, string> = {
  'NOT_ENOUGH_CANDLES': 'Not enough candles'
};
```

Undesirable:

```ts
const frameBuildErrorMessages: Record<FrameBuildErrorCode, string> = {
  NOT_ENOUGH_CANDLES: 'Not enough candles'
};
```

The behavior is the same, but the quotes make the intent explicit: this is symbolic code.

#### Exceptions

`ALL_CAPS` is only allowed where the name is an external contract and not an internal project name.

Allowed exceptions:

* environment variables;
* external protocol/API fields;
* names required by a third-party library;
* SQL/CLI/wire-format values;
* values ​​that must match the external contract verbatim.

Examples of acceptable exceptions:

```ts
process.env.NODE_ENV;
process.env.TRANSFORMER_ENDPOINT;
process.env.CUDA_VISIBLE_DEVICES;
```

```ts
const envName = 'TRANSFORMER_ENDPOINT';
```

```ts
const externalPayload = {
  API_KEY: valueFromExternalSystem
};
```

Published names are preserved as described in the [shared naming policy](./naming-policy.md#внешние-и-опубликованные-имена).

#### Object properties

For internal object properties, `camelCase` is used.

Acceptable:

```ts
const options = {
  maxRetryCount: 3,
  workerPoolSize: 4
};
```

Prohibited:

```ts
const options = {
  MAX_RETRY_COUNT: 3,
  WORKER_POOL_SIZE: 4
};
```

Exceptions are allowed only for external payloads, wire-format structures or contracts of third-party systems:

```ts
const externalPayload = {
  REQUEST_ID: requestId,
  API_VERSION: apiVersion
};
```

#### Enum members

Enum members should use `PascalCase`.

Acceptable:

```ts
enum CandleInterval {
  OneMinute = '1min',
  FiveMinutes = '5min'
}
```

Prohibited:

```ts
enum CandleInterval {
  ONE_MINUTE = '1min',
  FIVE_MINUTES = '5min'
}
```

If the external value should be `ALL_CAPS`, it should be the value of an enum, not the name of the enum member:

```ts
enum ExternalStatus {
  Active = 'ACTIVE',
  Disabled = 'DISABLED'
}
```

#### Examples

##### Environment variables

Acceptable:

```ts
const transformerEndpoint = process.env.TRANSFORMER_ENDPOINT;
const nodeEnv = process.env.NODE_ENV;
```

Prohibited:

```ts
const TRANSFORMER_ENDPOINT = process.env.TRANSFORMER_ENDPOINT;
const NODE_ENV = process.env.NODE_ENV;
```

#### Components and functions

The following conventions apply for components and functions:

- component is called a noun, for example `DateTimePicker`;
- DOM handler receives the prefix `handle`, callback prop - `on`; The
- boolean prop/state starts with `is`, `has`, `can` or directly if possible expresses a state without negation;
- `parse`, `format`, `resolve`, `normalize`, `build`, `create`, `get`, `is`, `has` and `can` are used according to the actual contract function;
- common names `process`, `data`, `item` and `helper` are valid only when context makes them unambiguous.

If a filename indicates its purpose, its contents must match that purpose. For example, a project may use the following conventions:

| Filename | Purpose |
| --- | --- |
| `*.engine.ts` | Independent calculations without side effects |
| `*.model.svelte.ts` | Reactive state and UI actions in Svelte |
| `*.draw.ts` | Canvas rendering |
| `*.test.ts` | Tests |

Names such as `utils.ts`, `helpers.ts`, and `common.ts` are appropriate only for modules that serve one clear shared purpose.

### Grouping tests

The test code follows the same TypeScript rules, but may use local minimal fixtures and mocks for the sake of clear scripting.

Test purpose, observable behavior, and example names are described in the [testing policy](./testing-policy.md). The following conventions apply to grouping with `describe()`.

#### Test suite naming

Test names must describe the public API path and expected behavior.

Top-level `describe()` calls unit under test:

* `ClassName` for classes and runtime components;
* `functionName` for standalone exported functions;
* `objectName` for exported objects or namespaces;
* `module-name` only when several closely related exports are tested and there is no one main subject.

Good:

- `BufferedTextFileWriter`
- `isFigi`
- `marketFeatureProfile`

Bad:

- `utils`
- `tests for writer`
- `validation works`

#### Naming nested suite

Nested `describe()` calls a public member or operation:

* `constructor` for constructor behavior;
* `#methodName` for instance methods called as `instance.methodName()`;
* `.methodName` for static methods called as `ClassName.methodName()`;
* `.methodName` for exported object/namespace methods called as `objectName.methodName()`;
* `functionName` for standalone functions grouped under module-level suite.

Examples:

- `BufferedTextFileWriter`
  - `#writeLine`
  - `#close`
- `FeatureRegistry`
  - `.fromProfile`
- `argGuards`
  - `readOptionalNumber`

A parent suite must not contain sibling `describe()` blocks with the same name.

Bad:

- `BufferedTextFileWriter`
  - `#close`
  - `#close`

If two blocks have the same name, then they need to be combined or named after different public scripts.

## Node.js

### npm scripts

The [script and build policy](./scripts-policy.md) describes when commands may change. The following details apply to Node.js.

Prohibited:

- add prebuild / postbuild
- add pretest / posttest
- replace node logic with shell commands

Example of the correct script:

"build": "tsc"

Example of an incorrect change:

"build": "rm -rf dist && tsc"

Examples of this cleanup through a separate command or automatic execution before builds and tests:

```json
"clean": "rm -rf dist",
"build": "npm run clean && tsc",
"test": "npm run clean && fwa --prune",
"prebuild": "rm -rf dist",
"pretest": "rm -rf dist"
```

Invalid:

- `"test": "npm run lint && vitest"` instead of the existing `"test": "vitest"`
- `"build": "node scripts/build.js"` instead of the existing `"build": "tsc"` without a direct task requirement

### npm dependencies

In the npm project, `package.json` and `package-lock.json` are updated together.

`overrides` applies to the specific problem explained and does not hide the incompatible dependency graph.

Dependency selection, updates, and checks are described in the [dependency policy](./dependencies-policy.md).

## Svelte 5

The following examples show how the general principles apply in Svelte 5. They concern presentation code and use framework features in that context.

### Reactive values

`$state` describes mutable state belonging to the current instance. `$derived` expresses a value computed from other data without side effects:

```ts
let total = $derived(price * quantity);
```

For this calculation, a separate mutable value and an effect that copies the result would introduce another piece of state to keep consistent.

`$effect` connects reactive data to an external system, such as the DOM API, a graphics library, or a subscription. A chain of effects that copy internal state into each other makes the reasons for changes harder to follow. Explicit actions and derived values make those reasons more visible.

Effects must not replace ordinary computations.

### Models and context

A `*.svelte.ts` file allows a reactive model to live outside a component. Such a model serves presentation; the file extension alone does not change its architectural role. Domain calculations and independent scenarios retain their independence from Svelte reactivity.

Context provides dependencies to a limited component tree. Typed functions for providing and accessing context help express its purpose and lifetime. Preparing application dependencies remains a separate task; context can pass on values that have already been prepared.

The examples use Svelte 5 rune mode. Resource creation and cleanup follow the [shared resource ownership principles](./architecture.md#внешние-эффекты-и-ресурсы).

### Components

- Props are declared via `$props` and are typed next to the component boundary.
- Bindable state is only used when bidirectional communication is part of API component.
- Do not transfer feature orchestration to markup expressions.

Local functions and closures are allowed for instance state and resource management. They are not placed in a class or module scope for the sake of style. `bind`, `call` and `apply` are valid if they preserve the receiver of the native DOM API or other necessary contract; a non-obvious reason is recorded next to the call.

Within `.svelte`, follow the local order `script`, `style`, markup. Don't rearrange large blocks just for the sake of consistency in an unrelated task.

Components and their files use `PascalCase`.

A top-level architectural comment is optional for trivial Svelte composition without its own logic, side effects, or a non-trivial contract. Other cases are described in the [comment policy](./comment-style.md).

For Svelte markup, text nodes and significant spaces between elements are taken into account. Do not wrap text and snippet boundaries mechanically. CSS and existing configuration files retain their native format.

### Component styles

- Component-specific styles remain scoped within the component.
- `:global` is used only for a conscious boundary with the child component or The document-level style.

## SvelteKit

SvelteKit conventions establish the roles of route files and server modules. Their particular use and the location of other parts are described in the project's documentation.

### Routes and server code

`src/routes` connects URLs, query parameters, server loading, HTTP statuses, and page composition. Route input validation can live in `+page.server.ts` when it concerns the route's HTTP behavior. Reusable domain checks stay near the corresponding application rules.

Server modules, including `+page.server.ts` and `+server.ts`, work with private environment data and server API clients. Separating server and browser code keeps secrets on the server; page data contains only values intended for the client.

A proxy route describes public HTTP behavior and response forwarding. The integration concentrates provider requests and the allowlist. This division helps explain route behavior and the conditions for accessing the external API separately.

### Server rendering

Access to `window`, `document`, `localStorage`, Canvas, Worker, and the Clipboard API takes account of the execution environment. Code needing the browser after the component appears is tied to the component lifecycle. A utility working in a SvelteKit context can use `browser` from `$app/environment`.

This makes the execution environment an explicit part of the solution. Exception handling, dynamic imports, or a change to server rendering mode have a purpose when they match the task and the application's chosen structure.

User-specific state on the server belongs to a particular request or user session. This keeps different users' data independent. `localStorage` is suitable for UI preferences and versioned client state; validation and recovery take account of browser availability.

### Module composition

A project might use the following conventions:

| File | Role |
| --- | --- |
| `*.svelte` | Markup, interaction, and local styles |
| `*.model.svelte.ts` | Reactive state and presentation actions |
| `*.engine.ts` | Independent pure calculations, parsing, and normalization |
| `config.ts` | Static defaults and limits |
| `types.ts` | Types for the corresponding module |
| `*.test.ts` | Checks of observable behavior |

This example shows a possible division of work. The set of files follows the task's complexity and the project's conventions.

Route files retain the names `+page`, `+layout`, and `+server`.

## Web interfaces

Reusable UI elements preserve native semantics, keyboard accessibility, and meaningful names. When using third-party components, their public API helps keep the application independent of the library's internal structure.

A demonstration page uses the showcased component's API. The application's main code retains its own dependencies, while the demonstration remains a separate usage example.

### Markup and accessibility

- Use the native element for its intended purpose before adding ARIA.
- Interactive `div` does not replace `button`, `a`, `input` or other control.
- Label, accessible name, focus state and keyboard behavior are part of implementation, not optional documentation.
- Decorative SVG icon is hidden from the accessibility tree; name is given interactive control.
- Do not remove focus outline without an equivalent `:focus-visible` state.

### CSS and layout

- Write each CSS declaration on its own line, including in inline styles.
- Repeatable theme values are passed by existing CSS variables/config if is truly a shared responsibility.
- Responsive rules are checked next to the affected breakpoint.
- Fixed size is acceptable for a known control or canvas contract, but should not accidentally break the narrow viewport.
- Don't rewrite the entire style block for the sake of a local visual change.

### Browser checks

SSR check or unit test in Node does not confirm DOM, hydration, focus, keyboard navigation, responsive layout and real browser integration of Canvas. For these properties, relevant browser checks are performed or manual checks are explicitly described using available means.

Pure calculations are checked on a DOM-independent boundary. This is not a replacement for checking component availability. Trivial Svelte composition, CSS and static markup usually do not require a separate unit test, but may require browser smoke.

A large Svelte DOM snapshot does not replace semantic assertions. A one-time screenshot is not an automated regression test.

## Python

Python uses its own notation and the project’s conventions. Code formatting, typing, validation tools, and dependency management are described in the relevant project documentation. JavaScript and TypeScript rules for names, indentation, and statement formatting do not apply to Python.


---

# Editorial history

## November 27, 2026 — CSS formatting

The CSS and layout section now specifies one CSS declaration per line.

## November 16, 2026 — documentation for the reader and their task

The documentation policy describes how to select content: the reader's knowledge, their task, the value of each explanation, and the placement of technical details. Imperatives are appropriate in instructions with a clear goal. Exact compatibility conditions are preserved and placed where they affect the reader's actions.

The README now starts local setup with package preparation and commands. Node.js versions are collected in the environment reference; deployment instructions link to the same source. Other policies have clearer introductions, the dependency and abstraction policies explain selection criteria, and repeated sections have been removed from the code style policy. Existing technical conventions and code examples are preserved.

## November 16, 2026 — architecture principles and the purpose of policies

Policies set out common working principles and explain their meaning. Each project's own sources and documentation describe its particular architecture and current contracts.

The architecture policy is the first document revised in this approach: repeated explanations have been combined, reasons for decisions added, and architectural arrangements and file conventions presented as examples. The principles of module responsibility, independent domain logic, state ownership, contract sources, and separation of server and browser code are preserved. The shared introduction and the description of policies' role now reflect their purpose; the other policies retain their existing wording in this change.

## November 12, 2026 — utility comments

All functions and methods in utility and tool modules require comments describing their purpose and relevant constraints. This includes internal operations, returned handlers, build tools, and test utilities.

## November 12, 2026 — method and function signatures

Method and function signatures should stay on one line whenever possible if the full signature fits within 100 characters, including indentation.

## November 12, 2026 — justified exceptions

Justified exceptions to the standard's rules are allowed. A comment next to the affected code is mandatory and must identify the rule and reason for the exception.

## November 12, 2026 — exception handling

The code style policy now prohibits nested exception handling statements within one function and at module scope. An operation with its own error handling is extracted into a named function while preserving exception boundaries, operation order, and resource cleanup.

## Revision 1 - November 5, 2026

Woodger's first common standard combines 13 Inventory policies and applicable site rules.

Retained requirements for minimum changes, architectural boundaries, code removal, comments, naming, tests, documentation, dependencies, assembly, metrics and abstractions.

When preparing the general edition, the scope of application was clearly changed:

- Mandatory PostgreSQL, device ML profiles, identity indicators and paths CLI Inventory remain contracts for this project; they do not become requirements for all applications.
- Clean Architecture Lite describes applications with appropriate layers. Presentation, Svelte and SvelteKit boundaries are separately defined for the UI. Directories prescribed by the framework are not considered arbitrary generic directories.
- TypeScript/JavaScript rules do not impose their notation on other languages. The names of external and published contracts are preserved.
- For trivial Svelte composition without its own logic is not required architectural block comment. For non-trivial runtime modules, the Inventory rule is preserved.
- Specific test runners, commands, ports, build output and deployment methods are described in the project documentation. The standard specifies requirements for inspections.
- Metric rules apply to the observability system used; mandatory OpenSearch connection is not entered.
- Safe equivalent commands and temporary workdir are allowed without modification project. A blocked check is reported explicitly; installation of software and changes to the environment retain the requirement for explicit permission from the owner.

The accepted format of Git commit messages has been moved to the general design policy. The current UI requirements of the site have been added to the general policies: SSR and hydration, semantics of native controls, focus, keyboard navigation, responsive layout, resource cleaning and protection from late asynchronous results.

The site is connected to this edition. The translation of the remaining repositories is carried out separately, while maintaining their existing contracts.
