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
| Fork | Decision |
|---|---|
| Scope | Config/docs/data only (md, json/jsonc, yaml, toml). No source code. |
| Config | One canonical style; honor .editorconfig. No prim.toml. |
| Ordering | Never reorder keys/entries/arrays (semantics-preserving). |
| Other text files | Hygiene on a curated orphan allowlist, never on source. |
| Markdown wrap | Hard-wrap prose to width (.editorconfig max_line_length, else 80). |
| JSON5 | Excluded (JSONC covers comment needs). |
.primignore | Yes — committed escape hatch (gitignore syntax); covers named paths. |
| Make / Shell | Out 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_lengthfrom.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.
.jsonfiles 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
.editorconfigsetstrim_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
.editorconfigsetsend_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
.primignorenegation 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!*.jsonor!*does not, and no negation re-includes a file that a directory exclusion above it already covers (FR-4.4). The.primignorefiles consulted for a path are bounded as FR-4.4b specifies, so a.primignoreoutside the repository cannot disable the built-in list for every repository beneath it.--no-primignoredisables the built-in list along with the rest of the.primignorestack.
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
.editorconfigand honorindent_style,indent_size,max_line_length,end_of_line,insert_final_newline, andtrim_trailing_whitespacethrough the normalroot=truechain and per-glob sections. (charsetis 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.editorconfigcascade. The current set contains three keys:prim_mdlint_strict = true|false(defaultfalse) 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, andprim_mdlint_report_line_length = true|false(defaultfalse, FR-3.2d) for reporting Markdown lines longer than the resolvedmax_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.editorconfigcascade asprim_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 ofunset(EditorConfig’s own reserved word) ornoneshall 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.editorconfigfile, 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 = trueshall select MD013 into whichever Markdown lint tier FR-5.5b already resolved for that path, measured against themax_line_lengthresolved for the same file (80 when unset oroff— the formatter’s own fallback, which treats both the same way), so that for every width prim can wrap to, no.editorconfigcascade makesprim fmt’s wrap width andprim 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 aboveu32::MAX, which the formatter truncates. A file carrying rumdl’s ownmarkdownlint-configure-filedirective 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 asprim_mdlint_strict. It shall not change which tier applies, andprim_mdlint_disable = MD013shall 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_lengthsupplies itsline-length, andprim_mdlint_strictsupplies itsheadings. 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.editorconfigscaffolder 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 = falseWhen
PATH/book.tomlexists, the strict glob shall use mdBook’s[book].srcdirectory instead ofdocs/, defaulting tosrc/**.mdwhen 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 coversdocs/**or a custom mdBooksrcdirectory. Specs and plans underdocs/wip/are transient; gardening moves their raw originals todocs/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/.editorconfigalready exists,prim initshall merge minimally and never reorder or rewrite unrelated bytes, with one exception: it shall write the whole file under one line ending, theend_of_linethat resolves for.editorconfigonce 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 thatprim fmt --checkreports. The ending must be resolved after the write and not before, because theroot = trueprim initwrites stops EditorConfig’s upward walk, so anend_of_linean ancestor declared before the write no longer reaches the file afterwards. Otherwise: leave an existing top-levelroot = ...untouched, otherwise prependroot = trueplus one blank line; for[*.md], the detected strict glob,[docs/wip/**.md], and[**/SUMMARY.md], leave any existing explicitprim_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 initshall 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 underdocs/wip/where that section applies, and aSUMMARY.md— it shall resolveprim_mdlint_strictthrough 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 initshall 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 = truestops 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. Wheneverprim initwritesroot = true— scaffolding a new file or prepending to an existing one — and the target directory currently reaches an.editorconfigabove 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 butrootis 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 andprim initcannot 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 initshall 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 initshall then resolve the file it leaves behind: for every canonical section present in it that carriesprim_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 buttrueresolves tofalse). 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 initresolves 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, andprim initshall 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 setsprim_mdlint_strictnor receives it — an ordinary[*.md] max_line_length = 80— shall take no part in that ordering. Runningprim inittwice 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 theignorecrate) without invoking git, and shall function in non-git directories. -
FR-4.2a
--no-ignoreshall disable only the git-family ignore rules from FR-4.2 (.gitignore, global gitignore,.git/info/exclude). It shall not disable.primignore, CLI--excludeglobs, or the.git/metadata-directory prune. -
FR-4.2b
--since <REF>and--stagedshall further restrict the matched file set through git-native diffs, and they shall be mutually exclusive.--since <REF>uses plain two-waygit 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.--stagedusesgit diff --name-only --cachedsemantics: paths staged in the index relative toHEAD. 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 (exit2) if git is unavailable, the current working directory is not inside a git working tree, or<REF>is invalid. -
FR-4.2c When
--stagedselects 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--stageddoes not update the index (#159). The warning shall namegit diff, which shows the unstaged result it just produced, and shall not namegit diff --cached, which compares the index againstHEADand 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, andgit addwould 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
--sinceor--stagedselect. prim shall read raw NUL-separated paths, so no quoting form hides a path (#164), and shall pindiff.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 (exit2) naming that path, rather than drop it. prim shall raise a usage error (exit2), 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 exit2for 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.--sincetherefore requires git 2.24 or newer, which is when--end-of-optionsreached 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, orassume-unchanged. A path that is absent, tracked, and of a type prim owns shall raise a usage error (exit2) 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-primignoreshall 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.primignorebeneath 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
.primignorecovers 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
.primignorefiles 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.gitentry, 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.primignorewhen 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.primignorethat 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 exit2when 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. A0there 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 exit0in 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 (exit0). 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
.editorconfigprim initwould 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 exits0rather than2.prim initis the one route that exits2, 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
.primignorereach 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 refuseprim fmt /tmp/...on a platform where/tmpis 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..., orprim 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.editorconfigcascade 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(alsofix --check) shall write nothing, exit0when 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 exits2instead of0(FR-4.4c). - FR-5.3
prim fmt --diffshall print a unified diff of pending changes and write nothing; it shall exit0whether or not changes are pending (--checkis the CI gate).prim fix --diffsharesfix --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, sincefix’s--checkand--diffare both format-drift gates, unlikefmt --diff’s preview-only behaviour (AD-0007 §4). Being gates, both also exit2when the run examined nothing (FR-4.4c);fmt --diffdoes not. - FR-5.3a
prim fmt --check-idempotence(also reachable as bareprim --check-idempotencethrough the permanentfmtalias) 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.editorconfigstyle, and exits1if any second pass still changes bytes. It lists each failing file on stdout, exits0when every second pass is stable (2when 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...andprim fix --dry-run --format json PATH...shall emit a versioned, exact, no-write effect plan. Each effect is a whole-filereplace_contentsoperation 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 explicitfmtorfixinvocation shall produce every plannedafterdigest and length when the input bytes and effective EditorConfig remain unchanged. No effects exits0, one or more replacements exits1, and an operational error exits2while retaining effects computed for other inputs. Errors use FR-5.8a’s stable codes. The document shall conform toschemas/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 onfmt,lint, andfix), prim shall read stdin and, forfmt/fix, write the formatted result to stdout. The flag is mutually exclusive with--checkand--diff. - FR-5.5
prim lintshall report hygiene and content violations without ever rewriting a file; it has neither--checknor--diff(report-only is its only mode). Being report-only makes it a gate throughout: alintrun that examined nothing exits2(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 lintshall report each whitespace-hygiene violation individually: a leading BOM, a line ending that does not match the resolvedend_of_line, trailing whitespace, an indentation character that contradicts the resolvedindent_style, and a missing final newline (wheninsert_final_newlineis set). Each finding carries a stable, namespaced diagnostic code (hygiene::bom,hygiene::eol,hygiene::trailing-whitespace,hygiene::indent,hygiene::final-newline) and a 1-indexedfile:line:col(prim_fmt::line_col, AD-0008), printed aspath: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 lintshall runrumdl_lib::lint()in Standard flavor throughprim_fmt::lint_markdown, building prim’s active rule subset by name throughrumdl_lib::rules::create_rule_by_name. The per-file.editorconfigkeyprim_mdlint_strict = true|false(defaultfalse) is resolved through the normal EditorConfig cascade;falseruns the always-on floor tier of 12 defect rules,trueadds 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-indexedpath:line:col, printed aspath:line:col: message [MD0xx]. This path is lint-only: prim shall never invoke rumdl’s formatter or auto-fix Markdown findings, andprim fixdoes 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 = trueonly, 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 fromACTIVE_RULESentirely: 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 inmdlint/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 = falseandcode-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-lengthfrom the resolvedmax_line_length, written to both rumdl’s global and the rule’s own key so their precedence rule cannot change the answer; andheadings = falseat the floor tier,trueat 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 to1; no Markdown rule emits a warning. - Rule configuration prim owns: prim passes rumdl a
Configwith MD025’sfront-matter-titleoption emptied, so a page’s front-mattertitle: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-resolvedprim_mdlint_strictfor 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::lintapplies them internally before returning findings, independent of thesource_fileprim 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.5a (hygiene diagnostics, story B1) For the un-owned-text
allowlist (the orphan set, shell excluded — same scope as FR-2.4/2.5),
- 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--excludeglob, a--sinceref — remains a usage error (exit2, 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-filepathshall echo stdin to stdout and exit2, and the LSP shall return no edits, no diagnostics, and keep the session.lint --stdin-filepathwrites a report to stdout rather than a buffer, so it echoes nothing. A--formatrun shall still emit its report document, since--formatgoverns stdout alone. - FR-5.7 (deprecated top-level flags) The top-level
--check,--diff, and--stdin-filepathflags remain accepted directly on bareprimas deprecated sugar for thefmtforms; 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 onprim fmt --checkandprim lint. In addition,--format jsonis required byprim fmt --dry-runandprim 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 forfmt --checkandlintremains unchanged.- FR-5.8a
--format jsonshall 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 includespath,code, andmessage; positioned findings also include 1-indexedlineandcolumn. Each operational error includes a stablecodeandmessage, pluspathwhen the error belongs to a file. A finding or error whose path is not valid UTF-8 also includespath_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 --checkreports oneformat::driftfinding per file that would change, with the message"would be reformatted".prim lintreports the existing coarse structured format drift asformat::drift, plus the B1 hygiene diagnostics for orphan files with their stablehygiene::*codes and positions. Operational failures use the stableinput::read,format::parse,internal::panic,scope::empty, orscope::resolvecode. A partial failure preserves findings from files prim could examine; a full failure still emits one complete document with an emptyfindingsarray. Both exit2. - FR-5.8b
--format sarifshall emit a valid SARIF 2.1.0 log with one result per finding or operational error. Each result’sruleIdshall match the stablecode,artifactLocation.urishall 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) — andregion.startLine/region.startColumnshall be present whenever the finding has a known position. Operational errors have levelerror; 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 exit2.
- FR-5.8a
- 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 --checklist, the same list underfmt --check-idempotence(FR-5.3a), and both plain-textlintfinding shapes — the positionedpath:line:colprefix and the coarsepath: messageline. Two stdout writers are not covered and stay lossy: thefmt --diffpatch header andprim explain. Rendering throughPath::displayreplaces each byte that is not valid UTF-8 with U+FFFD, which names a file that cannot be opened and breaks the documentedprim fmt --check --since <REF> . | xargshook (#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_encodedin JSON (FR-5.8a) and a percent-encodedartifactLocation.uriin 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 jsonshall emit one deterministic JSON document and exit0, without walking files, resolving repository configuration, or applying file-selection flags. A missing format or any format other than JSON is a usage error (exit2).- FR-5.10a The document shall conform to
schemas/prim-registry-v1.schema.jsonand containschema_version: 1, the running tool name and version, adiagnosticsarray sorted by stable code, and requiredaliasesandretiredarrays. 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_disablevalidation. Registry configuration keys shall share definitions withprim 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 inaliases, and a code that no longer emits is recorded inretired.
- FR-5.10a The document shall conform to
FR-6 — Correctness & safety
- FR-6.1 (idempotency) Running prim on its own output shall produce zero
further changes.
prim fmt --check-idempotenceis 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 makeprim 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 isprim-<version>.spdx.json, where the version excludes the tag’s leadingv. - RI-2 The reusable
.github/workflows/release-build.ymlshall build, package, sign, and attest the archive in the same job. The caller.github/workflows/release.ymlshall generate the SBOM from the tagged source andCargo.lock, using Syft v1.51.1spdx-jsonoutput, requirespdxVersion == "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/primand the reusable signer workflow, and exact verified subject names and SHA-256 digests. Archive cosign certificates shall identifyrelease-build.yml; the SBOM certificate shall identifyrelease.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 byorigin/mainand 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 scheduledcargo auditgate 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 embeddingshfmtcompiled 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.