diff --git a/apps/nexus42/src/commands/creator/works/mod.rs b/apps/nexus42/src/commands/creator/works/mod.rs index 7102763e3..33e805047 100644 --- a/apps/nexus42/src/commands/creator/works/mod.rs +++ b/apps/nexus42/src/commands/creator/works/mod.rs @@ -1148,6 +1148,7 @@ const fn reconcile_report_wire( updated: report.updated, resynced: report.resynced, preserved: report.preserved, + skipped: Vec::new(), } } diff --git a/crates/nexus-local-db/src/lib.rs b/crates/nexus-local-db/src/lib.rs index 30d441046..a0c729a15 100644 --- a/crates/nexus-local-db/src/lib.rs +++ b/crates/nexus-local-db/src/lib.rs @@ -259,7 +259,7 @@ pub use work_chapters::{ is_script_complete, is_work_completed, next_chapter, next_chapter_volume_aware, render_frontmatter_status, seed_chapters, seed_chapters_multi_volume, seed_chapters_multi_volume_tx, update_paths, update_status, InsertChapterParams, ReconcileDiff, - ReconcileOp, ReconcileReport, WorkChapterRecord, + ReconcileOp, ReconcileReport, ReconcileSkip, WorkChapterRecord, }; pub use force_gates_audit::{ diff --git a/crates/nexus-local-db/src/work_chapters.rs b/crates/nexus-local-db/src/work_chapters.rs index ad1daef45..b42e50ae5 100644 --- a/crates/nexus-local-db/src/work_chapters.rs +++ b/crates/nexus-local-db/src/work_chapters.rs @@ -515,6 +515,24 @@ pub async fn update_paths( Ok(()) } +/// Reason recorded when a chapter's frontmatter status write-back is skipped. +const UNRENDERABLE_FRONTMATTER_REASON: &str = + "status cannot be rendered (no opening `---` or an unclosed block)"; + +/// One chapter whose frontmatter status write-back reconcile had to skip. +/// +/// Only the file's `status` bytes are left alone: other decisions for the same +/// chapter — word-count mirroring, for instance — are still produced and +/// applied. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct ReconcileSkip { + /// Chapter path below the workspace root: + /// `Works//Stories/.md`. + pub path: String, + /// Why the status write-back was skipped. + pub reason: &'static str, +} + /// Report from reconciling `work_chapters` with the filesystem. #[derive(Debug, Clone, serde::Serialize)] pub struct ReconcileReport { @@ -526,10 +544,19 @@ pub struct ReconcileReport { /// /// These bytes are committed by the caller's Work byte-write port, never by /// [`apply_reconcile_diff`] — this counter is a file count, not a DB row - /// count. + /// count. A file whose frontmatter status cannot be rendered is never + /// counted here; it appears in [`ReconcileReport::skipped`] instead. pub resynced: u32, /// Number of chapter rows preserved unchanged. pub preserved: u32, + /// Chapters whose frontmatter status write-back was skipped, with the + /// reason (no opening `---`, or a block that never closes). + /// + /// Per chapter, not per write decision: a chapter listed here can also + /// appear in [`ReconcileReport::updated`] when its `word_count` was + /// mirrored into the DB. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub skipped: Vec, } /// A single write decision produced by [`compute_reconcile_diff`] (V1.49 P3, @@ -563,6 +590,10 @@ pub enum ReconcileOp { /// Resync the chapter file's frontmatter `status` to the DB source of /// truth (DB-as-SSOT; the file was ahead/conflicting). /// + /// Emitted only when [`render_frontmatter_status`] can produce the bytes; + /// a file it cannot render is recorded in [`ReconcileDiff::skipped`] + /// instead, so this op never stands for a write that silently no-ops. + /// /// **Index-only in [`apply_reconcile_diff`]**: that function treats this /// variant as a documented no-op. The bytes are rendered by /// [`render_frontmatter_status`] and committed by the caller's Work @@ -584,7 +615,8 @@ pub enum ReconcileOp { } /// The read-only result of [`compute_reconcile_diff`]: an ordered list of -/// [`ReconcileOp`]s plus the count of existing rows that need no write. +/// [`ReconcileOp`]s, the count of existing rows that need no write, and the +/// chapters whose frontmatter could not be rendered. /// /// Carrying the decisions (not the raw file/DB state) keeps [`apply_reconcile_diff`] /// cheap and free of re-reads, which is what makes the lock window short. @@ -595,6 +627,9 @@ pub struct ReconcileDiff { pub ops: Vec, /// Existing rows whose status and `word_count` already agree (no write). pub preserved: u32, + /// Chapters whose frontmatter status write-back was skipped; other ops for + /// them (word-count mirroring) are still produced. + pub skipped: Vec, } impl ReconcileDiff { @@ -618,6 +653,7 @@ impl ReconcileDiff { updated, resynced, preserved: self.preserved, + skipped: self.skipped.clone(), } } } @@ -876,10 +912,18 @@ pub async fn compute_reconcile_diff( // chapter transition. let status_conflicts = fm_status.as_ref().is_some_and(|s| s != &db_status); if status_conflicts { - diff.ops.push(ReconcileOp::ResyncFileStatus { - rel_child: std::path::Path::new("Stories").join(&fname), - db_status: db_status.clone(), - }); + let rel_child = std::path::Path::new("Stories").join(&fname); + if render_frontmatter_status(&content, &db_status).is_some() { + diff.ops.push(ReconcileOp::ResyncFileStatus { + rel_child, + db_status: db_status.clone(), + }); + } else { + // The status write-back cannot be produced. Report the + // skip; word-count mirroring for this chapter still + // applies below. + record_skipped_status_write_back(&mut diff, work_id, work_ref, &fname); + } } // Mirror word_count from file to DB when present and different. @@ -907,6 +951,28 @@ pub async fn compute_reconcile_diff( Ok(diff) } +/// Record one skipped frontmatter status write-back and surface it to the +/// operator on stderr. +/// +/// Never `tracing`: under `Creator` commands the global subscriber's writer is +/// stdout, so a `warn!` here would corrupt `creator works reconcile-chapters +/// --json` output. Only the skip branch reaches this, never a rendered chapter. +fn record_skipped_status_write_back( + diff: &mut ReconcileDiff, + work_id: &str, + work_ref: &str, + file_name: &str, +) { + eprintln!( + "reconcile: work {work_id}: frontmatter status write-back skipped for \ + Works/{work_ref}/Stories/{file_name}: {UNRENDERABLE_FRONTMATTER_REASON}" + ); + diff.skipped.push(ReconcileSkip { + path: format!("Works/{work_ref}/Stories/{file_name}"), + reason: UNRENDERABLE_FRONTMATTER_REASON, + }); +} + /// Write phase of reconcile (V1.49 P3, R-V148P4-W3). /// /// Executes the DB index mutations of `diff` in order, reproducing the legacy @@ -2475,6 +2541,152 @@ mod tests { assert_eq!(report2.preserved, 3); } + // ----------------------------------------------------------------------- + // I-000405: a chapter whose frontmatter status cannot be rendered is + // reported as skipped (path + reason), and no resync op is emitted for it, + // so the counters match what was actually written. + // ----------------------------------------------------------------------- + #[tokio::test] + async fn test_reconcile_reports_unrenderable_frontmatter_as_skipped() { + let (dir, pool) = fresh_pool().await; + insert_test_work(&pool, "wrk_recon_skip").await; + seed_chapters( + &pool, + "wrk_recon_skip", + "my-novel", + 2, + "2026-06-07T10:00:00Z", + ) + .await + .unwrap(); + + let stories_dir = dir.path().join("Works").join("my-novel").join("Stories"); + std::fs::create_dir_all(&stories_dir).unwrap(); + // Status conflicts with the DB row, but the frontmatter never closes, + // so no bytes can be rendered to resync it. + let broken = "---\ntitle: Broken\nchapter: 1\nstatus: draft\nUnclosed body"; + let broken_path = stories_dir.join("ch01-broken.md"); + std::fs::write(&broken_path, broken).unwrap(); + std::fs::write( + stories_dir.join("ch02-ok.md"), + "---\ntitle: Ok\nchapter: 2\nstatus: not_started\n---\nBody", + ) + .unwrap(); + + let diff = compute_reconcile_diff(&pool, "wrk_recon_skip", "my-novel", dir.path()) + .await + .unwrap(); + assert!( + !diff + .ops + .iter() + .any(|op| matches!(op, ReconcileOp::ResyncFileStatus { .. })), + "no resync op may stand for an unrenderable chapter: {:?}", + diff.ops + ); + assert_eq!(diff.skipped.len(), 1, "one chapter cannot be rendered"); + assert_eq!( + diff.skipped[0].path, + "Works/my-novel/Stories/ch01-broken.md" + ); + assert!( + diff.skipped[0].reason.contains("cannot be rendered"), + "skip must carry a reason naming the failure, got {:?}", + diff.skipped[0].reason + ); + + let report = apply_reconcile_diff(&pool, "wrk_recon_skip", "2026-06-07T11:00:00Z", &diff) + .await + .unwrap(); + assert_eq!(report.created, 0); + assert_eq!(report.updated, 0); + assert_eq!(report.resynced, 0, "no chapter file was written"); + assert_eq!(report.preserved, 1, "ch02 is unchanged"); + assert_eq!(report.skipped, diff.skipped, "the report carries the skip"); + let accounted = report.created + + report.updated + + report.resynced + + report.preserved + + u32::try_from(report.skipped.len()).unwrap(); + assert_eq!( + accounted, 2, + "no chapter here has a word-count op, so the counters partition both chapters" + ); + // The unrenderable file keeps its original bytes — nothing was lost. + assert_eq!(std::fs::read_to_string(&broken_path).unwrap(), broken); + } + + // ----------------------------------------------------------------------- + // I-000405 (review): `skipped` names a skipped status write-back, not an + // untouched chapter — word-count mirroring for the same chapter still + // applies. + // ----------------------------------------------------------------------- + #[tokio::test] + async fn test_reconcile_skips_status_write_back_but_mirrors_word_count() { + let (dir, pool) = fresh_pool().await; + insert_test_work(&pool, "wrk_recon_skip_wc").await; + seed_chapters( + &pool, + "wrk_recon_skip_wc", + "my-novel", + 1, + "2026-06-07T10:00:00Z", + ) + .await + .unwrap(); + + let stories_dir = dir.path().join("Works").join("my-novel").join("Stories"); + std::fs::create_dir_all(&stories_dir).unwrap(); + let broken = + "---\ntitle: Broken\nchapter: 1\nstatus: draft\nword_count: 1200\nUnclosed body"; + let broken_path = stories_dir.join("ch01-broken.md"); + std::fs::write(&broken_path, broken).unwrap(); + + let diff = compute_reconcile_diff(&pool, "wrk_recon_skip_wc", "my-novel", dir.path()) + .await + .unwrap(); + assert!( + !diff + .ops + .iter() + .any(|op| matches!(op, ReconcileOp::ResyncFileStatus { .. })), + "the status write-back must be skipped: {:?}", + diff.ops + ); + assert!( + diff.ops + .iter() + .any(|op| matches!(op, ReconcileOp::UpdateWordCount { chapter: 1, .. })), + "word-count mirroring must still be emitted: {:?}", + diff.ops + ); + assert_eq!(diff.skipped.len(), 1, "one skipped status write-back"); + assert_eq!( + diff.skipped[0].path, + "Works/my-novel/Stories/ch01-broken.md" + ); + + let report = + apply_reconcile_diff(&pool, "wrk_recon_skip_wc", "2026-06-07T11:00:00Z", &diff) + .await + .unwrap(); + assert_eq!(report.updated, 1, "the word count is mirrored into the DB"); + assert_eq!(report.resynced, 0); + assert_eq!(report.skipped, diff.skipped); + + let row = get_chapter(&pool, "wrk_recon_skip_wc", 1, 1) + .await + .unwrap() + .expect("ch1"); + assert_eq!(row.actual_word_count, Some(1200), "word_count is mirrored"); + assert_eq!(row.status, "not_started", "status stays the DB SSOT"); + assert_eq!( + std::fs::read_to_string(&broken_path).unwrap(), + broken, + "the file's frontmatter status is unchanged" + ); + } + // ----------------------------------------------------------------------- // Frontmatter re-sync rendering is pure (V1.48 P4-fix1 W-1 qc2). The atomic // byte write itself is the Work port's `fsync_write_atomic`, covered by