Skip to content

Latest commit

 

History

History
437 lines (288 loc) · 100 KB

PRODUCT.md

File metadata and controls

437 lines (288 loc) · 100 KB

Product Vision & Requirements

Vision

Measure a project's own codebase with understandable scope, test/production distinctions, and useful folder totals. LOCmetry is a policy-and-reporting layer over an established counter. Agents consume predictable JSON; developers get readable summaries and reviewable project configuration.

The product rests on three pillars:

  • Expressive configuration: reviewable project policy covers real repositories' scope, ownership, and classification needs, including build tooling, examples, generated code, and evidence.
  • Reuse with gap filling: the embedded counter does the counting; LOCmetry layers on top of its library and fills gaps it leaves, such as unrecognized file types, instead of reimplementing it.
  • Rich output: reports summarize the measurement, while full JSON keeps provenance and the effective policy, with per-file records when --files is requested so agents and scripts can answer further questions, including their own summations.

Scope and Status

  • Required: embedded Tokei integration in a Rust executable, test/production classification, production source derived from build descriptors, project configuration, personal defaults, and CLI options, a configuration schema that explains its semantics, configurable exclusions, language mappings for files the backend does not recognize, folder breakdowns and sums, a workspace mode that merges several repositories, JSON, human output that locates unclaimed source, net change between saved full reports, and focused explanations of a file's selection and classification.
  • Optional: further module detectors, additional counting adapters, custom content-kind overrides, and configuration self-checks that assert expected classifications for named paths without requiring those files to exist.
  • Excluded initially: a new counting engine, a generic plugin framework (module detectors are compiled-in implementations of one trait, not loadable plugins), and semantic splitting of production/tests within individual files.

LOCmetry is a Rust executable with LOCmetry's fork of the Tokei library embedded, which corrects how Tokei lexes literals, released for macOS arm64, Linux x86_64 and aarch64, and Windows x86_64. The installed executable must not require Python, Git, a separate Tokei executable, or a separately installed Rust runtime; the Homebrew formula installs the prebuilt release executable without runtime formula dependencies, needing Rust only to build --HEAD. Tokei integration and distribution records the backend boundary and packaging.

Release archives and Homebrew installations also include the optional compare-locmetry-files.sh Bash helper. It requires separately available jq and LOCmetry, reports a missing jq with an installation hint, and does not add dependencies to native commands. Its file-level review workflow and output limits belong in the comparison guide.

Measurement Model

Concept Meaning
Scope Whether a file belongs in the measurement; external/reference material is an inclusion decision, not a test category.
Kind source, data, documentation, or unknown, derived from the backend language through a reviewed mapping; a JSON test fixture remains data. unknown marks a counted language name this version's counter does not know, such as one from a newer report; unrecognized files, by contrast, are not counted at all.
Purpose production, test, or other. Production means maintained non-test source, not necessarily shipped runtime code; other is source that counts as neither, whether no stage claimed it or an entry assigned it on purpose.
Category Optional project-defined label such as implementation, tooling, test-support, example, benchmark, or evidence. It does not change counting.

Report code, comments, blanks, and total lines separately. Preserve each file's language and classification provenance; a language supplied by a mapping records the mapping ID. Embedded snippets inherit the host file's scope and purpose; documentation snippets do not inflate source totals. Documentation embedded in a non-documentation file, such as a Vue <template lang="markdown">, contributes its lines as comments of the host language; Rust doc comments, doctests included, are comments of their file. Derive human summaries and versioned JSON from the same records.

Project Configuration

Use .locmetryrc in TOML. Discover it in the selected scan root (locmetry DIR or locmetry --root DIR), which defaults to the current directory; an explicit --config path may select a different file without changing that root. Without a discovered or explicit configuration, built-in settings apply; an explicit configuration that cannot be read fails. Project configuration is policy, not project content: every file named .locmetryrc is excluded as **/.locmetryrc, loaded or not, so a nested project's file or the checked-in one beside an explicit --config does not change coverage; a loaded configuration with another name inside the scan root is excluded as a literal path. The effective exclusions record both, even when default exclusions are off. All patterns remain relative to the scan root. How it combines with built-in settings, user defaults, and command-line flags is defined in Matching and Precedence. A configuration file ending in .json, the retired JSON/regex profile format, is rejected with a hint to translate it to TOML. An invalid configuration, personal defaults or workspace file fails with exit 1 before scanning and names the file, with line and column where the TOML parser reports them. Its message uses TOML's words, such as array and table, and names the likely fix where one is close: the field, value or language name meant, [[languages.mappings]] for language_mappings, except for exclude in an entry, [[rules]] for a single [rules] table, or, for an unknown field without one, that a newer release may define it; an unsupported version names the version this release reads.

Single-root measurement accepts one optional directory argument, resolved from the working directory, and rejects combining it with --root or another directory. Bare command names retain their subcommand meaning regardless of directory existence; use a path such as ./compare, --root compare, or -- compare to measure a directory with that name. Root measurement arguments cannot be combined with a subcommand; each command's options follow its name. Positional directory selection uses the same config discovery, scope, output validation and counting as --root. Workspace and explanation commands retain their own argument forms. Adding a reserved command name can affect existing bare-directory invocations and requires compatibility review; scripts should use --root for arbitrary directory names.

locmetry --schema config prints the JSON Schema (Draft 2020-12) of this file, --schema user-config that of personal defaults, and --schema workspace that of a workspace file, then exits; --schema report describes the report (see Reporting and Coverage), --schema comparison describes net change, and --schema explanation describes path explanations. The schema is generated from the parser's types, so it accepts the same keys, types, and enums; checks it cannot express, such as glob syntax and unique IDs, still fail when the file loads. Its descriptions state each setting's default and meaning, the classification order, and this version's built-in conventions, build-module layouts, and language names, so an agent can write a configuration from the binary alone.

This example is synthetic:

version = 1
backend = "tokei"

[scope]
hidden = true
respect_ignore_files = true
exclude = ["reference-material/**"]

[classification]
builtin_tests = true
fallback = "other"

[languages]
builtin = true

[categories]
archived = "Archived probes kept for provenance, not maintained."
test-support = "Helpers that exist only for tests."
tooling = "Maintained scripts that check or release the project."

[[languages.mappings]]
id = "runbooks"
match = ["scripts/*.runbook"]
language = "BASH"

[[overrides]]
id = "archived-evidence"
match = ["docs/archive/**"]
kind = ["source"]
purpose = "other"
category = "archived"
reason = "Archived probes are kept for provenance, not maintained."

[[overrides]]
id = "shared-test-support"
match = ["packages/test-tools/**"]
purpose = "test"
category = "test-support"

[[rules]]
id = "maintained-tooling"
match = ["scripts/**"]
purpose = "production"
category = "tooling"

[[rules]]
id = "application-source"
match = ["src/**", "packages/*/{src,bin}/**"]
purpose = "production"
category = "implementation"

Subfolder Measurement

locmetry ROOT --subfolder DIR (equivalently --root ROOT) measures one literal root-relative folder and its descendants while retaining the project root's policy, selected module context and path identities. It is a single-root CLI option, not a configuration setting, glob, file selector or workspace option. Ancestor configuration discovery remains unsupported. Other command options and explicit configuration keep their existing bases; --config never changes the project root.

The folder must exist, have exact on-disk spelling, and stay beneath the project root without symlinks. Reject empty/absolute paths, .. components and files. Normalize . components and trailing separators; --subfolder . is equivalent to no restriction. A target directory or ancestor filtered by exclusions, ignore or hidden policy fails with no report. Diagnostics name recorded exclusions or a cause established by a single-setting probe, with a remedy; overlapping filters may leave the cause unknown. Overrides such as --hidden true or --respect-ignore-files false change policy for the whole project, including module context. A selected empty folder, including one whose children are all filtered, remains a valid empty measurement.

Count and classify each measured file exactly as an unrestricted run under the same policy would. Discover module context from the whole selected project before restricting counting; excluded descriptors do not become evidence. Only measured files contribute counts, coverage and backend inaccuracy. Context traversal failures still abort. A .locmetryrc directly inside the selected subfolder stays inactive unless explicitly loaded; one stderr warning names it and the effective project configuration. This warning does not change status or policy.

Record the normalized directory as optional metadata.scope.subfolder in headline and full JSON. Absence means no restriction; null, empty strings, ., dot/parent components, repeated/trailing separators and absolute paths are invalid saved values. Paths remain project-relative. metadata.modules retains all selected project context; in a restricted report, summary.build_modules counts, as in an unrestricted report, only modules credited with at least one measured production source file (even a zero-code file), and their measured code. Other summary totals, breakdown, review and coverage describe the measured selection. Unused-entry/exclusion findings concern this subtree only; configuration-cleanup instructions apply only to an unrestricted run.

JSON folder identities and top-level grouping stay project-relative. Folder table rows requested with --show-folders partition source into immediate children of the selected subfolder and a direct-files row, with full project-relative labels. Markdown depth starts below the selected subfolder: depth 1 includes immediate children, depth 2 their children. Parent rows remain recursive, so Markdown rows are not additive. Human titles expose the restriction. Output destinations must remain outside the entire project root.

