1use crate::engine::Engine;
21use crate::entity::MetadataValue;
22use crate::workspace::MountCapability;
23
24pub const DEFAULT_DUE_WINDOW: &str = "90d";
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum DueWindow {
32 Days(u32),
33 Months(u32),
34 Years(u32),
35}
36
37pub fn parse_due_window(input: &str) -> Result<DueWindow, String> {
41 let err = || {
42 format!(
43 "invalid window {input:?}: expected <N>d (days), <N>m (months), or <N>y (years) — \
44 e.g. 90d, 6m, 2y"
45 )
46 };
47 let (num, unit) = input.split_at(input.len().saturating_sub(1));
48 let n: u32 = num.parse().map_err(|_| err())?;
49 match unit {
50 "d" => Ok(DueWindow::Days(n)),
51 "m" => Ok(DueWindow::Months(n)),
52 "y" => Ok(DueWindow::Years(n)),
53 _ => Err(err()),
54 }
55}
56
57pub fn pinned_days_since_epoch(s: &str) -> Option<u64> {
65 let (y, m, d) = parse_ymd(s)?;
66 u64::try_from(days_from_civil(y, m, d)).ok()
67}
68
69fn parse_ymd(s: &str) -> Option<(i64, u32, u32)> {
70 let mut it = s.splitn(3, '-');
71 let y: i64 = it.next()?.parse().ok()?;
72 let m: u32 = it.next()?.parse().ok()?;
73 let d: u32 = it
74 .next()?
75 .get(..2)
76 .unwrap_or(it.next().unwrap_or(""))
77 .parse()
78 .ok()?;
79 if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
80 return None;
81 }
82 Some((y, m, d))
83}
84
85fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
86 let y = if m <= 2 { y - 1 } else { y };
87 let era = if y >= 0 { y } else { y - 399 } / 400;
88 let yoe = y - era * 400;
89 let mp = ((m + 9) % 12) as i64;
90 let doy = (153 * mp + 2) / 5 + d as i64 - 1;
91 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
92 era * 146097 + doe - 719468
93}
94
95fn civil_from_days(z: i64) -> (i64, u32, u32) {
96 let z = z + 719468;
97 let era = if z >= 0 { z } else { z - 146096 } / 146097;
98 let doe = z - era * 146097;
99 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
100 let y = yoe + era * 400;
101 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
102 let mp = (5 * doy + 2) / 153;
103 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
104 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
105 (if m <= 2 { y + 1 } else { y }, m, d)
106}
107
108pub fn civil_from_days_pub(days_since_epoch: i64) -> (i64, u32, u32) {
111 civil_from_days(days_since_epoch)
112}
113
114fn last_day_of_month(y: i64, m: u32) -> u32 {
115 match m {
116 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
117 4 | 6 | 9 | 11 => 30,
118 _ => {
119 if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 {
120 29
121 } else {
122 28
123 }
124 }
125 }
126}
127
128fn window_end(today: (i64, u32, u32), window: &DueWindow) -> String {
131 let (y, m, d) = today;
132 let (ey, em, ed) = match window {
133 DueWindow::Days(n) => civil_from_days(days_from_civil(y, m, d) + *n as i64),
134 DueWindow::Months(n) => {
135 let total = (y * 12 + (m as i64 - 1)) + *n as i64;
136 let ny = total.div_euclid(12);
137 let nm = (total.rem_euclid(12) + 1) as u32;
138 (ny, nm, d.min(last_day_of_month(ny, nm)))
139 }
140 DueWindow::Years(n) => {
141 let ny = y + *n as i64;
142 (ny, m, d.min(last_day_of_month(ny, m)))
143 }
144 };
145 format!("{ey:04}-{em:02}-{ed:02}")
146}
147
148struct DueEntry {
150 mem: String,
151 third_party: bool,
152 id: String,
153 title: String,
154 date: String,
155 status: String,
156 lead: Option<(String, String)>,
157 overdue: bool,
158 days_until: i64,
160}
161
162#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
167pub struct DueRow {
168 pub mem: String,
169 pub id: String,
170 pub title: String,
171 pub date: String,
172 pub status: String,
173 #[serde(skip_serializing_if = "std::ops::Not::not")]
174 pub third_party: bool,
175 #[serde(skip_serializing_if = "Option::is_none")]
177 pub days_past: Option<u32>,
178 #[serde(skip_serializing_if = "Option::is_none")]
180 pub days_until: Option<u32>,
181 #[serde(skip_serializing_if = "Option::is_none")]
183 pub lead: Option<DueLead>,
184}
185
186#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
187pub struct DueLead {
188 pub section: String,
189 pub body: String,
190}
191
192#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
195pub struct DueBrief {
196 pub today: String,
197 pub through: String,
198 pub mems: Vec<String>,
200 pub overdue: Vec<DueRow>,
201 pub due_soon: Vec<DueRow>,
202}
203
204impl Engine {
205 pub fn render_due_brief(
213 &self,
214 today: &str,
215 window: &DueWindow,
216 mem_filter: Option<&str>,
217 ) -> Result<String, String> {
218 let (today_iso, end, declaring_mems, entries) =
219 self.collect_due(today, window, mem_filter)?;
220 Ok(render_due_entries(
221 &today_iso,
222 &end,
223 window,
224 &declaring_mems,
225 &entries,
226 ))
227 }
228
229 pub fn due_brief(
235 &self,
236 today: &str,
237 window: &DueWindow,
238 mem_filter: Option<&str>,
239 ) -> Result<DueBrief, String> {
240 let (today_iso, end, mems, entries) = self.collect_due(today, window, mem_filter)?;
241 let row = |e: &DueEntry| DueRow {
242 mem: e.mem.clone(),
243 id: e.id.clone(),
244 title: e.title.clone(),
245 date: e.date.clone(),
246 status: e.status.clone(),
247 third_party: e.third_party,
248 days_past: e.overdue.then_some((-e.days_until) as u32),
249 days_until: (!e.overdue).then_some(e.days_until as u32),
250 lead: e.lead.as_ref().map(|(section, body)| DueLead {
251 section: section.clone(),
252 body: body.clone(),
253 }),
254 };
255 Ok(DueBrief {
256 today: today_iso,
257 through: end,
258 mems,
259 overdue: entries.iter().filter(|e| e.overdue).map(row).collect(),
260 due_soon: entries.iter().filter(|e| !e.overdue).map(row).collect(),
261 })
262 }
263
264 #[allow(clippy::type_complexity)]
265 fn collect_due(
266 &self,
267 today: &str,
268 window: &DueWindow,
269 mem_filter: Option<&str>,
270 ) -> Result<(String, String, Vec<String>, Vec<DueEntry>), String> {
271 let today_ymd = parse_ymd(today)
272 .ok_or_else(|| format!("invalid date {today:?}: expected YYYY-MM-DD"))?;
273 let today_iso = format!("{:04}-{:02}-{:02}", today_ymd.0, today_ymd.1, today_ymd.2);
274 let today_days = days_from_civil(today_ymd.0, today_ymd.1, today_ymd.2);
275 let end = window_end(today_ymd, window);
276
277 let mut entries: Vec<DueEntry> = Vec::new();
281 let mut declaring_mems: Vec<String> = Vec::new();
282 for mounted in &self.mounts {
283 let mem = mounted.mount.mem.as_str();
284 if let Some(filter) = mem_filter
285 && mem != filter
286 {
287 continue;
288 }
289 let Some(schema) = self.schemas.get(mem) else {
290 continue;
291 };
292 let declares = schema.types.values().any(|t| t.due.is_some());
293 if !declares {
294 continue;
295 }
296 declaring_mems.push(mem.to_string());
297 let third_party = mounted.mount.capability == MountCapability::ReadOnly;
298 for entity in self.store.all_entities() {
299 if entity.mem != mem || entity.stub {
300 continue;
301 }
302 let Some(td) = schema.types.get(&entity.entity_type) else {
303 continue;
304 };
305 let Some(due) = &td.due else { continue };
306 let status = match entity.metadata.get(&due.status_field) {
307 Some(MetadataValue::String(s)) => s.clone(),
308 _ => continue,
309 };
310 if !due.open_values.contains(&status) {
311 continue;
312 }
313 if let Some(gate) = &due.unless_open_via {
316 let neighbours: Vec<&crate::EntityId> = match gate.direction {
317 memstead_schema::ReachDirection::In => self
318 .store
319 .incoming(&entity.id)
320 .iter()
321 .filter(|e| gate.relationships.contains(&e.rel_type))
322 .map(|e| &e.from)
323 .collect(),
324 memstead_schema::ReachDirection::Out => self
325 .store
326 .outgoing(&entity.id)
327 .iter()
328 .filter(|e| gate.relationships.contains(&e.rel_type))
329 .map(|e| &e.target)
330 .collect(),
331 };
332 let blocked = neighbours.iter().any(|n| {
333 self.store.get(n).is_some_and(|other| {
334 matches!(
335 other.metadata.get(&gate.status_field),
336 Some(MetadataValue::String(v)) if gate.open_values.contains(v)
337 )
338 })
339 });
340 if blocked {
341 continue;
342 }
343 }
344 let date = match entity.metadata.get(&due.date_field) {
345 Some(MetadataValue::String(s)) => s.clone(),
346 _ => continue,
347 };
348 let base_part = date.get(..10).unwrap_or(&date).to_string();
353 let Some((by, bm, bd)) = parse_ymd(&base_part) else {
354 continue;
355 };
356 let due_days = days_from_civil(by, bm, bd) + due.offset_days as i64;
357 let (dy, dm, dd) = civil_from_days(due_days);
358 let date_part = format!("{dy:04}-{dm:02}-{dd:02}");
359 if date_part.as_str() > end.as_str() {
360 continue;
361 }
362 let days_until = due_days - today_days;
363 let lead = due.lead_section.as_ref().and_then(|key| {
364 entity
365 .sections
366 .get(key)
367 .filter(|body| !body.trim().is_empty())
368 .map(|body| (key.clone(), body.trim().to_string()))
369 });
370 entries.push(DueEntry {
371 mem: mem.to_string(),
372 third_party,
373 id: entity.id.to_string(),
374 title: entity.title.clone(),
375 date: date_part.clone(),
376 status,
377 lead,
378 overdue: date_part.as_str() < today_iso.as_str(),
379 days_until,
380 });
381 }
382 }
383
384 entries.sort_by(|a, b| {
387 b.overdue
388 .cmp(&a.overdue)
389 .then_with(|| a.date.cmp(&b.date))
390 .then_with(|| a.id.cmp(&b.id))
391 });
392 declaring_mems.sort();
393 declaring_mems.dedup();
394 Ok((today_iso, end, declaring_mems, entries))
395 }
396}
397
398fn render_due_entries(
399 today_iso: &str,
400 end: &str,
401 window: &DueWindow,
402 declaring_mems: &[String],
403 entries: &[DueEntry],
404) -> String {
405 {
406 let window_label = match window {
407 DueWindow::Days(n) => format!("{n}d"),
408 DueWindow::Months(n) => format!("{n}m"),
409 DueWindow::Years(n) => format!("{n}y"),
410 };
411 let mut out = String::new();
412 out.push_str(&format!(
413 "# Due brief — {today_iso}, window {window_label} (through {end})\n\n"
414 ));
415 if declaring_mems.is_empty() {
416 out.push_str(
417 "No mounted mem's schema declares a due axis (`due:` on a type). \
418 Nothing to render.\n",
419 );
420 return out;
421 }
422 out.push_str(&format!("Mems: {}\n\n", declaring_mems.join(", ")));
423 if entries.is_empty() {
424 out.push_str("Nothing open is due in this window.\n");
425 return out;
426 }
427 let overdue_count = entries.iter().filter(|e| e.overdue).count();
428 out.push_str(&format!(
429 "{} entr{} ({} overdue)\n\n",
430 entries.len(),
431 if entries.len() == 1 { "y" } else { "ies" },
432 overdue_count
433 ));
434 for e in entries {
435 let marker = if e.overdue {
436 format!(" **OVERDUE** ({} days past)", -e.days_until)
437 } else {
438 format!(" (in {} days)", e.days_until)
439 };
440 let origin = if e.third_party { " [third-party]" } else { "" };
441 out.push_str(&format!(
442 "- `{}` — {} — **{}**{} (status: {}, mem: {}{})\n",
443 e.id, e.title, e.date, marker, e.status, e.mem, origin
444 ));
445 if let Some((key, body)) = &e.lead {
446 if e.third_party {
447 out.push_str(&format!(" - {key} (third-party, quoted):\n"));
450 for line in body.lines() {
451 out.push_str(&format!(" > {line}\n"));
452 }
453 } else {
454 out.push_str(&format!(" - {key}:\n"));
455 for line in body.lines() {
456 out.push_str(&format!(" {line}\n"));
457 }
458 }
459 }
460 }
461 out
462 }
463}
464
465#[cfg(test)]
466mod tests {
467 use super::*;
468 use std::path::Path;
469 use tempfile::TempDir;
470
471 use crate::backend::MemBackend;
472 use crate::storage::FilesystemBackend;
473 use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
474
475 fn frist_schema_dir(root: &Path) {
476 let d = root.join("schemas").join("frist-schema");
477 std::fs::create_dir_all(d.join("types")).unwrap();
478 std::fs::write(
479 d.join("schema.yaml"),
480 "name: frist\nversion: 0.1.0\ndescription: t\nwhen_to_use: due tests\ntypes:\n - obligation\n - note\nrelationships:\n mode: strict\n definitions:\n - name: PART_OF\n description: h\n default_weight: 3.0\n - name: _default\n description: d\n default_weight: 1.0\ncommunity:\n resolution: 1.0\n seed: 42\n",
481 )
482 .unwrap();
483 std::fs::write(
484 d.join("types").join("obligation.yaml"),
485 "name: obligation\ndescription: dated obligation\nwhen_to_use: due tests\nsections:\n - key: body\n heading: Body\n required: true\n search_weight: 10.0\n catch_all: true\n write_rules: []\n - key: vorlauf\n heading: Vorlauf\n search_weight: 1.0\n write_rules: []\nmetadata_fields:\n - key: faellig_am\n description: due date\n field_type: date\n required: true\n - key: status\n description: state\n field_type: string\n required: true\n default_value: offen\n enum_values: [offen, in_arbeit, erledigt]\ndue:\n date_field: faellig_am\n status_field: status\n open_values: [offen, in_arbeit]\n lead_section: vorlauf\ntitle_weight: 100.0\ntext_fields: [body]\nhierarchy_relationship: PART_OF\nno_self_loop_relationships: []\nupdatable_fields: [title, body, status, faellig_am]\nhealth_required_fields: []\nstaleness_threshold_days: 90\nwrite_rules: []\n",
486 )
487 .unwrap();
488 std::fs::write(
489 d.join("types").join("note.yaml"),
490 "name: note\ndescription: undeclared type\nwhen_to_use: due tests\nsections:\n - key: body\n heading: Body\n required: true\n search_weight: 10.0\n catch_all: true\n write_rules: []\nmetadata_fields: []\ntitle_weight: 100.0\ntext_fields: [body]\nhierarchy_relationship: PART_OF\nno_self_loop_relationships: []\nupdatable_fields: [title, body]\nhealth_required_fields: []\nstaleness_threshold_days: 90\nwrite_rules: []\n",
491 )
492 .unwrap();
493 }
494
495 fn obligation_md(title: &str, date: &str, status: &str, vorlauf: Option<&str>) -> String {
496 let lead = vorlauf
497 .map(|v| format!("\n## Vorlauf\n\n{v}\n"))
498 .unwrap_or_default();
499 format!(
500 "---\ntype: obligation\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nfaellig_am: {date}\nstatus: {status}\n---\n# {title}\n\n## Body\n\nB.\n{lead}"
501 )
502 }
503
504 fn mount_with(mem: &str, path: std::path::PathBuf, capability: MountCapability) -> Mount {
505 Mount {
506 mem: mem.to_string(),
507 schema: Some("frist@0.1.0".parse().unwrap()),
508 storage: MountStorage::Folder { path },
509 capability,
510 lifecycle: MountLifecycle::Eager,
511 cross_linkable: true,
512 migration_target: None,
513 }
514 }
515
516 #[test]
521 fn due_brief_membership_order_and_labels() {
522 let tmp = TempDir::new().unwrap();
523 frist_schema_dir(tmp.path());
524 let own = tmp.path().join("own");
525 let foreign = tmp.path().join("foreign");
526 std::fs::create_dir_all(own.join(".memstead")).unwrap();
527 std::fs::create_dir_all(foreign.join(".memstead")).unwrap();
528 for dir in [&own, &foreign] {
531 std::fs::write(
532 dir.join(".memstead/config.json"),
533 "{\n \"version\": \"1.0.0\",\n \"description\": \"due fixture\",\n \"schema\": \"frist@0.1.0\"\n}",
534 )
535 .unwrap();
536 }
537 std::fs::write(
538 own.join("wartung.md"),
539 obligation_md(
540 "Wartung",
541 "2026-09-01",
542 "offen",
543 Some("Handwerker beauftragen"),
544 ),
545 )
546 .unwrap();
547 std::fs::write(
548 own.join("frist-alt.md"),
549 obligation_md("Frist Alt", "2026-07-01", "in_arbeit", None),
550 )
551 .unwrap();
552 std::fs::write(
553 own.join("weit-weg.md"),
554 obligation_md("Weit Weg", "2027-06-01", "offen", None),
555 )
556 .unwrap();
557 std::fs::write(
558 own.join("erledigt.md"),
559 obligation_md("Erledigt", "2026-08-20", "erledigt", None),
560 )
561 .unwrap();
562 std::fs::write(
563 own.join("plain-note.md"),
564 "---\ntype: note\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\n---\n# Plain Note\n\n## Body\n\nB.\n",
565 )
566 .unwrap();
567 std::fs::write(
569 own.join("b-gleich.md"),
570 obligation_md("B Gleich", "2026-09-10", "offen", None),
571 )
572 .unwrap();
573 std::fs::write(
574 own.join("a-gleich.md"),
575 obligation_md("A Gleich", "2026-09-10", "offen", None),
576 )
577 .unwrap();
578 std::fs::write(
580 foreign.join("fremd-frist.md"),
581 obligation_md(
582 "Fremd Frist",
583 "2026-06-15",
584 "offen",
585 Some("Nur zur Kenntnis"),
586 ),
587 )
588 .unwrap();
589
590 let own_writer = FilesystemBackend::new(own.clone());
591 let foreign_writer = FilesystemBackend::new(foreign.clone());
592 let engine = Engine::from_mounts_with_schemas_dir(
593 vec![
594 (
595 mount_with("own", own, MountCapability::Write),
596 Box::new(own_writer) as Box<dyn MemBackend>,
597 ),
598 (
599 mount_with("foreign", foreign, MountCapability::ReadOnly),
600 Box::new(foreign_writer) as Box<dyn MemBackend>,
601 ),
602 ],
603 Some(&tmp.path().join("schemas")),
604 )
605 .unwrap();
606
607 let brief = engine
608 .render_due_brief("2026-08-10", &DueWindow::Days(90), None)
609 .unwrap();
610
611 for present in [
614 "own--wartung",
615 "own--frist-alt",
616 "foreign--fremd-frist",
617 "own--a-gleich",
618 "own--b-gleich",
619 ] {
620 assert!(brief.contains(present), "{present} missing:\n{brief}");
621 }
622 for absent in ["weit-weg", "erledigt", "plain-note"] {
623 assert!(!brief.contains(absent), "{absent} leaked:\n{brief}");
624 }
625
626 let pos = |needle: &str| brief.find(needle).unwrap();
629 assert!(
630 pos("foreign--fremd-frist") < pos("own--frist-alt"),
631 "{brief}"
632 );
633 assert!(pos("own--frist-alt") < pos("own--wartung"), "{brief}");
634 assert!(pos("own--wartung") < pos("own--a-gleich"), "{brief}");
635 assert!(pos("own--a-gleich") < pos("own--b-gleich"), "{brief}");
636
637 assert!(brief.contains("**2026-07-01** **OVERDUE**"), "{brief}");
639 assert!(brief.contains("Handwerker beauftragen"), "{brief}");
640 assert!(brief.contains("status: offen"), "{brief}");
641
642 assert!(brief.contains("[third-party]"), "{brief}");
644 assert!(brief.contains("vorlauf (third-party, quoted):"), "{brief}");
645 assert!(brief.contains("> Nur zur Kenntnis"), "{brief}");
646 assert!(brief.contains(" Handwerker beauftragen"), "{brief}");
648
649 let again = engine
651 .render_due_brief("2026-08-10", &DueWindow::Days(90), None)
652 .unwrap();
653 assert_eq!(brief, again);
654
655 let own_only = engine
657 .render_due_brief("2026-08-10", &DueWindow::Days(90), Some("own"))
658 .unwrap();
659 assert!(!own_only.contains("foreign--fremd-frist"), "{own_only}");
660 assert!(own_only.contains("own--wartung"), "{own_only}");
661 }
662
663 #[test]
665 fn window_parse_and_calendar_math() {
666 assert_eq!(parse_due_window("90d").unwrap(), DueWindow::Days(90));
667 assert_eq!(parse_due_window("6m").unwrap(), DueWindow::Months(6));
668 assert_eq!(parse_due_window("2y").unwrap(), DueWindow::Years(2));
669 for bad in ["", "d", "90", "90w", "-1d", "1.5m"] {
670 let err = parse_due_window(bad).unwrap_err();
671 assert!(err.contains("<N>d"), "error names accepted forms: {err}");
672 }
673 assert_eq!(
675 window_end((2026, 1, 31), &DueWindow::Months(1)),
676 "2026-02-28"
677 );
678 assert_eq!(
679 window_end((2024, 1, 31), &DueWindow::Months(1)),
680 "2024-02-29"
681 );
682 assert_eq!(
683 window_end((2026, 8, 10), &DueWindow::Days(90)),
684 "2026-11-08"
685 );
686 assert_eq!(
687 window_end((2026, 11, 15), &DueWindow::Months(2)),
688 "2027-01-15"
689 );
690 assert_eq!(
691 window_end((2024, 2, 29), &DueWindow::Years(1)),
692 "2025-02-28"
693 );
694 }
695
696 #[test]
699 fn no_declaring_schema_renders_honest_empty_brief() {
700 let tmp = TempDir::new().unwrap();
701 let mem_dir = tmp.path().to_path_buf();
702 let writer = FilesystemBackend::new(mem_dir.clone());
703 let engine = Engine::from_mounts(vec![(
704 crate::engine::test_helpers::folder_mount("specs", mem_dir),
705 Box::new(writer) as Box<dyn MemBackend>,
706 )])
707 .unwrap();
708 let brief = engine
709 .render_due_brief("2026-08-10", &DueWindow::Days(90), None)
710 .unwrap();
711 assert!(
712 brief.contains("No mounted mem's schema declares a due axis"),
713 "{brief}"
714 );
715 }
716}
717
718#[cfg(test)]
719mod obligation_builtin_tests {
720 use super::*;
721 use tempfile::TempDir;
722
723 use crate::backend::MemBackend;
724 use crate::engine::test_helpers::{cli_actor, empty_create_args};
725 use crate::storage::FilesystemBackend;
726 use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
727
728 fn obligation_mount(mem: &str, path: std::path::PathBuf) -> Mount {
729 Mount {
730 mem: mem.to_string(),
731 schema: Some("obligation@0.1.0".parse().unwrap()),
732 storage: MountStorage::Folder { path },
733 capability: MountCapability::Write,
734 lifecycle: MountLifecycle::Eager,
735 cross_linkable: true,
736 migration_target: None,
737 }
738 }
739
740 fn obligation_engine(tmp: &TempDir) -> Engine {
741 let mem_dir = tmp.path().join("duties");
742 std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
743 std::fs::write(
744 mem_dir.join(".memstead/config.json"),
745 "{\n \"version\": \"1.0.0\",\n \"description\": \"obligation fixture\",\n \"schema\": \"obligation@0.1.0\"\n}",
746 )
747 .unwrap();
748 let writer = FilesystemBackend::new(mem_dir.clone());
749 Engine::from_mounts(vec![(
750 obligation_mount("duties", mem_dir),
751 Box::new(writer) as Box<dyn MemBackend>,
752 )])
753 .unwrap()
754 }
755
756 fn obligation_args(
757 mem: &str,
758 title: &str,
759 due_date: &str,
760 status: &str,
761 ) -> crate::engine::CreateEntityArgs {
762 let mut args = empty_create_args(mem, title);
763 args.entity_type = "obligation".to_string();
764 args.sections = indexmap::IndexMap::from_iter([
765 ("duty".to_string(), "Who owes what.".to_string()),
766 ("consequence".to_string(), "What forfeits.".to_string()),
767 ]);
768 args.metadata = indexmap::IndexMap::from_iter([
769 ("due_date".to_string(), due_date.to_string()),
770 ("status".to_string(), status.to_string()),
771 ]);
772 args.relations = vec![crate::ops::RelateArg {
773 target: crate::entity::EntityId::new(mem, "some-subject"),
774 rel_type: "CONCERNS".to_string(),
775 description: None,
776 }];
777 args
778 }
779
780 #[test]
785 fn shipped_obligation_schema_accepts_refuses_and_renders_due() {
786 let tmp = TempDir::new().unwrap();
787 let mut engine = obligation_engine(&tmp);
788 let (actor, client) = cli_actor();
789
790 engine
792 .create_entity(
793 obligation_args(
794 "duties",
795 "Renew Registration No. 4711 & File Proof",
796 "2026-09-01",
797 "open",
798 ),
799 actor,
800 Some(&client),
801 None,
802 )
803 .expect("conformant obligation lands");
804 engine
805 .create_entity(
806 obligation_args("duties", "Overdue Filing", "2026-07-01", "in_progress"),
807 actor,
808 Some(&client),
809 None,
810 )
811 .expect("second obligation lands");
812 engine
813 .create_entity(
814 obligation_args("duties", "Done Duty", "2026-08-01", "done"),
815 actor,
816 Some(&client),
817 None,
818 )
819 .map(|_| ())
820 .unwrap_err(); let err = engine
825 .create_entity(
826 obligation_args("duties", "Bad Status", "2026-09-01", "unknown"),
827 actor,
828 Some(&client),
829 None,
830 )
831 .unwrap_err();
832 assert_eq!(err.code(), "INVALID_ENUM_VALUE", "{err}");
833
834 let brief = engine
836 .render_due_brief("2026-08-10", &DueWindow::Days(90), None)
837 .unwrap();
838 let pos = |n: &str| brief.find(n).unwrap_or(usize::MAX);
839 assert!(brief.contains("duties--overdue-filing"), "{brief}");
840 assert!(
841 brief.contains("duties--renew-registration-no-4711-file-proof"),
842 "{brief}"
843 );
844 assert!(pos("duties--overdue-filing") < pos("duties--renew-registration-no-4711"));
845 assert!(brief.contains("**OVERDUE**"), "{brief}");
846 }
847
848 #[test]
852 fn shipped_constraints_refuse_like_the_field_schema() {
853 let tmp = TempDir::new().unwrap();
854 let mut engine = obligation_engine(&tmp);
855 let (actor, client) = cli_actor();
856
857 let err = engine
859 .create_entity(
860 obligation_args("duties", "Done Without Date", "2026-08-01", "done"),
861 actor,
862 Some(&client),
863 None,
864 )
865 .unwrap_err();
866 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED", "{err}");
867 assert!(err.to_string().contains("completed_on"), "{err}");
868
869 let mut args = obligation_args("duties", "Critical Unowned", "2026-09-01", "open");
871 args.metadata
872 .insert("criticality".to_string(), "high".to_string());
873 let err = engine
874 .create_entity(args, actor, Some(&client), None)
875 .unwrap_err();
876 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED", "{err}");
877 assert!(err.to_string().contains("responsible"), "{err}");
878
879 let mut args = obligation_args("duties", "About Nothing", "2026-09-01", "open");
881 args.relations.clear();
882 let err = engine
883 .create_entity(args, actor, Some(&client), None)
884 .unwrap_err();
885 assert!(
886 err.to_string().contains("CONCERNS") || err.code().contains("REQUIRED_OUTGOING"),
887 "required_outgoing must refuse: {err} ({})",
888 err.code()
889 );
890
891 let mut args = obligation_args("duties", "Done Properly", "2026-08-01", "done");
894 args.metadata
895 .insert("completed_on".to_string(), "2026-08-01".to_string());
896 engine
897 .create_entity(args, actor, Some(&client), None)
898 .expect("done with completed_on lands");
899 let mut args = obligation_args("duties", "Critical Owned", "2026-09-01", "open");
900 args.metadata
901 .insert("criticality".to_string(), "high".to_string());
902 args.metadata
903 .insert("responsible".to_string(), "Operations".to_string());
904 engine
905 .create_entity(args, actor, Some(&client), None)
906 .expect("high with responsible lands");
907 }
908}