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 due_now: Option<(String, String)>,
206}
207
208#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
213pub struct DueRow {
214 pub mem: String,
215 pub id: String,
216 pub title: String,
217 pub date: String,
218 pub status: String,
219 #[serde(skip_serializing_if = "std::ops::Not::not")]
220 pub third_party: bool,
221 #[serde(skip_serializing_if = "Option::is_none")]
223 pub days_past: Option<u32>,
224 #[serde(skip_serializing_if = "Option::is_none")]
226 pub days_until: Option<u32>,
227 #[serde(skip_serializing_if = "Option::is_none")]
229 pub lead: Option<DueLead>,
230}
231
232#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
233pub struct DueLead {
234 pub section: String,
235 pub body: String,
236}
237
238#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
243pub struct DueNowRow {
244 pub mem: String,
245 pub id: String,
246 pub title: String,
247 pub status: String,
248 pub check_kind: String,
249 pub standing: String,
250 #[serde(skip_serializing_if = "std::ops::Not::not")]
251 pub third_party: bool,
252 #[serde(skip_serializing_if = "Option::is_none")]
253 pub lead: Option<DueLead>,
254}
255
256#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
259pub struct DueBrief {
260 pub today: String,
261 pub through: String,
262 pub mems: Vec<String>,
264 pub overdue: Vec<DueRow>,
265 pub due_soon: Vec<DueRow>,
266 #[serde(skip_serializing_if = "Vec::is_empty")]
269 pub due_now: Vec<DueNowRow>,
270}
271
272impl Engine {
273 pub fn render_due_brief(
281 &self,
282 today: &str,
283 window: &DueWindow,
284 mem_filter: Option<&str>,
285 ) -> Result<String, String> {
286 let (today_iso, end, declaring_mems, entries) =
287 self.collect_due(today, window, mem_filter)?;
288 Ok(render_due_entries(
289 &today_iso,
290 &end,
291 window,
292 &declaring_mems,
293 &entries,
294 ))
295 }
296
297 pub fn due_brief(
303 &self,
304 today: &str,
305 window: &DueWindow,
306 mem_filter: Option<&str>,
307 ) -> Result<DueBrief, String> {
308 let (today_iso, end, mems, entries) = self.collect_due(today, window, mem_filter)?;
309 let row = |e: &DueEntry| DueRow {
310 mem: e.mem.clone(),
311 id: e.id.clone(),
312 title: e.title.clone(),
313 date: e.date.clone(),
314 status: e.status.clone(),
315 third_party: e.third_party,
316 days_past: e.overdue.then_some((-e.days_until) as u32),
317 days_until: (!e.overdue).then_some(e.days_until as u32),
318 lead: e.lead.as_ref().map(|(section, body)| DueLead {
319 section: section.clone(),
320 body: body.clone(),
321 }),
322 };
323 Ok(DueBrief {
324 today: today_iso,
325 through: end,
326 mems,
327 overdue: entries
328 .iter()
329 .filter(|e| e.overdue && e.due_now.is_none())
330 .map(row)
331 .collect(),
332 due_soon: entries
333 .iter()
334 .filter(|e| !e.overdue && e.due_now.is_none())
335 .map(row)
336 .collect(),
337 due_now: entries
338 .iter()
339 .filter_map(|e| {
340 let (kind, standing) = e.due_now.as_ref()?;
341 Some(DueNowRow {
342 mem: e.mem.clone(),
343 id: e.id.clone(),
344 title: e.title.clone(),
345 status: e.status.clone(),
346 check_kind: kind.clone(),
347 standing: standing.clone(),
348 third_party: e.third_party,
349 lead: e.lead.as_ref().map(|(section, body)| DueLead {
350 section: section.clone(),
351 body: body.clone(),
352 }),
353 })
354 })
355 .collect(),
356 })
357 }
358
359 #[allow(clippy::type_complexity)]
360 fn collect_due(
361 &self,
362 today: &str,
363 window: &DueWindow,
364 mem_filter: Option<&str>,
365 ) -> Result<(String, String, Vec<String>, Vec<DueEntry>), String> {
366 let today_ymd = parse_ymd(today)
367 .ok_or_else(|| format!("invalid date {today:?}: expected YYYY-MM-DD"))?;
368 let today_iso = format!("{:04}-{:02}-{:02}", today_ymd.0, today_ymd.1, today_ymd.2);
369 let today_days = days_from_civil(today_ymd.0, today_ymd.1, today_ymd.2);
370 let end = window_end(today_ymd, window);
371
372 let mut entries: Vec<DueEntry> = Vec::new();
376 let mut declaring_mems: Vec<String> = Vec::new();
377 let standing_of = self.check_standing_provider();
379 for mounted in &self.mounts {
380 let mem = mounted.mount.mem.as_str();
381 if let Some(filter) = mem_filter
382 && mem != filter
383 {
384 continue;
385 }
386 let Some(schema) = self.schemas.get(mem) else {
387 continue;
388 };
389 let declares = schema.types.values().any(|t| t.due.is_some());
390 if !declares {
391 continue;
392 }
393 declaring_mems.push(mem.to_string());
394 let third_party = mounted.mount.capability == MountCapability::ReadOnly;
395 for entity in self.store.all_entities() {
396 if entity.mem != mem || entity.stub {
397 continue;
398 }
399 let Some(td) = schema.types.get(&entity.entity_type) else {
400 continue;
401 };
402 let Some(due) = &td.due else { continue };
403 let status = match entity.metadata.get(&due.status_field) {
404 Some(MetadataValue::String(s)) => s.clone(),
405 _ => continue,
406 };
407 if !due.open_values.contains(&status) {
408 continue;
409 }
410 if let Some(gate) = &due.unless_open_via {
413 let neighbours: Vec<&crate::EntityId> = match gate.direction {
414 memstead_schema::ReachDirection::In => self
415 .store
416 .incoming(&entity.id)
417 .iter()
418 .filter(|e| gate.relationships.contains(&e.rel_type))
419 .map(|e| &e.from)
420 .collect(),
421 memstead_schema::ReachDirection::Out => self
422 .store
423 .outgoing(&entity.id)
424 .iter()
425 .filter(|e| gate.relationships.contains(&e.rel_type))
426 .map(|e| &e.target)
427 .collect(),
428 };
429 let blocked = neighbours.iter().any(|n| {
430 self.store.get(n).is_some_and(|other| {
431 matches!(
432 other.metadata.get(&gate.status_field),
433 Some(MetadataValue::String(v)) if gate.open_values.contains(v)
434 )
435 })
436 });
437 if blocked {
438 continue;
439 }
440 }
441 let lead = due.lead_section.as_ref().and_then(|key| {
442 entity
443 .sections
444 .get(key)
445 .filter(|body| !body.trim().is_empty())
446 .map(|body| (key.clone(), body.trim().to_string()))
447 });
448 let base_days = if let Some(kind) = &due.check_kind {
453 let standing = standing_of(entity, kind);
454 let newest = standing
455 .confirms()
456 .then(|| self.latest_check_record(mem, &entity.id.0, kind))
457 .flatten();
458 let Some(record) = newest else {
459 entries.push(DueEntry {
460 mem: mem.to_string(),
461 third_party,
462 id: entity.id.to_string(),
463 title: entity.title.clone(),
464 date: today_iso.clone(),
465 status,
466 lead,
467 overdue: false,
468 days_until: 0,
469 due_now: Some((kind.clone(), standing.label().to_string())),
470 });
471 continue;
472 };
473 (record.act_time() / 86_400) as i64
474 } else {
475 let Some(field) = &due.date_field else {
476 continue;
477 };
478 let date = match entity.metadata.get(field) {
479 Some(MetadataValue::String(s)) => s.clone(),
480 _ => continue,
481 };
482 let base_part = date.get(..10).unwrap_or(&date).to_string();
486 let Some((by, bm, bd)) = parse_ymd(&base_part) else {
487 continue;
488 };
489 days_from_civil(by, bm, bd)
490 };
491 let due_days = base_days + due.offset_days as i64;
493 let (dy, dm, dd) = civil_from_days(due_days);
494 let date_part = format!("{dy:04}-{dm:02}-{dd:02}");
495 if date_part.as_str() > end.as_str() {
496 continue;
497 }
498 let days_until = due_days - today_days;
499 entries.push(DueEntry {
500 mem: mem.to_string(),
501 third_party,
502 id: entity.id.to_string(),
503 title: entity.title.clone(),
504 date: date_part.clone(),
505 status,
506 lead,
507 overdue: date_part.as_str() < today_iso.as_str(),
508 days_until,
509 due_now: None,
510 });
511 }
512 }
513
514 entries.sort_by(|a, b| {
517 b.overdue
518 .cmp(&a.overdue)
519 .then_with(|| b.due_now.is_some().cmp(&a.due_now.is_some()))
520 .then_with(|| a.date.cmp(&b.date))
521 .then_with(|| a.id.cmp(&b.id))
522 });
523 declaring_mems.sort();
524 declaring_mems.dedup();
525 Ok((today_iso, end, declaring_mems, entries))
526 }
527}
528
529fn render_due_entries(
530 today_iso: &str,
531 end: &str,
532 window: &DueWindow,
533 declaring_mems: &[String],
534 entries: &[DueEntry],
535) -> String {
536 {
537 let window_label = match window {
538 DueWindow::Days(n) => format!("{n}d"),
539 DueWindow::Months(n) => format!("{n}m"),
540 DueWindow::Years(n) => format!("{n}y"),
541 };
542 let mut out = String::new();
543 out.push_str(&format!(
544 "# Due brief — {today_iso}, window {window_label} (through {end})\n\n"
545 ));
546 if declaring_mems.is_empty() {
547 out.push_str(
548 "No mounted mem's schema declares a due axis (`due:` on a type). \
549 Nothing to render.\n",
550 );
551 return out;
552 }
553 out.push_str(&format!("Mems: {}\n\n", declaring_mems.join(", ")));
554 if entries.is_empty() {
555 out.push_str("Nothing open is due in this window.\n");
556 return out;
557 }
558 let overdue_count = entries.iter().filter(|e| e.overdue).count();
559 let due_now_count = entries.iter().filter(|e| e.due_now.is_some()).count();
560 out.push_str(&format!(
561 "{} entr{} ({} overdue{})\n\n",
562 entries.len(),
563 if entries.len() == 1 { "y" } else { "ies" },
564 overdue_count,
565 if due_now_count > 0 {
566 format!(", {due_now_count} due now")
567 } else {
568 String::new()
569 }
570 ));
571 for e in entries {
572 let origin = if e.third_party { " [third-party]" } else { "" };
573 if let Some((kind, standing)) = &e.due_now {
574 out.push_str(&format!(
575 "- `{}` — {} — **due now**: no confirming `{kind}` check ({standing}) \
576 (status: {}, mem: {}{})\n",
577 e.id, e.title, e.status, e.mem, origin
578 ));
579 } else {
580 let marker = if e.overdue {
581 format!(" **OVERDUE** ({} days past)", -e.days_until)
582 } else {
583 format!(" (in {} days)", e.days_until)
584 };
585 out.push_str(&format!(
586 "- `{}` — {} — **{}**{} (status: {}, mem: {}{})\n",
587 e.id, e.title, e.date, marker, e.status, e.mem, origin
588 ));
589 }
590 if let Some((key, body)) = &e.lead {
591 if e.third_party {
592 out.push_str(&format!(" - {key} (third-party, quoted):\n"));
595 for line in body.lines() {
596 out.push_str(&format!(" > {line}\n"));
597 }
598 } else {
599 out.push_str(&format!(" - {key}:\n"));
600 for line in body.lines() {
601 out.push_str(&format!(" {line}\n"));
602 }
603 }
604 }
605 }
606 out
607 }
608}
609
610#[cfg(test)]
611mod tests {
612 use super::*;
613 use std::path::Path;
614 use tempfile::TempDir;
615
616 use crate::backend::MemBackend;
617 use crate::storage::FilesystemBackend;
618 use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
619
620 fn frist_schema_dir(root: &Path) {
621 let d = root.join("schemas").join("frist-schema");
622 std::fs::create_dir_all(d.join("types")).unwrap();
623 std::fs::write(
624 d.join("schema.yaml"),
625 "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",
626 )
627 .unwrap();
628 std::fs::write(
629 d.join("types").join("obligation.yaml"),
630 "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",
631 )
632 .unwrap();
633 std::fs::write(
634 d.join("types").join("note.yaml"),
635 "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",
636 )
637 .unwrap();
638 }
639
640 fn obligation_md(title: &str, date: &str, status: &str, vorlauf: Option<&str>) -> String {
641 let lead = vorlauf
642 .map(|v| format!("\n## Vorlauf\n\n{v}\n"))
643 .unwrap_or_default();
644 format!(
645 "---\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}"
646 )
647 }
648
649 fn mount_with(mem: &str, path: std::path::PathBuf, capability: MountCapability) -> Mount {
650 Mount {
651 mem: mem.to_string(),
652 schema: Some("frist@0.1.0".parse().unwrap()),
653 storage: MountStorage::Folder { path },
654 capability,
655 lifecycle: MountLifecycle::Eager,
656 cross_linkable: true,
657 migration_target: None,
658 }
659 }
660
661 #[test]
666 fn due_brief_membership_order_and_labels() {
667 let tmp = TempDir::new().unwrap();
668 frist_schema_dir(tmp.path());
669 let own = tmp.path().join("own");
670 let foreign = tmp.path().join("foreign");
671 std::fs::create_dir_all(own.join(".memstead")).unwrap();
672 std::fs::create_dir_all(foreign.join(".memstead")).unwrap();
673 for dir in [&own, &foreign] {
676 std::fs::write(
677 dir.join(".memstead/config.json"),
678 "{\n \"version\": \"1.0.0\",\n \"description\": \"due fixture\",\n \"schema\": \"frist@0.1.0\"\n}",
679 )
680 .unwrap();
681 }
682 std::fs::write(
683 own.join("wartung.md"),
684 obligation_md(
685 "Wartung",
686 "2026-09-01",
687 "offen",
688 Some("Handwerker beauftragen"),
689 ),
690 )
691 .unwrap();
692 std::fs::write(
693 own.join("frist-alt.md"),
694 obligation_md("Frist Alt", "2026-07-01", "in_arbeit", None),
695 )
696 .unwrap();
697 std::fs::write(
698 own.join("weit-weg.md"),
699 obligation_md("Weit Weg", "2027-06-01", "offen", None),
700 )
701 .unwrap();
702 std::fs::write(
703 own.join("erledigt.md"),
704 obligation_md("Erledigt", "2026-08-20", "erledigt", None),
705 )
706 .unwrap();
707 std::fs::write(
708 own.join("plain-note.md"),
709 "---\ntype: note\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\n---\n# Plain Note\n\n## Body\n\nB.\n",
710 )
711 .unwrap();
712 std::fs::write(
714 own.join("b-gleich.md"),
715 obligation_md("B Gleich", "2026-09-10", "offen", None),
716 )
717 .unwrap();
718 std::fs::write(
719 own.join("a-gleich.md"),
720 obligation_md("A Gleich", "2026-09-10", "offen", None),
721 )
722 .unwrap();
723 std::fs::write(
725 foreign.join("fremd-frist.md"),
726 obligation_md(
727 "Fremd Frist",
728 "2026-06-15",
729 "offen",
730 Some("Nur zur Kenntnis"),
731 ),
732 )
733 .unwrap();
734
735 let own_writer = FilesystemBackend::new(own.clone());
736 let foreign_writer = FilesystemBackend::new(foreign.clone());
737 let engine = Engine::from_mounts_with_schemas_dir(
738 vec![
739 (
740 mount_with("own", own, MountCapability::Write),
741 Box::new(own_writer) as Box<dyn MemBackend>,
742 ),
743 (
744 mount_with("foreign", foreign, MountCapability::ReadOnly),
745 Box::new(foreign_writer) as Box<dyn MemBackend>,
746 ),
747 ],
748 Some(&tmp.path().join("schemas")),
749 )
750 .unwrap();
751
752 let brief = engine
753 .render_due_brief("2026-08-10", &DueWindow::Days(90), None)
754 .unwrap();
755
756 for present in [
759 "own--wartung",
760 "own--frist-alt",
761 "foreign--fremd-frist",
762 "own--a-gleich",
763 "own--b-gleich",
764 ] {
765 assert!(brief.contains(present), "{present} missing:\n{brief}");
766 }
767 for absent in ["weit-weg", "erledigt", "plain-note"] {
768 assert!(!brief.contains(absent), "{absent} leaked:\n{brief}");
769 }
770
771 let pos = |needle: &str| brief.find(needle).unwrap();
774 assert!(
775 pos("foreign--fremd-frist") < pos("own--frist-alt"),
776 "{brief}"
777 );
778 assert!(pos("own--frist-alt") < pos("own--wartung"), "{brief}");
779 assert!(pos("own--wartung") < pos("own--a-gleich"), "{brief}");
780 assert!(pos("own--a-gleich") < pos("own--b-gleich"), "{brief}");
781
782 assert!(brief.contains("**2026-07-01** **OVERDUE**"), "{brief}");
784 assert!(brief.contains("Handwerker beauftragen"), "{brief}");
785 assert!(brief.contains("status: offen"), "{brief}");
786
787 assert!(brief.contains("[third-party]"), "{brief}");
789 assert!(brief.contains("vorlauf (third-party, quoted):"), "{brief}");
790 assert!(brief.contains("> Nur zur Kenntnis"), "{brief}");
791 assert!(brief.contains(" Handwerker beauftragen"), "{brief}");
793
794 let again = engine
796 .render_due_brief("2026-08-10", &DueWindow::Days(90), None)
797 .unwrap();
798 assert_eq!(brief, again);
799
800 let own_only = engine
802 .render_due_brief("2026-08-10", &DueWindow::Days(90), Some("own"))
803 .unwrap();
804 assert!(!own_only.contains("foreign--fremd-frist"), "{own_only}");
805 assert!(own_only.contains("own--wartung"), "{own_only}");
806 }
807
808 #[test]
812 fn iso_utc_seconds_parse_exactly_the_two_shapes() {
813 assert_eq!(parse_iso_utc_seconds("2026-10-20"), Some(1_792_454_400));
814 assert_eq!(
815 parse_iso_utc_seconds("2026-10-20T13:45:30Z"),
816 Some(1_792_503_930)
817 );
818 assert_eq!(parse_iso_utc_seconds("2024-02-29"), Some(1_709_164_800));
819 assert_eq!(parse_iso_utc_seconds("1970-01-01T00:00:00Z"), Some(0));
820 for bad in [
821 "",
822 "2026-10-20T13:45:30",
823 "2026-10-20 13:45:30Z",
824 "2026-10-20T13:45:30.000Z",
825 "2026-13-01",
826 "2026-02-30",
827 "2023-02-29",
828 "2026-10-20T24:00:00Z",
829 "1792454400",
830 "yesterday",
831 ] {
832 assert_eq!(parse_iso_utc_seconds(bad), None, "{bad:?} must not parse");
833 }
834 }
835
836 #[test]
838 fn window_parse_and_calendar_math() {
839 assert_eq!(parse_due_window("90d").unwrap(), DueWindow::Days(90));
840 assert_eq!(parse_due_window("6m").unwrap(), DueWindow::Months(6));
841 assert_eq!(parse_due_window("2y").unwrap(), DueWindow::Years(2));
842 for bad in ["", "d", "90", "90w", "-1d", "1.5m"] {
843 let err = parse_due_window(bad).unwrap_err();
844 assert!(err.contains("<N>d"), "error names accepted forms: {err}");
845 }
846 assert_eq!(
848 window_end((2026, 1, 31), &DueWindow::Months(1)),
849 "2026-02-28"
850 );
851 assert_eq!(
852 window_end((2024, 1, 31), &DueWindow::Months(1)),
853 "2024-02-29"
854 );
855 assert_eq!(
856 window_end((2026, 8, 10), &DueWindow::Days(90)),
857 "2026-11-08"
858 );
859 assert_eq!(
860 window_end((2026, 11, 15), &DueWindow::Months(2)),
861 "2027-01-15"
862 );
863 assert_eq!(
864 window_end((2024, 2, 29), &DueWindow::Years(1)),
865 "2025-02-28"
866 );
867 }
868
869 #[test]
872 fn no_declaring_schema_renders_honest_empty_brief() {
873 let tmp = TempDir::new().unwrap();
874 let mem_dir = tmp.path().to_path_buf();
875 let writer = FilesystemBackend::new(mem_dir.clone());
876 let engine = Engine::from_mounts(vec![(
877 crate::engine::test_helpers::folder_mount("specs", mem_dir),
878 Box::new(writer) as Box<dyn MemBackend>,
879 )])
880 .unwrap();
881 let brief = engine
882 .render_due_brief("2026-08-10", &DueWindow::Days(90), None)
883 .unwrap();
884 assert!(
885 brief.contains("No mounted mem's schema declares a due axis"),
886 "{brief}"
887 );
888 }
889}
890
891#[cfg(test)]
892mod obligation_builtin_tests {
893 use super::*;
894 use tempfile::TempDir;
895
896 use crate::backend::MemBackend;
897 use crate::engine::test_helpers::{cli_actor, empty_create_args};
898 use crate::storage::FilesystemBackend;
899 use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
900
901 fn obligation_mount(mem: &str, path: std::path::PathBuf) -> Mount {
902 Mount {
903 mem: mem.to_string(),
904 schema: Some("obligation@0.1.0".parse().unwrap()),
905 storage: MountStorage::Folder { path },
906 capability: MountCapability::Write,
907 lifecycle: MountLifecycle::Eager,
908 cross_linkable: true,
909 migration_target: None,
910 }
911 }
912
913 fn obligation_engine(tmp: &TempDir) -> Engine {
914 let mem_dir = tmp.path().join("duties");
915 std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
916 std::fs::write(
917 mem_dir.join(".memstead/config.json"),
918 "{\n \"version\": \"1.0.0\",\n \"description\": \"obligation fixture\",\n \"schema\": \"obligation@0.1.0\"\n}",
919 )
920 .unwrap();
921 let writer = FilesystemBackend::new(mem_dir.clone());
922 Engine::from_mounts(vec![(
923 obligation_mount("duties", mem_dir),
924 Box::new(writer) as Box<dyn MemBackend>,
925 )])
926 .unwrap()
927 }
928
929 fn obligation_args(
930 mem: &str,
931 title: &str,
932 due_date: &str,
933 status: &str,
934 ) -> crate::engine::CreateEntityArgs {
935 let mut args = empty_create_args(mem, title);
936 args.entity_type = "obligation".to_string();
937 args.sections = indexmap::IndexMap::from_iter([
938 ("duty".to_string(), "Who owes what.".to_string()),
939 ("consequence".to_string(), "What forfeits.".to_string()),
940 ]);
941 args.metadata = indexmap::IndexMap::from_iter([
942 ("due_date".to_string(), due_date.to_string()),
943 ("status".to_string(), status.to_string()),
944 ]);
945 args.relations = vec![crate::ops::RelateArg {
946 target: crate::entity::EntityId::new(mem, "some-subject"),
947 rel_type: "CONCERNS".to_string(),
948 description: None,
949 }];
950 args
951 }
952
953 #[test]
958 fn shipped_obligation_schema_accepts_refuses_and_renders_due() {
959 let tmp = TempDir::new().unwrap();
960 let mut engine = obligation_engine(&tmp);
961 let (actor, client) = cli_actor();
962
963 engine
965 .create_entity(
966 obligation_args(
967 "duties",
968 "Renew Registration No. 4711 & File Proof",
969 "2026-09-01",
970 "open",
971 ),
972 actor,
973 Some(&client),
974 None,
975 )
976 .expect("conformant obligation lands");
977 engine
978 .create_entity(
979 obligation_args("duties", "Overdue Filing", "2026-07-01", "in_progress"),
980 actor,
981 Some(&client),
982 None,
983 )
984 .expect("second obligation lands");
985 engine
986 .create_entity(
987 obligation_args("duties", "Done Duty", "2026-08-01", "done"),
988 actor,
989 Some(&client),
990 None,
991 )
992 .map(|_| ())
993 .unwrap_err(); let err = engine
998 .create_entity(
999 obligation_args("duties", "Bad Status", "2026-09-01", "unknown"),
1000 actor,
1001 Some(&client),
1002 None,
1003 )
1004 .unwrap_err();
1005 assert_eq!(err.code(), "INVALID_ENUM_VALUE", "{err}");
1006
1007 let brief = engine
1009 .render_due_brief("2026-08-10", &DueWindow::Days(90), None)
1010 .unwrap();
1011 let pos = |n: &str| brief.find(n).unwrap_or(usize::MAX);
1012 assert!(brief.contains("duties--overdue-filing"), "{brief}");
1013 assert!(
1014 brief.contains("duties--renew-registration-no-4711-file-proof"),
1015 "{brief}"
1016 );
1017 assert!(pos("duties--overdue-filing") < pos("duties--renew-registration-no-4711"));
1018 assert!(brief.contains("**OVERDUE**"), "{brief}");
1019 }
1020
1021 #[test]
1025 fn shipped_constraints_refuse_like_the_field_schema() {
1026 let tmp = TempDir::new().unwrap();
1027 let mut engine = obligation_engine(&tmp);
1028 let (actor, client) = cli_actor();
1029
1030 let err = engine
1032 .create_entity(
1033 obligation_args("duties", "Done Without Date", "2026-08-01", "done"),
1034 actor,
1035 Some(&client),
1036 None,
1037 )
1038 .unwrap_err();
1039 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED", "{err}");
1040 assert!(err.to_string().contains("completed_on"), "{err}");
1041
1042 let mut args = obligation_args("duties", "Critical Unowned", "2026-09-01", "open");
1044 args.metadata
1045 .insert("criticality".to_string(), "high".to_string());
1046 let err = engine
1047 .create_entity(args, actor, Some(&client), None)
1048 .unwrap_err();
1049 assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED", "{err}");
1050 assert!(err.to_string().contains("responsible"), "{err}");
1051
1052 let mut args = obligation_args("duties", "About Nothing", "2026-09-01", "open");
1054 args.relations.clear();
1055 let err = engine
1056 .create_entity(args, actor, Some(&client), None)
1057 .unwrap_err();
1058 assert!(
1059 err.to_string().contains("CONCERNS") || err.code().contains("REQUIRED_OUTGOING"),
1060 "required_outgoing must refuse: {err} ({})",
1061 err.code()
1062 );
1063
1064 let mut args = obligation_args("duties", "Done Properly", "2026-08-01", "done");
1067 args.metadata
1068 .insert("completed_on".to_string(), "2026-08-01".to_string());
1069 engine
1070 .create_entity(args, actor, Some(&client), None)
1071 .expect("done with completed_on lands");
1072 let mut args = obligation_args("duties", "Critical Owned", "2026-09-01", "open");
1073 args.metadata
1074 .insert("criticality".to_string(), "high".to_string());
1075 args.metadata
1076 .insert("responsible".to_string(), "Operations".to_string());
1077 engine
1078 .create_entity(args, actor, Some(&client), None)
1079 .expect("high with responsible lands");
1080 }
1081}