Keyboard shortcuts

Press ← or → to navigate between chapters

Press ? to show this help

Press Esc to hide this help

prim

prim is a single-binary, opinionated, near-zero-config formatter for a repository’s connective tissue — Markdown, JSON/JSONC, YAML, TOML — plus whitespace hygiene on a curated set of un-owned text files.

It is not a source-code formatter and has no plugin system. Think of it as the tool that tidies the files no other formatter owns.

  • One canonical style. No prim.toml, no per-rule knobs — prim honors .editorconfig and nothing else.
  • Semantics-preserving. prim never reorders keys, table entries, or array elements, and never changes the parsed data model of a document.
  • Safe by default. Unparseable or non-UTF-8 files are left byte-for-byte unchanged and reported.

Project status

All v1 requirements are implemented: recursive file discovery, the format-agnostic whitespace hygiene pass (trailing-whitespace removal, single final line-feed, LF endings, leading-BOM strip), .editorconfig style resolution, and structured formatting for JSON/JSONC, YAML, TOML, and Markdown (with prose-wrap guardrails) — all wired through the prim-fmt engine. prim formats its own Markdown.

Beyond v1, prim also ships prim lint (hygiene plus Markdown content diagnostics, with JSON/SARIF machine-readable output), prim fix, prim init (.editorconfig scaffolding), prim explain (per-file config provenance), and prim lsp (an LSP formatting-and-diagnostics server for editor integration). See the Specification for the full v1 scope and Usage for the complete command reference.

Getting started

Install

curl -sSfL https://raw.githubusercontent.com/driftsys/prim/main/install.sh | bash

This downloads the prebuilt prim binary for your platform, verifies its SHA-256 checksum, installs it to ~/.local/bin, and sets up shell completions.

From crates.io

cargo install prim-cli

The crate is prim-cli; the installed binary is prim.

For the full platform matrix, manual download with checksum verification, and building from source, see Installation.

First run

prim --version
prim --help

prim formats files in place, or a whole directory tree:

prim README.md config.yaml   # specific files
prim .                       # the current directory, recursively

Note: prim applies both whitespace hygiene (trailing-whitespace removal, single final line-feed, LF endings, leading-BOM strip) and structured per-format formatting (JSON/JSONC, YAML, TOML, Markdown) to every file it owns — see What prim formats for the full allowlist.

Installation

prim ships as a single self-contained binary named prim. Pick whichever method suits your platform; all of them install the same binary.

Supported platforms

Prebuilt binaries are published for each release and cover:

PlatformArchitectureTarget triple
Linuxx86-64x86_64-unknown-linux-musl
LinuxARM64 / aarch64aarch64-unknown-linux-musl
macOSIntel (x86-64)x86_64-apple-darwin
macOSApple Silicon (M-series)aarch64-apple-darwin
Windowsx86-64x86_64-pc-windows-msvc

The Linux builds are statically linked against musl, so they run on any distribution without a libc dependency. Any platform with a Rust toolchain can also build prim from source or install it from crates.io.

curl -sSfL https://raw.githubusercontent.com/driftsys/prim/main/install.sh | bash

The script detects your platform, downloads the matching prebuilt from the latest GitHub release, verifies its SHA-256 checksum, installs the binary, installs the man page, and sets up shell completions.

It respects two environment variables:

VariableDefaultPurpose
PRIM_INSTALL_DIR~/.local/binWhere the prim binary lands.
PRIM_MAN_DIR~/.local/share/man/man1Where the man page lands.
# Install to /usr/local/bin instead:
curl -sSfL https://raw.githubusercontent.com/driftsys/prim/main/install.sh \
  | PRIM_INSTALL_DIR=/usr/local/bin bash

If the install directory is not on your PATH, the script prints a note; add it (for example export PATH="$HOME/.local/bin:$PATH") to your shell profile.

Windows: the install script targets Unix shells. On Windows, either use it under WSL or download the binary manually. A native x86_64-pc-windows-msvc build is published with every release.

From crates.io

cargo install prim-cli

The crate is named prim-cli; the installed binary is prim. This compiles prim locally, so it works on any target with a Rust toolchain — including ones without a prebuilt.

Manual download

Every release attaches exactly one prim-<target>.tar.gz archive and matching prim-<target>.tar.gz.sha256 checksum for each supported target. Those names are stable and version-addressable below releases/download/<tag>/. The checksum file names the archive by its base name, so it can be verified after downloading both files into any directory. To install by hand:

VERSION=v1.0.0                  # the release tag you want
TARGET=aarch64-apple-darwin     # your target triple from the table above
BASE="prim-$TARGET"
URL="https://github.com/driftsys/prim/releases/download/$VERSION"

# Download the tarball and its checksum.
curl -sSfLO "$URL/$BASE.tar.gz"
curl -sSfLO "$URL/$BASE.tar.gz.sha256"

# Verify (use `shasum -a 256 -c` on macOS if `sha256sum` is absent).
sha256sum -c "$BASE.tar.gz.sha256"

# Unpack and install onto your PATH.
tar -xzf "$BASE.tar.gz"
install -m 0755 prim ~/.local/bin/prim

Each tarball also contains prim’s man page (prim.1); copy it into a man1 directory on your MANPATH if you want man prim.

Release signatures, SBOM, and provenance

Starting with v0.9.0, releases use this contract. v0.8.0 supplies the five platform archives and their checksums; it does not supply the signature, SBOM, or provenance assets described below. A supporting release is published only after its tagged hosted build passes the verification gate.

Each supporting release contains exactly 22 assets: four per supported target and two for the release as a whole.

AssetPurpose
prim-<target>.tar.gzBinary and man page archive.
prim-<target>.tar.gz.sha256SHA-256 checksum naming that archive.
prim-<target>.tar.gz.sigstore.jsonKeyless cosign signature bundle.
prim-<target>.tar.gz.provenance.sigstore.jsonGitHub SLSA build-provenance bundle.
prim-<version>.spdx.jsonRelease-wide SPDX 2.3 source/dependency SBOM.
prim-<version>.spdx.json.sigstore.jsonKeyless signature bundle for the SBOM.

<version> omits the tag’s leading v. All assets are directly addressable under https://github.com/driftsys/prim/releases/download/v<version>/; Folio and other pinned-binary consumers do not need to run install.sh.

The reusable release-build.yml workflow builds, packages, signs, and attests each archive. The caller release.yml generates the SBOM from the tagged source and Cargo.lock using Syft v1.51.1, requires spdxVersion to equal SPDX-2.3, and signs it. Consequently archive signatures identify the reusable workflow, while the SBOM signature identifies the caller.

To verify an archive from a supporting release, install cosign v3 and the GitHub CLI, authenticate gh, and run:

VERSION=vX.Y.Z                 # replace with a supporting release tag
TARGET=aarch64-apple-darwin
ARCHIVE="prim-$TARGET.tar.gz"
URL="https://github.com/driftsys/prim/releases/download/$VERSION"
IDENTITY="https://github.com/driftsys/prim/.github/workflows/release-build.yml@refs/tags/$VERSION"
COMMIT=$(gh api "repos/driftsys/prim/commits/$VERSION" --jq .sha)

for ASSET in "$ARCHIVE" "$ARCHIVE.sha256" "$ARCHIVE.sigstore.json" "$ARCHIVE.provenance.sigstore.json"; do
  curl -sSfLO "$URL/$ASSET"
done
shasum -a 256 -c "$ARCHIVE.sha256"
cosign verify-blob --bundle "$ARCHIVE.sigstore.json" \
  --certificate-identity "$IDENTITY" \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com \
  "$ARCHIVE"
gh attestation verify "$ARCHIVE" \
  --bundle "$ARCHIVE.provenance.sigstore.json" \
  --repo driftsys/prim \
  --signer-workflow driftsys/prim/.github/workflows/release-build.yml \
  --source-ref "refs/tags/$VERSION" --source-digest "$COMMIT" \
  --signer-digest "$COMMIT" --deny-self-hosted-runners \
  --format json > verified-provenance.json
DIGEST=$(shasum -a 256 "$ARCHIVE" | cut -d ' ' -f 1)
jq -e --arg name "$ARCHIVE" --arg digest "$DIGEST" '
  length > 0 and all(.[];
    .verificationResult.statement.subject == [{name: $name, digest: {sha256: $digest}}]
  )' verified-provenance.json

gh attestation verify validates SLSA v1 provenance and the archive digest. The additional assertion requires the verified statement’s subject name and digest to match exactly. These checks follow the GitHub CLI verification contract. Verify the release-wide SBOM using its caller identity:

SBOM="prim-${VERSION#v}.spdx.json"
curl -sSfLO "$URL/$SBOM"
curl -sSfLO "$URL/$SBOM.sigstore.json"
jq -e '.spdxVersion == "SPDX-2.3"' "$SBOM"
cosign verify-blob --bundle "$SBOM.sigstore.json" \
  --certificate-identity "https://github.com/driftsys/prim/.github/workflows/release.yml@refs/tags/$VERSION" \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com \
  "$SBOM"

The release verifier checks the exact asset set, checksums, signature identities and issuer, provenance signer/source commit and tag, verified subjects, and SPDX version. It also requires the tag’s commit to be an ancestor of origin/main. Both GitHub Release and crates.io publication depend on this job. GitHub Release downloads the verifier’s immutable artifact ID and publishes those bytes without repackaging them. install.sh continues to verify SHA-256 only.

These checks do not by themselves establish SLSA Build Level 3. Protected branch, tag, and release ruleset controls must be inspected to establish that the tagged commit and reusable workflow were reviewed and cannot be replaced by an unreviewed caller. That inspection, together with hosted OIDC signing and verification evidence, is required to establish #55’s provenance level. No SLSA level is claimed until those controls and run evidence have been reviewed and recorded. The existing pull-request and scheduled cargo audit CI gate remains in place.

From source

git clone https://github.com/driftsys/prim
cd prim
./bootstrap          # installs git-std and configures git hooks
cargo build --release

The binary is written to target/release/prim.

After installing

  • Verify: prim --version.
  • Shell completions and the man page are set up automatically by the install script; for other methods, generate completions yourself with prim --completions <shell> (see Usage).

Usage

prim [fmt|lint|fix] [OPTIONS] [PATH]...
prim init [PATH]
prim explain <PATH>
prim registry --format json
prim lsp

prim exposes three formatting verbs (AD-0007) plus four utilities: init (repo setup), explain (config introspection), registry (diagnostic introspection), and lsp (a format-on-save language server). Bare prim [PATH]... is a permanent alias for prim fmt [PATH]... — no verb is required for the common case.

CommandWrites?Purpose
fmtyes (in place)Format the parsed formats + whitespace hygiene. Default action.
lintneverReport hygiene and content violations only.
fixyes (in place)fmt plus autofixable content rules (none yet, so fix is currently identical to fmt).
init.editorconfig onlyScaffold or minimally merge prim’s Markdown strict-glob map.
explainneverPrint the .editorconfig settings that apply to one file, and where each came from.
registryneverPrint the versioned diagnostic catalog as JSON without inspecting files.
lspnever (returns edits)Run an LSP formatting server over stdio for editor format-on-save.

Arguments

ArgumentDescription
[PATH]...Files or directories to process. Directories are searched recursively (honoring .gitignore/.git/info/exclude/global gitignore/.ignore/.primignore by default); defaults to the current directory when omitted.

Explicit-file delegation

An orchestrator that already owns repository walking and file selection can pass its exact batch to prim:

prim fmt FILE...
prim fmt --check --format json FILE...
prim fmt --dry-run --format json FILE...
prim lint --format json FILE...
prim fix FILE...
prim fix --dry-run --format json FILE...

For file arguments, prim processes only the named paths; it does not search a file’s parent or add siblings. Passing a directory is different: it explicitly asks prim to perform its normal recursive discovery. Relative and absolute file paths are accepted, including paths containing spaces.

Delegation does not bypass prim’s safety boundary. .primignore, --exclude, generated-file protection, and symlink refusal still apply. Unsupported files are skipped, so shell files are never formatted or linted by prim. A named, owned file that is malformed or unreadable is left byte-for-byte unchanged and makes the command exit 2. The effective .editorconfig style is resolved for each accepted path at invocation time; a caller that needs reproducible output must keep both the input bytes and that configuration unchanged between a preview and a write.

Options

FlagVerbsDescription
--checkfmt, fixWrite nothing; exit non-zero if any file would change, and list it.
--difffmt, fixPrint a unified diff of pending changes; write nothing. Exit 0 on fmt regardless of pending changes; exit non-zero on fix if a fixable finding is pending (shares fix --check’s gated contract).
--check-idempotencefmtWrite nothing; for each matched prim-owned file, format it in memory twice with the resolved .editorconfig style and exit non-zero if the second pass still changes bytes.
--dry-runfmt, fixWrite nothing and emit an exact whole-file replacement plan. Requires --format json.
--format <json|sarif>fmt --check, lintEmit machine-readable findings to stdout instead of the default plain-text report. --dry-run and registry accept JSON only.
--stdin-filepath <PATH>fmt, lint, fixRead stdin and process it (format-on-save for fmt/fix; report for lint). Mutually exclusive with --check/--diff.
--exclude <GLOB>allExclude paths matching the glob (repeatable). A malformed glob is a usage error.
--no-ignorefmt, lint, fixDisable only VCS ignore files (.gitignore, global gitignore, .git/info/exclude). .primignore, --exclude, and the .git/ directory prune still apply.
--no-primignorefmt, lint, fixDisable .primignore, including for paths named on the command line. VCS ignore files, --exclude, and the .git/ directory prune still apply.
--since <REF>fmt, lint, fixLimit the file set to git diff --name-only <REF>: paths that differ between <REF> and the current working tree, including staged and unstaged changes (plain two-way diff, no merge-base comparison).
--stagedfmt, lint, fixLimit the file set to git diff --name-only --cached: paths staged in the git index relative to HEAD. Mutually exclusive with --since.
--color <auto|always|never>allWhen to use coloured output (default auto; auto honors NO_COLOR).
--completions <SHELL>globalGenerate a shell completion script and print it to stdout.
-h, --helpglobalPrint help.
-V, --versionglobalPrint version.

