lwc 0.15.2

Agent-driven proactive memory CLI for AI agents — autonomously recall, maintain, and evolve persistent, source-grounded knowledge across sessions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
use crate::{
    error::{AppError, Result},
    scope::{Scope, StorePath},
    store::{ChangesetDraftState, ChangesetPublishInput, ChangesetRollbackInput, Store},
};
use serde::Serialize;
use serde_json::{Value, json};
use std::{
    fs,
    path::{Path, PathBuf},
    time::Instant,
};

#[derive(Debug, Serialize)]
pub struct ChangesetBeginResponse {
    pub scope: &'static str,
    pub database: PathBuf,
    pub changeset_id: String,
    pub name: String,
    pub status: String,
    pub base_revision: String,
    pub duration_ms: u64,
}

#[derive(Debug, Serialize)]
pub struct ChangesetShowResponse {
    pub scope: &'static str,
    pub database: PathBuf,
    pub changeset_id: String,
    pub name: String,
    pub status: String,
    pub base_revision: String,
    pub draft_revision: String,
    pub staged_operation_count: usize,
    pub action_counts: std::collections::BTreeMap<String, usize>,
    pub operations: Vec<crate::store::OperationRecord>,
    pub empty: bool,
    pub conflict: bool,
    pub created_at: String,
}

#[derive(Debug, Serialize)]
pub struct ChangesetListResponse {
    pub scope: &'static str,
    pub database: PathBuf,
    pub changesets: Vec<ChangesetShowResponse>,
}

#[derive(Debug, Serialize)]
pub struct ChangesetDiscardResponse {
    pub scope: &'static str,
    pub database: PathBuf,
    pub changeset_id: String,
    pub name: String,
    pub status: &'static str,
}

#[derive(Debug, Serialize)]
pub struct ChangesetCommitResponse {
    pub scope: &'static str,
    pub database: PathBuf,
    pub changeset_id: String,
    pub name: String,
    pub status: &'static str,
    pub base_revision: String,
    pub post_revision: String,
    pub checkpoint: String,
    pub staged_operation_count: usize,
    pub lint_issues: usize,
    pub materialized: bool,
    pub wal_checkpointed: bool,
    pub duration_ms: u64,
    pub checkpoint_ms: u64,
    pub locked_publish_ms: u64,
    pub wal_checkpoint_ms: u64,
    pub cleanup_ms: u64,
    pub materialization_ms: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub graph_work: Option<Value>,
}

#[derive(Debug, Serialize)]
pub struct ChangesetRollbackResponse {
    pub scope: &'static str,
    pub database: PathBuf,
    pub changeset_id: String,
    pub name: String,
    pub status: &'static str,
    pub rollback_revision: String,
    pub checkpoint: String,
    pub materialized: bool,
    pub wal_checkpointed: bool,
    pub duration_ms: u64,
    pub checkpoint_ms: u64,
    pub locked_rollback_ms: u64,
    pub wal_checkpoint_ms: u64,
    pub materialization_ms: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub graph_work: Option<Value>,
}

pub fn begin(live: &StorePath, name: &str) -> Result<ChangesetBeginResponse> {
    let started = Instant::now();
    validate_name(name)?;
    let path = draft_path(live, name, true)?;
    reject_existing_draft(&path)?;
    remove_draft_runtime(&path)?;

    let live_store = Store::open_for_read(scope_name(live.scope), &live.path)?;
    let base = live_store.identity()?;
    let schema = live_store.schema_show()?.schema.unwrap_or_default();
    let purpose = live_store.purpose_show()?.purpose.unwrap_or_default();
    let max_source_id = live_store.max_source_id()?;

    let result = (|| -> Result<ChangesetDraftState> {
        let (mut draft, _) = Store::initialize(scope_name(live.scope), &path)?;
        let state = draft.changeset_begin_sparse(name, &base, &schema, &purpose, max_source_id)?;
        fs::create_dir(crate::scope::database_runtime_root(&path)?)?;
        Ok(state)
    })();
    let state = match result {
        Ok(state) => state,
        Err(error) => {
            let _ = remove_draft_files(&path);
            return Err(error);
        }
    };
    Ok(ChangesetBeginResponse {
        scope: scope_name(live.scope),
        database: path,
        changeset_id: state.id,
        name: state.name,
        status: state.status,
        base_revision: state.base_revision,
        duration_ms: elapsed_millis(started),
    })
}

