Skip to content

feat(cli): port the pnpm run cli surface to Rust - #1203

Merged
chappie-daemon merged 78 commits into
rewrite/mainfrom
factory/034-cli-port
Nov 21, 2026
Merged

chappie-daemon merged 78 commits into
rewrite/mainfrom
factory/034-cli-port

Conversation

@chappie-daemon

@chappie-daemon chappie-daemon commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Ports the TypeScript pnpm run cli surface into crates/nostream-cli, as family (c) of #867.

What ships

Eight commands the capture had and the port did not — start, stop, setup, info, update,
export, seed, invite — plus clean, clean-db as a top-level command, and
config list|get|set|validate|env. --version prints nostream/<crate version>. A usage error
is its own class at exit 2, and the four invocations the capture answers before its parser
(--help, -h, an empty command line, an unknown word) are answered the same way.

Four EventRepository methods back it, on both backends: scan_live, count_by_criteria,
delete_by_criteria and delete_all_events. The LMDB delete commits one batch of 10 000 rows at
a time, so a relay sharing the store keeps its writer between batches, and a run that stops part
way reports the rows it committed.

dev and its nine subcommands are out of scope by the operator's decision: six are
pnpm run test:*, the rest shell pnpm db:* and docker prune — the TypeScript development loop
that dies with #869. clean-db stays because dev db:clean is a real operator operation.

The port's promises are in CLI.md, and the decisions behind them — fourteen of them, each with
its cost — are docs/rewrite/decisions/0015-cli-surface.md.

Decision this PR asks for

The approver passed the branch on every criterion it could exercise and escalated on one subject:
three crates new to the workspace, of which two compile C, plus the CI steps and the test
expectations that depend on them. None of it is a defect — the spec requires each — but a
dependency surface is a person's call.

subject what it is why
bech32 a NIP-19 decoder in nostream-core the capture's nip19 dependency, used by invite create and seed
flate2 gzip for export --compress the capture's codec; zlib-rs is the backend, pure Rust when it can be
xz2 xz for the same the capture's second codec; lzma-sys compiles C
Cargo.lock six transitive entries for the three above —
.github/workflows/checks.yml:281,317 --test clean_up added to the Postgres parity run; cli_surface_windows run on Windows the spec's criteria require both
crates/nostream-cli/tests/import_cli.rs three expectations rewritten R5's --file alias and R1's rule that help is an unknown word

If windows-cli-check fails on lzma-sys, the spec's own fallback is to gate both codecs behind
a default compression feature (spec.md:1245-1247); ADR 0015's D6 records the choice and its
cost.

Verification

At 7c5c53ea, taken by the approver on its own target directory:

