Skip to content

rust-cli-template: fix the audit's seven defects and nine weak spots - #19

Merged
danieljhkim merged 2 commits into
agent-mainfrom
orbit/ORB-26727-6c5a7ade
Nov 22, 2026
Merged

danieljhkim merged 2 commits into
agent-mainfrom
orbit/ORB-26727-6c5a7ade

Conversation

@orbit-agent-01

Copy link
Copy Markdown
Contributor

Task

ORB-26727 — rust-cli-template: fix the audit's seven defects and nine weak spots

Description

Filed by const-0-capt (ORB-26697) from the scope amendment afb2915 (Shape 5, "Fix what the audit found"; Daniel approved the audit's findings 2026-11-21). Design: docs/design/rust-cli-template/1_scope.md in the constellation umbrella. This is the first task of the audit: every copy made before it lands inherits these. It depends on no phase. Paths below are at b75b6a1 and under crates/tmpl-cli-core/ or crates/tmpl-cli/ unless they start with scripts/.

Rule for every item: reproduce the defect with a failing test (or, for the scripts, a failing run against a scratch fixture) first, commit that as the first step, then fix. The chief confirmed defects 2 to 7 in the source; items 1 and the weak spots are the reviewers' reports, most reproduced in a scratch copy, so re-check each against the code before fixing and say in the execution summary which ones did not reproduce.

Problem

Defects:

  1. A lock timeout waits twice the deadline: the failed command's audit guard (tmpl-cli/src/commands/mod.rs:46-55, built before dispatch and recorded on drop) then calls Store::record_audit, which takes the same lock (tmpl-cli-core/src/store/mod.rs:139) and waits again. The audit line for the failure is always lost, and with --json a warning reaches stderr ahead of the error object.
  2. scripts/rename-template.sh:95 runs find -depth with the prune list, and -depth disables -prune, so the rename walks into .git/, target/ and docs/standards/. A branch named with the placeholder is renamed.
  3. A title accepts control characters other than tab and newline (tmpl-cli-core/src/note.rs:151 rejects only tab, newline and carriage return), so terminal escape sequences come out raw in piped note list. The body path lets a carriage return through (tmpl-cli/src/output/render.rs:81-91 only indents after '\n').
  4. A store holding the largest id hands that id out again (tmpl-cli-core/src/note.rs:74-76, next saturates); store/format.rs decode does not check ids for uniqueness on load.
  5. scripts/check-test-modules.sh:9-17 checks that each file under a tests/ directory is declared in that directory's mod.rs, but never that the parent module declares mod tests;, so a whole test directory can stop running with the gate green.
  6. scripts/check-dependency-direction.sh:101 matches std::fs but not the grouped import use std::{fmt, fs}.
  7. The help goldens are a hand-written list (tmpl-cli/tests/goldens.rs:15-21), so a new command has no golden and nothing fails. every_command() already exists (tmpl-cli/src/tests/cli.rs:68) to drive it.

Weak spots (same task unless one grows; if one grows, split it out and say so):
8. Title and Tag validate inside serde (tmpl-cli-core/src/note.rs:128-130 and 211-213, try_from = "String"), so one hand-edited title or tag makes the whole store unreadable.
9. A serialization failure is reported as an I/O error naming a path never touched (store/format.rs:91, store/mod.rs:135).
10. Table widths count characters, not display columns (tmpl-cli/src/output/table.rs:71-73, char_len).
11. A stored note missing a field is read with a default and the next write persists it (note.rs:313-320, serde(default) on body, tags, priority).
Bad-record policy (items 8 and 11 share it). A bad record is a note whose title or tag fails validation, or which lacks a required field. Decoding the store yields the valid notes plus one typed error per bad record, naming its id (or its line, when the id itself is unreadable) and the reason; nothing is defaulted or dropped silently. Read commands (note list, note show of a good id) succeed with the valid notes and write one warning per bad record to stderr. That holds under --json too: stdout keeps the documented payload, and the later warnings envelope field (Shape 4) moves these warnings into it. note show of a bad id fails with that record's typed error. Every write command refuses while the store holds a bad record, with a typed error naming it and the data-error exit code, so a rewrite can never drop or default it. The file is never modified on read.
12. The audit record names no actor (tmpl-cli-core/src/store/audit.rs:36-53; STD-08 R11).
Actor contract: AuditEvent gains actor: Option<String>, the OS user name. AppEnv (crates/tmpl-cli/src/app.rs) reads it once, from USER, else USERNAME, beside HOME, so tests inject it. The audit guard records it. It serializes as "actor": "<name>", or null when neither variable is set. No sentinel string. A line written before this change has no actor field and reads as null: the field is optional by contract, so item 11's refusal of missing required fields does not apply to it. Bump the audit line format, add the UPGRADES step, and list the field in docs/design/tmpl-cli/specs/store.md and in the audit section of docs/design/tmpl-cli/2_design.md.
13. A lock timeout can name a process that has already finished as the holder (tmpl-cli-core/src/store/fsio.rs:235-253, record_holder/read_holder).
14. note add --tag and --json state no default in help (tmpl-cli/src/commands/note.rs:70 and tmpl-cli/src/cli.rs:54; STD-01 R22).
15. DEFAULT_LOCK_WAIT and AUDIT_FILE are re-exported and unused (tmpl-cli-core/src/lib.rs:31).
16. The doc comment at tmpl-cli-core/src/store/mod.rs:19-20 says a load refuses any state that is not owner-only; fsio.rs:157-158 refuses only group- or world-writable state.

Owned work

  1. Items 1 to 7: a failing test each, then the fix. Item 1: the failure's audit line is written once, within one lock deadline, and --json writes the error object before any warning. Item 2: the rename leaves .git/, target/ and docs/standards/ untouched. Item 3: a title with any control character other than the ones the type already allows is refused with the existing error code, and a body with a carriage return or other control character cannot reach the terminal raw. Item 4: a store holding the largest id is refused or the next add fails with a stable error code; a store with a duplicate id is refused on load. Item 5: the gate fails when a parent of a tests/ directory has no mod tests;. Item 6: the gate catches grouped imports. Item 7: help goldens are generated from every_command(), and a command without a golden fails the test.
  2. Items 8 to 16: each fixed as "fixed" is defined in Shape 5: titles and tags validate at the construction boundary, so one bad record is a reported error on that record rather than an unreadable store; encode failures get their own error variant with no invented path; widths count display columns; a stored note missing a required field is refused with the record named, not defaulted; the audit event carries an actor; the lock holder is reported only while the process is alive, else as unknown; both flags state their default in help and the help goldens are regenerated; the unused re-exports are removed; the doc comment is made true to the code (or the code to the comment, whichever STD-05 R8, R9 asks, stated in the commit).
  3. A persisted-shape change (item 12, and any item 8 or 11 change to the store file) bumps the store format and appends a step to store/format.rs UPGRADES (AGENTS.md); --json field names are only added, never renamed.
  4. Regenerate goldens that change (help goldens for item 14) in the same commit as the code that changes them.

Left out

  • Shape 4 canon catch-up (the #[allow] reasons, mode bools, sentinels, Store::open I/O, the STD-04@‍2 unit-test cleanup) is the follow-up to phase 2, which lands after this task.
  • A usage-error type, a warnings envelope field and an audit-log reader are Shape 4 additions, not here: item 8 reports the bad record in the error, nothing more.
  • The init command and manifest (Shape 2, phase 3).
  • scribe's own check for the same items is a task in its workspace.
  • No task ids (ORB-...) in any file of this public repository.

Acceptance Criteria

  • A test per defect 1 to 7 failed before its fix and passes after (the failing test is in an earlier commit than the fix); make ci passes.
  • Item 1: a test holds the store lock past a short deadline, runs a failing audited command, and asserts it returns the lock-timeout error after one deadline (not two), that the audit file gains one failure line for it, and that in --json mode stdout/stderr order has the error object first.
  • Item 2: a test runs scripts/rename-template.sh on a scratch copy containing a .git, target and docs/standards entry named with the placeholder and asserts those paths are unchanged.
  • Item 3: tests assert a title with ESC (0x1b) or another control character is rejected, and note list and note show output piped to a file contains no byte below 0x20 other than newline and tab, including for a body containing a carriage return.
  • Item 4: tests assert a store file whose notes repeat an id fails to load with a stable error code, and a store whose highest id is u64::MAX does not return that id from add.
  • Item 5: running scripts/check-test-modules.sh on a scratch tree whose parent lacks mod tests; exits non-zero and names the directory; on this repository it exits 0.
  • Item 6: running scripts/check-dependency-direction.sh on a scratch core file containing use std::{fmt, fs}; exits non-zero; on this repository it exits 0.
  • Item 7: the help-golden test iterates every_command(), and adding a command in a scratch change without a golden file makes cargo test -p tmpl-cli --test goldens fail.
  • Items 8 and 11: for a store file holding one good note, one note with a bad title (or tag) and one note missing a required field: note list exits 0, lists only the good note, and writes one stderr warning per bad record naming its id and reason (also with --json, whose stdout stays the documented payload); note show <bad id> fails with a typed error naming the record; note add refuses with a typed error naming a bad record and the data-error exit code, and the store file is byte-identical afterwards; no code path writes a defaulted field.
  • Item 9: a test forces an encode failure and asserts the error is not Error::Io and names no path.
  • Item 10: a table test with a full-width (CJK) cell asserts columns line up by display width.
  • Item 12: with USER set, a recorded audit line carries "actor": "<that name>"; with USER and USERNAME both unset it carries "actor": null; an audit line from the previous format, which has no actor, still reads; the audit line format version is bumped with an UPGRADES step, and a test shows an old line upgrades.
  • Item 13: a test creates a lock file naming a finished pid and asserts the timeout error does not report it as the holder.
  • Item 14: tmpl-cli note add --help and tmpl-cli --help show the default for --tag and --json, and the help goldens match.
  • Item 15: cargo build and cargo clippy --workspace --all-targets -- -D warnings pass with DEFAULT_LOCK_WAIT and AUDIT_FILE no longer re-exported from lib.rs.
  • Item 16: grep -n 'not owner-only' crates/tmpl-cli-core/src/store/mod.rs matches nothing contradicting fsio.rs's check, and the comment states the check the code makes.
  • The execution summary lists which of items 1 to 16 did not reproduce at the base commit, if any.

Execution Summary

Click to expand

Summary

Fixed all 7 defects and all 9 weak spots from the audit at base commit b75b6a1.

Reproduction at base commit (b75b6a1)

All 16 items reproduced at b75b6a1 (none failed to reproduce). Before implementing the fixes, failing tests for defects 1–6 (and items 9, 10, 13) were added and run (cargo nextest run --workspace --all-targets --locked --no-fail-fast, captured in .orbit/tmp/repro-failures.txt): 12 tests failed as expected before fixes and all pass after. For defect 7, after migrating tests/goldens.rs to iterate every_command(), adding a temporary Scratch subcommand without a golden file caused cargo test -p tmpl-cli --test goldens --locked to fail (exit 101, reporting missing golden help/note-scratch.txt), after which the scratch variant was reverted.

Acceptance criteria mapping

  • AC1 (failing tests before fixes; make ci): Defects 1–7 were reproduced failing before fixes and pass after. Deviation on commit structure: Orbit's Handoff procedure requires leaving all changes uncommitted so the delivery pipeline creates the commit; failing-before-fix evidence was captured in .orbit/tmp/repro-failures.txt rather than a separate git commit.
  • Item 1: Store::record_audit now acquires its own .audit.lock (separate from .lock), and commands::run_with drops AuditGuard after output::finish flushes stdout/stderr. Verified by record_audit_succeeds_while_the_store_lock_is_held, lock_timeout_audited_command_waits_one_deadline_and_records_one_failure_line, and json_error_object_precedes_audit_failure_warning_on_stderr.
  • Item 2: Removed -depth from find in scripts/rename-template.sh so -prune protects .git/, target/, and docs/standards/, sorting matches deepest-first via perl. Verified by rename_template_leaves_git_target_and_standards_untouched.
  • Item 3: Title::try_from rejects all Unicode control characters (char::is_control) with NoteError::TitleNotSingleLine; output::render::note_detail normalizes CRLF and escapes control characters other than \n and \t. Verified by title_is_trimmed_and_must_be_one_non_empty_line, detail_view_sanitizes_body_control_characters_and_normalizes_crlf, and title_rejects_control_characters_and_piped_output_strips_body_control_bytes.
  • Item 4: NoteId::next_after uses checked addition and returns None at u64::MAX, mapped to Error::IdExhausted (note_id_exhausted); store/format.rs::decode rejects duplicate note ids with Error::DuplicateId (store_duplicate_id). Verified by duplicate_note_ids_fail_to_load_with_a_stable_code and add_refuses_when_max_id_is_already_in_use.
  • Item 5: scripts/check-test-modules.sh verifies every src/**/tests/ directory is declared (mod tests;) by its parent module (lib.rs/main.rs or mod.rs/<parent>.rs), naming the directory on failure. Verified by check_test_modules_fails_when_parent_lacks_mod_tests and exit 0 on this repo.
  • Item 6: scripts/check-dependency-direction.sh adds ban_import (awk) detecting single- and multi-line grouped use imports (use std::{fmt, fs};, use crate::{...};, use super::{...};). Verified by check_dependency_direction_catches_grouped_std_fs_import and exit 0 on this repo.
  • Item 7: Added crates/tmpl-cli/src/lib.rs exporting every_command() (shared with src/tests/cli.rs) and migrated tests/goldens.rs to iterate tmpl_cli::every_command(), failing on missing goldens. Verified by make goldens and the scratch-subcommand failure check.
  • Items 8 & 11: Removed serde Deserialize / try_from = "String" from Title and Tag and #[serde(default)] from Note. store/format.rs::decode validates every required field per record at construction boundaries, isolating bad records as BadRecord (RecordLocator::Id or 1-based RecordLocator::Line + BadRecordReason). Store::list and Store::show return Loaded<T> carrying bad_records; read commands exit 0 with valid notes and 1 stderr warning per bad record (preserving --json stdout payload); note show <bad id> fails exit 1 with store_bad_record; note add refuses exit 1 with store_bad_record leaving notes.json byte-identical. Verified by bad_records_are_isolated_with_id_or_line_and_reason, bad_records_are_isolated_on_read_fail_on_show_and_refuse_writes, and bad_records_warn_on_reads_fail_on_show_and_refuse_writes_without_touching_store.
  • Item 9: Added Error::Encode (encode_error) with no invented path for both store/format.rs::encode and store/audit.rs::encode_line. Verified by encode_failure_is_not_io_and_names_no_path and record_audit_encode_failure_is_not_io_and_names_no_path.
  • Item 10: Implemented Unicode display width (display_width / char_width covering East Asian Wide/Fullwidth and zero-width combining/control characters) in output/table.rs for column sizing, padding, and truncation. Verified by cjk_cells_align_by_display_width.
  • Item 12: Added actor: Option<String> to AuditEvent, bumped AUDIT_FORMAT to 2 with append-only UPGRADES (upgrade_v1_to_v2) and decode_line in store/audit.rs, captured USER else USERNAME in AppEnv/Context, passed into AuditGuard, and documented in specs/store.md and 2_design.md. Verified by actor_prefers_user_then_username_then_none, a_format_one_audit_line_without_actor_upgrades_to_null_actor, the_audit_format_is_one_more_than_the_number_of_upgrade_steps, and audit_line_records_actor_from_user_or_username_else_null.
  • Item 13: store/fsio.rs::read_holder parses the recorded PID and checks liveness on Unix via rustix::process::test_kill_process, reporting "an unknown process" when dead. Verified by a_lock_timeout_does_not_report_a_finished_pid_as_holder.
  • Item 14: Added [default: none] to note add --tag and [default: false] to --json, updated every_command_and_flag_has_help_text to enforce flag defaults, and regenerated all 5 help goldens. Verified by help_states_defaults_for_tag_and_json and make goldens.
  • Item 15: Removed DEFAULT_LOCK_WAIT and AUDIT_FILE from tmpl-cli-core/src/lib.rs re-exports and narrowed their visibility inside store. Verified by cargo build --workspace --locked and make clippy.
  • Item 16: Updated crates/tmpl-cli-core/src/store/mod.rs doc comment to accurately state STD-05 R8 (0700/0600 on creation) and R9 (load refuses symlinks, foreign owners, or group-/world-writable modes matching fsio.rs). Verified by ! grep -n 'not owner-only' crates/tmpl-cli-core/src/store/mod.rs.

Validation commands & outcomes

  • make ci-fast (cargo fmt --all -- --check, check-dependency-direction.sh, check-test-modules.sh, check-terminal-guard.sh, docs/standards/check.sh): passed
  • make clippy (cargo clippy --workspace --all-targets --locked -- -D warnings): passed
  • cargo deny check licenses bans sources: passed (bans ok, licenses ok, sources ok; Cargo.lock unchanged)
  • make deny (cargo deny check including advisories): failed (sandbox read-only path) — failed to obtain lock file '~/.cargo/advisory-dbs/db.lock': attempted to take an exclusive lock on a read-only path. No dependencies or Cargo.lock were modified; pipeline final validation runs outside the sandbox.
  • make test (cargo nextest run --workspace --all-targets --locked --no-tests=fail + cargo test --workspace --doc --locked): passed (129/129 tests passed, 0 skipped; 1/1 doctest passed)
  • make goldens: passed (2/2 golden test suites passed after regenerating help goldens with make goldens UPDATE=1)
  • cargo build --workspace --locked: passed
  • git diff --check: passed (no whitespace errors; no new ORB- IDs in diff)

Reconciliation & scope

  • Baseline: HEAD = b75b6a102b6e12357ad0c4031be08c6e99bcbe65, clean git status --short.
  • Deliverables: 45 modified tracked files + 2 new files (crates/tmpl-cli/src/lib.rs, crates/tmpl-cli/tests/scripts.rs), all uncommitted for pipeline delivery.
  • Paths changed outside original context_files selectors (necessary companions): crates/tmpl-cli/Cargo.toml, crates/tmpl-cli/src/lib.rs, crates/tmpl-cli/src/main.rs (expose every_command() to tests/goldens.rs for Item 7); crates/tmpl-cli/src/output/mod.rs, crates/tmpl-cli/src/output/payload.rs (stderr bad-record warnings on Output for Items 8 & 11); crates/tmpl-cli/tests/support/mod.rs (complete note fixtures without removed defaults for Item 11); crates/tmpl-cli/tests/scripts.rs (regression tests for Items 2, 5, 6).
  • Cleanup: scratch files only under gitignored .orbit/tmp/; zero unintended leftovers.

Validation

  • Not reported

Branch Freshness

  • Base ref: refs/remotes/origin/agent-main
  • Head ref: orbit/ORB-26727-6c5a7ade
  • Behind base: 0
  • Ahead of base: 1

Orchestrated-By: opus

orbit[gemini-4-neon-high] and others added 2 commits November 21, 2026 23:36
rust-cli-template: fix the audit's seven defects and nine weak spots

Fixed all 7 defects and all 9 weak spots from the audit at base commit `b75b6a1`.

Orbit-Task: ORB-26727
Orchestrated-By: Orchestrated-By: opus
Candidate b76845a (tree 2b186cd) against base b75b6a1 (ancestor of HEAD; required_validation_commands is an empty list). I checked all 16 items and their acceptance criteria against the diff, the callers, and the tests. Two concrete defects were repaired in the worktree, uncommitted: F1, Title::try_from ran the control-character check on the untrimmed value, so a trailing newline or tab that the base trimmed and accepted was refused; it now checks the trimmed value, and the title test asserts both trailing cases (failed with the fix reverted, passes with it). F2, docs/design/tmpl-cli/4_decisions.md named `run` as the chokepoint; it now says `run_with`. Checks on the repaired tree: make ci-fast passed; make clippy passed; make goldens passed (2/2); the scripts tests passed (3/3); the full workspace suite passed as a diagnostic (129/129 nextest, 1/1 doctest). make deny was refused by the sandbox: the advisory-db lock sits on a read-only path, and this cargo-deny build has no --db-path flag, so the advisories check did not run; licenses, bans and sources pass. I did not work around the refusal. Items 1 to 16 are implemented as the execution summary describes; I traced the audit-lock split, the JSON error ordering, the bad-record policy, the duplicate and exhausted ids, the actor contract, the holder liveness check, the help defaults and the three script fixes. I did not re-run the pre-fix red runs for every item; only the title test I added was checked red.

Repaired findings: F1, F2.

Changed paths: crates/tmpl-cli-core/src/note.rs, crates/tmpl-cli-core/src/tests/note.rs, docs/design/tmpl-cli/4_decisions.md.

Orbit-Task: ORB-26727
Orbit-Review-Attempt: rvw-49a20ff28968-1
Orbit-Review-Crew: haiku
@danieljhkim
danieljhkim merged commit c7d24df into agent-main Nov 22, 2026
2 checks passed
@danieljhkim
danieljhkim deleted the orbit/ORB-26727-6c5a7ade branch November 22, 2026 07:52
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