pub fn resolve_effective(live: StorePath, name: Option<&str>) -> Result<StorePath> {
    let Some(name) = name else {
        return Ok(live);
    };
    let path = draft_path(&live, name, false)?;
    validate_draft_binding(&live, name, &path, 0)?;
    ensure_draft_runtime(&path)?;
    Ok(live.with_database(path))
}

pub fn prepare_page_touch(
    live: &StorePath,
    name: &str,
    slug: &str,
    source_ids: &[i64],
) -> Result<()> {
    let path = draft_path(live, name, false)?;
    validate_draft_binding(live, name, &path, 0)?;
    let mut draft = Store::open(scope_name(live.scope), &path)?;
    let sparse = draft.changeset_storage_kind()?.as_deref() == Some("sparse-v1");
    if sparse {
        draft.changeset_prepare_page_touch(&live.path, slug, source_ids)?;
    }
    Ok(())
}

pub fn prepare_tag_touch(
    live: &StorePath,
    name: &str,
    tag: &str,
    page: Option<&str>,
    require_member: bool,
) -> Result<()> {
    let path = draft_path(live, name, false)?;
    validate_draft_binding(live, name, &path, 0)?;
    let member = if let Some(page) = page {
        Some(page.to_string())
    } else if require_member {
        Store::open_for_read(scope_name(live.scope), &live.path)?.tag_first_page(tag)?
    } else {
        None
    };
    let mut draft = Store::open(scope_name(live.scope), &path)?;
    if draft.changeset_storage_kind()?.as_deref() == Some("sparse-v1") {
        draft.changeset_prepare_tag_touch(&live.path, tag, member.as_deref())?;
    }
    Ok(())
}

pub fn show(live: &StorePath, name: &str, limit: usize) -> Result<ChangesetShowResponse> {
    validate_name(name)?;
    let path = draft_path(live, name, false)?;
    show_path(live, name, path, limit)
}

pub fn list(live: &StorePath, limit: usize) -> Result<ChangesetListResponse> {
    let directory = changeset_directory(live, false)?;
    if !directory.exists() {
        return Ok(ChangesetListResponse {
            scope: scope_name(live.scope),
            database: live.path.clone(),
            changesets: Vec::new(),
        });
    }
    let mut names = Vec::new();
    for entry in fs::read_dir(&directory)? {
        let entry = entry?;
        let path = entry.path();
        let metadata = fs::symlink_metadata(&path)?;
        if metadata.file_type().is_symlink() {
            return Err(invalid_path(&path));
        }
        if !metadata.is_file() || path.extension().and_then(|value| value.to_str()) != Some("db") {
            continue;
        }
        let Some(name) = path.file_stem().and_then(|value| value.to_str()) else {
            return Err(invalid_path(&path));
        };
        validate_name(name)?;
        names.push(name.to_string());
    }
    names.sort();
    let mut changesets = Vec::with_capacity(names.len().min(limit));
    for name in names.into_iter().take(limit) {
        changesets.push(show(live, &name, 0)?);
    }
    Ok(ChangesetListResponse {
        scope: scope_name(live.scope),
        database: live.path.clone(),
        changesets,
    })
}

pub fn discard(live: &StorePath, name: &str) -> Result<ChangesetDiscardResponse> {
    validate_name(name)?;
    let path = draft_path(live, name, false)?;
    let state = validate_draft_binding(live, name, &path, 0)?;
    remove_draft_files(&path)?;
    Ok(ChangesetDiscardResponse {
        scope: scope_name(live.scope),
        database: live.path.clone(),
        changeset_id: state.id,
        name: state.name,
        status: "discarded",
    })
}