The top-level --check, --diff, and --stdin-filepath flags remain accepted directly on bare prim as deprecated sugar for the fmt forms: the first use in a run prints a one-line deprecation warning to stderr. They are scheduled for removal in v2.0 — the bare fmt alias itself is not deprecated.

Exit codes

CodeMeaning
0Nothing to do, or already clean.
1Actionable: format drift, a planned replacement, or a lint finding.
2prim could not do its job (parse, I/O, or usage error).

Warnings never raise the exit code; only errors do. A gate that was pointed only at skipped paths examined nothing, and exits 2 rather than 0 (FR-4.4c).

These three are the whole contract. A path that is not valid UTF-8 reaches the filesystem as the bytes you gave, so naming one formats it like any other file; a non-UTF-8 --exclude glob or --since ref is still a usage error, because those are matched as text. A panic inside a formatter or the Markdown linter is caught per file: that file is reported, left byte-for-byte unchanged, and the run carries on to the next one, ending at 2. Under --stdin-filepath your buffer is echoed back unchanged rather than lost, and the LSP returns no edits and keeps the session. A --format run still emits its document. The panic also prints its own message, which is what to include in a bug report.

Operating modes

  • fmt (default) — format the given files in place.

  • fmt --check (also fix --check) — a CI gate: exit 1 and list the files that would change. Add --format json or --format sarif to emit the same findings as a machine-readable report instead of the default path list.

  • --no-ignore — keep prim’s own filters (.primignore, --exclude, and .git/ pruning) but ignore VCS ignore files so paths hidden by .gitignore, global gitignore, or .git/info/exclude are walked again.

  • --no-primignore — the opposite switch: keep VCS ignore files but drop .primignore. Needed only to process a path .primignore covers, since that file is honoured however prim is invoked — walked to or named on the command line (AD-0009), and under gitignore’s own rules: a ! line cannot re-include a file when a directory holding it is excluded, so fixtures/ followed by !fixtures/keep.md leaves keep.md covered. This same flag also disables the built-in generated-file list (AD-0011), which behaves as the outermost .primignore layer. Naming an ignored path without this flag prints a warning and changes nothing; warnings never raise the exit code. The one case that does is a gate — fmt --check, fix --check, fix --diff, fmt --check-idempotence, or lint — where every path prim was pointed at is skipped: prim then examined nothing, so it reports an error and exits 2 instead of reporting a clean run (FR-4.4c).

  • --since <REF> — limit discovery to the paths git diff --name-only <REF> reports: files that differ between <REF> and the current working tree, including both staged and unstaged changes. prim uses the plain two-way git diff <REF> semantics here — no merge-base (...) comparison. <REF> is read only as a revision: one git cannot resolve exits 2 rather than taking effect as a git option or a pathspec (FR-4.2f), and -- is rejected because it is git’s revision separator. This fencing needs git 2.24 or newer.

  • --staged — limit discovery to the paths git diff --name-only --cached reports: files staged in the git index relative to HEAD. It chooses paths only: a write mode still writes the working tree and never touches the index, so prim warns on stderr when it writes under --staged and leaves re-staging to the hook runner (FR-4.2c, FR-4.2d). The warning reports what prim wrote, not what the index holds — prim never reads the staged blob — and points at git diff, where the unstaged result shows up. It does not raise the exit code.

  • Undecodable paths — prim reads the paths git reports as bytes, so a filename that is not valid UTF-8 is selected and formatted like any other where the platform permits one. Where it does not, prim exits 2 naming the path rather than skipping it silently. Naming one directly on the command line works the same way. The fmt --check list and plain-text lint findings carry such a path as the bytes the filesystem holds, so the name prim prints is a name that opens; --format json adds path_encoded beside the lossy path, and --format sarif percent-encodes its uri. Two stdout writers still render a path lossily and are not covered: the fmt --diff patch header and prim explain. Human-facing messages on stderr stay lossy too, because a terminal cannot render an undecodable byte.

    Piping the list needs a newline delimiter, because bare xargs splits on spaces and interprets quotes. xargs -d '\n' is a GNU extension and is rejected by the BSD xargs on macOS; | tr '\n' '\0' | xargs -0 works on both. A filename containing a newline is legal and cannot be expressed in a newline-delimited list at all; there is no NUL-separated output mode.

  • Changed-file filters — --since and --staged are mutually exclusive. They compose by intersection with --check, --diff, lint, fix, explicit path arguments, .primignore, --exclude, --no-ignore, and --no-primignore. Paths git reports as deletions are skipped silently; any other path git reports that prim cannot find on disk is a usage error (exit 2), not a silent skip, and both flags require the current working directory to be inside a git working tree.

  • fmt --diff — preview pending changes without writing; always exits 0 (--check is the CI gate).

  • fmt --check-idempotence — a formatter self-check: prim formats each matched file in memory, reformats that output with the same resolved style, and exits 1 only if the second pass still changes bytes. It never writes to disk, even when the original file is not already in canonical form. Bare prim --check-idempotence [PATH]... works too through the permanent fmt alias.

  • fix --diff — preview pending changes without writing, like fmt --diff, but exits 1 if a fixable finding is pending — fix’s --check and --diff share one gated contract (AD-0007 §4), unlike fmt --diff’s preview-only behaviour.

  • lint — report-only: prints one finding per violation and never rewrites.

    • For the un-owned-text allowlist (BOM, line endings, trailing whitespace, indentation, missing final newline — same set .editorconfig/hygiene covers), each finding is a coded, positioned diagnostic: path:line:col: message [code] (e.g. notes.txt:1:6: trailing whitespace [hygiene::trailing-whitespace]).

    • For Markdown, prim lint runs rumdl in Standard flavor against prim’s own curated rule set, placed into two bands and selected per file through .editorconfig prim_mdlint_strict = true|false (default false). false runs the always-on floor tier of 12 defect rules; true adds 13 convention rules on top. Every rule prim runs, at either tier, is an error — there is no warning severity for Markdown, so a finding’s presence is its severity. prim prints each finding as path:line:col: message [MD0xx], passes rumdl’s rule codes through verbatim, never invokes rumdl’s formatter/fixer, and does not auto-fix these findings in fix yet.

      • Floor tier — defect rules (always on, error at floor and strict): MD011, MD034, MD042, MD045, MD051, MD052, MD056, MD062, MD066, MD068, MD070, MD075. Each reports something objectively broken — a dead link, a dangling reference, a malformed table — so it gates every repository with no opt-in.

      • Strict tier — convention rules (prim_mdlint_strict = true only, error when active): MD001, MD024, MD025 (SUMMARY-safe via .editorconfig; front-matter title excluded by default, see below), MD026, MD033, MD036, MD040, MD041, MD053, MD059, MD067, MD073, MD080. Each is decidable but fires on documents that are otherwise fine, so it gates only once a repository opts in.

      • Never linted (formatter territory): MD003-005, MD007, MD009, MD010, MD012, MD018-023, MD027-032, MD035, MD037-039, MD046-050, MD055, MD058, MD060, MD064, MD065, MD071, MD076, MD077.

      • Off in both tiers: MD014, MD043, MD044, MD054, MD061, MD063, MD069, MD072 (frontmatter key sorting stays off because prim must remain semantics-preserving), MD074, MD078, MD079, MD081, MD057 (dropped — a cross-file link’s target depends on the renderer, so prim does not check it; see AD-0013), and MD082 (dropped entirely — see AD-0012). A rule rumdl adds after this census was drawn is off in both tiers until a record places it; at rumdl 0.2.66 that is MD083-MD089 and MD091 (#194). MD051 does not see a heading written as raw HTML (<h2>): rumdl computes no anchor for it, so a link to that anchor is reported.

      • Line length (prim_mdlint_report_line_length): max_line_length (default 80) already controls how prim wraps Markdown prose. Setting prim_mdlint_report_line_length = true additionally makes prim lint report lines that exceed it.

        prim reports only the long lines that can actually be shortened. A long prose line is reported — prim fmt wraps prose to the same limit, so a repository that formats with prim sees no prose findings. Table rows, fenced code, and an inline code span with no internal space are never reported: a line break cannot be inserted into any of them without changing what the document means, so there is nothing to fix.

        Headings are the one case decided by the tier. prim cannot wrap a heading — a line break would end the heading and turn the rest into a paragraph — but you can shorten the wording. So a long heading is reported when prim_mdlint_strict = true, and silent otherwise, like every other convention-tier check. Note that rumdl measures a heading only up to its last whitespace, so the effective slack is the length of the final word: at an 80-column limit an 84-column heading is silent and an 86-column one is reported. Do not adopt this key expecting headings held to exactly max_line_length.

        The limit is whatever max_line_length resolves to for that file, so no .editorconfig cascade can leave the formatter and the linter disagreeing about the width. If your headings are long by convention — numbered decision records, for example — keep those files at the floor tier.

        Line contentFloorStrict
        Prosereportedreported
        Headingsilentreported
        Table rowsilentsilent
        Fenced or indented codesilentsilent
        Long only because of unbreakable inline codesilentsilent

        This is MD013, the one rule prim excludes from both tiers by default and lets a repository switch on, because it is the only rule whose options must track the formatter’s own line width. prim sets five of MD013’s options and exposes none of them: line-length from the resolved max_line_length, code-blocks, code-spans and tables off, and headings on at the strict tier only. Every other MD013 option keeps rumdl’s default — including ignore-link-urls, which is why a line that is long only because of a link URL is usually not reported; prim does not pin that one, so treat it as rumdl’s behaviour rather than prim’s guarantee.

        There is no .editorconfig key for any of these options. A single file can still override them with rumdl’s own markdownlint-configure-file directive, the same per-file escape hatch every other rule prim runs already has (AD-0012). It can change the width or re-enable the table and code checks for that one file; it cannot switch MD013 on where prim_mdlint_report_line_length has not. prim_mdlint_disable = MD013 turns the rule off again for a narrower glob, the same way it removes any other rule.

      • Floor-tier and strict-tier findings alike raise prim lint’s exit code to 1; no Markdown rule emits a warning.

      • Rule options prim sets for itself: prim configures MD025’s front-matter-title option to an empty string, so a page’s front-matter title: is treated as metadata rather than a heading, and — when prim_mdlint_report_line_length selects it — five of MD013’s options. These are prim’s own canonical defaults for rules it runs. A repository reaches only two of them, both MD013’s and both named by FR-3.3: max_line_length supplies line-length, and prim_mdlint_strict supplies headings. No other option of any rule is reachable — see “Configuration” below, AD-0012 and AD-0014.

      • Per-file override (story G5): a standalone <!-- prim-mdlint-strict: true|false --> line anywhere in the file overrides .editorconfig’s resolved tier for that file only — an escape hatch for the rare file that needs to differ from its glob (e.g. opt a legacy doc out of a docs/**.md strict glob, or opt one file into strict without a matching glob). The line must be the whole line once trimmed; if several are present, the last one wins; an unrecognized value (anything but true/false, case-insensitive) is ignored and falls back to the .editorconfig-resolved tier.

      • Per-glob rule exclusion: .editorconfig prim_mdlint_disable removes named rules from whichever tier a path already runs — see “Configuration” below.

      • rumdl’s own inline directives work as-is — prim calls rumdl_lib::lint directly, which applies them before returning findings, so no prim-side wiring was needed:

        DirectiveScope
        <!-- markdownlint-disable-file MD033 -->file
        <!-- markdownlint-disable MD033 --> … -enableblock
        <!-- markdownlint-disable-next-line MD033 -->one line
        <!-- rumdl-disable-file MD033 -->file
    • JSON/JSONC/YAML/TOML still report the coarser format drift fmt --check would report; their own content diagnostics are future work.

    • Add --format json or --format sarif to switch stdout from the plain-text report above to a machine-readable document carrying the same findings (hygiene, Markdown, and format-drift alike).

  • --stdin-filepath — editor format-on-save: stdin in, formatted stdout out (fmt/fix), or a report (lint).

  • Naming a path explicitly is strict: a missing file is an error (exit 2); an existing file prim does not own is skipped with a warning.

  • A symbolic link is a path prim does not own, so naming one skips it with a warning and leaves both the link and the file it points at untouched — a dangling link included, which is skipped for its type rather than reported as missing. Writes are a temporary file plus a rename, so following a link would replace it with a regular file. Name the file the link points at to format it. A path that merely goes through a symlinked directory is formatted as usual; only a link at the end of the path is skipped.

prim init

prim init [PATH] scaffolds or minimally merges .editorconfig in PATH (default .). It writes no other file. Where that .editorconfig is a symbolic link, prim writes nothing and exits 2: the write is a temporary file plus a rename, so it would replace the link and leave the shared config it points at without the merge. Run prim init on the directory holding that file instead.

With no existing .editorconfig, prim writes this exact placement map when no mdBook is detected:

root = true
[*.md]
prim_mdlint_strict = false
[docs/**.md]
prim_mdlint_strict = true
[docs/wip/**.md]
prim_mdlint_strict = false
[docs/archive/**.md]
prim_mdlint_strict = false
[**/SUMMARY.md]
prim_mdlint_strict = false

Section order is part of the contract: EditorConfig has no specificity ranking, so the broader [*.md] floor must appear before the stricter middle section, [docs/wip/**.md] and [docs/archive/**.md] must come after it to opt working memory back down, and [**/SUMMARY.md] must come last to opt mdBook summaries back down. [docs/wip/**.md] and [docs/archive/**.md] are literals, not derived from the strict glob: Superpowers specs and plans live under docs/wip/ while a branch is open, and gardening moves the raw originals to docs/archive/. That move is not an edit, so it must not change a document’s lint tier — otherwise filing work away is what makes a repository’s own CI start failing on it. (A repository that does want its archive linted can write prim_mdlint_strict = true under that section; prim init leaves an explicit choice alone on every later run.)

If PATH/book.toml exists, prim reads [book].src and uses that directory for the strict middle glob instead of docs/; for example, src = "guide" yields [guide/**.md]. If book.toml is present but omits src, or is malformed, prim falls back to mdBook’s conventional src/**.md.

If .editorconfig already exists, prim merges in place without reordering unrelated content:

  • leaves an existing top-level root = ... untouched; otherwise prepends root = true and a blank line
  • for [*.md], the detected strict glob, [docs/wip/**.md], [docs/archive/**.md], and [**/SUMMARY.md], leaves an existing explicit prim_mdlint_strict = ... untouched
  • if one of those sections exists but lacks the key, appends the key inside that section immediately before the next section (or end-of-file)
  • if one of those sections is missing entirely, inserts a new block without moving existing bytes so the final prim-managed order still reads [*.md] → strict glob → [docs/wip/**.md] → [docs/archive/**.md] → [**/SUMMARY.md] (falling back to end-of-file only when no later prim-managed section needs to stay after it)
  • if a section is missing and the file’s own existing section order already contradicts that canonical order — for example an existing [**/SUMMARY.md] written before the strict glob — there is no position left for the missing section; prim leaves it out and prints a warning naming the two conflicting sections, the lines they start at, and where to add the section by hand

Before it writes anything, prim resolves the file it would produce. For one representative path per canonical section it places — a top-level file, a file under the strict glob, a file under docs/wip/ where that section applies, a file under docs/archive/ where that section applies, and a SUMMARY.md — it applies EditorConfig’s last-match-wins section order and compares the result with the value it intended and with the value that path resolved to before the run. prim makes a write only when the path that write is meant to place lands on the intended value and none of the other representative paths moves. (The check is over prim’s own canonical globs: a glob you wrote that none of those paths stands for is not covered.) A write that would fail that check is not made: prim warns, naming the path and the value it would take, and still makes whatever other writes are safe. prim never reorders sections a person wrote, so a file whose own order contradicts the canonical one is reported and left for you to fix. An existing .editorconfig prim cannot parse at all is reported and left untouched — with no resolution there is nothing to check a change against.

prim also resolves every canonical section the file already carries prim_mdlint_strict for, not only the ones it plans to write, checking each against the same representative paths. A section fails that check three ways: a later section sets a different value and wins, so the wrong tier applies to the section’s own paths; a later section sets the same value and wins anyway, so the earlier section decides none of those paths even though nothing resolves incorrectly today; or the value itself is not true or false, which EditorConfig reads as false silently. Each is a warning naming the section, the line it starts at, and the section that decides instead — never a refusal, since a person’s own narrower override is legitimate and prim will not reorder sections a person wrote. When any of these warnings fires, the summary line reads .editorconfig left unchanged — see the warning(s) above instead of .editorconfig already contains the Markdown strict-glob map, even on a run that writes nothing, because the two are different outcomes.

prim init writes the whole file under one line ending: the end_of_line that resolves for .editorconfig once the write has been made, which is LF unless the file prim writes itself sets end_of_line = crlf (FR-2.3). It does not carry an existing file’s line endings through — merging LF additions into a CRLF file would leave mixed endings, and a uniformly CRLF file with no end_of_line key is a file that prim fmt --check reports.

The ending is resolved after the write rather than before, because the root = true that prim init writes stops EditorConfig’s upward walk: an end_of_line declared by an ancestor no longer reaches the file once prim has written it. So a scaffold placed under a CRLF-declaring parent is written LF, which is what prim fmt then resolves for it. A run that writes nothing — the map is already present — leaves the file exactly as it found it, line endings included.

Running prim init twice is idempotent: once the map is present, the second run reports a no-op and leaves .editorconfig byte-identical. An occurrence of one of those globs that neither sets prim_mdlint_strict nor receives it — an ordinary [*.md] max_line_length = 80 appended after a map that already sets the key — takes no part in prim’s ordering, so it never makes prim init refuse to work.

Running prim init in a subdirectory

EditorConfig requires root = true at the top of the file prim writes, and root = true stops EditorConfig’s upward walk — for every key and every file type, not just prim’s own. In a subdirectory of a repository that already has an .editorconfig, that means everything the parent configured stops reaching the files below:

$ prim explain sub/a.md | grep max_line_length
  max_line_length = 120  (.editorconfig:3 [*.md])
$ prim init sub
warning: sub: prim wrote root = true, which EditorConfig requires here, so files
under this directory no longer inherit from .editorconfig — the keys set there
(max_line_length) no longer reach this directory. Delete the root = true line to
keep inheriting them.
$ prim explain sub/a.md | grep max_line_length
  max_line_length = unset  (prim's default)

prim still makes the write — the root = true line is mandated, and prim init cannot know whether you wanted the parent cascade. Delete that line if you did.

The warning names every ancestor .editorconfig that becomes unreachable and every key those files set in a section. It lists what those files set, not what applied to any particular file below, so a section whose glob matches nothing here is still named. An ancestor that carries only root = true is left out, because cutting the walk off from it loses nothing, and so is a key written before the first section header, because EditorConfig never applied it. Running prim init at the top of a repository, where there is nothing above to inherit from, prints no warning.

prim explain

prim explain <PATH> prints every .editorconfig setting that applies to PATH, its effective value, and where that value came from: a specific .editorconfig file and line (with the [glob] section it came from, when one could be recovered), or prim's default when no .editorconfig entry set it. PATH need not exist — resolution is name/extension-based, the same classification fmt/lint/fix use, so explain also works for a not-yet-created file to preview what settings it would get.

Given a .editorconfig such as:

root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 2

[*.md]
max_line_length = 80

[docs/**.md]
prim_mdlint_strict = true
prim_mdlint_disable = MD033, MD041

prim explain prints:

$ prim explain docs/USAGE.md
docs/USAGE.md
  end_of_line                    = lf         (/repo/.editorconfig:5 [*])
  trim_trailing_whitespace       = true       (/repo/.editorconfig:7 [*])
  insert_final_newline           = true       (/repo/.editorconfig:6 [*])
  indent_style                   = space      (/repo/.editorconfig:8 [*])
  indent_size                    = 2          (/repo/.editorconfig:9 [*])
  max_line_length                = 80         (/repo/.editorconfig:12 [*.md])
  prim_mdlint_strict             = true       (/repo/.editorconfig:15 [docs/**.md])
  prim_mdlint_report_line_length = false      (prim's default)
  prim_mdlint_disable            = MD033, MD041 (/repo/.editorconfig:16 [docs/**.md])

(prim’s own .editorconfig sets prim_mdlint_strict in several sections and sets neither prim_mdlint_disable nor prim_mdlint_report_line_length, so running this against the repository prim ships in prints the tier resolved for that path and unset/false (prim's default) for the other two — see below.)

The settings shown depend on the file’s kind: un-owned text files (the Orphan allowlist) only get the three universal hygiene settings (end_of_line, trim_trailing_whitespace, insert_final_newline); Markdown additionally shows prim_mdlint_strict, prim_mdlint_report_line_length and prim_mdlint_disable. When prim_mdlint_disable was never set for a path, its value prints unset against prim's default. When it was set but resolves to no rules — a deliberate prim_mdlint_disable = none or = unset, or a list whose every id was unrecognised (which also warns on stderr) — the value prints none against the .editorconfig line that set it, because that is what prim applies there. A path prim does not format at all reports a warning (not a file type prim formats; skipped) and prints no settings, but still exits 0 — explain never gates a build. A symbolic link is reported the same way, for the same reason: prim would never apply those settings to it.

prim lsp

prim lsp runs a Language Server Protocol server over stdin/stdout, exposing prim’s formatter as a document formatting provider. Point an editor’s LSP client at it and prim formats prim-owned files through the editor’s native format-on-save, running the exact same engine as prim fmt — an editor save and a CLI run produce byte-identical output.

It is deliberately narrow: it advertises only whole-document formatting and Full document sync (it never splices incremental edits) — plus, as of G5’s follow-up story, textDocument/publishDiagnostics for the same findings prim lint already reports: whitespace-hygiene diagnostics (B1) for un-owned text files and rumdl Markdown content diagnostics (G2), reprojected onto LSP’s range/severity shape. It still does not publish completions, hover, or semantic highlighting — prim is a formatter, not a general language server. Diagnostics are republished (even as an empty list) on every didOpen/didChange, and cleared with an empty list on didClose, so stale findings never linger once a file is fixed or closed. Structured formats (JSON/JSONC/YAML/TOML) have no itemized diagnostics yet — the same scope prim lint covers for those kinds today.

Requesting to format a file prim does not own, or one that is already canonical, returns no edits; a file prim cannot parse is left untouched (no edits), matching --stdin-filepath’s fail-safe contract.

The server honors .editorconfig exactly as the CLI does; the client’s FormattingOptions (tab size, insert-spaces) are ignored in favour of prim’s resolved style.

VS Code

prim has no bundled extension yet; wire it through a generic LSP client such as vscode-glspc or any “generic LSP” bridge, pointing its server command at prim lsp and its document selector at the prim-owned languages (json, jsonc, yaml, toml, markdown, plaintext). Then enable format-on-save:

// settings.json
{
  "glspc.languageId": "markdown",
  "glspc.serverCommand": "prim",
  "glspc.serverCommandArguments": ["lsp"],
  "editor.formatOnSave": true
}

Neovim (0.8+)

Register prim as a formatting-only server with the built-in LSP client:

vim.api.nvim_create_autocmd("FileType", {
  pattern = { "json", "jsonc", "yaml", "toml", "markdown", "text" },
  callback = function(args)
    vim.lsp.start({
      name = "prim",
      cmd = { "prim", "lsp" },
      root_dir = vim.fs.dirname(vim.fs.find({ ".editorconfig", ".git" }, { upward = true })[1]),
    }, { bufnr = args.buf })
  end,
})

-- Format the prim-owned buffer on save.
vim.api.nvim_create_autocmd("BufWritePre", {
  pattern = { "*.json", "*.jsonc", "*.yaml", "*.yml", "*.toml", "*.md" },
  callback = function() vim.lsp.buf.format() end,
})

Zed

Add prim as a formatter-only language server and select it per language in settings.json:

{
  "lsp": {
    "prim": { "binary": { "path": "prim", "arguments": ["lsp"] } }
  },
  "languages": {
    "Markdown": { "format_on_save": "on", "language_servers": ["prim"] },
    "JSON": { "format_on_save": "on", "language_servers": ["prim"] },
    "YAML": { "format_on_save": "on", "language_servers": ["prim"] },
    "TOML": { "format_on_save": "on", "language_servers": ["prim"] }
  }
}

Machine-readable output

--format json and --format sarif are available on prim fmt --check and prim lint. JSON is also the required format for prim fmt --dry-run, prim fix --dry-run, and prim registry. These modes change only stdout; warnings, errors, and deprecation notices still go to stderr.

JSON schema

prim’s JSON report is intentionally small and stable:

{
  "version": 1,
  "mode": "lint",
  "findings": [
    {
      "path": "doc.json",
      "code": "format::drift",
      "message": "does not match prim's canonical format (run `prim fmt` to fix)"
    },
    {
      "path": "notes.txt",
      "code": "hygiene::trailing-whitespace",
      "message": "trailing whitespace",
      "line": 1,
      "column": 6
    }
  ],
  "errors": []
}
  • version is the report-schema version, starting at 1.
  • mode is fmt-check or lint.
  • findings contains one object per reported finding.
  • errors is always present. Operational failures use stable codes: input::read, format::parse, internal::panic, scope::empty, and scope::resolve. File failures include path; run-wide scope failures do not.
  • line and column appear only when prim has a concrete source position.
  • path_encoded appears only when the path is not valid UTF-8: it carries the path’s bytes percent-encoded, because JSON strings cannot hold them and path is a lossy rendering there. On a platform whose filenames are Unicode the field never appears.
  • fmt --check emits format::drift findings with the message would be reformatted.

SARIF 2.1.0

--format sarif emits a SARIF 2.1.0 log for the same findings and operational errors. ruleId matches prim’s stable code, artifactLocation.uri is the reported path, and region.startLine / region.startColumn are included when prim has a positioned finding. Operational errors have level error; a run-wide error has no invented location. A path that is not valid UTF-8 is percent-encoded, which is the form a SARIF uri calls for; a path that is valid UTF-8 is written as it is.

{
  "version": "2.1.0",
  "runs": [
    {
      "tool": {
        "driver": {
          "name": "prim"
        }
      },
      "results": [
        {
          "ruleId": "hygiene::trailing-whitespace",
          "message": { "text": "trailing whitespace" },
          "locations": [
            {
              "physicalLocation": {
                "artifactLocation": { "uri": "notes.txt" },
                "region": { "startLine": 1, "startColumn": 6 }
              }
            }
          ]
        }
      ]
    }
  ]
}

Formatting effect plans

Available starting with v0.9.0.

prim fmt --dry-run --format json FILE... and prim fix --dry-run --format json FILE... never write. They emit schema version 1 with operation, effects, and errors. Each effect is a whole-file replace_contents operation carrying:

  • path and, only for a non-UTF-8 name, path_encoded;
  • the classified kind;
  • before and after SHA-256 digests and byte lengths;
  • the exact resolved formatting configuration: end_of_line, trim_trailing_whitespace, insert_final_newline, indent_style, indent_size, and max_line_length.

An empty effect list exits 0; pending replacements exit 1; operational failure exits 2 while preserving any effects computed for other inputs. The schema is schemas/prim-effect-plan-v1.schema.json. Applying the equivalent prim fmt FILE... or prim fix FILE... invocation with unchanged inputs and configuration produces the exact planned after bytes. The v1 plan supports only whole-file content replacement. It does not describe file creation, deletion, rename, permission or index changes, command execution, or Markdown content-rule autofixes. fix currently plans the same bytes as fmt because prim has no autofixable content rules; its distinct top-level operation preserves the caller’s requested verb.

Diagnostic registry

Available starting with v0.9.0.

prim registry --format json prints one deterministic JSON document and exits 0. It never walks files, resolves .editorconfig, or applies changed-file or exclude filters. The v1 document contains:

  • schema_version and the tool name/version;
  • one diagnostics entry per code prim can emit, sorted by code;
  • empty but required aliases and retired arrays, reserving explicit places for future code migration.

Each diagnostic entry includes code, description, category, default_severity, applicable formats, enabled_by, configuration_keys, inline_controls, and can_disable. The Markdown entries and their descriptions are generated from the same rule-policy table and pinned rumdl objects used by lint; hygiene entries come from the same definitions used by the engine. The schema is schemas/prim-registry-v1.schema.json.

enabled_by is one of always, editorconfig, prim_mdlint_strict, prim_mdlint_report_line_length, or runtime. Inline-control names refer to:

NameSyntax and scope
prim-mdlint-strictA standalone <!-- prim-mdlint-strict: true|false --> line; last occurrence selects the file tier.
rumdl-disablerumdl disable/enable directives with file, block, line, and next-line forms.
markdownlint-disablemarkdownlint-compatible disable/enable directives with the same scopes.
markdownlint-configure-fileAn HTML comment containing this name followed by a JSON rule-options map, such as {"MD041":{"level":2}}; affects rules already selected for the file.

Within registry schema version 1, consumers must tolerate additive fields. Removing or redefining a field or diagnostic code requires a new schema version; code replacements go in aliases, and codes that stop emitting go in retired.

GitHub Actions integration

SARIF upload and problem matchers are separate GitHub features:

  • Use prim ... --format sarif when you want to upload a SARIF artifact with github/codeql-action/upload-sarif.
  • Use a problem matcher when you want GitHub Actions to parse prim’s default plain-text lint output from the step log.

Example SARIF upload:

- name: Run prim lint as SARIF
  run: prim lint --format sarif . > prim.sarif

- name: Upload prim SARIF
  uses: github/codeql-action/upload-sarif@v3
  with:
    sarif_file: prim.sarif

Example problem matcher for plain-text prim lint output:

{
  "problemMatcher": [
    {
      "owner": "prim-hygiene",
      "pattern": [
        {
          "regexp": "^([^:]+):(\\d+):(\\d+): (.+) \\[([^\\]]+)\\]$",
          "file": 1,
          "line": 2,
          "column": 3,
          "message": 4,
          "code": 5
        }
      ]
    },
    {
      "owner": "prim-format-drift",
      "pattern": [
        {
          "regexp": "^([^:]+): (does not match prim's canonical format.*)$",
          "file": 1,
          "message": 2
        }
      ]
    }
  ]
}

Register it in a workflow step before running prim:

- run: echo "::add-matcher::.github/problem-matchers/prim.json"
- run: prim lint .

What prim formats

Parsed formats (structured canonical formatting plus whitespace hygiene), by extension: .md, .markdown, .json, .jsonc, .yaml, .yml, .toml.

Orphan allowlist (whitespace hygiene only) — un-owned text files matched by exact name or pattern. An entry qualifies when it is committed repository connective tissue whose syntax is unaffected by the three hygiene operations (trailing-whitespace removal, one final line-feed, LF endings) — hygiene never re-indents, so tab-indented files keep their tabs:

KindEntries
Ignore files.gitignore, .gitattributes, .dockerignore, .npmignore, .eslintignore, .prettierignore, .primignore, .helmignore, .containerignore
Repo metadataCODEOWNERS, .mailmap, .gitmodules, .editorconfig, AUTHORS, CONTRIBUTORS, NOTICE, COPYING, LICENSE*
ContainersDockerfile, Dockerfile.*, Containerfile
Plain text*.txt, *.text

Everything else — source code, unknown types, binaries — is left byte-for-byte unchanged. .env files are deliberately excluded: their values are data and may be whitespace-sensitive. .gitconfig and .git/config are excluded for a different reason — they share .gitmodules’s syntax, but are user- and machine-local rather than committed.

Whitespace hygiene also strips a leading UTF-8 BOM (U+FEFF), unconditionally, from every file prim processes (parsed formats and orphans alike).

Generated files

prim declines four files outright, regardless of their type, because a tool generates them and rewrites prim’s output again on the next run:

FileGenerator
package-lock.jsonnpm
npm-shrinkwrap.jsonnpm
pnpm-lock.yamlpnpm
packages.lock.jsonNuGet

A directory walk skips a listed file silently. Naming one explicitly on the command line skips it too, with a warning on stderr. For those two path-based cases, the list behaves as the weakest .primignore layer (AD-0011): a committed !name line re-includes the file, and --no-primignore disables the built-in list along with the rest of the .primignore stack. The !name line works where nothing above the file is excluded, which is the documented recipe (!package-lock.json at the repository root). Where the .primignore stack leaves a directory holding the file excluded, that exclusion wins and the negation never reaches the built-in list — gitignore’s rule that a ! rule cannot re-include a path under an excluded directory. A directory a later ! line puts back is not excluded, so an override under it still applies.

--stdin-filepath and an editor’s format-on-save request skip a listed file without a warning: stdin echoes the input back unchanged, and the LSP formatting request returns no edits. Neither escape hatch applies there — a !name line and --no-primignore have no effect over --stdin-filepath or the LSP, because neither path consults .primignore at all.

Configuration

prim honors .editorconfig as its only style configuration — there is no prim.toml and there are no per-rule flags to configure a rule’s options or run a rule prim did not select. With no .editorconfig present, prim applies its built-in canonical style (LF endings, trailing whitespace stripped, exactly one final newline, two-space indent).

Markdown content lint does not add a second config source: .editorconfig remains prim’s only user-facing configuration file, including the documented prim_* keys below. There are two documented exceptions to “no per-rule flags”. prim_mdlint_disable is subtract-only: it can remove a rule from the tier prim already selected for a path, but it can never add one or change a rule’s behaviour. prim_mdlint_report_line_length selects MD013 into that same tier, and max_line_length — a value the repository already sets for the formatter — supplies its limit, so the formatter and the linter cannot disagree about the width. Neither key reaches any other option of any rule. See the scope notes below.

prim resolves the standard .editorconfig cascade for each file: it walks up the directory tree, stops at the nearest root = true, and applies matching per-glob sections (e.g. [*.md]). With --stdin-filepath, the cascade is resolved relative to that path’s directory.

Honored keys (standard EditorConfig keys plus prim’s closed custom-key set):

KeyEffect
end_of_linelf (default) or crlf; the emitted line ending.
trim_trailing_whitespacetrue (default) strips trailing whitespace; false preserves it.
insert_final_newlinetrue (default) keeps one final newline; false strips it.
indent_stylespace/tab — drives JSON/JSONC, TOML, and YAML indentation.
indent_sizeindent width for the JSON/JSONC, TOML, and YAML formatters. Applies on its own; indent_style is not required.
max_line_lengthline width for the structured formatters (default 80).
prim_mdlint_strictfalse (default) = floor tier; true = add strict tier for Markdown lint.
prim_mdlint_disablecomma-separated rule ids to exclude from the tier selected for a matching path (Markdown only, unset by default); none or unset excludes nothing.
prim_mdlint_report_line_lengthfalse (default) or true; report Markdown lines longer than max_line_length (MD013).

Scope notes:

  • prim treats files as UTF-8; charset values other than utf-8 are not supported (a non-UTF-8 file is left unchanged and reported).
  • end_of_line = cr (bare carriage return) is treated as lf.
  • prim_mdlint_strict, prim_mdlint_disable and prim_mdlint_report_line_length are currently the only documented prim_* keys.
  • prim_mdlint_report_line_length resolves through the same per-glob cascade as prim_mdlint_strict. It selects MD013 into the tier the path already runs; it does not change the tier, and it does not let a repository configure MD013’s options — prim sets those itself, and one of them varies by tier. The limit is the same max_line_length the formatter wraps to, so enabling the key cannot make prim report a line prim itself produced, except a heading the formatter was never able to wrap.
  • prim_mdlint_disable resolves through the same per-glob cascade as prim_mdlint_strict: EditorConfig’s ordinary last-match-wins resolution applies per section, so a narrower section’s value replaces a wider section’s list — it does not merge with it. Rule ids match case-insensitively. The key is subtract-only: it removes rules from the tier prim already selected for that path, and can never add a rule prim did not select. A value of none or unset (EditorConfig’s own reserved word for clearing an inherited value) excludes nothing — use it to drop a wider section’s list for a narrower glob. An id that names no rule prim runs in either tier disables nothing; prim reports it on stderr, naming the .editorconfig file, line and section it was written in, once per run for each section that carries it, and the exit code is unaffected.
  • Any other prim_* entry is silently ignored. That is intentional: prim_* is a closed allowlist, not a generic extension hook or a second config file.
  • Standard EditorConfig keys and documented prim_* keys resolve together for the same file; custom keys do not interfere with Style resolution.
  • prim reports a broken .editorconfig when the file has a valid first [section] header and its first invalid line comes after that header. It then warns, and the built-in canonical style applies for the whole cascade — including any .editorconfig that was read successfully before it.
  • Anything that goes wrong earlier in the file is reported too, but costs less. An .editorconfig prim cannot open, and one whose first invalid line is at or before its first [section] header — an unclosed [*.md, for instance — are named on stderr and then skipped, and the walk continues past them. Only that one file drops out; the rest of the cascade still applies. prim says unreadable when it could not read the bytes and malformed when it read them and they were not .editorconfig. A directory prim cannot search is reported the same way, because whatever config it holds has stopped applying. Each file is named once per run — and in prim lsp, once per session.
  • The exception is a byte-order mark immediately before a first-line [section] header, which is reported rather than skipped. ec4rs strips the mark when it first classifies that line but not when it re-reads it, so the file is accepted and then rejected on line 1.
  • Skipping a file silently can change resolution in both directions. The settings that file would have contributed go missing, and if it carried root = true, prim never sees that boundary and keeps reading .editorconfig files above it. So a file can resolve with a max_line_length back at prim’s default, or with an indent_style inherited from a directory that root = true was supposed to cut off, and nothing is printed on stderr either way.

Status: prim applies whitespace hygiene (trailing-whitespace removal, final newline, line endings) — driven by .editorconfig — to every file it owns, and structured canonical formatting to all of its parsed formats: JSON/JSONC (consistent indentation, one space after :, no trailing commas), TOML (canonical spacing, inline-table style and array line structure preserved), YAML (canonical layout with anchors/aliases and block scalar styles preserved), and Markdown (ATX headings, normalized lists/tables, and prose hard-wrapped to max_line_length with guardrails — inline code, links, tables, and fenced code are never broken, and fenced code is preserved verbatim). All formats preserve comments and never reorder. See the Specification.

Format notes

  • .json files are parsed leniently as JSONC: comments and trailing commas are accepted on input (trailing commas are removed on output). prim never rejects a .json file for containing comments (AD-0003).

Recipes

CI formatting gate

Fail the build when any tracked file is not formatted:

- name: Check formatting
  run: prim fmt --check .

prim fmt --check writes nothing, exits 0 when everything is already formatted, and exits 1 (listing the offending files) otherwise. The top-level prim --check spelling still works as deprecated sugar (warns on stderr; removed in v2.0) — prefer prim fmt --check in new pipelines.

A repository that is not formatted yet cannot adopt this gate on day one; see Incremental adoption on an unformatted repository for the two routes to it.

Incremental adoption on an unformatted repository

The gate above reports every pre-existing file that is not already in prim’s canonical form, which in a repository that has never been formatted can be most of the tree. Two strategies get that gate passing. Choose by whether a large one-off reformatting commit is acceptable.

Format as you touch

Gate only the files a change already modifies. The gate passes from the first commit, and coverage grows as the repository is edited:

- uses: actions/checkout@v4
  with:
    fetch-depth: 0 # a merge base needs the history on both sides
- name: Check formatting of changed files
  run: prim fmt --check --since "$(git merge-base origin/${{ github.base_ref }} HEAD)" .

That snippet is for a pull_request-triggered workflow: github.base_ref is empty on a push event, which leaves prim with origin/ and exits 2.

Compare against the merge base, not against the branch name. --since <REF> is a plain two-way git diff --name-only <REF>: it reports every path that differs between <REF> and the working tree, in either direction. Naming the branch directly also matches files modified on main after the branch point that this branch never touched — the gate then fails on an unrelated unformatted file. A branch cut from the tip of main therefore passes at first and starts failing as main advances underneath it, and a branch that has already merged main in does not hit the problem at all. (Only modifications trigger it: a file added on main is a deletion relative to this branch’s working tree, and prim drops those silently.) Any revision expression git diff accepts works, a merge-base SHA included. prim fences the REF so git reads it only as a revision, so a name that is also a path in the tree — a docs branch beside a docs/ directory — resolves to the branch rather than being ambiguous, and a REF git cannot resolve exits 2 instead of narrowing the file set. The fencing uses --end-of-options, so --since requires git 2.24 or newer. Both flags also ask git to exclude deletions, which needs git 1.8.5 or newer.

Either flag exits 2 if git reports a changed path that is not on disk and that git will still materialise — a file staged as a modification and then removed from the working tree, for instance. A sparse checkout, a skip-worktree entry and a dangling symlink are absent by design and do not raise it.

Locally the same filter formats rather than checks:

prim fmt --since "$(git merge-base main HEAD)" .

--staged applies the same idea to the index: it selects the paths git diff --name-only --cached reports, which is what a commit is about to contain. Use it to report on a commit before making it:

prim fmt --check --staged .

The index chooses the paths, but prim still reads each one from the working tree, so the report describes the commit only for files staged in full. A file staged in part is reported on its working-tree content, including the part that is not being committed.

Do not reach for prim fmt --staged . as a pre-commit hook on its own. --staged only chooses which paths prim looks at; prim then writes the formatted bytes to the working-tree file and never touches the index, so git commit still records the unformatted blob that was staged before prim ran. A run that writes under --staged ends with one warning on stderr naming how many files it wrote and pointing at git diff, which is where the unstaged formatting shows up, but a warning never raises the exit code, so it does not turn the hook into a gate. A hook has to re-stage the result, and for a partially staged file it has to deal with the unstaged remainder first. Both existing hook recipes below — git-std and pre-commit — already do that and pass prim the staged list themselves, so a hook needs neither of these flags.

Two limits are worth knowing before relying on either flag as a gate:

  • They see only what git reports. An untracked file does not appear in git diff output at all, so it is not gated until it is added to the index — prim fmt --check --since HEAD . passes on a brand-new file that prim fmt --check . would fail. Deleted paths that git does report are skipped silently.
  • Both require the working directory to be inside a git working tree, and --since requires git to resolve its REF. On a shallow actions/checkout clone there is no merge base, so the git merge-base substitution in the workflow above fails in the shell and prim is handed an empty REF. prim then exits 2 — a usage error, not a format finding — rather than passing silently. That is what fetch-depth: 0 above prevents.

Both filters intersect with the rest of discovery rather than replacing it, so .primignore, --exclude, and the ignore files still apply, and the two are mutually exclusive. See USAGE.md for the full semantics.

Format once and record the exceptions

The alternative is to reformat the whole tree in a single commit, add whatever must stay byte-exact to .primignore (see Protecting golden files), and use the full prim fmt --check . gate from then on:

prim fmt .
git commit -am "style: format the repository with prim"
git rev-parse HEAD >> .git-blame-ignore-revs

Make that commit on an otherwise clean tree: git commit -am also sweeps in any unrelated pending edit, and this is the commit you least want anything else mixed into.

This keeps every later diff free of formatting churn, at the cost of one commit that touches many files. Point git at the ignore file (git config blame.ignoreRevsFile .git-blame-ignore-revs) so that commit does not obscure git blame output.

Format-as-you-touch suits a repository where a large reformatting commit would conflict with branches already open, or is not permitted by review policy. Its running cost is the mirror image of that: a change touching one line of an unformatted file reformats the whole file, so every diff carries reformatting that has nothing to do with the change under review, for as long as adoption takes. Formatting once suits everything else: it is a shorter adoption period and a simpler gate. Either way, once the whole tree is formatted, drop --since and go back to the CI formatting gate.

CI Markdown lint gate

Fail the build when a Markdown file has a content-lint finding:

- name: Lint Markdown content
  run: prim lint .

prim lint never rewrites; it reports findings and exits 1 when any are present. For Markdown specifically, every rule prim runs is an error, so there is no silent warn-tier pass to worry about: if prim lint prints a Markdown finding, the gate fails. Three settings decide which rules run — the always-on floor tier, the strict tier once a path opts in via .editorconfig prim_mdlint_strict = true, and MD013 once a path opts in via prim_mdlint_report_line_length = true. See USAGE.md for the rule lists.

Excluding a Markdown lint rule for a tree

A convention rule can legitimately fire across an entire tree — for example MD033 (inline HTML) on a docs tree that intentionally uses <kbd> or <img align="right">. Rather than adding a <!-- markdownlint-disable-file MD033 --> comment to every affected file, exclude the rule once per glob:

[docs/**.md]
prim_mdlint_strict = true
prim_mdlint_disable = MD033, MD041

prim_mdlint_disable only removes rules from the tier prim already selected for that path — it is subtract-only, so it can never turn on a rule prim decided not to run. See USAGE.md for the full resolution semantics.

prim checks the links that resolve inside a file — a dead heading anchor (MD051), an undefined reference definition (MD052) — and nothing beyond it. A link to another file is left to a dedicated link checker, because whether it resolves depends on the renderer the file is published through, not on the filesystem alone (AD-0013).

Run one beside prim. lychee checks local and remote links across a whole tree and is the general choice; for an mdBook site, mdbook-linkcheck resolves links the way mdBook itself does, which catches a link that exists on disk but escapes the book root. Note that mdbook build on its own checks nothing: it renders a link to a missing page without a warning and exits 0, so the backend has to be installed and configured for the check to run.

Editor format-on-save

Point your editor’s “format with external command” hook at:

prim fmt --stdin-filepath "$FILE"

prim reads the buffer on stdin and writes the formatted result to stdout. The path is used only to select the right formatter.

Excluding files

prim respects .gitignore and .ignore automatically. To exclude a tracked file from formatting (for example a deliberately malformed test fixture, or a generated CHANGELOG.md), add it to a committed .primignore using gitignore syntax:

# .primignore
CHANGELOG.md
fixtures/malformed.json

A lockfile needs no entry of its own: package-lock.json, npm-shrinkwrap.json, pnpm-lock.yaml, and packages.lock.json are declined outright by a built-in list (AD-0011), because prim can always tell that these four are generated. CHANGELOG.md still needs the .primignore entry above — some projects hand-author it, so prim cannot tell a generated changelog from a hand-written one by name alone.

Protecting golden files

Test fixtures and golden files often contain deliberate formatting violations (trailing whitespace, missing final newlines, non-canonical indentation) that must stay byte-exact. Add those directories to .primignore — prim’s own repository does this for its test fixtures:

# .primignore
crates/prim-fmt/tests/correctness/fixtures/

Note: .primignore applies however prim is invoked — a file it covers is left alone whether prim walked to it or you named it on the command line (AD-0009). Excluding a directory covers everything under it, and a later ! line cannot take one file back out: under gitignore’s rules fixtures/ followed by !fixtures/keep.md leaves keep.md covered, wherever the ! line is written. That is what makes the entry worth having in a pre-commit hook, which passes prim an explicit list of staged files. Naming an ignored path prints a warning so the no-op is visible; pass --no-primignore to process it anyway.

To keep one file formatted, exclude the directory’s contents rather than the directory itself. fixtures/* covers what is in the directory without covering the directory, so the negation beneath it still works:

# .primignore
fixtures/*
!fixtures/keep.md

Skipping some of the paths given never changes the exit code, so a commit that stages one ignored file alongside others still passes the hook — and so does one that stages nothing but ignored files, because prim fmt and prim fix write and doing nothing is the correct outcome there. A gate is the exception: where prim fmt --check, prim fix --check, prim fix --diff, prim fmt --check-idempotence, or prim lint is pointed only at paths it skips, it examined nothing and exits 2 rather than reporting a clean run (FR-4.4c). The rule counts the paths prim was pointed at, so prim fmt --check --since <ref> . — the changed-file gate above — is outside it: . was pointed at and was not skipped. It is a gate handed a path list that the rule protects. Wire one with that in mind: a pipeline whose changed-file list can legitimately be all-ignored — a release commit touching only a .primignored CHANGELOG.md, say — should run the gate over the repository rather than over the diff. Do not paper over it with || [ $? -eq 2 ] either: 2 is also how prim reports a file it could not parse, a path it could not read, and a malformed --exclude glob, so a pipeline that accepts 2 accepts those too.

A .primignore governs only the repository that holds it. prim reads the .primignore files that apply from the path upward, stopping at the root of the repository it was pointed at — the nearest directory holding a .git entry, which is a file rather than a directory in a git worktree. So running prim inside a nested checkout or a worktree uses that checkout’s own .primignore, even when it sits at a path the enclosing repository’s .primignore names. Running prim on the enclosing repository still prunes it, the way a .gitignore entry would.

--exclude globs apply to directory walks and explicitly named files, including descendants of an excluded directory.

Using prim with git-std

git-std generates CHANGELOG.md, which prim would otherwise hard-wrap as Markdown. In repositories using both tools, add CHANGELOG.md to .primignore (prim ships this entry by default).

Wiring prim into a git-std pre-commit hook

git-std hook run already resolves the staged-file list for you — a glob at the end of a .githooks/pre-commit.hooks line restricts $@ to matching staged files, and the ~ (fix) sigil stashes unstaged changes, runs the command, then re-stages the result. prim needs none of that plumbing duplicated: pass it whatever files git-std gives it, and prim’s own file-type detection skips anything it doesn’t own (a .rs/.sh file, for example) with a warning instead of failing:

# .githooks/pre-commit.hooks
~ prim fmt $@

No glob is required — an explicit glob like *.{md,json,yaml,toml} also works and avoids invoking prim on staged files it will just skip, but it is an optimization, not a correctness requirement. prim’s own repository wires itself this way; see .githooks/pre-commit.hooks.

Using prim with the pre-commit framework

For repositories using the separate pre-commit framework instead of (or alongside) git-std, prim ships a .pre-commit-hooks.yaml manifest at the root of this repository. Reference it from a consumer repository’s .pre-commit-config.yaml:

repos:
  - repo: https://github.com/driftsys/prim
    rev: v0.2.2 # pin to a released tag
    hooks:
      - id: prim

The hook uses language: system, so prim must already be on PATH (install it with the install script or cargo install). The pre-commit framework itself narrows the argument list to staged files matching the hook’s types, the same way git-std’s $@ does — prim never needs to re-derive that list itself.

Specification (v1)

This is the human-readable v1 requirements specification for prim. It supersedes issue #1, which was closed once this document formalized the v1 scope it originally proposed. Code and tests remain the source of truth; this document describes the intended system.

Identity

prim is a single-binary, opinionated, near-zero-config formatter for a repository’s connective tissue — Markdown, JSON/JSONC, YAML, TOML — plus whitespace hygiene on a curated set of un-owned text files. It is not a source-code formatter and has no plugin system.

Settled decisions

ForkDecision
ScopeConfig/docs/data only (md, json/jsonc, yaml, toml). No source code.
ConfigOne canonical style; honor .editorconfig. No prim.toml.
OrderingNever reorder keys/entries/arrays (semantics-preserving).
Other text filesHygiene on a curated orphan allowlist, never on source.
Markdown wrapHard-wrap prose to width (.editorconfig max_line_length, else 80).
JSON5Excluded (JSONC covers comment needs).
.primignoreYes — committed escape hatch (gitignore syntax); covers named paths.
Make / ShellOut of v1 allowlist; shell deferred to Phase 2 (shfmt/wasm).

FR-1 — Structured formatting

  • FR-1.1 prim shall format Markdown to one canonical style (ATX headings, normalized list markers, normalized table padding, normalized blank-line spacing) and hard-wrap paragraph prose to the line width — max_line_length from .editorconfig, else 80.
  • FR-1.1a (wrap guardrails) prim shall wrap prose paragraphs only; it shall not break inside inline code, shall not split a URL or link, shall not wrap tables or fenced code blocks, shall not move text onto the closing line of an HTML comment that ended a line in the input (CommonMark parses the rest of that line as raw HTML), and shall preserve explicit hard line breaks (trailing \ or two-space).
  • FR-1.2 prim shall format JSON to a canonical style (consistent indentation, one space after :, no trailing commas).
  • FR-1.3 prim shall format JSONC, preserving all comments in position. .json files are parsed with the same lenient JSONC parser: comments and trailing commas are accepted on input and never emitted (AD-0003). (JSON5 excluded.)
  • FR-1.4 prim shall format YAML, preserving comments, anchors/aliases, and multi-line scalar styles.
  • FR-1.5 prim shall format TOML, preserving comments and inline-table style.
  • FR-1.5a (array layout) prim shall expand an array that exceeds the resolved line width to one element per line, and shall otherwise preserve the array’s line structure as written — an array on one line stays on one line, an array across several lines is never collapsed (AD-0010).
  • FR-1.6 prim shall preserve fenced code-block contents verbatim (no reformatting of embedded source).

FR-2 — Text hygiene (parsed formats + orphan allowlist)

  • FR-2.1 For every file it processes, prim shall remove trailing whitespace from each line, unless .editorconfig sets trim_trailing_whitespace = false (FR-3.2 takes precedence).
  • FR-2.2 prim shall ensure each processed file ends with exactly one line-feed.
  • FR-2.3 prim shall normalize line endings to LF, unless .editorconfig sets end_of_line = crlf.
  • FR-2.4 (scope) prim shall process only (a) the parsed formats (md/json/jsonc/yaml/toml) and (b) a built-in orphan allowlist of un-owned text files. Every other file — recognized source code, unknown types, binaries — is left byte-for-byte unchanged.
  • FR-2.5 prim shall identify allowlisted files by filename/extension, not content sniffing. Neither test shall require the filename to be valid UTF-8: prim shall read the extension before it needs the whole name, and shall match the orphan allowlist on the filename’s bytes. A file whose name is not valid UTF-8 is therefore owned, and formatted, exactly as the same name would be were it decodable (#168), whether prim reached it by directory walk or through --since/--staged, and whether it was named on the command line (#173). prim reports such a path as the bytes the filesystem holds on the stdout streams FR-5.9 names (#172).
  • FR-2.6 prim shall strip a leading UTF-8 BOM (U+FEFF), unconditionally, from every file it processes.
  • FR-2.7 prim shall leave a tool-generated file byte-for-byte unchanged, including whitespace hygiene, even when its type is one prim formats. The set is a built-in, name-keyed list (AD-0011). A committed .primignore negation re-includes such a file only when its final path segment is a literal file name equal to the generated file’s name (for example !package-lock.json, !**/package-lock.json, or !vendor/package-lock.json) — a broader negation such as !*.json or !* does not, and no negation re-includes a file that a directory exclusion above it already covers (FR-4.4). The .primignore files consulted for a path are bounded as FR-4.4b specifies, so a .primignore outside the repository cannot disable the built-in list for every repository beneath it. --no-primignore disables the built-in list along with the rest of the .primignore stack.

FR-3 — Style resolution

  • FR-3.1 prim shall apply its built-in canonical style with no config file present.

  • FR-3.2 prim shall read .editorconfig and honor indent_style, indent_size, max_line_length, end_of_line, insert_final_newline, and trim_trailing_whitespace through the normal root=true chain and per-glob sections. (charset is out of scope: prim processes UTF-8 only — FR-6.5, AD-0002.)

  • FR-3.2a prim shall also read a small, closed, documented set of namespaced prim_* keys from the same .editorconfig cascade. The current set contains three keys: prim_mdlint_strict = true|false (default false) for Markdown lint-tier selection, prim_mdlint_disable = <rule ids> (FR-3.2c) for excluding named Markdown lint rules from the tier selected for a matching path, and prim_mdlint_report_line_length = true|false (default false, FR-3.2d) for reporting Markdown lines longer than the resolved max_line_length.

  • FR-3.2b Any other prim_* key is ignored silently. Unknown custom keys must never error, widen the public configuration surface, or interfere with standard EditorConfig-key resolution.

  • FR-3.2c prim_mdlint_disable’s value shall be a comma-separated list of rule ids, resolved through the same per-glob .editorconfig cascade as prim_mdlint_strict: EditorConfig’s ordinary last-match-wins resolution applies per section, so a narrower section’s value replaces a wider section’s list rather than merging with it. Rule ids shall match case-insensitively. The key is subtract-only: it shall remove named rules from the tier already selected for that path and shall never add a rule prim did not already select for that tier. A value of unset (EditorConfig’s own reserved word) or none shall clear the list rather than name a rule, and shall not be reported as unrecognised. An id that names no rule prim can run in either tier disables nothing; prim shall report it on stderr, naming the .editorconfig file, line and section that set it, once per run for each section that carries it, without changing the exit code.

  • FR-3.2d prim_mdlint_report_line_length = true shall select MD013 into whichever Markdown lint tier FR-5.5b already resolved for that path, measured against the max_line_length resolved for the same file (80 when unset or off — the formatter’s own fallback, which treats both the same way), so that for every width prim can wrap to, no .editorconfig cascade makes prim fmt’s wrap width and prim lint’s reported width differ. Two values fall outside that range and are documented rather than reconciled: max_line_length = 0, which the formatter treats as one word per line while the rule is clamped to 1, and a value above u32::MAX, which the formatter truncates. A file carrying rumdl’s own markdownlint-configure-file directive is the one exception, and the same escape hatch AD-0012 already documents: it can change MD013’s options for that file, the width included, but it cannot select MD013 where this key has not. It resolves through the same per-glob cascade as prim_mdlint_strict. It shall not change which tier applies, and prim_mdlint_disable = MD013 shall remove the rule again like any other.

  • FR-3.3 prim shall expose no other style configuration (no prim.toml, no per-rule flags, and no way for a repository to configure a rule’s options), with two named exceptions, both feeding MD013 (FR-3.2d) and no other rule: max_line_length supplies its line-length, and prim_mdlint_strict supplies its headings. Each is a value a repository already sets for another purpose — the formatter’s wrap width, and the lint tier — reused so that the setting and the rule cannot disagree. Neither is a per-rule dial, and no other option of any rule is reachable. prim_mdlint_disable (FR-3.2c) is not an exception either: it only ever narrows the rule set prim already selected, never widens it or changes a rule’s behaviour.

  • FR-3.4 prim shall never reorder keys, table entries, or array elements.

  • FR-3.5 prim shall provide prim init [PATH] as a one-time .editorconfig scaffolder for Markdown lint-tier placement. With no existing .editorconfig, it writes exactly:

    root = true
    [*.md]
    prim_mdlint_strict = false
    [docs/**.md]
    prim_mdlint_strict = true
    [docs/wip/**.md]
    prim_mdlint_strict = false
    [docs/archive/**.md]
    prim_mdlint_strict = false
    [**/SUMMARY.md]
    prim_mdlint_strict = false
    

    When PATH/book.toml exists, the strict glob shall use mdBook’s [book].src directory instead of docs/, defaulting to src/**.md when the key is absent or the TOML is malformed. [docs/wip/**.md] and [docs/archive/**.md] are literals, not derived from the strict glob: they hold Superpowers working memory, so the strict tier must not apply to them even when the strict glob covers docs/** or a custom mdBook src directory. Specs and plans under docs/wip/ are transient; gardening moves their raw originals to docs/archive/. That move is not an edit, so it must not change a document’s tier — without the second exemption, filing work away is what would make a repository’s own CI start failing on it. An exemption whose directory the strict glob is rooted at, or inside, is not written: there the exemption would be the broader glob and would turn the whole book back off.

    When PATH/.editorconfig already exists, prim init shall merge minimally and never reorder or rewrite unrelated bytes, with one exception: it shall write the whole file under one line ending, the end_of_line that resolves for .editorconfig once the write has been made (FR-2.3). Composing LF additions into a CRLF file would otherwise leave mixed endings, and carrying the existing endings through would leave a uniformly CRLF file that prim fmt --check reports. The ending must be resolved after the write and not before, because the root = true prim init writes stops EditorConfig’s upward walk, so an end_of_line an ancestor declared before the write no longer reaches the file afterwards. Otherwise: leave an existing top-level root = ... untouched, otherwise prepend root = true plus one blank line; for [*.md], the detected strict glob, [docs/wip/**.md], and [**/SUMMARY.md], leave any existing explicit prim_mdlint_strict = ... untouched, append the missing key inside an existing section, and insert any missing section without moving existing bytes so the final relative order still reads [*.md] → strict glob → [docs/wip/**.md] → [**/SUMMARY.md] (appending at end-of-file only when no later prim section needs to stay after it). prim init shall check each write against the file it would produce before making it. For one representative path per canonical section it places — a top-level file, a file under the strict glob, a file under docs/wip/ where that section applies, and a SUMMARY.md — it shall resolve prim_mdlint_strict through EditorConfig’s last-match-wins section order, and shall make a write only when the path that write is meant to place resolves to the value prim intended and every other representative path resolves exactly as it did before the run. A write that fails that check shall not be made: prim init shall print a warning naming the path that would resolve differently and the value it would take, and shall still make whatever other writes pass the check.

    root = true stops EditorConfig’s upward walk for every key and every file type, not just prim’s own, so writing it into a nested directory drops whatever a parent configured. Whenever prim init writes root = true — scaffolding a new file or prepending to an existing one — and the target directory currently reaches an .editorconfig above it that sets at least one key in a section, it shall warn, naming those files and the keys that no longer reach the directory. An ancestor that sets nothing but root is left out: cutting the walk off from it loses nothing. Keys written before any section header are left out too, because EditorConfig does not apply them and prim never resolved them. The write is still made; the prepend is mandated and prim init cannot know whether the author wants the parent cascade, so this is a warning and never a refusal.

    When a section is missing and the file’s own existing section order already contradicts the canonical order — for example an existing [**/SUMMARY.md] written before the strict glob — no position satisfies that order; prim init shall leave that section out and print a warning naming the two conflicting sections, the lines they start at, and where the section has to be added by hand. prim init shall then resolve the file it leaves behind: for every canonical section present in it that carries prim_mdlint_strict, it shall warn when that section does not decide its own representative paths — either because a later section overrides it, or because its value is one prim does not read as a tier (every value but true resolves to false). It shall warn when the section decides none of its representative paths, not merely when a later section happens to set a different value for one of them: a later section that agrees on value but still decides the path leaves the earlier section deciding none of its own representatives, and that must be reported too. To tell that case apart from a person’s narrower override that still leaves the section deciding other paths, prim init resolves one further representative per canonical section, never named in any message. That covers a section prim planned no write for because the key was already there, and equally one that prim’s own write has just taken a path away from. It is a warning, never a refusal: a person’s narrower override is legitimate, and prim init shall stay able to report on a file it disagrees with. It shall never reorder sections a person wrote. An occurrence of a canonical glob that neither sets prim_mdlint_strict nor receives it — an ordinary [*.md] max_line_length = 80 — shall take no part in that ordering. Running prim init twice shall be a byte-identical no-op on the second run.

FR-4 — File discovery

  • FR-4.1 prim shall default to the current working directory, recursively, when given no paths.

  • FR-4.2 prim shall respect .gitignore, .git/info/exclude, global gitignore rules, and .ignore (via the ignore crate) without invoking git, and shall function in non-git directories.

  • FR-4.2a --no-ignore shall disable only the git-family ignore rules from FR-4.2 (.gitignore, global gitignore, .git/info/exclude). It shall not disable .primignore, CLI --exclude globs, or the .git/ metadata-directory prune.

  • FR-4.2b --since <REF> and --staged shall further restrict the matched file set through git-native diffs, and they shall be mutually exclusive. --since <REF> uses plain two-way git diff --name-only <REF> semantics: paths that differ between <REF> and the current working tree, including both staged and unstaged changes, with no merge-base (...) comparison. --staged uses git diff --name-only --cached semantics: paths staged in the index relative to HEAD. Both intersect with FR-4.2/4.2a/4.3/4.4/4.5 filtering rather than replacing it, silently drop paths git reports as deletions, and shall raise a usage error (exit 2) if git is unavailable, the current working directory is not inside a git working tree, or <REF> is invalid.

  • FR-4.2c When --staged selects the file set and prim writes at least one file, prim shall emit exactly one warning on stderr, reporting how many files it wrote to the working tree and that --staged does not update the index (#159). The warning shall name git diff, which shows the unstaged result it just produced, and shall not name git diff --cached, which compares the index against HEAD and so cannot show that result at all.

  • FR-4.2d prim shall not re-stage a file it wrote under --staged, and shall not state what the index holds. prim never reads the staged blob: for a partially staged file that blob may already be canonical, and git add would also stage the remainder the author kept out of the commit. Re-staging belongs to the hook runner.

  • FR-4.2e No git configuration and no path spelling shall change which files --since or --staged select. prim shall read raw NUL-separated paths, so no quoting form hides a path (#164), and shall pin diff.relative=false, so the paths git reports are the ones prim resolves (#165). prim shall treat those paths as bytes rather than as text, so on a platform whose filenames are byte strings a name that is not valid UTF-8 selects, classifies and formats like any other (#168), and prim reports it as the bytes the filesystem holds on the stdout streams FR-5.9 names, so the name prim prints there is a name that opens (#172). Where a path cannot be represented at all — a platform whose filenames are Unicode, given output that is not valid UTF-8 — prim shall raise a usage error (exit 2) naming that path, rather than drop it. prim shall raise a usage error (exit 2), rather than resolve an empty file set, when git reports output that is not NUL-separated. Output that is empty is a legitimately empty selection and shall stay a clean run.

  • FR-4.2f No <REF> shall reach git as anything but a revision. prim shall exit 2 for a <REF> git will not resolve, including one beginning with - (#167), one naming an existing file, and -- itself, and shall never let such a <REF> take effect as a git option or as a pathspec. --since therefore requires git 2.24 or newer, which is when --end-of-options reached the revision parser.

  • FR-4.2g prim shall ask git for the status of each changed path and shall classify every one before passing over any (#169, AD-0015). A path that resolves on disk shall be selected whatever its status, so a staged deletion of a file still present is still formatted. A path that is absent shall be passed over in silence when git reports it as a deletion, when something other than a regular file is at it, or when the index will not materialise it — skip-worktree, which is how sparse checkout is implemented, or assume-unchanged. A path that is absent, tracked, and of a type prim owns shall raise a usage error (exit 2) within the paths prim was pointed at. A path git reports but does not track shall raise a usage error wherever prim was pointed, because no repository state produces one.

  • FR-4.3 prim shall process explicit file/directory path arguments.

  • FR-4.4 prim shall respect a committed .primignore (gitignore syntax) for every path it is given, whether reached by a directory walk or named on the command line (AD-0009). --no-primignore shall process ignored paths anyway. gitignore’s re-inclusion rule shall hold on both routes: a ! rule shall not re-include a path when a directory holding it is excluded, however near that path the rule is written, including in a .primignore beneath the excluded directory (#114).

  • FR-4.4a prim shall report on stderr each path that was named on the command line and skipped, whether because .primignore covers it or because it matches the built-in generated-file list (FR-2.7, AD-0011). Skipping a path reached by a directory walk shall be silent for either reason. Where no path is named, the working directory is the path prim was pointed at, and skipping it shall be reported the same way.

  • FR-4.4b The .primignore files that apply to a path shall be those from its own directory up to a bound, and none above that bound. The bound shall be the root of the repository containing whatever prim was pointed at — a path named on the command line, or the root of a directory walk — resolved once and applied to every path considered under it. A repository root is the nearest directory holding a .git entry, which is a directory in an ordinary clone and a file in a git worktree. Only where no repository is found shall the bound be the current working directory instead. Consequently a nested checkout is governed by the enclosing repository’s .primignore when prim is pointed at the enclosing repository, and by its own when prim is pointed at the checkout. Where the working directory is the bound, the bound shall be the outermost directory holding the path that resolves inside the working directory with every directory between it and the path resolving inside it too, named as the path names it (#113). Matching itself shall stay lexical — a rule naming a symlinked directory covers the paths written through it — so a path is never judged under a spelling other than the one prim was given, and a .primignore that the path as spelled does not pass shall not apply to it however that path resolves.

  • FR-4.4c In a gate mode — one whose exit code gates on pending findings: fmt --check, fix --check, fix --diff, fmt --check-idempotence, lint — prim shall exit 2 when every path it was pointed at was skipped (FR-4.4a): each path named on the command line, or the working directory when none was named. A 0 there would report a clean run over files prim never looked at, which is the assurance a CI gate reads. The modes that write (fmt, fix) and the preview mode (fmt --diff) shall exit 0 in the same case, so a pre-commit hook handed a staged list of ignored paths still passes (AD-0009). Skipping only some of the paths given shall not raise the exit code in any mode.

  • FR-4.5 prim shall accept CLI exclude globs; a malformed glob is a usage error (exit 2).

  • FR-4.6 prim shall handle an explicitly named path strictly: a path that does not exist shall be reported as an error (exit 2); an existing path whose type prim does not own shall be reported as a warning and left unchanged (exit 0). An unowned path reached only by directory walking shall be skipped silently (FR-2.4).

  • FR-4.6a A symbolic link is a path type prim does not own (AD-0016). prim shall not write to one. Where a link is itself the file prim would read or write — a path named on the command line in any verb or gate, a path a changed-file scope reports, or the .editorconfig prim init would write — the link shall be left byte-for-byte unchanged and the file it points at shall be neither read nor written. Naming one shall be reported (FR-4.6) and shall not count toward FR-4.4c. This overrides FR-4.6’s missing-path rule for a dangling link: it is declined for its type, so it exits 0 rather than 2. prim init is the one route that exits 2, because it was asked to write one named file and did not.

  • FR-4.6b Two shapes are outside FR-4.6a, both because they end at a regular file and so destroy no link. A path that passes through a symlinked directory shall be processed normally, and the .primignore reach limit that follows from FR-4.4b’s lexical matching stands as decided. A symlinked directory named directly shall likewise be walked: refusing it would refuse prim fmt /tmp/... on a platform where /tmp is itself a link. A walk shall not descend into a symlinked directory in either case (FR-2.4), so naming one and walking past it answer about different trees. The answer follows what prim was pointed at — the same rule FR-4.4b applies to a nested checkout.

  • FR-4.7 A caller may delegate an explicit file list with prim fmt FILE..., prim fmt --check --format json FILE..., prim lint --format json FILE..., or prim fix FILE.... prim shall process only those arguments; it shall not search their parents or add sibling files. A directory argument deliberately requests prim’s standalone recursive discovery and is therefore not an explicit-file delegation. All normal ownership and safety rules still apply to a named file: .primignore, --exclude, generated-file protection, symlink refusal, and unsupported-type handling are not bypassed. Shell files remain unowned. Style is resolved independently for each accepted path from the .editorconfig cascade visible at invocation time. Relative and absolute paths, including paths containing spaces, are supported.

FR-5 — Operating modes (CLI)

prim exposes three verbs (AD-0007): fmt, lint, fix. Bare prim [PATH]... is a permanent alias for prim fmt [PATH]... — no verb is required for the default, format-in-place action.

  • FR-5.1 (default) prim fmt (and its bare alias) shall format matched files in place.
  • FR-5.2 prim fmt --check (also fix --check) shall write nothing, exit 0 when all files are already formatted, exit non-zero when any file would change, and list the files that would change. A run that examined nothing exits 2 instead of 0 (FR-4.4c).
  • FR-5.3 prim fmt --diff shall print a unified diff of pending changes and write nothing; it shall exit 0 whether or not changes are pending (--check is the CI gate). prim fix --diff shares fix --check’s gated contract instead (FR-5.2): it also prints the diff and writes nothing, but exits non-zero when a fixable finding is pending, since fix’s --check and --diff are both format-drift gates, unlike fmt --diff’s preview-only behaviour (AD-0007 §4). Being gates, both also exit 2 when the run examined nothing (FR-4.4c); fmt --diff does not.
  • FR-5.3a prim fmt --check-idempotence (also reachable as bare prim --check-idempotence through the permanent fmt alias) shall write nothing and verify FR-6.1 across the matched corpus: for each discovered file prim owns, it formats the current bytes in memory, formats that output a second time with the same resolved .editorconfig style, and exits 1 if any second pass still changes bytes. It lists each failing file on stdout, exits 0 when every second pass is stable (2 when it examined nothing, FR-4.4c), and uses the normal discovery/classify rules (structured formats plus the orphan hygiene allowlist only).
  • FR-5.3b prim fmt --dry-run --format json PATH... and prim fix --dry-run --format json PATH... shall emit a versioned, exact, no-write effect plan. Each effect is a whole-file replace_contents operation containing its path and file kind, before/after SHA-256 digest and byte length, and the six resolved EditorConfig values that affect output. Version 1 promises no file creation, deletion, rename, permission or index change, command execution, or Markdown content-rule autofix. Applying the equivalent explicit fmt or fix invocation shall produce every planned after digest and length when the input bytes and effective EditorConfig remain unchanged. No effects exits 0, one or more replacements exits 1, and an operational error exits 2 while retaining effects computed for other inputs. Errors use FR-5.8a’s stable codes. The document shall conform to schemas/prim-effect-plan-v1.schema.json; consumers shall tolerate additive fields in schema version 1, while removing or redefining a field requires a new schema version.
  • FR-5.4 With --stdin-filepath <path> (valid on fmt, lint, and fix), prim shall read stdin and, for fmt/fix, write the formatted result to stdout. The flag is mutually exclusive with --check and --diff.
  • FR-5.5 prim lint shall report hygiene and content violations without ever rewriting a file; it has neither --check nor --diff (report-only is its only mode). Being report-only makes it a gate throughout: a lint run that examined nothing exits 2 (FR-4.4c).
    • FR-5.5a (hygiene diagnostics, story B1) For the un-owned-text allowlist (the orphan set, shell excluded — same scope as FR-2.4/2.5), prim lint shall report each whitespace-hygiene violation individually: a leading BOM, a line ending that does not match the resolved end_of_line, trailing whitespace, an indentation character that contradicts the resolved indent_style, and a missing final newline (when insert_final_newline is set). Each finding carries a stable, namespaced diagnostic code (hygiene::bom, hygiene::eol, hygiene::trailing-whitespace, hygiene::indent, hygiene::final-newline) and a 1-indexed file:line:col (prim_fmt::line_col, AD-0008), printed as path:line:col: message [code]. JSON/JSONC/TOML/YAML keep the coarser format-drift finding until their own content diagnostics land (D2).
    • FR-5.5b (Markdown content diagnostics, stories G2/G3) For Markdown files, prim lint shall run rumdl_lib::lint() in Standard flavor through prim_fmt::lint_markdown, building prim’s active rule subset by name through rumdl_lib::rules::create_rule_by_name. The per-file .editorconfig key prim_mdlint_strict = true|false (default false) is resolved through the normal EditorConfig cascade; false runs the always-on floor tier of 12 defect rules, true adds 13 convention rules on top. Every rule prim runs, at either tier, is an error: there is no warning severity for Markdown, so a finding’s presence is its severity. Each finding carries rumdl’s rule code verbatim and a 1-indexed path:line:col, printed as path:line:col: message [MD0xx]. This path is lint-only: prim shall never invoke rumdl’s formatter or auto-fix Markdown findings, and prim fix does not yet auto-fix these rules.
      • Floor tier — defect rules (always on, error at floor and strict): MD011, MD034, MD042, MD045, MD051, MD052, MD056, MD062, MD066, MD068, MD070, MD075. Each reports something objectively broken — a dead link, a dangling reference, a malformed table — independent of what the author intended, so it can gate every repository with no opt-in.
      • Strict tier — convention rules (prim_mdlint_strict = true only, error when active): MD001, MD024, MD025 (SUMMARY-safe via .editorconfig; front-matter title excluded by default, see below), MD026, MD033, MD036, MD040, MD041, MD053, MD059, MD067, MD073, MD080. Each is decidable but fires on documents that are otherwise fine, so it gates only once a repository opts in.
      • Never linted (formatter territory): MD003-005, MD007, MD009, MD010, MD012, MD018-023, MD027-032, MD035, MD037-039, MD046-050, MD055, MD058, MD060, MD064, MD065, MD071, MD076, MD077.
      • Off in both tiers: MD014, MD043, MD044, MD054, MD061, MD063, MD069, MD072 (frontmatter key sorting would violate prim’s semantics-preserving guardrail), MD074, MD078, MD079, MD081, MD057 (dropped from ACTIVE_RULES: whether a link that leaves the file resolves depends on the renderer, so a file-existence check is the wrong question at this layer; see AD-0013), and MD082 (dropped from ACTIVE_RULES entirely: absent from markdownlint, opt-in in rumdl, no fix by design, and — measured across six public documentation sites — 569 of 573 findings flag a parent heading immediately followed by a deeper one, an ordinary outline shape rather than an empty section; see AD-0012). A rule rumdl adds after this census was drawn is off in both tiers until a record places it; at rumdl 0.2.66 that is MD083-MD089 and MD091 (#194). The same census, as lists in mdlint/tests/census.rs, is checked against the rules rumdl registers, so a bump that adds or drops a rule fails the build until those lists are updated; this prose is edited with them.
      • Selected by prim_mdlint_report_line_length (FR-3.2d), off otherwise: MD013. It sits outside the tier model — the key decides whether it runs, and the tier decides only whether it examines headings. prim shall set five of its options and expose none of them: code-blocks = false and code-spans = false, because prim preserves fenced content verbatim (FR-1.6) and keeps an unbreakable inline span on one line (FR-1.1a); tables = false, pinned rather than inherited from rumdl, because a table row cannot carry a line break; line-length from the resolved max_line_length, written to both rumdl’s global and the rule’s own key so their precedence rule cannot change the answer; and headings = false at the floor tier, true at the strict tier. A heading is the one construct prim cannot wrap but an author can shorten, which is the strict tier’s definition of a finding. The tier used is the one in force after FR-5.5c’s file-level override, so the directive moves the heading check with it.
      • Exit-code implication: floor-tier findings and strict-tier findings alike raise prim lint’s exit code to 1; no Markdown rule emits a warning.
      • Rule configuration prim owns: prim passes rumdl a Config with MD025’s front-matter-title option emptied, so a page’s front-matter title: is treated as metadata rather than a heading, and — when FR-3.2d selected it — MD013’s five options as listed above. These are prim choosing its own canonical defaults for rules it runs, not a configuration surface a repository can reach: there is still no way for a repository to configure a rule’s options, save the one named path FR-3.3 records. See AD-0012 for the evidence behind the MD025 choice.
    • FR-5.5c (override surface, story G5) A standalone <!-- prim-mdlint-strict: true|false --> line anywhere in a Markdown file (the whole line, once trimmed) overrides FR-5.5b’s .editorconfig-resolved prim_mdlint_strict for that file only. When several such lines are present, the last one (top-to-bottom) wins; an unrecognized value falls back to the .editorconfig-resolved tier rather than erroring the lint run. rumdl’s own inline directives (rumdl-disable/rumdl-enable, markdownlint-disable/-enable, and their line/next-line/file-scoped forms) require no additional wiring: rumdl_lib::lint applies them internally before returning findings, independent of the source_file prim passes (None). No second config source is introduced — the override surface is the strict boolean plus these two inline mechanisms, never a per-rule matrix.
  • FR-5.6 (exit codes) 0 = nothing to do / already clean · 1 = actionable — format drift (fmt/fix --check), a planned replacement (fmt/fix --dry-run), or a lint finding · 2 = prim could not do its job (parse/IO/usage error, or a gate that examined nothing — FR-4.4c). Warnings never raise the exit code; only errors do.
  • FR-5.6a (argv survives a byte prim cannot decode) prim shall read its command line with std::env::args_os, so a path that is not valid UTF-8 reaches the filesystem as the bytes prim was given — satisfying FR-2.5 for a named path, not only a discovered one (AD-0017). A non-UTF-8 value for an option that is not a path — an --exclude glob, a --since ref — remains a usage error (exit 2, FR-4.5): those are matched and resolved as text, and prim has no meaning for bytes that are not.
  • FR-5.6b (a contained fault keeps the contract) prim shall not exit outside FR-5.6 for a panic raised inside a third-party formatter or linter. It shall contain such a panic per file: the file shall be reported as an error with its path named and left byte-for-byte unchanged (FR-6.3), the run shall continue to the next file, and the process shall exit 2. A panic shall be an error whether the file was named or walked, because it is a fault in prim rather than in the input. Where prim holds a buffer it does not own it shall return that buffer unchanged: fmt/fix --stdin-filepath shall echo stdin to stdout and exit 2, and the LSP shall return no edits, no diagnostics, and keep the session. lint --stdin-filepath writes a report to stdout rather than a buffer, so it echoes nothing. A --format run shall still emit its report document, since --format governs stdout alone.
  • FR-5.7 (deprecated top-level flags) The top-level --check, --diff, and --stdin-filepath flags remain accepted directly on bare prim as deprecated sugar for the fmt forms; the first use in a run emits a one-line deprecation warning to stderr. They are scheduled for removal in v2.0; the bare alias itself is not deprecated.
  • FR-5.8 (machine-readable reports, story D2) --format <json|sarif> shall be accepted on prim fmt --check and prim lint. In addition, --format json is required by prim fmt --dry-run and prim fix --dry-run; SARIF is not an effect-plan format. Machine format changes only stdout for these no-write modes: write behaviour and exit codes are unchanged, and warnings/errors remain on stderr. Without --format, the existing plain-text stdout for fmt --check and lint remains unchanged.
    • FR-5.8a --format json shall emit a stable JSON document of the form { "version": 1, "mode": "fmt-check"|"lint", "findings": [...], "errors": [...] }. Both arrays are required, including when empty. A finding or error may gain a field within a version — a consumer shall ignore one it does not know, rather than reject the document — and the version rises only when an existing field changes shape or meaning. Each finding includes path, code, and message; positioned findings also include 1-indexed line and column. Each operational error includes a stable code and message, plus path when the error belongs to a file. A finding or error whose path is not valid UTF-8 also includes path_encoded, the path’s bytes percent-encoded (FR-5.9), on a platform whose filenames are byte strings; the field is absent for every other finding, and absent everywhere on a platform whose filenames are Unicode, which has no bytes to offer. A decodable path therefore renders exactly as it did before. fmt --check reports one format::drift finding per file that would change, with the message "would be reformatted". prim lint reports the existing coarse structured format drift as format::drift, plus the B1 hygiene diagnostics for orphan files with their stable hygiene::* codes and positions. Operational failures use the stable input::read, format::parse, internal::panic, scope::empty, or scope::resolve code. A partial failure preserves findings from files prim could examine; a full failure still emits one complete document with an empty findings array. Both exit 2.
    • FR-5.8b --format sarif shall emit a valid SARIF 2.1.0 log with one result per finding or operational error. Each result’s ruleId shall match the stable code, artifactLocation.uri shall be the reported file path — percent-encoded when that path is not valid UTF-8 and the platform has its bytes, which a SARIF uri requires and which leaves every decodable path unchanged (FR-5.9) — and region.startLine / region.startColumn shall be present whenever the finding has a known position. Operational errors have level error; file errors carry a location and run-wide scope errors do not. As in JSON, partial and full failures emit a complete SARIF log and exit 2.
  • FR-5.9 (the machine-readable stream names files that open) On a platform whose filenames are byte strings, prim shall write a path to stdout as the bytes the filesystem holds in three places: the fmt --check list, the same list under fmt --check-idempotence (FR-5.3a), and both plain-text lint finding shapes — the positioned path:line:col prefix and the coarse path: message line. Two stdout writers are not covered and stay lossy: the fmt --diff patch header and prim explain. Rendering through Path::display replaces each byte that is not valid UTF-8 with U+FFFD, which names a file that cannot be opened and breaks the documented prim fmt --check --since <REF> . | xargs hook (#172). Where a format’s strings must be valid UTF-8, prim shall carry the bytes in a form that round-trips rather than drop them: path_encoded in JSON (FR-5.8a) and a percent-encoded artifactLocation.uri in SARIF (FR-5.8b). Human-facing output on stderr stays lossy — it is prose for a reader, and a terminal cannot render an undecodable byte.
  • FR-5.10 (diagnostic registry) prim registry --format json shall emit one deterministic JSON document and exit 0, without walking files, resolving repository configuration, or applying file-selection flags. A missing format or any format other than JSON is a usage error (exit 2).
    • FR-5.10a The document shall conform to schemas/prim-registry-v1.schema.json and contain schema_version: 1, the running tool name and version, a diagnostics array sorted by stable code, and required aliases and retired arrays. The latter two start empty.
    • FR-5.10b Each diagnostic shall identify its code, description, category, default severity, applicable formats, enabling policy, configuration keys, applicable inline controls, and whether it can be disabled. The inventory shall cover format::drift, every whitespace hygiene and selected Markdown code, and every operational error code from FR-5.8a.
    • FR-5.10c Hygiene codes shall come from the same definitions their constructors use. Markdown codes, tiers, and descriptions shall be derived from the same rule-policy table and pinned rumdl rule objects used by lint selection and prim_mdlint_disable validation. Registry configuration keys shall share definitions with prim explain; the CLI shall not maintain a second rule inventory.
    • FR-5.10d Consumers shall tolerate additive metadata within registry schema version 1. Removing or redefining a code or field requires a new schema version; a renamed code is recorded in aliases, and a code that no longer emits is recorded in retired.

FR-6 — Correctness & safety

  • FR-6.1 (idempotency) Running prim on its own output shall produce zero further changes. prim fmt --check-idempotence is the CLI-facing verification surface for this guarantee and never writes to disk.
  • FR-6.2 (semantic preservation) Formatting shall not change the parsed data model of a JSON/JSONC/YAML/TOML document.
  • FR-6.3 (fail-safe) An unparseable file shall be left byte-for-byte unchanged and reported, with the severity graded by how prim reached it — FR-4.6’s rule that an explicitly named path is handled strictly. A file named on the command line shall be reported as an error (exit 2); one reached only by a directory walk shall be reported as a warning and shall leave the exit code alone, so that one unparseable file in a tree does not make prim fmt . unusable. A panic raised inside a third-party formatter or linter is an error whether the file was named or walked, because it is prim’s own defect rather than the input’s (FR-5.6b, AD-0017).
  • FR-6.4 (atomic write) prim shall write via a temporary file and atomic rename, preserving permission bits.
  • FR-6.5 prim shall process only UTF-8 text; it shall leave non-UTF-8 files unchanged and report them under FR-6.3’s grading: an error (exit 2) when the path was named, a warning that leaves the exit code alone when the file was reached by a directory walk.

Release integrity (v0.9.0)

  • RI-1 Each release shall retain the five supported target archives and matching SHA-256 files documented in Installation. It shall add a keyless cosign bundle and a SLSA v1 build-provenance bundle for every archive, plus one release-wide SPDX JSON SBOM and its keyless signature: exactly 22 assets. Archive names remain prim-<target>.tar.gz; the companion suffixes are .sha256, .sigstore.json, and .provenance.sigstore.json. The SBOM is prim-<version>.spdx.json, where the version excludes the tag’s leading v.
  • RI-2 The reusable .github/workflows/release-build.yml shall build, package, sign, and attest the archive in the same job. The caller .github/workflows/release.yml shall generate the SBOM from the tagged source and Cargo.lock, using Syft v1.51.1 spdx-json output, require spdxVersion == "SPDX-2.3", and sign the SBOM. Uploads shall fail when any expected asset is missing.
  • RI-3 Before either GitHub Release or crates.io publication, a blocking verifier shall download the build and SBOM artifacts and require the exact asset set, matching checksum names and digests, valid cosign bundles with the GitHub Actions OIDC issuer and exact workflow/tag identities, valid provenance bundles scoped to driftsys/prim and the reusable signer workflow, and exact verified subject names and SHA-256 digests. Archive cosign certificates shall identify release-build.yml; the SBOM certificate shall identify release.yml. Provenance shall bind the source tag and source/signer commit and reject self-hosted runners. The verifier shall require the release tag’s commit to be contained by origin/main and require SPDX 2.3.
  • RI-4 GitHub Release shall consume the verifier’s immutable artifact ID and publish the verified bytes without transforming archives. Signing and attestation permissions shall be scoped to their jobs; only GitHub Release publication shall receive contents: write. crates.io publication shall retain its idempotent version checks and existing package credential. The pull-request and scheduled cargo audit gate shall remain unchanged.
  • RI-5 Attestation generation alone shall not be presented as evidence of SLSA Build Level 3. Protected branch/tag/release ruleset inspection and the successful hosted OIDC signing and verification evidence are separate acceptance gates for #55. The repository shall not claim that level until reviewed controls and run evidence establish it. These release-integrity assets are introduced in v0.9.0; v0.8.0 establishes only archive/checksum availability.

NFR — non-functional (targets, tunable)

  • NFR-1 One statically linked binary, zero runtime dependencies.
  • NFR-2 Linux/macOS/Windows on amd64 + arm64.
  • NFR-3 (determinism) identical input → byte-identical output on every supported platform. Parallel file processing must preserve discovery order for reports and deferred warnings/errors so output stays byte-identical across runs.
  • NFR-4 (throughput) format a 5,000-file repository in under 2 s on an 8-core machine with warm cache, parallelized across files. prim satisfies this by parallelizing the per-file read → style-resolution → format pipeline across discovered files.
  • NFR-5 (footprint) peak memory scales with the largest single file, not repository size.

Style stability

The canonical style is a compatibility contract. Any change to prim’s output for already-canonical input — including a change inherited from a formatter dependency upgrade (dprint-plugin-json, dprint-plugin-markdown, taplo, pretty_yaml) — is a versioned, release-noted event: a minor version bump while prim is pre-1.0, a major bump once prim reaches 1.0. The same holds for a lint finding a gate did not report before, including one inherited from a rumdl upgrade: prim lint fails a build through the same exit code as format drift. Either kind carries the breaking marker on its commit — ! on the type or a BREAKING CHANGE: footer — which is what the release tooling turns into the minor bump and the changelog note; a bare feat is a patch while prim is pre-1.0. The release notes must call out the changed output explicitly so downstream prim --check and prim lint gates upgrade deliberately. The fixture harness (crates/prim-fmt/tests/correctness/fixtures/) is prim’s golden corpus: its spec_cases_format_as_expected test byte-compares formatter output against each fixture’s committed -- expected -- section, so canonical-output drift fails the build until it is reverted, or deliberately regenerated with PRIM_SPEC_UPDATE=1 cargo test -p prim-fmt --test correctness spec_cases_format_as_expected, reviewed in the diff, and released as above. CI runs the plain, ungated cargo test --workspace (no PRIM_SPEC_UPDATE), so an unreviewed golden-corpus regeneration can never merge silently.

Because releases are generated from Conventional Commits (git std bump), the policy above only holds if commit messages carry the marker the tooling reads: a commit that changes a golden fixture’s -- expected -- section, or otherwise changes canonical output or makes a gate report a finding it did not report before, carries the breaking marker — ! on its type, or a BREAKING CHANGE: footer — on whatever type fits the change (fix! for a corrected defect, feat! for new behaviour). That marker is what yields the minor bump and the changelog note; the type alone does not, since a bare feat is a patch while prim is pre-1.0. A reviewer who sees such a change in a commit without the marker should request it before merge.

Non-goals

  • No source-code formatting (Rust/JS/TS/Python/Go/…).
  • No plugins or user-facing extensibility API.
  • No schema validation or generalized lint framework beyond the documented whitespace-hygiene and Markdown-content checks.
  • No style knobs beyond .editorconfig.

Phase 2 — roadmap (not v1)

  • prim may format shell scripts (*.sh/*.bash) by embedding shfmt compiled to WebAssembly. This brushes the “no plugins” non-goal and is to be decided deliberately at Phase 2 start: prim has no plugin system (no user-supplied formatters), but may embed specific curated wasm formatters internally.