# Common Coding Rules

---

# Scope and Precedence

_Standards and Conventions / Common Coding Rules_

> How common rules, language conventions, and repository exceptions interact.

This is the consolidated working draft developed with Jack under PEI-1506. It
records the agreed policies and applies them to the language profiles. An
unanswered proposal is not a rule. Requirements, preferences, and soft review
thresholds retain their stated strength; a formatter must not silently turn a
preference into a mandatory rule.

The [style tooling guide](/psc/style-tooling/style-tooling.md) explains the available
configurations and checks. These tools implement the policies; they do not
replace them. The kernel exception guide,
`kernel/peios/CODING_STYLE.md`, defines the scope of the kernel's deviations.
Git workflow and commit rules remain in [Using Git](/psc/git-workflow/development-model.md).

## Shared defaults and language conventions

Use the Peios default when a language's community has several reasonable
conventions. A merely popular preference does not override the Peios baseline.

Follow a language convention when it is strongly established across the
ecosystem. Jack's comparison of roughly 60% versus 90% adoption describes the
strength of consensus intended, not measured thresholds or a requirement to
invent adoption statistics.

Assess that strength using language guidance, standard tooling, and
established practice together. A configurable formatter's default or one
organization's styleguide alone does not establish an ecosystem-wide
convention. Record the reason for each language-specific departure from the
shared default; discuss unclear cases before adopting an exception.

## Rule organization

Keep common rules and per-language rules in the central Peios styleguide.
Repository-specific guides describe explicit, scoped deviations from that
baseline. A repository exception should identify the rule it overrides, the
files or language it covers, and its rationale.

Apply language syntax and required external contracts first, then explicit
repository exceptions for their stated scope, then language-specific rules,
then common defaults. An exception overrides only the rules it identifies; it
does not discard the rest of the guide. Bring unresolved conflicts back for
discussion instead of inferring an exemption.

The kernel has its own exception guide. Its kernel C conventions do not apply
to Peios-only Python scripts or Bazel files because they share a repository.

---

# Formatting

_Standards and Conventions / Common Coding Rules_

> Indentation, line length, whitespace, quoting, and brace placement.

## Indentation

Use four spaces per indentation level as the shared Peios default. Use spaces,
not hard tabs, unless a language or repository exception applies.

## Line length

Keep source lines within 100 columns as a strong expectation, not an absolute
limit. Wrap ordinary code and comments to fit. A longer line needs a concrete
readability or correctness reason; convenience alone is not an exception.

Examples include a URL that must remain intact, a diagnostic string whose
splitting would make it harder to find, or an expression that wrapping would
make materially harder to understand. Keep the exception local rather than
using it to justify long lines throughout a file.

Configure formatters to target 100 columns where supported, subject to the
agreed language and repository exceptions. Do not require awkward changes
solely to bring an otherwise justified exception under the limit.

## Text-file hygiene

Use UTF-8 encoding and LF line endings. End text files with a newline and
remove trailing whitespace. Preserve exceptions where the file format requires
a different representation or gives the whitespace meaning.

## Spacing and multiline lists

Prefer ordinary spacing rather than manually padding neighboring statements to
align columns. Allow alignment when it makes a genuine table clearer or is
produced by the agreed standard formatter. Avoid alignment that causes
unrelated lines to change merely because one identifier becomes longer.

Prefer a trailing comma after the final item of a multiline list where the
language permits it. Follow language-specific conventions and the agreed
formatter. Adding an item should not needlessly require changing the preceding
item's line.

## Quotes and statement terminators

Prefer double-quoted strings where single and double quotes are semantically
interchangeable. Allow alternative quoting when it reduces escaping. Preserve
language-specific distinctions, such as shell expansion and string
interpolation; this preference must not change a value's meaning. Use
semicolons in JavaScript and TypeScript.

## Braces

Use same-line opening braces as the common default for functions and control
flow, as in `if (ready) {`. Keep a closing brace and following `else` together
as `} else {`. Language and documented repository exceptions can override this
placement.