pub fn lint(
    live: &StorePath,
    name: &str,
    limit: usize,
    offset: usize,
) -> Result<crate::store::LintResponse> {
    let path = draft_path(live, name, false)?;
    validate_draft_binding(live, name, &path, 0)?;
    let draft = Store::open_for_read(scope_name(live.scope), &path)?;
    if draft.changeset_storage_kind()?.as_deref() != Some("sparse-v1") {
        return draft.lint(limit, offset);
    }
    Store::open(scope_name(live.scope), &live.path)?.changeset_sparse_lint(&path, limit, offset)
}

pub fn commit(
    live: &StorePath,
    name: &str,
    allow_lint_issues: bool,
    reason: Option<&str>,
) -> Result<ChangesetCommitResponse> {
    let started = Instant::now();
    validate_lint_override(allow_lint_issues, reason)?;
    validate_name(name)?;
    let path = draft_path(live, name, false)?;
    match fs::symlink_metadata(&path) {
        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => {
            return Err(invalid_path(&path));
        }
        Ok(_) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Err(AppError::new(
                "changeset_not_found",
                format!("draft changeset not found: {name}"),
            ));
        }
        Err(error) => return Err(error.into()),
    }
    let state = validate_draft_binding(live, name, &path, 0)?;
    if state.staged_operation_count == 0 {
        return Err(AppError::new(
            "changeset_empty",
            "changeset has no staged operation after begin",
        ));
    }

    let live_reader = Store::open_for_read(scope_name(live.scope), &live.path)?;
    if let Some(committed) = live_reader.changeset_committed_by_id(&state.id)? {
        drop(live_reader);
        let graph_work = if committed.graph_documents.is_empty() {
            let graph = crate::external_graph::passive_status(scope_name(live.scope), &live.path)?;
            if graph["engine"] == "disabled" {
                None
            } else {
                Some(crate::work::start_graph_projection(
                    scope_name(live.scope),
                    &live.path,
                )?["work"]
                    .clone())
            }
        } else {
            Store::open(scope_name(live.scope), &live.path)?
                .schedule_graph_documents(&committed.graph_documents)?
        };
        return finish_committed(live, &path, committed, started, 0, graph_work);
    }
    let live_identity = live_reader.identity()?;
    let draft = Store::open_for_read(scope_name(live.scope), &path)?;
    if live_identity.store_id != draft.identity()?.store_id {
        return Err(AppError::new(
            "changeset_scope_mismatch",
            "changeset is not bound to this live Wiki",
        ));
    }
    let sparse = draft.changeset_storage_kind()?.as_deref() == Some("sparse-v1");
    if sparse {
        for (slug, expected) in draft.changeset_touched_pages()? {
            let observed = live_reader
                .page_mutation_fingerprint(&slug)?
                .unwrap_or_else(|| "absent".into());
            if observed != expected {
                return Err(AppError::new(
                    "changeset_conflict",
                    format!("page {slug} changed after it was first touched"),
                )
                .with_details(json!({"entity_type": "page", "identifier": slug})));
            }
        }
        for (key, expected) in draft.changeset_touched_meta()? {
            if live_reader.meta_fingerprint(&key)? != expected {
                return Err(AppError::new(
                    "changeset_conflict",
                    format!("{key} changed after the changeset began"),
                )
                .with_details(json!({"entity_type": "meta", "identifier": key})));
            }
        }
        for (tag, expected) in draft.changeset_touched_tags()? {
            if live_reader.tag_fingerprint(&tag)? != expected {
                return Err(AppError::new(
                    "changeset_conflict",
                    format!("tag {tag} changed after it was first touched"),
                )
                .with_details(json!({"entity_type": "tag", "identifier": tag})));
            }
        }
    }
    draft.validate_changeset_integrity()?;
    let lint_issues = if sparse {
        Store::open(scope_name(live.scope), &live.path)?
            .changeset_sparse_lint(&path, 1, 0)?
            .total
    } else {
        draft.lint(1, 0)?.total
    };
    if lint_issues > 0 && !allow_lint_issues {
        return Err(AppError::new(
            "changeset_lint_failed",
            format!("changeset has {lint_issues} lint issue(s); repair it before commit"),
        ));
    }
    let mut graph_documents = draft.changeset_graph_documents()?;
    for path in draft.changeset_touched_source_paths()? {
        if let Some(source_id) = live_reader.source_path_head(&path)? {
            graph_documents.push(("source".to_string(), source_id.to_string()));
        }
    }
    drop(draft);
    let mut draft_store = Store::open(scope_name(live.scope), &path)?;
    draft_store.changeset_freeze(
        &state.id,
        &state.draft_revision,
        state.draft_operation_id,
        state.staged_operation_count,
    )?;
    drop(draft_store);
    let checkpoint_started = Instant::now();
    let checkpoint = if sparse {
        live_reader.changeset_sparse_checkpoint_create(&state.id, &path)?
    } else {
        live_reader.changeset_checkpoint_create(&state.id)?
    };
    let checkpoint_ms = elapsed_millis(checkpoint_started);
    drop(live_reader);

    let mut live_store = Store::open(scope_name(live.scope), &live.path)?;
    let committed = live_store.changeset_publish(
        &path,
        &ChangesetPublishInput {
            id: state.id,
            name: state.name,
            store_id: live_identity.store_id,
            base_revision: state.base_revision,
            draft_revision: state.draft_revision,
            draft_operation_id: state.draft_operation_id,
            staged_operation_count: state.staged_operation_count,
            checkpoint: checkpoint.checkpoint,
            lint_issues,
            lint_override_reason: reason.map(str::to_string),
            graph_documents: graph_documents.clone(),
        },
    )?;
    let graph_work = live_store
        .schedule_graph_documents(&committed.graph_documents)
        .map_err(|error| {
            AppError::new(
                "graph_projection_failed",
                "changeset committed canonically but graph Work could not be queued",
            )
            .with_details(json!({
                "canonical_committed": true,
                "changeset_id": committed.changeset_id,
                "checkpoint": committed.checkpoint,
                "cause": error.code,
                "recovery_command": format!("lwc changeset commit {}", committed.name),
            }))
        })?;
    drop(live_store);
    finish_committed(live, &path, committed, started, checkpoint_ms, graph_work)
}