Comparison requires identical recorded subfolder values, including presence versus absence, and otherwise fails without producing or overwriting output. Matching restrictions still retain ordinary policy and coverage findings. Comparison module/package topology describes recorded project context; totals come only from measured contributions. Existing explain PATH --root ROOT provides the same per-file decision using project-relative paths, with no subfolder option. Measurement semantics covers traversal limits; report compatibility covers consumer obligations.

User Defaults

Personal defaults live in $XDG_CONFIG_HOME/locmetry/config.toml when XDG_CONFIG_HOME is an absolute path. Otherwise they live in ~/.config/locmetry/config.toml on macOS and Linux, and in %APPDATA%\locmetry\config.toml on Windows, where Tokei, cloc and uv also keep user configuration. They may only narrow scope and teach languages, never assign purpose or category. Personal mappings can nevertheless change recognition and content kind, so reproducibility requires the same effective personal settings or --no-user-config:

version = 1

[scope]
exclude = ["**/*.generated.ts"]

[[languages.mappings]]
id = "runbooks"
match = ["**/*.runbook"]
language = "BASH"
  • version is required and must be 1. scope.exclude is added after the default exclusions and before the project's. languages.mappings apply after the project's mappings and before the built-in ones; mapping IDs must be unique across both files.
  • Any other key fails, as does invalid content; a missing file is ignored.
  • Reports record the file as metadata.user_config_path, or null. --no-user-config skips it, for CI or for comparing measurements across machines.
  • Excluded: user-level classification entries, scope booleans, and nested project configurations.

Module Detection

A selected build descriptor triggers conventional source-layout inference: its directory becomes a build module, and the detector's default source layout inside that module is production. This is whole-file classification, not semantic membership in build targets; custom manifest targets and scripts require explicit policy. Build systems call this unit a module, project, package, or crate; it is unrelated to language-level modules or packages, and this document's "module" always means a build module. Detectors inspect selected file names, without parsing manifests or running builds. Each build system is one detector, so supporting another one adds a detector without changing the stages. Detector layouts are not selected by version: a release that narrows or widens an existing layout marks the change Breaking, as the Go layout's exclusion of vendor/, testdata/ and names starting with _ or . was, accepted 2026-10-23 by the owner under the pre-1.0 policy.

The built-in detection reference lists every detector with its descriptors and production source, in detection order, and explains how detectors and conventions combine.

The innermost module containing a file decides, as build tools treat nested projects: an outer module's layout never claims files of a module nested inside it, while build systems sharing one directory, such as Gradle and npm, combine their layouts. Where those layouts overlap, the detector whose ID sorts first decides, such as cargo before npm; purpose and category are the same either way, so only provenance and the per-module totals depend on it. Test and build conventions run earlier, so tests inside these trees stay tests. Files outside every module's production source keep the fallback, because no applicable conventional layout claimed them. A module is credited with the production source its layout covers, as the innermost covering module chosen by these rules, whichever stage decided the file: an entry that keeps production and only names a category, such as native or generated, keeps the credit, while one that changes the purpose to test or other removes it. Each such file names its module as module in per-file records. The report file lists every detected module as metadata.modules; the summary's build_modules and the --verbose note count only modules credited with at least one measured production source file, and their code, while the Markdown report lists every module, where 0 hints at a misleading build file. Because a layout decides production without review, summary.largest_module_files, the --verbose note and the Markdown module section name the five largest source files module layouts claimed, by code and then path, with their lines, module folder and detector; exclude or reclassify a generated or vendored file among them.

Matching and Precedence

Four layers combine into the effective configuration. Only the project layer sets purpose/category policy; personal mappings and scope options can still affect which files and kinds enter that policy:

Layer Source May set Combination
Built-in version conventions, language mappings, default exclusions applies unless the project switches it off
User defaults User Defaults file scope.exclude, languages.mappings exclusions are added; mappings apply after the project's and before the built-in ones
Project .locmetryrc in the scan root, or the file --config names every key exactly one file: --config replaces discovery, and other .locmetryrc files are never read
Command line --exclude GLOB, --hidden BOOL, --respect-ignore-files BOOL, --no-user-config scope exclusions are added; the booleans replace the project's; --no-user-config drops the user layer; in workspace mode only --no-user-config is accepted

Exclusions from all layers form one union, so their order is irrelevant and no layer can re-include a file another excluded. Every file then takes the first matching stage:

  1. Apply scope exclusions and the selected ignore-file policy.
  2. Apply the first matching overrides entry.
  3. Apply built-in test conventions, then built-in build conventions, if enabled; provenance records the convention, for example builtin:gradle-test-source-set.
  4. Apply the first matching ordinary rules entry.
  5. Apply module detection, if enabled: source in a conventional production layout inferred from a selected build descriptor is production with category implementation, and provenance names the detector, for example builtin:npm-module. A generated-code marker, if enabled, refines such a file to category generated, and provenance names the marker, for example builtin:roslyn-generated.
  6. Assign classification.fallback if no classification matched.
  7. Apply the first matching refinements entry whose purpose equals the file's decided purpose, unless the file reached the fallback or a generated-code marker refined it: it replaces the category, records its ID as the file's refinement, and leaves purpose, rule and module credit unchanged.

An entry matches when any of its patterns matches the path, none of its except patterns does, and, if kind is present, the file's kind is listed. A file an entry's except leaves out falls through to later entries and stages, as if the entry were absent. A match terminates purpose/category classification. Each file records its provenance as the matching entry ID, builtin:<convention>, or fallback; fallback files receive category unclaimed. Broad production rules therefore do not swallow conventional tests or build scripts, while an explicit archived-evidence override can take precedence over test filenames. Entries that assign ownership of a whole tree, such as a test-only package whose build scripts are test support, belong in overrides so built-in conventions do not preempt them. No ordinary run requires an LLM; agent assistance proposes reviewable configuration.

The built-in build-wrapper convention matches gradlew, gradlew.bat, mvnw, mvnw.cmd, and files under gradle/wrapper/ or .mvn/wrapper/ at any depth. It assigns purpose other and category third-party-wrapper when enabled and no earlier classification wins. Overrides and built-in test conventions take precedence; for example, tests/gradlew matches the test-directory convention under default policy. classification.builtin_build = false disables build conventions, including wrappers. These patterns do not change selection or make unrecognized binary files countable. The built-in detection reference lists every convention, and the built-in definitions and locmetry --schema config enumerate the executable rules.

The stage order is fixed, so where [[overrides]], [[rules]], and other tables appear in the file is irrelevant. Order matters only within a list: the first matching entry of overrides, of rules, of refinements, or of languages.mappings decides, and built-in conventions apply in their documented order. Because rules precede build modules, a rule also takes source a build module would claim; it should match only the folders it is about. Within the module stage, nesting and same-folder overlaps resolve as Module Detection defines.

Measurement counts and ordering are deterministic for identical selected file contents, effective configuration, backend settings and LOCmetry version. Selection also depends on repository, parent and global ignore context. Timestamps, project/member names and contextual paths can differ across runs or locations; reports do not fingerprint source, ignore contents or executable builds. No counting result depends on traversal order, and report lists have defined ordering.

Setting Type and contract
version Required integer; initially 1. Unsupported versions fail. It selects the sets of built-in conventions, generated-code markers and language mappings: a release may add entries to a set and new build-module detectors, which can reclassify files, but changing or removing an entry requires a new version. Every report records what it applied as metadata.config.builtin_conventions, metadata.config.builtin_generated_markers, metadata.config.builtin_language_mappings, and metadata.modules, so measurements by different releases can be compared.
backend String; initially only tokei, also the default.
scope.hidden Boolean, default true; hidden-file selection is independent of metadata exclusions.
scope.respect_ignore_files Boolean, default true; controls the adapter's ignore-file policy.
scope.exclude Array of root-relative glob strings, default empty, added to the default exclusions. A folder is excluded as <folder>/**; patterns that exclude nothing are reported as summary.unused_exclusions.
scope.default_excludes Boolean, default true; applies **/.git/**, **/node_modules/**, and the SwiftPM and Lake build folders **/.build/** and **/.lake/**. false is the only way to drop them. build directories are not excluded by default because they can hold maintained source; ignore files normally exclude build output.
classification.builtin_tests Boolean, default true; enables the built-in test conventions selected by version, which the built-in detection reference lists, and which every report records as metadata.config.builtin_conventions. Ambiguous names such as fixtures and spec are left to project entries.
classification.builtin_build Boolean, default true; enables the built-in build conventions selected by version, which the built-in detection reference lists, and which reports record with the test conventions. Build scripts and the configuration of named JavaScript tools are production with category build-tooling, so they stay separate from implementation; and build-tool wrappers such as gradlew are other with category third-party-wrapper.
classification.builtin_modules Boolean, default true; enables module detection (see Module Detection). It runs after rules, so it changes only files that would otherwise reach the fallback.
classification.builtin_generated Boolean, default true; enables the generated-code markers selected by version, which the built-in detection reference lists, and which every report records as metadata.config.builtin_generated_markers. Module-claimed source that carries a marker, such as Go's // Code generated … DO NOT EDIT. line, Roslyn's generated names and comments, Java's type-level @Generated or a .gitattributes linguist-generated declaration, is production with category generated and the marker as its rule, such as builtin:go-generated-header. Purpose, totals and module credit stay the same; files an override, convention or rule decides keep that decision, and -linguist-generated or linguist-generated=false in .gitattributes declares a file not generated. Markers read the leading comments or declarations of Go, C#, Visual Basic and Java files and the .gitattributes files of the directories holding counted files, so they need module detection.
classification.fallback Purpose enum, default other; projects can explicitly choose another purpose. Files reaching the fallback get category unclaimed. Since 0.5, the retired value unclassified fails with a message naming other.
languages.builtin Boolean, default true; enables documented language mappings for common file types the backend does not recognize, such as .gradle scripts as Groovy and .jsonc as JSON. version selects the set, which the built-in detection reference lists, and every report records it as metadata.config.builtin_language_mappings.
languages.mappings Ordered array of {id, match, language} entries, applied before built-in mappings. language must be a backend language name. Mappings apply only to selected files the backend does not recognize; backend detection is never overridden. The first matching mapping counts the file with the backend's parser for that language. A project mapping's id shares one space with overrides, rules, refinements and corrections, and summary.policy_entries audits it: a selected file it matches that the backend recognizes is preempted by builtin:recognition, so a mapping that counts no file appears in summary.unused_entries. Personal mappings apply to every project and stay out of that audit.
languages.corrections Ordered array of {id, match, language} entries with an optional reason, for files the backend recognizes wrongly, such as LaTeX class files read as Visual Basic 6. Only the project configuration may set them. The first matching correction decides before the backend recognizes the file, and mappings no longer apply to it: a backend language name counts the file with that language's parser and content kind, and the reserved unrecognized leaves it selected, uncounted and listed in metadata.coverage.unrecognized. Counted files name the correction as language_correction; IDs share one space with overrides and rules, and a correction that decides no selected file is listed in summary.unused_entries.
categories Optional table mapping category names to their meanings. When present, every entry category must be declared there or be built in: a purpose name, implementation, or the category of a built-in convention or marker (test, build-tooling, third-party-wrapper, generated). It catches typos and invented names; without it, categories are free-form. The effective configuration records the meanings.
overrides, rules Ordered arrays of entries; omitted arrays are empty. Each entry requires a unique string id (not fallback, which names the fallback provenance), a nonempty string-array match, and a valid purpose. category defaults to the purpose. except is an optional nonempty string array of globs the entry leaves out. kind is an optional nonempty array of kinds. reason is an optional string recorded in the effective-policy snapshot.
refinements Ordered array of entries that change only a decided file's category. Each requires a unique id, a purpose naming the decided purpose it applies to, a nonempty string-array match and a category; except, kind and reason are optional, as for rules. A refinement that relabels no file is listed in summary.unused_entries.

Match normalized root-relative paths with case-sensitive globs: * stays within a segment, ** spans zero or more directories, ? matches one non-separator character, [...] matches one character from a class, and {a,b} matches any listed alternative, an empty one included, so run{,.cmd} matches run and run.cmd. Backslash escapes the next character on every platform. Any pattern in match selects its entry. Patterns do not use implicit basename matching, negation, or absolute paths. Reject invalid patterns, unknown keys, duplicate IDs, and invalid types/enums.

Explicit exclusions still apply when ignore files are disabled. Removing a built-in exclusion does not override a repository ignore rule; use the project's ignore exceptions or an explicit ignore-file policy. Backend pattern syntax must not silently alter these semantics.

Workspace Mode

A workspace measures several repositories as one virtual monorepo: each member is measured exactly as a regular run would measure it, with its own .locmetryrc, and the results merge into one report whose top-level folders are the members. Alternatively, a workspace file names folders of one project, each measured exactly as --subfolder measures it under the project's single .locmetryrc.

  • Selection: locmetry workspace --root DIR [--root DIR ...] names the members, relative to the working directory or absolute; locmetry workspace --workspace-file FILE reads them instead from a TOML workspace file with version = 1 and roots, an array of paths relative to the file's folder or absolute, or with project, one such path, and folders, an array of literal project-relative folders. roots excludes project and folders, which require each other. --workspace-file and --root exclude each other, and a workspace file is read only when named, never discovered. locmetry --schema workspace describes the file. Plain locmetry is unaffected, and options given before workspace are rejected, so the mode is always explicit.
  • Options: --config, --exclude, --hidden, and --respect-ignore-files are rejected, because each member's own configuration decides them. --no-user-config applies to every member; --format, --output, --files, --show-categories, --sort, and --markdown-depth apply to the merged report using Output Routing. --output must lie outside every member's root, which members that are project folders share with their project, and must not overwrite the workspace file.
  • Members: each member is named after its root's folder name, or the last segment of its project folder, and every report path is prefixed with it, as in web/src/a.ts. At least one root or folder is required; two members with the same name, a root or folder named twice, or one inside another fail before measuring. Project folders follow the subfolder rules: they must exist and stay selected, . is rejected, and files outside every folder are not measured. A member that contains the workspace file does not measure it, as with a configuration file.
  • Determinism and failure: members are measured in parallel and merged in name order, so neither the order of roots nor thread scheduling changes the report. If any member fails, for example with an invalid configuration, the run fails and names that member; there is no partial merge.
  • Report: the merged report keeps the regular shape: totals, top_folders (one per member), categories, unclaimed_folders, submodules, build_modules, largest_module_files, review, breakdown, files, and metadata.coverage and metadata.modules cover the prefixed records, and project joins the member names with +. metadata.members lists each member's name, root, config_path, scope, unused_entries, unused_exclusions, policy_entries when its own policy has entries, and coverage, plus its effective config in full JSON; metadata.workspace_path names the workspace file when one was used. These settings and findings are relative to one member, so in workspace mode they appear there instead of in metadata.root, metadata.scope, metadata.config_path, metadata.config, and summary.unused_entries, summary.unused_exclusions and summary.policy_entries. Human notes name the member, as in ghost (web). A project-folder member records the project as root, its folder as scope.subfolder and the project's configuration. Because the folders share one policy, its unused entries and exclusions are those unused in every folder; they appear once in summary.unused_entries and summary.unused_exclusions, without member names, and the members' own lists are empty. Its summary.policy_entries adds up the folders' counts, and a glob is unused only when it is unused in every folder. A build module enclosing a folder is reported at that member's root, and only when it is credited with the folder's files. The human footer names the project and its folders.

Excluded: discovering a workspace file, explicit member names, overlapping members, mixing roots and project folders in one workspace, and configuration inherited across independent roots.

Per-Member Breakdown

A workspace adds the member as a dimension of the merged report, so members, whether repositories or one project's folders, can be compared beyond code per purpose. Human output calls them members.

  • summary.members, keyed by member name, holds each member's totals in the shape of the summary's own: all_counted, source, by_kind_purpose, source_purpose, source_categories, and source_languages. They equal what a regular run of that member reports; for a project folder, the project's --subfolder run of that folder.
  • metadata.members also holds each member's coverage counts: selected_files, counted_files, mapped_files, unrecognized_files, unread_files, and parse_failed_files (always emitted now; absent in older reports).
  • The terminal table shows member rows in place of folder rows: total source lines, code, production, test, other, Test Code divided by Production Code, and the share of the workspace's source code, with a total row.
  • The Markdown report adds a Members section with the same table, followed by source categories and source languages by member, as grids with Lines and Code columns per member and corresponding total columns; rows follow --sort.
  • Default and verbose tables name each member with read/parse failures under Unavailable counts:, listing only its failure counts. --verbose separately lists unclaimed source by member. Markdown retains its comprehensive combined member note. Unrecognized types appear only in the verbose table’s neutral Unrecognized files: note and in Markdown/JSON coverage; they are not counting failures.

Excluded: detecting copies across members. Saved measurements can be compared through net change.

Reporting and Coverage

Reports serve aggregation: totals by purpose, category, kind, language, and folder. Count original file reports and embedded statistics once. breakdown rows are additive, and so are top-level folder totals, which cover each subtree and, with the root files, every file once. The Markdown folder table lists nested levels, in which a parent includes its subfolders, so its rows are not all additive; it also shows each folder's Test/prod ratio, and its language table each language's.

Embedded Task Guides

Available since v0.4.0: --guide configure|selection|reports|compare|categories|reference prints one task-oriented Markdown guide with a source-path and producer-version header. The rest of stdout equals the repository Markdown source; successful output has no stderr, styling, paging, project/configuration reads or network dependency. Relative links remain unchanged and supplementary; essential instructions are self-contained, and cross-guide navigation names executable commands. The six guide sources cover configuration, selection, report interpretation, comparison, the non-binding category reference and the reference for exit status, environment, files, the man page and completions, a reader's view of guarantees this contract owns; --guide index prints the task index, which routes each task to the sections and schema definitions it needs.

--section ID prints one section of a guide or schema, so that a task reads only what it needs; repeated, it prints several sections of the one topic in the order given, and a repeated id fails. For a guide, ID is a ## or ### heading's GitHub anchor, and each section prints as the source line, naming the section, followed by the heading and its text up to the next heading of the same or a higher level. Ids ignore case. For a schema, ID is overview, the name of a $defs definition or the name of a top-level property; a definition wins over a property whose name differs only in case. overview is the root with $defs reduced to their names and properties kept in full, so a shadowed property's default and description stay readable. The output is one pretty-printed JSON object whose keys are the requested sections in order, spelled as the schema spells them, also for a single id, and whose values are fragments; their $ref values resolve against the full schema. --section requires exactly one --guide or --schema topic and follows their standalone-query rule. All ids are checked before anything is printed: an unknown section fails with exit 1, empty stdout, the unknown ids and the topic's valid ids. A routed section states its own prerequisites or the route names the reads they need. The published ids stay requestable; removing one is a breaking change.

Root long/short/help-command output leads with source counts by language, names --show-folders for folder rows and --verbose for classification/scope/coverage notes, and presents locmetry --guide configure as optional configuration. Long help describes all topics and includes common-command examples, which the README task table mirrors, followed by a maintained-scripts TOML rule and a command that saves per-file JSON and prints a verbose table. For production-rule changes covered by that example, help directs the reader to inspect existing configuration, measure current decisions, adapt the example and verify decisions and unresolved review items; initial guide/schema reading is optional. Other needs are directed to sections: test or script categories, category names, and the task index for the rest; the closing pointer also names the index. Root long help also supplies selection, JSON, adaptive table and Markdown recipes, with compact notes on result interpretation, policy precedence, personal defaults and automation status. Explain, compare and workspace long help each include executable task recipes and consequential input, scope and output constraints; their reference queries use the root-level guide/schema syntax. For routine capture-and-compare work, root help directs readers to the executable comparison recipes; additional guide/schema reading is optional for their covered input contract, with summary and findings verification still required. Short help omits the extended examples and notes. Topics are required, case-sensitive enum values. Missing/unknown topics fail with exit 1, accepted names and a help remedy. --guide follows the same standalone-query rule as --schema, and the two conflict. Save guide text by shell redirection.

Man Page and Completions

--generate KIND prints a generated document on stdout: man the locmetry(1) man page in roff, and complete-bash, complete-zsh, complete-fish and complete-powershell a completion script for that shell. It is a standalone query: it accepts --no-color and nothing else, so roots, measurement and presentation options, commands, --guide, --schema and --section fail with exit 1 before anything is written. It reads no configuration, personal defaults or files and scans nothing; --help and --version keep their early exits. Success exits 0 with the document on stdout and nothing on stderr; a missing or unknown kind fails with exit 1, empty stdout and the valid kinds. The option is hidden from --help and -h but supported: removing or renaming a kind is a breaking change. The reference guide shows how to install each document.

The man page renders the root and each command from their help definitions, with options, value names, possible values, positional arguments and each command's long-help examples and notes, followed by the reference guide's exit status, environment and files sections and a list of guide topics; it is dated by its version's release. Completion scripts offer each command's visible options; bash, zsh and fish also complete possible values, PowerShell completes commands and options only. Section ids and category names are not completed. Release archives carry the documents their platform uses, the Linux packages install the man page and the bash, zsh and fish completions, Homebrew generates them at installation, and Scoop's notes name the PowerShell profile line.

Configuration guidance distinguishes evidence-based classification, intentional other entries with reasons, and unresolved unclaimed questions reported to the owner. Correct inferred decisions need no redundant entry. A clean review list does not prove correct policy, and open questions are distinct from invalid configuration or partial counts. Guides own workflows; executable schemas and this contract remain the semantic authorities.

Output Routing

Output contract since v0.4.0. Measurement, workspace and comparison produce one result at one destination; measurement and workspace runs may add one printed view with --print. An explicit --format table|markdown|json|headline always wins. Without it, any --output selects full JSON. Otherwise an option that shapes only one format selects that format, on a terminal and in pipes alike: the table presentation options listed under applicability, --show-folders, --folder-rows and --tables-only select a table, --markdown-depth Markdown and --files full JSON. Options of different formats select none, and --split-languages and --sort, which shape tables and Markdown, select neither. Failing that, stdout selects a table on a terminal and a compact JSON headline in pipes. Changed after 0.11.0: before, such an option in a pipe left the headline and a warning, which agents, running without a terminal, often missed behind their own output filters. File extensions never infer the format.

Destination Behavior
No --output Write the chosen result to stdout.
--output FILE Write only to FILE; stdout stays empty. Full JSON is the default, including when run interactively.
--output - Write the chosen result to stdout; full JSON is the default. Explicit table, Markdown and headline formats are accepted.
--output FILE --print FORMAT Write the result to FILE as above, and the same measurement to stdout in FORMAT (table, markdown, json or headline), from one scan. --print without a file destination fails before scanning with exit 1. The printed view follows stdout's styling and automatic bars; --files affects only full JSON.

json is the complete document. headline is compact JSON: measurement omits review, breakdown, files, metadata.config, metadata.kinds, metadata.modules, metadata.coverage.unrecognized and workspace member configurations. Comparison uses its headline projection. Measurement schema 3 requires document_type: "measurement" and detail: "full" or "headline", and rejects the retired report pointer. Comparison schema 2 retains its historical pointer on reading but does not emit it in new output. --files adds per-file measurement records to every full JSON view, whether saved or printed. At least one view must be json; a headline never includes file records. With no full JSON view, the request fails before scanning or writing. Full JSON without file records is sufficient for aggregate comparison.

File output is always unstyled. Stdout styling follows Human Presentation. Measurement file destinations must be outside the scan root and must not overwrite the configuration; workspace destinations must be outside every member's root and must not overwrite the workspace file. Comparison protects both input files and their aliases. These protections apply to every exported format. Shell redirection and tee are outside these checks; they may truncate inputs before LOCmetry runs and need pipeline status handling to preserve partial-result failures.

Diagnostics go to stderr. LOCmetry's own begin with error: or warning:, as argument errors do, so their severity is readable without color. File exports do not echo the result or its informational findings to stderr; informational findings follow the selected format: saved tables require --verbose for routine notes, while Markdown and JSON retain their established evidence. Partial results are written, produce a stderr warning and retain exit 2; output failures exit 1. Command outcomes owns the status rules. Running twice to display and save separately is not a guarantee of identical filesystem state; --print shows the saved measurement itself. Rendering saved measurements is outside this interface.

View options apply to every supporting saved or printed view of the same measurement. Their format boundaries and ineffective-option outcomes are defined under Option names and applicability.

--schema is a standalone query: it emits its JSON schema on stdout without loading configuration or measuring. It accepts global --no-color but rejects explicit roots, measurement/presentation options and subcommands with exit 1 before scanning or writing. Explicit default-valued flags such as --markdown-depth 2 also conflict; implicit defaults do not. Help/version retain their normal early exits. Redirect stdout to save a schema. explain retains table|markdown|json, no headline and no --output; its pipe default is the complete JSON explanation.

Option Names and Applicability

Help groups selection and policy, output and content, and presentation. Selection options change what is measured; presentation options change a view. In pipes, where the default is a headline, a table presentation option selects a table; explicit --format table keeps a recipe's format independent of its options. --table-purpose, --table-category and --table-language filter tables only; they do not restrict JSON or Markdown measurement totals.

The following are exact option names. Former spellings are rejected, not aliases, with exit 1 and an error that names the current option; command names and unrelated options are unchanged.

Current option Rejected former spelling
--show-folders --folders
--show-categories --categories
--show-bars[=KIND] --bars[=KIND]
--table-purpose PURPOSES --purpose PURPOSES
--markdown-depth N --depth N
--workspace-file FILE workspace --file FILE, explain --workspace FILE

For options accepted by a measurement command, applicability is evaluated across both output views:

Option Supporting view Explicit request without a supporting view
--show-folders Single-root table. Warn on stderr; preserve output and exit status.
--folder-rows N Single-root table, saved or printed. Fail with exit 1 before scanning or writing.
--show-categories, --verbose, --show-bars, --no-bars, --table-purpose, --table-category, --table-language, --tables-only Root/workspace table; for --tables-only also a comparison table. Warn on stderr; preserve output and exit status.
--split-languages Root, workspace or comparison table or Markdown. Warn on stderr; preserve output and exit status.
--markdown-depth N Root/workspace Markdown. Warn on stderr; preserve output and exit status.
--sort code|name Root/workspace table or Markdown. Accept silently.
--files Root/workspace full JSON, saved or printed. Fail with exit 1 before scanning or writing.

Without --format and --output, a single-format option selects its own view (Output Routing), so the outcomes above arise when an explicit format, a saved report or an option of another format decides the view. Implicit defaults do not warn or fail; explicit default-valued depth still warns without Markdown. --sort code (default) orders human rows by descending Code and --sort name alphabetically; Markdown folders retain hierarchy and review rows remain largest first. Global --no-color is accepted for all formats and standalone queries. Applicability does not require a visible change on a particular dataset: sorting empty tables or suppressing already-absent bars remains valid.

Applicability warnings/errors identify the option and supporting format and offer a valid --format remedy, or --print when there is a real saved-file destination. Unsupported-command options and parser/query conflicts remain separate errors; changing formats does not make an unsupported command option valid. --print without a real file destination fails before scanning or writing. These validation failures leave stdout empty and neither create nor modify LOCmetry-managed output files; shell redirection is outside this guarantee.

--markdown-depth N accepts a nonnegative integer, default 2, and limits only the Folder breakdown. Immediate project folders are level 1; positive depth may also include the single-root . aggregate row. With subfolder selection, immediate child folders are level 1 relative to that selection, while labels remain project-relative and direct source files in the selected folder may have a separate row. In workspaces, member names occupy level 1 and their immediate folders level 2. Depth 0 leaves the Folder breakdown without data rows. Review, module and other evidence can still contain deeper paths; depth neither limits scanning nor trims JSON.

Report Content

table shows source Lines and Code per language by default, with language columns ordered Files, Lines, Code, Comments, Blanks before the code split by purpose and a Test/prod ratio. Terminal tables head the Production column Prod. while the full word would be wider than every value in it; legends, Markdown and JSON keep the full term. Optional folder rows and default workspace member rows include Lines before Code, followed by purpose code, Test/prod ratios and reconciliation legends; optional category rows also include Lines before Code. Successful default tables contain no routine findings: non-source totals, build-module inference, the largest files counted as production only by a build layout, Git submodule hints, unclaimed folders, unused configuration and unrecognized-file counts require --verbose. No reminder is added to ordinary output. The default table deliberately gives no indication of data/documentation totals or unrecognized files; its totals cover counted source. This presentation choice changes neither selection nor counts. markdown provides the full human report with recursive folder rows and coverage details. Both group thousands with commas; JSON keeps integers. These are views of the same measurement, not separate scans. Markdown count tables likewise place Lines before Code, including folder, member, build-module and review tables. Lines always means Code + Comments + Blanks; purpose columns and ratios continue to describe Code. Legends clarify Test/prod = Test / Production (Code). Every Test/prod divides classified Test code by Production code, excluding Other; totals divide summed counts rather than averaging rows. - means no production code and 0.00 production without tests. Ratios are neutral at every magnitude; no styling depends on their value. Language tables note that tests written in another language than the code they test skew per-language ratios. When shown rows include Rust #[cfg(test)] code inside non-test files, a muted line per language and purpose names it, such as “Rust production includes 8 code lines of inline #[cfg(test)] tests in 1 file; --files --output - names them.”; it follows the rows' language and purpose filters and is absent when there is none. JSON count objects already retain lines; explicitly code-only projections such as top_folders and build-system classification summaries keep their existing semantics.

--show-folders is a boolean single-root presentation option that adds the folder table. It applies equally to stdout and saved tables, including --subfolder. --folder-rows N implicitly enables the folder table with adaptive detail; both flags may be supplied together. --verbose selects notes independently and does not enable the folder table. Workspace retains member rows by default and rejects --show-folders; comparison, explanation and standalone queries also reject it. Markdown and JSON retain their folder evidence regardless of this option. Measurement dates and real-failure diagnostics remain visible with or without folder rows.

--verbose is a boolean root/workspace presentation option, applying equally to stdout and saved tables and to subfolder/adaptive views. Verbose tables include neutral optional classification advice: “To inspect or refine purpose classification, use '--guide configure'. '--files --output -' shows each file's rule.” The Not source code: note totals files and lines per non-source kind, adds the code lines of embedded languages in those files, such as fenced snippets in Markdown, as “including N code lines in embedded snippets” when there are any, and ends with “'--files --output -' lists each file's kind.” The Markdown report's Inline tests: note, below the purpose table, names per purpose other than test the code lines of Rust #[cfg(test)] items its source includes and the files containing them, such as “production includes 8 code lines in Rust #[cfg(test)] items (1 file)”; it is absent when there are none. Unclaimed source remains counted under Other in either view. Below the category table of --show-categories, verbose tables list the meanings the policy declares in [categories] for the categories its rows show, each name once; the Markdown report always lists them in a Category | Meaning table below its source categories. A workspace lists a meaning only when every member declaring the name gives the same one. Policy notes, also in the Markdown report, name entries that decided no file, the match and except globs that did nothing in other entries, entries other than language mappings that lost matching files to an earlier policy entry rather than to a built-in convention, language mappings that matched files the backend already recognizes, with the correction that would change such a file's language, and entries that changed the purpose a later stage would give. Unrecognized files and their leading extension groups appear in a separate muted Unrecognized files: note, not a warning-styled failure summary.

Share bars chart each language, folder, member or category row's share of source Code; a category row holds one purpose, so its bar has one segment. Table output to a terminal shows them automatically beside each table they fit and omits them elsewhere; other destinations show none. Of the conflicting root/workspace options, --show-bars forces them for any table destination, with a chart below each table they do not fit, and --no-bars omits them. --show-bars takes an optional kind written with =: --show-bars=purpose, the default kind before the single-purpose substitution described below, or --show-bars=comments, which charts each row's comment density as one dim ▓ segment scaled so the densest row fills the bar, with Comment % as the row's percentage. A bare --show-bars never consumes the next argument. Each purpose bar row shows its percentage of total source Code and a bar split by purpose into whole cells: █ Production, ▓ Test and ░ Other, in the purpose hues when styled, so the split stays readable without color. The largest row fills the bar; a row too small for one cell shows ▏, and a row without code shows no bar. Placement is decided per table from its geometry: when the available width reaches the table's width including a Share column, plus a two-space gap and a minimum of 10 bar cells, or the bar column title's width when wider, the table gains a Share column (repository tables already have one, every Total row shows 100.0% without a bar, and the category table has no Total row), its rows end with bars of up to 40 cells under a bar column titled Code share for purpose bars or Comment density for comment bars, the rule lines extend beneath it, and a legend line explains the glyphs. Bars use plain, never bold, hues. Otherwise, with --show-bars, a Code share chart follows the table's legends, with bars of 10 to 40 cells in the width left after label and percentage. The available width is a positive COLUMNS value, then the stdout terminal's width, otherwise 80, including for saved tables. JSON and Markdown are unchanged.

--table-purpose LIST (root/workspace, comma-separated production, test, other) restricts table output to the selected purposes' source: every row, total, Share and bar counts only those files, including Lines, Comments and Blanks, and rows left without selected source are omitted. Non-source content and coverage notes are unchanged. Purpose columns appear only for selected purposes, and not at all for a single purpose, whose column would repeat Code. Test/prod needs both production and test; otherwise its column becomes Comment % = Comments / (Code + Comments) of the counted source, SonarQube's comment-density formula. With --table-purpose production that is production comment density; like Test/prod, it is neutral at every magnitude. Legends follow the shown columns, and a muted Not shown (purposes): … line under the language table names the excluded purposes with the source code they exclude. The command and the table already show the selection, so neither this line nor the footer repeats it; the label is singular for one name. A single selected purpose leaves purpose bars nothing to split, so bars then chart comment density even with explicit --show-bars=purpose, matching the Comment % column; the bar column's title names the change. A dataset containing only one purpose does not itself trigger this substitution. Markdown and JSON stay complete; agents filter breakdown by purpose.

--table-language LIST (root/workspace, comma-separated source language names, matched in any case) restricts table output to those languages' source in the same way. A file's lines count only under its selected languages: an embedded language keeps its own lines, and the host file counts as a file only when its own language is selected, as in the unfiltered language table. Unknown names and data or documentation languages are usage errors, because tables count only source. Purposes filter first and languages then; a muted Not shown (languages): … line under the language table names the measured languages the selection excludes, the five with the most code by name and the rest as a count, with the source code they exclude, so the shown total and both notes' excluded code add up to the full measurement. Naming every measured language selects everything and adds no line.

--table-category LIST (root/workspace, comma-separated) restricts table output to the selected categories' source in the same way. Each entry is a purpose, which selects all its categories, or a purpose:category key as the category table prints it; * in either part matches any run of characters, an empty part matches anything, so :*law selects the categories ending in law under any purpose and test: all of Test, and category names are case-sensitive. An entry without : is a purpose, and an empty entry, as from a stray comma, is a usage error. A purpose part that can match no purpose, with or without *, is a usage error; for an entry without :, the error suggests the :CATEGORY spelling. An entry that matches no category in the measurement only warns on stderr, naming the entry and listing the measured category keys, those resembling the entry first, because category names are the project's own and case-sensitive and the filtered category table may be empty; exit status and tables are unchanged. Purposes filter first, categories next and languages last; a muted Not shown (categories): … line names the excluded keys like the language line, so the shown total and every note's excluded code add up to the full measurement. Purpose columns appear only for purposes an entry can select. Categories divide a purpose, so when the selection keeps only part of Production's or Test's code, Test/prod gives way to Comment %, because it would compare unrelated slices of the two; whole purposes keep it. Selecting every category selects everything and adds no line.

Table and Markdown views of root, workspace and compare show language variants within their family's row: TSX and Glimmer TS in TypeScript, JSX and Glimmer JS in JavaScript, C++ Header and C++ Module in C++, Unreal Shader Header in Unreal Shader, and BASH in Shell, because the backend names a script BASH only by its .bash extension or a bash shebang and every .sh file Shell, whatever its shebang. A family row adds its variants' lines and files, and a comparison family row takes its change from the summed before and after counts. A muted line such as Folded: TSX → TypeScript. names each fold that contributes to the shown rows, by family and then variant, and appears only when one does; --tables-only omits it. --table-language matches the shown rows, so a variant name selects its family. --split-languages shows every variant as its own row under the backend's name, and a variant name then selects only that variant. C Header stays its own row because the backend assigns every .h file to it, including C++ and Objective-C headers; Fortran's two backend languages stay apart because the backend has no family name for them. JSON, headline, per-file records and explain keep the backend's names either way, so a JSON language total can differ from a folded row.

In default and verbose tables, Not counted: contains only unreadable and parse-failed counts; the backend-incomplete warning, existing stderr diagnostic and partial-result exit 2 remain even without identified failure paths. Workspace tables also name affected members under Unavailable counts:; their unclaimed counts require the separate verbose note. The report’s per-path parse-failure list, capped at 25 paths, appears only with --verbose; the existing stderr diagnostic still names up to 10 unavailable paths. Markdown, JSON/headline evidence and explicit comparison/explanation findings retain their detail. Invalid configuration/output errors and ineffective-option warnings remain visible.

--tables-only (root, workspace and compare) prints the tables and nothing else, for transcripts and pipes that need only rows. Tables keep their rows, totals, Share column and inline bars. Everything outside them is omitted: legends, selection notes, the inline bar key, routine and failure notes, the backend-incomplete line and the closing context and date lines; comparison tables also lose the title, member and subfolder lines, composition lines, measurement notes, findings and Before/After dates. A --show-bars chart that does not fit beside its table keeps its heading and key, because the chart is the requested view of that table. Omission hides no outcome: partial counts keep the stderr warning and exit 2, and ineffective-option warnings remain. A --table-purpose or --table-language selection is no longer named in the output, so the command line alone records it. --verbose conflicts with the option; JSON and Markdown are unchanged.

Table and Markdown measurement reports end with a context line, then Measured at: YYYY-MM-DD HH:MM:SS UTC as the final line. The context line is Root: PATH with the canonical absolute scan root, extended by , subfolder DIR for a subfolder measurement, or Roots: PATH, … with each workspace member's root in member order; Markdown sets the paths as code and separates the two lines as paragraphs, and both formats replace control characters in paths with spaces. The final line uses the measurement-start value in metadata.measured_at_unix_seconds, including workspace and partial reports. JSON and headline retain that existing timestamp; no filesystem creation time or duplicate date field is used. Comparison table and Markdown reports end with Before/After measurement dates from the inputs, not the comparison-render time. --tables-only omits these closing lines from tables. Dates outside the formatter’s supported calendar range retain their numeric Unix seconds with an explicit range notice.

Measurement JSON schema version 3, which locmetry --schema report prints as a JSON Schema covering the headline and the full report. The schema is generated from the typed contract used to serialize and deserialize reports, sharing configuration types for effective policy. Tests validate current root/workspace output and malformed inputs; historical release fixtures document retired formats. Saved report compatibility documents field history, internal semantic validation and the stricter evidence required for comparison:

Field Contents
document_type, schema_version, detail "measurement", "3", and "full" or "headline". Schema and semantic validation require the sections appropriate to that projection; files remains optional for full reports. Measurement schemas 1 and 2 must be recaptured.
project The scan root's directory name, or a workspace display name; not a verified repository identity.
metadata root, measured_at_unix_seconds, locmetry_version, backend, backend_inaccurate, backend_configuration; scope (effective hidden, ignore-file, symlink, and exclude settings, plus optional subfolder selection); kinds (language lists per content kind); coverage (selected_files, counted_files, mapped_files, unrecognized_files, unrecognized_extensions, the unrecognized paths, the unread paths, and parse_failures, an always-emitted array of {path, reason, message} for readable files without counts); modules (full JSON only: detected modules with path and detector); config_path and user_config_path; and config, the effective configuration after merging user defaults including builtin_conventions and builtin_language_mappings. In workspace mode, members and, for a workspace file, workspace_path replace root, scope, config_path, and config.
summary Totals: all_counted (every kind) and source; by_kind_purpose keyed kind:purpose; source_purpose, source_categories keyed purpose:category, and source_languages, all restricted to kind = source; inline_tests, keyed by purpose other than test, the lines of inline Rust #[cfg(test)] items that purpose's source includes and the files containing them, absent when there are none (recognized forms); top_folders, source code lines per purpose for each top-level folder (. holds files directly in the root); submodules, present when Git submodules declared in the scan root's .gitmodules hold measured source, an array of {path, files, code} that disappears once they are excluded (see submodule hint semantics; Git is never invoked); unused_entries, present when configuration entries, language corrections or project language mappings decided no file, because their globs match nothing or an earlier stage always decides first; policy_entries, present when the configuration has overrides, rules, refinements, language corrections or language mappings, an array in that order with each entry's id, stage (override, rule, refinement, correction or mapping), purpose (the purpose an override or rule assigns, or the one a refinement applies to; absent for corrections and mappings) and the files and code it decided (for a mapping, the files it counted), plus, when nonempty, preempted ({by, files}: matching files an earlier entry or built-in convention decided; for a mapping, an earlier mapping, a correction, or builtin:recognition for files the backend recognizes, which a mapping cannot change), unused_patterns (its match globs that decided no file), unused_exceptions (its except globs that left out no matching file) and displaced ({decision, files, code}: the purpose:category later stages would give its files without it, before generated-code markers, omitting files that would reach the fallback, or for a refinement the decision it recategorized); unused_exclusions, present when exclusions from the project, user defaults, or --exclude left out no file or folder, such as a folder written without /** or a path ignore files already hide (default exclusions and the configuration's own path are never listed); build_modules, keyed by detector with modules, the number of modules credited with at least one measured production source file, and the code credited to them (see Module Detection); a detector without credited modules is omitted, and reports of earlier producers counted every adopted module and credited files by rule; largest_module_files, up to five {path, lines, code, module, detector} entries for the largest source files module layouts claimed (see Module Detection), always present and empty when layouts claimed none, while reports of earlier producers omit it; and unclaimed_folders, an array of {folder, files, code} that locates all unclaimed source (source of purpose other that reached the fallback) in non-overlapping folders, always present and empty when every file is decided, largest first: chains of single subfolders collapse to the deepest folder, and the largest folder splits into its subfolders while the list stays within eight rows, or always while it holds most of the code.
review Unclaimed source files, largest first: path, language, category, rule, code, lines. These are the files a configuration may still need to classify; code an entry or convention assigns other on purpose, such as a parked prototype or a build wrapper, is counted as other but not listed.
breakdown One row per folder, kind, purpose, category, and language with files, code, comments, blanks, and lines. folder is each file's parent (. for the root); a folder's recursive totals are the sum over rows whose folder equals it or starts with it plus /. Embedded-language rows count lines but zero files, so every column is additive.
files Only with --files: one record per counted file, sorted by path: path, language, kind, optional language_mapping or language_correction, purpose, category, rule, counts (without files), and, only for files with embedded languages, per-language languages counts, and, only for non-test source with inline Rust #[cfg(test)] items, inline_tests, the lines those items span within counts; and, only for production source a module layout covers, module with the credited module's path and detector, which reports of earlier producers omit; and, only for files a refinement recategorized, refinement with its ID.

other is a purpose of any kind: documentation or data with purpose other is not other source, which source_purpose and review report. Count objects have files, code, comments, blanks, and lines, including zero-valued counters. Summaries may omit an empty source object or empty maps, except all_counted; absence means zero only for the aggregate fields whose schema explicitly permits this omission. Report files put each top-level field and each table row on its own line, so line tools work on rows while the file stays one JSON document.

Surface known counting-coverage limitations: report how many files were selected and counted, list selected files the backend did not recognize, and separately list recognized files it could not read. Readable Handlebars and Lean files with undecodable content and notebooks with invalid or unsupported counting structure are separately recorded in parse_failures; they have no counted file record, set backend_inaccurate, and follow the partial-measurement outcome. The array is optional only for historical version-1 schema compatibility: absence means not recorded, not zero failures. Counting semantics defines Handlebars and Lean decoding failures (invalid_encoding); notebook semantics defines notebook versions, cell treatment, language selection and reason codes. Path rules cannot recover source files omitted by the backend. Language mappings recover unrecognized files; absent records must not be represented as proven zero LOC. Inline tests in mixed files remain a whole-file classification limitation; Rust #[cfg(test)] items are reported as inline_tests without changing any purpose.

Adaptive Folder Detail

--folder-rows N (introduced in v0.3.0) enables the optional Folder table with adaptive detail, implicitly selecting --show-folders; it does not change the Language table. N is a required positive integer; there is no default. It requires at least one single-root table view under the applicability contract. --output FILE --print table can save full JSON while showing adaptive rows; --output FILE --format table saves the adaptive table and --output - --format table prints it. Workspace, comparison, explanation and schema queries reject the option.

The view starts with existing folder and direct-files rows and keeps every measured source contribution exactly once. Collapse single-child chains with no direct source files on both initial and newly revealed rows. Then repeatedly split the largest positive-code folder whose replacement fits, breaking ties by project-relative path components. A split replaces its parent with immediate source-bearing children and a direct-files row when necessary; parent subtotals are never retained alongside their children. Source-bearing includes counted files with zero code. Zero-code folders remain represented but do not drive expansion.

If all children do not fit, keep the direct-files row, show as many largest children as fit (at least two, code ties by path components), and collect the other children and their descendants into one scoped remainder. A remainder must represent at least two children; a single remaining child is named instead at the same row cost. If this minimum cannot fit, leave the parent intact and consider the next largest eligible row. Direct-files and remainder rows are never expanded. Continue until no further split fits.

N counts data rows, excluding the total, headers and notes. It is a soft budget only for initial rows: retain them even when they exceed N, allowing cost-free chain collapse but no further rows beyond max(initial rows, N). A muted hint names the largest displayed row when it has positive code and is either a folder with source-bearing children or a remainder whose children could be named with more budget. Select that row by code descending, then path components and row kind, independently of --sort. A flat folder or direct-files row as the largest row produces no hint, even if smaller folders have depth. The hint suggests increasing --folder-rows without proposing N, because another budget can change earlier expansion choices. No code-share or quality threshold drives expansion.

Labels stay project-relative; X (direct files) and X (K more child folders) are annotations, not folder identities. As with the existing direct-files convention, a real name can resemble an annotation; terminal labels have no uniqueness guarantee, while JSON identities are unaffected. Adaptive labels use the shared terminal-cell sanitization described under Human Presentation. --sort orders final rows without changing selected contributions: code descending or ascending by path components, ties by path components then row kind (folder, direct files, remainder). Ratios use each row’s summed test and production code. The total, source-purpose reconciliation, coverage notes and exit status are unchanged.

Adaptive rows may change when counts change. The Unclaimed source note requested with --verbose and JSON summary.unclaimed_folders retain their separate partition of unclaimed source, including its existing dominance/budget behavior. Different boundaries between these two views are expected; neither changes measured scope. Markdown retains its overlapping parent/child hierarchy, and workspace retains member rows.

Human Presentation

Root and subcommand help wrap descriptions to the detected terminal width, preserving indentation for command and option descriptions. When no terminal width is available, help uses 100 columns. Clap owns this layout independently of report-table presentation.

Human output uses semantic presentation roles shared by measurement, workspace, comparison and explanation rendering. Terminal measurement and comparison reports identify tables through their column headers, without separate table section titles. Each table opens with a full-width thin ─ rule in the existing muted separator style, directly above its headers. A blank line separates each table from its legends and from the next table. The rule spans inline bars when present; the column-header and total separators retain their existing style. Comparison folder tables retain the recursive-counting caveat as a muted legend below the table. Measurement notes and findings retain their section headings, and Markdown retains its table headings. The measurement footer names what was measured. In measurement tables, hue identifies a column: cyan for Code and the Code share chart heading, green for Production, magenta for Test and blue for Other, bold in column headings and totals. Purpose hues are identities, not judgements, so no purpose uses the warning color. The palette uses bold for the measurement title, other column headings, row identities, total rows and informational labels, dim text for secondary measurement figures, and gray for legends, separators, zero values and unavailable ratios. Comparison changes follow the diff convention, green for increases and red for decreases, with gray for zero deltas and bold in total rows. The Kind → Source row’s Lines/Code deltas and every Source total row’s Lines/Code deltas share bold teal-green increases (ANSI 256-color index 43, #00D7AF) and coral-red decreases (index 203, #FF5F5F); their zero deltas remain gray. These accents identify the source-total role, never coincidentally equal numbers; ordinary rows and All counted keep green/red. Comments, Blanks and Files deltas use dim directional colors. Warning labels use yellow and error labels bold red. Each hue has one meaning except green and red, which mark purposes in measurement tables and changes in comparisons, never in the same table. Command-line help and usage errors use the same palette. Positive and negative changes are not judgments of quality. Purpose categories remain neutral; code assigned to Other on purpose is not itself a warning. Numeric signs and textual states retain the meaning without color.

Global --no-color disables terminal colors, bold and dim text for reports, help, usage errors and application diagnostics, whether placed before or after a subcommand. It is also accepted with standalone guide/schema queries. Like nonempty NO_COLOR, it leaves share bars and Markdown emphasis unchanged; use --no-bars to omit measurement share bars.

Terminal styling is enabled only when --no-color is absent and the result destination is stdout attached to a terminal and NO_COLOR is absent or empty and TERM is not dumb. Application diagnostics assess stderr independently using the same NO_COLOR and TERM rules, even when the result goes to a file. Redirected tables and diagnostics receive no styling escapes; JSON is never styled. Markdown uses portable italic legends and bold emphasis instead of ANSI or HTML colors. Shared measurement-table cells (headers, body and totals), table notes and application stderr diagnostics replace control characters with spaces before styling. Unclaimed-source folder labels are sanitized before padding; their intentional list layout is retained. JSON retains the original path identities. Styling is applied after terminal padding, preserving column alignment. Custom theme files, palette flags and configuration fields are not supported; the shared palette is the implementation boundary for future themes.

Net Change

Inputs must have matching subfolder restrictions, including present versus absent.

locmetry compare BEFORE.json AFTER.json compares saved full measurements, with net change = after − before. Direction follows argument order, not timestamps. The command reads the two files without rescanning roots, loading current policy/ignore files, or invoking Git. Inputs may be UTF-8, or UTF-8 or UTF-16 with a byte-order mark, as Windows PowerShell 5.1 writes them when redirecting output; LOCmetry itself writes UTF-8 without a mark. It compares two single-root reports or two workspaces; mixed modes fail. Saved report compatibility owns version support, structural/semantic validation, and full-input eligibility. Per-file records are optional input detail; per-file comparison is excluded from this initial interface.

--member NAME focuses two workspace reports on one exact, case-sensitive member name present in either report. Unknown names and single-root inputs fail before output is written. Both full inputs are validated before selection. The selected member supplies all summary dimensions, composition, member rows, folders, packages, breakdown and presence counts; its Test/prod ratio uses its own source counts. Members present on only one side retain their arrival/departure and zero contribution on the absent side, including empty members. This selection uses saved evidence without rescanning. It selects a workspace root, not an arbitrary nested folder.

Selected comparisons retain original input filenames, project names and metadata. Report-level findings remain whole-input evidence; member-specific findings are limited to the selected member. Partial status still reflects either complete input, including failures in other members or unattributed backend inaccuracy. Human output emphasizes the selected member and presence in bold, explains the whole-input provenance boundary and omits the redundant Members grid. In a selected-member terminal report, the workspace-wide Net change title uses ordinary unstyled text, matching the input-provenance line; unfiltered comparison titles remain bold. The terminal Folders grid shows changed immediate subfolders relative to the selected root and its recursive Source total; Markdown shows changed folders and presence changes throughout the selected member’s hierarchy; full JSON also retains unchanged folders. JSON paths keep their member prefixes. The optional top-level member field records selection in full JSON and headline output; absence preserves the complete-workspace behavior.

Comparison follows Output Routing: explicit --format controls stdout or file content, json is complete, and headline is compact JSON. --output FILE writes only that file. Output must not overwrite either input, including symlink/hard-link aliases. Unlike measurement, there is no scan-root output restriction. Input validity and observed input inaccuracy determine the command outcome; changed settings, unrecognized files and absent historical failure evidence alone do not make a comparison partial.

The comparison has document_type: "comparison", schema_version: "3" and, like a measurement, detail: "full" or "headline"; comparisons written by 0.8.0 and earlier lack detail. Both inputs must be full version-3 measurements; a report of another schema version fails as invalid, naming its version. Measurement, comparison and explanation documents share one schema version. Typed models generate its self-contained Draft 2020-12 schema with the same mechanism as configuration and measurement; schema examples and actual outputs are tested. CountChange holds complete before/after unsigned counts and signed delta counts for files, code, comments, blanks and lines. Unsigned sums must fit u64, deltas i64; overflow fails rather than wrapping or rounding. Line equations hold on both sides and in the delta. Language file counts remain overlapping participation counts; breakdown file counts remain additive. Validation bounds participation by the available host-file evidence and total source files.

Field Meaning
before, after Input filename, project name and measurement metadata; filenames are not verified Git provenance.
member Optional exact workspace member selector. Summary/detail and presence counts cover this member; input metadata and report-level findings still describe whole inputs. Retained in headline output.
summary Changes for all_counted, source, and the union of by_kind_purpose, source_purpose, source_categories, source_languages. Workspace composition provides each of all_counted and source as signed matched, unsigned entering, and unsigned leaving counts: total delta = matched + entering − leaving.
members Workspace only, keyed by member name, with presence and the same count dimensions.
folders Full output only, keyed by root-relative paths (member-prefixed in workspaces). Each row has presence and direct/recursive changes for all_counted and source. Parents include descendants; recursive rows are not additive across levels.
packages Full output only: rows identified by explicit folder and detector, with presence. The folder key references its recursive counts, including tests/descendants; package rows do not independently contribute LOC.
breakdown Full output only: union of (folder, kind, purpose, category, language) rows, each with additive counts: CountChange.
presence_summary Always-present members, folders, packages, each with before_only and after_only entity counts, including zeros. These are topology counts, not LOC.
findings Stable tagged variants counter_changed, policy_changed, modules_changed, identity_changed, coverage_gap, presence_changed; each includes side, human message, affected input-field JSON-pointer paths, and optional member. Presence findings add typed entity identity and presence; coverage findings can add the direct folder with missing counts.

Identity is evidence-based: single roots are paired by the caller, workspace roots by member name, folders by recorded path, packages by folder/detector. Absolute locations and timestamps are provenance, not matching keys. Names do not prove repository identity. Every entity has presence: both|before_only|after_only, referring to its appearance in the reports. Zero-count members and zero-code arrivals/departures stay visible; entirely disjoint nonempty workspaces are supported. Missing members contribute zero to that side's workspace aggregate because they were not included, not because they were measured empty.

Folder presence comes from breakdown rows, coverage paths, adopted modules and their ancestors, with . for a single root and the member name for each workspace root. Physical empty directories and directories containing only excluded files leave no evidence. Coverage-only folders retain coverage findings: their zero recorded counts do not estimate their unavailable lines. Removing a three-line package.json beside two JavaScript source lines changes all-counted LOC from 5 to 2, source LOC from 2 to 2, production source from 2 to 0 and other source from 0 to 2; package departure is not another subtraction.

The headline omits folders, packages, breakdown and individual presence findings, and uses the measurement headline's compact metadata projection. It retains summary, member changes, other findings and presence_summary. Only the topology summary is fixed-size; member rows and coverage findings can grow with evidence.

Workspace table and Markdown output omit the composition paragraphs when every displayed matched, entering and leaving Lines/Code figure is zero. Nonzero components remain visible even when they cancel in the total. Styled terminal composition figures use the table delta colors: positive contributions green, negative contributions red, and zeros muted and unsigned; redirected and Markdown composition prose remains plain. When all recorded count deltas and member/folder/package presence changes are absent, these formats state “No recorded count or presence changes.” Count changes within individual members, dimensions or breakdown rows prevent that statement even when aggregate totals cancel; measurement notes and findings remain visible. JSON retains the complete composition.

Full JSON preserves all union rows. Human Totals show one row per content kind present in either report (Source, Data, Documentation, Unknown) with Lines and Code before, after and net change plus net Comments, Blanks and Files changes; the bold All counted row is their sum. Human Purpose, Categories and Languages grids select changes to source Lines or Code, keyed purpose:category in Categories; Members and Folders also retain recorded arrivals/departures, including zero-code entities. Each grid shows before, after and signed net change for Lines and Code. Purpose, Categories, Languages and Members end in a bold Source total covering all source, including rows not shown; the table's Folders grid lists top-level folders and ends in the root folder's recursive total. Comment-only or blank-only growth appears when it changes total lines. Changes to file counts or the comment/blank split that leave Lines and Code unchanged appear only in Totals and full JSON. Human grids use the measurement tables' layout: right-aligned numbers grouped with commas, │ between column groups, and a muted 0 for no change. Terminal grids center each group name above its columns (Lines, Code, Change), without decorative rules around the labels, so headings stay as narrow as the figures; Markdown keeps full titles such as Lines before. Human output shows signed changes and keeps Markdown folders in hierarchy order. Arrays/maps have deterministic identity order; findings sort by code, member, side and paths, with a deterministic tie-break.

Whenever the Purpose grid is shown, table and Markdown output follow it with Test/prod (Code): BEFORE → AFTER (before → after). Each value is total test source Code divided by total production source Code for that input, including unchanged purposes omitted from the grid and all workspace members; Other and non-source content are excluded. Values use two decimal places, or - when production Code is zero, and neutral styling. The line is omitted with an empty Purpose grid; JSON retains the underlying counts without adding a ratio field.

Recorded version/backend settings, content-kind mappings, effective policy, module sets, names and coverage differences produce findings. Policy comparisons ignore location/timestamps, treat exclusion lists as sets, and preserve rule/mapping order. Identical unavailable paths still produce coverage findings in JSON. Historical absent failure evidence means not recorded; it does not certify old notebook counts. These are differences between recorded measured subsets, not Git line additions/deletions, editing effort, rename detection or proof of source-only growth. Reports lack source-content hashes, ignore-file contents and executable fingerprints. No history store or source checkout is required.

Table and Markdown always show Measurement notes after the comparison results, starting with the net-change definition and the caveats on unreadable files and on folder visibility. Coverage and producer/backend differences follow in the same section, using typed input metadata; policy, module, identity and presence findings remain under Findings.

Human Findings bound presence findings for large restructures. A folder or package inside a member or folder whose presence changed on the same side is not listed separately; the outer finding names how many folders and packages it holds, as in “Folder 'old' appears only in the before report, with 40 folders and 40 packages inside it.” A folder's own package counts as inside it. After folding, a side with more than 11 presence findings lists the first 10 in their usual order, and one closing line counts the rest by kind and names '--format json'; a single extra finding is listed by name instead. Other findings are always listed in full. JSON findings, presence_summary and exit statuses are unaffected: full JSON keeps one finding per entity.

Coverage categories appear in order: inaccurate inputs, unreadable files, parse failures, missing failure evidence, then unrecognized files. Unrecognized files are muted notes; inaccurate inputs and read/count failures remain warnings. “Same” refers only to equal recorded path sets, or equal (path, reason) sets for parse failures, never unchanged unavailable content. Different sets show before/after counts and shared/before-only/after-only identities; absent historical failure evidence remains “not recorded”, not zero or unchanged. Workspace summaries span all members, name members with recorded read/parse failures and count members lacking failure evidence. Per-folder coverage stays in JSON findings[].folder; human output gives one explanation of counted-only folder totals.

Producer notes show each differing version/backend/configuration value without asserting whether counting behavior changed. The no-recorded-settings-differences caveat depends on counter, policy, module and identity findings, independently of coverage or presence findings. These notes do not change JSON findings, schemas, arithmetic or exit statuses.

Folder-presence findings cite the recorded source of each folder identity: breakdown, coverage paths, modules or root/member metadata. Ancestors inherit those evidence pointers; a coverage-only folder is not attributed to nonexistent breakdown rows.

Path Explanations

locmetry explain PATH... inspects current files with the same selection, parser and classifier used by measurement, each on its own as a single-target explanation would. Single-root mode accepts --root, --config, --exclude, --hidden, --respect-ignore-files and --no-user-config; target paths are root-relative. --workspace-file FILE instead requires MEMBER/PATH, applies that member's policy and rejects single-root policy flags. It validates membership but loads only the queried member's configuration. Selected names determine module inference; only the target's content is counted. Absolute targets, parent traversal and spellings that differ from directory entries are rejected. Case-insensitive or Unicode-equivalent filesystem aliases must use the exact on-disk spelling. Directories and missing paths fail; encountering a symlink stops inspection without following it.

Table, JSON and Markdown describe the same result. The default is table on a terminal, JSON otherwise; --format chooses explicitly. JSON is the full explanation on stdout, with no separate headline or --output option; with several targets it is JSON Lines, one complete explanation per line in argument order, and table and Markdown show the explanations in that order. Every target is inspected before output, so a failing target leaves stdout empty. It has document_type: "explanation", schema_version: "3", canonical member/root location, target path, optional member name, nullable loaded configuration paths, effective selection and a tagged result. --schema explanation derives its structure and semantics from the serialized types through the shared schema generator. An explanation cannot be used as a comparison input.

result.state Evidence
counted The same file object as a measurement with --files, plus decision: winning stage, matching patterns, optional user reason and optional module path/detector when a module layout decided the file, and optional generated with the marker and its matched line, file name, annotation or .gitattributes line when a generated-code marker refined that decision, shown as Generated marker in human output, and optional refinement with the ID, matching patterns and reason of the refinement that replaced the category, shown as Refinement and Refinement reason. Counts may be a known zero. When an entry decided a file whose module keeps the credit, file.module names that module and human output shows it as Module credit. A language correction that counted the file appears as correction with its ID and reason.
excluded at and patterns recorded by the ordinary exclusion filter at the target or its pruned ancestor.
not_selected reason is ignore_policy if disabling only ignore filtering selects the target, hidden_policy if enabling only hidden paths does so, or reason_not_recorded when neither establishes a cause. No winning ignore file/line is claimed.
unrecognized Selected but no recognized or mapped parser, or a language correction to unrecognized, which correction then names with its reason; no count is supplied.
unread Selected and recognized but unreadable; counts unavailable.
parse_failed The measurement failure's path, stable reason and human message; counts unavailable.
symlink at identifies the target or ancestor link. No link destination or competing filter is inspected.

Workspace result paths, including module and failure paths, are member-prefixed; globs remain relative to the member root. Stage precedence and language-mapping behavior remain those of matching and precedence. The command outcome distinguishes a successful explanation from unavailable target counts or a command failure. Unrelated counting failures do not make the target partial. Filesystem changes between runs or probes are not snapshot-isolated. The troubleshooting guide owns task examples and explains the evidence limits.

Command Outcomes

Diagnostics go to stderr; successful or partial documents use the selected stdout format. Exit status describes execution and known count availability, not whether a policy, purpose or source change is desirable. LOCmetry enforces no limits; CI gates query per-file records instead, as the file-size gates show for size limits by purpose.

Command Exit 0 Exit 2
Single-root or workspace measurement A report with metadata.backend_inaccurate = false. Unrecognized files may still be present. A report with metadata.backend_inaccurate = true, including read/parse failures or backend-reported inaccuracy without identified paths. Coverage lists known paths; their absence does not cancel the flag.
compare Valid inputs with no observed inaccuracy/read/parse failure. Missing historical evidence, policy differences and presence changes alone do not make the result partial. A comparison using an input with recorded inaccuracy or read/parse failures. Missing lines are not estimated.
explain A counted, excluded, not_selected, unrecognized or symlink result for every target. An unread or parse_failed result for any target.

Exit 1 means a command, configuration, input, traversal, arithmetic or output failure. A usable document is not promised. In particular, traversal errors abort explain; they do not produce a successful result with incomplete module inference. Help, version, guide, schema and generation queries exit 0 when successful.

Sensitive Analysis

Public documentation and fixtures are synthetic; CLAUDE.md governs this repository's real measurements. That is a development-data policy: users of the released CLI may write reports anywhere outside the scan root.