Where a language permits optional braces for conditionals or loops, braces can
be omitted only when the body contains one statement and the control clause
and body appear together on one line within 100 columns. Omitting braces is
permitted in that case, not required.

```c
if (!token) return INVALID_TOKEN;
```

Use braces for a body containing multiple statements, or when the condition or
body spans multiple lines. This includes a single statement placed on a line
below its condition:

```c
if (!token) {
    return INVALID_TOKEN;
}
```

If any branch in an `if` / `else if` / `else` chain needs braces, use braces
for every branch in that chain:

```c
if (!token) {
    record_failure();
    report_invalid_token();
} else {
    use_token(token);
}
```

Language requirements and documented repository exceptions still apply. Kernel
C deviations are specified in its repository guide. The optional-brace rule
applies where braces are optional control-flow delimiters; it does not replace
the block syntax of languages such as Python, Go, or Rust.

---

# Naming and Organization

_Standards and Conventions / Common Coding Rules_

> Names, units, constants, imports, visibility, and source organization.

## File organization

Group closely related code by purpose. Keep a small implementation and its
private helpers together when that makes them easier to understand; separate
unrelated features. Do not impose a blanket rule of one function or type per
file. Follow language-specific layout conventions where applicable.

## Naming

Use these shared defaults where there is no strong language convention or
documented repository exception:

| Identifier | Style | Example |
| --- | --- | --- |
| Variables | `snake_case` | `retry_count` |
| Functions | `snake_case` | `load_config` |
| Modules | `snake_case` | `package_store` |
| Types | `PascalCase` | `AccessToken` |
| Constants | `SCREAMING_SNAKE_CASE` | `MAX_RETRIES` |

Language-specific naming departures follow the [consensus
rule](/psc/common-coding-rules/scope-and-precedence.md); these defaults do not override a strongly
established language convention.

### Identifier wording

Prefer descriptive names that communicate the role of a value or operation.
Allow familiar abbreviations such as `id`, `fd`, and `url` when their meaning
is clear in context. Short local names such as `i` are acceptable in small
scopes where their purpose is obvious. A short name is not a reason to make
readers trace distant code to discover its meaning.

### Units and type information

Make units explicit in a value's name or type. For example, use `timeout_ms`
for a number of milliseconds, or `timeout` when its type conveys the unit or
duration semantics. Do not leave readers guessing whether a bare number means
seconds, milliseconds, bytes, or another unit.

In typed languages, do not encode a value's programming-language type in its
name. Use `timeout_ms`, not `timeout_ms_int`: the unit explains the meaning,
while the type declaration already supplies the representation. Name values
for their role and meaning rather than adding type prefixes or suffixes.

## Constants and literal values

Strongly avoid magic constants: fixed values whose meaning or significance is
unclear from the code. This applies to strings, numeric values, bit masks, and
other literals, not only numbers. Give them meaningful names or use
appropriate named choices so readers can understand their purpose. Explain the
reason for a particular value when its name alone cannot convey it.

For example, use `MAX_RETRIES` for a retry policy instead of an unexplained
number in the retry logic. A name should explain meaning, not merely repeat
the value. Obvious literals, such as starting a counter at `0`, do not need a
named constant solely because they are literals.

## Imports

Prefer explicit imports that make dependencies and the origins of names clear.
Avoid wildcard imports by default. This is a preference, not a hard rule:
allow exceptions when they improve clarity or follow a strongly established
language convention. Explain non-obvious exceptions where useful.

Group standard-library, third-party, and project-local imports in that order
where the language supports it. Preserve side-effect-sensitive ordering and
document narrow exceptions rather than blindly sorting imports.

## Visibility and encapsulation

Keep functions, types, and fields private or module-local by default where the
language supports it. Expose them more widely when other code needs that
interface. Keep implementation details behind the interface so they can change
without requiring changes in callers.

Encapsulation should serve a clear purpose. Do not add unnecessary getter,
setter, or forwarding wrappers solely to make simple code appear encapsulated.

## Unused and commented-out code

Remove unused code and old implementations left inside comments. Use version
control to recover previous implementations instead of retaining them in the
source for possible future use.

