Skip to content

[#4] ISSUE-005: Command Execution Error Handling Gap - #15

Merged
bonsai merged 5 commits into
mainfrom
takt/issue-4-1794488324
Nov 12, 2026
Merged

bonsai merged 5 commits into
mainfrom
takt/issue-4-1794488324

Conversation

@bonsai

@bonsai bonsai commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Issue-005: Command Execution Error Handling Gap

Problem: The execute_command method has inconsistent error reporting - some commands update status_message while others silently fail or produce terminal output only.

Evidence:

  • :w (save) updates status on success/failure
  • :q shows message only if modified, otherwise sets should_quit
  • :db and :dir show usage message if arg missing, but don't prevent mode switch
  • Some error paths don't restore normal mode properly

Suggested Fix:

  • Standardize error handling pattern across all commands
  • Ensure mode always returns to Normal on error or completion
  • Add validation before mode transitions

Execution Report

Workflow simple-mini completed successfully.

Closes #4

Summary by Sourcery

Unify command execution results and validation so operations consistently report errors, preserve state on failure, and return the editor to Normal mode.

Bug Fixes:

  • Standardize command success and failure reporting so errors are consistently surfaced as status messages.
  • Prevent invalid database, directory, file, and navigation operations from partially changing application state.
  • Ensure startup, reload, save, navigation, and source-switching failures are reported accurately.

Enhancements:

  • Refactor command execution around shared Result handling and dedicated command handlers.
  • Ensure command execution returns to Normal mode and validates inputs before source or document transitions.
  • Improve handling of external chira command failures, including actionable messaging when the executable is unavailable.
  • Preserve and clarify save, reload, navigation, quit, and source-switching behavior across directory and database modes.

Tests:

  • Expand command execution coverage for error reporting, mode restoration, save and quit behavior, document loading, navigation, source switching, startup state, and external command failures.

@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Change the public App command and navigation operations to return message-or-error results, so callers can handle failures consistently.

  • src/app.rs L212-221, L281-300, L342-428 (+11 small edits)

Replace the old command dispatcher with Result-based command handlers and centralized status reporting, including validation and external-command errors.

  • src/app.rs L915-1100

Uses of the API

Route startup, save, and navigation outcomes through the shared result handler so their messages and errors reach the status bar.

  • src/app.rs L123-128, L471-482 (+2 small edits)

Implementation

Move note-loading and file-collection helpers into App and update their callers to use the associated functions.

  • src/app.rs L130-181 (+4 small edits)

Remove edit-session snapshot and commit calls from mode transitions and visual edits.

  • src/app.rs L642 (removed lines), L676 (removed lines), L831 (removed lines)

Tests

Replace and expand App tests to cover result reporting, command validation, save and navigation failures, source switches, startup outcomes, and external-command errors.

  • src/app.rs L1102-1143, L1193-1425, L1430-1677 (+4 small edits)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-12T14:26:38.746654Z
We couldn’t complete this review. Comment @codex review to try again.
7de6bc1 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: fd942b56-4265-4a1f-bb97-11770fff9f19
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit f73440f

#4 ISSUE-005: Command Execution Error Handling Gap · 2 of 3 met

# Requirement Status Notes
1 Standardize error handling across commands ✅ Met Commands return a Result and execute_command applies results centrally, displaying failures as Error messages.
2 Always return to Normal mode on error or completion ✅ Met execute_command sets the mode to Normal before parsing or running any command.
3 Validate before mode transitions 🟡 Partly met Required arguments and target paths are checked before switching, but failures opening the first note or file can occur after source and directory state have already changed.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 9 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/app.rs" line_range="205" />
<code_context>

     /// DB の 1 ノートを開いて本文をバッファに載せる
-    pub fn open_note_at_index(&mut self, idx: usize) {
+    pub fn open_note_at_index(&mut self, idx: usize) -> Result<String, String> {
         if idx >= self.notes.len() {
-            return;
</code_context>
<issue_to_address>
**Failed reads open blank notes**

When the selected note is missing, its content query fails, or the database file is removed before navigation, `Connection::open` creates a missing database, and `open_note_at_index` converts content-query errors with `unwrap_or_default()` into an “opened” success. The caller sees a blank note instead of the read error and can overwrite its content.

Open the database without creating it and propagate content-query errors from `open_note_at_index`.

Also at `src/app.rs:214-216`, `src/app.rs:236`, `src/app.rs:976`.
</issue_to_address>

### Comment 2
<location path="src/app.rs" line_range="973-977" />
<code_context>
+            return Err(format!("Invalid path: {}", p));
+        }
+        let notes = load_notes(&path).map_err(|e| e.to_string())?;
+        self.source = Source::Db(path.clone());
+        self.notes = notes;
+        if !self.notes.is_empty() {
+            self.open_note_at_index(0)?;
+            Ok(format!("db -> {}", path.display()))
+        } else {
+            Ok(format!("db -> {}. {}", path.display(), self.new_note()))
</code_context>
<issue_to_address>
**Source switches discard unsaved edits**

When the current document is modified and the user runs `:db` or `:dir`, `cmd_db` and `cmd_dir` replace the current document via `open_note_at_index`, `open_file_at_index`, or `new_note` without checking `doc.modified`, so the source switch succeeds and the caller’s unsaved edits disappear.

Reject these switches while modified, or require an explicit discard/override confirmation before replacing the document.

Also at `src/app.rs:997-1001`.
</issue_to_address>

### Comment 3
<location path="src/app.rs" line_range="973" />
<code_context>
+            return Err(format!("Invalid path: {}", p));
+        }
+        let notes = load_notes(&path).map_err(|e| e.to_string())?;
+        self.source = Source::Db(path.clone());
+        self.notes = notes;
+        if !self.notes.is_empty() {
</code_context>
<issue_to_address>
**Failed switches leave mixed state**

When opening the selected note or file fails after the target has been validated or listed, `cmd_db` and `cmd_dir` update `source`, their note or file lists, and `root_dir` before opening the selected document; the open error leaves the new source active with the previous document still loaded. The caller sees a failed command and a partially switched app.

Stage the target source, lists, and document, and commit them only after the selected item opens successfully.

Also at `src/app.rs:997-1001`.
</issue_to_address>

### Comment 4
<location path="src/app.rs" line_range="109" />
<code_context>
         app.refresh();
-        app.open_initial();
+        let initial_result = app.open_initial();
+        app.apply_command_result(initial_result);

         Ok(app)
</code_context>
<issue_to_address>
**Startup database errors get hidden**

When loading the configured database fails during application startup, `refresh_notes` records a database-load error, but `open_initial` treats the resulting empty note list as an empty database and returns “New note created”; `apply_command_result` replaces the load error, so startup presents a successful state instead of the database failure.

Propagate the refresh failure into startup initialization and avoid replacing it with the empty-database success message.
</issue_to_address>

### Comment 5
<location path="src/app.rs" line_range="137-145" />
<code_context>
         }
     }

+    /// DB からノート一覧を読み出す(副作用なし)。
+    fn load_notes(path: &Path) -> anyhow::Result<Vec<NoteEntry>> {
+        let conn = Connection::open(path)?;
+        conn.execute(
+            "CREATE TABLE IF NOT EXISTS notes (\
+             id TEXT PRIMARY KEY, title TEXT NOT NULL DEFAULT '', \
+             content TEXT NOT NULL DEFAULT '', updatedAt INTEGER NOT NULL DEFAULT 0)",
+            rusqlite::params![],
+        )?;
+        let mut stmt = conn
+            .prepare("SELECT id, title, updatedAt FROM notes ORDER BY updatedAt DESC, id DESC")?;
</code_context>
<issue_to_address>
**Note loading creates database state**

When a caller uses `load_notes` expecting it only to read an existing database, `load_notes` is documented as having no side effects, but it opens the database and executes `CREATE TABLE IF NOT EXISTS`. Callers relying on the documented behavior can create a database or schema simply by loading notes.

Remove the schema creation from `load_notes` and initialize the schema separately, or document that loading may create the database and table.
</issue_to_address>

### Comment 6
<location path="src/app.rs" line_range="165" />
<code_context>
+    /// ディレクトリ内の md/txt ファイルを収集する(副作用なし)。
+    fn collect_files(dir: &Path) -> Vec<PathBuf> {
+        let mut list = Vec::new();
+        if let Ok(entries) = fs::read_dir(dir) {
+            for entry in entries.flatten() {
+                let path = entry.path();
</code_context>
<issue_to_address>
**Unreadable directories look empty**

When the target path is a directory but reading its entries fails, `collect_files` discards a `read_dir` error and returns an empty list; `cmd_dir` then switches to that directory and creates a new note, so the caller sees a successful switch to an empty directory.

Return a `Result` from `collect_files` and propagate directory-read errors before switching sources.
</issue_to_address>

### Comment 7
<location path="src/app.rs" line_range="1263-1264" />
<code_context>
+        let msg = app.status_message.as_ref().unwrap();
+        assert!(msg.contains("written"));
+        assert!(app.files.len() >= 1);
+        assert!(!app.doc.modified);
+    }
+
+    #[test]
</code_context>
<issue_to_address>
**Write-and-quit can skip saving**

When the `wq` implementation quits and clears `doc.modified` without writing, `wq_saves_then_quits` checks only `should_quit` and `doc.modified` at `src/app.rs:1261-1263`; it passes if `wq` clears the modified flag and quits without persisting the buffer.

Assert that the buffer contents were persisted before verifying that the app quits.
</issue_to_address>

### Comment 8
<location path="src/app.rs" line_range="1430-1431" />
<code_context>
+        fs::File::create(&blocker).unwrap();
+        let mut app = App::new(Source::Dir(dir.clone()), dir.clone()).unwrap();
+        let original_source = app.source.clone();
+        app.execute_command("db notadb");
+        assert_eq!(app.source, original_source);
+        let msg = app.status_message.as_ref().unwrap();
+        assert!(msg.starts_with("Error:"));
</code_context>
<issue_to_address>
**Relative fixtures target wrong directory**

When the tests run from a working directory different from their temporary fixture directories, `db_invalid_target_does_not_change_source`, `dir_invalid_path_does_not_change_source`, and `dir_regular_file_does_not_change_source` pass relative names at `src/app.rs:1430-1431`, `1466-1467`, and `1478-1480`, not paths to their temporary fixtures. The commands operate relative to the process working directory, so `db` can open/create a database and `dir` can create or switch to a directory there; the source assertions then fail.

Pass absolute fixture paths in these commands, or explicitly resolve the relative arguments against the temporary directory.

Also at `src/app.rs:1466-1467`, `src/app.rs:1479-1480`.
</issue_to_address>

### Comment 9
<location path="src/app.rs" line_range="1287" />
<code_context>
+# Ignore everything by default
+*
+
+# This file itself
+!.gitignore
</code_context>
<issue_to_address>
**Modified-buffer guard tests fail**

When the modified-buffer guards reject the commands without copying the buffer into `doc.body`, when `e` or `new` correctly rejects a modified buffer, `e_rejects_when_modified` and `new_rejects_when_modified` compare `app.doc.body` to `"changed"` at `src/app.rs:1285` and `1333`. The tests set `app.buffer`, not `doc.body`, so those assertions fail even though the buffer was preserved.

Assert that `app.buffer.to_string()` is still `"changed"`, or initialize `doc.body` consistently with the buffer before the command.

Also at `src/app.rs:1333`.
</issue_to_address>

Sourcery assessment

Approval pending. 8 findings to address first.

Blocking findings: src/app.rs:205, src/app.rs:977, src/app.rs:973, src/app.rs:109, src/app.rs:165, and 3 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/app.rs Resolved
Comment thread src/app.rs
Comment on lines +973 to +977
self.source = Source::Db(path.clone());
self.notes = notes;
if !self.notes.is_empty() {
self.open_note_at_index(0)?;
Ok(format!("db -> {}", path.display()))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Source switches discard unsaved edits

When the current document is modified and the user runs :db or :dir, cmd_db and cmd_dir replace the current document via open_note_at_index, open_file_at_index, or new_note without checking doc.modified, so the source switch succeeds and the caller’s unsaved edits disappear.

Reject these switches while modified, or require an explicit discard/override confirmation before replacing the document.

Also at src/app.rs:997-1001.

Prompt for AI agents
In `src/app.rs` at lines 973-977:

**Source switches discard unsaved edits**

When the current document is modified and the user runs `:db` or `:dir`, `cmd_db` and `cmd_dir` replace the current document via `open_note_at_index`, `open_file_at_index`, or `new_note` without checking `doc.modified`, so the source switch succeeds and the caller’s unsaved edits disappear.

Reject these switches while modified, or require an explicit discard/override confirmation before replacing the document.

Also at `src/app.rs:997-1001`.

Comment thread src/app.rs
return Err(format!("Invalid path: {}", p));
}
let notes = load_notes(&path).map_err(|e| e.to_string())?;
self.source = Source::Db(path.clone());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Failed switches leave mixed state

When opening the selected note or file fails after the target has been validated or listed, cmd_db and cmd_dir update source, their note or file lists, and root_dir before opening the selected document; the open error leaves the new source active with the previous document still loaded. The caller sees a failed command and a partially switched app.

Stage the target source, lists, and document, and commit them only after the selected item opens successfully.

Also at src/app.rs:997-1001.

Prompt for AI agents
In `src/app.rs` at line 973:

**Failed switches leave mixed state**

When opening the selected note or file fails after the target has been validated or listed, `cmd_db` and `cmd_dir` update `source`, their note or file lists, and `root_dir` before opening the selected document; the open error leaves the new source active with the previous document still loaded. The caller sees a failed command and a partially switched app.

Stage the target source, lists, and document, and commit them only after the selected item opens successfully.

Also at `src/app.rs:997-1001`.

From #4:

Add validation before mode transitions.

Comment thread src/app.rs
app.refresh();
app.open_initial();
let initial_result = app.open_initial();
app.apply_command_result(initial_result);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Startup database errors get hidden

When loading the configured database fails during application startup, refresh_notes records a database-load error, but open_initial treats the resulting empty note list as an empty database and returns “New note created”; apply_command_result replaces the load error, so startup presents a successful state instead of the database failure.

Propagate the refresh failure into startup initialization and avoid replacing it with the empty-database success message.

Prompt for AI agents
In `src/app.rs` at line 109:

**Startup database errors get hidden**

When loading the configured database fails during application startup, `refresh_notes` records a database-load error, but `open_initial` treats the resulting empty note list as an empty database and returns “New note created”; `apply_command_result` replaces the load error, so startup presents a successful state instead of the database failure.

Propagate the refresh failure into startup initialization and avoid replacing it with the empty-database success message.

Comment thread src/app.rs
Comment on lines +137 to +145
/// DB からノート一覧を読み出す(副作用なし)。
fn load_notes(path: &Path) -> anyhow::Result<Vec<NoteEntry>> {
let conn = Connection::open(path)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS notes (\
id TEXT PRIMARY KEY, title TEXT NOT NULL DEFAULT '', \
content TEXT NOT NULL DEFAULT '', updatedAt INTEGER NOT NULL DEFAULT 0)",
rusqlite::params![],
)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚪ Low · Note loading creates database state

When a caller uses load_notes expecting it only to read an existing database, load_notes is documented as having no side effects, but it opens the database and executes CREATE TABLE IF NOT EXISTS. Callers relying on the documented behavior can create a database or schema simply by loading notes.

Remove the schema creation from load_notes and initialize the schema separately, or document that loading may create the database and table.

Prompt for AI agents
In `src/app.rs` at lines 137-145:

**Note loading creates database state**

When a caller uses `load_notes` expecting it only to read an existing database, `load_notes` is documented as having no side effects, but it opens the database and executes `CREATE TABLE IF NOT EXISTS`. Callers relying on the documented behavior can create a database or schema simply by loading notes.

Remove the schema creation from `load_notes` and initialize the schema separately, or document that loading may create the database and table.

Comment thread src/app.rs
/// ディレクトリ内の md/txt ファイルを収集する(副作用なし)。
fn collect_files(dir: &Path) -> Vec<PathBuf> {
let mut list = Vec::new();
if let Ok(entries) = fs::read_dir(dir) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Unreadable directories look empty

When the target path is a directory but reading its entries fails, collect_files discards a read_dir error and returns an empty list; cmd_dir then switches to that directory and creates a new note, so the caller sees a successful switch to an empty directory.

Return a Result from collect_files and propagate directory-read errors before switching sources.

Prompt for AI agents
In `src/app.rs` at line 165:

**Unreadable directories look empty**

When the target path is a directory but reading its entries fails, `collect_files` discards a `read_dir` error and returns an empty list; `cmd_dir` then switches to that directory and creates a new note, so the caller sees a successful switch to an empty directory.

Return a `Result` from `collect_files` and propagate directory-read errors before switching sources.

Comment thread src/app.rs
Comment on lines +1263 to +1264
assert!(!app.doc.modified);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Write-and-quit can skip saving

When the wq implementation quits and clears doc.modified without writing, wq_saves_then_quits checks only should_quit and doc.modified at src/app.rs:1261-1263; it passes if wq clears the modified flag and quits without persisting the buffer.

Assert that the buffer contents were persisted before verifying that the app quits.

Prompt for AI agents
In `src/app.rs` at lines 1263-1264:

**Write-and-quit can skip saving**

When the `wq` implementation quits and clears `doc.modified` without writing, `wq_saves_then_quits` checks only `should_quit` and `doc.modified` at `src/app.rs:1261-1263`; it passes if `wq` clears the modified flag and quits without persisting the buffer.

Assert that the buffer contents were persisted before verifying that the app quits.

Comment thread src/app.rs Resolved
Comment thread src/app.rs Resolved
@bonsai
bonsai merged commit c7e932f into main Nov 12, 2026
5 checks passed
@bonsai
bonsai deleted the takt/issue-4-1794488324 branch November 12, 2026 15:32
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.

ISSUE-005: Command Execution Error Handling Gap

1 participant