fn finish_committed(
    live: &StorePath,
    path: &Path,
    committed: crate::store::ChangesetCommitState,
    started: Instant,
    checkpoint_ms: u64,
    graph_work: Option<Value>,
) -> Result<ChangesetCommitResponse> {
    let cleanup_started = Instant::now();
    if let Err(error) = remove_draft_files(path) {
        return Err(AppError::new(
            "changeset_committed_cleanup_failed",
            format!("changeset committed but draft cleanup failed: {error}"),
        )
        .with_details(json!({
            "committed": true,
            "changeset_id": committed.changeset_id,
            "checkpoint": committed.checkpoint,
            "recovery_command": format!("lwc changeset commit {}", committed.name),
        })));
    }
    let cleanup_ms = elapsed_millis(cleanup_started);
    let materialization_started = Instant::now();
    let materialized = Store::open(scope_name(live.scope), &live.path)
        .and_then(|store| store.materialize_incremental(true).map(|_| ()));
    if let Err(error) = materialized {
        return Err(AppError::new(
            "changeset_committed_materialization_failed",
            format!("changeset committed but Markdown materialization failed: {error}"),
        )
        .with_details(json!({
            "committed": true,
            "changeset_id": committed.changeset_id,
            "checkpoint": committed.checkpoint,
            "recovery_command": "lwc maintenance materialize",
        })));
    }
    let materialization_ms = elapsed_millis(materialization_started);
    let wal_checkpoint_started = Instant::now();
    let wal_checkpointed = Store::open(scope_name(live.scope), &live.path)
        .is_ok_and(|store| store.try_checkpoint_wal());
    let wal_checkpoint_ms = elapsed_millis(wal_checkpoint_started);
    Ok(ChangesetCommitResponse {
        scope: scope_name(live.scope),
        database: live.path.clone(),
        changeset_id: committed.changeset_id,
        name: committed.name,
        status: "committed",
        base_revision: committed.base_revision,
        post_revision: committed.post_revision,
        checkpoint: committed.checkpoint,
        staged_operation_count: committed.staged_operation_count,
        lint_issues: committed.lint_issues,
        materialized: true,
        wal_checkpointed,
        duration_ms: elapsed_millis(started),
        checkpoint_ms,
        locked_publish_ms: committed.locked_publish_ms,
        wal_checkpoint_ms,
        cleanup_ms,
        materialization_ms,
        graph_work,
    })
}