Keep useful documentation examples and code with a real supported purpose. An
implementation for another supported platform is not unused merely because the
current build does not select it. Establish that code is obsolete before
removing it.

---

# Interfaces and Data

_Standards and Conventions / Common Coding Rules_

> Arguments, dependencies, documentation, contracts, and data boundaries.

## Function arguments

Avoid positional arguments whose purpose is difficult to infer at the call
site. This applies to all argument types, especially booleans: a call such as
`save(file, true, false)` leaves the reader guessing what the switches
control.

Use named arguments where supported, meaningful named choices, or a clearer
interface to make the purpose apparent. Positional arguments remain
appropriate when their meaning is clear, as in `set_enabled(true)`. Do not
require readers to look up the function declaration merely to decipher an
ambiguous argument.

## Dependencies

Give a proportionate justification when adding a dependency. Explain what it
provides and consider maintenance, compatibility, licensing, build and runtime
footprint, and performance costs. Record the reasoning with the associated
work; a small, obvious choice does not need an elaborate report.

A maintained library can be appropriate for a complex parser, while a whole
package might be unnecessary for a trivial helper. There is no blanket rule to
reimplement functionality or always prefer a library.

## Documentation comments

Document public APIs and non-obvious internal contracts. Describe behavior,
errors, ownership, and locking requirements where relevant, using the
language's documentation-comment format. Explain constraints callers must
satisfy and guarantees they can rely on.

Use implementation comments to explain reasoning, invariants, or surprising
constraints that the code alone does not make clear. Keep comments accurate
when behavior changes. Do not add comments that merely repeat obvious code. An
internal function whose purpose and contract are clear from its code and names
does not need a documentation comment solely because it is a function.

## External contracts and style changes

Style cleanup must preserve behavior and externally consumed contracts. This
includes API and ABI names, calling conventions, and layouts, serialized field
names and values, configuration keys, and protocol-defined identifiers. Follow
required external names even when they differ from the naming table.

For example, renaming a local variable to match the guide must not silently
rename the JSON field it is serialized into. A symbol with no internal callers
might still be a supported public entry point; it is not obsolete on that
basis.

Intentional contract changes are functional work, not incidental formatting.
Apply the component's compatibility requirements and the breaking-change
documentation in [Commit Style](/psc/git-workflow/commit-style.md). This styleguide does not
establish a new ABI support period or authorize a breaking change during
cutover.

## Data representation

Prefer data structures that make contradictory states difficult to express.
For example, represent mutually exclusive connection states with one choice
between `connecting`, `connected`, and `disconnected`, rather than independent
boolean flags that can accidentally contradict one another. Apply this where
it simplifies the code; do not require elaborate types for every small value.

Represent missing values explicitly using the language's appropriate mechanism
rather than assigning a hidden meaning to an otherwise ordinary value. For
example, prefer an optional timeout to using `-1` for an unspecified timeout.
Respect established external APIs and formats that prescribe special values;
make their meaning clear where those representations are used.

## Validation boundaries

Make representations explicit at file-format and protocol boundaries. Specify
the text encoding and, for binary data, relevant field sizes, byte order, and
layout rather than accidentally depending on the current machine's in-memory
representation. Reference an existing format specification where it already
defines these details; do not duplicate or silently change its contract.

Deliberately platform-specific formats are permitted when their assumptions
are explicit. This rule does not require every format to be portable or choose
one universal encoding or byte order for Peios.

Validate incoming data at component boundaries and document the guarantees
internal code can rely on. For example, parse and check configuration values
before passing them around as valid settings. Internal helpers need not repeat
every check when the required guarantees already hold.

Revalidate when data can change in ways that invalidate those guarantees or
when it crosses another trust boundary. Boundary validation does not justify
trusting unchecked or subsequently changed data.

## Type annotations and inference

Where a language supports local type inference, prefer it when the type is
clear. For example, Rust's `let user = User::new()` need not repeat the `User`
type. Add an explicit annotation when it clarifies important information or
selects the intended type, such as a particular numeric representation.

