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
use std::collections::HashMap;
use std::path::PathBuf;
use uuid::Uuid;
use crate::config::Config;
use crate::error::{Error, Result};
use crate::project::{BOOKS_DIR, ProjectLayout};
use crate::store::Store;
use crate::store::node::{Node, NodeKind};
/// In-memory snapshot of every node in the project, loaded from bdslib via
/// `list_metadata()`. Cheap at literary scale (hundreds of nodes).
pub struct Hierarchy {
by_id: HashMap<Uuid, Node>,
/// Sorted by (depth, order) so iteration and printing stay stable.
order: Vec<Uuid>,
}
impl Default for Hierarchy {
fn default() -> Self {
Self {
by_id: HashMap::new(),
order: Vec::new(),
}
}
}
impl Hierarchy {
pub fn load(store: &Store) -> Result<Self> {
let raw = store
.raw()
.list_metadata()
.map_err(|e| Error::Store(format!("list_metadata: {e}")))?;
let mut by_id = HashMap::with_capacity(raw.len());
for (id, value) in raw {
// Skip non-hierarchy documents (e.g. chunked bodies) — those won't
// have our schema. Don't fail the whole load if one is malformed.
if let Ok(node) = Node::from_json(id, &value) {
by_id.insert(id, node);
}
}
let mut order: Vec<Uuid> = by_id.keys().copied().collect();
order.sort_by_key(|id| {
let n = &by_id[id];
(n.path.len(), n.order, n.slug.clone())
});
Ok(Self { by_id, order })
}
pub fn is_empty(&self) -> bool {
self.by_id.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = &Node> {
self.order.iter().map(move |id| &self.by_id[id])
}
pub fn get(&self, id: Uuid) -> Option<&Node> {
self.by_id.get(&id)
}
pub fn children_of(&self, parent_id: Option<Uuid>) -> Vec<&Node> {
let mut out: Vec<&Node> = self
.iter()
.filter(|n| n.parent_id == parent_id)
.collect();
out.sort_by_key(|n| n.order);
out
}
/// Depth-first flatten in display order. Each entry is `(node, depth)`
/// where root books have depth 0.
pub fn flatten(&self) -> Vec<(&Node, usize)> {
let mut out: Vec<(&Node, usize)> = Vec::new();
for root in self.children_of(None) {
self.walk_into(root, 0, &mut out);
}
out
}
/// Same as `flatten`, but the children of any node whose id is in
/// `collapsed` are hidden. The collapsed nodes themselves are still
/// present in the output — they just don't expand into their subtree.
pub fn flatten_with_collapsed(
&self,
collapsed: &std::collections::HashSet<Uuid>,
) -> Vec<(&Node, usize)> {
let mut out: Vec<(&Node, usize)> = Vec::new();
for root in self.children_of(None) {
self.walk_into_collapsed(root, 0, collapsed, &mut out);
}
out
}
fn walk_into<'a>(&'a self, node: &'a Node, depth: usize, out: &mut Vec<(&'a Node, usize)>) {
out.push((node, depth));
for child in self.children_of(Some(node.id)) {
self.walk_into(child, depth + 1, out);
}
}
fn walk_into_collapsed<'a>(
&'a self,
node: &'a Node,
depth: usize,
collapsed: &std::collections::HashSet<Uuid>,
out: &mut Vec<(&'a Node, usize)>,
) {
out.push((node, depth));
if collapsed.contains(&node.id) {
return;
}
for child in self.children_of(Some(node.id)) {
self.walk_into_collapsed(child, depth + 1, collapsed, out);
}
}
/// True when `node_id` has at least one child in the hierarchy.
pub fn has_children(&self, node_id: Uuid) -> bool {
!self.children_of(Some(node_id)).is_empty()
}
pub fn next_order(&self, parent_id: Option<Uuid>) -> u32 {
self.children_of(parent_id)
.iter()
.map(|n| n.order)
.max()
.map(|m| m + 1)
.unwrap_or(1)
}
/// Walk up from `start` and return the nearest node (including `start`
/// itself) whose kind permits `child_kind` as a direct child under `cfg`.
/// Returns `Ok(None)` when `child_kind` is `Book` (no parent needed).
pub fn pick_parent_for(
&self,
cfg: &Config,
start: Option<Uuid>,
child_kind: NodeKind,
) -> Result<Option<&Node>> {
if child_kind == NodeKind::Book {
return Ok(None);
}
let mut current = start;
while let Some(id) = current {
let node = self
.get(id)
.ok_or_else(|| Error::Store(format!("hierarchy missing node {id}")))?;
if self
.validate_placement(cfg, Some(node), child_kind)
.is_ok()
{
return Ok(Some(node));
}
current = node.parent_id;
}
Err(Error::Store(format!(
"no ancestor accepts a {} as a child",
child_kind.as_str()
)))
}
/// IDs of `root` and all its descendants, in pre-order. Use for deletion.
pub fn collect_subtree(&self, root: Uuid) -> Vec<Uuid> {
let mut out = Vec::new();
self.walk_ids(root, &mut out);
out
}
fn walk_ids(&self, node_id: Uuid, out: &mut Vec<Uuid>) {
if !self.by_id.contains_key(&node_id) {
return;
}
out.push(node_id);
for child in self.children_of(Some(node_id)) {
self.walk_ids(child.id, out);
}
}
/// Walk a slash-separated slug path (relative to `books/`) and return the
/// node it identifies. Paragraphs cannot appear as intermediate segments.
pub fn find_by_path(&self, path: &str) -> Option<&Node> {
let segments: Vec<&str> = path
.split('/')
.map(str::trim)
.filter(|s| !s.is_empty())
.collect();
if segments.is_empty() {
return None;
}
let mut current_parent: Option<Uuid> = None;
let mut current: Option<&Node> = None;
for seg in segments {
let next = self
.children_of(current_parent)
.into_iter()
.find(|n| n.slug == seg)?;
current_parent = Some(next.id);
current = Some(next);
}
current
}
/// Filesystem path for a node, walking its ancestor chain to reconstruct
/// the correct `NN-slug` prefixes.
pub fn fs_path(&self, node: &Node, _layout: &ProjectLayout) -> PathBuf {
let mut p = PathBuf::from(BOOKS_DIR);
for ancestor in self.ancestors(node) {
p.push(ancestor.fs_name());
}
p.push(node.fs_name());
p
}
/// Ancestors from the root book down to (but not including) `node`.
pub fn ancestors(&self, node: &Node) -> Vec<&Node> {
let mut chain: Vec<&Node> = Vec::new();
let mut cur = node.parent_id;
while let Some(id) = cur {
if let Some(parent) = self.by_id.get(&id) {
chain.push(parent);
cur = parent.parent_id;
} else {
break;
}
}
chain.reverse();
chain
}
/// Slash-separated slug path used in CLI args (e.g. `my-book/01-chapter`).
pub fn slug_path(&self, node: &Node) -> String {
let mut parts: Vec<&str> = self
.ancestors(node)
.into_iter()
.map(|n| n.slug.as_str())
.collect();
parts.push(&node.slug);
parts.join("/")
}
/// Validate that `child_kind` may be placed under `parent`.
///
/// Default config (unbounded_subchapters = false):
/// books → chapter, paragraph, image
/// chapter → subchapter, paragraph, image
/// subchapter → paragraph, image
///
/// Images sit wherever paragraphs sit — first-class leaves
/// alongside prose. The wrap_image_* function picked by the
/// assembler depends on the Image's parent kind (book art /
/// chapter art / subchapter art).
///
/// With unbounded_subchapters = true, subchapter → subchapter is also OK.
pub fn validate_placement(
&self,
cfg: &Config,
parent: Option<&Node>,
child_kind: NodeKind,
) -> Result<()> {
// 1.2.13+ Phase D.1 / hotfix — per-language sub-
// books are nested Books under the `Language`
// system book. The general "Book under any
// parent is disallowed" rule pre-dates the
// Language system book and silently broke every
// scaffold attempt (CLI `inkhaven language init`
// included) — this special case allows
// Book → Book ONLY when the parent carries
// `system_tag == "language"`.
let parent_is_language_root = parent
.and_then(|p| p.system_tag.as_deref())
== Some(crate::store::SYSTEM_TAG_LANGUAGES);
let allowed = match (parent.map(|p| p.kind), child_kind) {
(None, NodeKind::Book) => true,
(None, _) => false,
(Some(NodeKind::Book), NodeKind::Book) => parent_is_language_root,
(Some(_), NodeKind::Book) => false,
(Some(NodeKind::Book), NodeKind::Chapter) => true,
(Some(NodeKind::Book), NodeKind::Paragraph) => true,
(Some(NodeKind::Book), NodeKind::Image) => true,
(Some(NodeKind::Book), NodeKind::Script) => true,
(Some(NodeKind::Chapter), NodeKind::Subchapter) => true,
(Some(NodeKind::Chapter), NodeKind::Paragraph) => true,
(Some(NodeKind::Chapter), NodeKind::Image) => true,
(Some(NodeKind::Chapter), NodeKind::Script) => true,
(Some(NodeKind::Subchapter), NodeKind::Paragraph) => true,
(Some(NodeKind::Subchapter), NodeKind::Image) => true,
(Some(NodeKind::Subchapter), NodeKind::Script) => true,
(Some(NodeKind::Subchapter), NodeKind::Subchapter) => {
cfg.hierarchy.unbounded_subchapters
}
_ => false,
};
if allowed {
Ok(())
} else {
let parent_desc = parent
.map(|p| format!("a {}", p.kind.as_str()))
.unwrap_or_else(|| "the root".into());
Err(Error::Store(format!(
"{} cannot be placed under {}",
child_kind.as_str(),
parent_desc
)))
}
}
}
#[cfg(test)]
mod placement_tests {
use super::*;
use uuid::Uuid;
/// Minimal Book Node for placement tests. Skips the
/// every-field expansion `make_event_node` does — only
/// the fields validate_placement reads (kind +
/// system_tag) need to be set; the rest fall through to
/// reasonable defaults via the Node struct's Serde
/// defaults (we use serde_json round-trip to avoid
/// listing every field manually).
fn book(system_tag: Option<&str>) -> Node {
let raw = serde_json::json!({
"id": Uuid::nil(),
"kind": "book",
"title": "test",
"slug": "test",
"path": [],
"parent_id": null,
"order": 0,
"file": null,
"modified_at": "2026-01-01T00:00:00Z",
"system_tag": system_tag,
});
serde_json::from_value(raw).expect("test node deserialises")
}
/// 1.2.13+ hotfix — Book-under-Book is allowed ONLY
/// when the parent is the Language system book. This
/// is the special case that makes
/// `inkhaven language init` work; the general rule
/// against nested Books still applies for every other
/// parent (Notes, Places, user books, etc.).
#[test]
fn book_under_language_system_book_is_allowed() {
let cfg = Config::default();
let h = Hierarchy::default();
let parent = book(Some(crate::store::SYSTEM_TAG_LANGUAGES));
assert!(
h.validate_placement(&cfg, Some(&parent), NodeKind::Book).is_ok(),
"Book child under Language system book should be allowed (language sub-book)"
);
}
#[test]
fn book_under_regular_book_is_rejected() {
let cfg = Config::default();
let h = Hierarchy::default();
let parent = book(None);
assert!(
h.validate_placement(&cfg, Some(&parent), NodeKind::Book).is_err(),
"Book child under a non-system Book parent should still be rejected"
);
}
#[test]
fn book_under_non_language_system_book_is_rejected() {
let cfg = Config::default();
let h = Hierarchy::default();
// Notes is a system book, but it's not Language —
// the special case must NOT generalise to every
// system book.
let parent = book(Some(crate::store::SYSTEM_TAG_NOTES));
assert!(
h.validate_placement(&cfg, Some(&parent), NodeKind::Book).is_err(),
"Book child under Notes (a non-Language system book) should still be rejected"
);
}
}