pub fn rollback(live: &StorePath, changeset_id: &str) -> Result<ChangesetRollbackResponse> {
    let started = Instant::now();
    validate_id(changeset_id)?;
    let live_reader = Store::open_for_read(scope_name(live.scope), &live.path)?;
    let history = live_reader
        .changeset_history_by_id(changeset_id)?
        .ok_or_else(|| {
            AppError::new(
                "changeset_not_found",
                format!("committed changeset not found: {changeset_id}"),
            )
        })?;
    if history.status == "rolled_back" {
        let state = live_reader
            .changeset_rollback_state_by_id(changeset_id)?
            .ok_or_else(|| {
                AppError::new(
                    "changeset_corrupt",
                    "rolled-back changeset has no rollback operation",
                )
            })?;
        drop(live_reader);
        return finish_rolled_back(live, state, started, 0);
    }
    if history.status != "committed" {
        return Err(AppError::new(
            "changeset_not_found",
            format!("changeset is not committed: {changeset_id}"),
        ));
    }
    let identity = live_reader.identity()?;
    let sparse =
        live_reader.changeset_rollback_checkpoint_validate(&history, &identity.store_id)?;
    if !sparse && history.post_revision.as_deref() != Some(identity.revision.as_str()) {
        return Err(AppError::new(
            "changeset_rollback_conflict",
            "live Wiki changed after this changeset committed",
        ));
    }
    let checkpoint_started = Instant::now();
    let checkpoint = if sparse {
        live_reader.changeset_sparse_rollback_checkpoint_create(&history)?
    } else {
        live_reader.changeset_rollback_checkpoint_create(changeset_id)?
    };
    let checkpoint_ms = elapsed_millis(checkpoint_started);
    drop(live_reader);

    let mut live_store = Store::open(scope_name(live.scope), &live.path)?;
    let rolled_back = live_store.changeset_rollback(&ChangesetRollbackInput {
        history,
        store_id: identity.store_id,
        pre_rollback_checkpoint: checkpoint.checkpoint,
    })?;
    drop(live_store);
    finish_rolled_back(live, rolled_back, started, checkpoint_ms)
}

fn finish_rolled_back(
    live: &StorePath,
    rolled_back: crate::store::ChangesetRollbackState,
    started: Instant,
    checkpoint_ms: u64,
) -> Result<ChangesetRollbackResponse> {
    let materialization_started = Instant::now();
    let materialized = Store::open(scope_name(live.scope), &live.path)
        .and_then(|store| store.materialize_incremental(true).map(|_| ()));
    if let Err(error) = materialized {
        return Err(AppError::new(
            "changeset_rolled_back_materialization_failed",
            format!("changeset rolled back but Markdown materialization failed: {error}"),
        )
        .with_details(json!({
            "rolled_back": true,
            "changeset_id": rolled_back.changeset_id,
            "checkpoint": rolled_back.checkpoint,
            "recovery_command": format!("lwc changeset rollback {}", rolled_back.changeset_id),
        })));
    }
    let materialization_ms = elapsed_millis(materialization_started);
    let graph_work = Store::open(scope_name(live.scope), &live.path)?
        .schedule_graph_documents(&rolled_back.graph_documents)
        .map_err(|error| {
            AppError::new(
                "changeset_rolled_back_graph_projection_failed",
                "changeset rolled back canonically but graph Work could not be queued",
            )
            .with_details(json!({
                "rolled_back": true,
                "changeset_id": rolled_back.changeset_id,
                "checkpoint": rolled_back.checkpoint,
                "cause": error.code,
                "recovery_command": format!("lwc changeset rollback {}", rolled_back.changeset_id),
            }))
        })?;
    let wal_checkpoint_started = Instant::now();
    let wal_checkpointed = Store::open(scope_name(live.scope), &live.path)
        .is_ok_and(|store| store.try_checkpoint_wal());
    let wal_checkpoint_ms = elapsed_millis(wal_checkpoint_started);
    Ok(ChangesetRollbackResponse {
        scope: scope_name(live.scope),
        database: live.path.clone(),
        changeset_id: rolled_back.changeset_id,
        name: rolled_back.name,
        status: "rolled_back",
        rollback_revision: rolled_back.rollback_revision,
        checkpoint: rolled_back.checkpoint,
        materialized: true,
        wal_checkpointed,
        duration_ms: elapsed_millis(started),
        checkpoint_ms,
        locked_rollback_ms: rolled_back.locked_rollback_ms,
        wal_checkpoint_ms,
        materialization_ms,
        graph_work,
    })
}