Function interfaces follow their language's separate rules. Local inference
does not remove the requirement to make units and meaning clear.

---

# Errors and Resources

_Standards and Conventions / Common Coding Rules_

> Error handling and reporting, mutability, resource ownership, and cleanup.

## Error handling

Handle expected failures through the language's normal error mechanism.
Invalid input, missing files, and I/O failures are ordinary possibilities:
handle them where an appropriate response is known, or return/propagate the
error so the caller can decide what to do. Recovery is not required at every
layer.

Reserve assertions and panics for internal bugs or broken invariants:
conditions the implementation relies on being impossible during correct
operation. Do not use them as ordinary error handling for externally supplied
invalid input. Application boundaries can decide to report an error and exit.
Kernel and other component-specific requirements can impose stricter rules on
assertions or panics; this distinction does not require panicking on every
internal failure.

### Intentionally ignored errors

Make a deliberate error discard explicit in the code. Document why ignoring
the error is safe, either at the discard site or in the helper's contract. An
empty handler or an unchecked result must not conceal forgotten error
handling.

For example, after a document has been saved successfully, failure to update
an optional recent-files list can be deliberately ignored. The explanation
should make clear that the document is safely saved and that the list is
optional. This does not justify ignoring failure of the save itself.

## Error reporting

Normally report a failure once, with enough context to understand it. Add
relevant context as an error propagates, then report it at the layer
responsible for handling or presenting it. Avoid logging the same failure at
every layer.

For example, preserve the underlying file error while adding that it happened
while loading settings during application startup. Separate log entries remain
appropriate when they serve distinct operational purposes rather than merely
duplicating the same report.

## Mutability

Prefer read-only data and bindings where the language supports them. Permit
mutation when the implementation needs it, rather than making values mutable
for hypothetical future changes.

Account for changes made through helper functions or other references, not
only assignments in the current scope. Distinguish a binding that cannot be
reassigned from an object whose contents cannot change; language-specific
rules will describe the appropriate mechanisms.

## Resource ownership and cleanup

Every resource must have a clear owner responsible for releasing it. Resources
include memory, open files, and acquired locks. Make ownership transfers clear
when responsibility passes to another part of the program.

Prefer the language's automatic cleanup mechanisms where available. For
example, Go's `defer` can schedule cleanup after successful acquisition so it
runs when the surrounding function returns, including early returns. Choose
the cleanup lifetime to match the resource's actual use: function-exit cleanup
is not the same as cleanup at the end of a nested block.

Where cleanup is explicit, cover error paths and early returns as well as the
successful path. Cleanup errors still follow the error-handling rules in this
article; scheduling cleanup does not justify silently ignoring a meaningful
failure.

## Shared mutable state

Avoid mutable global state by default. Pass the data or services a function
needs explicitly so its dependencies and possible effects are visible. This
does not require a framework or elaborate wrappers.

Allow justified exceptions for genuinely shared facilities, such as a
system-wide device list. Document who owns the state, how long it lives, who
can change it and how concurrent access is coordinated.

---

# Design and Concurrency

_Standards and Conventions / Common Coding Rules_

> Control flow, review thresholds, shared code, concurrency, and performance.

## Control flow

Prefer guard clauses and early returns to handle invalid inputs, errors, and
special cases before the main path. Keep the main path shallow rather than
nesting it inside successive checks. There is no requirement to use a single
return point.

Use a shared cleanup path when resource management makes it clearer or safer.
Early returns must still release owned resources and locks correctly.

## Function size and nesting

Use soft numeric thresholds to prompt a review of function size and nesting,
not hard limits. When a threshold is exceeded, consider whether the function
still has a clear purpose and understandable control flow, and whether a
meaningful extraction or simpler structure would improve it.

Review a function when it exceeds either initial threshold:

- More than 50 nonblank, non-comment lines in its body.
- More than three nested control-flow levels.

For length, count physical body lines containing code, including
delimiter-only lines; exclude the function signature, blank lines, and
comment-only lines. Count a mixed code/comment line once. Do not compress
statements to reduce the count.

