Skip to content
darkmatterPublic

About

Shared adhere rules

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

standards

Shared adhere rules for darkmatter's repositories. Each rule is a directory in .adhere/rules/ that holds a RULE.md, or a RULE.ts, and a repo that copies it in has Jev judge its files against it when it runs adhere lint.

Use these rules

List the rules, then copy them into a repo, all of them or one topic or rule:

adhere list darkmatter/standards
adhere install darkmatter/standards
adhere install darkmatter/standards/style
adhere install darkmatter/standards/style/prefer-small-files

The copies land in .adhere/rules/darkmatter/standards/ and are that repo's own from then on, to edit or to start other rules from. To take a later version of a rule, install it again with --force, which overwrites local edits.

Add a rule

Add a directory under .adhere/rules/<topic>/ with the rule in a RULE.md; its path is the rule's id. See Rules as Markdown files and the rule writing tips. adhere validate checks each rule's wording and asks Jev whether any two contradict. CI runs it on every push to main and every pull request.

Setup

alchemy.run.ts creates this repository on GitHub, or adopts it when it exists, and sets the TYPESAFE_API_KEY secret CI's adhere validate needs. Install, which init already did, deploy once, then push:

npm install
TYPESAFE_API_KEY=... npx alchemy deploy
git init && git add -A && git commit -m "Add shared adhere rules"
git remote add origin git@github.com:darkmatter/standards.git && git push -u origin main

Deploying again updates the secret, as after rotating the key.

Contents

Rules

ci

A workflow job in a private repository must run on a self-hosted runner label (linux, macos, arc, arc-dind, kvm, or arc-kvm), never on a GitHub-hosted runner such as ubuntu-latest. Jobs in public repositories may use any runner. In a private repository, a job that publishes to npm through npm trusted publishing may name a GitHub-hosted label that no self-hosted runner available to the repository carries, such as ubuntu-24.04, with a comment beside runs-on saying why. ci/use-self-hosted-runners

The organization runs its own runners, labeled linux, macos, arc, arc-dind, kvm, and arc-kvm. A job's runs-on names one of them, alone or with self-hosted, as in runs-on: [self-hosted, macos]. GitHub-hosted labels include ubuntu-*, windows-*, and macos-* with a version or -latest. The bare macos label is self-hosted, but macos-latest or macos-14 is GitHub-hosted. The rule covers workflow YAML anywhere: in .github/workflows/, in strings that generate a workflow, and in docs that show one. A runs-on that comes from a matrix or expression breaks the rule if any value it can take is a GitHub-hosted label.