fn elapsed_millis(started: Instant) -> u64 {
    u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)
}

pub fn reject_selector(selector: Option<&str>, command: &str) -> Result<()> {
    if selector.is_some() {
        return Err(AppError::new(
            "changeset_command_unsupported",
            format!("{command} cannot be combined with --changeset"),
        ));
    }
    Ok(())
}

fn show_path(
    live: &StorePath,
    name: &str,
    path: PathBuf,
    limit: usize,
) -> Result<ChangesetShowResponse> {
    let state = validate_draft_binding(live, name, &path, limit)?;
    let live_identity = Store::open_for_read(scope_name(live.scope), &live.path)?.identity()?;
    let draft = Store::open_for_read(scope_name(live.scope), &path)?;
    let empty = state.staged_operation_count == 0;
    let sparse = draft
        .changeset_storage_kind()?
        .as_deref()
        .is_some_and(|value| value == "sparse-v1");
    let conflict = live_identity.store_id != draft.identity()?.store_id
        || (!sparse && live_identity.revision != state.base_revision);
    Ok(ChangesetShowResponse {
        scope: scope_name(live.scope),
        database: path,
        changeset_id: state.id,
        name: state.name,
        status: state.status,
        base_revision: state.base_revision,
        draft_revision: state.draft_revision,
        staged_operation_count: state.staged_operation_count,
        action_counts: state.action_counts,
        operations: state.operations,
        empty,
        conflict,
        created_at: state.created_at,
    })
}

fn validate_draft_binding(
    live: &StorePath,
    name: &str,
    path: &Path,
    limit: usize,
) -> Result<ChangesetDraftState> {
    require_regular_file(path)?;
    let draft = Store::open_for_read(scope_name(live.scope), path)
        .map_err(|error| map_draft_error(error, name))?;
    let state = draft
        .changeset_draft(name, limit)
        .map_err(|error| map_draft_error(error, name))?;
    let live_identity = Store::open_for_read(scope_name(live.scope), &live.path)?.identity()?;
    let draft_identity = draft.identity()?;
    if live_identity.store_id != draft_identity.store_id {
        return Err(AppError::new(
            "changeset_scope_mismatch",
            format!("draft changeset {name} is not bound to the selected Wiki"),
        ));
    }
    Ok(state)
}

fn map_draft_error(error: AppError, name: &str) -> AppError {
    if error.code == "store_not_found" || error.code == "changeset_not_found" {
        AppError::new(
            "changeset_not_found",
            format!("draft changeset not found: {name}"),
        )
    } else {
        error
    }
}

fn validate_name(name: &str) -> Result<()> {
    if name.is_empty()
        || name.len() > 80
        || name != name.trim()
        || matches!(name, "." | "..")
        || name.contains(['/', '\\'])
        || name.chars().any(char::is_control)
    {
        return Err(AppError::new(
            "changeset_name_invalid",
            "changeset name must be one safe filename segment of at most 80 bytes",
        ));
    }
    Ok(())
}

