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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
//! # mana-core Public API
//!
//! Programmatic access to all mana unit operations. Use this module when embedding
//! mana in another application — a GUI, MCP server, orchestration daemon, or custom
//! tooling.
//!
//! The API is organized into layers:
//!
//! - **Types** — Core data structures re-exported from internal modules
//! - **Discovery** — Find `.mana/` directories and unit files
//! - **Query** — Read-only operations (list, get, tree, status, graph)
//! - **Mutations** — Write operations (create, update, close, delete)
//! - **Orchestration** — Agent dispatch, context assembly, and verification
//! - **Facts** — Verified project knowledge with TTL
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use mana_core::api::*;
//! use std::path::Path;
//!
//! // Find the .mana/ directory
//! let mana_dir = find_mana_dir(Path::new(".")).unwrap();
//!
//! // Load the index (cached, rebuilds if stale)
//! let index = load_index(&mana_dir).unwrap();
//!
//! // Get a specific unit
//! let unit = get_unit(&mana_dir, "1").unwrap();
//! println!("{}: {}", unit.id, unit.title);
//! ```
//!
//! ## Design Principles
//!
//! - **No I/O side effects** — Library functions never print to stdout/stderr.
//! All output is returned as structured data.
//! - **Structured params and results** — Each mutation takes a `Params` struct
//! and returns a typed result. No raw argument passing.
//! - **`&Path` as entry point** — Every function takes `mana_dir: &Path`.
//! No global state, no singletons, no `Arc` required.
//! - **Serializable** — All types derive `Serialize`/`Deserialize` for easy
//! IPC (Tauri, JSON-RPC, MCP).
//! - **Thread-safe** — No interior mutability, no shared global state.
use HashMap;
use Path;
use Result;
use crate;
// ---------------------------------------------------------------------------
// Re-exported core types
// ---------------------------------------------------------------------------
/// Core unit type representing a single work item.
pub use crate;
/// Index types for working with the unit cache.
pub use crate;
/// Project configuration.
pub use crateConfig;
/// Typed error and result types.
pub use crate;
// ---------------------------------------------------------------------------
// Discovery re-exports
// ---------------------------------------------------------------------------
/// Find the `.mana/` directory by walking up from `path`.
///
/// Searches the given path and all parent directories until a `.mana/`
/// directory is found.
///
/// # Errors
/// - Returns an error if no `.mana/` directory is found in the hierarchy
/// - [`ManaError::IoError`] — filesystem failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::find_mana_dir;
/// use std::path::Path;
///
/// let mana_dir = find_mana_dir(Path::new("/some/project/subdir")).unwrap();
/// ```
pub use cratefind_mana_dir;
/// Find the file path for a unit by ID.
///
/// Searches the `.mana/` directory for an active (non-archived) unit with
/// the given ID.
///
/// # Errors
/// - [`ManaError::UnitNotFound`] — no unit file for the given ID
/// - [`ManaError::InvalidId`] — ID is empty or contains invalid characters
/// - [`ManaError::IoError`] — filesystem failure
pub use cratefind_unit_file;
/// Find the file path for an archived unit by ID.
///
/// Searches the `.mana/archive/` tree for a unit that was previously closed.
///
/// # Errors
/// - [`ManaError::UnitNotFound`] — unit ID not found in archive
/// - [`ManaError::InvalidId`] — ID is empty or contains invalid characters
pub use cratefind_archived_unit;
// ---------------------------------------------------------------------------
// Graph types (new: not in ops modules)
// ---------------------------------------------------------------------------
/// A node in the unit hierarchy tree, used by [`get_tree`].
/// A node in the unit hierarchy tree, used by [`get_tree`].
/// A full dependency graph representation.
///
/// The graph is a directed acyclic graph where each edge `a -> b`
/// means "unit `a` depends on unit `b`".
/// A node in the dependency graph.
// Re-export orchestration and ops types
pub use crate;
pub use cratesummarize_child_units as compare_sibling_jobs;
pub use crateAgentContext;
pub use crate;
pub use crate;
pub use crate;
pub use crate;
pub use crateStatsResult;
pub use crateStatusSummary;
pub use crateVerifyResult;
// ---------------------------------------------------------------------------
// Query functions
// ---------------------------------------------------------------------------
/// Load a unit by ID.
///
/// Finds the unit file in the `.mana/` directory and deserializes it.
/// Works for active (non-archived) units only. For archived units, use
/// [`get_archived_unit`].
///
/// # Errors
/// - [`ManaError::UnitNotFound`] — no unit file for the given ID
/// - [`ManaError::InvalidId`] — ID is empty or contains invalid characters
/// - [`ManaError::ParseError`] — file cannot be deserialized
/// - [`ManaError::IoError`] — filesystem failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::get_unit;
/// use std::path::Path;
///
/// let mana_dir = Path::new("/project/.mana");
/// let unit = get_unit(mana_dir, "42").unwrap();
/// println!("{}: {}", unit.id, unit.title);
/// ```
/// Load a unit from the archive by ID.
///
/// Searches the `.mana/archive/` tree for a unit that was previously closed
/// and archived.
///
/// # Errors
/// - [`ManaError::UnitNotFound`] — unit ID not found in archive
/// - [`ManaError::InvalidId`] — ID is empty or contains invalid characters
/// - [`ManaError::ParseError`] — file cannot be deserialized
/// - [`ManaError::IoError`] — filesystem failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::get_archived_unit;
/// use std::path::Path;
///
/// let mana_dir = Path::new("/project/.mana");
/// let unit = get_archived_unit(mana_dir, "42").unwrap();
/// println!("Closed at: {:?}", unit.closed_at);
/// ```
/// Load the index, rebuilding from unit files if stale.
///
/// The index is a YAML cache that's faster than reading every unit file.
/// It is automatically rebuilt when unit files are newer than the cached index.
///
/// # Errors
/// - [`ManaError::IndexError`] — index cannot be built, loaded, or saved
/// - [`ManaError::IoError`] — filesystem failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::load_index;
/// use std::path::Path;
///
/// let index = load_index(Path::new("/project/.mana")).unwrap();
/// println!("{} units", index.units.len());
/// ```
/// List units with optional filters.
///
/// Returns index entries (lightweight unit summaries) for all units matching
/// the given filters. By default, closed units are excluded.
///
/// # Errors
/// - [`ManaError::IndexError`] — index cannot be loaded
/// - [`ManaError::IoError`] — filesystem failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::list_units;
/// use mana_core::ops::list::ListParams;
/// use std::path::Path;
///
/// let mana_dir = Path::new("/project/.mana");
///
/// // List all open units
/// let units = list_units(mana_dir, &ListParams::default()).unwrap();
///
/// // List units assigned to alice
/// let alice_units = list_units(mana_dir, &ListParams {
/// assignee: Some("alice".to_string()),
/// ..Default::default()
/// }).unwrap();
/// ```
/// Build a unit hierarchy tree rooted at the given unit ID.
///
/// Returns a [`TreeNode`] with all descendants nested recursively. Only units
/// in the active index are included (archived units are excluded).
///
/// # Errors
/// - [`ManaError::UnitNotFound`] — no unit with the given ID in the active index
/// - [`ManaError::IndexError`] — index cannot be loaded
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::get_tree;
/// use std::path::Path;
///
/// let tree = get_tree(Path::new("/project/.mana"), "1").unwrap();
/// println!("{}: {} children", tree.id, tree.children.len());
/// ```
/// Get a categorized project status summary.
///
/// Returns units grouped into: epics, features, in-progress (claimed), ready to run,
/// goals (no verify command), and blocked (dependencies not met).
///
/// # Errors
/// - [`ManaError::IndexError`] — index cannot be loaded
/// - [`ManaError::IoError`] — filesystem failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::get_status;
/// use std::path::Path;
///
/// let summary = get_status(Path::new("/project/.mana")).unwrap();
/// println!("Ready: {}, Blocked: {}", summary.ready.len(), summary.blocked.len());
/// ```
/// Get aggregate project statistics.
///
/// Returns counts by status, priority distribution, completion percentage,
/// and cost/token metrics from unit history (if available).
///
/// # Errors
/// - [`ManaError::IndexError`] — index cannot be loaded
/// - [`ManaError::IoError`] — filesystem failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::get_stats;
/// use std::path::Path;
///
/// let stats = get_stats(Path::new("/project/.mana")).unwrap();
/// println!("Completion: {:.1}%", stats.completion_pct);
/// println!("Total: {}, Open: {}, Closed: {}", stats.total, stats.open, stats.closed);
/// ```
// ---------------------------------------------------------------------------
// Graph functions
// ---------------------------------------------------------------------------
/// Return units with all dependencies satisfied (ready to dispatch).
///
/// A unit is "ready" if it is an open dispatchable task and all of its
/// explicit dependency IDs are closed in the active index or archived.
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::{load_index, ready_units};
/// use std::path::Path;
///
/// let mana_dir = Path::new("/project/.mana");
/// let index = load_index(mana_dir).unwrap();
/// let ready = ready_units(&index);
/// for entry in ready {
/// println!("Ready: {} {}", entry.id, entry.title);
/// }
/// ```
/// Build a dependency graph from the active index.
///
/// Returns a [`DependencyGraph`] with all units as nodes and explicit
/// dependency relationships as directed edges (`a -> b` = `a` depends on `b`).
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::{load_index, dependency_graph};
/// use std::path::Path;
///
/// let mana_dir = Path::new("/project/.mana");
/// let index = load_index(mana_dir).unwrap();
/// let graph = dependency_graph(&index);
/// println!("{} nodes, {} with deps", graph.nodes.len(),
/// graph.edges.values().filter(|deps| !deps.is_empty()).count());
/// ```
/// Topologically sort all units by dependency order.
///
/// Returns a list of unit IDs where each unit appears after all its
/// dependencies. Units with no dependencies appear first.
///
/// # Errors
/// - Returns an error if a cycle is detected in the dependency graph.
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::{load_index, topological_sort};
/// use std::path::Path;
///
/// let mana_dir = Path::new("/project/.mana");
/// let index = load_index(mana_dir).unwrap();
/// let order = topological_sort(&index).unwrap();
/// println!("Execution order: {:?}", order);
/// ```
// ---------------------------------------------------------------------------
// Additional graph utilities (re-exported from graph module)
// ---------------------------------------------------------------------------
/// Build a text dependency tree rooted at a unit ID.
///
/// Returns a box-drawing string showing which units depend on the given unit.
///
/// # Errors
/// - Returns an error if the unit ID is not found in the index.
pub use cratebuild_dependency_tree;
/// Build a project-wide dependency graph as a text tree.
///
/// Shows all units with no parents as roots, with their dependents branching below.
///
/// # Errors
/// - Returns an error only on unexpected failures.
pub use cratebuild_full_graph;
/// Count total verify attempts across all descendants of a unit.
///
/// Includes the unit itself and archived descendants. Used by the circuit
/// breaker to detect runaway retry loops across a subtree.
///
/// # Errors
/// - Returns an error on I/O failures reading the index.
pub use cratecount_subtree_attempts;
/// Find all dependency cycles in the graph.
///
/// Returns a list of cycle paths (each path is a list of unit IDs forming a cycle).
/// An empty list means the graph is acyclic.
///
/// # Errors
/// - Returns an error only on unexpected graph traversal failures.
pub use cratefind_all_cycles;
// Also re-export validate_priority for callers who need to validate
pub use cratevalidate_priority;
/// Detect whether adding an edge from `from_id` to `to_id` would create a cycle.
///
/// Returns `true` if the proposed edge would introduce a cycle. Use this
/// before calling [`add_dep`] to pre-validate the addition.
///
/// # Errors
/// - Returns an error only on unexpected graph traversal failures.
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::{load_index, detect_cycle};
/// use std::path::Path;
///
/// let mana_dir = Path::new("/project/.mana");
/// let index = load_index(mana_dir).unwrap();
/// if detect_cycle(&index, "3", "1").unwrap() {
/// eprintln!("Cannot add that dependency — would create a cycle");
/// }
/// ```
// ---------------------------------------------------------------------------
// Mutation functions
// ---------------------------------------------------------------------------
/// Create a new unit.
///
/// Assigns the next sequential ID (or child ID if `params.parent` is set),
/// writes the unit file, and rebuilds the index.
///
/// # Errors
/// - [`anyhow::Error`] — validation failure, I/O error, or hook rejection
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::create_unit;
/// use mana_core::ops::create::CreateParams;
/// use std::path::Path;
///
/// let result = create_unit(Path::new("/project/.mana"), CreateParams {
/// title: "Fix the login bug".to_string(),
/// verify: Some("cargo test --test login".to_string()),
/// ..Default::default()
/// }).unwrap();
/// println!("Created unit {}", result.unit.id);
/// ```
/// Update a unit's fields.
///
/// Only fields set to `Some(...)` are updated. Notes are appended with
/// a timestamp separator rather than replaced.
///
/// # Errors
/// - [`anyhow::Error`] — unit not found, validation failure, or hook rejection
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::update_unit;
/// use mana_core::ops::update::UpdateParams;
/// use std::path::Path;
///
/// let result = update_unit(Path::new("/project/.mana"), "1", UpdateParams {
/// notes: Some("Discovered the root cause: off-by-one in pagination".to_string()),
/// ..Default::default()
/// }).unwrap();
/// ```
/// Move a unit under a new parent, or detach it to the root.
/// Close a unit — run verify, archive, and cascade to parents.
///
/// The full close lifecycle:
/// 1. Pre-close hook (if configured)
/// 2. Run verify command (unless `opts.force` is true)
/// 3. Worktree merge (if in worktree mode)
/// 4. Feature gate (feature units require manual confirmation)
/// 5. Mark closed and archive
/// 6. Post-close hook and on_close actions
/// 7. Auto-close parents whose children are all done
///
/// Returns a [`close::CloseOutcome`] that describes what happened — the unit
/// may have been closed, verify may have failed, or the close may have been
/// blocked by a hook or feature gate.
///
/// # Errors
/// - [`anyhow::Error`] — unit not found or unexpected I/O failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::close_unit;
/// use mana_core::ops::close::{CloseOpts, CloseOutcome};
/// use std::path::Path;
///
/// let outcome = close_unit(Path::new("/project/.mana"), "1", CloseOpts {
/// reason: Some("Implemented and tested".to_string()),
/// force: false,
/// defer_verify: false,
/// }).unwrap();
///
/// match outcome {
/// CloseOutcome::Closed(r) => println!("Closed! Auto-closed parents: {:?}", r.auto_closed_parents),
/// CloseOutcome::VerifyFailed(r) => eprintln!("Verify failed: {}", r.output),
/// _ => {}
/// }
/// ```
/// Mark a unit as explicitly failed without closing it.
///
/// Releases the claim, finalizes the current attempt as `Failed`, appends a
/// structured failure summary to notes, and returns the unit to `Open` status
/// for retry.
///
/// # Errors
/// - [`anyhow::Error`] — unit not found or I/O failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::fail_unit;
/// use std::path::Path;
///
/// let unit = fail_unit(Path::new("/project/.mana"), "1",
/// Some("Blocked by missing auth token".to_string())).unwrap();
/// assert_eq!(unit.status, mana_core::api::Status::Open);
/// ```
/// Delete a unit and remove all references to it from other units' dependencies.
///
/// # Errors
/// - [`anyhow::Error`] — unit not found or I/O failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::delete_unit;
/// use std::path::Path;
///
/// let r = delete_unit(Path::new("/project/.mana"), "1").unwrap();
/// println!("Deleted: {}", r.title);
/// ```
/// Reopen a closed unit.
///
/// Sets status back to `Open`, clears `closed_at` and `close_reason`,
/// and rebuilds the index.
///
/// # Errors
/// - [`anyhow::Error`] — unit not found or I/O failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::reopen_unit;
/// use std::path::Path;
///
/// let r = reopen_unit(Path::new("/project/.mana"), "1").unwrap();
/// println!("Reopened: {}", r.unit.id);
/// ```
/// Claim a unit for work.
///
/// Sets status to `InProgress`, records who claimed it and when, and starts
/// a new attempt in the attempt log.
///
/// If `params.force` is false and the unit has a verify command with
/// `fail_first: true`, the verify command is run first. If it already passes,
/// the claim is rejected (nothing to do). This enforces fail-first/TDD semantics.
/// Any claimed unit with a verify command also records a checkpoint SHA so
/// later diff/review/close flows can compare against the claim baseline.
///
/// # Errors
/// - [`anyhow::Error`] — unit not found, not open, or verify pre-check failed
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::claim_unit;
/// use mana_core::ops::claim::ClaimParams;
/// use std::path::Path;
///
/// let r = claim_unit(Path::new("/project/.mana"), "1", ClaimParams {
/// by: Some("agent-42".to_string()),
/// force: true,
/// }).unwrap();
/// println!("Claimed by: {}", r.claimer);
/// ```
/// Release a claim on a unit.
///
/// Clears `claimed_by`/`claimed_at`, sets status back to `Open`, and marks
/// the current attempt as `Abandoned`.
///
/// # Errors
/// - [`anyhow::Error`] — unit not found or I/O failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::release_unit;
/// use std::path::Path;
///
/// let r = release_unit(Path::new("/project/.mana"), "1").unwrap();
/// assert_eq!(r.unit.status, mana_core::api::Status::Open);
/// ```
/// Add a dependency: `from_id` depends on `dep_id`.
///
/// Validates both units exist, checks for self-dependency, detects cycles,
/// and persists the change.
///
/// # Errors
/// - [`anyhow::Error`] — unit not found, self-dependency, or cycle detected
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::add_dep;
/// use std::path::Path;
///
/// // Unit 3 now depends on unit 2
/// add_dep(Path::new("/project/.mana"), "3", "2").unwrap();
/// ```
/// Remove a dependency: `from_id` no longer depends on `dep_id`.
///
/// # Errors
/// - [`anyhow::Error`] — unit not found or dependency not present
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::remove_dep;
/// use std::path::Path;
///
/// remove_dep(Path::new("/project/.mana"), "3", "2").unwrap();
/// ```
// ---------------------------------------------------------------------------
// Orchestration functions
// ---------------------------------------------------------------------------
/// Compute which units are ready to dispatch.
///
/// Returns a [`ReadyQueue`] with units sorted by priority then critical-path
/// weight (units blocking the most downstream work come first).
///
/// Optionally filters to a specific unit ID or its ready children if
/// `filter_id` is a parent unit.
///
/// Set `simulate = true` to include all open units with verify commands,
/// even those whose dependencies are not yet met. This is the dry-run mode.
///
/// # Errors
/// - [`anyhow::Error`] — index or I/O failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::compute_ready_queue;
/// use std::path::Path;
///
/// let queue = compute_ready_queue(Path::new("/project/.mana"), None, false).unwrap();
/// for unit in &queue.units {
/// println!("Ready: {} (weight={})", unit.id, unit.critical_path_weight);
/// }
/// println!("Blocked: {}", queue.blocked.len());
/// ```
/// Compute a ready queue for a canonical run target.
/// Assemble the full agent context for a unit.
///
/// Loads the unit, resolves dependency context (which sibling units produce
/// artifacts this unit requires), reads referenced files, and extracts
/// structural summaries. Returns a structured [`AgentContext`] ready for
/// rendering into any format (text prompt, JSON, IPC message).
///
/// # Errors
/// - [`anyhow::Error`] — unit not found or I/O failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::assemble_context;
/// use std::path::Path;
///
/// let ctx = assemble_context(Path::new("/project/.mana"), "1").unwrap();
/// println!("Rules: {:?}", ctx.rules.is_some());
/// println!("Files: {}", ctx.files.len());
/// println!("Dep providers: {}", ctx.dep_providers.len());
/// ```
/// Record a verify attempt result on a unit.
///
/// Appends an [`AttemptRecord`] to the unit's `attempt_log` and persists.
/// Use this when an external orchestrator completes a verify cycle and wants
/// to record the outcome without going through the full close lifecycle.
///
/// # Errors
/// - [`anyhow::Error`] — unit not found or I/O failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::{record_attempt, AttemptRecord, AttemptOutcome};
/// use std::path::Path;
/// use chrono::Utc;
///
/// let now = Utc::now();
/// let attempt = AttemptRecord {
/// num: 1,
/// outcome: AttemptOutcome::Success,
/// notes: Some("Passed on first attempt".to_string()),
/// agent: Some("imp-agent".to_string()),
/// started_at: Some(now),
/// finished_at: Some(now),
/// autonomy_observation: None,
/// };
/// record_attempt(Path::new("/project/.mana"), "1", attempt).unwrap();
/// ```
/// Run the verify command for a unit without closing it.
///
/// Loads the unit, resolves the effective timeout (unit override → config default),
/// spawns the verify command in a subprocess, and captures all output.
///
/// Returns `Ok(None)` if the unit has no verify command.
///
/// # Errors
/// - [`anyhow::Error`] — unit not found, spawn failure, or I/O error
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::run_verify;
/// use std::path::Path;
///
/// match run_verify(Path::new("/project/.mana"), "1").unwrap() {
/// Some(result) => {
/// if result.passed {
/// println!("Verify passed (exit {:?})", result.exit_code);
/// } else {
/// eprintln!("Verify failed:\n{}", result.stderr);
/// }
/// }
/// None => println!("No verify command"),
/// }
/// ```
// ---------------------------------------------------------------------------
// Facts functions
// ---------------------------------------------------------------------------
/// Create a verified fact — a unit that encodes checked project knowledge.
///
/// Facts differ from regular units in that they:
/// - Have `unit_type = "fact"` and the `"fact"` label
/// - Require a verify command (the verification is the point)
/// - Have a TTL (default 30 days) after which they are considered stale
/// - Can reference source file paths for relevance scoring
///
/// # Errors
/// - [`anyhow::Error`] — empty verify command, validation failure, or I/O error
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::create_fact;
/// use mana_core::ops::fact::FactParams;
/// use std::path::Path;
///
/// let r = create_fact(Path::new("/project/.mana"), FactParams {
/// title: "Auth uses RS256 JWT signing".to_string(),
/// verify: "grep -q 'RS256' src/auth.rs".to_string(),
/// description: Some("JWT tokens are signed with RS256 (not HS256)".to_string()),
/// paths: Some("src/auth.rs".to_string()),
/// ttl_days: Some(90),
/// pass_ok: true,
/// }).unwrap();
/// println!("Created fact {} (stale after {:?})", r.unit_id, r.unit.stale_after);
/// ```
/// Verify all facts and report staleness and failures.
///
/// Re-runs the verify command for every unit with `unit_type = "fact"`.
/// Stale facts (past their `stale_after` date) are reported without re-running.
/// Facts that require artifacts produced by failing/stale facts are flagged as
/// "suspect" (up to depth 3 in the dependency chain).
///
/// Facts whose verify passes have their `stale_after` deadline extended.
///
/// # Errors
/// - [`anyhow::Error`] — index or I/O failure
///
/// # Example
/// ```rust,no_run
/// use mana_core::api::verify_facts;
/// use std::path::Path;
///
/// let r = verify_facts(Path::new("/project/.mana")).unwrap();
/// println!("{}/{} facts verified", r.verified_count, r.total_facts);
/// if r.failing_count > 0 {
/// println!("{} facts failing!", r.failing_count);
/// }
/// ```
/// Check the root `facts.mana` fact sheet.
// Legacy aliases removed — beans→mana rename complete.