check result
cargo test --workspace --all-features --no-fail-fast 108 targets, 1 725 passed / 0 failed / 7 ignored
cargo test -p nostream-cli 197 passed / 0 failed (lib 76, cli_surface 60, config_cli 9, import_cli 10, migrate_cli 45)
cargo fmt --all --check, both clippy passes, cargo build --release, cargo check exit 0
mocha test/unit/cli/docs.spec.ts (the capture's own docs test) 6 passing
git merge-tree --write-tree against 982e6759 clean

Nine review rounds. Rounds 6 to 9 answered five findings from an external review and then three
rounds of word-level findings; round 9 passed code, security and architecture, with user
experience, performance and UI stood down on measured reasons recorded in review-plan.json (no
message, page, prompt or exit code reachable from the delta; one .env open deleted where two ran).

Two things this PR cannot verify and CI or the merge will:

  • AC53 — the Postgres arm of clean_up needs PARITY_ADMIN_URL; CI's Storage parity against
    Postgres
    step runs it.
  • AC58 — this PR's own title being a Conventional Commit. It is.

Known and filed, not silently carried: #1201 (the TLS leg of crates/nostream-storage/tests/parity.rs
is #[ignore]d and runs nowhere), #1193, #1194.

One criterion is met with a gap against its letter: AC44's dry-run path is exercised and the
counts are proved by AC51's in-process case, but the branch's own ac44 fixture holds two rows
where the criterion describes five.

Part of #1184.

…tore refusal, keep the write's line, name the import page
The per-batch delete dropped its accumulator on a mid-run error, so up to a batch of already-committed rows were gone and the error named none. A failure after one commit now answers StorageError::Partial with the count, which clean-db prints as its one bare line, and the comment that justified the partial window with a capture behaviour that cannot exist is rewritten as the port's own trade.
1 000 rows a batch made a 160 001-row clean-db 4.5x the one-transaction run for a writer hold a 10 000-row batch nearly matches. The curve is in the constant's doc; the writer-release test is rescaled to the shipped size so the value cannot move without a red.
D13 states the measured trade (commits, wall clock, writer hold at 160 001 rows), which end of the curve 10 000 is and why, the write volume both shipped shapes paid, and the partial count a stopped run now reports. CLI.md teaches the same numbers where the command's options are.
@greptile-apps

greptile-apps Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 4/5

[Critical impact] The Rust CLI gains operator controls that can change deployments and permanently delete event data.

The saved-password issue still needs a fix before merging.

Findings

  1. P1 Saved passwords lose their suffix ▶

Summary

Ports the operator CLI to Rust, including Compose commands, settings edits, exports, invites, seeding, and event cleanup.

  • The Rust CLI now presents a consistent command surface for operators.
  • Operators can start, stop, update, and clean a Compose relay from the CLI.
  • Settings and .env commands now share the values used by CLI workflows.
  • Operators can export live events and remove selected events from either store.
  • First-time setup now prepares configuration before starting the relay.
  • The CLI now reports relay settings, keys, and Compose uptime.
  • Operators can add sample events to a relay store with seed.
  • Operators can create invite codes from the Rust CLI.
  • Import accepts both file flag spellings and reads database settings from .env.
  • Postgres checks for active vanish requests now use the primary store.

Reviews (7) · Last reviewed commit: "docs(adr): cite the set text read where ..." · Reviewed by Greptile

Comment thread crates/nostream-cli/src/env_file.rs Resolved
@coveralls

coveralls commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Coverage Report for CI Build 44901452960

Warning

Build has drifted: This PR's base is out of sync with its target branch, so coverage data may include unrelated changes.
Quick fix: rebase this PR. Learn more →

Coverage decreased (-0.006%) to 77.582%

Details

  • Coverage decreased (-0.006%) from the base build.
  • Patch coverage: No coverable lines changed in this PR.
  • No coverage regressions found.

Uncovered Changes

No uncovered changes found.

Coverage Regressions

No coverage regressions found.


Coverage Stats

Coverage Status
Relevant Lines: 12081
Covered Lines: 9792
Line Coverage: 81.05%
Relevant Branches: 6342
Covered Branches: 4501
Branch Coverage: 70.97%
Branches in Coverage %: Yes
Coverage Strength: 762.43 hits per line

💛 - Coveralls

parse_values trimmed and stopped, so a quoted password kept its quotes and DB_PORT=5432 # note was unparseable — while the module names node's --env-file as its oracle and node strips both. One balanced quote pair is removed, then an unquoted # starts a comment; the split on the first = is unchanged and a # inside quotes stays. Measured against node v24.22.1 over the five probe lines.
SettingsPaths::resolve reads the process only, so a NOSTR_CONFIG_DIR that lives in .env alone was invisible to clean-db, export, info, invite and seed — the capture runs under node --env-file-if-exists=.env and honours it. resolve_paths now owns the choice (--config-dir, then the .env-layered environment, then the cwd) and all six settings call sites go through it; SettingsPaths::resolve stays process-only for the daemon.
CapturedResult::Signalled fell through to was_stash_created, which answered 'created' because a killed git prints neither line, so update went on to pull and pop a stash it had not made. The step now fails as the capture's ok === false branch does and stops before the pull.
The sink was a Box<dyn Write>, so the gzip/xz trailer was written from Drop where its error had nowhere to go: a sink that refused the last write left a truncated archive behind exit 0. The three writers are now one Sink enum with a fallible finish(), which export_stream calls and maps through stream_error.
count_by_criteria read the replica while delete_by_criteria wrote the master, so on a replica deployment a dry run's number described different rows than the delete removed. Both now take the master, and the trait doc states the rule a backend with a replica must keep.
Comment on lines +291 to +292
match trimmed.find('#') {
Some(at) => trimmed[..at].trim_end().to_owned(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Saved passwords lose their suffix

config env set DB_PASSWORD 'p@ss#word' still writes DB_PASSWORD=p@ss#word and reports success. The new parser reads that back as p@ss, so later CLI commands use the wrong password and cannot connect. config env get also loses the saved suffix.

Keep dotenv decoding for runtime reads, but update upsert_value to quote values that would otherwise change when read back. Add a set-then-get test with a password containing #.

…divergences

node --env-file strips a balanced backtick pair as well as the other two quotes (measured, v24.22.1: D=`tik` answers tik), and parse_value left it quoted while the doc claimed node's reading. The module doc now also records the line-level divergences the parser keeps on purpose (export A=1, dotted and spaced keys, multi-line values) and why they are safe.
Round 6's single parse served both the environment a launched process sees and the file the config env commands describe, so config env set DB_PASSWORD 'p#ss' wrote a line its own get answered as p. The capture has two views (node's parse, parseEnvFile's raw match[2]); Environment now holds both — get answers node's rule, file/file_values answer the raw table — and D8 records the split with its cost.
Sink::finish's xz arm and export_stream's interrupt branch were claimed by no test that could fail: AC38 asserts six magic bytes a flush() still writes. The xz refusing-sink case is the gzip case's twin and goes red under that swap; the interrupt case decodes the archive, so the branch is exercised, and the comment now says where the trailer is Drop's and why.
is_vanished hydrated has_active_request_to_vanish from the reader and then made that answer durable on the master, where it short-circuits every later call: a replica that had not yet seen a NIP-09 request turned its 'no' permanent. Both halves now use the master, which is the pool its transactional twin already resolved the question in.
The capture's ENV_LINE_REGEX keeps match[2] verbatim — A=1  answers 1  — while the raw view trimmed both ends, so config env set DB_PASSWORD 'p#ss ' read back as p#ss and the mask's last characters differed. parse_raw now strips only the leading whitespace the pattern eats; a CRLF carriage return is dropped for both views, as the capture's /\r?\n/ split does.
…reader

migrate reads std::env::var directly and D14 records why (a copied source must never come from a file's layer); the module's get doc and D8's new paragraph now say so, and the module doc states the multi-line divergence to the measurements: node joins a closed pair across lines, this parser reads line by line as the capture does, and an unterminated quote is not a divergence at all. The two sentences landed together because they interleave in one file and one ADR paragraph; the pin is a_multi_line_value_is_the_line_it_started_on.
Context::at loads an Environment for every command and the three config env readers build a second one for the raw view, so the cost is two parses per command and four for those three, with config env set parsing none (round-7 review, note 1).
The paragraph said a command's own lookup loads its parse and that config env set parses none; strace on set shows the context's Environment::load (two parses, one read open) plus its own text read, and Environment::load has one call site besides the three readers (app.rs:47). Two parses per command, four for list/get/validate, two plus a text read for set (round-8 review, finding 1).
…PPORTED_KEYS

node continues a value onto the next line for a closed quote pair and for a value that is only whitespace (env -i, v24.22.1: ZQ1=<spaces> then ZQ2=5 makes ZQ1 the string ZQ2=5); the parser answers the first line in both, pinned in a_multi_line_value_is_the_line_it_started_on. The SUPPORTED_KEYS clause claimed every consumer goes through the table, which RELAY_DOMAIN (compose.rs:136) and NOSTREAM_XZ_* (compression.rs:73,85) do not; the doc now says what the CLI looks up and that an export/dotted/spaced key is in none of it. parse_raw's 'byte for byte' is narrowed to trailing whitespace, and the lone-CR and BOM divergences join the list.
Round 8's strip_suffix('\r') was claimed by no test: deleting it left every suite green while the raw view answered 1 \r for A=1 \r\n, where the capture splits on /\r?\n/ and answers 1 . The case asserts both views (round-8 review, note 2).
env_list, env_get and env_validate each loaded a second Environment over the file app.rs:47 had already read, and the context's raw map had no reader. They now take &Environment like the module's other commands, so strace on config env list counts one .env open instead of two with the same output, and D8's cost paragraph says what is true (round-8 architecture finding 1, and its note 1 on node's escaping).
…from node

The doc and the test's own comment said an unterminated quote is no divergence at all. Measured on node v24.22.1, A="abc # def is "abc # def there and "abc here, because a leading quote without a partner falls through to the comment rule; that shorter answer is the layer store::open, import and RelayKeySource read, while parse_raw keeps the line whole. Both sites now state the split, and the pin reddens when the fall-through changes (left: Some("\"abc # def") against Some("\"abc")) (round-8 security finding 1).
…ementer reads it

is_vanished's rule (hydration and the cache write on the pool writes use, because the cached no is permanent) now sits in the trait doc beside count_by_criteria's, with the impl pointing back at it; has_active_request_to_vanish gets its own sentence saying why a read may answer from the reader, which is what &self.reader does and what no production caller asks today (grep: the only consumers are doubles, an unavailable stub and the mcp rollup) (round-8 architecture finding 2).
…ence

Environment::get filters an empty process value and falls through to the file, where node keeps the empty string (measured on v24.22.1: NOSTR_CONFIG_DIR= prints ""); the split made that shape reachable through NOSTR_CONFIG_DIR, so the module's divergence list names it (round-8 architecture note 2).
It was below D8's --data-dir Cost with a second unrelated Cost of its own, and the preamble's count and provenance did not name it, so the record's enumeration could not see the decision that governs the crate's most-read file. A #### heading inside D8 and one preamble clause fix the index without a fifteenth id: grep -c '^### D' still prints 14, which is what V45, Amendment 4 and the digest are built on (round-8 architecture finding 3).
The case asserted the confirmation line, which an empty reloaded .env also produces, so restoring env_validate's self-load left it green. The table now carries WORKER_COUNT=notanumber, which only the handed instance refuses: the inverted reader panics on unwrap_err with Ok(Environment settings are valid). The doc says how each of the three assertions fails (round-9 finding 1).
…at exists

cargo doc printed unresolved links at :699 and :819 because each pointed at Self:: for a method on the other trait; they now name UserRepository::is_vanished and EventRepository::has_active_request_to_vanish, and the sentence names PostgresBackend rather than a PostgresRepository the crate does not have. cargo doc -p nostream-storage --no-deps prints the two pre-existing warnings only (round-9 findings 2 and 3).
The paragraph pointed at config.rs:337, which 323b20a moved to :342 when env_set followed the multiline signatures; the cite now names the line grep -n prints (round-9 finding 4).
@chappie-daemon
chappie-daemon merged commit ff04544 into rewrite/main Nov 21, 2026
21 of 22 checks passed
@chappie-daemon
chappie-daemon deleted the factory/034-cli-port branch November 21, 2026 13:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants