cometa-0.2.0.0: CODING_CONVENTIONS.md
# Haskell coding conventions
These rules apply to Cometa.hs.
Use the checked-in formatter and HLint settings as the mechanical source of truth.
Before editing, inspect nearby modules and match their organization and vocabulary.
## Modules, layout, and imports
Use Ormolu 0.8.0.2 and HLint 3.8 with the repository's HLint configuration. Prefer readable
named arguments and pattern matching over dense point-free expressions. Use
normal Haskell layout, not Allman braces. Use ordinary comment section banners
to separate imports, types, and related operations, as described below.
Every module has an explicit export list and a Haddock introduction explaining
its domain. Group public exports by construction, inspection, transformation,
serialization, and effects when those groups help navigation. Keep public modules
focused; `Cometa` is a curated convenience module, not an indiscriminate re-export
of internals. Files follow the module hierarchy.
Give every public binding a type signature. Give internal helpers signatures when
they explain constraints or prevent unintended polymorphism. Prefer explicit
import lists; qualify domain modules with names such as `Address`, `Tx`, `Plan`,
or `Blake2b`. Do not use a custom Prelude or require an effects framework for
ordinary use. Avoid orphan instances; optional interoperability uses owned wrappers.
Use the package's declared language baseline. Enable an extension in the module
that needs it, with an explanatory comment when its safety or API consequences
are not obvious. Do not add package-wide extensions casually. Use ordinary record
selectors; do not introduce `DuplicateRecordFields` or `OverloadedRecordDot`
without a repository-wide decision and compiler-matrix evidence.
## Design from complete workflows
Before designing or extending a public API, review how relevant established
Haskell libraries solve the same task. Read their actual documentation, source
and usage examples, including the complete caller workflow and error handling.
Record links and the reviewed version or commit in the change description,
explain which contracts inform Cometa, and justify material differences. This
review is required before choosing the API; familiar names or remembered
signatures are insufficient evidence. Adopt patterns that fit the domain and
Cometa's guarantees rather than copying another library mechanically.
Design a complete caller workflow before adding primitives. Write the code an
application needs to validate input, assemble values, execute the operation, and
handle the result. Review successful use, invalid input, and cleanup together.
Use these examples to justify abstractions and discover avoidable ceremony.
Validate external input once, then compose abstract validated values with total
functions. Provide lawful standard instances and useful defaults when their
semantics are clear: `Bounded Index` supplies raw zero and `2^31 - 1`, so a known
first index can use `minBound` without an impossible error branch. Do not add
`Num`, `Enum`, partial literals, or unsafe constructors merely to shorten examples.
Keep `mkIndex` for integers supplied at runtime.
Prefer pure, Haskell-owned values for validation, assembly, and inspection.
Require effects only for observable effects, scoped resources, or unaudited
native boundaries; follow the specific purity audits below. Offer a small
workflow helper when the common task otherwise requires callers to manage
intermediate secrets. For example, one-shot BIP32 public-key derivation manages
private scopes internally while lower-level scoped operations remain available
for several related operations. Convenience must preserve cancellation, cleanup,
and error behavior.
Group pure input validation in small `Either` functions before running effects.
Use ordinary `do` notation or applicative composition inside `Either`; lift a
validated group once when combining it with `ExceptT`. Use `ExceptT` for a
sequence of fallible effects, and handle the result at the caller's boundary. Avoid nested error matches and mandatory custom monads or
effects frameworks. A single fallible operation needs no transformer. Helpers
should name actual workflow steps rather than disguise errors or ownership.
Review signatures for ambiguous same-typed arguments, especially password,
entropy, and storage `ByteString` values. Use descriptive argument documentation
and examples; introduce an options record or another abstraction only when a
complete workflow demonstrates its benefit. Compare the relevant contracts of
idiomatic libraries; do not copy historical
partial conveniences or claim one universal Haskell style.
## Naming
- Modules, types, classes, and constructors use `UpperCamelCase`; functions,
fields, variables, and constants use `lowerCamelCase`.
- Prefer domain names and qualified module vocabulary. Do not repeat `cometa` or
mechanically expose C prefixes, getters, and setters.
- Use `fromBytes`/`toBytes`, `fromText`/`toText`, and `decodeCbor`/`encodeCbor`
consistently. The type signature, not the name, determines effects.
- Use `mk...` for validated construction from a more general value. Return an
explicit error; do not shorten call sites with partial smart constructors.
Prefer plain names such as `accountPath` for total assembly from validated
values. This repository uses the distinction to make validation boundaries
visible; other Haskell libraries may use `mk...` more broadly.
- `with...` scopes a resource. `run...` interprets an action. `eval...` and
`exec...` follow the familiar distinction between returning a result or state.
- Prefer observers such as `fee` or `networkId` in qualified modules.
- Suffix `_` means a result is discarded. An apostrophe marks a documented variant,
usually strictness, not an unexplained error policy. Use `By` for supplied
comparison behavior and `On` for projection behavior where appropriate.
- Keep `TxId`, `Utxo`, and `Cbor` consistent. Prefer complete domain names over
unexplained abbreviations. Exported unqualified record fields receive a domain
prefix when needed to avoid ambiguity.
- Reuse lawful standard operators. A new symbolic operator needs a demonstrated
readability benefit, a named equivalent, and documented fixity.
- Private FFI names may retain C spelling with an internal prefix for auditing;
this vocabulary must not determine public Haskell names.
## Values, invariants, and laws
Use algebraic data types for alternatives and validated newtypes for invariants.
Hide constructors when they protect bounds, byte lengths, original encodings,
roles, or resource ownership. An exported record update or representation
conversion must not bypass those protections.
Audit every instance. `Read`, `IsString`, `Num`, `Generic`, and `Data` can expose
construction routes that violate invariants; justify their use individually.
`Show` is diagnostic, not a stable interchange format. Never derive secret-bearing
`Show` output. Role-indexed hashes and keys need a `Coercible` audit, nominal
roles where required, and compile-fail checks for the intended boundary.
Introduce a class only for a coherent abstraction with meaningful instances and
laws. Runtime providers, evaluators, selectors, and signers initially use records
of functions. Test every advertised law, including associativity and identity for
plan composition. Do not claim a total numeric monoid when bounded arithmetic
can fail. Optional optics must preserve invariants and obey their laws; a
normalizing or validating operation is not automatically a lawful lens.
Use `Integer` for arbitrary-precision protocol integers. Keep signed quantities
signed; validate nonnegative amounts and native bounds before conversion. Never
route monetary values through floating point. Do not derive unrestricted `Num`
for validated quantities.
Choose collections by their semantics. Preserve order, duplicate keys, absence,
null, empty, and zero wherever the format distinguishes them. Do not automatically
replace arbitrary Plutus maps with `Data.Map`. Define equality and ordering for
encoded values explicitly; pointer identity is not domain equality.
## Totality, effects, and evaluation
Expected invalid input returns `Either` with a structured domain error. `Maybe`
means legitimate absence. Native/effectful operations initially return
`IO (Either ... ...)`. Preserve error codes and context without leaking secrets.
Do not make a universal Cometa monad mandatory; callers may compose with `ExceptT`.
Normal public input handling must not rely on `error`, `undefined`, `fromJust`,
unchecked indexing, or incomplete patterns. Genuinely necessary unsafe operations
belong in an explicitly separated internal/unsafe surface with preconditions and
safe alternatives. Keep validation, composition, and materialized-value inspection
pure where practical. Native calls remain in `IO` until a specific purity review;
`unsafePerformIO` is not a shortcut. The reviewed exceptions are the concrete,
private boundaries documented in [the BIP39 purity audit](docs/development/BIP39_PURITY.md)
and [the PBKDF2 purity audit](docs/development/PBKDF2_PURITY.md).
They apply only to the separately audited pinned deterministic owner-free paths
and their marshaling/cleanup/error handling. Re-audit source and native build changes; never
generalize the boundary to an arbitrary IO runner.
Use strict accumulators and snapshots where needed to bound retention or keep
exceptions inside cleanup scopes. Do not enable blanket strictness without
justification. Strict fields and strict maps force particular structures only to
WHNF; nested values and functions may remain lazy. Specify which callback result
parts must be forced before returning to C. `NFData` on a surrounding record does
not establish that a function has been fully evaluated.
Preserve ordinary asynchronous cancellation after safe foreign-boundary unwind.
Use structured, bounded concurrency. A timeout is not evidence that C stopped
using its buffers or callback state. Measure marshaling, allocations, startup,
and evaluation before adding specialization or unsafe optimization.
## FFI and resource safety
Separate raw declarations, marshaling, ownership scopes, and callbacks. Audit the
current native headers and implementation rather than assuming that all getters
borrow or all outputs transfer ownership. Document contracts beside the FFI boundary.
- Copy borrowed bytes/strings or retain an immutable owner for their entire use.
Retaining a reference is not cloning; native reference counts are not atomic.
- Track every ownership obligation explicitly. After unref, mark the local
obligation released even if another owner leaves the pointer non-null.
- Copy native diagnostics before releasing their owner. Release operation-scoped
resources deterministically on all exits; finalizers are a fallback for suitable
persistent resources.
- Access managed pointers through `withForeignPtr`. Typed pointer-to-pointer C
unref functions cannot serve directly as unary `ForeignPtr` finalizers.
- Keep callback closures rooted with supported stable handles. Keep `StablePtr`,
`FunPtr`, contexts, and error state alive through the last possible callback,
including repeated balancing and cleanup.
- Distinguish provider/key-handler context adoption from borrowed deferred contexts.
Retain operation owners while callbacks run. Prevent unsupported reentry.
- Use callback-capable `safe` imports when C can re-enter Haskell. Audit short,
non-callback `unsafe` imports individually; account for scheduler behavior in
long-running evaluation. Do not mark arbitrary calls `interruptible` for timeouts.
- Bracket/mask ownership transitions. Catch callback exceptions within the bridge,
return a native failure, and rethrow or translate after safe unwind. Do not
silently turn asynchronous cancellation into a recoverable provider error.
- Concurrent operations have independent mutable handles and error slots, or a
documented synchronization scheme. A worker continuing after cancellation owns
and eventually releases all state it still uses.
Hash-bearing transaction values must preserve original encoding where identity
requires it. Controlled edits invalidate affected caches and define witness
behavior. Never silently canonicalize a signed transaction. Establish exact CBOR,
body-hash, signature, and edit-independence tests before broad implementation.
Secret resources are opaque and scoped. Reject use after close, including escaped
handles; a callback-shaped acquisition alone does not prove safety. Private-key
export must be explicit and explain the loss of controlled lifetime after copying.
## Documentation and tests
Public Haddock describes observable behavior: meaning, parameter units and bounds,
return values, errors, defaults, ordering, and effects. Each public module explains
its purpose and has a small valid example. Keep raw ownership mechanics internal. Do not put implementation status, future
roadmaps, pointer ownership, copying strategies, or ABI details in public API
contracts. Document observable restrictions honestly, including unsupported inputs.
Use Haddock section headings to group related exports. Document constructor
payloads and arguments when their meaning, units, or bounds are not clear from
the type. Internal modules should document ownership, synchronization, and exception
contracts at the declarations that enforce them; ordinary comments explain local
invariants. Avoid comments that merely repeat a name or narrate a line of code.
Separate acquisition, computation, and result handling with blank lines where they
form distinct steps. Keep related bindings together. Let Ormolu determine indentation
and wrapping. Use section banners for substantial logical groups, not individual
functions. Keep banners outside Haddock comments so they do not enter API prose.
Use the Microsoft Writing Style Guide as an editorial reference and established
Haddock syntax for declarations. Narrative pages teach tasks; proposed interfaces
stay in developer plans and must be labeled as proposals.
Compile executable examples and check links. Use pure deterministic doctests when
appropriate and compiled fixtures for effectful flows. Never require credentials
for ordinary documentation builds. Keep the guide and versioned Haddock aligned
with the source/package they describe.
Prefer Hedgehog for new shrinking and state-machine properties; retain imported
QuickCheck properties when practical. Test laws, bounds, invalid encodings,
round trips, collection semantics, snapshot independence, allocation baselines,
callback rooting, exceptions, repeated callbacks, cancellation, and supported
concurrency as relevant. Use deterministic fakes for injected components. Selector
tests assert invariants rather than identical random choices. Save minimized
failures as regression cases.
Pin native/corpus revisions and record imported test source paths, commits, and
licenses. Test through public values, not only opaque CBOR forwarding. Native
agreement detects binding errors; use independent vectors or oracles where
possible. Keep authorized live-network evidence separate from fixture evidence.
## Native adapters
Keep C adapters in `cbits` limited to ABI layout, ownership, and marshaling.
Use the checked-in `.clang-format` with ClangFormat 18, matching cardano-c's
formatting. Haskell keeps its own Ormolu conventions. Document adoption, borrowing,
callback lifetime, and failure ownership at each boundary. Match the section
banners, Doxygen `\brief`/`\param`/`\return` comments, header guards, and logical
spacing in cardano-c provider headers and sources. A formatter alone does not
establish this organization. Document declarations in headers and local helpers
next to their definitions; avoid duplicating the same contract in both. Native callbacks must
never unwind a Haskell exception through C.
## Compatibility and review
Follow the Haskell Package Versioning Policy for exposed types, declarations,
instances, and dependency bounds; track native version/ABI separately. Test the
supported compiler matrix and dependency bounds. Use meaningful warnings,
including incomplete patterns and record updates. CI may promote warnings to
errors; do not ship unconditional `-Werror` to consumers.
Before bulk implementation, review complete use cases for payment, script spend,
custom evaluation, external signing, decoding failure, and cancellation. Before
first release, seek experienced Haskell/FFI maintainer review when available and
record its outcome. Passing automated checks does not prove exception safety or
API quality.
Use current primary documentation when comparing established library APIs.
Adopt contracts that fit this library rather than copying partial APIs or adding
dependencies solely for stylistic similarity.
## API review checklist
Before accepting a public API change, review concrete caller code:
- Have relevant established libraries' documentation, source and real usage been
reviewed before design, with links, version or commit, workflow and justified
differences recorded in the change description?
- Can the common task run from input to result with one clear error boundary?
Are runtime inputs validated once and valid values assembled without spurious
failure branches?
- Do names distinguish validation, assembly, inspection, and scoped effects?
Are same-typed arguments, defaults, units, bounds, and byte encodings clear?
- Are standard instances lawful and useful without bypassing invariants? Can
known defaults use existing total values instead of partial construction?
- Does a workflow helper manage intermediate secrets automatically while keeping
advanced scoped composition available? Are cleanup and cancellation preserved?
- Are pure values and native effects separated according to audited contracts?
Is each new abstraction justified by an actual caller workflow?
- Do compiled examples show real derivation, signing, or storage/reload work,
with explicit imports, logical spacing, total matches, and one failure boundary?
Are the guide, Haddock, tests, and native contracts consistent?
## File headers, sections, and function size
Start every Haskell source file with the Apache-2.0 copyright and license
notice used by neighboring modules, before language pragmas. Keep the module's
Haddock introduction immediately before its declaration. License notices are
ordinary comments, not API documentation.
Use consistent comment banners, similar to the C sources, for meaningful groups:
```haskell
-- IMPORTS --------------------------------------------------------------------
-- TYPES ----------------------------------------------------------------------
-- DEFINITIONS ---------------------------------------------------------------
-- FOREIGN IMPORTS ------------------------------------------------------------
```
Use these general names consistently: `IMPORTS` for module imports, `TYPES` for
data and type declarations and their instances, `DEFINITIONS` for functions and
other value bindings, and `FOREIGN IMPORTS` for FFI declarations. Do not add
domain-specific banners, empty sections, or a banner per declaration. Small
modules need only the sections they use. Export-list Haddock headings may remain
domain-oriented for navigation in generated API documentation.
Keep functions focused on one responsibility. Prefer short orchestration functions
and named helpers for distinct validation, acquisition, execution, and conversion
steps. Roughly 20–30 lines is a review prompt, not a hard limit: never split a
resource scope or cancellation protocol merely to meet a line count. Helpers must
clarify intent and retain the same exception masking, cleanup, evaluation order,
and resource lifetime. Keep closely related local helpers local when that makes
their scope clearer. Name test scenarios instead of embedding long sequences in
the test tree; preserve lifecycle-test ordering where global counters require it.
Keep C headers out of Haskell source. Write native constants explicitly and record
their source in internal comments; verify them against the pinned headers in tests.
Keep ABI-dependent representation conversions in small C adapters. Do not replace
header-derived types with guessed platform sizes or signedness.