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
69pub fn parse_iso_utc_seconds(s: &str) -> Option<u64> {
75 let (date, time) = match s.len() {
76 10 => (s, None),
77 20 if s.as_bytes()[10] == b'T' && s.as_bytes()[19] == b'Z' => (&s[..10], Some(&s[11..19])),
78 _ => return None,
79 };
80 let (y, m, d) = parse_ymd(date)?;
81 let last_day = match m {
82 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
83 4 | 6 | 9 | 11 => 30,
84 _ => {
85 if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 {
86 29
87 } else {
88 28
89 }
90 }
91 };
92 if d > last_day {
93 return None;
94 }
95 let days = u64::try_from(days_from_civil(y, m, d)).ok()?;
96 let secs = match time {
97 None => 0,
98 Some(t) => {
99 let mut it = t.split(':');
100 let hh: u64 = it.next()?.parse().ok()?;
101 let mm: u64 = it.next()?.parse().ok()?;
102 let ss: u64 = it.next()?.parse().ok()?;
103 if it.next().is_some() || hh > 23 || mm > 59 || ss > 60 {
104 return None;
105 }
106 hh * 3600 + mm * 60 + ss
107 }
108 };
109 Some(days * 86_400 + secs)
110}
111
112fn parse_ymd(s: &str) -> Option<(i64, u32, u32)> {
113 let mut it = s.splitn(3, '-');
114 let y: i64 = it.next()?.parse().ok()?;
115 let m: u32 = it.next()?.parse().ok()?;
116 let d: u32 = it
117 .next()?
118 .get(..2)
119 .unwrap_or(it.next().unwrap_or(""))
120 .parse()
121 .ok()?;
122 if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
123 return None;
124 }
125 Some((y, m, d))
126}
127
128fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
129 let y = if m <= 2 { y - 1 } else { y };
130 let era = if y >= 0 { y } else { y - 399 } / 400;
131 let yoe = y - era * 400;
132 let mp = ((m + 9) % 12) as i64;
133 let doy = (153 * mp + 2) / 5 + d as i64 - 1;
134 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
135 era * 146097 + doe - 719468
136}
137
138fn civil_from_days(z: i64) -> (i64, u32, u32) {
139 let z = z + 719468;
140 let era = if z >= 0 { z } else { z - 146096 } / 146097;
141 let doe = z - era * 146097;
142 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
143 let y = yoe + era * 400;
144 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
145 let mp = (5 * doy + 2) / 153;
146 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
147 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
148 (if m <= 2 { y + 1 } else { y }, m, d)
149}
150
151pub fn civil_from_days_pub(days_since_epoch: i64) -> (i64, u32, u32) {
154 civil_from_days(days_since_epoch)
155}
156
157fn last_day_of_month(y: i64, m: u32) -> u32 {
158 match m {
159 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
160 4 | 6 | 9 | 11 => 30,
161 _ => {
162 if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 {
163 29
164 } else {
165 28
166 }
167 }
168 }
169}
170
171fn window_end(today: (i64, u32, u32), window: &DueWindow) -> String {
174 let (y, m, d) = today;
175 let (ey, em, ed) = match window {
176 DueWindow::Days(n) => civil_from_days(days_from_civil(y, m, d) + *n as i64),
177 DueWindow::Months(n) => {
178 let total = (y * 12 + (m as i64 - 1)) + *n as i64;
179 let ny = total.div_euclid(12);
180 let nm = (total.rem_euclid(12) + 1) as u32;
181 (ny, nm, d.min(last_day_of_month(ny, nm)))
182 }
183 DueWindow::Years(n) => {
184 let ny = y + *n as i64;
185 (ny, m, d.min(last_day_of_month(ny, m)))
186 }
187 };
188 format!("{ey:04}-{em:02}-{ed:02}")
189}
190
191struct DueEntry {
193 mem: String,
194 third_party: bool,
195 id: String,
196 title: String,
197 date: String,
198 status: String,
199 lead: Option<(String, String)>,
200 overdue: bool,
201 days_until: i64,
203}
204
205#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
210pub struct DueRow {
211 pub mem: String,
212 pub id: String,
213 pub title: String,
214 pub date: String,
215 pub status: String,
216 #[serde(skip_serializing_if = "std::ops::Not::not")]
217 pub third_party: bool,
218 #[serde(skip_serializing_if = "Option::is_none")]
220 pub days_past: Option<u32>,
221 #[serde(skip_serializing_if = "Option::is_none")]
223 pub days_until: Option<u32>,
224 #[serde(skip_serializing_if = "Option::is_none")]
226 pub lead: Option<DueLead>,
227}
228
229#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
230pub struct DueLead {
231 pub section: String,
232 pub body: String,
233}
234
235#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
238pub struct DueBrief {
239 pub today: String,
240 pub through: String,
241 pub mems: Vec<String>,
243 pub overdue: Vec<DueRow>,
244 pub due_soon: Vec<DueRow>,
245}
246
247impl Engine {
248 pub fn render_due_brief(
256 &self,
257 today: &str,
258 window: &DueWindow,
259 mem_filter: Option<&str>,
260 ) -> Result<String, String> {
261 let (today_iso, end, declaring_mems, entries) =
262 self.collect_due(today, window, mem_filter)?;
263 Ok(render_due_entries(
264 &today_iso,
265 &end,
266 window,
267 &declaring_mems,
268 &entries,
269 ))
270 }
271
272 pub fn due_brief(
278 &self,
279 today: &str,
280 window: &DueWindow,
281 mem_filter: Option<&str>,
282 ) -> Result<DueBrief, String> {
283 let (today_iso, end, mems, entries) = self.collect_due(today, window, mem_filter)?;
284 let row = |e: &DueEntry| DueRow {
285 mem: e.mem.clone(),
286 id: e.id.clone(),
287 title: e.title.clone(),
288 date: e.date.clone(),
289 status: e.status.clone(),
290 third_party: e.third_party,
291 days_past: e.overdue.then_some((-e.days_until) as u32),
292 days_until: (!e.overdue).then_some(e.days_until as u32),
293 lead: e.lead.as_ref().map(|(section, body)| DueLead {
294 section: section.clone(),
295 body: body.clone(),
296 }),
297 };
298 Ok(DueBrief {
299 today: today_iso,
300 through: end,
301 mems,
302 overdue: entries.iter().filter(|e| e.overdue).map(row).collect(),
303 due_soon: entries.iter().filter(|e| !e.overdue).map(row).collect(),
304 })
305 }
306
307 #[allow(clippy::type_complexity)]
308 fn collect_due(
309 &self,
310 today: &str,
311 window: &DueWindow,
312 mem_filter: Option<&str>,
313 ) -> Result<(String, String, Vec<String>, Vec<DueEntry>), String> {
314 let today_ymd = parse_ymd(today)
315 .ok_or_else(|| format!("invalid date {today:?}: expected YYYY-MM-DD"))?;
316 let today_iso = format!("{:04}-{:02}-{:02}", today_ymd.0, today_ymd.1, today_ymd.2);
317 let today_days = days_from_civil(today_ymd.0, today_ymd.1, today_ymd.2);
318 let end = window_end(today_ymd, window);
319
320 let mut entries: Vec<DueEntry> = Vec::new();
324 let mut declaring_mems: Vec<String> = Vec::new();
325 for mounted in &self.mounts {
326 let mem = mounted.mount.mem.as_str();
327 if let Some(filter) = mem_filter
328 && mem != filter
329 {
330 continue;
331 }
332 let Some(schema) = self.schemas.get(mem) else {
333 continue;
334 };
335 let declares = schema.types.values().any(|t| t.due.is_some());
336 if !declares {
337 continue;
338 }
339 declaring_mems.push(mem.to_string());
340 let third_party = mounted.mount.capability == MountCapability::ReadOnly;
341 for entity in self.store.all_entities() {
342 if entity.mem != mem || entity.stub {
343 continue;
344 }
345 let Some(td) = schema.types.get(&entity.entity_type) else {
346 continue;
347 };
348 let Some(due) = &td.due else { continue };
349 let status = match entity.metadata.get(&due.status_field) {
350 Some(MetadataValue::String(s)) => s.clone(),
351 _ => continue,
352 };
353 if !due.open_values.contains(&status) {
354 continue;
355 }
356 if let Some(gate) = &due.unless_open_via {
359 let neighbours: Vec<&crate::EntityId> = match gate.direction {
360 memstead_schema::ReachDirection::In => self
361 .store
362 .incoming(&entity.id)
363 .iter()
364 .filter(|e| gate.relationships.contains(&e.rel_type))
365 .map(|e| &e.from)
366 .collect(),
367 memstead_schema::ReachDirection::Out => self
368 .store
369 .outgoing(&entity.id)
370 .iter()
371 .filter(|e| gate.relationships.contains(&e.rel_type))
372 .map(|e| &e.target)
373 .collect(),
374 };
375 let blocked = neighbours.iter().any(|n| {
376 self.store.get(n).is_some_and(|other| {
377 matches!(
378 other.metadata.get(&gate.status_field),
379 Some(MetadataValue::String(v)) if gate.open_values.contains(v)
380 )
381 })
382 });
383 if blocked {
384 continue;
385 }
386 }
387 let date = match entity.metadata.get(&due.date_field) {
388 Some(MetadataValue::String(s)) => s.clone(),
389 _ => continue,
390 };
391 let base_part = date.get(..10).unwrap_or(&date).to_string();
396 let Some((by, bm, bd)) = parse_ymd(&base_part) else {
397 continue;
398 };
399 let due_days = days_from_civil(by, bm, bd) + due.offset_days as i64;
400 let (dy, dm, dd) = civil_from_days(due_days);
401 let date_part = format!("{dy:04}-{dm:02}-{dd:02}");
402 if date_part.as_str() > end.as_str() {
403 continue;
404 }
405 let days_until = due_days - today_days;
406 let lead = due.lead_section.as_ref().and_then(|key| {
407 entity
408 .sections
409 .get(key)
410 .filter(|body| !body.trim().is_empty())
411 .map(|body| (key.clone(), body.trim().to_string()))
412 });
413 entries.push(DueEntry {
414 mem: mem.to_string(),
415 third_party,
416 id: entity.id.to_string(),
417 title: entity.title.clone(),
418 date: date_part.clone(),
419 status,
420 lead,
421 overdue: date_part.as_str() < today_iso.as_str(),
422 days_until,
423 });
424 }
425 }
426
427 entries.sort_by(|a, b| {
430 b.overdue
431 .cmp(&a.overdue)
432 .then_with(|| a.date.cmp(&b.date))
433 .then_with(|| a.id.cmp(&b.id))
434 });
435 declaring_mems.sort();
436 declaring_mems.dedup();
437 Ok((today_iso, end, declaring_mems, entries))
438 }
439}
440
441fn render_due_entries(
442 today_iso: &str,
443 end: &str,
444 window: &DueWindow,
445 declaring_mems: &[String],
446 entries: &[DueEntry],
447) -> String {
448 {
449 let window_label = match window {
450 DueWindow::Days(n) => format!("{n}d"),
451 DueWindow::Months(n) => format!("{n}m"),
452 DueWindow::Years(n) => format!("{n}y"),
453 };
454 let mut out = String::new();
455 out.push_str(&format!(
456 "# Due brief — {today_iso}, window {window_label} (through {end})\n\n"
457 ));
458 if declaring_mems.is_empty() {
459 out.push_str(
460 "No mounted mem's schema declares a due axis (`due:` on a type). \
461 Nothing to render.\n",
462 );
463 return out;
464 }
465 out.push_str(&format!("Mems: {}\n\n", declaring_mems.join(", ")));
466 if entries.is_empty() {
467 out.push_str("Nothing open is due in this window.\n");
468 return out;
469 }
470 let overdue_count = entries.iter().filter(|e| e.overdue).count();
471 out.push_str(&format!(
472 "{} entr{} ({} overdue)\n\n",
473 entries.len(),
474 if entries.len() == 1 { "y" } else { "ies" },
475 overdue_count
476 ));
477 for e in entries {
478 let marker = if e.overdue {
479 format!(" **OVERDUE** ({} days past)", -e.days_until)
480 } else {
481 format!(" (in {} days)", e.days_until)
482 };
483 let origin = if e.third_party { " [third-party]" } else { "" };
484 out.push_str(&format!(
485 "- `{}` — {} — **{}**{} (status: {}, mem: {}{})\n",
486 e.id, e.title, e.date, marker, e.status, e.mem, origin
487 ));
488 if let Some((key, body)) = &e.lead {
489 if e.third_party {
490 out.push_str(&format!(" - {key} (third-party, quoted):\n"));
493 for line in body.lines() {
494 out.push_str(&format!(" > {line}\n"));
495 }
496 } else {
497 out.push_str(&format!(" - {key}:\n"));
498 for line in body.lines() {
499 out.push_str(&format!(" {line}\n"));
500 }
501 }
502 }
503 }
504 out
505 }
506}
507
508#[cfg(test)]
509mod tests {
510 use super::*;
511 use std::path::Path;
512 use tempfile::TempDir;
513
514 use crate::backend::MemBackend;
515 use crate::storage::FilesystemBackend;
516 use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
517
518 fn frist_schema_dir(root: &Path) {
519 let d = root.join("schemas").join("frist-schema");
520 std::fs::create_dir_all(d.join("types")).unwrap();
521 std::fs::write(
522 d.join("schema.yaml"),
523 "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",
524 )
525 .unwrap();
526 std::fs::write(
527 d.join("types").join("obligation.yaml"),
528 "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",
529 )
530 .unwrap();
531 std::fs::write(
532 d.join("types").join("note.yaml"),
533 "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",
534 )
535 .unwrap();
536 }
537
538 fn obligation_md(title: &str, date: &str, status: &str, vorlauf: Option<&str>) -> String {
539 let lead = vorlauf
540 .map(|v| format!("\n## Vorlauf\n\n{v}\n"))
541 .unwrap_or_default();
542 format!(
543 "---\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}"
544 )
545 }
546
547 fn mount_with(mem: &str, path: std::path::PathBuf, capability: MountCapability) -> Mount {
548 Mount {
549 mem: mem.to_string(),
550 schema: Some("frist@0.1.0".parse().unwrap()),
551 storage: MountStorage::Folder { path },
552 capability,
553 lifecycle: MountLifecycle::Eager,
554 cross_linkable: true,
555 migration_target: None,
556 }
557 }
558
559 #[test]
564 fn due_brief_membership_order_and_labels() {
565 let tmp = TempDir::new().unwrap();
566 frist_schema_dir(tmp.path());
567 let own = tmp.path().join("own");
568 let foreign = tmp.path().join("foreign");
569 std::fs::create_dir_all(own.join(".memstead")).unwrap();
570 std::fs::create_dir_all(foreign.join(".memstead")).unwrap();
571 for dir in [&own, &foreign] {
574 std::fs::write(
575 dir.join(".memstead/config.json"),
576 "{\n \"version\": \"1.0.0\",\n \"description\": \"due fixture\",\n \"schema\": \"frist@0.1.0\"\n}",
577 )
578 .unwrap();
579 }
580 std::fs::write(
581 own.join("wartung.md"),
582 obligation_md(
583 "Wartung",
584 "2026-09-01",
585 "offen",
586 Some("Handwerker beauftragen"),
587 ),
588 )
589 .unwrap();
590 std::fs::write(
591 own.join("frist-alt.md"),
592 obligation_md("Frist Alt", "2026-07-01", "in_arbeit", None),
593 )
594 .unwrap();
595 std::fs::write(
596 own.join("weit-weg.md"),
597 obligation_md("Weit Weg", "2027-06-01", "offen", None),
598 )
599 .unwrap();
600 std::fs::write(
601 own.join("erledigt.md"),
602 obligation_md("Erledigt", "2026-08-20", "erledigt", None),
603 )
604 .unwrap();
605 std::fs::write(
606 own.join("plain-note.md"),
607 "---\ntype: note\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\n---\n# Plain Note\n\n## Body\n\nB.\n",
608 )
609 .unwrap();
610 std::fs::write(
612 own.join("b-gleich.md"),
613 obligation_md("B Gleich", "2026-09-10", "offen", None),
614 )
615 .unwrap();
616 std::fs::write(
617 own.join("a-gleich.md"),
618 obligation_md("A Gleich", "2026-09-10", "offen", None),
619 )
620 .unwrap();
621 std::fs::write(
623 foreign.join("fremd-frist.md"),
624 obligation_md(
625 "Fremd Frist",
626 "2026-06-15",
627 "offen",
628 Some("Nur zur Kenntnis"),
629 ),
630 )
631 .unwrap();
632
633 let own_writer = FilesystemBackend::new(own.clone());
634 let foreign_writer = FilesystemBackend::new(foreign.clone());
635 let engine = Engine::from_mounts_with_schemas_dir(
636 vec![
637 (
638 mount_with("own", own, MountCapability::Write),
639 Box::new(own_writer) as Box<dyn MemBackend>,
640 ),
641 (
642 mount_with("foreign", foreign, MountCapability::ReadOnly),
643 Box::new(foreign_writer) as Box<dyn MemBackend>,
644 ),
645 ],
646 Some(&tmp.path().join("schemas")),
647 )
648 .unwrap();
649
650 let brief = engine
651 .render_due_brief("2026-08-10", &DueWindow::Days(90), None)
652 .unwrap();
653
654 for present in [
657 "own--wartung",
658 "own--frist-alt",
659 "foreign--fremd-frist",
660 "own--a-gleich",
661 "own--b-gleich",
662 ] {
663 assert!(brief.contains(present), "{present} missing:\n{brief}");
664 }
665 for absent in ["weit-weg", "erledigt", "plain-note"] {
666 assert!(!brief.contains(absent), "{absent} leaked:\n{brief}");
667 }
668
669 let pos = |needle: &str| brief.find(needle).unwrap();
672 assert!(
673 pos("foreign--fremd-frist") < pos("own--frist-alt"),
674 "{brief}"
675 );
676 assert!(pos("own--frist-alt") < pos("own--wartung"), "{brief}");
677 assert!(pos("own--wartung") < pos("own--a-gleich"), "{brief}");
678 assert!(pos("own--a-gleich") < pos("own--b-gleich"), "{brief}");
679
680 assert!(brief.contains("**2026-07-01** **OVERDUE**"), "{brief}");
682 assert!(brief.contains("Handwerker beauftragen"), "{brief}");
683 assert!(brief.contains("status: offen"), "{brief}");
684
685 assert!(brief.contains("[third-party]"), "{brief}");
687 assert!(brief.contains("vorlauf (third-party, quoted):"), "{brief}");
688 assert!(brief.contains("> Nur zur Kenntnis"), "{brief}");
689 assert!(brief.contains(" Handwerker beauftragen"), "{brief}");
691
692 let again = engine
694 .render_due_brief("2026-08-10", &DueWindow::Days(90), None)
695 .unwrap();
696 assert_eq!(brief, again);
697
698 let own_only = engine
700 .render_due_brief("2026-08-10", &DueWindow::Days(90), Some("own"))
701 .unwrap();
702 assert!(!own_only.contains("foreign--fremd-frist"), "{own_only}");
703 assert!(own_only.contains("own--wartung"), "{own_only}");
704 }
705
706 #[test]
710 fn iso_utc_seconds_parse_exactly_the_two_shapes() {
711 assert_eq!(parse_iso_utc_seconds("2026-10-20"), Some(1_792_454_400));
712 assert_eq!(
713 parse_iso_utc_seconds("2026-10-20T13:45:30Z"),
714 Some(1_792_503_930)
715 );
716 assert_eq!(parse_iso_utc_seconds("2024-02-29"), Some(1_709_164_800));
717 assert_eq!(parse_iso_utc_seconds("1970-01-01T00:00:00Z"), Some(0));
718 for bad in [
719 "",
720 "2026-10-20T13:45:30",
721 "2026-10-20 13:45:30Z",
722 "2026-10-20T13:45:30.000Z",
723 "2026-13-01",
724 "2026-02-30",
725 "2023-02-29",
726 "2026-10-20T24:00:00Z",
727 "1792454400",
728 "yesterday",
729 ] {
730 assert_eq!(parse_iso_utc_seconds(bad), None, "{bad:?} must not parse");
731 }
732 }
733
734 #[test]
736 fn window_parse_and_calendar_math() {
737 assert_eq!(parse_due_window("90d").unwrap(), DueWindow::Days(90));
738 assert_eq!(parse_due_window("6m").unwrap(), DueWindow::Months(6));
739 assert_eq!(parse_due_window("2y").unwrap(), DueWindow::Years(2));
740 for bad in ["", "d", "90", "90w", "-1d", "1.5m"] {
741 let err = parse_due_window(bad).unwrap_err();
742 assert!(err.contains("<N>d"), "error names accepted forms: {err}");
743 }
744 assert_eq!(
746 window_end((2026, 1, 31), &DueWindow::Months(1)),
747 "2026-02-28"
748 );
749 assert_eq!(
750 window_end((2024, 1, 31), &DueWindow::Months(1)),
751 "2024-02-29"
752 );
753 assert_eq!(
754 window_end((2026, 8, 10), &DueWindow::Days(90)),
755 "2026-11-08"
756 );
757 assert_eq!(
758 window_end((2026, 11, 15), &DueWindow::Months(2)),
759 "2027-01-15"
760 );
761 assert_eq!(
762 window_end((2024, 2, 29), &DueWindow::Years(1)),
763 "2025-02-28"
764 );
765 }
766
767 #[test]
770 fn no_declaring_schema_renders_honest_empty_brief() {
771 let tmp = TempDir::new().unwrap();
772 let mem_dir = tmp.path().to_path_buf();
773 let writer = FilesystemBackend::new(mem_dir.clone());
774 let engine = Engine::from_mounts(vec![(
775 crate::engine::test_helpers::folder_mount("specs", mem_dir),
776 Box::new(writer) as Box<dyn MemBackend>,
777 )])
778 .unwrap();
779 let brief = engine
780 .render_due_brief("2026-08-10", &DueWindow::Days(90), None)
781 .unwrap();
782 assert!(
783 brief.contains("No mounted mem's schema declares a due axis"),
784 "{brief}"
785 );
786 }
787}
788
789#[cfg(test)]
790mod obligation_builtin_tests {
791 use super::*;
792 use tempfile::TempDir;
793
794 use crate::backend::MemBackend;
795 use crate::engine::test_helpers::{cli_actor, empty_create_args};
796 use crate::storage::FilesystemBackend;
797 use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
798
799 fn obligation_mount(mem: &str, path: std::path::PathBuf) -> Mount {
800 Mount {
801 mem: mem.to_string(),
802 schema: Some("obligation@0.1.0".parse().unwrap()),
803 storage: MountStorage::Folder { path },
804 capability: MountCapability::Write,
805 lifecycle: MountLifecycle::Eager,
806 cross_linkable: true,
807 migration_target: None,
808 }
809 }
810
811 fn obligation_engine(tmp: &TempDir) -> Engine {
812 let mem_dir = tmp.path().join("duties");
813 std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
814 std::fs::write(
815 mem_dir.join(".memstead/config.json"),
816 "{\n \"version\": \"1.0.0\",\n \"description\": \"obligation fixture\",\n \"schema\": \"obligation@0.1.0\"\n}",
817 )
818 .unwrap();
819 let writer = FilesystemBackend::new(mem_dir.clone());
820 Engine::from_mounts(vec![(
821 obligation_mount("duties", mem_dir),
822 Box::new(writer) as Box<dyn MemBackend>,
823 )])
824 .unwrap()
825 }
826
827 fn obligation_args(
828 mem: &str,
829 title: &str,
830 due_date: &str,
831 status: &str,
832 ) -> crate::engine::CreateEntityArgs {
833 let mut args = empty_create_args(mem, title);
834 args.entity_type = "obligation".to_string();
835 args.sections = indexmap::IndexMap::from_iter([
836 ("duty".to_string(), "Who owes what.".to_string()),
837 ("consequence".to_string(), "What forfeits.".to_string()),
838 ]);
839 args.metadata = indexmap::IndexMap::from_iter([
840 ("due_date".to_string(), due_date.to_string()),
841 ("status".to_string(), status.to_string()),
842 ]);
843 args.relations = vec![crate::ops::RelateArg {
844 target: crate::entity::EntityId::new(mem, "some-subject"),
845 rel_type: "CONCERNS".to_string(),
846 description: None,
847 }];
848 args
849 }
850
851 #[test]
856 fn shipped_obligation_schema_accepts_refuses_and_renders_due() {
857 let tmp = TempDir::new().unwrap();
858 let mut engine = obligation_engine(&tmp);
859 let (actor, client) = cli_actor();
860
861 engine
863 .create_entity(
864 obligation_args(
865 "duties",
866 "Renew Registration No. 4711 & File Proof",
867 "2026-09-01",
868 "open",
869 ),
870 actor,
871 Some(&client),
872 None,
873 )
874 .expect("conformant obligation lands");
875 engine
876 .create_entity(
877 obligation_args("duties", "Overdue Filing", "2026-07-01", "in_progress"),
878 actor,
879 Some(&client),
880 None,
881 )
882 .expect("second obligation lands");
883 engine
884 .create_entity(
885 obligation_args("duties", "Done Duty", "2026-08-01", "done"),
886 actor,
887 Some(&client),
888 None,
889 )
890 .map(|_| ())
891 .unwrap_err(); let err = engine
896 .create_entity(
897 obligation_args("duties", "Bad Status", "2026-09-01", "unknown"),
898 actor,
899 Some(&client),
900 None,
901 )
902 .unwrap_err();
903 assert_eq!(err.code(), "INVALID_ENUM_VALUE", "{err}");
904
905 let brief = engine
907 .render_due_brief("2026-08-10", &DueWindow::Days(90), None)
908 .unwrap();
909 let pos = |n: &str| brief.find(n).unwrap_or(usize::MAX);
910 assert!(brief.contains("duties--overdue-filing"), "{brief}");
911 assert!(
912 brief.contains("duties--renew-registration-no-4711-file-proof"),
913 "{brief}"
914 );
915 assert!(pos("duties--overdue-filing") < pos("duties--renew-registration-no-4711"));
916 assert!(brief.contains("**OVERDUE**"), "{brief}");
917 }
918
919 #[test]
923 fn shipped_constraints_refuse_like_the_field_schema() {
924 let tmp = TempDir::new().unwrap();
925 let mut engine = obligation_engine(&tmp);
926 let (actor, client) = cli_actor();
927
928 let err = engine
930 .create_entity(
931 obligation_args("duties", "Done Without Date", "2026-08-01", "done"),
932 actor,
933 Some(&client),
934 None,
935 )
936 .unwrap_err();
937 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED", "{err}");
938 assert!(err.to_string().contains("completed_on"), "{err}");
939
940 let mut args = obligation_args("duties", "Critical Unowned", "2026-09-01", "open");
942 args.metadata
943 .insert("criticality".to_string(), "high".to_string());
944 let err = engine
945 .create_entity(args, actor, Some(&client), None)
946 .unwrap_err();
947 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED", "{err}");
948 assert!(err.to_string().contains("responsible"), "{err}");
949
950 let mut args = obligation_args("duties", "About Nothing", "2026-09-01", "open");
952 args.relations.clear();
953 let err = engine
954 .create_entity(args, actor, Some(&client), None)
955 .unwrap_err();
956 assert!(
957 err.to_string().contains("CONCERNS") || err.code().contains("REQUIRED_OUTGOING"),
958 "required_outgoing must refuse: {err} ({})",
959 err.code()
960 );
961
962 let mut args = obligation_args("duties", "Done Properly", "2026-08-01", "done");
965 args.metadata
966 .insert("completed_on".to_string(), "2026-08-01".to_string());
967 engine
968 .create_entity(args, actor, Some(&client), None)
969 .expect("done with completed_on lands");
970 let mut args = obligation_args("duties", "Critical Owned", "2026-09-01", "open");
971 args.metadata
972 .insert("criticality".to_string(), "high".to_string());
973 args.metadata
974 .insert("responsible".to_string(), "Operations".to_string());
975 engine
976 .create_entity(args, actor, Some(&client), None)
977 .expect("high with responsible lands");
978 }
979}