For nesting, the function body starts at level zero. Each nested conditional,
loop, switch/match, or exception-handling construct adds a level. An `else if`
chain or sibling switch/match arms are alternatives at the same level, not
successively deeper levels. Plain grouping braces do not add control-flow
levels. Assess nested functions and lambdas separately.

Do not split a cohesive function solely to satisfy a number. Crossing a
threshold alone is not an automatic CI failure.

## Shared code and duplication

Avoid duplication when repeated code represents the same concept or rule.
Share that behavior through a meaningful helper or abstraction so changes to
the common rule can be made consistently.

Similar-looking code does not necessarily represent the same idea. Allow
duplication when combining it would tie together unrelated behavior that needs
to change independently. Do not introduce a shared abstraction solely to
eliminate repeated lines.

## Background work

Give background work a clear owner, lifetime, and shutdown behavior. Define
how failures are handled. When the initiating component stops, stop its work
or deliberately transfer responsibility to an owner that remains alive.

For example, closing a window that started a download should either stop the
download or hand it to a longer-lived service. Do not leave work running
merely because its ownership or cleanup was forgotten.

## Locking

Keep locks held for as little work as practical while preserving correctness.
Avoid slow work and calls into unknown code while holding a lock where
possible. Document the acquisition order when multiple locks must be held, and
follow it consistently.

Holding a lock longer is appropriate when correctness requires it. Respect the
requirements of the particular lock and execution context; shortening a lock
hold must not expose inconsistent state or introduce races.

## Unsafe operations

Keep operations that bypass language safety checks in narrow, reviewable parts
of the code. Document why they are safe and the assumptions they depend on.
For a direct memory access, this includes the relevant guarantees about memory
lifetime and validity of the access.

Review the surrounding code that maintains those assumptions as well as the
unsafe operations themselves. A small unsafe block alone does not establish
safety if other code can invalidate its assumptions.

## Performance

Treat performance as a design concern from the outset, not an afterthought.
Choose suitable algorithms and data structures and account for known critical
paths while designing the implementation.

Permit and encourage minor to moderate increases in complexity proactively
when there is a clear reason to expect substantial relative performance gains,
especially on hot paths in critical components. A benchmark is not a
prerequisite for every such decision. Make the expected benefit and reasoning
clear; distinguish an anticipated improvement from a measured result.

Use measurements where practical to validate and refine performance decisions.
Require stronger evidence as the complexity and maintenance cost of an
optimization grow. Avoid elaborate speculative optimizations without adequate
justification. Do not require a benchmark for every straightforward
improvement or use the absence of measurements to excuse wasteful code.

---

# Tests

_Standards and Conventions / Common Coding Rules_

> Test behavior, regressions, repeatability, and useful failure details.

Prefer tests of observable behavior over tests of incidental implementation
steps. For example, check that saving and reopening a document preserves its
contents rather than requiring the save function to call particular helpers.
Internal restructuring that preserves the required behavior should not break
otherwise valid tests.

Test internal details when those details are themselves part of a real
requirement. This preference does not restrict tests to public APIs or prevent
focused tests of internal components.

## Regression tests

Strongly prefer adding a regression test when fixing a bug: a test that
catches the faulty behavior and passes with the fix. For example, a fix for a
crash on an empty filename should normally include a test of that case.

Allow justified exceptions when a useful automated test is impractical. Record
why the test was omitted and how the fix was checked in the associated work's
validation record.

## Independence and repeatability

Prefer tests that work independently and give repeatable results. Do not rely
on another test leaving files or other state behind. Control inputs such as
time, randomness, and external services where practical, and clean up
resources owned by the test.

Tests that genuinely require a network, special hardware, or randomness should
make those requirements explicit and provide enough information to investigate
failures. For example, report the seed or failing input for a randomized test
when that helps reproduce the failure.

## Names and failure details

Use descriptive test names or case descriptions that explain the behavior
being checked. For example, `empty_filename_returns_error` is more useful than
`test_7`.

Make failures informative, including relevant expected and actual values where
appropriate. Use the test framework's existing diagnostics; do not add
messages that merely repeat information it already reports.