The rule applies to workflows that run in a private repository. A workflow that runs in a public repository may use any runner, GitHub-hosted ones included: standard GitHub-hosted runners cost nothing in public repositories (https://docs.github.com/en/billing/concepts/product-billing/github-actions). A workflow file stored in one repository but run in another, such as a monorepo folder exported to its own repository, follows the visibility of the repository it runs in. In any repository, runs-on: ubuntu-latest may still land on darkmatter's self-hosted arc-ubuntu pool, which carries that label for every repository; a job that must run on GitHub's own machines names a versioned label such as ubuntu-24.04.

In a private repository, one kind of job may still use a GitHub-hosted runner: a job that publishes to npm through npm trusted publishing, with a comment beside runs-on that says why. Such a job signs in to npm with its OIDC token (id-token: write, granted on the job or on the workflow) instead of a stored npm token. npm accepts trusted publishing only from GitHub-hosted runners (https://docs.npmjs.com/trusted-publishers). The job names a GitHub-hosted label that no self-hosted runner available to the repository carries, such as ubuntu-24.04. It cannot use ubuntu-latest when a self-hosted runner also carries that label, as darkmatter's arc-ubuntu pool does: the job then runs on that runner, where trusted publishing fails. The exception looks like this:

jobs:
  publish:
    # npm trusted publishing works only on GitHub-hosted runners. Not
    # ubuntu-latest: darkmatter's self-hosted arc-ubuntu pool carries it too.
    runs-on: ubuntu-24.04
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@v7
      # No --provenance: npm refuses provenance from private repositories.
      - run: npm publish

Must
jobs:
  release:
    runs-on: arc
    steps:
      - uses: actions/checkout@v7

Never

In a private repository:

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

Source: ci/use-self-hosted-runners.

↑ Back to contents

design

Effect code must obtain each dependency from its context, as a yielded service, Config, or platform service, and must never read it from process, globalThis, or module scope, take a service or Context as a parameter, or create a service class inside a function. design/effect-declared-dependencies

A dependency that comes from the context appears in the Effect's requirements type. A layer can then replace it in tests or at the entry point. A dependency read from process or module scope, or passed in by hand, is hidden from that type, and nothing can substitute it.

Effect code here is a generator passed to Effect.gen or Effect.fn, a layer, or a function that returns an Effect. It also includes any module-scope value or helper that such code in the same file reads.

This rule covers these cases:

  • Reading process.env instead of Config. Reading process.cwd(), process.platform, process.stderr.columns, or globalThis instead of using a platform service such as Path or Terminal. Each of these breaks the rule inside a service, layer, or workflow, including as a fallback such as options.root ?? process.cwd(). It also breaks the rule in a module-scope value or helper that Effect code in the file reads, such as const columns = () => process.stderr.columns ?? 80.
  • A function that takes a service implementation (SourceWalker["Service"], FileSystem.FileSystem) or a Context.Context<...> as a parameter and provides or calls it. It should yield the service instead and keep it in its requirements.
  • A function that defines and returns a service class, such as const make = (args) => class Service extends Context.Service<...>()(...). A service is declared once, at module scope.

These do not break the rule:

  • A function that takes plain values, such as a path, and returns a layer for a service declared at module scope, such as (base?: string) => Layer.effect(AuditCache)(...).
  • Constants, schemas, and pure functions imported or declared at module scope. These are not dependencies.
  • A plain function that returns a value or a Promise rather than an Effect, when no Effect code in its file calls it, such as post(name, url, headers, body, signal, fetch = globalThis.fetch). A file that imports only Schema from effect may hold no Effect code at all.
  • The program's entry point, where the layers are assembled. A file that passes its main Effect to BunRuntime.runMain is one, whether it is the CLI or a script. It may read the process anywhere in that file. That includes module scope, such as const platform = `${process.platform}-${process.arch}`, and a layer built there, such as one checking process.stderr.isTTY. Its functions still must not take a service or a Context as a parameter.

Must
export const JevLive = Layer.effect(Jev)(
  Effect.gen(function* () {
    const config = yield* AdhereConfig;
    const credentials = yield* Credentials;
    const fetch = yield* FetchHttpClient.Fetch;
    const limiter = yield* RateLimiter.RateLimiter;

    const provider: Provider = config.provider ?? jev({ model: config.model, fetch });
  }),
);

Never
Effect.gen(function* () {
  const walker = yield* SourceWalker;
  const files = yield* walker.files;
  const root = options.root ?? process.cwd();
});

Source: design/effect-declared-dependencies.

Code should handle only the cases its real inputs produce, and should not handle edge cases those inputs do not produce, such as unused corners of a format or a recheck of what the program's own code already guarantees. design/no-speculative-edge-cases

Every branch for a case that does not happen is code someone has to read, test, and keep working, and it hides which cases matter. Leaving the case out costs less than carrying it. The rule holds for every line in the file, old or new: speculative handling already in the code is a finding too.

Speculative handling looks like parsing every form a spec allows when the inputs use one, such as tilde fences, indented headings, or closing # runs in Markdown whose format the project defines, or \u{...} and \x.. escapes in an import's module name. It also looks like a fallback for a value that cannot occur, such as a code point above 0x10FFFF, or validating again what the program's own launcher or caller already chose.

A case the program does meet is not an edge case, however rare it looks: the platforms it runs on (Windows names the home directory USERPROFILE), the file system it walks (a directory can be a symbolic link), or a dependency that can return less than it was given. Handling those is a requirement.

Should
export const adhereConfigDirectory = (path: Path.Path) =>
  Config.NonEmptyString("XDG_CONFIG_HOME").pipe(
    Config.orElse(() =>
      Config.NonEmptyString("HOME").pipe(
        Config.orElse(() => Config.NonEmptyString("USERPROFILE")),
        Config.map((home) => path.join(home, ".config")),
      ),
    ),
    Config.map((configHome) => path.join(configHome, "adhere")),
  );

Should not
const specifierOf = (token: Token): string => {
  const body = token.text.slice(1, -1);
  return body.replace(
    /\\(u\{[\da-fA-F]{1,6}\}|u[\da-fA-F]{4}|x[\da-fA-F]{2}|[\s\S])/g,
    (_, escaped: string) => {
      if (/^(?:u\{|u[\da-fA-F]{4}$|x[\da-fA-F]{2}$)/.test(escaped)) {
        const point = Number.parseInt(
          escaped.startsWith("u{") ? escaped.slice(2, -1) : escaped.slice(1),
          16,
        );
        return point <= 0x10ffff ? String.fromCodePoint(point) : `\\${escaped}`;
      }
      return ESCAPES[escaped] ?? escaped;
    },
  );
};

Source: design/no-speculative-edge-cases.

↑ Back to contents

modules

TypeScript rule modules/namespace-imports

This rule is TypeScript, so the guide does not read or run it: modules/namespace-imports.

↑ Back to contents

style

A function must be named after the domain action it performs, never after a generic verb like handle. style/name-domain-actions

Must
export const loadCustomerProfile = (customerId: CustomerId) =>
  Effect.gen(function* () {
    return yield* CustomerStore.find(customerId);
  });

Never

The code under Never shows what a violation looks like. It is optional, and a rule can have it without the code under Must.

export const handle = (id: string) =>
  Effect.gen(function* () {
    return yield* CustomerStore.find(id);
  });

Source: style/name-domain-actions.

A condition that combines several distinct checks should be named by a predicate function or constant that states the idea, and should not be written inline where its result is used. style/one-idea-per-line

People read code top to bottom more easily than left to right. A condition that chains several different checks with && or || makes the reader hold every check in mind at once to work out what it means. A name such as isBuiltin(name) or isNotFound(e) says the idea in one word. Move the checks into a predicate function or a named const, and use the name in the condition.

What counts as distinct checks: tests of different properties or methods, or different kinds of test, combined in one expression. For example, a type-guard chain like e && typeof e === "object" && "code" in e && e.code === "ENOENT", or startsWith calls mixed with an includes lookup. Splitting such a condition across several lines does not fix it. It still needs a name.

An inline use is anywhere the result is consumed directly: an if, an early-return guard, a ternary, or an anonymous callback passed to find, filter, some, or every whose body chains several distinct checks. Name the callback too, as in .find(isFileDescription).

These cases already follow the rule:

  • The compound expression is the whole body of a named predicate or the initializer of a named const. There the expression defines the name and is not an inline use.
  • The same check is repeated across sibling values, such as !accessKeyId || !secretAccessKey || !sessionToken || !expiration. That reads as one idea: one of the values is missing.
  • The condition is a single call, comparison, or negation, such as if (!(await pathExists(src))).

Should
const isRecord = (value: unknown): value is Record<string, unknown> =>
  typeof value === "object" && value !== null && !Array.isArray(value);

const strings = (value: unknown): Record<string, string> =>
  isRecord(value)
    ? Object.fromEntries(
        Object.entries(value).filter(
          (entry): entry is [string, string] => typeof entry[1] === "string",
        ),
      )
    : {};

Should not
if (name.startsWith("node:") || name.startsWith("bun:") || builtinModules.includes(name)) {
  return "builtin";
}

Source: style/one-idea-per-line.

A file should be small and focused, with one primary responsibility, and should not mix unrelated concerns. style/prefer-small-files

A guideline, so its description and its headings say should and should not. A rule that must hold says must and never instead, as name-domain-actions does. Use this rule as a template for repository-specific conventions.

Should
export const parsePort = (value: string) =>
  Port.make(Number.parseInt(value, 10));

Should not
export const parsePort = (value: string) => Port.make(Number.parseInt(value, 10));
export const sendWelcomeEmail = (to: Email) => Mailer.send(to, welcomeTemplate);
export const renderInvoice = (invoice: Invoice) => Html.table(invoice.lines);

Source: style/prefer-small-files.

↑ Back to contents

Lint settings

  • None.

Custom lint plugins

  • None.

↑ Back to contents

Shared CI checks

Story coverage provides a reusable action for new React component exports and existing story coverage. Consumers pin a reviewed commit and opt in through their CI configuration before making the check required.

About

Shared adhere rules

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages