config-discovery
Goal
lucisv.toml / .lucisv.toml discovery in the style of ruff's ruff.toml:
for every input file, search upward from its directory for a config file
and take line-length, indent and exclude from the first one found.
CLI flags still win. This is what makes lucisv usable in a repo where the
style is a property of the tree rather than of the command line — an
editor's format-on-save (which goes through stdin) picks up the same
settings as CI's lucisv --check, with no per-editor configuration. Kept
deliberately tiny per TODO.md §3: three keys, no tables, no option
explosion, no new dependency.
Assumptions
- Three keys is the whole surface.
line-length,indent,exclude— exactly the CLI's own knobs. Anything else in the file is a hard error, not a warning: ruff's experience is that silently ignoringline_length(underscore) or a misspelled key wastes far more user time than a strict parser costs. - A full TOML crate is not justified for this. CLAUDE.md requires a
written justification for a dependency;
toml+serdeis ~30k lines of transitive code to read three scalars and a string array out of a file that is, in practice, four lines long. The hand-rolled subset parser is ~100 lines, has no unsafe, no build-time cost, and its failure mode ("unsupported in lucisv.toml") is a better error than a full parser silently accepting syntax lucisv would then ignore. If the key set ever grows past ~10 keys or needs tables, revisit. - The supported grammar is a subset, and says so. Anything valid in real TOML but outside the subset (tables, multi-line arrays, dotted keys, floats, booleans, datetimes, literal/multi-line strings, string escapes) is rejected with an error naming the file and line. It is never silently ignored.
- Config files are read fresh on every run. No caching across runs, no config hash in a cache key (TODO.md §3's content-hash cache item will need one — see Handshakes).
- Discovery is lexical, not symlink-aware. The upward walk
normalizes
./..textually and never callscanonicalize, so a file reached through a symlink resolves against the symlink's path, not the link target's. This matches how the path was typed, which is what a user editing that path expects. excludeis resolved once per command-line input, not per walked directory. A config file found at (or above) the input path contributes itsexcludepatterns to that whole walk; a config file in a subdirectory of the walk does not add excludes mid-walk. Itsline-length/indentstill apply per file. Doing better would mean re-resolving config at every directory during the walk, which is more machinery than the payoff justifies today.- Range checks apply to config files, not to CLI flags. A typo in a
file you can't see the effect of is worth catching (
line-length = 1000is nearly always a mistake); an explicit--line-length 1000on the command line stays as permissive as it has always been, because tightening it would change frozen CLI behavior for no safety gain.
Behavior (the contract this feature adds)
Discovery rule
For a directory D, in this exact order:
- If
D/lucisv.tomlexists → use it. Stop. - Else if
D/.lucisv.tomlexists → use it. Stop. - Else if
D/.gitexists (file or directory) → stop with no config. The.gitcheck happens after steps 1–2, so a config file sitting next to.gitin the repo root is found. - Else move to
D's parent and repeat. At the filesystem root, stop with no config.
The starting directory D is:
- for an input file: the directory containing it;
- for a directory named on the command line: that directory itself;
- for stdin: the directory of
--stdin-filenamewhen given, else the current working directory.
Relative paths are resolved against the current directory before the
walk, so lucisv a.sv searches the cwd and its ancestors.
Exactly one config file is ever used per file — there is no merging of a
parent config into a child config (ruff's extend is not implemented).
Recognized keys
| Key | Type | Range | Effect |
|---|---|---|---|
line-length |
integer | 40..=400 | same as --line-length |
indent |
integer | 1..=8 | same as --indent |
exclude |
array of strings | — | appended to --exclude patterns, same glob semantics |
All optional. An unknown key is a hard error naming the key, the file and the line. A duplicate key is an error too.
Supported TOML subset (grammar)
file := line*
line := ws* (comment | entry)? ws*
comment := '#' <rest of line>
entry := key ws* '=' ws* value (ws* comment)?
key := "line-length" | "indent" | "exclude"
value := integer | string | array
integer := digit+
string := '"' <any char except '"' and '\'> '"'
array := '[' ws* (string (ws* ',' ws* string)* (ws* ',')?)? ws* ']'
Everything is one entry per line; whitespace around every token is
optional. Rejected with an explicit "unsupported in lucisv.toml" error:
tables/sections ([tool.lucisv]), multi-line arrays, string escapes,
booleans/floats/datetimes, and any line that is not a comment, blank, or
key = value.
Precedence
CLI flag > config file > built-in default, per setting, not per
file: --line-length 80 with a config that sets only indent uses the
CLI's width and the file's indent. exclude is the exception and
accumulates: CLI patterns plus config patterns, since both are "also
skip this".
Files in different directories can get different configs in a single
run; discovered configs are cached in a HashMap keyed by directory (the
whole upward chain is memoized, so a big tree under one config file
parses that file once).
--no-config
Ignores config files entirely — nothing is read from disk, every file gets CLI-flags-or-defaults. The escape hatch for "format this the way I just typed, whatever the repo says".
Errors
A config file that cannot be read or parsed is a fatal error:
error: <path>:<line>: <what>, exit code 2, and no file is written
— all configs are resolved before any formatting starts, so a broken
config in a deep subdirectory cannot leave a run half-applied. This
respects the frozen exit-code contract (2 = error, files untouched).
Handshakes
- Consumes
Options.stdin_filenamefrom cli-polish exactly as that feature's README promised: the raw path is used only as the anchor directory for discovery. Nothing is read from or written to that path, and it still need not exist. - Consumes
Options.excludeas the CLI layer; configexcludepatterns are appended to it and matched by the samewalk::is_excluded. - Consumes
vlog_formatter::Config(max_width,indent_width) unchanged. Nothing incrates/vlog_formatterorcrates/vlog_parserwas touched; the two fields sufficed, so no change request was needed. - Changes
args::Options(internal tocrates/lucisv): the eagerconfig: Configfield is replaced byline_length: Option<usize>andindent: Option<usize>— "was the flag given?" has to survive to the point where the file config is known.Options::config_with(&FileConfig)builds the per-fileConfig. A newno_config: boolfield carries--no-config. - Promises to TODO.md §3's content-hash cache: the cache key must
include the resolved per-file settings (or a hash of the config file
that produced them), not just file content + lucisv version — two files
with identical content under different config files must not share a
cache entry.
config::FileConfigderivesPartialEqand is cheap to hash-by-debug if that is all the cache needs. - Promises to TODO.md §3's parallelism item: config resolution
happens entirely up front, in
gather, on one thread. TheVec<(PathBuf, Config)>it produces is exactly the work list apar_iterwants —Discoveryitself never needs to be shared across threads. - Promises to the future LSP (TODO.md §6):
Discovery::for_fileis the one entry point a server needs to answer "what settings apply to this buffer?", and its cache is per-Discovery, so a server can drop and rebuild one when a config file changes on disk.
Status / TODO
src/config.rs: TOML-subset parser (parse) + upward discovery with a per-directoryHashMapcache (Discovery).- Discovery rule:
lucisv.tomlbefore.lucisv.toml,.gitstops the walk after the current directory is checked, filesystem root stops it. - Keys
line-length(40..=400),indent(1..=8),exclude(appended to CLI excludes); unknown key / duplicate key / bad value / out-of-range are hard errors naming file and line. - Precedence CLI > file > default, per setting; per-file resolution so different directories can differ in one run.
--no-configflag, documented in--help.- stdin anchors on
--stdin-filename's directory, else cwd. - Config errors are fatal, exit 2, before anything is written.
- Unit tests for the parser and for discovery; CLI integration
tests in
crates/lucisv/tests/cli.rs. README.md: Configuration section.TODO.md§3 config item checked off.
Work log
2026-08-19 — dev agent
- Read CLAUDE.md, TODO.md §3, README.md,
docs/features/cli-polish/README.mdand all ofcrates/lucisv/srcbefore writing anything. cli-polish's Handshakes section already promisedstdin_filenameas the discovery anchor andexcludeas the CLI layer; both are honored literally. - No TOML dependency. Justification (CLAUDE.md requires one in
writing): three keys, one array, no tables —
toml+serdewould be three transitive crates and a proc-macro build step to read four lines of text. The subset parser is 95 lines including error messages, and it rejects what it does not support rather than accepting TOML lucisv would then ignore, which is the better failure mode here. Revisit if the key set passes ~10 or ever needs tables. - Discovery walks up,
.gitstops it after the directory is checked. The alternative (check.gitfirst) would make the common layout —lucisv.tomlnext to.gitin the repo root — silently not work, which is exactly the ruff layout people expect. Both halves of the rule have tests (git_stops_the_walk_but_only_after_its_own_directoryinconfig.rs,the_search_stops_at_a_git_directory_after_checking_itintests/cli.rs). A.gitfile (submodule / worktree) stops the walk too. - The cache memoizes the whole chain, not just the starting
directory. One
HashMap<PathBuf, FileConfig>: after resolvinga/b/c, the entries fora/b/c,a/b,aand the root all point at the same answer, so a tree of 1000 directories under one config file reads and parses that file once. This is a three-line addition (chain) over the naive version and needs no extra data structure. - Config errors are fatal, and resolved before any write.
gathernow returnsVec<(PathBuf, Config)>— every config file in the run is read while building that list, so a brokenlucisv.tomlin a deep subdirectory aborts with exit 2 and nothing written, rather than half the tree formatted. It also keeps the error from being repeated once per file in the offending directory. Optionschanged shape (internal tocrates/lucisv):config: Configbecameline_length: Option<usize>/indent: Option<usize>, because "was the flag given?" has to survive until the file config is known.Options::config_with/exclude_withapply precedence in one place each. Nothing outsidecrates/lucisvwas touched;vlog_formatter::Config's two fields sufficed exactly.- Range checks (
line-length40..=400,indent1..=8) apply to the file only, not to--line-length/--indent. Tightening the flags would change frozen CLI behavior for no safety gain; a typo in a file you can't see the effect of is the case worth catching. Recorded under Assumptions. excluderesolves once per command-line input, not per walked directory — the walk needs its pattern list before it starts. A config in a subdirectory still setsline-length/indentfor the files under it; it just cannot add excludes mid-walk. Documented as an assumption rather than built, per "simplicity first".- Trailing
#comments after a value are supported (quote-aware, soexclude = ["a#b"]is not truncated); trailing commas in arrays are accepted like real TOML. Both cost three lines and are the two things people actually type. - The workspace was uncompilable for part of this run — the concurrent
agent's span work in
vlog_parser/vlog_formatterwas mid-landing (56-60 compile errors invlog_parser, none inlucisv). Waited it out rather than touching their crates; final gates re-run on the merged tree, see Results. - Sanity-checked the real binary outside the test suite (scratchpad, then
deleted): a tree with
indent = 4+exclude = ["gen"] # generatedformattedrtl/a.svto 4 spaces, leftgen/g.svuntouched, exit 0; changing the key toline_lengthproducederror: …/lucisv.toml:2: unknown key \line_length` (known keys: line-length, indent, exclude)` and exit 2 with nothing written.
Results (workspace root, final):
cargo test -p lucisv: 59 passed, 0 failed — 38 unit (config 18: 8 parser + 10 discovery; args 6; walk 4; diff 6; main 4 — the 6 args tests include the two new precedence tests) and 21 CLI integration (8 new: upward search, per-directory configs, CLI override,--no-config, broken-config-exits-2 (5 malformed files), config excludes, stdin discovery + stdin config error,.gitstop).cargo test --workspace: 148 passed, 0 failed (lucisv59,vlog_formatter42,vlog_parser47) on the tree as merged with the concurrent span work.cargo clippy -p lucisv --all-targets: zero warnings.cargo fmt -p lucisv --check: clean. Onlycrates/lucisvwas formatted, so no file owned by the other agent was touched.- Sizes:
config.rs476 lines (203 of code + doc comments, 273 of tests; the parser half is 95 lines),args.rs220,main.rs261,tests/cli.rs465. NoCargo.tomlchange, no new dependency.
QA log
2026-08-19 — QA agent
Scope: crates/lucisv/** only (a concurrent dev agent was landing the spans
feature in vlog_parser/vlog_formatter; the workspace was compilable by
the time these checks ran, so both scoped and full-workspace runs were
possible).
Gates — all clean:
cargo test -p lucisv: 59 passed, 0 failed (38 unit + 21 integration, exact match to the claim).cargo test --workspace: 158 passed, 0 failed (lucisv59,vlog_formatter42,vlog_parser57) — higher than the work log's "148 at the time of dev's run" because the concurrent span work (10 newtests/spans.rscases) landed afterward; not a config-discovery regression.cargo clippy -p lucisv --all-targets: zero warnings.cargo fmt -p lucisv --check: clean.- No
Cargo.toml/Cargo.lockdiff anywhere in the repo — the no-new-dependency claim holds. unwrap()/expect()/panic!audit ofconfig.rs,args.rs,main.rs: every occurrence outside#[cfg(test)] mod testswas checked by line number; none exist outside test modules (main.rs's are all inside its ownmod teststoo, so the CLAUDE.md main.rs exemption wasn't even needed). All public items inconfig.rs(FileConfig+ its 3 fields,parse,Discovery+ its 3pub fns) carry a doc comment.
Claims verified against the real binary (scratchpad trees, deleted
after): nearest-wins-no-merge with two files formatted differently in one
run (byte-exact); .git as a plain file and as a directory both stop the
walk, and a config sitting next to .git is still found either way;
--no-config reads nothing off disk even when the file present is garbage;
CRLF config files parse and apply correctly (verified actual indent +
line-length effect, not just exit code, since str::lines() strips the
\r); a 5000-element exclude array and a 10-directory deep chain both
resolve correctly with no slowdown; a symlinked input resolves its config
against the symlink's own directory, not the real target's — matching the
documented "lexical, not symlink-aware" behavior exactly (confirmed by
pointing a symlink from a dir with indent=2 at a real file under a dir
with indent=8: the write came out at 2). --stdin-filename pointing at a
nonexistent directory doesn't error — the upward walk just finds no config
and falls through to defaults, exit 0, no crash.
Pre-write fatality (the contract claim most worth breaking) — held.
Built the adversarial case directly: a_good/x.sv (alphabetically first,
its directory has no config problem) plus b_bad/lucisv.toml with an unknown
key governing b_bad/y.sv (alphabetically later, so it's walked and
formatted after a_good/x.sv in walk_dir's sorted order). Ran the real
binary: exit 2, and both files came back byte-identical to their
originals — gather() really does resolve every file's config before
run_files writes anything, even when the broken config belongs to a file
later in walk order than an otherwise-fine one.
Findings — all non-blocking (no silent write-despite-config-error, no parser hole that accepts a wrong value; every malformed input tried failed closed at exit 2 with nothing written):
- [Low] BOM breaks key matching with a confusing message. A
lucisv.tomlstarting with a UTF-8 BOM (EF BB BF) fails every key on its first line:read_to_stringdoesn't strip it andstr::trim()doesn't treat U+FEFF as whitespace, soindent = 4becomes the "key"\u{FEFF}indent, reported asunknown keywith an invisible character in the message. Still exit 2, nothing written — just a diagnosis a user can't act on without knowing to check for a BOM.config.rs:29-64. - [Low] Permission-denied paths are misreported as "no such file or
directory".
chmod 000on a directory (or an ancestor needed to reach it) makesPath::is_dir()/is_file()/.exists()swallow the underlyingEACCESand returnfalseeverywhere they're used —collect_filesinwalk.rs:17-23(pre-existing, not new to this feature) andDiscovery::for_dir'sconfig_file_in/.gitchecks inconfig.rs:175,180,213-215. The user seesno such file or directoryinstead of a permission error, and a config file sitting inside a permission-blocked directory is silently treated as "not present there" rather than erroring — the walk just continues upward. Still fails safe (exit 2 or a sensible fallback, never a crash, never a wrong write), just a misleading diagnosis. Restored permissions after testing. - [Info] Integer grammar is looser than documented. The grammar in
this README says
integer := digit+, and the "unsupported TOML is named, not ignored" philosophy explicitly lists booleans/floats/escapes as rejected-by-name — butindent = +4andindent = 04both parse silently to4(str::parse::<usize>accepts a leading+and leading zeros). The resulting value is correct in both cases, so this is not a safety issue, just an undocumented acceptance outside the stated grammar.config.rs:66-83(set_int). - [Doc, fixed directly] Work log arithmetic didn't add up. The Work
log's Results section said "config 20: 9 parser + 11 discovery" tests.
Actual count from the test run: 18
config::unit tests (8 parser-only + 10 that exerciseDiscovery/TempTree) — matches the real total, since 18 + args 6 + walk 4 + diff 6 + main 4 = 38, the verified unit-test count; the original "20" would have made it 40. Fixed the two numbers directly in place above (small, unambiguous, per the QA fixing latitude in CLAUDE.md) rather than filing it as a finding only.
Verdict: all four scope claims (discovery rule, TOML subset parser, precedence, test counts) hold up under adversarial testing through the real binary and the unit suite. Nothing here rises to the level CLAUDE.md cares most about — no masked corruption, no silent wrong write.
Review
2026-08-19 — lead. Verdict: accepted and committed, with two small lead fixes.
Textbook feature: the strict-subset TOML parser is the right reading of
the no-dependencies rule (and the "unknown key is a hard error" behavior
is worth more than the whole rest of the feature — a silently ignored
line_length typo is exactly how formatters lose users' trust), the
.git-stops-after-check ordering is correct and well documented, and
gather() resolving every config before any write is the exit-code
contract taken seriously. QA's walk-order attack on pre-write fatality
was the right test and it held.
Lead fixes while accepting (QA findings 1 and 3):
- BOM stripped at the top of
parse()— a BOM'd config now parses instead of producing anunknown keywith an invisible cause. +4rejected —from_straccepts a leading+that the documenteddigit+grammar does not; the parser now enforces the grammar it documents. (Leading zeros like04remain accepted: they aredigit+.)
Dispositions:
- EACCES swallowed as "not found" (finding 2): pre-existing in
walk.rstoo, fails safe (exit 2, nothing written), and fixing it properly means switching the discovery checks fromis_file()tometadata()error inspection across both modules — queued as a follow-up note here rather than patched piecemeal. - QA's in-place arithmetic fix to the work log (finding 4) was within its small-fix latitude and is appreciated.