fn validate_id(id: &str) -> Result<()> {
    if id.len() == 64 && id.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Ok(());
    }
    Err(AppError::new(
        "changeset_not_found",
        "changeset id must be a 64-character hexadecimal value",
    ))
}

fn validate_lint_override(allow: bool, reason: Option<&str>) -> Result<()> {
    match (allow, reason) {
        (false, None) => return Ok(()),
        (true, Some(value)) if !value.trim().is_empty() => return Ok(()),
        _ => {}
    }
    Err(AppError::new(
        "changeset_lint_override_invalid",
        "--allow-lint-issues and a nonblank --reason must be provided together",
    ))
}

fn draft_path(live: &StorePath, name: &str, create_directory: bool) -> Result<PathBuf> {
    validate_name(name)?;
    Ok(changeset_directory(live, create_directory)?.join(format!("{name}.db")))
}

fn changeset_directory(live: &StorePath, create: bool) -> Result<PathBuf> {
    let parent = live
        .path
        .parent()
        .ok_or_else(|| AppError::new("invalid_store_path", "database has no parent"))?;
    let directory = parent.join("changesets");
    match fs::symlink_metadata(&directory) {
        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => {
            return Err(invalid_path(&directory));
        }
        Ok(_) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound && create => {
            fs::create_dir(&directory)?;
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => return Err(error.into()),
    }
    Ok(directory)
}

fn reject_existing_draft(path: &Path) -> Result<()> {
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => {
            Err(invalid_path(path))
        }
        Ok(_) => Err(AppError::new(
            "changeset_exists",
            format!("draft changeset already exists: {}", path.display()),
        )),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error.into()),
    }
}

fn require_regular_file(path: &Path) -> Result<()> {
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => {
            return Err(invalid_path(path));
        }
        Ok(_) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Err(AppError::new(
            "changeset_not_found",
            format!("draft changeset not found: {}", path.display()),
        ))?,
        Err(error) => return Err(error.into()),
    }
    for sidecar in [
        database_sidecar(path, "-wal"),
        database_sidecar(path, "-shm"),
    ] {
        match fs::symlink_metadata(&sidecar) {
            Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => {
                return Err(invalid_path(&sidecar));
            }
            Ok(_) => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error.into()),
        }
    }
    Ok(())
}

fn remove_draft_files(database: &Path) -> Result<()> {
    let paths = [
        database_sidecar(database, "-wal"),
        database_sidecar(database, "-shm"),
        database.to_path_buf(),
    ];
    for path in &paths {
        match fs::symlink_metadata(path) {
            Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => {
                return Err(invalid_path(path));
            }
            Ok(_) => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error.into()),
        }
    }
    remove_draft_runtime(database)?;
    for path in paths {
        match fs::remove_file(&path) {
            Ok(()) => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error.into()),
        }
    }
    Ok(())
}

fn remove_draft_runtime(database: &Path) -> Result<()> {
    let runtime = crate::scope::database_runtime_root(database)?;
    match fs::symlink_metadata(&runtime) {
        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => {
            Err(invalid_path(&runtime))
        }
        Ok(_) => fs::remove_dir_all(&runtime).map_err(Into::into),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error.into()),
    }
}

fn ensure_draft_runtime(database: &Path) -> Result<()> {
    let runtime = crate::scope::database_runtime_root(database)?;
    match fs::symlink_metadata(&runtime) {
        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => {
            Err(invalid_path(&runtime))
        }
        Ok(_) => Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            fs::create_dir(&runtime)?;
            Ok(())
        }
        Err(error) => Err(error.into()),
    }
}

fn database_sidecar(path: &Path, suffix: &str) -> PathBuf {
    let mut sidecar = path.as_os_str().to_os_string();
    sidecar.push(suffix);
    sidecar.into()
}

fn invalid_path(path: &Path) -> AppError {
    AppError::new(
        "changeset_path_invalid",
        format!(
            "changeset path is not a regular owned path: {}",
            path.display()
        ),
    )
}

fn scope_name(scope: Scope) -> &'static str {
    match scope {
        Scope::Project => "project",
        Scope::Global => "global",
        Scope::All => "all",
    }
}