Skip to content

fix: ISSUE-004 front matter init for new .md, txt stays plain (#5) - #12

Merged
bonsai merged 2 commits into
mainfrom
takt/issue-5-1794449013
Nov 12, 2026
Merged

bonsai merged 2 commits into
mainfrom
takt/issue-5-1794449013

Conversation

@bonsai

@bonsai bonsai commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

ISSUE-004: Missing Front Matter on New Text Files (#5)

takt simple-mini(ernie free)で実装 → coding-review 7/20 まで進行した時点でセッション中断。WIP を回収して PR 化(CI で検証)。

内容

  • :e <new .md> で新規作成時に front matter を初期化(従来は未初期化だった)
  • 既存の plain テキスト(front matter 無し)は open/save とも素テキストのまま保持
  • レビュー記録の non-blocking note を含む(Document::new_empty() の failed-first-open 経路など)

仕様確認(design decision)

補足

  • ローカルは Windows SDK 不備で cargo test 不可(winapifamily.h 無し)。CI の判定を正とする
  • 実装: takt (ernie-5.5-flash-preview:free) / レビュー記録は .takt/runs/ のログ

Closes #5

Summary by Sourcery

Preserve plain-text semantics while initializing front matter for new Markdown documents and harden document commands and editing history.

New Features:

  • Initialize front matter for newly created Markdown files while keeping new and existing text files as plain text.
  • Add consistent command outcome handling with protection against replacing unsaved buffers and clearer failure reporting.
  • Document and enforce shared per-document undo/redo behavior with bounded edit history.

Bug Fixes:

  • Preserve plain-text content when opening, saving, reloading, or exporting files without Markdown front matter.
  • Prevent failed database, directory, file, and reload operations from partially changing application state.
  • Avoid recording undo steps for edit sessions that do not modify text.

Enhancements:

  • Centralize file and database loading and make Markdown detection case-insensitive.
  • Add comprehensive coverage for front matter behavior, command handling, source switching, and undo/redo semantics.

Documentation:

  • Document undo/redo behavior and safeguards for commands that would replace unsaved buffers.

Tests:

  • Add regression tests covering Markdown front matter initialization, plain-text round trips, command failures, source switching, and edit history.

Chores:

  • Add repository ignore rules for takt run artifacts.

@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Update document persistence so Markdown files serialize front matter when present, plain-text targets write only the body, and extension detection is case-insensitive.

  • src/doc.rs L59-83, L94-106, L122-131

API

Make document-opening methods return errors and add Markdown-path detection so callers can handle failed opens and initialize new Markdown documents.

  • src/app.rs L229-236, L294-318 (+4 small edits)

Change navigation methods to return command outcomes and reject attempts to replace modified buffers.

  • src/app.rs L406-450, L457-463, L470-473

Add deferred undo snapshots and commit them only when editing operations mutate the buffer.

  • src/buffer.rs L77-94, L375-388 (+12 small edits)

Uses of the API

Centralize command results and apply them consistently to user-visible status and quit state.

  • src/app.rs L43-56, L943-958, L967-969

Route navigation keypresses through the new outcome handling and commit edits performed by the visual-edit path.

  • src/app.rs L502-508, L858

Refactor command dispatch to guard buffer replacement, report failures, and separate safe database, directory, and external-command operations.

  • src/app.rs L970-998, L1003-1160

Implementation

Extract shared database-note loading and sorted Markdown/text file collection helpers.

  • src/app.rs L57-103

Open the initial document through fallible loaders and surface loading errors instead of silently swallowing them.

  • src/app.rs L184-197, L209-210

Save explicit targets before database persistence, initialize front matter for Markdown targets, and preserve existing-path save behavior.

  • src/app.rs L369-389, L391 (removed lines)

Configuration

Add repository-local takt ignore configuration.

  • .takt/.gitignore L1-25

Documentation

Document per-document undo/redo behavior and explain that commands which replace a modified buffer are rejected.

  • README.md L76-83, L102-103

Tests

Test deferred undo history, edit-session grouping, redo preservation, and the history limit.

  • src/buffer.rs L528-596

Add coverage for command outcomes, unsaved-buffer guards, safe source switching, and Markdown-versus-plain-text save behavior.

  • src/app.rs L1161-1783

Verify that documents with front matter save as plain text when the destination is a text file.

  • src/doc.rs L312-332

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-12T10:56:31.518061Z
We couldn’t complete this review. Comment @codex review to try again.
f11903f 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.

@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: b38d0071-ec98-4f27-86cd-b50268ecd06c
  • 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

@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.

@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit d2eb03b

#5 ISSUE-004: Missing Front Matter on New Text Files · 0 of 1 met

# Requirement Status Notes
1 Ensure all new files get appropriate metadata initialization. 🟡 Partly met New .md files get front matter, but new .txt files deliberately do not.

@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/doc.rs" line_range="81" />
<code_context>
+        let content = if markdown {
+            self.to_string_content()
+        } else {
+            self.body.clone()
+        };
+        self.write(path_ref, content)
</code_context>
<issue_to_address>
**Saving text files deletes their headers**

When a `.txt` file begins with a block that `parse_markdown_or_plain` recognizes as front matter and is saved, `Document::load_from_file` parses the block regardless of extension, removing it from `body`, and `save_to` writes only `body` for non-Markdown paths. The saved text file loses its original header.

Make loading extension-aware so non-Markdown files remain whole plain-text bodies.
</issue_to_address>

### Comment 2
<location path="src/app.rs" line_range="1054" />
<code_context>
-                    if !crate::config::validate_path(&path) {
-                        self.status_message = Some(format!("Invalid path: {}", p));
-                    } else {
-                        self.source = Source::Db(path.clone());
-                        self.refresh_notes();
-                        if !self.notes.is_empty() {
</code_context>
<issue_to_address>
**Failed switches leave sources inconsistent**

When the new source list loads but opening its first file or note fails, `switch_to_db` and `switch_to_dir` replace the active source and list before opening the first item succeeds. The open returns an error while the old document and buffer remain, so the failed switch still changes state and leaves them paired with the new source.

Stage the new source, list, and opened document, and update the active app state only after opening succeeds.

Also at `src/app.rs:1091-1100`.
</issue_to_address>

### Comment 3
<location path="src/app.rs" line_range="373" />
<code_context>
-                let _ = self.doc.save_to(&path_buf);
+        if let Some(path) = &explicit_target {
+            // 明示された `.md` 保存先は新規作成として front matter を補完する。
+            if is_markdown(path) {
+                self.doc.ensure_front_matter();
             }
</code_context>
<issue_to_address>
**Overwriting plain Markdown adds metadata**

When an existing front-matter-free `.md` file is saved to via an explicit target, `save_current_file` calls `ensure_front_matter` for every explicit Markdown target, then writes the metadata into the existing file. The file no longer remains plain text.

Only call `ensure_front_matter` for an explicit Markdown target that is being newly created.
</issue_to_address>

### Comment 4
<location path="src/app.rs" line_range="389" />
<code_context>
-                self.doc.ensure_front_matter();
+                let now = chrono::Utc::now().timestamp_millis();
+                let name = format!("{}.md", now);
+                self.doc.save_to(self.root_dir.join(name))?;
             }
-            self.doc.save_to(&path_buf)?;
</code_context>
<issue_to_address>
**Fallback Markdown saves lack metadata**

When the initial listed file fails to open and the user saves the pathless document, `save_current_file` writes the generated `.md` path without calling `ensure_front_matter`, so the saved note lacks its ID, title, and timestamp.

Call `ensure_front_matter` before saving the generated Markdown path.

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

### Comment 5
<location path="src/app.rs" line_range="196-197" />
<code_context>
+        } else {
+            self.open_file_at_index(0)
+        };
+        if let Err(e) = opened {
+            self.status_message = Some(format!("Error: {e}"));
         }
     }
</code_context>
<issue_to_address>
**Startup loses failed filename**

When the initially listed file disappears or becomes unreadable between list collection and opening, `open_file_at_index` returns an error before assigning the selected path to `doc`, and `open_initial` only records the error; the app remains usable with `Document::new_empty()` and no path, so a later save creates a timestamp-named file instead of retrying the selected file.

Retain the failed target path for retry, or return the open error from initialization instead of leaving a pathless editable document.
</issue_to_address>

### Comment 6
<location path="src/app.rs" line_range="346" />
<code_context>
-            let ext = full_path.extension().and_then(|e| e.to_str()).unwrap_or("");
-            if ext == "md" {
+            if is_markdown(&full_path) {
                 doc.ensure_front_matter();
             }
             self.buffer = TextBuffer::new();
</code_context>
<issue_to_address>
**New notes can share IDs**

When two new `.md` files are opened in the same millisecond, `ensure_front_matter()` assigns the generated ID to each new Markdown file; if two files are opened in the same millisecond, both IDs are identical, so importing them into the ID-keyed notes table causes one note to overwrite the other.

Generate IDs with an independent random component or check for collisions before assigning them.
</issue_to_address>

### Comment 7
<location path="src/buffer.rs" line_range="388" />
<code_context>
     // --- Insert & editing operations ---

     pub fn insert_char(&mut self, c: char) {
+        self.commit_edit();
         let line = &mut self.lines[self.cursor.row];
         let mut chars: Vec<char> = line.chars().collect();
</code_context>
<issue_to_address>
**Deleting an empty line clears redo**

When the buffer is a single empty line and redo history exists, `delete_line` commits the pending snapshot before checking whether deleting the sole empty line changes any text, so `dd` on that line clears the redo stack despite being a no-op.

Only commit the pending snapshot when `delete_line` actually changes the buffer.
</issue_to_address>

### Comment 8
<location path="src/app.rs" line_range="345-346" />
<code_context>
             doc.path = Some(full_path.clone());
-            let ext = full_path.extension().and_then(|e| e.to_str()).unwrap_or("");
-            if ext == "md" {
+            if is_markdown(&full_path) {
                 doc.ensure_front_matter();
             }
             self.buffer = TextBuffer::new();
</code_context>
<issue_to_address>
**New `.txt` files lack metadata**

The issue asks for appropriate metadata initialization for new files, and specifically raises newly created `.txt` files. This branch initializes front matter only when the path is Markdown, leaving new `.txt` files without metadata or an opt-in path.
</issue_to_address>

### Comment 9
<location path="src/app.rs" line_range="1418" />
<code_context>
+            Source::Dir(_) => unreachable!("db app"),
+        };
+
+        app.execute_command(&format!("db {}", db_path.display()));
+
+        assert!(status(&app).starts_with("db -> "), "{}", status(&app));
</code_context>
<issue_to_address>
**Database switch test uses preloaded state**

When the test invokes `:db` with the database already loaded by `App::new`, `test_db_switch_loads_notes` switches to the same database that `app_in_db` already loaded, so a `switch_to_db` implementation that leaves `notes` and `buffer` untouched still passes the assertions at lines 1421–1422.

Switch to a second database with distinct seeded notes, or clear/change the current notes and buffer before switching, then assert the target database’s distinct contents are loaded.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 9 findings to address first, and saving a document with front matter to a .txt path now writes only the body, so an existing target can lose its metadata when overwritten. Reverting the change would not restore content already written to disk.

Blocking findings: src/doc.rs:81, src/app.rs:1054, src/app.rs:373, src/app.rs:389, src/app.rs:197, and 4 more


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

Comment thread src/doc.rs
let content = if markdown {
self.to_string_content()
} else {
self.body.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 · Saving text files deletes their headers

When a .txt file begins with a block that parse_markdown_or_plain recognizes as front matter and is saved, Document::load_from_file parses the block regardless of extension, removing it from body, and save_to writes only body for non-Markdown paths. The saved text file loses its original header.

Make loading extension-aware so non-Markdown files remain whole plain-text bodies.

Prompt for AI agents
In `src/doc.rs` at line 81:

**Saving text files deletes their headers**

When a `.txt` file begins with a block that `parse_markdown_or_plain` recognizes as front matter and is saved, `Document::load_from_file` parses the block regardless of extension, removing it from `body`, and `save_to` writes only `body` for non-Markdown paths. The saved text file loses its original header.

Make loading extension-aware so non-Markdown files remain whole plain-text bodies.

Comment thread src/app.rs
_ => {
self.status_message = Some(format!("Unknown command: {}", cmd));
};
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 sources inconsistent

When the new source list loads but opening its first file or note fails, switch_to_db and switch_to_dir replace the active source and list before opening the first item succeeds. The open returns an error while the old document and buffer remain, so the failed switch still changes state and leaves them paired with the new source.

Stage the new source, list, and opened document, and update the active app state only after opening succeeds.

Also at src/app.rs:1091-1100.

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

**Failed switches leave sources inconsistent**

When the new source list loads but opening its first file or note fails, `switch_to_db` and `switch_to_dir` replace the active source and list before opening the first item succeeds. The open returns an error while the old document and buffer remain, so the failed switch still changes state and leaves them paired with the new source.

Stage the new source, list, and opened document, and update the active app state only after opening succeeds.

Also at `src/app.rs:1091-1100`.

Comment thread src/app.rs
let _ = self.doc.save_to(&path_buf);
if let Some(path) = &explicit_target {
// 明示された `.md` 保存先は新規作成として front matter を補完する。
if is_markdown(path) {

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 · Overwriting plain Markdown adds metadata

When an existing front-matter-free .md file is saved to via an explicit target, save_current_file calls ensure_front_matter for every explicit Markdown target, then writes the metadata into the existing file. The file no longer remains plain text.

Only call ensure_front_matter for an explicit Markdown target that is being newly created.

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

**Overwriting plain Markdown adds metadata**

When an existing front-matter-free `.md` file is saved to via an explicit target, `save_current_file` calls `ensure_front_matter` for every explicit Markdown target, then writes the metadata into the existing file. The file no longer remains plain text.

Only call `ensure_front_matter` for an explicit Markdown target that is being newly created.

Comment thread src/app.rs
self.doc.ensure_front_matter();
let now = chrono::Utc::now().timestamp_millis();
let name = format!("{}.md", now);
self.doc.save_to(self.root_dir.join(name))?;

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 · Fallback Markdown saves lack metadata

When the initial listed file fails to open and the user saves the pathless document, save_current_file writes the generated .md path without calling ensure_front_matter, so the saved note lacks its ID, title, and timestamp.

Call ensure_front_matter before saving the generated Markdown path.

Also at src/app.rs:390.

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

**Fallback Markdown saves lack metadata**

When the initial listed file fails to open and the user saves the pathless document, `save_current_file` writes the generated `.md` path without calling `ensure_front_matter`, so the saved note lacks its ID, title, and timestamp.

Call `ensure_front_matter` before saving the generated Markdown path.

Also at `src/app.rs:390`.

Comment thread src/app.rs
Comment on lines +196 to +197
if let Err(e) = opened {
self.status_message = Some(format!("Error: {e}"));

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 loses failed filename

When the initially listed file disappears or becomes unreadable between list collection and opening, open_file_at_index returns an error before assigning the selected path to doc, and open_initial only records the error; the app remains usable with Document::new_empty() and no path, so a later save creates a timestamp-named file instead of retrying the selected file.

Retain the failed target path for retry, or return the open error from initialization instead of leaving a pathless editable document.

Prompt for AI agents
In `src/app.rs` at lines 196-197:

**Startup loses failed filename**

When the initially listed file disappears or becomes unreadable between list collection and opening, `open_file_at_index` returns an error before assigning the selected path to `doc`, and `open_initial` only records the error; the app remains usable with `Document::new_empty()` and no path, so a later save creates a timestamp-named file instead of retrying the selected file.

Retain the failed target path for retry, or return the open error from initialization instead of leaving a pathless editable document.

Comment thread src/app.rs
let ext = full_path.extension().and_then(|e| e.to_str()).unwrap_or("");
if ext == "md" {
if is_markdown(&full_path) {
doc.ensure_front_matter();

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 · New notes can share IDs

When two new .md files are opened in the same millisecond, ensure_front_matter() assigns the generated ID to each new Markdown file; if two files are opened in the same millisecond, both IDs are identical, so importing them into the ID-keyed notes table causes one note to overwrite the other.

Generate IDs with an independent random component or check for collisions before assigning them.

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

**New notes can share IDs**

When two new `.md` files are opened in the same millisecond, `ensure_front_matter()` assigns the generated ID to each new Markdown file; if two files are opened in the same millisecond, both IDs are identical, so importing them into the ID-keyed notes table causes one note to overwrite the other.

Generate IDs with an independent random component or check for collisions before assigning them.

Comment thread src/buffer.rs
}

pub fn delete_line(&mut self) -> String {
self.commit_edit();

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 · Deleting an empty line clears redo

When the buffer is a single empty line and redo history exists, delete_line commits the pending snapshot before checking whether deleting the sole empty line changes any text, so dd on that line clears the redo stack despite being a no-op.

Only commit the pending snapshot when delete_line actually changes the buffer.

Prompt for AI agents
In `src/buffer.rs` at line 388:

**Deleting an empty line clears redo**

When the buffer is a single empty line and redo history exists, `delete_line` commits the pending snapshot before checking whether deleting the sole empty line changes any text, so `dd` on that line clears the redo stack despite being a no-op.

Only commit the pending snapshot when `delete_line` actually changes the buffer.

Comment thread src/app.rs Resolved
Comment thread src/app.rs
Source::Dir(_) => unreachable!("db app"),
};

app.execute_command(&format!("db {}", 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.

🟡 Medium · Database switch test uses preloaded state

When the test invokes :db with the database already loaded by App::new, test_db_switch_loads_notes switches to the same database that app_in_db already loaded, so a switch_to_db implementation that leaves notes and buffer untouched still passes the assertions at lines 1421–1422.

Switch to a second database with distinct seeded notes, or clear/change the current notes and buffer before switching, then assert the target database’s distinct contents are loaded.

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

**Database switch test uses preloaded state**

When the test invokes `:db` with the database already loaded by `App::new`, `test_db_switch_loads_notes` switches to the same database that `app_in_db` already loaded, so a `switch_to_db` implementation that leaves `notes` and `buffer` untouched still passes the assertions at lines 1421–1422.

Switch to a second database with distinct seeded notes, or clear/change the current notes and buffer before switching, then assert the target database’s distinct contents are loaded.

@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.

New gaps against the linked issues

Comment thread src/app.rs
Comment on lines +345 to 347
if is_markdown(&full_path) {
doc.ensure_front_matter();
}

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 · Initialize text-file metadata

The issue asks for appropriate metadata initialization for all new files. This path initializes front matter only for Markdown, leaving newly created .txt files without metadata.

Prompt for AI agents
In `src/app.rs` at lines 345-347:

**Initialize text-file metadata**

The issue asks for appropriate metadata initialization for all new files. This path initializes front matter only for Markdown, leaving newly created `.txt` files without metadata.

From #5:

Ensure all new files get appropriate metadata initialization.

@bonsai
bonsai merged commit f33a4d8 into main Nov 12, 2026
5 checks passed
@bonsai
bonsai deleted the takt/issue-5-1794449013 branch November 12, 2026 12:55
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-004: Missing Front Matter on New Text Files

1 participant